Smart Home Automation Forum
[arduino code examples for A32 Pro]-05 Read free GPIO state - Printable Version

+- Smart Home Automation Forum (https://www.kincony.com/forum)
+-- Forum: Technical Support (https://www.kincony.com/forum/forumdisplay.php?fid=20)
+--- Forum: KC868-A32/A32 Pro (https://www.kincony.com/forum/forumdisplay.php?fid=27)
+--- Thread: [arduino code examples for A32 Pro]-05 Read free GPIO state (/showthread.php?tid=6684)



[arduino code examples for A32 Pro]-05 Read free GPIO state - admin - 09-13-2024

Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* GPIO Status Monitoring
*
* This program monitors the status (high or low) of multiple GPIO pins on the ESP32-S3.
* It prints the status of the pins to the serial monitor whenever a change is detected.
*
* GPIO Pins Monitored:
* - GPIO 1
* - GPIO 2
* - GPIO 38
* - GPIO 0
* - GPIO 21
*
* Hardware Requirements:
* - Connect the pins to appropriate devices or pull them to HIGH/LOW for testing
*/

#define GPIO_PIN_1  1
#define GPIO_PIN_2  2
#define GPIO_PIN_38 38
#define GPIO_PIN_0  0
#define GPIO_PIN_21 21

// Store the previous state of the GPIO pins
bool prevState[5] = {false, false, false, false, false}; // Adjusted to 5 elements

void setup() {
  // Initialize serial communication for debugging purposes
  Serial.begin(115200); // Initialize the serial monitor at 115200 baud
  while (!Serial);      // Wait for the serial monitor to open

  // Initialize GPIO pins as inputs
  pinMode(GPIO_PIN_1, INPUT);
  pinMode(GPIO_PIN_2, INPUT);
  pinMode(GPIO_PIN_38, INPUT);
  pinMode(GPIO_PIN_0, INPUT);
  pinMode(GPIO_PIN_21, INPUT);

  Serial.println("GPIO Status Monitoring Started");
}

void loop() {
  // Read the current state of each GPIO pin
  bool currentState[5];
  currentState[0] = digitalRead(GPIO_PIN_1);
  currentState[1] = digitalRead(GPIO_PIN_2);
  currentState[2] = digitalRead(GPIO_PIN_38);
  currentState[3] = digitalRead(GPIO_PIN_0);
  currentState[4] = digitalRead(GPIO_PIN_21);

  // Check for changes in GPIO pin states
  for (int i = 0; i < 5; i++) {
    if (currentState[i] != prevState[i]) {
      // Print the pin number and its new state if it has changed
      Serial.print("GPIO ");
      Serial.print(i == 0 ? GPIO_PIN_1 :
                   i == 1 ? GPIO_PIN_2 :
                   i == 2 ? GPIO_PIN_38 :
                   i == 3 ? GPIO_PIN_0 : GPIO_PIN_21);
      Serial.print(" changed to ");
      Serial.println(currentState[i] ? "HIGH" : "LOW");
      // Update the previous state
      prevState[i] = currentState[i];
    }
  }

  // Delay to avoid flooding the serial monitor
  delay(100); // Adjust the delay as needed
}
arduino ino file download: 
.zip   5-free-gpio-state.zip (Size: 1,011 bytes / Downloads: 42)
BIN file (you can use esp32 download tool download to ESP32-S3 with address 0x0 then directly to use) download:
.zip   5-free-gpio-state.ino.merged.zip (Size: 177.4 KB / Downloads: 34)