92 lines
2.5 KiB
C++
92 lines
2.5 KiB
C++
#include "FastLED.h"
|
|
|
|
#define NUMBER_LEDS 60
|
|
#define STRIP_PIN 6
|
|
|
|
#define USE_SECOND_HALL 1
|
|
|
|
CRGB leds[NUMBER_LEDS];
|
|
|
|
// speed in rounds-per-millisecond
|
|
volatile float rpms = 0;
|
|
|
|
volatile unsigned long current_mus = 0;
|
|
volatile unsigned long current_loop_mus = 0;
|
|
volatile unsigned long last_mus = 0;
|
|
volatile unsigned long revolution_startmus = 0;
|
|
volatile byte current_pos = 0;
|
|
byte offset = 0;
|
|
|
|
void setup() {
|
|
Serial.begin(115200);
|
|
Serial.println("Started.");
|
|
attachInterrupt(digitalPinToInterrupt(2), magnet_detect, RISING);//Initialize the intterrupt pin (Arduino digital pin 2)
|
|
#ifdef USE_SECOND_HALL
|
|
attachInterrupt(digitalPinToInterrupt(3), magnet_detect2, RISING);
|
|
#endif
|
|
FastLED.addLeds<WS2812B, STRIP_PIN, GRB>(leds, NUMBER_LEDS).setCorrection( TypicalLEDStrip );
|
|
showPosition();
|
|
}
|
|
|
|
void loop() {
|
|
current_loop_mus = micros();
|
|
if((current_loop_mus - revolution_startmus) > 1000000) {
|
|
revolution_startmus = current_loop_mus;
|
|
rpms = 0;
|
|
offset = current_pos;
|
|
}
|
|
|
|
current_pos = (int)((((float)(current_loop_mus - revolution_startmus)) / 1000.0) * rpms * NUMBER_LEDS + offset) % NUMBER_LEDS;
|
|
showPosition();
|
|
FastLED.delay(50);
|
|
}
|
|
|
|
void showPosition() {
|
|
// show the led at position pos (NUMBER_LEDS must be < 256)!
|
|
for (int i = 0; i < NUMBER_LEDS; i++) {
|
|
leds[i] = CRGB::Black;
|
|
}
|
|
byte next = (current_pos + 1) % NUMBER_LEDS;
|
|
byte prev = (current_pos -1)%NUMBER_LEDS;
|
|
leds[current_pos] = CRGB::White;;
|
|
leds[current_pos].fadeLightBy(32);
|
|
leds[next] = CRGB::DarkOrange;
|
|
leds[next].fadeLightBy(128);
|
|
leds[prev] = CRGB::DarkOrange;
|
|
leds[prev].fadeLightBy(128);
|
|
FastLED.show();
|
|
}
|
|
|
|
void magnet_detect()//This function is called whenever a magnet/interrupt is detected by the arduino
|
|
{
|
|
Serial.println("detect");
|
|
current_mus = micros();
|
|
#ifndef USE_SECOND_HALL
|
|
rpms = 1000.0 / (float)(current_mus - revolution_startmus );
|
|
#else
|
|
// half revolutions
|
|
rpms = 500.0 / (float)(current_mus - revolution_startmus );
|
|
#endif
|
|
Serial.println(rpms, DEC);
|
|
revolution_startmus = current_mus;
|
|
current_pos = 0;
|
|
offset = 0;
|
|
//showPosition();
|
|
}
|
|
|
|
#ifdef USE_SECOND_HALL
|
|
void magnet_detect2()//This function is called whenever a magnet/interrupt is detected by the arduino
|
|
{
|
|
Serial.println("detect");
|
|
current_mus = micros();
|
|
// half revolutions
|
|
rpms = 500.0 / (float)(current_mus - revolution_startmus );
|
|
Serial.println(rpms, DEC);
|
|
revolution_startmus = current_mus;
|
|
//current_pos = 0;
|
|
//offset = 0;
|
|
//showPosition();
|
|
}
|
|
#endif
|
|
|