0

我正在尝试将串行数据从 NodeMCU 发送到 Arduino。我使用 MicroPython 进行编程。以及Serial.read在 Arduino 上。我可以成功发送和接收。但问题是 NodeMCU 发送数据以及不需要的数字。Arduino 接收数据和数字。例如,如果我发送“ Hello ”,它会发送为“ Hello5 ”。我知道这个数字只不过是字符串中字母的数量。我怎样才能删除这个?

NodeMCU 上的 MicroPython:

import os
import machine
from machine import UART
uart = UART(0)
import time
while True:
    uart.write('1')

Arduino程序:

String received;
String msg;
void setup() {
  Serial.begin(115200);
  attachInterrupt(0, light, FALLING);//When arduino Pin 2 is FALLING from   HIGH to LOW, run light procedure!
}

void light() {
  Serial.println(msg);
}

void loop()
{
   if (Serial.available() > 0){ 
    received = Serial.readStringUntil('\n');
    msg = received;
   }
}
4

1 回答 1

0

我刚刚检查了 microPython 的 UART(http://docs.micropython.org/en/latest/wipy/library/machine.UART.html)和 Arduino 的串行(https://www.arduino.cc/en/Reference/Serial ),并且您似乎缺少 UART 的一条初始化行。UART 文档指出它设置的默认波特率为 9600,而您期望串行接收器上的波特率为 115200。我相信在每一侧设置不同的波特率会产生未定义的行为。

在您的 python 代码中,您可以在 uart = UART(0) 调用之后尝试 uart.init(115200) 吗(其余的默认值似乎与串行对接收器的期望相同)?

此外,Serial 文档说,如果它找不到您在 readStringUntil() 中定义的字符,那么它将尝试直到超时。所以我猜你的函数调用超时,因为它不会在流中找到结束行('\n'),因为你没有注入任何东西。

此外,虽然您正在使用的功能的帮助文档没有说明这样的事情,但如果您真的总是将字符数作为接收器的第一个字符,那么尝试使用它可能是值得的. 我想知道您是否可以先尝试获取该数字,然后再读取那么多字符(在 Arduino 接收器站点)。这是一些我希望可以帮助的代码(恐怕我没有尝试使用它):

#include <string.h>
char buffer[256];  // buffer to use while reading the Serial
memset(buffer, (char)0, 256);  // reset the buffer area to all zeros

void loop()
{
   if (Serial.available() > 0){ 
    int count = Serial.read();  // the first byte that shows the num of chars to read after, assuming that this is a 'byte' - which means we can have max 256 chars in the stream
    Serial.readBytes(buffer, count);
    msg = String(buffer);
   }
}
于 2017-05-13T03:50:38.097 回答