Daniel Petti | d6ff3d5 | 2014-01-02 11:24:39 -0800 | [diff] [blame] | 1 | #include "gpi.h" |
| 2 | |
| 3 | #include <stdio.h> |
| 4 | |
| 5 | #include "aos/common/logging/logging.h" |
| 6 | |
| 7 | namespace bbb { |
| 8 | |
| 9 | Gpi::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 | |
| 21 | int 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 Petti | fe47525 | 2014-01-05 14:15:16 -0800 | [diff] [blame] | 48 | } // namespace bbb |