1
votes

I'm new to Arduino, and I'm trying to make a game. I'm sending the serial data with Python to the Arduino. I want to make the Arduino wait untill it recieves the serial data from Python.

My questions are:

  • Why isn't the Arduino program working with serial data from Python, but it works with data from Serial Monitor?
  • How can I make the program work with data from Python? (Wait untill serial data from Python, and then save the data.)

Arduino code:

int select;
void setup() {
  Serial.begin(9600);
  Serial.flush();
  while(!Serial.available()){
  }
  if(Serial.available()>0){
    select=Serial.read();
  }
}
void loop() {
  Serial.println(select);
  delay(500);

}

Python code:

import serial
ser=serial.Serial('COM4',9600)
ser.write(b'1235')
ser.close()

Solved the problem that I don't get the serial data, but a new problem occured:

The problem is that, if I get the serial data, my Arduino program jumps back to the while(!Serial.available()){} loop, and not goes to the void loop(){}.

2

2 Answers

0
votes

A new USB connection with ser=serial.Serial('COM4',9600) resets the Arduino. The data sent right after connection are lost because the Arduino boots.

0
votes

Like Juraj says that resets the Arduino you should add code to wait for it to come back up

import serial
ser=serial.Serial('COM4',9600)
sleep(.5)
if arduino.is_open == 1:
        print("open")
ser.write(b'1235')
ser.close()