Python Serial.write Examples - JohnHau/mis GitHub Wiki
EXAMPLE #12 File: watcher.py Project: MrLeeh/jsonwatch def read_serial(ser: serial.Serial, q_out: queue.Queue, q_in: queue.Queue, stop_event: threading.Event): while (ser.isOpen()): if stop_event.is_set(): return if not q_in.empty(): ser.write(q_in.get() + b'\n') q_out.put(bytestostr(ser.readline()))
EXAMPLE #21 File: controlador.py Project: mcendon/fiuba-nubeinteractiva-mapper class Controlador(threading.Thread): def init(self): threading.Thread.init(self)
self._idle = True
try:
self.serial = Serial('/dev/rfcomm0', 19200, timeout = 0.1)
except Exception as e:
raise Exception("Error al inicializar puerto: " + str(e))
self.serial.flushInput() # Para limpiar el buffer de entrada de la compu.
self.start()
def isIdle(self):
return self._idle
def run(self):
while True:
if self.serial.inWaiting() > 0 and self.serial.read().encode('hex') == "55":
self._idle = True
time.sleep(0.2)
def hacerEfecto(self,idEfecto):
if idEfecto != None:
self._idle = False
self.serial.write(chr(idEfecto))
print "[Mensaje del Controlador]: Despache el efecto Id ",idEfecto," a la nube"
else:
print "No hay definido un mapeo para el evento solicitado"
EXAMPLE #21 File: controlador.py Project: mcendon/fiuba-nubeinteractiva-mapper class Controlador(threading.Thread): def init(self): threading.Thread.init(self)
self._idle = True
try:
self.serial = Serial('/dev/rfcomm0', 19200, timeout = 0.1)
except Exception as e:
raise Exception("Error al inicializar puerto: " + str(e))
self.serial.flushInput() # Para limpiar el buffer de entrada de la compu.
self.start()
def isIdle(self):
return self._idle
def run(self):
while True:
if self.serial.inWaiting() > 0 and self.serial.read().encode('hex') == "55":
self._idle = True
time.sleep(0.2)
def hacerEfecto(self,idEfecto):
if idEfecto != None:
self._idle = False
self.serial.write(chr(idEfecto))
print "[Mensaje del Controlador]: Despache el efecto Id ",idEfecto," a la nube"
else:
print "No hay definido un mapeo para el evento solicitado"
EXAMPLE #40 File: server.py Project: astrolitterbox/opengreenhouse def interact(self): if not self.mock: try: serial = Serial(SERIAL_DEVICE, SERIAL_RATE) except SerialException: print("Error opening serial. To use without arduino: ./server.py --mock") os._exit(1) while True: try: while True: cmd = self.sendq.get(block=False) if self.mock: print("SERIAL WRITE:", cmd) else: serial.write(cmd.encode('ascii')) serial.write(b'\n') except Empty: pass if self.mock: time.sleep(1) line = b'temp 18\n' else: line = serial.readline() key, value = line.decode('ascii').strip().split(' ') value = self.from_arduino(key, int(value)) self.log_value(key, value) self.state[key] = value self.handle() self.recvq.put((key, value))
EXAMPLE #50 File: client.py Project: miguelgrinberg/arduino-digital-picture-frame def main(): args = parse_arguments()
images = scan_for_images(args.folder)
if len(images) == 0:
print('Error: found no jpeg images in "%s".' % args.folder)
sys.exit(1)
print('Found %d images.' % len(images))
serial = Serial(args.port)
serial.baudrate = args.baudrate
print('Opened serial port %s.' % serial.name)
print('Interval between pictures is %d seconds.' % args.interval)
width = 0
height = 0
# display random pictures
while True:
time.sleep(args.interval)
if width == 0:
# connect to the Arduino and obtain screen size
serial.write('C')
width = int(serial.readline())
height = int(serial.readline())
print('Display is %dx%d.' % (width, height))
image = random.choice(images)
print('Uploading "%s"...' % image)
upload_image(image, serial, (width, height))
EXAMPLE #60 File: bluebell.py Project: thegaragelab/bluebell def update(self, red, green, blue, time = 10): """ Change the device to the requested color for the period specified.
@param red the red component of the color (0 to 255)
@param green the green component of the color (0 to 255)
@param blue the blue component of the color (0 to 255)
@param time the time (in seconds) to hold the color.
@return true if the command was sucessfuly sent to the device.
"""
# Set up the serial port
port = None
try:
port = Serial(self._port, baudrate = 57600, timeout = 0.2)
except:
return False
# Write the data
data = "!%c%c%c%c\n" % (
trimValue(red),
trimValue(green),
trimValue(blue),
trimValue(time)
)
for ch in data:
port.write(ch)
sleep(0.01)
# All done
port.close()
return True
EXAMPLE #70 File: serial_port.py Project: UoMCS/Perentie class SerialPortBackEnd(BackEnd):
def __init__(self, port = None, baudrate = 115200,
read_timeout = 1.0, write_timeout = 0.1):
"""
Provides a serial-port back-end for the protocol. Timeouts are in seconds.
"""
BackEnd.__init__(self)
self.name = "Serial"
# Start the emulator as a child-process
self.serial = Serial(port,
baudrate = baudrate,
timeout = read_timeout,
writeTimeout = write_timeout)
def read(self, length):
return self.serial.read(length)
def write(self, data):
self.serial.write(data)
def flush(self):
self.serial.flush()
def close(self):
self.serial.close()
EXAMPLE #80 class MachineCom(): def init(self, port = 'AUTO', baudrate = 250000): self.serial = None if port == 'AUTO': programmer = stk500v2.Stk500v2() for port in serialList(): try: programmer.connect(port) programmer.close() self.serial = Serial(port, baudrate, timeout=5) break except ispBase.IspError: pass programmer.close() else: self.serial = Serial(port, baudrate, timeout=5)
def readline(self):
if self.serial == None:
return ''
ret = self.serial.readline()
print "Recv: " + ret.rstrip()
return ret
def close(self):
if self.serial != None:
self.serial.close()
self.serial = None
def sendCommand(self, cmd):
if self.serial == None:
return
self.serial.write(cmd + '\n')
EXAMPLE #90
File: setposition.py Project: atfienberg/sipmometer
def main():
if len(sys.argv) != 2:
print('requires one argument, the filter position')
sys.exit(1)
filterwheel = Serial('/dev/filterwheel', 115200, timeout=0.1)
filterwheel.write('pos=%i\r' % int(sys.argv[1]))
filterwheel.close()
EXAMPLE #100
File: tarjetaTOC.py Project: Lilito/Conector-toc
class tarjetaTOC():
'''
Clase de comunicacion con la tarjeta mediante puerto serial.
'''
def __init__(self, controlador):
'''
Constructor de la clase
'''
self.puerto = "/dev/ttyS0"
self.BAUDS = "9600"
self.TIMEOUT = 1
self.serial = Serial(port=self.puerto,
baudrate=self.BAUDS,
bytesize=8,
stopbits=1,
timeout=self.TIMEOUT,
dsrdtr=False,
rtscts=True)
self.cerrar_puerto()
def abrir_puerto(self):
try:
self.serial.open()
#time.sleep(2)
except:
print "Error de apertura de puerto"
def cerrar_puerto(self):
self.serial.close()
def desconectar(self):
self.cerrar_puerto()
def escribir_datos(self, datos):
# Escribe datos en el puerto
self.serial.flushOutput()
self.serial.write(datos)
print "Escribio"
def crear_datos_simulador(self):
pass
def leer_datos(self):
recv = self.serial.readline()
if len(recv) >= 5:
self.serial.flushInput()
return recv
else:
return (recv)
def enviar_comando(self, comando):
# Envia un comando y espera a que se reciba respuesta
self.abrir_puerto()
self.escribir_datos(comando)
recv = self.leer_datos()
self.cerrar_puerto()
return recv
EXAMPLE #110
File: biu.py Project: daniel-kurushin/iisu
def get_my_port(self, open_ports = []):
ports = configuration.PORTS
for port in open_ports:
ports.remove(port)
for p in configuration.PORTS:
try:
print('Trying port %s ...' % p, end = '', file = sys.stderr)
s = Serial(port = p, baudrate = configuration.BAUDRATE, timeout = 0.1)
if s.read(10) != b'': raise SerialException('wrong port, unexpected data')
self.state = {}
print(' ok, ', end = '', file = sys.stderr)
for biuname in configuration.BIU_QUERY.keys():
print('trying biu %s ' % biuname, end = '', file = sys.stderr)
q = configuration.BIU_QUERY[biuname]['q']
a = configuration.BIU_QUERY[biuname]['a']
s.write(q)
if len(s.readall()) == a:
present = True
print('ok', file = sys.stderr)
else:
present = False
print('none', file = sys.stderr)
self.state.update({
biuname : dict(present = present)
})
if self.state['kru']['present'] or
self.state['khc']['present'] or
self.state['ken']['present'] or
self.state['kst']['present'] : return p
except SerialException as e:
print(e, file = sys.stderr)
return None
EXAMPLE #120 File: main.py Project: Viral-MediaLab/esp8266_benchmarks class ESP8266(): def init(self, port, baud_rate): print "opening connection" self.ser = Serial(port, baud_rate, timeout=1) self.ser.close() self.ser.open() print "connection opened"
def send_command(self, cmd, timeout=1000, until="-a-string-thats-never-there-"):
self.ser.write(cmd + "\r\n")
last_activity = millis()
buf = ""
while True and (millis() - last_activity) < timeout and until not in buf:
bytes_to_read = self.ser.inWaiting()
buf += self.ser.read(bytes_to_read)
if bytes_to_read > 0:
last_activity = millis()
return buf
def make_http_request(self, host, port, route):
start = millis()
self.send_command("AT+CIPSTART=0,\"TCP\",\"" + host + "\"," + str(port), 500, "OK")
self.send_command("AT+CIPSTATUS", 500, "OK")
msg = "GET " + route + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n"
self.send_command("AT+CIPSEND=0," + str(len(msg)), 500, "OK")
result = self.send_command(msg, 10000, "+IPD,0,5:0")
print result
self.send_command("AT+CIPCLOSE=0", 500, ",CLOSED")
print str(1 if "CC3000" in result else 0) + "," + str(millis() - start)
EXAMPLE #130 File: dmx.py Project: ungood/IdahoCore class Widget: """Class to interface with the USBDMX Pro Widget"""
def __init__(self, port):
try:
if(port == 'fake'):
import fakes
self.serialPort = fakes.Serial(port='/dev/fake')
else:
self.serialPort = Serial(port=port, baudrate=57600, timeout=1)
print("Connected to USBDMX on port '%s'" % (self.serialPort.portstr))
except:
print("ERROR: Could not open port '%s'" % port)
sys.exit(1)
def transmit(self, label, data):
data_size = len(data)
header = bytearray(label)
header.append(int(data_size & 0xFF))
header.append(int((data_size >> 8) & 0xFF))
message = SOM + header + data + EOM
self.serialPort.write(message)
def send_dmx(self, packet):
msg = SC + bytes(packet.data)
self.transmit(LABEL_OUTPUT_ONLY_SEND_DMX, msg)
def send_palette(self, palette):
self.send_dmx(Packet(palette))
EXAMPLE #140 File: bus_pirate.py Project: bsmt/dumperino class BusPirate(Board): def init(self, dev, baudrate): Board.init(self, dev, baudrate)
self.serial = Serial(self.dev, self.baud, timeout=2)
self._init_bus_pirate()
def _init_bus_pirate(self):
'''Try to put the bus pirate into bitbang mode.'''
# hardware reset
self.serial.write(b"\xff")
sleep(1)
# enter bitbang mode
self.serial.flushInput()
for _ in range(25):
serial.write(b"\x00")
sleep(0.2)
if serial.inWaiting():
bbio1 = serial.read(5)
if bbio1 == "BBIO1":
break
else:
raise BoardInitError
EXAMPLE #150 File: views.py Project: mrasmus/UbiCondo-django def light_on(request): ser = Serial("/dev/tty.usbserial-A900UCLV", 115200) if (not ser.isOpen()): ser.open() ser.write("m\n9\nW\n") text = 'Light is now on.' return HttpResponse(text)
EXAMPLE #160 File: SerialSocket.py Project: DarkmatterVale/BlocklyPropClient class SerialSocket(WebSocket): def init(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=None): super(SerialSocket, self).init(sock, protocols, extensions, environ, heartbeat_freq) self.serial = Serial()
def received_message(self, message):
if message.data[0:len(OPEN_CONNECTION_STRING)] == OPEN_CONNECTION_STRING:
port = message.data[len(OPEN_CONNECTION_STRING):]
self.serial.port = port
self.serial.baudrate = 115200
try:
self.serial.open()
except SerialException as se:
self.send("Failed to connect to: " + port + "\n\r(" + se.message + ")\n\r")
return
if self.serial.isOpen():
self.send("Connection established with: " + port + "\n\r")
thread.start_new_thread(serial_poll, (self.serial, self))
else:
self.send("Failed to connect to: " + port + "\n\r")
else:
if self.serial.isOpen():
self.send(message.data)
self.serial.write(message.data)
def close(self, code=1000, reason=''):
# close serial connection
print 'closing'
self.serial.close()
super(SerialSocket, self).close(code, reason)
EXAMPLE #170 File: serial_communicator.py Project: alextercete/robotcv class SerialCommunicator:
def __init__(self, port='/dev/usb/ttyUSB0', baudrate=19200):
self.connection = Serial()
self.connection.port = port
self.connection.baudrate = baudrate
def set_port(self, port_name):
self.connection.port = port_name
def send_command(self, message):
self.connection.open()
self.connection.write(message)
# Waits until the robot starts the response
while self.connection.read() != SOT:
time.sleep(SLEEPING_TIME)
message_length = self.connection.read()
remaining_chars = ord(message_length) + 1
message = self.connection.read(remaining_chars)
message_type = message[0]
encoded_data = message[1:-1]
self.connection.close()
return message_type, encoded_data
EXAMPLE #180 File: flash_xbee.py Project: Kniyl/Drone-Racer class XBeeManager: def init(self, iface, baud): self.serial = Serial(iface, baud) while self.serial.inWaiting(): self.serial.read()
def __enter__(self):
sleep(2)
self.write('+++', False)
return self
def __exit__(self, eType, eValue, traceback):
self.write('ATCN')
sleep(1)
def write(self, message, endline=True):
msg = message.encode()
if endline:
msg += b'\r'
self.serial.write(msg)
char = b''
print('[', datetime.now(), '] ', end='')
while char != b'\r':
char = self.serial.read()
print(char.decode(), end='')
print('')
EXAMPLE #190 File: terminal.py Project: jisanch1/sepial class Terminal:
def __init__(self, port, baud):
self.sp = Serial(port, baud)
self.reader_thread = Thread(None, self.read, "Reader")
self.writer_thread = Thread(None, self.write, "Writer")
self.alive = False
def start(self):
self.reader_thread.start()
self.reader_thread.join()
def read(self):
self.alive = True
self.writer_thread.start()
ch = stdin.read(1)
while ch != '#':
self.sp.write(ch)
ch = stdin.read(1)
self.alive = False
self.sp.write(' ')
self.writer_thread.join()
def write(self):
while self.alive:
ch = self.sp.read()
stdout.write(ch)
EXAMPLE #200 File: serio.py Project: TanujSharma/acgtools class serio: def init(self, line, baud, tracefile=None): self.__s = Serial(line, baud, timeout=None) if tracefile: self.__trace = open(tracefile, 'w') self.flush_buffers()
def trace(self, line):
self.__trace.write(line + '\n')
self.__trace.flush()
def tx(self, cmd):
#cmd = cmd + '\r\n'
self.trace(">>> %r"%cmd)
self.__s.write(cmd)
def peekbuffer(self, tmo=0):
self.__s.setTimeout(tmo)
ret = self.rx()
self.__s.setTimeout(None)
return ret
def rx(self):
ret = self.__s.readline()
if ret[-1:] == '\n':
ret = ret[:-1]
if ret[-1:] == '\r':
ret = ret[:-1]
self.trace("<<< %r"%ret)
return ret
def flush_buffers(self):
self.__s.flushInput()
self.__s.flushOutput()
self.trace("--- flushed buffers")
EXAMPLE #210 File: alatweet.py Project: pdp7/tweetypi class HashTagDisplay(): def init(self, delay=5, debug=False): # duration in seconds to allow human to read display self.delay = delay # print messages to shell for debugging self.debug = debug self.ser = Serial('/dev/ttyS0', baudrate=9600, timeout=1)
def search(self, hashtag):
# search for tweets with specified hashtag
twitter_search = Twitter(domain="search.twitter.com")
return twitter_search.search(q=hashtag)
def display(self, results):
# Display each tweet in the twitter search results
for tweet in results.get('results'):
msg = "@" + tweet.get('from_user') + ": " + tweet.get('text')
#http://stackoverflow.com/questions/8689795/python-remove-non-ascii-characters-but-leave-periods-and-spaces
msg = filter(lambda x: x in string.printable, msg)
msg = re.sub('\s+',' ', msg)
if self.debug == True:
print "msg: [" + msg + "]"
for c in msg:
self.ser.write(c)
sleep(0.01)
self.ser.write('\n');
sleep(self.delay)
EXAMPLE #220 File: polarisation_analyser.py Project: asafpm/PolarizationAnalyzer class PlotUpdater(threading.Thread): """This class sets the fraction of the progressbar"""
#Thread event, stops the thread if it is set.
stopthread = threading.Event()
def __init__(self, gui):
threading.Thread.__init__(self) #Call constructor of parent
self.gui = gui
self.frac = 0
self.ser = Serial("/dev/ttyACM0",115200)
#self.ser.timeout = 1
self.i = 0
def run(self):
"""Run method, this is the code that runs while thread is alive."""
#self.ser.readline()
#self.ser.readline()
#While the stopthread event isn't setted, the thread keeps going on
while not self.stopthread.isSet() :
# Acquiring the gtk global mutex
#gtk.threads_enter()
#Setting the fraction
self.frac += 0.01
self.i += 1
#self.gui.line.set_data((t, np.sin(3*np.pi*(t+self.frac))))
rslt = ''
self.ser.write("d\n")
s = self.ser.readline().strip()
while s != '' :
rslt += s+'\n'
s = self.ser.readline().strip()
#print repr(s)
try:
n = np.loadtxt(StringIO(rslt))
angles = n[:,1]
intensities = n[:,2]
#(self.gui.s0p, self.gui.s1, self.gui.s2, self.gui.s3, self.gui.dop)=get_stokes(angles,intensities)
self.gui.line.set_data((angles, intensities))
except ValueError:
print "Value Error"
# Releasing the gtk global mutex
#gtk.threads_leave()
#Delaying 100ms until the next iteration
self.ser.close()
def stop(self):
"""Stop method, sets the event to terminate the thread's main loop"""
self.stopthread.set()
EXAMPLE #230 File: connexion.py Project: mattwilliamson/WaDeD class Connexion: """ Manage the USB connexion. """
def __init__(self, tty = "/dev/ttyACM0"):
"""
Open a serial connexion on specified tty, with a 1152000
baudrate.
"""
try:
self.serial = Serial(tty, baudrate = 115200)
except SerialException:
print("Can't open", tty)
exit(1)
def read(self):
""" Read a line. """
try:
return self.serial.readline().decode("ascii", "ignore")
except OSError:
sleep(1)
return self.read()
def write(self, msg):
""" Send a string. """
self.serial.write(normalize("NFD", msg).encode("ascii", "ignore"))
EXAMPLE #240 File: run_g29_tests.py Project: lumbric/kossel_config class Rubinstein(object): def init(self, port='/dev/ttyUSB0', baudrate=250000, timeout=0.25): self.serial = Serial(port=port, baudrate=baudrate, timeout=timeout) # FIXME don't know why initialization stops with this line while self.serial.readline() != 'echo:SD init fail\n': sleep(0.2) self.busy = False
def command(self, cmd, timeout=float('inf')):
# FIXME needs mutex!
if self.busy or self.serial.read():
raise RuntimeError("busy")
self.busy = True
self.serial.write("{}\n".format(cmd))
response = ''
start = time()
while time() - start < timeout:
sleep(0.2)
line = self.serial.readline()
if line == 'ok\n':
# FIXME missing try/finally for busy=False
self.busy = False
return response
if len(line) > 0:
print line,
response += line
else:
raise RuntimeError(
"timeout when waiting for command {}".format(cmd))
EXAMPLE #250 File: radio.py Project: CustardCat/le-mesmer class Radio: "Kenwood THF7E Radio interface"
def __init__(self):
self.radio = Serial(port="/dev/tty.usbserial", timeout=3, baudrate=9600)
# self.radio = Serial( port='/dev/ttyUSB0',timeout=3,baudrate=9600 )
self.last_cmd = ""
def receive(self):
buffer = ""
while True:
buffer = buffer + self.radio.read(self.radio.inWaiting())
if "\r" in buffer:
lines = buffer.split("\r")
last_received = lines.pop(0)
buffer = "\r".join(lines)
if self.last_cmd in last_received:
break
if "N" in last_received:
break
return last_received
def send(self, cmd, args):
self.last_cmd = cmd
self.radio.write("\r")
self.radio.write(cmd + " " + args + "\r")
self.radio.flushInput()
EXAMPLE #260 File: serveurSMS.py Project: beaukams/BusTrackingGPS class SerialServer(Thread): def init(self, port="/dev/ttyACM0", baudrate=9600, timetoread=2): Thread.init(self) self.server = Serial(port=port, baudrate=baudrate) self.dataInQueeud = False self.running = True self.timetoread = timetoread #periodicite de lecture du port self.datas = "" #les donnees lus self.dataToSend = "" #les donneees à envoyer
def run(self):
"""lecture continue du port série. Lorsqu'il y'a quelque chose à lire, il lie puis envoie les donnees"""
while self.running == True:
while self.server.inWaiting() > 0:
self.datas += self.server.readline()
sleep(self.timetoread) #pause
#envoie s'il y'a quelques a envoyer
if self.dataToSend != "":
self.server.write(self.dataToSend)
self.server.flush()
def recvdatas(self):
res = self.datas
self.datas = ""
return res
def senddatas(self, data = ""):
self.dataToSend = data
def toStop(self):
self.server.close()
self.running = False
EXAMPLE #270 File: remote_lib.py Project: FinK-M/Cable-Climbing-Robot def send(message): ser = Serial("COM3", baudrate=57600) ser.flush() ser.write(message.encode()) sleep(0.1) if ser.inWaiting(): print(ser.readline().decode().rstrip('\r\n').split(",")[0]) EXAMPLE #280 File: arduino.py Project: saltire/hardlivin class Arduino: def init(self, port, baud): self.serial = Serial(port, baud) time.sleep(2)
def write_ints(self, *ints):
self.serial.write(''.join(chr(i) for i in ints))
EXAMPLE #290 File: SerialPortDataSource.py Project: Max-Might/Elmo-Scan class SerialPortDataSource: def init(self, params): self.port = Serial() self.port.port = params['port'] self.port.baudrate = params['baudrate']
def open(self):
try:
self.port.open()
return True
except SerialException as e:
return str(e)
def close(self):
self.port.close()
def execute(self, command):
self.port.write(command + '\r\n')
res = ""
c = ''
while (c != '>'):
res += c
c = self.port.read(1)
return res
EXAMPLE #30-1 File: Impresion.py Project: drmelectronic/Despacho def buscar_serial(self): num_ports = 20 dispositivos_serie = [] if os.name == "nt": for i in range(num_ports): try: s = Serial(port=i, baudrate=9600, bytesize=8, timeout=0) s.write("\n\n") s.close() except: self.log += "No se pudo conectar a COM%s\n" % i else: dispositivos_serie.append(s.portstr) else: for i in range(num_ports): port = "/dev/ttyS%d" % i try: s = Serial(port=port, baudrate=9600, bytesize=8, timeout=0) s.close() except: self.log += "No se pudo conectar %s\n" % port else: dispositivos_serie.append(port) for i in range(num_ports): port = "/dev/ttyUSB%d" % i try: s = Serial(port=port, baudrate=9600, bytesize=8, timeout=0) s.close() except: self.log += "No se pudo conectar %s\n" % port else: dispositivos_serie.append(port) self.seriales = dispositivos_serie