_       _       
  (_) ___ | |_ ____
  | |/ _ \| __|_  /
  | | (_) | |_ / / 
 _/ |\___/ \__/___|

Python data logging script for BioSlam

This is a simple data logging script in Python for use with the BioSlam biopotential signal acquisition system. This script can be used to record data from the BioSlam directly into a CSV text file, which can subsequently be loaded into MATLAB / Octave or opened in Excel (or similar).

The script can easily be adapted to sample at a different frequency, or to sample multiple channels, etc. In this version, a single analog channel is sampled at 10 Hz (i.e. the sampling period is 100 ms).

To log data into a file called "mydata.csv", run this command:

python3 datalogger.py mydata.csv

In Windows, the lines that open the serial port name will need to be changed to something like the following (change the COM port number to the value assigned to the connected Arduino):

ser = serial.Serial(                # open serial port

This is the complete Python code:

# Description: Python data logger for BioSlam circuit
# Author: Ted Burke
# Date: 22-Nov-2023
# To log incoming data to a file "mydata.csv":
#    python3 datalogger.py mydata.csv

import sys
import serial

ser = serial.Serial(                # open serial port

filename = 'data.csv'               # default data output filename
if len(sys.argv) > 1:               # check if any command line arguments were provided
    filename = sys.argv[1]          # if a filename was provided in command then use that

with open(filename, 'w') as f:      # open the specified filename for data logging
    while 1:
        text = ser.readline()       # read a line of text from serial port
        text = text.decode('ascii') # convert from bytes object to string
        text = text.rstrip()        # strip trailing newline characters
        print(text)                 # print the text on screen
        f.write(text + '\n')        # write the text to the data file

The Arduino code I used to test the program is shown below, but the data logging script should work with any incoming serial data that is arranged in a single column of ascii numerical values, provided that the same baudrate is selected at both ends (115200 bits/s in the example code shown here) and the correct port is selected in the Python script.

void setup()
  Serial.begin(115200); // open a serial connection to the PC at 115200 bits/s

void loop()
  int v_du; // integer variable to store voltage reading in du (digital units)

  v_du = analogRead(6); // measure the analog voltage on pin A0 and store in v_du

  Serial.println(v_du); // print the measured value as ascii text via serial link

  delay(100); // 10ms delay -> 10 Hz sampling (adjust to control sampling frequency)