首页 > 解决方案 > 使用python通过usb端口将数据发送到esp32

问题描述

我的主要目标是通过 USB 端口将图片发送到我的 ESP32。所以首先我创建了一个 Arduino 项目,其中 esp32 可以从 USB 接收数据。

const byte numChars = 32;
char receivedChars[numChars];   // an array to store the received data

boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
    pinMode(2, OUTPUT);
}

void loop() {
    recvWithEndMarker();
    showNewData();
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;
   
    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.println(receivedChars);
        newData = false;
    }
}

当我使用 arduino 串行监视器发送数据时,它工作得很好。但是当我尝试用我的 python 程序发送数据时,它并没有真正起作用。这是python代码:

import serial


def sendData(data):
    ser = serial.Serial("COM4", 9600)
    ser.write(data.encode())


def main():
    data = input()
    sendData(data)
    ser = serial.Serial("COM4", 9600)
    while True:
        receiveddata = ser.readline()
        if len(receiveddata) > 0:
            print(receiveddata)
            print("\n")



if __name__ == '__main__':
    main()

正如大家在我发送一些文本后看到的那样,我开始观察 COM4 端口。因此,当我发送文本时,python 代码会收到“Arduino is ready”这句话,所以我认为 ESP32 在我发送文本后会重新启动。我对吗?我该如何解决这个问题?如果我想发送更大一点的数据,比如图片(它没有那么大,只有 128x128 大小的图片),我该怎么做?谢谢您的帮助。

编辑:我尝试将数据从我的计算机发送到 ESP32。该设备通过 USB 连接,使用 micro usb 电缆。当我使用 python 程序发送数据时,ESP32 设备没有收到任何内容。但是当我在 arduino 串行监视器中写一些文本时,ESP32 会立即接收数据。所以很明显我在我的python代码中做错了什么。

标签: pythonarduinoesp32

解决方案


推荐阅读