Search code examples
python-3.xpyserialuart

Writing through UART to a microcontroller


I am new to python. I am using a BeagleBone Black Wireless, with Debian 9.5 installed on it as well as Python 3.5.3 The Microcontroller is connected to my BeagleBone via USB. It is reading the serial line at baud rate 9600. I can control solenoids to turn on or off by sending enable "9----" to the microcontroller, where - can be a 0 or a 1. to turn on solenoid 1 and 3 I would have to send '91010' to turn all of them off I would have to send '90000'

I need a python program that would help me send enable signals (9----)

I am using this from PYserial documentation as my reference:

import serial
ser = serial.Serial('/dev/ttyUSB0',9600, timeout = 0)  # open serial port
print(ser.name)         # check which port was really used
ser.write(str('91010'))     # write a string
line = ser.readline()
ser.close()             # close port

If I run this program, theoretically, would that work to turn solenoid 1 and 3 on? Ideally, I would like to create a function with 4 arguments, one for the state of each solenoid , for example something like pwr_solenoid(1,1,1,1) would send '91111' over serial to turn all the solenoids on


Solution

  • You need to write the data as bytes e.g. '91010'.encode() using https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.write

    Also if the serial port has a way for it to tell you if the write operation is successful, you can also do ser.read after you write using https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.read and process that output