It is VERY easy to interface with hardware using Python. While I am definitely not a Python expert, I thought it would still be worthwhile to write this quick post. How many times have you wanted to connect a microcontroller based project up to the computer to either save data or control something via a simple program?
In my previous post I discussed using a thermistor for our toaster oven based reflow oven. The next step for our toaster oven is to see how well it can follow a temperature curve. The Python code below will allow us to log/acquire the temperature of our oven over a set duration (a few minutes). While the example presented here is specifically for saving raw data to a file (to be read in MATLAB), it can be used in any application. For example, I am currently using Python to interface with a Bluetooth Low Energy breakout board (buy one now at our store!).
This simple code will receive a single byte of data over a virtual serial port and save it to a file. The code actually does not need to be modified to receive 16-bit values. While this example will acquire data for a specific duration of time, Python can be used to interface directly with a microcontroller for any number of applications. Be sure to install pySerial, otherwise this will not work.
# Duration in seconds, sample rate (fs) in Hz
duration = 420;
fs = 2.0;
# Calculate sample time and number of loops needed
T = 1/fs;
loops = int(duration/T)
# Setup serial port and open file to write
serial = serial.Serial("COM3", 9600, timeout=5)
f = open("Data1.raw", "w")
# Loop as needed, writing datato file
for i in range(0,loops):
data = serial.read()
# Be sure to close the file afterwards
Change the sample rate (fs) and the duration to match your application. Set the COM port and baud rate. Specify the file name where you want to save the data, and then run the script. The code should be fairly self explanatory.
Now that we have a file which contains our data, time to do something with it! The MATLAB (Octave) code below will read in a file which contains 16-bit values and plot it.
fid = fopen('Data1.raw');
raw_data = fread(fid, 'uint16');
x = double(raw_data)
This is all you need to interface your next project with your computer or to test out your toaster oven reflow oven. The example below shows the entire temperature curve from a test run of the toaster oven. Stay tuned for more cool projects!