Bibsta
Bibsta

Reputation: 57

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(",");

}

Upvotes: 3

Views: 2555

Answers (2)

codeflag
codeflag

Reputation: 191

There is an issue with the Raspberry Pi 3 and the uart0 (Bluetooth), uart1 (Serial).
For the Pi 3 uart1 is usually available on /dev/ttyS0 and TX-GPIO 14, RX-GPIO 15.
The baud rate for uart1 is dependent on the core clock. So if the core clock changes, the baud rate will change!
Workaround 1: In /boot/config.txt, add the line core_freq=250. Save and reboot! Now your Pi have a constant core frequency. Raspberry Pi 3 UART baud rate workaround
Workaround 2: Change the device tree, use uart0 for Serial communication and uart1 for Bluetooth (same issue now for Bluetooth).Raspberry Pi 3 compatibility (BT disable & serial port remap fix)

Upvotes: 0

dubafek
dubafek

Reputation: 1113

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.

Upvotes: 2

Related Questions