Arduino only responds to serial monitor not python

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");
    
    
  }
}

I think you will get better responses if you write to the Arduino rather than reading from it, as you are also reading in the Arduino code.

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.

Take a look at this link which is an article created by Nick Gammon Gammon Forum : Electronics : Microprocessors : How to process incoming serial data without blocking

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)

const unsigned int MAX_MESSAGE_LENGTH = 20;
static char message[MAX_MESSAGE_LENGTH];
static unsigned int message_pos = 0;


void setup(){
Serial.begin(115200);
}
 
void loop()
   {
   while (Serial.available() > 0)
   {                                                                                      
   char inByte = Serial.read();

   if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )
   {                                                                                      
    message[message_pos] = inByte;
    message_pos++;
   }                                                                                        
   else
   {    
   message[message_pos] = '\0';
   Serial.println(message) ;                                                                    
   message_pos = 0;
    if (strcmp(message,"on")==0)
   {
   Serial.println("High") ;                                                                                  
   }
   else if (strcmp(message,"off")==0)
   {
   Serial.println("Low") ; 
   }
   }                                                                                       
   } 
   }

That is not a very long delay.

Does the line before that send a '\n'?

PS
Remember that Arduinos that don't use native USB go through a reset cycle when you open the serial port.

it turns out it was just printing the \n that worked

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.