輸入訊號可分成兩大類:數位和類比,分別使用digitalRead()和analogRead()函式來讀取其內容值,因為其電路設計上有些差異,數位輸入和類比輸入的腳位不同,在類比腳位上標示"A",A0~A5共有5支腳,簡單的程式設計如下:
int sensorValue = 0;
void setup()
{
pinMode(A0, INPUT);
pinMode(13, OUTPUT);
}
void loop()
{
// read the value from the sensor
sensorValue = analogRead(A0);
// turn the LED on
digitalWrite(13, HIGH);
// stop the program for the
// milliseconds
delay(sensorValue); // Wait for sensorValue millisecond(s)
// turn the LED off
digitalWrite(13, LOW);
// stop the program for the
// milliseconds
delay(sensorValue); // Wait for sensorValue millisecond(s)
}
上面程式利用analogRead讀取數值後,用來當成延成時間的數值,因此我們可以用可變電阻來改變燈光閃爍的頻率或快慢。
接下來我們來介紹類比數值由串列埠輸出,利用set視覺模組來取得A0腳位的數值,並把它放到sensorValue變數中,在利用print to serial monitor視覺模塊將值經由串列埠輸出。
程式如下:
int sensorValue = 0;
void setup()
{
pinMode(A0, INPUT);
Serial.begin(9600);
}
void loop()
{
// read the input on analog pin 0:
sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(10); // Delay a little bit to improve simulation performance
}
類比輸入轉換成電壓值的程式,把0-1023轉換0-5V,其公式為:
X=X*5.0 / 1023.0
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
沒有留言:
張貼留言