【问题标题】:Difficulty Sending Numbers from Arduino to Python via Serial Data难以通过串行数据将数字从 Arduino 发送到 Python
【发布时间】:2019-02-23 05:05:20
【问题描述】:

我正在尝试编写一个程序,它将串行数据从 Arduino 发送到在树莓派上运行的 Python 程序。我在发送大于 9 的数字时遇到了问题。当我发送大于 9 的数字时,python 程序只解释数字中的第一个数字。 5 代表 563,9 代表 9135,4 代表 43,等等...任何解决此问题的帮助将不胜感激。谢谢。

Arduino 代码:

int First=2;
int buttonState=0;
int num = 0;

void setup()
{
 Serial.begin(9600);
 pinMode(First, INPUT);  

}

void loop()
{
 int buttonState=digitalRead(First);

 if(buttonState==HIGH&&(num==1))
 {
   Serial.print(549);
   num--;
   delay(500);
   buttonState = 0;
 }
 if(buttonState==HIGH&&(num==0))
 {
   Serial.print(74);
   num++;
   delay(500);
   buttonState = 0;
 }
 if(buttonState==LOW)
 {
   //do nothing
 }
}

Python 代码:

import numpy
import cv2, glob
import sys
import os
import keyboard
import serial

from pynput.keyboard import Key, Controller
import time

keyboard = Controller()
ser=serial.Serial('/dev/ttyUSB3',9600)

while True:
    command = ser.read()
    if command:
        ser.flushInput()
        print("new command:", command)
        if(int(command) == 74):
            time.sleep(2)
            keyboard.press(Key.space)
            keyboard.release(Key.space)

基本上,问题是当我点击按钮时,Arduino会发送74,但python程序只能识别为7。结果,只有7输出到屏幕上。有没有办法让python程序识别整个数字,而不仅仅是第一个数字?

【问题讨论】:

  • 您发送的不是数字 74,而是文本“7459474594...”被一些延迟打断。
  • 他在if语句中将其转换为整数int(command)

标签: python serialization arduino raspberry-pi byte


【解决方案1】:

stream.read() 只返回传入数据的第一个字节,即本例中的 char。您应该改用stream.readBytes()stream.readString()。他们读取数据直到到达终点或函数超时。这是我用来读取多位整数的代码示例:

int getInt()
{
  // Create an empty string
  String val = "";

  // While the string is empty...
  while(val == "")
  {
    // ... wait for the user to enter a string
    val = Serial.readString();
  }

  // Return the string converted to an integer
  return val.toInt();  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多