3色LEDにサインカーブでPWMをかけ、できるだけ美しく色変化をかけたい。実はこれは前にもやったが、もうちょっとコードを美しくしたいのであった。
3項演算子があったらなあ……。
// // sinCurvePWM.ino // 3色LEDをできるだけ幻想的に美しく光らせたい。 // 佐藤俊夫 // 27.06.27(土) // const int R = 9, G = 10, B = 11; // void setup() { pinMode(R, OUTPUT); pinMode(G, OUTPUT); pinMode(B, OUTPUT); } void loop() { static float thetaR = 0.0, thetaG = 0.0, thetaB = 0.0; const float PI2 = 2.0 * PI; const float Rtic = PI2 / 1000.0, Gtic = PI2 / 900.0, Btic = PI2 / 1100.0; thetaR += Rtic; thetaG += Gtic; thetaB += Btic; if(thetaR >= PI2) thetaR = 0.0; if(thetaG >= PI2) thetaG = 0.0; if(thetaB >= PI2) thetaB = 0.0; analogWrite(R, 255 - sin255(thetaR)); analogWrite(G, 255 - sin255(thetaG)); analogWrite(B, 255 - sin255(thetaB)); delay(20); } int sin255(float theta){ return((int)((sin(theta) + 1.0) * 127.5)); }
「美しくLチカ」への1件のフィードバック