Advertisement
microrobotics

PCF8574P I2C 8-bit I/O expander

Apr 4th, 2023
810
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Here's an example code to control an PCF8574P I2C 8-bit I/O expander using an Arduino:
  3.  
  4. 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.
  5.  
  6. Connect the PCF8574P I2C 8-bit I/O expander to the Arduino as follows:
  7.  
  8. VCC pin to 5V (or 3.3V, depending on your module's voltage level)
  9. GND pin to GND
  10. SDA pin to the SDA pin on your Arduino (A4 on the Uno, Leonardo, or Nano; pin 20 on the Mega)
  11. SCL pin to the SCL pin on your Arduino (A5 on the Uno, Leonardo, or Nano; pin 21 on the Mega)
  12. If you have a different I2C address for your PCF8574P, you can change the pcf8574Address constant accordingly.
  13.  
  14. 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.
  15. */
  16.  
  17. #include <Arduino.h>
  18. #include <Wire.h>
  19.  
  20. const byte pcf8574Address = 0x20; // I2C address of the PCF8574P
  21.  
  22. void setup() {
  23.   Wire.begin();
  24.   Serial.begin(9600);
  25.   Serial.println("PCF8574P I2C 8-bit I/O Expander Example");
  26. }
  27.  
  28. void loop() {
  29.   // Turn on each output one by one
  30.   for (byte output = 0; output < 8; output++) {
  31.     writePCF8574(output, HIGH);
  32.     delay(500);
  33.   }
  34.  
  35.   // Turn off each output one by one
  36.   for (byte output = 0; output < 8; output++) {
  37.     writePCF8574(output, LOW);
  38.     delay(500);
  39.   }
  40. }
  41.  
  42. void writePCF8574(byte output, byte state) {
  43.   static byte currentStates = 0;
  44.  
  45.   if (state == HIGH) {
  46.     currentStates |= (1 << output); // Set the corresponding output bit to 1
  47.   } else {
  48.     currentStates &= ~(1 << output); // Set the corresponding output bit to 0
  49.   }
  50.  
  51.   Wire.beginTransmission(pcf8574Address);
  52.   Wire.write(currentStates);
  53.   Wire.endTransmission();
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement