CCCPaste

# I2C Expander rev_01

/********* Pleasedontcode.com **********

	Pleasedontcode thanks you for automatic code generation! Enjoy your code!

	- Terms and Conditions:
	You have a non-exclusive, revocable, worldwide, royalty-free license
	for personal and commercial use. Attribution is optional; modifications
	are allowed, but you're responsible for code maintenance. We're not
	liable for any loss or damage. For full terms,
	please visit pleasedontcode.com/termsandconditions.

	- Project: # I2C Expander
	- Source Code NOT compiled for: ESP8266 NodeMCU V1.0
	- Source Code created on: 2026-02-05 14:51:45

********* Pleasedontcode.com **********/

/****** SYSTEM REQUIREMENTS *****/
/****** SYSTEM REQUIREMENT 1 *****/
	/* add i2c gpio expander PCF8574 */
/****** END SYSTEM REQUIREMENTS *****/


// Create PCF8574 instance with default I2C address 0x20
// Address range: 0x20 to 0x27 depending on A0, A1, A2 pins
PCF8574 expander;

/****** FUNCTION PROTOTYPES *****/
void setup(void);
void loop(void);

void setup(void)
{
	// Initialize Serial communication
	Serial.begin(115200);
	delay(100);
	
	Serial.println("\n\nPCF8574 I2C GPIO Expander Initialization...");
	
	// Initialize PCF8574 with I2C address 0x20
	// Using default ESP8266 pins: SDA=4 (D2), SCL=5 (D1)
	if (expander.begin()) {
		Serial.println("PCF8574 initialized successfully!");
		Serial.print("I2C Address: 0x");
		Serial.println(0x20, HEX);
		
		// Initialize all pins to HIGH (default state)
		expander.writePort(0xFF);
		Serial.println("All pins set to HIGH");
	} else {
		Serial.println("Failed to initialize PCF8574!");
		Serial.println("Please check I2C connections and address configuration");
	}
	
	delay(500);
}


void loop(void)
{
	// Check if PCF8574 is still connected
	if (expander.isConnected()) {
		// Example: Set pins individually
		// Set pin 0 to HIGH
		expander.setPin(0);
		delay(500);
		
		// Set pin 1 to HIGH
		expander.setPin(1);
		delay(500);
		
		// Clear pin 0 to LOW
		expander.clearPin(0);
		delay(500);
		
		// Clear pin 1 to LOW
		expander.clearPin(1);
		delay(500);
		
		// Toggle pin 2 multiple times
		expander.togglePin(2);
		delay(250);
		expander.togglePin(2);
		delay(250);
		
		// Read entire port state
		uint8_t portState = expander.readPort();
		Serial.print("Port state: 0x");
		Serial.println(portState, HEX);
		
		// Read individual pin states
		for (int i = 0; i < 8; i++) {
			Serial.print("Pin ");
			Serial.print(i);
			Serial.print(": ");
			Serial.println(expander.getPinState(i) ? "HIGH" : "LOW");
		}
		
		Serial.println("---");
		delay(2000);
	} else {
		Serial.println("PCF8574 device not connected!");
		delay(2000);
	}
}

/* END CODE */