本文章将教会大家如何使用Arduino制作以旋钮控制小灯明灭。
一、目标实现:
使用Arduino编程,使得扭动旋钮改变阻值从而改变LED灯明灭状态。
二、前期准备:
软件准备:Arduino 18.8
硬件准备:Arduino开发板,LED灯,220Ω电阻,面包板,杜邦线,旋钮电位器。
三、接线:
如下图:
四、编写程序:
const int analogInPin = A0;
int sensorValue = 0;
int LED_G = 2;
int LED_Y = 4;
int LED_R = 6;
void setup()
{
Serial.begin(9600);
pinMode(LED_G, OUTPUT);
pinMode(LED_Y, OUTPUT);
pinMode(LED_R, OUTPUT);
}
void loop()
{
sensorValue = analogRead(analogInPin);
Serial.println(sensorValue);
if (sensorValue == 0)
{
digitalWrite(LED_G, LOW);
digitalWrite(LED_Y, LOW);
digitalWrite(LED_R, LOW);
}
if (sensorValue > 1 && sensorValue < 250)
{
digitalWrite(LED_G, LOW);
digitalWrite(LED_Y, LOW);
digitalWrite(LED_R, HIGH);
}
if (sensorValue > 255 && sensorValue < 500)
{
digitalWrite(LED_G, LOW);
digitalWrite(LED_Y, HIGH);
digitalWrite(LED_R, LOW);
}
if (sensorValue > 510 && sensorValue < 1000)
{
digitalWrite(LED_G, HIGH);
digitalWrite(LED_Y, LOW);
digitalWrite(LED_R, LOW);
}
if (sensorValue == 1023)
{
digitalWrite(LED_G, HIGH);
digitalWrite(LED_Y, HIGH);
digitalWrite(LED_R, HIGH);
}
}
五、成果展示: