note:
- After open the port, the Arduino will reset. So I insert delay for 3 seconds after serial.Serial('/dev/ttyACM1', 9600).
- In my board, 115200 seem not too stable. I modify the baud rate to 9600.
Python code:
import serial import time # assign your port and speed ser = serial.Serial('/dev/ttyACM1', 9600) print("Reset Arduino") time.sleep(3) ser.write(bytes('L', 'UTF-8')) print('Enter 1 to Turn Arduino LED ON') print('Enter 0 to Turn Arduino LED OFF') print('Enter Q/q to quit:') char_in = '' print(char_in) while char_in not in ['Q', 'q']: char_in = input() if char_in == '0': print("LED OFF") ser.write(bytes('L', 'UTF-8')) if char_in == '1': print("LED ON") ser.write(bytes('H', 'UTF-8'))
Arduino code:
int led = 13; int incomingByte = 0; void setup() { pinMode(led, OUTPUT); //Setup Serial Port with baud rate of 9600 Serial.begin(9600); Serial.println("Press H to turn LED ON"); Serial.println("Press L to turn LED OFF"); } void loop() { if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); if(incomingByte == 'H'){ digitalWrite(led, HIGH); Serial.println("LED ON"); }else if(incomingByte == 'L'){ digitalWrite(led, LOW); Serial.println("LED OFF"); }else{ Serial.println("invalid!"); } } }
Communicate with Arduino with Python programmatically |
Next:
- Control Arduino LED using Python with GUI
No comments:
Post a Comment