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

Sending sensor readings from an Arduino to a Python program

In this example, an Arduino reads the analog voltage from pin A4 once per second and transmits the reading over a serial connection (running at 9600 baud) to a PC where it is received and printed on the screen by a Python program.

insert alt text here

Arduino code:

//
// Title: Transmit sensor readings to PC over serial connection
// Author: Ted Burke
// Date: 8-Nov-2023
//

void setup()
{
  Serial.begin(9600); // Open a serial connection to the PC at 9600 bits/second
}

void loop()
{
  int voltage; // Declare an integer variable to store each sensor reading

  voltage = analogRead(4); // Measure voltage on pin A4 (0 -> 1023 du)

  Serial.println(voltage);

  delay(1000);
}

Python code:

#
# Title: signal.py
# Description: Read serial data from a connected Arduino
# Author: Ted Burke
# Date: 8-Nov-2023
#

import serial

ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=9600
)

while 1:
    text = ser.readline()
    print(text)

Improved Python code that converts the incoming bytes object to a string:

#
# Title: signal.py
# Description: Read serial data from a connected Arduino
# Author: Ted Burke
# Date: 8-Nov-2023
#

import serial

ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=9600
)

while 1:
    text = ser.readline()
    text = text.decode('ascii').rstrip() # convert from bytes object to string and strip trailing newline characters
    print(text)

insert alt text here

To log data to a csv file:

python3 signal.py > data.csv

To plot the logged data using Octave / MATLAB:

x = csvread('data.csv');
plot(x)