KeyboardManager: a class to manage the polling of a switch-matrix keyboard
Diff: KeyboardMonitor.cpp
- Revision:
- 2:eb4cc53ff33d
- Child:
- 3:1310c57aca77
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/KeyboardMonitor.cpp Sun Jan 23 23:15:36 2011 +0000 @@ -0,0 +1,52 @@ +#include "kbd_mgr/KeyboardMonitor.h" + +namespace kbd_mgr { + +KeyboardMonitor::KeyboardMonitor(PortName inPort, std::size_t numKeysPerRow, std::size_t inLowestBit, + const KeyboardMonitor::OutPinsSet &outPins, KeyboardStateHandler *handler) : + in(inPort, ((1 << numKeysPerRow)-1) << inLowestBit), inBitShift(inLowestBit), outPins(outPins), handler(handler), + ticker(), scanRow(0), currentState(outPins.size(), numKeysPerRow) +{ } + +void KeyboardMonitor::start(float pollingPeriod) +{ + if (this->outPins.empty()) { + return; + } + + if (pollingPeriod < 20e-6) { + pollingPeriod = 20e-6; + } + + for(OutPinsSet::const_iterator p = this->outPins.begin(); p != this->outPins.end(); ++p) { + DigitalOut out(*p); + out.write( p == this->outPins.begin() ? 1 : 0 ); + } + this->in.mode(PullDown); + this->scanRow = 0; + this->ticker.attach(this, &KeyboardMonitor::timerHandler, pollingPeriod); +} + +void KeyboardMonitor::stop() +{ + this->ticker.detach(); + this->in.mode(OpenDrain); +} + +void KeyboardMonitor::timerHandler() +{ + DigitalOut out(this->outPins[this->scanRow]); + out.write(1); + wait_us(10); + int v = (this->in.read() >> this->inBitShift); + out.write(0); + this->currentState.setRowState(this->scanRow, v); + this->scanRow = (this->scanRow + 1) % this->currentState.getNumRows(); + if (this->scanRow == 0) { + if (this->handler) { + (*this->handler)(this->currentState); + } + } +} + +} // kbd_mgr