def configureArduinoUart(self): ckboxtree = CheckboxTree(height=2, scroll=0) ckboxtree.append(text='RX & TX', item=1, selected=self.checkPinmuxConfig('UART_RX')) ckboxtree.append(text='CTS & RTS', item=2, selected=self.checkPinmuxConfig('UART_CTS')) buttonbar = ButtonBar(screen=self.topmenu.gscreen, buttonlist=[('Ok', 'ok'), ('Cancel', 'cancel', 'ESC')]) g = GridForm(self.topmenu.gscreen, # screen 'Enable UART on IO0-IO3', # title 1, 2) # 2x1 grid g.add(ckboxtree, 0, 0) g.add(buttonbar, 0, 1) result = g.runOnce() if buttonbar.buttonPressed(result) == 'cancel': return selected = ckboxtree.getSelection() if 1 in selected: uart = mraa.Uart(0) uart.setFlowcontrol(False, True if 2 in selected else False) self.setPinmuxOfUserConfig('UART_RX') self.setPinmuxOfUserConfig('UART_TX') if 2 in selected: self.setPinmuxOfUserConfig('UART_CTS') self.setPinmuxOfUserConfig('UART_RTS') else: self.resetPinmuxOfUserConfig('UART_CTS') self.resetPinmuxOfUserConfig('UART_RTS') else: self.resetPinmuxOfUserConfig('UART') self.saveConfig(self.config)
def __init__(self, device_address, uart_port): self.address = device_address #Configure uart port. self.uart = mraa.Uart(uart_port) self.uart.setBaudRate(DEFAULT_BAUDRATE) self.uart.setMode(8, mraa.UART_PARITY_NONE, 1) self.uart.setFlowcontrol(False, False)
def __init__(self, speedCalculatorInstance): #Set the publishing rate of the airmar to 2Hz for now self.pubInterval = 0.1 # Seconds between publishes self.heading = 0 self.amrRoll = 0 self.truWndDir = 0 self.truWndSpd = 0 self.cog = 0 self.lat = 0 self.long = 0 self.sog = 0 self.wndUnits = "K" self.apWndDir = 0 self.apWndSpd = 0 #Store the speed calculator self.spd = speedCalculatorInstance #Initialize a publisher self.pub = rospy.Publisher('/airmar_data', AirmarData, queue_size = 10) # Debugging, turns airmar into steering wheel # self.servoPub = rospy.Publisher('/servo_pos', ServoPos, queue_size = 10) #Use mraa to initialize edison pins 0 and 1 to serial mraa.Uart(0) #...but, after initialized, let's use the pyserial library self.ser = serial.Serial('/dev/ttyMFD1', 4800, timeout=1) self.ser.readline()
def sendData(data, interface=1): """Send data through selected interface. Interface is selected according to the chart below Interfaces: Serial -- 0 Bluetooth -- 1 :param data: Data to send of type list :param interface: integer denoting interface to select :return: """ print "My length is:" print len(data) #Serial if interface is 0: uart = mraa.Uart(0) # Enable UART for serial port usage ser = serial.Serial( port='/dev/ttyMFD2', # Port dependant on hardware block baudrate=115200, parity=serial.PARITY_EVEN) # Send each number in the list for number in data: #print "Sending:", number bytesSent = ser.write(str(number) + '\n') #print "Bytes Sent:", bytesSent ser.write('\n') # Send EOF Character print "Transmission successful" else: #socket.setdefaulttimeout(10) s.sendall(data) print "Transmission Successful"
def getWeight(): ret = "" x = mraa.Uart(0) try: ser = serial.Serial('/dev/ttyACM0', 115200) ser.bytesize = serial.EIGHTBITS ser.parity = serial.PARITY_NONE ser.stopbits = serial.STOPBITS_ONE ser.timeout = 1 ser.flush() ser.write("LOGIN=0047\r\n") counter = "READ\r\n" ser.write(counter) sleep(1) r = ser.readlines() #print(r) if (len(r) > 0): ret = r[3] ret = ret.replace('kg', '') ret = ret.replace(',', '.') print ret else: ret = "-1" except: ret = "-1" #ser.close() return ret
def sendsigfox(data): print('Sending SigFox Message...') uart = mraa.Uart(0) # define sigfox and implicitely makes a sigfox.open() sigfox = serial.Serial(uart.getDevicePath(), baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) sigfox.write('AT\r') if (WaitFor(sigfox, 'OK', 3)): print('SigFox Modem OK') else: print('SigFox Modem Error') sigfox.close() return False print("sending data " + data + " to SigFox network:") print("Sigfox: AT$SF=" + data + "\r") sigfox.write("AT$SF=") sigfox.write(data) sigfox.write("\r") if (WaitFor(sigfox, 'OK', 15)): print('Message sent OK') else: print('Error Sending message') sigfox.close() return False sigfox.close() return True
def getGPS(): u = mraa.Uart(0) u.setBaudRate(9600) #print u.getDevicePath() status = "V" while (status != "A"): if (u.dataAvailable()): buff = u.readStr(256) if (buff.find("GPRMC") != -1): #print buff trimbuff = buff[buff.find("GPRMC"):-1] splitbuff = trimbuff.strip().split(',') #print trimbuff #print splitbuff if (len(splitbuff) < 8): continue status = splitbuff[2] latnmea = splitbuff[3] latdir = splitbuff[4] lonnmea = splitbuff[5] londir = splitbuff[6] speed = splitbuff[7] lat = float(latnmea[0:2]) + float(latnmea[2:]) / 60 lon = float(lonnmea[0:3]) + float(lonnmea[3:]) / 60 spd = float(speed) * 1.852 if (latdir == "S"): lat *= -1 if (londir == "W"): lon *= -1 return [lat, lon, spd]
def meteoroData(): failed = 0 try: x = mraa.Uart(0) #------- Opening port and sending command------ ser = serial.Serial('/dev/ttyACM0', 115200) ser.bytesize = serial.EIGHTBITS ser.parity = serial.PARITY_NONE ser.stopbits = serial.STOPBITS_ONE ser.timeout = 2 ser.write("LOGIN=0047\r\n") counter = "READ\r\n" ser.write(counter) print("Sent: " + str(counter)) #-------Lecturas---------- r = ser.readlines() temp = r[4].replace("\xb0C\r\n", "").replace(",", ".") hum = r[5].replace("%\r\n", "").replace(",", ".") brood = r[6].replace("\xb0C B\r\n", "").replace(",", ".") lit = r[7].replace("l/h\r\n", "").replace(",", ".") km = r[8].replace("km/h\r\n", "").replace(",", ".") print("Weight: " + r[3].replace("kg\r\n", "")) print("Temperature: " + temp) print("Humidity: " + hum) print("Brood: " + brood) print("Liters per hour: " + lit) print("Kilometers per hour: " + km) print("Failed: " + str(failed)) ser.close() #------Comprobacion------ float(temp) float(hum) float(brood) float(lit) float(km) #-----Insercion--------- pubTempI = insert_observation.insert(temp, "Temperature Int") pubHum = insert_observation.insert(hum, "Humidity") pubBrood = insert_observation.insert(brood, "Brood") pubPluvi = insert_observation.insert(lit, "Pluviometer") pubAnemo = insert_observation.insert(km, "Anemometer") #--------Publicacion a horas--------- if (tRet.isTimeToSend()): mosquitto_publisher.publisher("TemperatureI", pubTempI) mosquitto_publisher.publisher("Humidity", pubHum) mosquitto_publisher.publisher("Brood", pubBrood) mosquitto_publisher.publisher("Pluviometer", pubPluvi) mosquitto_publisher.publisher("Anemometer", pubAnemo) except: print("Something went wrong, comunication or data, nothing done.") failed = failed + 1
def __init__ (self, port, baud): self.baud = baud self.port = port self.Serial = mraa.Uart(port) self.Serial.setBaudRate(baud) self.Serial.setFlowcontrol(False, False) self.triggerPin = mraa.Gpio(self.triggerPinNum) self.triggerPin.dir(mraa.DIR_OUT)
def UART_init(): global u_port try: u_port = m.Uart(u_p) print("Initializing pin " + str(u_p) + " as UART") return 0 except ValueError: print(sys.exc_info()[1][0]) return 1
def __init__(self, q): Process.__init__(self) self.q = q self.u = mraa.Uart(1) self.u.setBaudRate(9600) self.u.setMode(8, mraa.UART_PARITY_NONE, 1) self.u.setFlowcontrol(False, False) self.co2_avg = move_avge.move_avg(1)
def setupSerial(self): ''' Setsum the Serial device :return: serial object ''' self.uart = mraa.Uart(0) #self.uart.setBaudRate(9600) #self.uart.setMode(8, mraa.UART_PARITY_NONE, 1) #self.uart.setFlowcontrol(False, False) #self.ser = serial.Serial(self.uart.getDevicePath(), 9600) self.ser = serial.Serial("/dev/ttyMFD1", 9600) self.sio = io.TextIOWrapper(io.BufferedRWPair(self.ser, self.ser))
def __init__(self, q): Process.__init__(self) self.q = q self.u = mraa.Uart(1) self.u.setBaudRate(9600) self.u.setMode(8, mraa.UART_PARITY_NONE, 1) self.u.setFlowcontrol(False, False) self.gpstime = 0 self.sat_num = 0 self.lat = 0 self.lon = 0 self.gps_stat = 0 self.alt = 0
def __init__(self, q): Process.__init__(self) self.q = q self.u=mraa.Uart(0) self.u.setBaudRate(9600) self.u.setMode(8, mraa.UART_PARITY_NONE, 1) self.u.setFlowcontrol(False, False) self.cfpm1_0_avg = move_avge.avge(60) self.cfpm2_5_avg = move_avge.avge(60) self.cfpm10_avg = move_avge.avge(60) self.pm1_0_avg = move_avge.avge(10) self.pm2_5_avg = move_avge.avge(10) self.pm10_avg = move_avge.avge(10)
def init(): mraa.Uart(0) # Use mraa to initialize the serial port, then use default pyserial library # Open serial communication on pin 0(RX) and 1(TX) s.baudrate = 115200 s.port = "/dev/ttyS0" s.timeout = 0 s.open() # print s signal.signal(signal.SIGINT, signal_handler) print "Press Ctrl+C to stop the motors and the program" # Sets digital pin2(=Direction) to output pin2.dir(mraa.DIR_OUT) setAllResolution(aPins, RESOLUTION) setMode(TX_MODE) # IMPORTANT, OTHERWISE NOTHING WILL WORK
def __init__(self, q): Process.__init__(self) self.q = q self.u = mraa.Uart(0) self.u.setBaudRate(9600) self.u.setMode(8, mraa.UART_PARITY_NONE, 1) self.u.setFlowcontrol(False, False) self.u.flush() cmd = bytearray([0x68, 0x01, 0x02, 0x95]) #cmd = bytearray([0x68,0x01,0x04,0x96]) self.u.write(cmd) self.u.flush() time.sleep(0.1) if self.u.dataAvailable(): ready = False while ready is False: getstr = self.u.readStr(2) bytedata = bytearray(getstr) if bytedata[0] == 165 and bytedata[1] == 165: ready = True else: time.sleep(0.1) self.u.flush() cmd = bytearray([0x68, 0x01, 0x01, 0x96]) self.u.write(cmd) self.u.flush() time.sleep(0.1) if self.u.dataAvailable(): ready = False while ready is False: getstr = self.u.readStr(2) bytedata = bytearray(getstr) for i in range(0, 2, 1): print(int)(bytedata[i]) if bytedata[0] == 165 and bytedata[1] == 165: ready = True else: time.sleep(0.1) self.u.flush() self.pm1_0_avg = move_avge.move_avg(1) self.pm2_5_avg = move_avge.move_avg(1) self.pm10_avg = move_avge.move_avg(1)
def meteoroData(): failed = 0 try: x = mraa.Uart(0) #------- Opening port and sending command------ ser = serial.Serial('/dev/ttyACM0', 115200) ser.bytesize = serial.EIGHTBITS ser.parity = serial.PARITY_NONE ser.stopbits = serial.STOPBITS_ONE ser.timeout = 1 ser.write("LOGIN=0047\r\n") counter = "READ\r\n" ser.write(counter) #print("Sent: "+str(counter)) #-------Lecturas---------- r = ser.readlines() temp = r[4].replace("\xb0C\r\n", "").replace(",", ".") hum = r[5].replace("%\r\n", "").replace(",", ".") brood = r[6].replace("\xb0C B\r\n", "").replace(",", ".") lit = r[7].replace("l/h\r\n", "").replace(",", ".") km = r[8].replace("km/h\r\n", "").replace(",", ".") #print("Weight: "+r[3].replace("kg\r\n","")) #------Comprobacion------ float(temp) float(hum) float(brood) float(lit) float(km) print("Temperature Int: " + temp + "°C") print("Humidity: " + hum + "%") print("Brood: " + brood + "°C") print("Pluviometer: " + lit + "lt/hr") print("Anemometer: " + km + "km/hr") #print("Failed: "+str(failed)) ser.close() except: print("Something went wrong, comunication or data, nothing done.") failed = failed + 1
def sendData(data, interface=1): """Send data through selected interface. Interface is selected according to the chart below Interfaces: Serial -- 0 Bluetooth -- 1 :param data: Data to send of type list :param interface: integer denoting interface to select :return: """ #Serial if interface is 0: uart = mraa.Uart(0) # Enable UART for serial port usage ser = serial.Serial( port='/dev/ttyMFD2', # Port dependant on hardware block baudrate=115200, parity=serial.PARITY_EVEN) # Send each number in the list for number in data: #print "Sending:", number bytesSent = ser.write(str(number) + '\n') #print "Bytes Sent:", bytesSent ser.write('\n') # Send EOF Character print "Transmission successful" else: for number in data: s = socket.socket() # Create a socket object port = 80 # Reserve a port for your service. s.connect(('192.168.0.11', port)) s.send(str(float(number)) + '\n') s.close() s = socket.socket() # Create a socket object port = 80 # Reserve a port for your service. s.connect(('192.168.0.11', port)) s.send('\n') print "Transmission Successful"
def do_POST(self): print "POST request: " + self.path form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-type'], }) self.send_response(200) self.end_headers() if 'usermsg' in form: u = mraa.Uart(0) u.setBaudRate(9600) u.setMode(8, mraa.UART_PARITY_NONE, 1) u.setFlowcontrol(False, False) u.writeStr(form['usermsg'].value + "\n") u.flush()
def getWeight(): x = mraa.Uart(0) ser = serial.Serial('/dev/ttyMFD1', 9600) ser.bytesize = serial.EIGHTBITS ser.parity = serial.PARITY_NONE ser.timeout = 2 counter = 66 ser.write(chr(counter)) #print("Sent: "+str(chr(counter))) res = ser.readline() print(res + "nnnn") try: res = float(res) / 1000 except: res = -1 ser.close() if res == -1: correctWeight() return res
def __init__(self): self.heading = 0 self.amrRoll = 0 self.truWndDir = 0 self.truWndSpd = 0 self.cog = 0 self.lat = 0 self.long = 0 self.sog = 0 self.wndUnits = "K" self.apWndDir = 0 self.apWndSpd = 0 # we need to change this port to whatever it's going to be for the # actual machine we run ROS on #Turn pins 0 and 1 on to uart so we can actually use them mraa.Uart(0) #...but, mraa is a bitch, after they're turned on let's just use pyserial library instead ;) self.ser = serial.Serial('/dev/ttyMFD1', 4800, timeout=1) self.ser.readline()
import mraa import time import codecs u = mraa.Uart(1) u.setBaudRate(115200) u.setMode(8, mraa.UART_PARITY_NONE, 1) u.setFlowcontrol(False, False) alarm = mraa.Gpio(1) alarm.dir(mraa.DIR_OUT) wake_up = bytearray( b'x55\x55\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\x03\xfd\xd4\x14\x01\x17\x00' ) inlistpassive_target = bytearray( b'x00\x00\xff\x04\xfc\xd4\x4a\x01\x00\xe1\x00') indataexchange = bytearray( b'x00\x00\xff\x0d\xf3\xd4\x40\x01\x00\xa4\x04\x00\x05\xf2\xff\xff\xff\xff\x50\x00' ) card_uid = bytearray(4) mac = bytearray(12) while 1: u.write(wake_up) u.flush() if u.dataAvailable(3000): data_wakeup = u.read(15) hex_data_wakeup = codecs.getencoder('hex')(data_wakeup) str_data_wakeup = str(hex_data_wakeup) print(str_data_wakeup)
#coding: utf-8 import mraa from threading import Thread from socket import * from numpy import fft, ifft import struct #bytes import numpy as np # Inicializa a comunicação USART usart = mraa.Uart(0) # Informa que a taxa de transmissão será de 115.2 kb/s usart.setBaudRate(115200) # Informa que o tamanho das palavras recebidas terão 8 bits, que serão recebidas juntamente com um # bit de paridade par para conferir a integridade dos dados recebidos e que haverá um bit indicando o fim do frame transmitido usart.setMode(8, mraa.UART_PARITY_EVEN, 1) # Desativa controles de fluxo usart.setFlowcontrol(False, False) sound_fft = [] fft_filtrada = [] sound_ifft = [] # Thread responsável pela comunicação entre o cliente (PC) e a Galileo class Comunicacao(Thread): def __init__(self, fila_envio): Thread.__init__(self) self.serverName = '' # ip do servidor (em branco) self.serverPort = 12000 # porta a se conectar self.serverSocket = socket(AF_INET,
# The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE import mraa import sys sys.stdout.write("Initializing UART...") u=mraa.Uart(3) print("...done") print("Setting UART parameters: baudrate 115200, 8N1, no flow control") u.setBaudRate(115200) u.setMode(8, mraa.UART_PARITY_NONE, 1) u.setFlowcontrol(False, False) msg_b = bytearray("Hello, mraa byte array!", "ascii") print("Sending message as a byte array: '{0}'".format(msg_b)) u.write(msg_b) # Make sure the message gets out to the line. # It's generally unnecessary (and performance-degrading) to do this explicitly, # UART driver normally takes care of that, but it may be useful with specific # half-duplex endpoints, like Dynamixel servos. u.flush()
def enableUart0(self): u = mraa.Uart(0) self.showIoConfiguration()
import socket import fcntl import struct import json from ubidots import ApiClient import time import pyupm_i2clcd as lcd import math HOST = '' # Symbolic name meaning all available interfaces PORT = 2211 # Arbitrary non-privileged port CLIENT_PORT = 4000 CLIENT_IP = "192.168.96.151" sensor_values = {} B = 3975 sys.stdout.write("Initializing UART...") u = mraa.Uart(0) u.setBaudRate(9600) u.setMode(8, mraa.UART_PARITY_NONE, 1) u.setFlowcontrol(False, False) print("setting UART done") # Initialize Jhd1313m1 at 0x3E (LCD_ADDRESS) and 0x62 (RGB_ADDRESS) myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62) suffix = ':' grocery_list = [] data_file = open("sensor_data.txt", "rw+") car_parked = False temperature = "0" homeLocked = False data_has_arrived = False x = mraa.I2c(0) x.address(0x77)
def setUp(self): self.uart = m.Uart(MRAA_UART_DEV_NUM)
#!/usr/bin/env python # uart example in python using mraa # # Author: Manivannan Sadhasivam <*****@*****.**> # # Usage: sends "Hello Mraa" string through tty96B0 uart port # # Execution: sudo python mraa_uart.py import mraa import time import sys # serial port port = "/dev/tty96B0" data = 'Hello Mraa!' # initialize uart tty96B0 uart = mraa.Uart(port) # send data through uart uart.write(bytearray(data, 'utf-8'))
import mraa #Importando os modulos import time u = mraa.Uart(0) #Inicializacao da UART u.setBaudRate(115200) #Baudrate 115200 u.setMode(8, mraa.UART_PARITY_NONE, 1) #8 bits de dados, 1 de parada e sem paridade u.setFlowcontrol(False, False) #Sem flow control msg_b = bytearray("Ola, Arduino em bytearray!", "ascii") #Enviando como bytearray print("Enviando como bytearray: '{0}'".format(msg_b)) u.write(msg_b) u.flush() time.sleep(1.5) #Sleep para garantir o recebimento no Arduino msg_s = "Ola, Arduino em string!" print("Enviando mensagem como string: '{0}'".format(msg_s)) u.writeStr(msg_s) time.sleep(1.5) u.writeStr("X") print("Existe algo do outro lado?") time.sleep(1.5) if u.dataAvailable(100): #Esperando resposta, com 100ms de timeout print("'{0}', diz o Arduino".format(u.readStr(20))) else: print("Nenhum dado recebido. Existe algo conectado?")
import mraa # on ubilinux, dl & blt v0.8.1, but only works as sudo? import time import serial import datetime y=mraa.Uart(0) # libmraa should configure the gpio ports port = y.getDevicePath() # and provide the devicepath name print 'Opening Uart(0): %s' % port # configure the serial connections (the parameters differs on the device you are connecting to) ser = serial.Serial(port,19200) #ser.open() ser.isOpen() print 'Enter your commands below.\r\nInsert "exit" to leave the application.' input=1 while 1 : # get keyboard input ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S') input = raw_input(st+">> ") # Python 3 users # input = input(">> ") if input == 'exit': ser.close() exit() else: # Kangaroo x2 Simplified Serial Commands: <Channel> <,> <Command> <\n> ser.write(input + '\n') out = ''