树莓派Python控制16路数字I O扩展芯片PCA9655E例子
# 树莓派Python控制16路数字I/O扩展芯片PCA9655E例子
# 导入所需的库
from smbus2 import SMBus
from time import sleep
# 定义PCA9655E芯片地址和端口号
PCA_ADDRESS = 0x20
IODIRA = 0x00
IODIRB = 0x01
GPIOA = 0x12
GPIOB = 0x13
# 初始化SMBus对象和GPIO口方向
bus = SMBus(1)
bus.write_byte_data(PCA_ADDRESS, IODIRA, 0x00)
bus.write_byte_data(PCA_ADDRESS, IODIRB, 0x00)
# 关闭所有GPIO口
bus.write_byte_data(PCA_ADDRESS, GPIOA, 0x00)
bus.write_byte_data(PCA_ADDRESS, GPIOB, 0x00)
# 定义设置GPIO口状态的方法
def set_gpio(index, status):
if index < 8:
reg = GPIOA
shift = index
else:
reg = GPIOB
shift = index - 8
value = bus.read_byte_data(PCA_ADDRESS, reg)
if status:
value |= 1 << shift
else:
value &= ~(1 << shift)
bus.write_byte_data(PCA_ADDRESS, reg, value)
# 设置GPIO口状态
set_gpio(0, True) # 打开GPIO口0
sleep(1)
set_gpio(0, False) # 关闭GPIO口0
# 关闭SMBus对象
bus.close()
下载地址
用户评论