python 使用python将串口引脚设置为高电平
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2438848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set serial port pin high using python
提问by morph
Is it possible to set one pin of the serial port continuously high using python (or C)? If yes, how?
是否可以使用python(或C)将串行端口的一个引脚连续设置为高电平?如果是,如何?
回答by Alejandro
Using the pyserial methods setRTS(level=True)
and setDTR(level=True)
you can control the RTS and DTR lines at will. For instance, the following code will toggle the RTS pin of the first serial port. (See the pyserial documentation for the details).
使用pyserial方法setRTS(level=True)
,setDTR(level=True)
你可以随意控制RTS和DTR线路。例如,以下代码将切换第一个串行端口的 RTS 引脚。(有关详细信息,请参阅 pyserial 文档)。
import time
import serial
ser = serial.Serial(0)
ser.setRTS(False)
time.sleep(0.5)
ser.setRTS(True)
time.sleep(0.5)
ser.setRTS(False)
回答by mtrw
If you open the port, the Tx line should go to the voltage high state, and if you never send data it should stay in that state (see here). I've never actually tried this though. You might find you need to enable one of the control lines instead, like CTR.
如果您打开端口,Tx 线应进入电压高状态,如果您从不发送数据,它应保持该状态(请参阅此处)。我从来没有真正尝试过这个。您可能会发现需要启用控制线之一,例如 CTR。
As for software, TheMachineCharmer's suggestion of pySerial is the most platform independent way of doing it. If you're on Windows, the Win32 API calls are summarized here. Look for CreateFile
and (if you need to set control lines) GetCommState
and SetCommState
. Note that the filename you pass to CreateFile
should look like "\\\\.\\COM1"
. The .NET way of doing is is summarized here. You'll need to construct a SerialPort
object, then access its properties to set control lines.
至于软件,TheMachineCharmer对 pySerial 的建议是最独立于平台的方式。如果您使用的是 Windows,则此处汇总了 Win32 API 调用。寻找CreateFile
和(如果您需要设置控制线)GetCommState
和SetCommState
。请注意,您传递给的文件名CreateFile
应类似于"\\\\.\\COM1"
. 这里总结了.NET 的做法。您需要构造一个SerialPort
对象,然后访问其属性以设置控制线。