I want to monitor for a specific GPIO pin which has a button connected to it and depending on the number of times the button has been pressed it will either turn on some LED lights, make them blink or turn them off.
#include <stdio.h>
#include <pigpio.h>
#include <stdlib.h>
#include <unistd.h>
#define LED_1 13
#define LED_2 19
#define BUTTON 25
#define ON 1
#define OFF 0
#define DELAY 1
void initalise_pins();
void clear_all();
void start_button();
void turn_on_lights();
void increment_state(int gpio, int level, uint32_t tick);
int current_state = 0; /*Don't have a better way of breaking out of loop during pulse so using global var*/
int main(){
if (gpioInitialise() < 0){
printf("Error initializing pigpio library, exiting");
}
else{
initalise_pins();
clear_all();
start_button();
}
}
int main(){
initalise_pins();
clear_all();
start_button();
}
void initalise_pins(){
gpioSetMode(LED_1, PI_OUTPUT); /*Set LED at pin 13 to output*/
gpioSetMode(LED_2, PI_OUTPUT); /*Set LED at pin 19 to output*/
gpioSetMode(BUTTON, PI_INPUT); /*Set Button at pin 25 to input*/
gpioSetPullUpDown(BUTTON, PI_PUD_DOWN); /*Set Button at pin 25 to pulldown*/
gpioSetAlertFunc(BUTTON, increment_state); /*Function to watch for GPIO state change*/
}
void clear_all(){
gpioWrite(LED_1, OFF); /*Resets LED_1 to off*/
gpioWrite(LED_2, OFF); /*Resets LED_2 to off*/
}
void turn_on_lights(){
gpioWrite(LED_1, ON);
gpioWrite(LED_2, ON);
}
void increment_state(int gpio, int level, uint32_t tick){
if (level == 1){
current_state += 1;
}
}
void start_button(){
for (;;){ /*Loop to keep reading button value*/
if (current_state == 0){ /*Current state off*/
continue;
}
else if (current_state == 1){ /*Current state on*/
turn_on_lights();
}
else if (current_state == 2){ /*Current state blinking*/
clear_all();
sleep(DELAY);
turn_on_lights();
sleep(DELAY);
}
else{ /*Reset state to off*/
clear_all();
current_state = 0;
}
sleep(0.1);
}
}
The code works as expected but is there a proper way to set the value of current_state
instead of having it as a global variable? Main issue with this solution is that when I compile it as a library to be used in Python this function will break.