วันพุธที่ 8 กุมภาพันธ์ พ.ศ. 2560

การรับค่าจากสวิตซ์ Arduino C++

ในบทความตอนนี้จะเป็นการทดลองการรับค่าจากสวิตช์ ขาแต่ละขาของ Arduino
เราสามารถตัวสอบว่า ขาแต่ละขาของ Arduino เป็น HIGH(มีไฟ) หรือ LOW(ไม่มีไฟ)
ได้ด้วยคำสั่ง digitalRead(ชื่อขาที่ต้องการอ่าน)
ให้ต่อวงจรตามรูปข้างล่างนะครับ

รูปการต่อวงจร


รูปแบบของการทำงานของสวิตช์ซึ่งจะต่อวงจรดังรูปจะทำงานได้ดังนี้ เมื่อไม่กดสวิตช์ จะส่งค่า HIGH ออกไป เมื่อกดสวิตช์ จะส่งค่า LOW ออกไป 

Code( ถ้ากดปุ่ม  LED จะดับ)
 int buttonPin = 2;     // the number of the pushbutton pin
 int ledPin =  9;      // the number of the LED pin
// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
void setup() {
  // initialize the LED pin as an output:
Serial.begin(9600);
  pinMode(ledPin, OUTPUT);      
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);     
}
void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {     
    // turn LED on:    
Serial.println("turn LED on");
    digitalWrite(ledPin, HIGH);  
  } 
  else {
    // turn LED off:
Serial.println("turn LED off");
    digitalWrite(ledPin, LOW); 
  }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น