I am creating a DigitalIO library, the purpose being to simplify using sensors and devices that use the digital IO pins. Maybe it'll be of use to some here.
- For AVR boards like UNO it can generate faster more compact code by avoiding digitalRead/Write methods.
- It has built in debounce for level changes (like push butttons) as well as for brief trigger signal (like knock sensors).
I've added more specific support for:
-
ultrasonic sensors (returns distance in mm, cm, inch 1/10th inch, 1/16 inch)
-
rotary encoders (range of values can be constrained, supports interrupts on AVR to simplify main loop).
-
For AVR, it also has a scheduler class to run callbacks functions asynchronously on a time schedule (millisecond precision). It uses Timer 0 comparator A interrupts (it does not interfere with millis() nor the Timer0 clock interrupt). I hope Comparator A interrupt is usually not used since it's tied to the system clock.
A simple scheduler like that might be a cleaner way for people to implement doing "multiple things at the same time".
Library is here, if you appreciate the effort, please give it a star on github to motivate me:
https://wordpress.com/post/dntruong.wordpress.com/1093
If you have ideas, opinions, critiques etc. please let me know on github or here.
Example:
#include <DigitalIO.hpp>
// Encoder is wired to pins 3 4 and 5, with interrupt (on pin 3).
// It returns values [-16,16] only.
// It uses encoderData to store its state (don't read it)
volatile int32_t encoderData = 0;
digitalRotaryEncoder<5,4,3, -16,16, true, encoderData> encoder;
// We have a LED on pin 13, turned off when LOW
digitalIo<13, LOW> led;
void setup() {
Serial.begin(9600);
led.outputMode();
}
void loop() {
// If the encoder switch is pressed down display the value
// We also turn on the LED
switch(encoder.changed())
{
case 1:
led.turnOn();
// We can read the value and not worry about managing the encoder mechanical movement
// that's handled by the interrupt handler. Otherwise we'd have to call this function every 5~10ms
// in the main body of the loop to not skip a beat.
const int32_t val = encoder.rotaryRead();
Serial.print("Button pressed, position: ");
Serial.println(val);
break;
case -1:
led.turnOff();
break;
case 0:
break;
}
delay(100);
}