I've been writing a code to analyze the signal of a sensor. To test the code I wrote a signalgenerator which outputs a pwm Signal with variable duty cycle and frequency.
The analyzer has to print the recieved frequency and duty, but the serial monitor isn't displaying anything or just question marks.
#define CPUclk 16000000UL
volatile uint16_t captureValue1;
volatile uint16_t captureValue2;
volatile unsigned long ovf_counter;
volatile int duty;
volatile int frequenz;
volatile uint8_t printFlag;
volatile int i = 1;
int main() { //Normal Mode Timer 1 16Bit
init();
Serial.begin(9600);
DDRB &= ~ (1 << DDB0); //PIN8
TCCR1A = 0;
TCCR1B = 0;
TCCR1B |= (1 << CS10); //Prescaler 1
TCCR1B |= (1 << ICNC1);
TCCR1B &= ~ (1 << ICES1); //NC & Input Capture steigende Flanke
TIMSK1 |= (1 << TOIE1) | (1 << ICIE1); // Ovf Interrupt & Input Capture ein
sei();
while (1) {
if (printFlag) {
printFlag = 0;
Serial.print(frequenz);
Serial.print("Hz");
Serial.print("---");
Serial.print(duty);
Serial.println("%");
}
}
}
ISR(TIMER1_OVF_vect) {
ovf_counter = 0; // Neue Periode Flankencounter reseten
}
ISR(TIMER_CAPT_vect) {
printFlag = 1;
if (i) {
TCCR1B |= (1 << ICES1); //steigende Flanke
uint16_t captureValue1 = ICR1; //Wert bei fallender Flanke speichern
i = 0;
ovf_counter++; //Flanken in einer Periode zählen
}
else {
TCCR1B &= ~ (1 << ICES1); // fallende Flanke
uint16_t captureValue2 = ICR1; //Wert bei steigender Flanke speichern
i = 1;
ovf_counter++; //Flanken in einer Periode zählen
}
//duty in % duty = HIGH/LOW
duty = 100 * ((unsigned long)(captureValue2 - captureValue1) / (unsigned long)(65535 - (captureValue2 - captureValue1)));
frequenz = CPUclk * 2 / ovf_counter;
// f = Frequenz von Arduino / ( Anzahl der auftretenden Flanken * 0.5 )
}