一、教學目標:利用光敏電阻控制 LED燈:
http://yehnan.blogspot.tw/2012/02/arduino_23.html二、接線圖
三、程式碼
int photocellPin = A0; // 光敏電阻 (photocell) 接在 anallog pin A0 int photocellVal = 0; // photocell variable int minLight = 600; // 最小光線門檻值 int ledPin = 13; int ledState = 0; void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop() { // 讀取光敏電阻並輸出到 Serial Port photocellVal = analogRead(photocellPin); Serial.println(photocellVal); // 光線不足時打開 LED if (photocellVal < minLight && ledState == 0) { digitalWrite(ledPin, HIGH); // turn on LED ledState = 1; } // 光線充足時關掉 LED if (photocellVal > minLight && ledState == 1) { digitalWrite(ledPin, LOW); // turn off LED ledState = 0; } delay(100); }練習-01-加入序列埠的除錯(serial moniter)
int photocellPin = A0; // 光敏電阻 (photocell) 接在 anallog pin A0 int photocellVal = 0; // photocell variable int minLight = 800; // 最小光線門檻值 int ledPin = 13; int ledState = 0; int no=0; void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); } void loop() { // 讀取光敏電阻並輸出到 Serial Port photocellVal = analogRead(photocellPin); no++; Serial.print("test:"); Serial.print(no); Serial.print(":"); Serial.println(photocellVal); // 光線不足時打開 LED if (photocellVal < minLight && ledState == 0) { digitalWrite(ledPin, HIGH); // turn on LED ledState = 1; } // 光線充足時關掉 LED if (photocellVal > minLight && ledState == 1) { digitalWrite(ledPin, LOW); // turn off LED ledState = 0; } delay(100); }四、作業練習
1.請設定當光敏電阻的測量值小於設定值時亮紅色LED燈,否則亮綠燈。
沒有留言:
張貼留言