I'm trying to read potentiometer values from an arduino using python. But my serial read values are strange.
Python Code:
import serial
ser = serial.Serial('COM12')
print ( "connected to: " + ser.portstr )
count = 1
while True:
for line in ser.read():
print( str(count) + str( ': ' ) + str( line ) )
count = count + 1
ser.close()
Arduino Code:
int potpin = 0; // analog pin used to connect the potentiometer
int val = 0; // variable to store the value coming from the sensor
int oldVal = 0; // used for updating the serial print
void setup()
{
Serial.begin(9600);
}
void loop()
{
val = analogRead(potpin);
val = map(val, 0, 1023, 0, 179);
if( val != oldVal )
{
Serial.print(val); // print the value from the potentiometer
oldVal = val;
}
delay(100);
}
Some Python Output: This output came from a straight, slow increase on the potentiometer, I never turned it down at any point.
1: 56
2: 57
3: 49
4: 48
5: 49
6: 49
7: 49
8: 50
9: 49
10: 51
When I run the arduino serial terminal I get values that range from 0-179. Why isn't Python getting the correct values from the serial port?
Thanks
EDIT:
Solved the problem. 48-55 are the ascii values for 1-9 so it's a matter of changing the python code to print the character not the value. However this causes another problem in that it prints individual digits. for example, the number '10' comes in as a single '1' and '0'. This is simply solved by using Serial.write instead of Serial.print in the the arduino sketch. This also means that you'll be receiving a byte that is your number and not the ascii value of the number so you don't need to convert the read in line from a value to ascii.
Hope this helps.