Hello
Please help. I'm learning to use an i2c PCF8574 with an Arduino Uno board.
I want to control the LED work by controlling the ON push button and the OFF push button. So when RUN the LED should turn off because the ON push button has not been pressed and it only turns on when the ON push button is pressed. And the LED will turn off when the OFF push button is pressed.
I deliberately took both the INPUT and OUTPUT pins from the PCF8574 because I wanted to know how they worked.
The circuit I made is in the picture below.
I'm actually still very much a beginner. And I tried to ask ChatGPT to generate code for the operation of my circuit.
However, when I RUN with TINKERCAD the results are not correct. I have tried many times with other methods but it doesn't work.
Please help to correct the code that I attached below. Thank you very much.
#include <Wire.h>
const int PCF8574_address = 0x20;
void setup() {
Wire.begin();
pinModePCF8574(0, OUTPUT);
pinModePCF8574(1, INPUT);
pinModePCF8574(2, INPUT);
Serial.begin(9600);
}
void loop() {
int buttonOnState = digitalReadPCF8574(1);
int buttonOffState = digitalReadPCF8574(2);
if (buttonOnState == LOW) {
digitalWritePCF8574(0, HIGH);
Serial.println("LED ON");
}
if (buttonOffState == LOW) {
digitalWritePCF8574(0, LOW);
Serial.println("LED OFF");
}
}
void pinModePCF8574(int pin, int mode) {
Wire.beginTransmission(PCF8574_address);
Wire.write(1 << pin);
if (mode == OUTPUT) {
Wire.write(0);
} else {
Wire.write(1);
}
Wire.endTransmission();
}
void digitalWritePCF8574(int pin, int value) {
Wire.beginTransmission(PCF8574_address);
Wire.write(1 << pin);
Wire.write(value << pin);
Wire.endTransmission();
}
int digitalReadPCF8574(int pin) {
Wire.beginTransmission(PCF8574_address);
Wire.write(1 << pin);
Wire.requestFrom(PCF8574_address, 1);
int value = Wire.read();
Wire.endTransmission();
return value >> pin & 0x01;
}