LED闪烁

1
2
3
4
5
6
7
8
9
10
11
12
//当你给开发板通电后或者按下复位按钮后,setup函数运行一次
int setup(){
//初始化LED_BUTLTIN数字引脚为输出模式
pinMod(LED_BUILTIN,OUTPUT);
}
//loop 函数永远会反复的运行
int loop(){
digitalWrit(LED_BUILTIN,HIGH); //点亮LED(高电平)
delay(1000); //等待1秒
digitalWrite(LED_BUILTIN,LOW); //将电平设置为低来熄灭LED
delay(1000); //等待1秒
}

HIGH有电流
LOW没电流
pinMode()
说明
通过pinMode()函数,你可以将Arduino的引脚配置为以下三种模式:

  • 输出(OUTPUT)模式
  • 输入(INPUT)模式
  • 输入上拉(INPUT_PULLUP)模式 (仅支持Arduino 1.0.1以后版本)
    在输入上拉(INPUT_PULLUP)模式中,Arduino将开启引脚的内部上拉电阻,实现上拉输入功能。一旦将引脚设置为输入(INPUT)模式,Arduino内部上拉电阻将被禁用。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    //引脚2链接有按键开关,给他一个名字:
    int pushButton=2;
    void setup(){
    //串口通信初始化,每秒9600位
    Serial.begin(9600);
    //设置按键引脚为输入
    pinMode(pushButton,INPUT);
    }
    void loop(){
    //读取输入引脚:
    int buttonState=digitalRead(pushButton);
    //显示按键状态
    Serial.println(buttnState);
    delay(1); //为确保程序稳定运行进行短暂停止
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24

    void setup() {
    //start serial connection
    Serial.begin(9600);
    //configure pin 2 as an input and enable the internal pull-up resistor
    pinMode(2, INPUT_PULLUP);
    pinMode(13, OUTPUT);
    }

    void loop() {
    //read the pushbutton value into a variable
    int sensorVal = digitalRead(2);
    //print out the value of the pushbutton
    Serial.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);
    }
    }