Python is not reading the information from Arduino

Hello my project sends data from the Arduino to Python so that python does an action when a certain value has been read from the serial.

The Arduino sends a Serial.println("s");

Then Python interprets it with

import serial
import time
import pyautogui
import keyboard
from pynput import mouse
from pynput.mouse import Button, Controller


arduino = serial.Serial(port='COM3', baudrate=9600, timeout=.01)

def issensed():
    data = arduino.readline()
    return data


while (True):
    value = str(issensed())
    if value == "s":
       pyautogui.typewrite("hi")
    else:
        pyautogui.typewrite("no")

However hi is not being written and no is not being written.

Any help would be much appreciated

post your full arduino code

1 Like

Arduino Code:

const int sensor = A0;
int count = 0;
void setup() {
  Serial.begin(9600);
  
}

void loop() {
  int sensorVal = analogRead(sensor);
  if(sensorVal > 2){
    count++;
    if(count % 7 == 0){
      Serial.println("s");
    }
    delay(400);
  }
  
}

Try something simple first:

Arduino code:

void setup() {
  Serial.begin(115200);
  Serial.println("Arduino boot");
}

void loop() {
  Serial.println("s");
  delay(1000);
}

Python Code:

#!/usr/bin/env python3
import serial
import time
arduino = serial.Serial(port='COM3', baudrate=115200, timeout=.1)
def arduinoRead():
    data = arduino.readline()
    return data

while True:
    value = arduinoRead()
    if value != b'':
        print(value)

of course make sure COM3 is where you arduino is connected and don't open the IDE serial monitor

you should see in the Python terminal

b'Arduino boot\r\n'
b's\r\n'
b's\r\n'
b's\r\n'
b's\r\n'
b's\r\n'

==> note that you get the \r\n from the println() in the resulting data so this is to be taken into account if you want to do some testing against that string

Yeah that works but the original doesn't work.

yes, as I wrote you have the "\r\n" in your result, so your compare is wrong

#!/usr/bin/env python3
import serial
import time
arduino = serial.Serial(port='COM3', baudrate=115200, timeout=.1)
def arduinoRead():
    data = arduino.readline()
    return data

while True:
    value = arduinoRead()
    if value != b'':
        print(value) # printing the value
    if value == b's\r\n':
            print("this is what I expected")

if you run this, you should now see

b'Arduino boot\r\n'
b's\r\n'
this is what I expected
b's\r\n'
this is what I expected
b's\r\n'
this is what I expected
b's\r\n'
this is what I expected
b's\r\n'
this is what I expected
b's\r\n'
this is what I expected
b's\r\n'
this is what I expected