Skip to content

Instantly share code, notes, and snippets.

@numist
Created September 29, 2019 01:17
Show Gist options
  • Save numist/7f27f2d2c0aa0c92c4c947c6694cae96 to your computer and use it in GitHub Desktop.
Save numist/7f27f2d2c0aa0c92c4c947c6694cae96 to your computer and use it in GitHub Desktop.
Digispark firmware providing a digital optical sensor used for controlling timing on model motors
#include "Opto.h"
static Opto o1;
static Opto o2;
/* Pin allocation. Note the Digispark does some weird nonsense
* with analog pin numbering:
*
* Bank 1:
* Pin 0 → OUT
* Pin 1 → OUT (LED)
* Pin 2 → IN analogRead(1), pinMode(2, INPUT)
*
* Bank 2:
* Pin 3 → OUT
* Pin 4 → OUT
* Pin 5 → IN analogRead(0), pinMode(5, INPUT)
*/
void setup() {
pinMode(0, OUTPUT);
pinMode(1, OUTPUT);
pinMode(2, INPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, INPUT);
}
void loop() {
// Bank 1:
if (o1.loop(analogRead(1))) {
// H-bridge rules: set LOW before HIGH
if (o1.getState()) {
digitalWrite(1, LOW);
digitalWrite(0, HIGH);
} else {
digitalWrite(0, LOW);
digitalWrite(1, HIGH);
}
}
// Bank 2:
if (o2.loop(analogRead(0))) {
// H-bridge rules: set LOW before HIGH
if (o2.getState()) {
digitalWrite(4, LOW);
digitalWrite(3, HIGH);
} else {
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
}
}
}
#include "Opto.h"
bool Opto::getState() {
return state;
}
bool Opto::loop(int val) {
bool prev_state = state;
if (val > highest) { highest = val; }
if (val < lowest) { lowest = val; }
if (state == 0 && val > highest - third()) { state = 1; }
if (state == 1 && val < lowest + third()) { state = 0; }
return prev_state != state;
}
#pragma once
// Basic decoder/state machine for optical detector p/n QRD1114
class Opto {
int highest = 0;
int lowest = 4095;
bool state = false;
int third() { return (highest - lowest) / 3; }
public:
// Returns current state
bool getState();
// Returns true on state change
bool loop(int val);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment