1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include <chrono>
16
17 #include "pw_chrono/system_clock.h"
18 #include "pw_digital_io_linux/digital_io.h"
19 #include "pw_log/log.h"
20 #include "pw_status/try.h"
21 #include "pw_thread/sleep.h"
22 #include "pw_thread/thread.h"
23 #include "pw_thread_stl/options.h"
24
25 using namespace std::chrono_literals;
26
27 using pw::digital_io::InterruptTrigger;
28 using pw::digital_io::LinuxDigitalIoChip;
29 using pw::digital_io::LinuxGpioNotifier;
30 using pw::digital_io::LinuxInputConfig;
31 using pw::digital_io::Polarity;
32 using pw::digital_io::State;
33
InterruptExample()34 pw::Status InterruptExample() {
35 // Open handle to chip.
36 PW_TRY_ASSIGN(auto chip, LinuxDigitalIoChip::Open("/dev/gpiochip0"));
37
38 // Create a notifier to deliver interrupts to the line.
39 PW_TRY_ASSIGN(auto notifier, LinuxGpioNotifier::Create());
40
41 // Configure input line.
42 LinuxInputConfig config(
43 /* gpio_index= */ 5,
44 /* gpio_polarity= */ Polarity::kActiveHigh);
45 PW_TRY_ASSIGN(auto input, chip.GetInterruptLine(config, notifier));
46
47 // Configure the interrupt handler.
48 auto handler = [](State state) {
49 PW_LOG_DEBUG("Interrupt handler fired with state=%s",
50 state == State::kActive ? "active" : "inactive");
51 };
52 PW_TRY(input.SetInterruptHandler(InterruptTrigger::kActivatingEdge, handler));
53 PW_TRY(input.EnableInterruptHandler());
54 PW_TRY(input.Enable());
55
56 // There are several different ways to deal with events:
57
58 // Option A: Wait once for events.
59 PW_TRY(notifier->WaitForEvents(0)); // Non-blocking.
60 PW_TRY(notifier->WaitForEvents(500)); // Block for 500 milliseconds.
61 PW_TRY(notifier->WaitForEvents(-1)); // Block indefinitely.
62
63 // Option B: Handle events synchronously, blocking forever.
64 notifier->Run();
65
66 // Option C: Handle events in a separate thread.
67 pw::Thread notifier_thread(pw::thread::stl::Options(), *notifier);
68 pw::this_thread::sleep_for(30s);
69 notifier->CancelWait();
70 notifier_thread.join();
71
72 return pw::OkStatus();
73 }
74