Hello community,
I am new with arduino. I just started working with arduino due, watched some tutorials and tried to do the basics..
I now got a short code of a collegue, that reads an FM signal from an SRM crank. The code simply reads the time difference between a rising signal and the next one. Since I don't really get all parts of this code, a friend recommended me to put it on this page. I am really looking forward for some help on this code. Regarding the comments: The guy I got this code from, used a Teensy and he tried to comment it a little bit for me and my due.
Thank you guys,
Patrick
This is the code:
//October 2017
// Simple read HZ using pin 11 and interrupts
//Connect red (Blue) to 3.3v
//Black (green) = ground (GND)
//White (violett) = hz signal into any digital pin, just change number below to match pin
#define hzPin 11
#define DEGREE_FLAG 1
volatile uint8_t bUpdateFlagsShared; //hold the updated flag
// shared variables are updated by the ISR and read by loop.
const int BUFFERSIZE = 50;//change this to whatever size you want to read from the serial port
volatile uint8_t BufferInShared = 0;
volatile uint8_t HZSamplesShared = 0;
int HZInShared[BUFFERSIZE];
volatile int Samples = 0;
unsigned long HZStart;
unsigned long HZPeriod;
unsigned long HZ;
void setup(void)
{
Serial.begin(9600);//this might need to change for the DUE
pinMode(hzPin, INPUT);
attachInterrupt(hzPin, counterhz, RISING);
}
void loop(void)
{
static int HZIn[BUFFERSIZE];
static uint8_t bUpdateFlags;
static uint8_t HZSamples = 0;
noInterrupts(); // turn interrupts off quickly while we take local copies of the shared variables
if (bUpdateFlagsShared)
{
// take a local copy of which channels were updated in case we need to use this in the rest of loop
bUpdateFlags = bUpdateFlagsShared;
if (bUpdateFlags & DEGREE_FLAG)
{
HZSamples = HZSamplesShared;
memcpy (HZIn, HZInShared, sizeof HZInShared);
}
bUpdateFlagsShared = 0;
BufferInShared = 0; //need to be reset?
HZSamplesShared = 0;
}
interrupts();
if (bUpdateFlags & DEGREE_FLAG && Samples < 50) {
for (int i = 0; i < HZSamples; i++) { //print HZ array to serial port
Serial.print(HZIn[i]);
if (i < HZSamples - 1) {
Serial.print(",");
}
}
SerialUSB.println();
bUpdateFlags = 0;
}
}
void counterhz() //This is what determines the frequency
{
HZPeriod = micros() - HZStart;
if (HZPeriod >= 75) { //285us=3500hz, 334=3000hz
HZStart = micros();
HZ = 1000000 / HZPeriod; //convert period to frequency
if ( HZSamplesShared < BUFFERSIZE && HZ > 300 && HZ < 10000) {//simple filter to eliminate small or large values
HZInShared[HZSamplesShared++] = HZ;
HZ = 10000;//not sure why I do this, you migth be able to remove it
}
}
if (HZSamplesShared == BUFFERSIZE) {//when buffer if full, set flag to print data to serial port
bUpdateFlagsShared |= DEGREE_FLAG;
}
}