python - 使用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代码中做错了什么。
解决方案
推荐阅读
- reactjs - 如何配置“adb reverse”自动运行?
- ruby-on-rails - 为什么 Webpacker 4 不发出 CSS 文件?
- ios - 我正在尝试从 Document 目录访问视频,但出现错误“没有这样的文件或目录”
- java - 调用相同的模拟方法时如何返回不同的结果?
- python - 你如何计算二维张量的每一行的掩码平均值?
- javascript - 这个作业在 javascript 中做了什么?
- jquery - 选择动态内部元素,而不是静态容器
- sql - 从数据表中读取的 Powershell 脚本在找到值中的句号时出错
- report - 在没有命令行参数的 pytest 中自动生成 html 报告
- performance - 在 Common Lisp 中,函数和宏之间是否存在性能差异?