Arduino内置教程-模拟-渐变
渐变
这个例子示范了怎样用模拟输出(PWM)来使LED灯变亮或者变暗。PWM是一种技巧,可以使数字引脚通过快速开关和不同的开关时间来表现出一种类似模拟的动作。
硬件要求
- Arduino 或者 Genuino 开发板
- LED
- 220 ohm 电阻
- 连接线
- 面包板
电路
一个LED灯通过一个220 ohm电阻连接到数字引脚pin9
原理图
样例代码
在这个例子里,两个循环一个接一个地执行来增加然后减少pin9的输出值
/*
Fading
This example shows how to fade an LED using the analogWrite() function.
The circuit:
* LED attached from digital pin 9 to ground.
Created 1 Nov 2008
By David A. Mellis
modified 30 Aug 2011
By Tom Igoe
http://www.arduino.cc/en/Tutorial/Fading
This example code is in the public domain.
*/
int ledPin = 9; // LED connected to digital pin 9
void setup() {
// nothing happens in setup
}
void loop() {
// fade in from min to max in increments of 5 points:
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade out from max to min in increments of 5 points:
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
更多
- for()
- analogWrite()
- delay()
- AnalogInOutSerial - 读取一个模拟输入引脚,按比例划分读数,然后用这个数据来熄灭或者点亮一个LED灯
- AnalogInput - 用电位计来控制LED灯闪烁
- AnalogWriteMega - 永一个Arduino或者Genuino Mega开发板来使12个LED灯一个接一个逐渐打开和熄灭
- Calibration - 定义期望中的模拟传感值的最大值和最小值
- Smoothing - 使多个模拟输入引脚的读取值变得平滑