Arduino控制器
时间: 2024-06-18 17:04:46 浏览: 11
Arduino是一款便携式开源电子原型平台,由一个硬件和一个软件构成。Arduino板子上有微控制器,它可以通过Arduino软件编程来控制外围设备,以实现各种各样的交互效果。Arduino板子可以用于各种各样的交互项目,例如音频、视觉、环境感知、机器人和艺术项目,因此非常受欢迎。
以下是一些简单的Arduino控制器示例:
1. 点亮LED灯:让LED灯亮或熄灭是使用Arduino的最简单的项目之一。在这个例子中,我们将使用数字引脚13,将其设置为“输出”模式,并使其在不断闪烁。
```arduino
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
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
}
```
2. 按钮控制LED灯:在这个例子中,我们将使用数字引脚2连接按钮,并使用数字引脚13连接LED。如果按下按钮,则LED将亮起,否则LED将关闭。
```arduino
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop() {
buttonState = digitalRead(buttonPin); // read the state of the pushbutton value:
if (buttonState == HIGH) { // check if the pushbutton is pressed.
digitalWrite(ledPin, HIGH); // turn LED on:
} else {
digitalWrite(ledPin, LOW); // turn LED off:
}
}
```
3. 通过串口控制LED灯:在这个例子中,我们将使用串行通信,通过电脑控制LED灯。如果从串口接收到“H”,则LED灯将亮起,如果从串口接收到“L”,则LED将关闭。
```arduino
char data = 0; // variable to store the received data
void setup() {
Serial.begin(9600); // initialize serial communication at 9600 bits per second
pinMode(13, OUTPUT); // initialize digital pin 13 as an output:
}
void loop() {
if (Serial.available() > 0) { // if data is available to read:
data = Serial.read(); // read it and store it in 'data'
if (data == 'H') { // if 'H' was received:
digitalWrite(13, HIGH); // turn ON the LED
} else if (data == 'L') { // if 'L' was received:
digitalWrite(13, LOW); // turn OFF the LED
}
}
}
```