blob: 90c46d586c465042dbd7e83e75fcbf3a087ba134 [file] [log] [blame]
Daniel Pettid6ff3d52014-01-02 11:24:39 -08001#include "gpi.h"
2
3#include <stdio.h>
4
5#include "aos/common/logging/logging.h"
6
7namespace bbb {
8
9Gpi::Gpi(int bank, int pin) {
10 // All the failures here are fatal, seeing as
11 // if we can't initialize the pin, we're
12 // probably screwed anyway.
13 if (!InitPin(bank, pin)) {
14 LOG(FATAL, "Failed to export pin.\n");
15 }
16 if (!DoPinDirSet(1)) {
17 LOG(FATAL, "Failed to set pin as an input.\n");
18 }
19}
20
21int Gpi::Read() {
22 // NOTE: I can't find any docs confirming that one can indeed
23 // poll a pin's value using this method, but it seems that it
24 // should work. Really, the "right" (interrupt driven) way to
25 // do this is to set an event, but that involves messing with
26 // dev tree crap, which I'm not willing to do unless we need
27 // this functionality.
28 char buf, val_path[64];
29 snprintf(val_path, sizeof(val_path), "/sys/class/gpio/gpio%d/value",
30 kernel_pin_);
31
32 if ((handle_ = fopen(val_path, "rb")) == NULL) {
33 LOG(ERROR, "Unable to open file for pin value reading.\n");
34 fclose(handle_);
35 return -1;
36 }
37
38 if (fread(&buf, sizeof(char), 1, handle_) <= 1) {
39 LOG(ERROR, "Reading from file failed with error %d\n",
40 ferror(handle_));
41 fclose(handle_);
42 return -1;
43 }
44 fclose(handle_);
45 return atoi(&buf);
46}
47
Daniel Pettife475252014-01-05 14:15:16 -080048} // namespace bbb