#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const int signalPin = A1;
void setup() {
// put your setup code here, to run once:
lcd.init(); lcd.backlight();
pinMode(signalPin, INPUT);
lcd.setCursor(0, 0); lcd.print("Freq Counter");
}
void loop() {
// put your main code here, to run repeatedly:
//測量高電位與低電位的持續時間(單位:微秒 uS)
unsigned long hightime = pulseIn(signalPin, HIGH, 1000000);
unsigned long lowtime = pulseIn(signalPin, LOW, 1000000);
//周期=高電位時間+低電位時間
unsigned long period = hightime + lowtime ;
float frequency = 0 ;
if (period > 0){
frequency = 1000000.0 / period; //頻率 = 1 / 週期
}
lcd.setCursor(0,1);lcd.print("Freq:");
if (hightime == 0 || lowtime == 0){
lcd.print("0.00 Hz "); //沒訊號顯示 0
} else {
lcd.print(frequency, 2);lcd.print("Hz "); //有訊號顯示頻率
}
delay(300);
}