我需要使用Python控制CP2108芯片Latch。 C#示例代码(来自制造商示例源代码):
comString.Format(_T("\\\\.\\COM%d"), m_COMPort.GetCurSel() + 1);
//Open a handle the the device specified
HANDLE hDevice = CreateFile(comString,
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
0);
//If the handle is valid, then it opened
if (hDevice != INVALID_HANDLE_VALUE)
{
WORD latch = 0;
//Read the latch
if (CP210xRT_ReadLatch(hDevice, &latch) != CP210x_SUCCESS)
{.....}
}
挖掘Python代码:
import win32file
import win32con
import ctypes
cp201x_dll = ctypes.windll.LoadLibrary('CP210xRuntime.dll')
lp_latch = ctypes.c_int(0)
h_device = win32file.CreateFile(r'\\.\\COM37',
win32con.GENERIC_READ|win32con.GENERIC_WRITE,
0,
None,
win32con.OPEN_EXISTING,
win32con.FILE_ATTRIBUTE_NORMAL|win32con.FILE_FLAG_OVERLAPPED,
None)
cp201x_dll.CP210xRT_ReadLatch(h_device, ctypes.byref(lp_latch))
print 'VALUE: {}'.format(lp_latch)
但是我收到了一个错误:
Traceback (most recent call last):
File "D:/Dropbox/ElgsisTests/src/lib/cp210x/practise.py", line 27, in <module>
cp201x_dll.CP210xRT_ReadLatch(h_device, ctypes.byref(lp_latch))
ctypes.ArgumentError: argument 1: <type 'exceptions.TypeError'>: Don't know how to convert parameter 1
我试图传递ctypes整数,但我的Latch值为零。我想这是因为这个CP210xRuntime.dll需要有关COM端口的信息。
来自API手册:
3.1. CP210xRT_ReadLatch
Description:
Gets the current port latch value from the device.
Supported Devices: CP2103, CP2104, CP2105, CP2108
Location: CP210x Runtime DLL
Prototype: CP210x_STATUS CP210xRT_ReadLatch(HANDLE Handle, LPWORD Latch)
Parameters: 1. Handle—Handle to the Com port returned by CreateFile().
2. Latch—Pointer for 4-byte return GPIO latch value [Logic High = 1, Logic Low = 0].
Return Value: CP210x_STATUS = CP210x_SUCCESS,
CP210x_INVALID_HANDLE,
CP210x_DEVICE_IO_FAILED
CP210x_FUNCTION_NOT_SUPPORTED
所以也许有人知道如何正确传递它?
答案 0 :(得分:1)
用以下代码更新Python代码:
handle = ctypes.c_long(int(h_device))
status = cp201x_dll.CP210xRT_ReadLatch(handle, ctypes.byref(lp_latch))
print 'STATUS: {}'.format(status)
print 'VALUE: {}'.format(lp_latch)
并且确实收到了正确的值