Program Arduino : Saklar Lampu On/Off Satu Tombol

Buatlah skema modul seperti gambar di atas, kemudian upload sketch di bawah ini :

const int buttonPin = 2;    
const int ledPin = 13;
 int x = 1;

 // This will store the last known state of the button
int oldButtonState = LOW;

void setup() {   
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);   
  pinMode(ledPin, OUTPUT);  
}


void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH && oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}

Semoga terinspirasi !
Previous
Next Post »