Today I'm going to show you guys how to get your computer to communicate with and arduino through a serial port using python. I'm using an clone of an arduino mega but this should work with any arduino compatible boards.
If you are having problems with the communications things you should try:
-make sure everything is plunged in correctly -make sure thee Com port and baud rate are the same
-make sure no other program is using the same COM port
I did not make this python module and you can find how to download the module by following this link. https://pypi.org/project/pyserial/
software I used to make/edit this video
-open camera
-python
-arduino
-free cam
-tupitube
-shotcut
Arduino: code you can just copy and paste this code into your own projects:
String incomingByte ;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
}void loop() {
if (Serial.available() > 0) {
incomingByte = Serial.readStringUntil('\n');
if (incomingByte == "on") {
digitalWrite(LED_BUILTIN, HIGH);
Serial.write("Led on");
}
else if (incomingByte == "off") {
digitalWrite(LED_BUILTIN, LOW);
Serial.write("Led off");
}
else{
Serial.write("invald input");
}
}
}
Python: code you can just copy and paste this code into your own projects:
import serial
import time
serialcomm = serial.Serial('COM7', 9600)
serialcomm.timeout = 1
while True:
i = input("Enter Input: ").strip()
if i == "Done":
print('finished')
break
serialcomm.write(i.encode())
time.sleep(0.5)
print(serialcomm.readline().decode('ascii'))
serialcomm.close()