音頻實驗

#include <Wire.h>

#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,16,2); // 若LCD 無法啟用,請將0X3F 改為0X27

char cmd[9] ;

unsigned long f,t,t1;

int x = 34 ;

void setup(){

Serial.begin(9600);

Serial.setTimeout(20); // 設定為每10毫秒結束一次讀取(數字愈小愈快)

lcd.init();

lcd.backlight();

lcd.clear();

pinMode(4,OUTPUT);

pinMode(2,OUTPUT);

Serial.println("Please insert the frequency");

lcd.setCursor(0,0);

lcd.print("Waiting for your");

lcd.setCursor(0,1);

lcd.print("key-in...");

}

void loop(){

if(Serial.available()){

Serial.readBytes(cmd,9);

f=atoi(cmd) ;

t=500000/f;

t1=500/f;

Serial.print("f=");

Serial.print(f);

Serial.print(" , us=");

Serial.print(t);

Serial.print(" , ms=");

Serial.println(t1);

if(f==0){

lcd.clear();

lcd.setCursor(0,0);

lcd.print("f= ");

lcd.print(f);

lcd.print(" Hz");

lcd.setCursor(0,1);

lcd.print("T= ");

lcd.print("infinite");

lcd.print(" us");

}else{

lcd.clear();

lcd.setCursor(0,0);

lcd.print("f= ");

lcd.print(f);

lcd.print(" Hz");

lcd.setCursor(0,1);

lcd.print("T= ");

lcd.print(t);

lcd.print(" us");

}

}

if(f>=x ){

digitalWrite(4,1);

digitalWrite(2,0);

delayMicroseconds(t);

digitalWrite(4,0);

digitalWrite(2,1);

delayMicroseconds(t);

}else if(f>0 && f<x){

digitalWrite(4,1);

digitalWrite(2,0);

delay(t1);

digitalWrite(4,0);

digitalWrite(2,1);

delay(t1);

}else{

digitalWrite(4,0);

digitalWrite(2,0);

}

}