Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Here's an example code to control an PCF8574P I2C 8-bit I/O expander using an Arduino:
- This code turns on and off each output of the PCF8574P I2C 8-bit I/O expander one by one, with a 500ms delay between each output change.
- Connect the PCF8574P I2C 8-bit I/O expander to the Arduino as follows:
- VCC pin to 5V (or 3.3V, depending on your module's voltage level)
- GND pin to GND
- SDA pin to the SDA pin on your Arduino (A4 on the Uno, Leonardo, or Nano; pin 20 on the Mega)
- SCL pin to the SCL pin on your Arduino (A5 on the Uno, Leonardo, or Nano; pin 21 on the Mega)
- If you have a different I2C address for your PCF8574P, you can change the pcf8574Address constant accordingly.
- Please note that you may need to use pull-up resistors (typically 4.7kΩ) for the SDA and SCL lines. Some PCF8574P modules might already have pull-up resistors on board; in that case, you don't need to add external ones.
- */
- #include <Arduino.h>
- #include <Wire.h>
- const byte pcf8574Address = 0x20; // I2C address of the PCF8574P
- void setup() {
- Wire.begin();
- Serial.begin(9600);
- Serial.println("PCF8574P I2C 8-bit I/O Expander Example");
- }
- void loop() {
- // Turn on each output one by one
- for (byte output = 0; output < 8; output++) {
- writePCF8574(output, HIGH);
- delay(500);
- }
- // Turn off each output one by one
- for (byte output = 0; output < 8; output++) {
- writePCF8574(output, LOW);
- delay(500);
- }
- }
- void writePCF8574(byte output, byte state) {
- static byte currentStates = 0;
- if (state == HIGH) {
- currentStates |= (1 << output); // Set the corresponding output bit to 1
- } else {
- currentStates &= ~(1 << output); // Set the corresponding output bit to 0
- }
- Wire.beginTransmission(pcf8574Address);
- Wire.write(currentStates);
- Wire.endTransmission();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement