First of all, thanks for stopping by to my post. I’m an amateur python writer, I’m writing an application to send I2C Commands to via USB-RS232 (Hardware B0CFK14PVS) to my PCF8574. I’ve struggle trying to send commands to the PCF8575 though B0CFK14PVS.
The few libraries I found to do this are basically for raspberry pi who use the smbus2 & smbus libraries but I haven’t been able to find a Windows Library.
appreciate your help on this.
Please see below my code:
import serial
import time
port = "COM1" # Change to the appropriate CH341SER COM Port
baud_rate = 115200
ser = serial.Serial(port, baud_rate)
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()
data_to_write = [0b00000000] # Example data
pcf8574_address = 0x20 # Change this to the address of your PCF8574 if different
i2c_write(pcf8574_address, data_to_write)
for _ in range(8):
data_to_write[0] += 1 # Increment the first (and only) byte in the list by one
print("Byte " + str(data_to_write))
i2c_write(pcf8574_address, data_to_write)
time.sleep(1) # Wait for 1 second between each transmission
ser.close()
The following code is the one I’ve using with a RaspBerry pi, however, I need to migrate from the Raspberry Pi to a Windows:
from bin.pcf8574 import PCF8574
i2c_port = 1 # SDA = Pin 2, SCL = Pin 3
addr = 0x20 # Address for Relay card if A0=A1=A2=0
i2c = SMBus(i2c_port)
coils = PCF8575(i2c, addr)
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):
if vector[i] == 1:
vector[i] = 0
else:
vector[i] = 1
vector = vector[::-1]
coils.port = 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)
Thanks for the help.
Francisco