电位器
电位器
电位器模板有S-V-G,通过3P数据线,连接扩展板A0~A5任意引脚,读取模拟输入数据。
analogRead 函数
analogRead(pin) 系统自带函数,功能是从指定的模拟输入引脚(A0~A5) 读取数据值,将0~5V输入电压映射到 0~1023之间的整数值
示例代码
const int potPin=A0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
int potVal = analogRead(potPin);
Serial.print("电位器值十进制为:");
Serial.println(potVal);
Serial.print("电位器值十六进制为:");
Serial.println(potVal,HEX);
delay(5000);
}
演示效果
电位器值十进制为:1023
电位器值十六进制为:3FF
搭建效果

通过电位器控制LED的亮度
analogRead(ledPin,potVal)
对指定的led数字引脚通过PWM方式输出模拟值,指定引脚输出电压范围在0~5V
const int potPin=A0;//模拟输入引脚
const int ledPin=6;//pwm引脚 3 5 6 9 10 11
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
int potVal = analogRead(potPin);//电位器模拟输入值为0~1023
Serial.print("电位器值为:");
Serial.println(potVal);
potVal=potVal/4;//电位器范围~led pwm输出范围匹配
analogWrite(ledPin,potVal);//led模拟输出范围0~255
delay(100);
}
演示效果
1.电位器值较小,LED不亮

2.电位器值变大,LED灯变亮

练习
1.使用电位器控制LED灯由暗变亮,电位器值小灯暗,电位器值大,灯亮
2.使用电位器控制LED灯由亮变暗,电位器值小灯亮,电位器值大,灯暗
作者:newcode 更多资源请关注纽扣编程微信公众号

从事机器人比赛、机器人等级考试、少儿scratch编程、信息学奥赛等研究学习

浙公网安备 33010602011771号