0
votes

I am playing with arduino. Inside the projects book it has a project for getting the temperature from a temperature sensor. I hooked as it says and wrote the following simple code

const int sensorPin = A0;
void loop(){
    int sensorVal = analogRead(sensorPin);
    float voltage = (sensorVal / 1024.0)* 5.0;
    float temperature = (voltage - .5) * 100;
    Serial.println(temperature);
}

to print the temperature in the serial monitor. I used pySerial to get the temp from the arduino like this

try:
    ser = serial.Serial('/dev/ttyACM0', 9600)
except serial.SerialException as se:
    print se
    exit()

while True:
    temperature = ser.readline()
    print "Temp from arduino", temperature
    try:
        temperature = float(temperature)
        print "FLoat temperature", temperature
    except ValueError as ve:
        print ve
        continue

But the problem is that while the Serial monitor from the arduino ide shows the temperature normally (22.3 e.g) a normal float number that is python has the number divided by 10

Temp from arduino 2.27
FLoat temperature 2.27

How can I deal with that?

1
Your outputs are identical? Also, you would want to do float() much ealier, beacause after recieving the data.. You've already ruined it by not treating it as a float() from the start. For instance, you can't do x = 10.15; x = int(x); x = float(x); because it will end up 10 even tho you try to convert it back. Not that this will help but do temperature = float(ser.readline() instead.Torxed
It's strange to have a difference between the output in the serial monitor and in the input pySerial. I see no reason for that - both of them show text coming from the serial interface. I have two questions and one suggestion. Why don't you divide by 1023 instead of 1024? Why is this - .5? Try to print the voltage value to the serial to see the results.Andrei Boyanov
@Torxed ValueError: invalid literal for float(): 22.73.24 this is what I get for float(ser.readline()) Its like its reading a line and something from the following line...Must I sync arduino Serial.println() and python's serial.readline()?Apostolos
@Torxed I don't think something is ruined... the first time temperature is a string and this is a good idea to print in for debugging before converting it to float. Really it's a better practice to use different variables for that...Andrei Boyanov
Could it be because I was having the Ide monitor openned up at the same time with python script running?Apostolos

1 Answers

0
votes

It seams that something else except the temperature is printed to the serial interface by your Arduino. Try to prefix the temperature with some tag and to parse it in the python side:

Serail.print('Temp:')
Serial.println(temperature);

And in the client:

input = ser.readline()
print "Input from arduino", input
try:
    if input.startswith('Temp:')
    temperature = float(input[len('Temp'):])
        print "Float temperature", temperature