// code modified from https://forum.arduino.cc/t/i-would-love-to-receive-help-with-frequency-transmission-using-arduino/1211551/29?u=davex
// https://wokwi.com/projects/387127367989449729
unsigned long T0;
float Hightime = 0;
float Lowtime = 0;
float frequency;
float Time;
float Duty;
float digitalPin = 7;
const byte simPin = 9;
#include <TimerOne.h>
void setup() {
Serial.begin(115200);
pinMode(digitalPin, INPUT);
pinMode(9, OUTPUT);
Timer1.initialize(250); // 250 us = 4 kHz
//analogWrite(simPin, 10);
Timer1.pwm(simPin, 500);
}
void loop() {
bool read = digitalRead(digitalPin);
const int steps = 5;
for (int simDuty = 1023 / (2*steps); simDuty <= 1023; simDuty += 1023 / steps) {
while (digitalRead(digitalPin) == LOW); // wait to start
T0 = micros(); // mark the first rising
while ( digitalRead(digitalPin) == HIGH); // wait to fall
Hightime = micros() - T0; //measure the high time;
while ( digitalRead(digitalPin) == LOW);
Time = micros() - T0; // measure the total time
frequency = 1000000 / Time ;
Duty = Hightime / Time;
Serial.print("Tus:");
Serial.print(Time);
Serial.print(" f:");
Serial.print(frequency);
Serial.print(" HighUs:");
Serial.print(Hightime);
Serial.print(" d%:");
Serial.println(Duty*100, 2);
Timer1.pwm(simPin, simDuty); // change the duty cycle sim
delay(777); // pause for viewing
while (digitalRead(digitalPin) == HIGH); // wait again
}
}