Bibsta Bibsta - 1 month ago 17
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:

#!/usr/bin/python

import serial
import MySQLdb
import time

db = MySQLdb.connect(host="localhost",
user="user",
passwd="password",
db="database")

cur = db.cursor()

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

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

vals = []

while (port.inWaiting()==0):
port.write("*")
time.sleep(1)

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")

db.close()


Arduino code:

const int BattVolt = A0;

int BattVal = 0;
float Battout;

void setup() {
Serial.begin(9600);
}


void loop() {

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

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

Serial.print(Battout);
Serial.print(",");

}

Answer

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.