Arduino/Python串口通讯

Arduino/Python Serial communication

我想通过串行输出将数据从 python 发送到 May Arduino Mega。当我 运行 Python 脚本时,Arduino 的 RX Led 闪烁。然而,Serial.available() = false。这只是一个示例代码。真正的项目是为模拟赛车游戏构建一个速度计(使用 UDP 数据)。知道为什么它不起作用吗?

代码如下:

Python:

import time
import serial
port = "COM3"
Arduino = serial.Serial(port ,9600, timeout=1);

i = 0
while i<= 9999 :
    time.sleep(1/10)
    i+=1
    print(i)
    Arduino.write(i)

Arduino:

#include <Arduino.h>
#include <TM1637Display.h>

#define CLK 2
#define DIO 3
int i=0;
int Number;
TM1637Display display(CLK, DIO);
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  display.setBrightness(0x0f);
  display.showNumberDec(9999);
  delay(3000);
}

void loop() { 
   Number= Serial.read();
  
  if (Serial.available()>0){
    display.setBrightness(0x0f);
    display.showNumberDec(Number);
  }
  if (Serial.available() == false){
    display.setBrightness(0x0f);
    display.showNumberDec(0000);
  }
    
}

这是它的工作原理。非常感谢来自 reddit 的 csongoose 帮助了我很多。也感谢您对此的所有答复。 Python:

import time
import serial
port = "COM3"
Arduino = serial.Serial(port ,9600, timeout=1);

i = 0
while i<= 9999 :
    time.sleep(1)
    i+=1
    print(i)
    #converts int i to string b
    b = "%s" %i
    Arduino.write(bytes(b, 'utf-8'))
    #the Arduino waits for this and can seperate the numbers 
    Arduino.write(b'\n')

Arduino:

#include <Arduino.h>
#include <TM1637Display.h>

#define CLK 2
#define DIO 3
#define D1 5
#define D2 7

int Number;
String b;
//i am using a 7-digit display to show the numbers
TM1637Display display(CLK, DIO);
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(D1 ,OUTPUT);
  pinMode(D2 ,OUTPUT);
  Serial.begin(9600);
}

void loop() { 
  if (Serial.available()>0){
    //looks for new numbers, which are sperated with '\n'
    b = Serial.readStringUntil('\n');
    //converts string b to integer Number
    Number = b.toInt();
    display.setBrightness(0x0f);
    display.showNumberDec(Number);
    //delay equals the same rate as python sends data
    delay(1000);
  
  }
  //this indicates if the data is available and if the Arduino has rebooted
  //you need to wait for it and then start your Python stream
  if (Serial.available() == 0){
    digitalWrite( D1, HIGH);}
    else digitalWrite(D1, LOW);

  if (Number != 0){
    digitalWrite( D2, HIGH);}
    else digitalWrite(D2, LOW);
    
}