6713| 2
|
[进阶] RGB渐变灯 |
[mw_shl_code=cpp,true]int RedPin = 9; int GreenPin = 10; int BluePin = 3; int cycleVal; int RedVal=0; int GreenVal=0; int BlueVal=0; float sinRed; float sinGreen; float sinBlue; void setup() { pinMode(RedPin,OUTPUT); pinMode(GreenPin,OUTPUT); pinMode(BluePin,OUTPUT); } void loop() { //设定周期值360 cycleVal++; //判断周期值是否小于180 然后点亮红灯 if(cycleVal<180) { sinRed=sin(cycleVal*(3.1412/180)); RedVal=int((1-sinRed)*255); //应该等价于 sinRed<<8? analogWrite(RedPin,RedVal); } //判断周期值是否在90~180之间点亮绿灯 if(cycleVal>90 && cycleVal<180) { //绿灯0~90度的周期所以要减去90 sinGreen=sin((cycleVal-90)*(3.1414/180)); GreenVal=int((1-sinGreen)*255); analogWrite(GreenPin,GreenVal); } //判断周期是否在180~360之间点亮蓝灯 if(cycleVal>180) { //蓝灯0~90度的周期所以要减去180 sinBlue=sin((cycleVal-180)*3.1412/180); BlueVal=int((1-sinBlue)*255); analogWrite(BluePin,BlueVal); } //周期值不能大于360 if(cycleVal>360)cycleVal=0; //50ms的延时效果不错 delay(50); }[/mw_shl_code] 做了一个十分简单的RGB渐变灯小程序,重新复习了一下的三角函数。 |
© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed