【发布时间】:2019-07-19 23:12:30
【问题描述】:
我有一个 arduino,当我从 arduino 串行监视器发送数据时,它通过串行连接读取两个整数,它可以正常工作,但无论我做什么,当我发送使用 pySerial 来自 python 的相同数据,我一直在这个时间,却一无所获
我已经尝试将数据编码为 utf8,不同的编码会刷新输出缓冲区,并且已经阅读了太多其他类似的 stackoverflow Q&A 来计数
我在 Windows 10 中使用 python 3.7.1,但代码将不合时宜地在 Rpi 上运行
import os
import time
import serial
ser = serial.Serial('COM7', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=5)
print("writting")
time.sleep(0.5)
ser.write(b'4,5')
ser.write(b'\r\n')
time.sleep(0.5)
ser.flushOutput()
ser.close()
#include <SoftwareSerial.h>
byte buttonPin = 9;
const int pin_led = LED_BUILTIN; // Pin for indication LED
int sensorPin = A0;
int sensorValue = 0;
int remotePower = 0;
SoftwareSerial mySerial(11, 12); // RX, TX
void setup()
{
pinMode(pin_led, OUTPUT); // Set LED pin as output
Serial.begin(9600);
mySerial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
int oldremotePower = 0;
void loop()
{
// if there's any serial available, read it:
while (Serial.available() > 0) {
Serial.println("theres Data");
// look for the next valid integer in the incoming serial stream:
int mode = Serial.parseInt();
// do it again:
int action = Serial.parseInt();
// do it again:
//int blue = Serial.parseInt();
// look for the newline. That's the end of your sentence:
if (Serial.read() == '\n') {
// constrain the values to 0 - 255 and invert
// if you're using a common-cathode LED, just use "constrain(color, 0, 255);"
mode = constrain(mode, 1, 4);
action = constrain(action, 0, 100);
mySerial.print(mode);
mySerial.print(",");
mySerial.println(action);
}
}
oldremotePower = remotePower;
sensorValue = analogRead(sensorPin);
remotePower = map(sensorValue, 0, 1023, 1, 100);
if (oldremotePower != remotePower){
//Serial.println(oldremotePower);
//Serial.println(remotePower);
}
if (digitalRead(buttonPin) == LOW) {
mySerial.println(remotePower);
}
}
我从 arduino 串行监视器发送“1,100”,uno 以“theres Data”响应,并在软件串行上打印刚刚发送的值 这可行,但是当我尝试从我的 python 脚本发送“1,100\r”时,没有任何反应,脚本运行没有错误,uno 上的 Rx 指示灯闪烁,但软件串行端口上没有输出它一定是我的 python 串行有问题代码。
【问题讨论】:
-
实际上,我对您的通信结构不太满意,但是您是否尝试过删除
ser.flushOutput()?另外,删除sleep语句,因为它们是不必要的。 -
Arduino 在新的 USB 连接上重置 (
serial.Serial('COM7')。等待 2 秒,然后将内容发送到您的草图
标签: python serialization arduino pyserial