6749| 2
|
[求助] 光控+PWM模拟输出 . |
按照图片所示进行连接: 光敏电阻的电阻大小与光亮度成反比,通过测量电阻的电压可以知道光敏电阻的电阻大小,从而知道光亮度。 代码: #define LED_GREEN 9//定义与绿灯连接的引脚 #define LED_RED 10//定义与红灯连接的引脚 int brightness = 0; // how bright the LED is int fadeAmount = 5; // how many points to fade the LED by void setup() { pinMode(LED_GREEN,OUTPUT); pinMode(LED_RED,OUTPUT); Serial.begin(9600); // 打开串口,设置波特率为9600 bps } void loop() { int i; while(1) { i=analogRead(5);//读模拟口5 Serial.println(i,DEC);//从串口发送字符串并换行 if(i>400)//有光时,根据实际情况修改此数值 { // set the brightness of pin 9: analogWrite(LED_GREEN, brightness); analogWrite(LED_RED, 0); // change the brightness for next time through the loop: brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = -fadeAmount ; } // digitalWrite(LED_GREEN,HIGH);//绿灯亮 // digitalWrite(LED_RED,LOW);//红灯灭 // delay(1000); //设定延时时间,1000 = 1秒 // digitalWrite(LED_GREEN,LOW);//绿灯亮 // delay(1000); //设定延时时间,1000 = 1秒 }else { // set the brightness of pin 9: analogWrite(LED_RED, brightness); analogWrite(LED_GREEN, 0); // change the brightness for next time through the loop: brightness = brightness + fadeAmount; // reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = -fadeAmount ; } // digitalWrite(LED_RED,HIGH);//红灯亮 // digitalWrite(LED_GREEN,HIGH);//绿灯灭 // delay(1000); //设定延时时间,1000 = 1秒 // digitalWrite(LED_RED,LOW);//红灯亮 // digitalWrite(LED_GREEN,LOW);//绿灯亮 // delay(1000); //设定延时时间,1000 = 1秒 } delay(30); } } 编译并上传以后,当光敏电阻无遮挡时,绿色LED从暗到亮,再从亮到暗交替进行。当遮挡住光敏电阻时,红色LED开始同样的动作。查看串口数据可以看到电阻电压的模拟值(0-1024区间,最大值1024) 这儿的代码中还有一点需要修改的地方,例如遮挡住光敏电阻,红色LED的亮度是绿色LED熄灭前最后一刻的亮度。 与光敏电阻串联的电阻值最好与光敏电阻无光时的电阻值差不多,或者略小一点,这样效果比较好 |
© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed