Saving Serial Data to a .txt

Serial communication has been established between the L4 and the Pi, next is to store the sent data. To do this a knowledge of basic file input/output is needed in addition to the previous PySerial script in the earlier post. The built-in Python function, open(), is used to do this.

More Information: File Handling in Python

import datetime
import serial
import string

print ("Starting... ")
## Serial setup
ser = serial.Serial(port = '/dev/ttyS0', 
 baudrate = 19200,
 parity = serial.PARITY_NONE,
 stopbits = serial.STOPBITS_ONE,
 bytesize = serial.EIGHTBITS,
 timeout = 100)

print ("Connected")
x = open("/home/pi/New.txt", "a") # gives directory, "a" is for appending

while True: 
 readData = ser.readline().strip() # Storing incoming data in "readData" and stripping string 
 x.write(readData) # writes data to variable x, to file New.txt
 x.close()

In the previous post, there were problems with viewing the strings as whole words, the wind direction was being printed as long column of characters which wasn’t very legible so a new function had to be used in PySerial. when reading in the serial data read() was originally used but readline() is a better alternative as it prints the entire transmission.

In the serial set up, a parameter was added called timeout. Timeout determines how long the port reads data, to make it easy the timeout was made to be 100s seconds.

More Information: PySerial Documentation

Unfortunately, the other Telit transmitter was being used for other parts of the project so a direct serial connection was made between a laptop via USB. To use a Windows machine to connect, serial connection software must be installed. We used Termite as it’s easy to install and use.

Termite Available Here: Termite Download

 

Leave a comment