/* * Name: OT_dutycycle * Purpose: Measures dutycycle of measured OT signals. * Author: Martijn van den Burg * */ #include #include #define TIMER_RESET TCNT1 = 0 #define SAMPLE_SIZE 64 int OTpin = 2; unsigned int TimeLow[SAMPLE_SIZE]; unsigned int TimeHigh[SAMPLE_SIZE]; char direction[SAMPLE_SIZE]; byte change_count; long temp; long time; long AvgLow; long AvgHigh; long TotalLow; long TotalHigh; long dutycycle; void setup() { Serial.begin(115200); Serial.println("Analyze OT dutycycle"); TCCR1A = 0x00; // COM1A1=0, COM1A0=0 => Disconnect Pin OC1 from Timer/Counter 1 -- PWM11=0,PWM10=0 => PWM Operation disabled // ICNC1=0 => Capture Noise Canceler disabled -- ICES1=0 => Input Capture Edge Select (not used) -- CTC1=0 => Clear Timer/Counter 1 on Compare/Match // CS12=0 CS11=1 CS10=1 => Set prescaler to clock/64 TCCR1B = 0x03; // 16MHz clock with prescaler means TCNT1 increments every 4uS // ICIE1=0 => Timer/Counter 1, Input Capture Interrupt Enable -- OCIE1A=0 => Output Compare A Match Interrupt Enable -- OCIE1B=0 => Output Compare B Match Interrupt Enable // TOIE1=0 => Timer 1 Overflow Interrupt Enable TIMSK1 = 0x00; pinMode(OTpin, INPUT); } void loop() { Serial.println("Waiting..."); change_count = 0; TotalLow = 0; TotalHigh = 0; int i = 0; int j = 0; int n = 0; while(digitalRead(OTpin) == LOW) {} Serial.println("Sampling..."); TIMER_RESET; direction[change_count++] = '0'; while (change_count < SAMPLE_SIZE) { temp = TCNT1; if (direction[change_count-1] == '0') { while(digitalRead(OTpin) == LOW) {} TimeLow[i] = TCNT1 - temp; direction[change_count++] = '1'; i++; } else { while(digitalRead(OTpin) == HIGH) {} TimeHigh[j] = TCNT1 - temp; direction[change_count++] = '0'; j++; } } for (int i = 0; i < SAMPLE_SIZE / 2; i++) { time = (long) TimeLow[i] * 4; if (time < 1300 && time > 0) { n++; TotalLow += time; } } AvgLow = (float)TotalLow / n; n = 0; for (int i = 0; i < SAMPLE_SIZE / 2; i++) { n++; time = (long) TimeHigh[i] * 4; if (time < 1300 & time > 0) { TotalHigh += time; } } AvgHigh = (float)TotalHigh / n; dutycycle = (float)TotalHigh / (TotalHigh + TotalLow) * 100; Serial.print("Duty cycle: "); Serial.print(dutycycle); Serial.println(" %"); Serial.print("Average time LOW: "); Serial.println(AvgLow); Serial.print("Average tome HIGH: "); Serial.println(AvgHigh); Serial.println(""); Serial.println("Done"); delay(2000); }