|
| 1 | +// ----- |
| 2 | +// LimitedRotator.ino - Example for the RotaryEncoder library. |
| 3 | +// This class is implemented for use with the Arduino environment. |
| 4 | +// Copyright (c) by Matthias Hertel, http://www.mathertel.de |
| 5 | +// This work is licensed under a BSD style license. See http://www.mathertel.de/License.aspx |
| 6 | +// More information on: http://www.mathertel.de/Arduino |
| 7 | +// ----- |
| 8 | +// 26.03.2017 created by Matthias Hertel |
| 9 | +// ----- |
| 10 | + |
| 11 | +// This example checks the state of the rotary encoder in the loop() function. |
| 12 | +// The current position is printed on output when changed. |
| 13 | +// In addition to the SimplePollRotator example here the range of the rotator is limited to the range 0 - 16 and only incremental steps of 2 are realized. |
| 14 | +// To implement this limit the boundaries are checked and eventually the current position is adjusted. |
| 15 | +// The internal (physical) position of the rotary encoder library remains by stepping with the increment 1 |
| 16 | +// so the the logical position is calculated by applying the ROTARYSTEPS factor. |
| 17 | + |
| 18 | +// Hardware setup: |
| 19 | +// Attach a rotary encoder with output pins to A2 and A3. |
| 20 | +// The common contact should be attached to ground. |
| 21 | + |
| 22 | +#include <RotaryEncoder.h> |
| 23 | + |
| 24 | +#define ROTARYSTEPS 2 |
| 25 | +#define ROTARYMIN 0 |
| 26 | +#define ROTARYMAX 16 |
| 27 | + |
| 28 | +// Setup a RoraryEncoder for pins A2 and A3: |
| 29 | +RotaryEncoder encoder(A2, A3); |
| 30 | + |
| 31 | +// Last known rotary position. |
| 32 | +int lastPos = -1; |
| 33 | + |
| 34 | +void setup() |
| 35 | +{ |
| 36 | + Serial.begin(57600); |
| 37 | + Serial.println("LimitedRotator example for the RotaryEncoder library."); |
| 38 | + encoder.setPosition(10 / ROTARYSTEPS); // start with the value of 10. |
| 39 | +} // setup() |
| 40 | + |
| 41 | + |
| 42 | +// Read the current position of the encoder and print out when changed. |
| 43 | +void loop() |
| 44 | +{ |
| 45 | + encoder.tick(); |
| 46 | + |
| 47 | + // get the current physical position and calc the logical position |
| 48 | + int newPos = encoder.getPosition() * ROTARYSTEPS; |
| 49 | + |
| 50 | + if (newPos < ROTARYMIN) { |
| 51 | + encoder.setPosition(ROTARYMIN / ROTARYSTEPS); |
| 52 | + newPos = ROTARYMIN; |
| 53 | + |
| 54 | + } else if (newPos > ROTARYMAX) { |
| 55 | + encoder.setPosition(ROTARYMAX / ROTARYSTEPS); |
| 56 | + newPos = ROTARYMAX; |
| 57 | + } // if |
| 58 | + |
| 59 | + if (lastPos != newPos) { |
| 60 | + Serial.print(newPos); |
| 61 | + Serial.println(); |
| 62 | + lastPos = newPos; |
| 63 | + } // if |
| 64 | +} // loop () |
| 65 | + |
| 66 | +// The End |
| 67 | + |
0 commit comments