#**************************************************************
# Raspberry Pi 5 I2C Example
# Written for Design News
# Written by: Fred Eady
# Last Update: 08-20-2024
# Notes:
#**************************************************************
# SDA = GPIO 2
# SCK = GPIO 3
#**************************************************************
# PLACE 10K PULL UP RESISTORS TO 3V3 ON THE SDA AND SCK LINES.
# Run the SLAVE code before running this code. This code will
# send a command sequence of 0xAA and wait for a response.
# Then wait 5 seconds, send 0xBB and wait for a response.
# The user LED should illuminate for 5 seconds and then
# extinguish. The responses will contain the LED ON/OFF status.  
#**************************************************************

import smbus
import time

slaveAddr = 0x20

# Open the Pi 5 I2C Interface
bus = smbus.SMBus(1)

print("I2C Example..")
# Send command LED ON and wait for response
print("Sending LED ON Command..")
bus.write_byte(slaveAddr,0xAA)
time.sleep(0.0001)
responseON = bus.read_byte(slaveAddr)
if responseON == 0xBB:
    print("Response from NUCLEO-G031K8 -> LED is ON\r\n")
else:
    print("Unrecognized Response from NUCLEO=G031K8!\r\n")

print("Executing 5 second delay..\r\n")
time.sleep(5)

# Send command LED OFF and wait for response
print("Sending LED OFF Command..")
bus.write_byte(slaveAddr,0xCC)
time.sleep(0.0001)
responseOFF = bus.read_byte(slaveAddr)
if responseOFF == 0xDD:
    print("Response from NUCLEO-G031K8 -> LED is OFF\r\n")
else:
    print("Unrecognized Response from NUCLEO=G031K8!\r\n")
