Bibsta Bibsta - 11 months ago 60
Python Question

Raspberry Pi & Arduino reading serial sensor data

I have a voltage sensor attached to my Arduino uno which in turn is connected to my Raspberry Pi 3. I would like to grab the sensor info in a ping pong type of way from the Arduino to the Raspberry Pi. I will wake it up with a character sent via a Python script on a cronjob and the sensor values grabbed and put into a mysql database.

In the future I would like to add more sensors to the Arduino

The issue I'm having is the Python side when I run the python code I just get a blank black line.

Raspberry Pi 3 Python code:


import serial
import MySQLdb
import time

db = MySQLdb.connect(host="localhost",

cur = db.cursor()

port = serial.Serial("/dev/ttyACM0", baudrate = 9600, timeout=None)

sensor1 = 0;
sensor2 = 0;
sensor3 = 0;

vals = []

while (port.inWaiting()==0):

vals = (port.readline()).split(',')
print vals
sensor1 = int(vals[0])
sensor2 = int(vals[1])
sensor3 = int(vals[2])
cur.execute("insert into voltage(volts) values(" + str(Battout) + ")" )

cur.execute("SELECT * from voltage")


Arduino code:

const int BattVolt = A0;

int BattVal = 0;
float Battout;

void setup() {

void loop() {

while(!Serial.available()); //wait for character from raspi

float Voltage;
BattVal = analogRead(BattVolt); //read analog pins



Answer Source

Some observations to your implementation.

  1. Why do you use Battout in the python script?

  2. In the python script you are expecting a line (that means a string ended in '\n') but in the Arduino C++ code you use print instead of println or adding a line feed.

  3. Apparently you are expecting to receive something like "12,32,15," in the python script but if you send only one character to the Arduino it will make just 1 iteration of the main loop.