Skip to content

Instantly share code, notes, and snippets.

@n13i n13i/Makefile
Created Aug 14, 2017

Embed
What would you like to do?
Shutdown the Raspbian when GPIO24 is continuously HIGH for 5 seconds
@reboot /usr/local/bin/powerloss_watch &
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <wiringPi.h>
#define PIN_POWERLOSS_IN (5) // BCM GPIO24 (Header Pin 18)
#define READ_INTERVAL (100) // msec
#define COUNT_TO_SHUTDOWN (50) // x {READ_INTERVAL}msec
void signal_handler(int signum);
void init()
{
setenv("WIRINGPI_GPIOMEM", "1", 1);
if(-1 == wiringPiSetup())
{
fprintf(stderr, "wiringPiSetup() failed\n");
exit(1);
}
pinMode(PIN_POWERLOSS_IN, INPUT);
pullUpDnControl(PIN_POWERLOSS_IN, PUD_DOWN);
}
void set_signal_handler(int signum)
{
if(SIG_ERR == signal(signum, signal_handler))
{
fprintf(stderr, "set_signal_handler failed\n");
exit(1);
}
}
void signal_handler(int signum)
{
fprintf(stderr, "signal_handler: got signal %d\n", signum);
exit(1);
}
void run()
{
int on_count = 0;
int prev_in = 0;
int current_in = 0;
int prev_read_value = 0;
while(1)
{
int read_value = digitalRead(PIN_POWERLOSS_IN);
if(prev_read_value == read_value)
{
current_in = read_value;
}
if(prev_in != current_in)
{
fprintf(stderr, "state changed %d to %d\n", prev_in, current_in);
}
if(1 == current_in)
{
on_count++;
if(on_count >= COUNT_TO_SHUTDOWN)
{
break;
}
}
else
{
on_count = 0;
}
prev_in = current_in;
prev_read_value = read_value;
delay(READ_INTERVAL);
}
}
int main()
{
set_signal_handler(SIGINT);
set_signal_handler(SIGTERM);
init();
run();
return 0;
}
gpio_shutdown: gpio_shutdown.o
cc -o $@ $^ -lwiringPi
.c.o:
cc -c $<
clean:
@rm gpio_shutdown
@rm gpio_shutdown.o
#!/bin/sh
/usr/local/bin/gpio_shutdown
/sbin/shutdown -h now
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.