1、setup()
当Arduino开始的时候被调用。用它来初始化变量,设置引脚运行模式,启动库文件等。setup函数只运行一次,每次上电或者被重置时候调用。
int buttonPin = 3;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop()
{
// ...
}
2、loop()
创建setup()时,该函数设置初始值等一些初始化操作。该函数是Arduino运行控制的函数,所有的实时控制逻辑都在该方法内执行。
const int buttonPin = 3;
// setup initializes serial and the button pin
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
// loop checks the button pin each time,
// and will send serial if it is pressed
void loop()
{
if (digitalRead(buttonPin) == HIGH)
Serial.write('H');
else
Serial.write('L');
delay(1000);
}
3、pinMode()
配置指定的引脚的输入或输出模式。
模式类型: INPUT, OUTPUT, or INPUT_PULLUP.
int ledPin = 13; // LED connected to digital pin 13
void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop()
{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}
4、digitalWrite()
int ledPin = 13; // LED connected to digital pin 13
void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop()
{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}
5、digitalRead()
读取指定引脚的值 HIGH或者 LOW。
int ledPin = 13; // LED connected to digital pin 13
int inPin = 7; // pushbutton connected to digital pin 7
int val = 0; // variable to store the read value
void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output
pinMode(inPin, INPUT); // sets the digital pin 7 as input
}
void loop()
{
val = digitalRead(inPin); // read the input pin
digitalWrite(ledPin, val); // sets the LED to the button's value
}
本文详细介绍了Arduino编程中常用的五个基础函数:setup()用于初始化设置;loop()负责程序的主要逻辑循环;pinMode()用于设定引脚的工作模式;digitalWrite()实现数字引脚的高低电平输出;digitalRead()则用来读取数字引脚的状态。
1067

被折叠的 条评论
为什么被折叠?



