Hello! This is my first time posting on this forum.
I am testing out serial communication with various applications, starting with python. I have the following Arduino Code which listens at my port /dev/ttyACM0 for bytes to respond to by turning on/off LEDs.
#define redLED 7
#define greenLED 6
#define blueLED 5
int data;
void setup() {
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(blueLED, OUTPUT);
pinMode(buzzer, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
data = Serial.read();
switch(data) {
case 'r':
digitalWrite(redLED, HIGH);
break;
case 'g':
digitalWrite(greenLED, HIGH);
break;
case 'b':
digitalWrite(blueLED, HIGH);
break;
default:
digitalWrite(redLED, LOW);
digitalWrite(greenLED, LOW);
digitalWrite(blueLED, LOW);
break;
}
}
}
I then used the python library pySerial to write to the serial port . I run the following commads in an interactive Python session and they work perfectly (the LEDs turn on and off as expected):
from serial import Serial
arduino = Serial('/dev/ttyACM0');
arduino.baudrate = 9600;
arduino.write(b'rgb') # red, then green, then blue,
arduino.write(b'x') # turn them off
arduino.close()
However, when I put the above commands into a script and run the script python3 ./script.py, it does not work. The RX and TX pins flash but the LEDs do not glow. Is there any explanation for this?