Arduino等待来自Python的串行数据

2024-05-04 23:50:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的,我想做一个游戏。我用Python把串行数据发送到Arduino。我想让Arduino等待,直到它从Python接收到串行数据。你知道吗

我的问题是:

  • 为什么Arduino程序不能处理来自Python的串行数据,但可以处理来自串行监视器的数据?你知道吗
  • 如何使程序使用Python中的数据?(等待Python中的串行数据,然后保存数据。)

Arduino代码:

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代码:

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(){}.


Tags: the数据代码程序loopifserialselect
2条回答

就像Juraj所说的重置Arduino,你应该添加代码等待它恢复

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

使用ser=serial.Serial('COM4',9600)的新USB连接重置Arduino。由于Arduino启动,连接后立即发送的数据丢失。你知道吗

相关问题 更多 >