Skip to content

Commit

Permalink
Improved example, using Timer for encoder.update()
Browse files Browse the repository at this point in the history
  • Loading branch information
TomSaw committed Mar 17, 2021
1 parent 74ebedd commit 83eb468
Showing 1 changed file with 31 additions and 7 deletions.
38 changes: 31 additions & 7 deletions examples/arduino_nano/encoder_input/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,49 @@

#include <modm/board.hpp>
#include <modm/driver/encoder/encoder_input.hpp>
#include <modm/math/algorithm/prescaler.hpp>
#include <modm/processing/timer.hpp>

using namespace modm::platform;

// Connect the encoders outputs to D7 and D8 Pins (usually the outer pins)
// The common third pin (usually in the middle) is connected to GND.
// Don't add any resistors or filters. It's all in the MCU and the driver.
modm::BitBangEncoderInput<Board::D7, Board::D8, modm::bitbang_encoder_input::Division::FOUR>
encoder;

MODM_ISR(TIMER2_COMPA)
{
encoder.update();
}

void
init_Timer2()
{
constexpr float f = 1_kHz;
constexpr auto inputDevice_prescaler =
modm::Prescaler::from_list(SystemClock::Timer, f * 2, {0, 1, 8, 32, 64, 128, 256, 1024});
constexpr auto ocr = (inputDevice_prescaler.frequency / f) - 1;
static_assert(ocr <= 255, "Can't configure Timer2 for desired f");

// Timer in CTC Mode
TCCR2A = (1 << WGM21);
OCR2A = ocr;
TIMSK2 |= (1 << OCIE2A);
TCCR2B |= inputDevice_prescaler.index;
}

int
main()
{
Board::initialize();
LedD13::setOutput();

// Connect the encoders outputs to D7 and D8 Pins (usually the outer pins)
// The common third pin (usually in the middle) is connected to GND.
// Don't add any resistors or filters. It's all in the MCU and the driver.
modm::BitBangEncoderInput<Board::D7, Board::D8, modm::bitbang_encoder_input::Division::FOUR>
encoder;

encoder.connect();

init_Timer2();
enableInterrupts();

int value(0);

modm::ShortPeriodicTimer heartbeat(500ms);
Expand All @@ -38,7 +63,6 @@ main()
while (true)
{
if (heartbeat.execute()) Board::LedD13::toggle();
if (encoderUpdate.execute()) encoder.update();
if (outputValue.execute())
{
value += encoder.getValue();
Expand Down

0 comments on commit 83eb468

Please sign in to comment.