入门"/>
【Arduino】Arduino UNO入门
一、LED闪烁
void setup() {// initialize digital pin LED_BUILTIN as an output.pinMode(LED_BUILTIN, OUTPUT); //13脚
}// the loop function runs over and over again forever
void loop() {digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)delay(1000); // wait for a seconddigitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOWdelay(1000); // wait for a second
}
二、按键控制LED亮灭(普通输入)
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;// the setup routine runs once when you press reset:
void setup() {// initialize serial communication at 9600 bits per second:Serial.begin(9600);// make the pushbutton's pin an input:pinMode(pushButton, INPUT);
}// the loop routine runs over and over again forever:
void loop() {// read the input pin:int buttonState = digitalRead(pushButton);// print out the state of the button:Serial.println(buttonState);delay(1); // delay in between reads for stability
}
要外界上拉电阻 一般10K
三、按键控制LED亮灭(上拉输入)
void setup() {//start serial connectionSerial.begin(9600);//configure pin 2 as an input and enable the internal pull-up resistorpinMode(2, INPUT_PULLUP);pinMode(13, OUTPUT);}void loop() {//read the pushbutton value into a variableint sensorVal = digitalRead(2);//print out the value of the pushbuttonSerial.println(sensorVal);// Keep in mind the pull-up means the pushbutton's logic is inverted. It goes// HIGH when it's open, and LOW when it's pressed. Turn on pin 13 when the// button's pressed, and off when it's not:if (sensorVal == HIGH) {digitalWrite(13, LOW);} else {digitalWrite(13, HIGH);}
}
四、按键控制LED亮灭(上拉布尔型)
bool pushButton;void setup() {// put your setup code here, to run once:pinMode(2,INPUT_PULLUP);pinMode(13,OUTPUT);}void loop(){// put your main code here, to run repeatedly:pushButton=digitalRead(2);if(pushButton){ //2口上拉输入时 默认高电平 按键按下时 改为低电平 //if(!pushButton){ 上行改为这个 现象和实验三一致digitalWrite(13,HIGH);}else{digitalWrite(13,LOW);}
}
五、模拟输入按键PWM小灯
boolean pushButton1; // 创建布尔型变量用来存储按键开关1的电平状态
boolean pushButton2; // 创建布尔型变量用来存储按键开关2的电平状态
int ledPin = 13; //LED引脚号 ****实际不是他 我没有电阻 可以用别的脚,现象更明显***
int brightness = 128; //LED亮度参数void setup() {// put your setup code here, to run once:pinMode(2, INPUT_PULLUP); //将引脚2设置为输入上拉模式pinMode(8, INPUT_PULLUP); //将引脚8设置为输入上拉模式pinMode(ledPin, OUTPUT); //将LED引脚设置为输出模式Serial.begin(9600); //启动串口通讯
}void loop() {// put your main code here, to run repeatedly:pushButton1 = digitalRead(2); //读取引脚2电平状态并将其赋值给布尔变量pushButton2 = digitalRead(8); //读取引脚8电平状态并将其赋值给布尔变量if (!pushButton1 && brightness > 0){ // 当按下按键开关1并且LED亮度参数大于0brightness--; // 减低LED亮度参数//(brightness-- 相当于 brightness = brightness - 1;)} else if (!pushButton2 && brightness < 255) { //当按下按键开关2并且LED亮度参数小于255brightness++; //增加LED亮度参数//(brightness++ 相当于 brightness = brightness + 1;)}analogWrite(ledPin, brightness); //模拟输出控制LED亮度Serial.println(brightness); //将LED亮度参数显示在串口监视器上delay(10);
}
更多推荐
【Arduino】Arduino UNO入门
发布评论