Im trying to talk to a arduino UNO over USB using a python script. However i can't get it to respond. If try to talk to it using the serial monitor in the arduino IDE it however does respond.
Can anyone help me out?
Python code:
import json
import time
from serial import Serial
startTime = time.time()
serialPort = Serial(port="COM10", baudrate=115200, timeout=1)
time.sleep(0.5)
serialPort.write(str('on').encode())
messageBytes = serialPort.read_until('\n')
messageString = messageBytes.decode('utf-8')
serialPort.close()
print("Reponse time:", (time.time() - startTime) * 1000)
print("String:", messageString)
Arduino code:
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(12, OUTPUT);
}
void loop() {
if (Serial.available() > 0) {
String messageData = Serial.readStringUntil("\n");
messageData.trim();
if(messageData=="on")
{
digitalWrite(12, HIGH);
}
if(messageData=="off")
{
digitalWrite(12, LOW);
}
Serial.println("succes");
}
}
On the line above the one you mentioned it writes to the arduino on the line you mentioned im waiting for the succes response seen in the arduino code.
Here is a variation on the Python code that uses a thread to monitor incoming serial data and transmits "on" "off" at 0.5 second intervals
import serial
import threading
from threading import *
from time import sleep
ser = serial.Serial("COM10", 115200)
event = threading.Event()
def my_thread():
while True:
if event.is_set():
break
try:
input_string = ser.readline().strip().decode("utf-8")
except UnicodeDecodeError as e:
print(e)
except serial.SerialException as e:
print(e)
if len(input_string) > 0:
print(input_string)
input_string=''
t1 = Thread(target=my_thread, daemon=True)
t1.start()
while True:
ser.write('on'.encode())
ser.write('\n'.encode())
sleep(0.5)
ser.write('off'.encode())
ser.write('\n'.encode())
sleep(0.5)
This is a variation of your arduino code that uses the methods laid out in Nick Gammon's article that echoes "on" "off" back to Python along with on off's effect on the arduino program (High or Low)