Arduino Speen sensor from Joy it

Hi,
I recently purchased a Speedsensor from joy-it Speed sensor | Joy-IT
it came a example code which works fine for me.
But i dosent really understand how the Programm works. I have programmed arduino before but I am still an beginner. Can someone explain to me what it does.
Thanks in advance,
Cori

Here is the code:

MODERATION EDIT- added code tags

// sen-speed Demo
// The code measures the revolutions of the encoder disk over a period of
// time (5 seconds by default), then converts it to revolutions per minute
// and outputs it via the serial interface.

// library import
#include "TimerOne.h"
#define pin 2


// needed variables
int interval, wheel, counter;
unsigned long previousMicros, usInterval, calc;

void setup()
{
  counter = 0;  // setting counter to 0
  interval = 5;  // 5 second interval
  wheel = 20; // number of encoder disc holes
  
  calc = 60 / interval;  // calculate interval to one minute
  usInterval = interval * 1000000;  // convert interval to micro
                                    // seconds
  wheel = wheel * 2;  // number of encoder disc wholes times 2 

  pinMode(pin, INPUT);  // setting pin 2 as input
  Timer1.initialize(usInterval);  // initialize timer with interval time
  attachInterrupt(digitalPinToInterrupt(pin), count, CHANGE);
  // executes count, if the level on pin 2 changes
  
  Timer1.attachInterrupt(output);  // executes output after interval time
  Serial.begin(9600);  // starts serial interface with 9600 Baud
}

// counts holes on disc (with filter)
void count(){
  if (micros() - previousMicros >= 700) {
    counter++;
    previousMicros = micros();
  }
}

// output to serial
void output(){
  Timer1.detachInterrupt(); // interrupts the timer
  Serial.print("Drehzahl pro Minute: ");
  int speed = ((counter)*calc) / wheel;
  // calculate round per minute
  
  Serial.println(speed);
  counter = 0;  // resetting the counter
  Timer1.attachInterrupt(output);  // restarts the timer for output
}

void loop(){
 // no loop needed
}

Hello, do yourself a favour and please read How to get the best out of this forum and post accordingly in the future (including code tags and necessary documentation of your ask).


it works through 2 interruptions

  • There is an interruption as well (on pin 2) that will increase the value of count every time you see a CHANGE on that pin (so a LOW to HIGH or HIGH to LOW front) (and at least 700µs have elapsed since the last recording probably to avoid bouncing)

  • the Timer is used to print and reset the counter every 12 seconds (5 times per minute)

Note: 'counter' should be declared "volatile int" since it is changed in the interrupt.

Since 'counter' is larger than one byte it should be buffered when used outside theinterrupt:

  noInterrupts();
  int counterValue = counter;
  counter = 0;
  interrupts();

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.