arduino:碼盤測速實驗
實驗描述
利用槽型光耦與20格碼盤測量馬達轉速(rps)(每秒鐘轉數),並在串口監視器中顯示出來;
實驗器材
arduino uno,槽型光耦模塊,20格碼盤,5V直流馬達;
原理簡介
取時間段1秒鐘(1000ms);
測量1秒鐘內槽型光耦計數次數:count ;
馬達轉速:rps = count / 20 ;
示例代碼
int count = 0;
float rps = 0.00;
int interruptPin = 2;//中斷函數引腳設定
unsigned long time1 = 0;
unsigned long time2 = 0;
unsigned long time3 = 0;
void setup()
{
Advertisements
Serial.begin(9600);
pinMode(interruptPin,INPUT);
digitalWrite(interruptPin,HIGH);
attachInterrupt(0,countFunction,FALLING);//中斷調用函數
}
void loop()
{
time2 = millis();
if(abs(time2 - time1) >= 1000)//取1秒鐘的時間段進行測速計算,代碼為如果超過1秒則關閉中斷計數清零
{
detachInterrupt(0);
rps = count/20;//20格碼盤,計數總數除以20即為時間段內(1秒)的圈數
count = 0;
Advertisements
time1 = millis();
attachInterrupt(0,countFunction,FALLING);
}
}
void countFunction()
{
if((millis() - time3) > 20)//中斷有效性判斷代碼,兩次中斷間隔時間如果超過20ms則判定為真實,起濾波消噪的作用
{
count = count + 1;
time3 = millis();
Serial.print("rps = ");
Serial.println(rps);
Serial.println("------------------");
}
}