具体讲解
接线
我有一个光敏电阻连接到模拟引脚0(任何模拟引脚都可以工作)和面包板右侧的5V电压。它通过接地的1K欧姆电阻器运行。我将面包板另一侧的LED(任何颜色)连接到数字引脚13(任何数字引脚都可以工作)和接地的220欧姆电阻(100欧姆也可以工作)。在第一个LED的右侧,通过不同的数字引脚,以相同的方式为不同颜色的LED接线。
这个怎么运作
如果光敏电阻读取的值大于450,则显示“It is quite light!”。在串行监视器上,然后关闭所有LED,如下所示:
if(light > 450) { // If it is bright...
Serial.println("It is quite light!");
digitalWrite(13,LOW); //turn left LED off
digitalWrite(12,LOW); // turn right LED off
}
如果读取的值介于230到450之间,则会打印“It is average light!”。在串行监视器上,并打开左侧的LED,如下所示:
else if(light > 229 && light < 451) { // If it is average light...
Serial.println("It is average light!");
digitalWrite(13, HIGH); // turn left LED on
digitalWrite(12,LOW); // turn right LED off
}
这仅使我们得到低于230的值。如果该值小于230,则打印“It is quite dark!”。在串行监视器上,并打开两个LED,如下所示:
else { // If it's dark...
Serial.println("It is pretty dark!");
digitalWrite(13,HIGH); // Turn left LED on
digitalWrite(12,HIGH); // Turn right LED on
}
我在循环末尾添加了1000的延迟,以防止信息超载到串行监视器中,如下所示:
delay(1000); // don't spam the computer!
电路连接
代码实现
int light = 0; // store the current light value
void setup() {
// put your setup code here, to run once:
Serial.begin(9600); //configure serial to talk to computer
pinMode(13, OUTPUT); // configure digital pin 13 as an output
pinMode(12, OUTPUT); // configure digital pin 12 as an output
}
void loop() {
// put your main code here, to run repeatedly:
light = analogRead(A0); // read and save value from PR
Serial.println(light); // print current light value
if(light > 450) {
// If it is bright...
Serial.println("It is quite light!");
digitalWrite(13,LOW); //turn left LED off
digitalWrite(12,LOW); // turn right LED off
}
else if(light > 229 && light < 451) {
// If it is average light...
Serial.println("It is average light!");
digitalWrite(13, HIGH); // turn left LED on
digitalWrite(12,LOW); // turn right LED off
}
else {
// If it's dark...
Serial.println("It is pretty dark!");
digitalWrite(13,HIGH); // Turn left LED on
digitalWrite(12,HIGH); // Turn right LED on
}
delay(1000); // don't spam the computer!
}