I'm working on a project that needs to send some numbers from python in windows 10 to an arduino uno over a serial port. As a simple test I just want to turn an LED on by sending '2', and off by sending '4' from a command prompt, although I would like to be able to ultimately use any number 0-99 for different purposes. Here's my arduino code:
const int ledPin = 13;
byte b1, b2;
int val;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (Serial.available() > 1) {
b1 = Serial.read();
b2 = Serial.read();
val = ((b1-48)*10) + (b2-48);
if (val == 2) {
digitalWrite(ledPin, HIGH);
}
if (val == 4) {
digitalWrite(ledPin, LOW);
}
}
This feels like kind of a hack but works because '0' starts at 48 on the ASCII table (so 2 = 50, etc.), which is what the arduino is actually receiving when I use the following python code to send some numbers:
import serial
ser = serial.Serial('COM4',9600)
n = 2
s = str(n)
t = s.rjust(2,'0')
ser.write(t.encode())
So I've found that this does indeed turn on my LED when using python 3.4 on my desktop, and using n = 4 turns it off. This always returns '2' regardless of the number I choose for n, as in "2 bytes have been sent", which is what I want. The problem I'm having is that this is all fine and dandy in python 3.4, but when I tried loading this project on my laptop using python 2.7 I get a '2L' return instead of just '2', and the LED no longer turns on.
Both my laptop and desktop are using pySerial 3.3, and I've confirmed that the same thing happens (doesn't work) when I use python 2.7 on my desktop, and it does work when I use python 3.4 on my laptop.
I need to use python 2.7 for this project because of some additional hardware/API I want to add later, so what is the significance of this 'L' being appended on the serial return and why does this not work with python 2.7?