Smart Home Automation Forum
[arduino code examples for F16]-02 Read digital input ports state - Printable Version

+- Smart Home Automation Forum (https://www.kincony.com/forum)
+-- Forum: Technical Support (https://www.kincony.com/forum/forumdisplay.php?fid=62)
+--- Forum: F16 (https://www.kincony.com/forum/forumdisplay.php?fid=63)
+--- Thread: [arduino code examples for F16]-02 Read digital input ports state (/showthread.php?tid=6817)



[arduino code examples for F16]-02 Read digital input ports state - admin - 10-01-2024

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* Description:
* This Arduino program reads the state of a 16-channel PCF8575 I/O expander
* and prints the state of all input pins to the Serial Monitor. The state of
* each pin is represented as a bit in a 16-bit value, where each bit corresponds
* to an input pin. The program prints the input state in binary format.
*
* Pin Definitions:
* - SDA: GPIO 21
* - SCL: GPIO 22
* - PCF8575 I2C Address: 0x24
*/

#include "Arduino.h"
#include "PCF8575.h"

// Define I2C pins
#define I2C_SDA 8  // Define SDA pin
#define I2C_SCL 18  // Define SCL pin

// Set I2C address
PCF8575 pcf8575_IN1(0x24); // The I2C address of the PCF8575

void setup() {
    Serial.begin(115200);

    // Initialize I2C communication
    Wire.begin(I2C_SDA, I2C_SCL); // Initialize I2C with defined SDA and SCL pins

    pcf8575_IN1.begin(); // Initialize the PCF8575

    Serial.println("KinCony F16 16 channel input state 0:ON  1:OFF");
}

void loop() {
    uint16_t state = 0;

    // Read the state of each pin (assuming 16 pins)
    for (int pin = 0; pin < 16; pin++) {
        if (pcf8575_IN1.read(pin)) {
            state |= (1 << pin); // Set the bit for the active pin
        }
    }

    Serial.print("Input state: ");
    Serial.println(state, BIN); // Print the state of inputs in binary

    delay(500); // Delay 500ms
}
arduino ino file download:
.zip   2-digital-input.zip (Size: 839 bytes / Downloads: 8)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download: 
.zip   2-digital-input.ino.merged.zip (Size: 187.5 KB / Downloads: 10)