cgi - PySerial:创建串行对象而不打开端口

标签 cgi arduino pyserial

我正在 Arduino 上运行一些代码,我有一个带有 slider 的网站,它使用 cgi 脚本将值传递给 Python。然后 python 脚本使用 pySerial 将值发送到控制电机的 Arduino。

计划是能够使用网站上的 slider 控制电机速度。

但是,每当我更改网站上的值时,我似乎都会遇到 Arduino 重置的问题,导调用机停止。有没有办法解决?我的Python代码如下。

#!/usr/bin/env python
import cgi
form=cgi.FieldStorage()

import json

ser = serial.Serial('dev/ttyACM0', 9600) 
#I think there should be a sleep here for 1.5 seconds
ser.write("%s\n" % (form["value"]))
ser.close()

print "Content-type: application/json"
print
print(json.JSONEncoder().encode({"status":"ok"}))

所以,假设我让电机以 50% 的速度运行,然后更改网站上的值,它会运行此脚本,该脚本执行 serial.Serial('dev/ttyACM0', 9600) 命令。这将打开重置 arduino 的端口,在传递新命令之前停止电机。

有没有办法将 ser.write("%s\n"% (form["value"])) 传递到 arduino 而无需重新打开端口?例如在 python session 之间保持端口打开?

如果没有的话,还有其他办法解决这个问题吗?

最佳答案

我相信重置是由于您正在使用的特定 Arduino 设备的硬件设计造成的。我建议改用 Arduino Micro 或 Leonardo 板。它们使用虚拟串行端口,并且不应在每次打开串行端口时重新启动草图。这是来自 Arduino 网站:

No reset when you open the serial port.

Unlike the Arduino Uno, the Leonardo and Micro won't restart your sketch when you open a serial port on the computer. That means you won't see serial data that's already been sent to the computer by the board, including, for example, most data sent in the setup() function.

Serial re-enumeration on reset.

Since the boards do not have a dedicated chip to handle serial communication, it means that the serial port is virtual -- it's a software routine, both on your operating system, and on the board itself. Just as your computer creates an instance of the serial port driver when you plug in any Arduino, the Leonardo/Micro creates a serial instance whenever it runs its bootloader. The board is an instance of USB's Connected Device Class (CDC) driver. This means that every time you reset the board, the USB serial connection will be broken and re-established. The board will disappear from the list of serial ports, and the list will re-enumerate. Any program that has an open serial connection to the Leonardo will lose its connection. This is in contrast to the Arduino Uno, with which you can reset the main processor (the ATmega328P) without closing the USB connection (which is maintained by the secondary ATmega8U2 or ATmega16U2 processor). This difference has implications for driver installation, uploading, and communication...

关于cgi - PySerial:创建串行对象而不打开端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18251153/

相关文章:

ssl - 使用 TLS 保护 arduino 到 mosquitto 的连接

python - 嗅探串口数据而不从缓冲区中删除数据

python - 如何在 Windows XP 上安装 pySerial

perl - 为什么 Perl CGI 模块使用连字符开始命名参数?

node.js - 为什么 Node SerialPort Readline 解析器不工作?

perl - 如何在 Perl 中关闭和重新打开 STDOUT?

php - 将数据从 Arduino 发布到网站

python - python中写入和监听同一个串口

python - 将 python 脚本作为 cgi apache 服务器运行

html - 如何使用Perl基于值的刻度为HTML形状创建颜色渐变