当前位置:   article > 正文

python 操作FT232H——(1)准备工作与IO输出方波信号_ft232h编程

ft232h编程

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设备,并读设备信息

  1. import sys, ftd2xx as ftd
  2. d = ftd.open(0) # Open first FTDI device
  3. print(d.getDeviceInfo())
  4. print(hex(d.getDriverVersion()))
  5. 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

另外的设备打开方式:
  1. def testopenEx(self):
  2. dev0 = None
  3. try:
  4. devices = ftd2xx.listDevices()
  5. if devices is None:
  6. raise DeviceError("Device not found")
  7. dev0_id = devices[0]
  8. dev0 = ftd2xx.openEx(dev0_id)
  9. self.assertIsInstance(dev0, ftd2xx.FTD2XX)
  10. self.assertEqual(dev0.getDeviceInfo()["serial"], dev0_id)
  11. except AssertionError:
  12. raise
  13. finally:
  14. if dev0:
  15. dev0.close()

 3.代码操作-DO 输出3个方波信号:

(Bitbang mode: toggling an I/O pin)

  1. import sys, ftd2xx as ftd
  2. print("hello")
  3. d = ftd.open(0)
  4. print(d.getDeviceInfo())
  5. print(hex(d.getDriverVersion()))
  6. print(hex(d.getComPortNumber()))
  7. OP = 0x01 # Bit mask for output D0
  8. d.setBitMode(OP, 1) # Set pin as output, and async bitbang mode
  9. d.write(str(OP)) # Set output high
  10. d.write(str(0)) # Set output low
  11. d.write(str(OP)) # Set output high
  12. d.write(str(0)) # Set output low
  13. d.write(str(OP)) # Set output high
  14. d.write(str(0)) # Set output low

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/106465?site
推荐阅读
相关标签
  

闽ICP备14008679号