pyserial read
//python
import serial
port = serial.Serial('COM5',9600)
while( port.isOpen()):
comdata = int(input())
if(comdata == 1):
port.write(str.encode('1'))
elif(comdata == 2):
port.write(str.encode('2'))
elif (comdata == 3):
port.write(str.encode('3'))
elif (comdata == 4):
port.write(str.encode('4'))
elif (comdata == 5):
port.write(str.encode('5'))
elif (comdata == 6):
port.write(str.encode('6'))
elif (comdata == 7):
port.write(str.encode('7'))
elif (comdata == 8):
port.write(str.encode('8'))
else:
print('Invalid input!!!!')
// arduino
const int LED1 = 8;
const int LED2 = 9;
const int LED3 = 10;
const int LED4 = 11;
char comdata;
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(LED4, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
comdata =(Serial.read());
if (comdata == '1') {
Serial.println("LED1 is ON");
digitalWrite(LED1, HIGH);
}
else if (comdata == '2') {
Serial.println("LED1 is OFF");
digitalWrite(LED1, LOW);
}
else if (comdata == '3' ) {
Serial.println("LED2 is ON");
digitalWrite(LED2, HIGH);
}
else if (comdata == '4' ) {
Serial.println("LED2 is OFF");
digitalWrite(LED2, LOW);
}
else if (comdata == '5') {
Serial.println("LED3 is ON");
digitalWrite(LED3, HIGH);
}
else if (comdata == '6') {
Serial.println("LED3 is OFF");
digitalWrite(LED3, LOW);
}
else if (comdata == '7') {
Serial.println("LED4 is ON");
digitalWrite(LED4, HIGH);
}
else if (comdata == '8') {
Serial.println("LED4 is OFF");
digitalWrite(LED4, LOW);}
}
}
4
2
# https://pyserial.readthedocs.io/en/latest/pyserial_api.html
# pip install pyserial
import serial
if __name__ == "__main__":
with serial.Serial('COM10') as serial_port:
line = serial_port.readline()
Thank you!
2
0
Are there any code examples left?
New code examples in category Python
-
Python 2023-04-11 03:04:20
-
Python 2022-03-27 22:40:04 pycharm no module named
-
Python 2022-03-27 22:25:05 assign multiple variablesin one line
-
Python 2022-03-27 22:20:02 levenshtein distance
-
Python 2022-03-27 21:35:09 get text from url python last slash
-
Python 2022-03-27 21:30:30 df concatenate df
-
Python 2022-03-27 21:25:09 python odd or even
-
Python 2022-03-27 21:15:32 python include function from another file
-
Python 2022-03-27 21:10:01 color module python
-
Python 2022-03-27 21:00:27 python tkinter cursor types