Python在Windows下操作CH341DLL

 1 #! /usr/bin/env python
 2 #coding=utf-8
 3 import os
 4 import time
 5 from ctypes import *
 6 
 7 class USBI2C():
 8     ch341 = windll.LoadLibrary("CH341DLL.dll")
 9     def __init__(self, usb_dev = 0, i2c_dev = 0x5c):
10         self.usb_id   = usb_dev
11         self.dev_addr = i2c_dev
12         if USBI2C.ch341.CH341OpenDevice(self.usb_id) != -1:
13             USBI2C.ch341.CH341SetStream(self.usb_id, 0x82)
14             USBI2C.ch341.CH341CloseDevice(self.usb_id)
15         else:
16             print("USB CH341 Open Failed!")
17 
18     def read(self, addr):
19         if USBI2C.ch341.CH341OpenDevice(self.usb_id) != -1:
20             obuf = (c_byte * 2)()
21             ibuf = (c_byte * 1)()
22             obuf[0] = self.dev_addr
23             obuf[1] = addr
24             USBI2C.ch341.CH341StreamI2C(self.usb_id, 2, obuf, 1, ibuf)
25             USBI2C.ch341.CH341CloseDevice(self.usb_id)
26             return ibuf[0] & 0xff
27         else:
28             print("USB CH341 Open Failed!")
29             return 0
30 
31     def write(self, addr, dat):
32         if USBI2C.ch341.CH341OpenDevice(self.usb_id) != -1:
33             obuf = (c_byte * 3)()
34             ibuf = (c_byte * 1)()
35             obuf[0] = self.dev_addr
36             obuf[1] = addr
37             obuf[2] = dat & 0xff
38             USBI2C.ch341.CH341StreamI2C(self.usb_id, 3, obuf, 0, ibuf)
39             USBI2C.ch341.CH341CloseDevice(self.usb_id)
40         else:
41             print("USB CH341 Open Failed!")

 

posted @ 2018-05-11 15:54  BH5HSV  阅读(3896)  评论(0编辑  收藏  举报