-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
button_pigpio_basic.cpp
80 lines (66 loc) · 2.44 KB
/
button_pigpio_basic.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// button_pigpio_basic.cpp
//
// Description:
// A C++ program that turns on an LED when a button is pressed on a
// Raspberry Pi using the pigpio library.
//
// Circuit:
// - A momentary push button (normally open) is connected to BCM pin 5,
// physical pin 29.
// - An LED is connected to BCM pin 21, physical pin 40.
//
// Created by John Woolsey on 10/07/2022.
// Modified by John Woolsey on 12/19/2022.
// Copyright (c) 2022 Woolsey Workshop. All rights reserved.
// Includes
#include <csignal>
#include <iostream>
#include <pigpio.h>
// Pin Mapping
const int Button = 5;
const int RedLED = 21;
// Global Variables
volatile sig_atomic_t signal_received = 0; // interrupt signal received
// Functions
void sigint_handler(int signal) {
signal_received = signal; // capture interrupt signal
}
void buttonChanged(int gpio, int level, uint32_t tick) {
static uint32_t previousTimeButtonChanged = 0;
uint32_t currentTime = tick;
if (currentTime - previousTimeButtonChanged > 10000) { // debounce time of 10 ms
if (level == PI_LOW) {
std::cout << "Button pressed." << std::endl;
gpioWrite(RedLED, PI_HIGH);
} else if (level == PI_HIGH) {
std::cout << "Button released." << std::endl;
gpioWrite(RedLED, PI_LOW);
} else if (level == PI_TIMEOUT) {
std::cout << "Timeout occurred." << std::endl;
}
previousTimeButtonChanged = currentTime;
}
}
// Main
int main() {
// Initialize pigpio library GPIO interface
if (gpioInitialise() == PI_INIT_FAILED) {
std::cout << "ERROR: Failed to initialize the GPIO interface." << std::endl;
return 1; // exit with positive number to denote failure
}
// Pin configuration
gpioSetMode(Button, PI_INPUT);
gpioSetPullUpDown(Button, PI_PUD_UP); // enable microcontroller's internal pull-up resistor
gpioSetMode(RedLED, PI_OUTPUT);
gpioWrite(RedLED, PI_LOW);
gpioSetAlertFunc(Button, buttonChanged); // call buttonChanged() when button changes state
// Detect when CTRL-C is pressed
signal(SIGINT, sigint_handler); // enable interrupt handler
std::cout << "Press CTRL-C to exit." << std::endl;
while (!signal_received); // loops until CTRL-C is pressed
// Exit cleanly when CTRL-C is pressed
gpioSetMode(RedLED, PI_INPUT); // reset RedLED pin as an input
gpioTerminate(); // terminate pigpio library GPIO interface
std::cout << std::endl;
return 0; // exit with zero to denote success
}