How to do it...

  1. Create the following serialControl.py script:
#!/usr/bin/python3 #serialControl.py import serial import time #Serial Port settings SERNAME="/dev/ttyUSB0" #default setting is 9600,8,N,1 IDLE=0; SEND=1; RECEIVE=1 def b2s(message): '''Byte to String''' return bytes.decode(message) def s2b(message): '''String to Byte''' return bytearray(message,"ascii") class serPort(): def __init__(self,serName="/dev/ttyAMA0"): self.ser = serial.Serial(serName) print (self.ser.name) print (self.ser) self.state=IDLE def __enter__(self): return self def send(self,message): if self.state==IDLE and self.ser.isOpen(): self.state=SEND self.ser.write(s2b(message)) self.state=IDLE def receive(self, chars=1, timeout=5, echo=True, terminate="r"): message="" ...

Get Raspberry Pi 3 Cookbook for Python Programmers - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.