Hello all,
Just wanted to share my way of reading values from the arduino with python on the raspberry pi.
In python 2.7.3
import serial
from sys import exit
import os
ser = serial.Serial('/dev/ttyACM0', 9600)
#Setting first boot temperature
set_temp = 0
while True:
if set_temp == 0:
set_temp = raw_input("What temperature would you like? ")
else:
print "Menu:"
print "Hello what would you like to check?"
print "1. Temperature"
print "2. Humidity"
print "3. Settings"
print "4. Exit"
choice = raw_input("> ")
# Read values from serial port
ser.close()
ser.open()
#Get values from serial
from_serial = ser.readline()
#Looks if all values are with the serial connection
if len(from_serial) < 12:
from_serial = ser.readline()
else:
#Just for feedback
print "Serial read OK"
ser.close()
# Split values using *
values = from_serial.split('*')
# Setting temperature value from element [1]
temperature = values[1]
# Setting humidity value from element [0]
humidity = values[0]
#Temperature choice
if choice == "1" or choice == "temperature":
print "Temperature is: ", temperature
print "Set temperature is:", set_temp
raw_input("Press enter")
os.system('clear')
#Humidity choice
elif choice == "2" or choice == "humidity":
print "Humidity is: ", humidity
raw_input("Press enter")
os.system('clear')
#Settings choice
elif choice == "3" or choice == "settings":
choice = raw_input("Change temperature value?(y/n)")
if choice == "y":
set_temp = raw_input("What temperature would you like? ")
os.system('clear')
else:
print "Ok"
os.system('clear')
else:
exit(0)
This line will be different to what port you are using:
ser = serial.Serial('/dev/ttyACM0', 9600)
and in the arduino most of this is from the DHT library.
#include <DHT.h>
#define DHTPIN 7
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup()
{Serial.begin(9600);
//Serial.println("Booting..");
dht.begin();}
void loop()
{
// Read values from dht11 sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
//Print temperatures
// check if returns are valid, if they are NaN , output error.
if (isnan (temperature) || isnan (humidity)) {
Serial.println("Failed to read from dht");
} else {
Serial.print(humidity);
Serial.print("");
Serial.print(temperature);
Serial.println("");}
}
Some links i used:
http://pyserial.sourceforge.net/shortintro.html#opening-serial-ports