Python code for serial port communication

We will make use of the pySerial library (https://pyserial.readthedocs.io/en/latest/shortintro.html#opening-serial-ports) for interfacing the carbon dioxide sensor:

  1. As per the sensor's documentation, the sensor output can be read by initiating the serial port at a baud rate of 9600, no parity, 8 bits, and 1 stop bit. The GPIO serial port is ttyAMA0. The first step in interfacing with the sensor is initiating serial port communication:
       import serial 
ser = serial.Serial("/dev/ttyAMA0")
  1. As per the sensor documentation (http://co2meters.com/Documentation/Other/SenseAirCommGuide.zip), the sensor responds to the following command for the carbon dioxide concentration:
Command to read carbon dioxide concentration from the sensor-borrowed from the sensor datasheet
  1. The command can be transmitted to the sensor as follows:
       ser.write(bytearray([0xFE, 0x44, 0x00, 0x08, 0x02, 0x9F, 0x25]))
  1. The sensor responds with a 7-byte response, which can be read as follows:
       resp = ser.read(7)
  1. The sensor's response is in the following format:
Carbon dioxide sensor response
  1. According to the datasheet, the sensor data size is 2 bytes. Each byte can be used to store a value of 0 and 255. Two bytes can be used to store values up to 65,535 (255 * 255). The carbon dioxide concentration could be calculated from the message as follows:
       high = resp[3] 
low = resp[4]
co2 = (high*256) + low
  1. Put it all together:
       import serial 
import time
import array
ser = serial.Serial("/dev/ttyAMA0")
print("Serial Connected!")
ser.flushInput()
time.sleep(1)

while True:
ser.write(bytearray([0xFE, 0x44, 0x00, 0x08,
0x02, 0x9F, 0x25]))
# wait for sensor to respond
time.sleep(.01)
resp = ser.read(7)
high = resp[3]
low = resp[4]
co2 = (high*256) + low
print()
print()
print("Co2 = " + str(co2))
time.sleep(1)
  1. Save the code to a file and try executing it.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.241.82