How do I make my Arduino r4 wifi work with my python script?

Hi! I am trying to get these scripts to co-operate with each other using UART, but both of my scripts seem to think otherwise, My Arduino is trying to add the received data from python by one, and also displaying the incremented value onto python.
anyways, here is my code:
Arduino,

int x;

void setup() {
    pinMode(12, OUTPUT);
    Serial.begin(115200);
    Serial.setTimeout(1000); // Set a timeout of 1 second
}

void loop() {
    if (Serial.available()) {
        x = Serial.readString().toInt();
        Serial.print("Received value: ");
        Serial.println(x);
        x++;
        Serial.print("Incremented value: ");
        Serial.println(x);
        
        // Blink the LED x times
        for(int i = 0; i < x; i++) {
            digitalWrite(12, HIGH);
            delay(2000);
            digitalWrite(12, LOW);
            delay(2000); // Wait for 2 seconds before turning on again
        }
    }
}

import serial
import time

# Connect to the Arduino (adjust the port name as needed)
arduino = serial.Serial(port='COM5', baudrate=115200, timeout=.1)

def write_read(x):
    arduino.write(bytes(x, 'utf-8'))
    time.sleep(0.05)
    data = arduino.readline().decode().strip()  # decode and strip newline characters
    return data

while True:
    num = input("Enter a number: ")  # Taking input from the user
    time.sleep(1)
    value = write_read(num)
    print("Received value from Arduino:", value)  # Printing the received value

Since

was utterly unhelpful in telling anyone what problem you were encountering, I decided to load your sketch up onto an Uno R3 and run it.

First tested it with a serial terminal, and it worked fine. Responded with the expected text, and blinked the LED.

Fine, the problem must be in the python script. I changed the serial port to match my system, loaded it, and lo and behold, it worked fine too. Typed in a number, got text from the Arduino, and the LED blinked.

So, no problem. Over to you.

1 Like

My python script first displays blank and then I press enter it displays the received value after I press enter again It displays the incremented value, The fourth time, The light doesn't work

Oh, and I also dug up an Uno R4 WiFi to run the sketch on. Identical results. Works just fine.

I would suggest that you narrow down which side of things is not working for you. Do as I did to start, and have the Arduino communicate not with your python code, but a terminal program. That way you stand some chance of being able to figure out which side is giving you trouble.

Which terminal program should I use?

Whichever one you like. Perhaps even the serial monitor in the Arduino IDE that you may be using.

The led doesn't blink this time.

As I've already said, your sketch and python code work just fine for me. So I don't think I have anything more I can add here. Good luck with your project.