我正在编写一个应用程序,通过 USB-RS232(硬件 B0CFK14PVS)将 I2C 命令发送到我的 PCF8574。我一直在尝试通过 B0CFK14PVS 向 PCF8575 发送命令。
我发现执行此操作的少数库基本上适用于使用 smbus2 和 smbus 库的 Raspberry Pi/Linux,但我一直无法找到 Windows 库。
我已经编写了以下代码,但我仍然无法通过 I²C 与我的继电器板设备通信。我知道我的硬件可以正常工作,因为我使用 Raspberry Pi 2 并且可以正常工作。但我现在需要将其迁移到 Windows 中。
请参阅下面我的代码:
import serial
import time
port = "COM1" # Change to the appropriate CH341SER COM Port
baud_rate = 115200
ser = serial.Serial(port, baud_rate)
pcf8574_address = 0x20 # Change this to the address of your PCF8574 if different
def i2c_start():
ser.write(b'\x02')
def i2c_stop():
ser.write(b'\x03')
def i2c_write_byte(byte):
ser.write(byte.to_bytes(1, byteorder='big'))
def i2c_write(address, data):
i2c_start()
i2c_write_byte(address << 1)
for byte in data:
i2c_write_byte(byte)
i2c_stop()
def write_coils(vector):
"""
Function to write all coils in relay card. Receive an integer vector with output values
"""
try:
for i in range(0, 8):
print ("i " + str (1))
if vector[i] == 1:
print ("vector" + str(vector))
vector[i] = 0
else:
vector[i] = 1
vector = vector[::-1]
#coils.port = vector
i2c_write(pcf8574_address, vector)
except Exception as e:
print("Error in write_coils:", e)
while True:
write_coils([1,0,1,0,1,0,1,0])
time.sleep(0.5)
write_coils([0,1,0,1,0,1,0,1])
time.sleep(0.5)
您的代码似乎执行正确,但比需要的复杂得多。以下是一个简化版本,它生成与原始代码相同的串行端口输出:
import serial
import time
port = "COM1" # Change to the appropriate CH341SER COM Port
baud_rate = 115200
ser = serial.Serial(port, baud_rate)
pcf8574_address = 0x20 # Change this to the address of your PCF8574 if different
def write_coils(data):
addr = pcf8574_address << 1
ser.write([0x02]) # Start byte
ser.write([addr])
ser.write(data)
ser.write([0x03]) # Stop byte
while True:
write_coils([1,0,1,0,1,0,1,0])
time.sleep(0.5)
write_coils([0,1,0,1,0,1,0,1])
time.sleep(0.5)
第一次调用
write_coils()
,即write_coils([1,0,1,0,1,0,1,0])
的结果是将以下内容发送到串口:
02 40 01 00 01 00 01 00 01 00 03
通过使用 Arduino 设备从端口读取数据,我已经验证了您的原始代码和我的较短版本都是这种情况。如果这不是您想要发送到您的设备的内容,那么相应地编辑我的代码应该是一件非常简单的事情。