RGB 三色 LED
#define R_PIN A3 // P17
#define G_PIN A2 // P16
#define B_PIN A1 // P15
#define MAX_STEP (10)
#define IS_OVER(x) (((x) >> 8) != 0)
#define CLAMP(x) (((x) < 0)? 0: 255)
int r, g, b;
int r_dir = 1, g_dir = 1, b_dir = 1;
void setup()
{
// initialize the pin directions
pinMode(R_PIN, OUTPUT);
pinMode(G_PIN, OUTPUT);
pinMode(B_PIN, OUTPUT);
}
void loop()
{
// walk in a random step
r += random(MAX_STEP) * r_dir;
g += random(MAX_STEP) * g_dir;
b += random(MAX_STEP) * b_dir;
// check if it walks out of the boundary and thus needs to turn back
if (IS_OVER(r)) { r = CLAMP(r); r_dir = -r_dir; }
if (IS_OVER(g)) { g = CLAMP(g); g_dir = -g_dir; }
if (IS_OVER(b)) { b = CLAMP(b); b_dir = -b_dir; }
// Set the output value
analogWrite(R_PIN, r);
analogWrite(G_PIN, g);
analogWrite(B_PIN, b);
delay(50);
}Last updated

