开关控制LED

使用按钮开关控制LED,按下开关时LED亮起,松开开关后LED关闭。

一、工具原料

1、零知ESP32:http://www.lingzhilab.com/home/introduction.html?gid=184
2、按钮开关
3、220Ω电阻
4、LED

二、连线

三、代码


												
	// set pin numbers
	const int buttonPin = 4;     // the number of the pushbutton pin
	const int ledPin =  16;      // the number of the LED pin
	 
	// variable for storing the pushbutton status 
	int buttonState = 0;
	 
	void setup() {
	  // initialize the pushbutton pin as an input
	  pinMode(buttonPin, INPUT);
	  // initialize the LED pin as an output
	  pinMode(ledPin, OUTPUT);
	}
	 
	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
	    digitalWrite(ledPin, HIGH);
	  } else {
	    // turn LED off
	    digitalWrite(ledPin, LOW);
	  }
	}				
					

导入程序代码,在右侧选择ESP32开发板,然后验证程序,如图: