Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python code for digital inputs
#1
Hi,

Is there a python code example for reading the digital inputs on the kincony server 16?

Thanks in advance,
Pieter
Reply
#2
Code:
import smbus2
import time

# I2C device address
I2C_ADDR = 0x20

# MCP23017 register addresses
IODIRA = 0x00  # Port A direction register (1 = input, 0 = output)
IODIRB = 0x01  # Port B direction register
IPOLA = 0x02   # Port A polarity inversion register
IPOLB = 0x03   # Port B polarity inversion register
GPIOA = 0x12   # Port A data register
GPIOB = 0x13   # Port B data register

# Initialize I2C bus
bus = smbus2.SMBus(1)  # Raspberry Pi default I2C-1

# Configure MCP23017 as input and enable polarity inversion
bus.write_byte_data(I2C_ADDR, IODIRA, 0xFF)  # Set all Port A pins as input
bus.write_byte_data(I2C_ADDR, IODIRB, 0xFF)  # Set all Port B pins as input
bus.write_byte_data(I2C_ADDR, IPOLA, 0xFF)  # Invert polarity for Port A (1->0, 0->1)
bus.write_byte_data(I2C_ADDR, IPOLB, 0xFF)  # Invert polarity for Port B

# Define pin names
pins = [
    "Button_1", "Button_2", "Button_3", "Button_4",
    "Button_5", "Button_6", "Button_7", "Button_8",
    "Button_9", "Button_10", "Button_11", "Button_12",
    "Button_13", "Button_14", "Button_15", "Button_16"
]

def read_inputs():
    """Read GPIOA and GPIOB from MCP23017 and parse button states"""
    gpio_a = bus.read_byte_data(I2C_ADDR, GPIOA)  # Read Port A
    gpio_b = bus.read_byte_data(I2C_ADDR, GPIOB)  # Read Port B
   
    # Parse button states
    states = [(gpio_a >> i) & 1 for i in range(8)] + [(gpio_b >> i) & 1 for i in range(8)]
   
    return {pins[i]: states[i] for i in range(16)}

# Main loop: Read and display button states
try:
    while True:
        button_states = read_inputs()
        print("Button States:", button_states)
        time.sleep(0.5)
except KeyboardInterrupt:
    print("\nProgram terminated")
    bus.close()
Reply
#3
(02-09-2025, 07:40 PM)pietpoerrie Wrote: Hi,
Thank you for the example.  Is it possible to combine 16DI and 16 DO (relays) in the same python program?
Do you have an example code for this?

Thanks in advance,
Pieter
Reply


Forum Jump:


Users browsing this thread:
2 Guest(s)