深入了解ArduinoC编程基础
立即解锁
发布时间: 2025-08-20 01:16:46 阅读量: 1 订阅数: 4 


Arduino C语言编程入门与实践
### 深入了解Arduino C编程基础
#### 1. 第一个Arduino程序
在Arduino C编程中,我们首先来看一个简单的示例程序:
```cpp
void setup()
{ // Start of setup() function body
Serial.begin(115200);// Step 1, Initialization
// Step 2, Input (the letters between the quotes)
// Step 3. Process – Serial object formats data for display
// Step 4. Output – Display the message on the monitor
Serial.println("This is my first Arduino program!");
} // End of setup() function body
void loop()
{ // Start of loop() function body
} // End of loop() function body
```
这个程序包含了`setup()`和`loop()`两个函数,这是每个Arduino程序都必须有的。
#### 2. `setup()`函数
`setup()`函数的作用是设置程序运行的环境,它在程序启动时只执行一次。在上述示例中,`Serial.begin(115200);`这一语句初始化了`Serial`对象,用于后续的数据传输,这里的`115200`是波特率。而`Serial.println("This is my first Arduino program!");`语句则完成了输入、处理和输出的过程:
- **输入**:双引号内的字符序列是程序的输入数据。
- **处理**:`Serial`对象将这些字符转换为适合显示的格式,使用的是ASCII字符集。例如,显示器上显示的大写字母A,处理器看到的是整数值65。
- **输出**:`println()`方法将处理后的消息显示在`Serial`监视器上。
#### 3. `loop()`函数
`loop()`函数在`setup()`函数执行完毕后开始执行,并且会不断循环执行。在最初的示例中,`loop()`函数体为空,程序看似结束,但实际上Arduino程序会持续在空的`loop()`函数中循环,直到断电或出现组件故障。
我们可以通过修改程序来验证`loop()`函数的循环特性,将`setup()`函数中的最后一条语句移到`loop()`函数中:
```cpp
void setup()
{ // Start of setup() function body
Serial.begin(115200);// Step 1, Initialization
// Step 2, Input (the letters between the quotes)
// Step 3. Process – Serial object formats data for display
// Step 4. Output – Display the message on the monitor
} // End of setup() function body
void loop()
{ // Start of loop() function body
Serial.println("This is my first Arduino program!");
} // End of loop() function body
```
重新编译并上传程序后,`Serial`监视器会不断显示消息,这表明`loop()`函数在不断重复执行。
`loop()`函数的这种特性在很多实际应用中非常有用。例如,在一个有100个火灾传感器的建筑物中,程序可以在`loop()`函数中不断循环读取每个传感器的数据:
```cpp
void loop()
{
int sensorIndex;
int fire;
for (sensorIndex = 1; sensorIndex <= 100; sensorIndex = sensorIndex + 1) {
fire = ReadSensor(sensorIndex); // Return 1 if fire, 0 otherwise
if (fire == 1) { // If fire, do the following statements...
SoundAlarm();
TurnOnSprinklerSystem();
CallFireDepartment();
WaitForAllClear();
}
// If fire equals 0, go read the next sensor
}
}
```
这个程序会不断循环检查每个传感器,直到检测到火灾或出现其他异常情况。
#### 4. Arduino程序要求
- 每个Arduino程序必须有`setup()`函数,用于初始化。
- `setup()`函数在程序启动时只执行一次。
- 每个Arduino程序必须有`loop()`函数,用于重复执行任务。
- `loop()`函数会不断循环,直到断电、程序重置或组件故障。
#### 5. 示例程序流程图
```mermaid
graph TD;
A[开始] --> B[执行setup()函数];
B --> C[初始化Serial对象];
C --> D[输入数据];
D --> E[处理数据];
E --> F[输出数据到监视器];
F --> G[执行loop()函数];
G --> H{是否有任务};
H -- 是 --> I[执行任务];
I --> G;
H -- 否 --> G;
```
#### 6. Blink程序
Arduino IDE自带了许多示例程序,其中一个是Blink程序。要加载Blink程序,可通过`File ➤ Examples ➤ Basics ➤ Blink`菜单序列操作。其源代码如下:
```cpp
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
```
#### 7. 程序注释
程序注释用于解释代码的功能和意图,帮助他人(也包括自己)理解代码。注释分为单行注释和多行注释:
- **单行注释**:以`//`开头,从`//`到行末的内容都是注释,编译器会忽略这些内容。例如:`// Pin 13 has an LED connected on most Arduino boards.`
- **多行注释**:以`/*`开头,以`*/`结尾,可以跨越多行。例如:
```cpp
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and
Leonardo, it is attached to digital pin 13. If you're unsure what
pin the on-board LED is connected to on your Arduino model, check
the documentation at http://arduino.cc
This example code is in the public domain.
modified 8 May 2014
by Scott Fitzgerald
*/
```
注释的使用需要适度,过多或过少的注释都不利于代码的理解。一般来说,在函数块前或执行特殊操作的代码行前使用多行注释,在需要解释的特殊代码行使用单行注释。例如:
```cpp
x = y * .5; // Divide the number in half
```
#### 8. `setup()`函数在Blink程序中的作用
在Blink程序中,`setup()`函数只有一条语句`pinMode(13, OUTPUT);`,它调用了`pinMode()`函数,该函数是Arduino IDE提供的标准函数库中的函数,用于设置引脚的使用方式。这里将引脚13设置为输出引脚,因为大多数Arduino板的引脚13连接着一个内置LED,通过设置为输出引脚,就可以通过软件控制LED的开关。
#### 9. 查找库函数信息
如果想了解Arduino标准库中某个函数的详细信息,可以访问`http://arduino.cc/en/Reference/HomePage`。在搜索框中输入函数名(如`pinMode()`),点击放大镜图标进行搜索,搜索结果通常会显示相关的Google页面。也可以通过双击函数名并右键选择`Find in Reference`来查找详细描述。
#### 10. 引脚设置总结
| 引脚设置 | 描述 |
| ---- | ---- |
| `pinMode(13, OUTPUT);` | 将引脚13设置为输出引脚 |
| `pinMode(13, INPUT);` | 将引脚13设置为输入引脚 |
#### 11. 注意事项
- 对于一些没有内置LED的“自制”Arduino板,可以将LED的阳极连接到引脚13,阴极通过一个220 - 1000欧姆的电阻连接到地,这样在运行Blink程序时,外部LED也会闪烁。
- `setup()`函数在程序启动时只执行一次,如果需要再次执行,可按下开发板的复位按钮或重新上电。在大多数较新的Arduino板上,每次从PC上传新的程序代码时,`setup()`函数会自动调用。
### 深入了解Arduino C编程基础(续)
#### 12. 深入理解`loop()`函数在Blink程序中的应用
在Blink程序里,`loop()`函数实现了LED的闪烁效果。其代码如下:
```cpp
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
```
这个`loop()`函数的执行流程如下:
- 首先,`digitalWrite(13, HIGH);`将引脚13的电压设置为高电平,从而点亮连接在该引脚的LED。
- 接着,`delay(1000);`让程序暂停1000毫秒(即1秒),使LED保持点亮状态。
- 然后,`digitalWrite(13, LOW);`将引脚13的电压设置为低电平,熄灭LED。
- 最后,再次使用`delay(1000);`让程序暂停1秒,使LED保持熄灭状态。
之后,`loop()`函数会不断重复这个过程,从而实现LED的闪烁效果。
#### 13. 程序执行流程图
```mermaid
graph TD;
A[开始] --> B[执行setup()函数];
B --> C[设置引脚13为输出];
C --> D[执行loop()函数];
D --> E[点亮LED];
E --> F[延时1秒];
F --> G[熄灭LED];
G --> H[延时1秒];
H --> D;
```
#### 14. 常见函数总结
| 函数 | 描述 |
| ---- | ---- |
| `Serial.begin(115200);` | 初始化`Serial`对象,设置波特率为115200 |
| `Serial.println("message");` | 输出消息到`Serial`监视器 |
| `pinMode(pin, OUTPUT);` | 将指定引脚设置为输出引脚 |
| `pinMode(pin, INPUT);` | 将指定引脚设置为输入引脚 |
| `digitalWrite(pin, HIGH);` | 将指定引脚的电压设置为高电平 |
| `digitalWrite(pin, LOW);` | 将指定引脚的电压设置为低电平 |
| `delay(milliseconds);` | 让程序暂停指定的毫秒数 |
#### 15. 代码优化建议
- **减少魔法数字**:在代码中直接使用数字(如13、1000)会降低代码的可读性。可以使用常量或变量来代替这些数字,例如:
```cpp
const int LED_PIN = 13;
const int DELAY_TIME = 1000;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(DELAY_TIME);
digitalWrite(LED_PIN, LOW);
delay(DELAY_TIME);
}
```
这样,代码的含义更加清晰,后续修改也更加方便。
- **添加注释**:虽然前面已经提到注释的重要性,但在代码优化时,更要注意注释的使用。例如,在关键代码行或函数前添加注释,解释其功能和目的。
#### 16. 实际应用场景拓展
- **传感器监测**:除了火灾传感器监测,还可以使用`loop()`函数实现其他传感器的监测,如温度传感器、湿度传感器等。例如,每隔一段时间读取一次传感器数据,并根据数据做出相应的处理。
```cpp
const int SENSOR_PIN = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(SENSOR_PIN);
Serial.print("Sensor Value: ");
Serial.println(sensorValue);
delay(1000);
}
```
- **控制多个设备**:可以在`loop()`函数中控制多个设备的运行。例如,同时控制多个LED的闪烁,或者控制电机的转动。
#### 17. 总结
通过对Arduino C编程基础的学习,我们了解了`setup()`和`loop()`函数的重要性,掌握了程序注释的使用方法,学会了如何设置引脚和调用标准库函数。同时,我们还通过Blink程序和其他示例代码,深入理解了这些知识在实际应用中的使用。在编写Arduino程序时,要注意代码的可读性和可维护性,合理使用注释和常量,避免使用魔法数字。通过不断实践和学习,我们可以开发出更加复杂和实用的Arduino项目。
#### 18. 实践建议
- **自己动手编写代码**:不要只是阅读示例代码,要亲自编写一些简单的程序,如控制LED闪烁、读取传感器数据等,通过实践加深对知识的理解。
- **修改示例代码**:尝试对现有的示例代码进行修改,改变参数或添加功能,观察程序的运行结果,从而更好地掌握代码的工作原理。
- **参考其他项目**:在网络上搜索其他Arduino项目,学习他人的代码和设计思路,从中获取灵感和经验。
0
0
复制全文
相关推荐










