• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 using pw::thread::Thread;
34 
InterruptExample()35 pw::Status InterruptExample() {
36   // Open handle to chip.
37   PW_TRY_ASSIGN(auto chip, LinuxDigitalIoChip::Open("/dev/gpiochip0"));
38 
39   // Create a notifier to deliver interrupts to the line.
40   PW_TRY_ASSIGN(auto notifier, LinuxGpioNotifier::Create());
41 
42   // Configure input line.
43   LinuxInputConfig config(
44       /* index= */ 5,
45       /* polarity= */ Polarity::kActiveHigh);
46   PW_TRY_ASSIGN(auto input, chip.GetInterruptLine(config, notifier));
47 
48   // Configure the interrupt handler.
49   auto handler = [](State state) {
50     PW_LOG_DEBUG("Interrupt handler fired with state=%s",
51                  state == State::kActive ? "active" : "inactive");
52   };
53   PW_TRY(input.SetInterruptHandler(InterruptTrigger::kActivatingEdge, handler));
54   PW_TRY(input.EnableInterruptHandler());
55   PW_TRY(input.Enable());
56 
57   // There are several different ways to deal with events:
58 
59   // Option A: Wait once for events.
60   PW_TRY(notifier->WaitForEvents(0));    // Non-blocking.
61   PW_TRY(notifier->WaitForEvents(500));  // Block for 500 milliseconds.
62   PW_TRY(notifier->WaitForEvents(-1));   // Block indefinitely.
63 
64   // Option B: Handle events synchronously, blocking forever.
65   notifier->Run();
66 
67   // Option C: Handle events in a separate thread.
68   Thread notifier_thread(pw::thread::stl::Options(), *notifier);
69   pw::this_thread::sleep_for(30s);
70   notifier->CancelWait();
71   notifier_thread.join();
72 
73   return pw::OkStatus();
74 }
75