1.准备工作:
python环境:
安装python 环境,我目前使用的是pycharm2023.2.1 community Edition 版本
需要注意设置python解释器的版本及关联本地库,这样就不需要在新的工程中安装库文件了,(当然也有缺点,在另外新的开发环境下,需要重安装一次)
在设置中找到python 解释器,虚拟环境使用本地。
FTDI库:
我选择的是FTD2xx,安装命名为 :pip install ftds2xx;
Device driver
As standard, when an FTDI device is plugged into a Windows PC, the operating system loads the default Virtual Com Port driver, that can only handle asynchronous serial (RS232-type) protocols. However, we want to be a bit more adventurous, so need to substitute the ‘d2xx’ driver, available from the FTDI drivers page. A quick way to check which driver is active is to look at the Device Manager; if the FTDI part appears as a COM port, it is asynchronous-only.
Use ‘pip’ to install a Python library that will access the d2xx driver; there are several available (such as pyftdi, pylibftdi) but the only one that worked seamlessly with Python 2.7 and 3.x on my systems was the simplest: ftd2xx, which is just a CTYPES wrapper round the d2xx API
2.代码及操作--连接FTDI设备,并读设备信息
import sys, ftd2xx as ftd
d = ftd.open(0) # Open first FTDI device
print(d.getDeviceInfo())
print(hex(d.getDriverVersion()))
print(hex(d.getComPortNumber()))
执行结果为:
{'type': 8, 'id': 67330068, 'description': b'Single RS232-HS', 'serial': b''}
注意要连接上设备,否则会报错误:
Traceback (most recent call last):
File "F:\python_t\test_proj\main.py", line 37, in <module>
d = ftd.open(0)
^^^^^^^^^^^
File "F:\python_t\test_proj\venv\Lib\site-packages\ftd2xx\ftd2xx.py", line 268, in open
call_ft(_ft.FT_Open, dev, c.byref(h))
File "F:\python_t\test_proj\venv\Lib\site-packages\ftd2xx\ftd2xx.py", line 178, in call_ft
raise DeviceError(status)
ftd2xx.ftd2xx.DeviceError: DEVICE_NOT_FOUND
另外的设备打开方式:
def testopenEx(self):
dev0 = None
try:
devices = ftd2xx.listDevices()
if devices is None:
raise DeviceError("Device not found")
dev0_id = devices[0]
dev0 = ftd2xx.openEx(dev0_id)
self.assertIsInstance(dev0, ftd2xx.FTD2XX)
self.assertEqual(dev0.getDeviceInfo()["serial"], dev0_id)
except AssertionError:
raise
finally:
if dev0:
dev0.close()
3.代码操作-DO 输出3个方波信号:
(Bitbang mode: toggling an I/O pin)
import sys, ftd2xx as ftd
print("hello")
d = ftd.open(0)
print(d.getDeviceInfo())
print(hex(d.getDriverVersion()))
print(hex(d.getComPortNumber()))
OP = 0x01 # Bit mask for output D0
d.setBitMode(OP, 1) # Set pin as output, and async bitbang mode
d.write(str(OP)) # Set output high
d.write(str(0)) # Set output low
d.write(str(OP)) # Set output high
d.write(str(0)) # Set output low
d.write(str(OP)) # Set output high
d.write(str(0)) # Set output low