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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.