【问题标题】:ESP32 Hardware Serial - only write 1 byte at a timeESP32 硬件串行 - 一次只写入 1 个字节
【发布时间】:2020-04-20 07:52:18
【问题描述】:

我正在使用

Serial2.begin(9600, SERIAL_8N1, 15, 14,true);
Serial2.write(b,100);

从 esp32 将缓冲区写入串行

但由于某种原因它没有传输完整的缓冲区? 而是一次传输一个字节。

有人对我如何传输完整缓冲区而不是一次传输 1 个字节有建议吗?

代码示例:

#include <HardwareSerial.h>

void setup() {
    Serial.begin(9600);
    Serial2.begin(9600, SERIAL_8N1, 15, 14,true); 
}

uint8_t buf[1000];

uint8_t* genBuffer(const char* txt, int* bufSZ)
{
    int index = 0;
    int i = 0;

    buf[index++] = 0x00;
    buf[index++] = 0x00;
    buf[index++] = 0x00;
    buf[index++] = 0x00;
    buf[index++] = 0x00;
    buf[index++] = 0x01;
    buf[index++] = 0x46;
    buf[index++] = 0x46;
    buf[index++] = 0x30;
    buf[index++] = 0x30;
    buf[index++] = 0x02;
    buf[index++] = 0x41;
    buf[index++] = 0x41;
    buf[index++] = 0x43;
    buf[index++] = 0x32;

    for (i = 0; txt[i]; i++) {
        buf[index++] = txt[i];
    }

    *bufSZ = index;

    return buf;
}

void loop()
{
    int sz = 0;
    uint8_t* b = genBuffer("test", &sz);     
    Serial.println(sz); 
    Serial2.write(b,sz);

    for (int i = 0; i < sz; i++) {  
        Serial.print(" ");
        Serial.print(b[i], HEX);
    }
    Serial.println();
    delay(5000);
    // put your main code here, to run repeatedly:
}

【问题讨论】:

  • 你的缓冲区是多少?这是 C++ 顺便说一句,不是 C
  • UART 设置的波特率是多少,您期望的传输速度是多少? “一次一个字节”是你发送缓冲区的方式,当然......
  • 00 00 00 00 00 01 46 46 30 30 02 41 41 43 32 30 37 46 32 30 30 36 30 31 30....@Piglet
  • 请提供minimal reproducible example,而不是两行代码
  • 9600baud 我的意思是在串行监视器/总线狗中,它一次显示 1 个长度为 1 的字节。使用 USB/串行适配器,此缓冲区显示同一传输中的所有字节,长度等。60 @unwind

标签: arduino serial-port esp8266 esp32 arduino-c++


【解决方案1】:

定义为Serial.write(buf,len)

Serial: serial port object. See the list of available serial ports for each board on the Serial main page.
val: a value to send as a single byte.
str: a string to send as a series of bytes.
buf: an array to send as a series of bytes.
len: the number of bytes to be sent from the array.

你必须定义例如

char b[] = "Two hundred and fiftyfive character have to be in here tomake theexample work ....";

然后

 Serial2.write(b,100);

会起作用,或者你定义一个固定长度的缓冲区

 char b[256] = {'\0'};

然后你用itoa, utoa, ftoa 填充值(转换为字符串)到它用strcpystrcat 比你必须确保至少100 个字符在缓冲区中写入。如果 b 是 int 或类似的命令,则该命令会触发 ,100 并表现得像 Serial.write(val) -> 值作为单个字节发送!
编辑答案是在 OP 发布之前给出的代码,但由于 buf 被定义为全局数组,因此无需从函数中返回它
您将其定义为 uint8
如果您将 b 打印到串行,您会看到奇怪的字符(可能是终止符和一些内存内容)编者应该做什么?由

uint8_t* b

指针值被写入串行而不是我猜从那个指针开始的缓冲区 - 那么你期望什么?请参阅文档中的上述用法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 2021-04-25
    • 2017-07-27
    相关资源
    最近更新 更多