七色灯控制系统
开发原理
七彩循环主要是依靠光的叠加原理,利用光的三基色组合成其他的颜色,实现七彩循环:
红、
绿、
红+绿=黄、
蓝、
红+绿=紫、
绿+蓝=青、
红+蓝+绿=白。
实验代码
#define led_r 2//红色引脚
#define led_g 3//绿色引脚
#define led_b 4//蓝色引脚
#define key 5//按键引脚
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
void scan_key();
void change_color();
void lcd_hanshu();
unsigned char key_num = 0;
unsigned char color_value = 0;
//枚举类型,定义了一串类型
enum { color_r, color_g, color_b, color_rg, color_rb, color_gb, color_rgb };
//红 绿 蓝 黄 紫 青 白
void setup() {
//设置输出
pinMode(led_r, OUTPUT);
pinMode(led_g, OUTPUT);
pinMode(led_b, OUTPUT);
pinMode(key, INPUT_PULLUP);
change_color(color_rgb);
lcd_hanshu();
}
void loop() {
scan_key();//按键扫描
if (key_num == 1) {//按键执行程序
key_num = 0;//清空标志位
change_color(color_value);//切换颜色
color_value++;//颜色变量进行加一操作
if (color_value == color_rgb + 1) {
//当颜色变量 == 7
color_value = color_r;//颜色变量清零
}
}
}
void lcd_hanshu() {
lcd.init();
lcd.backlight();
}
//选择颜色的函数
void change_color(unsigned char data_color) {
switch (data_color)
{
//红色
case color_r: {
lcd.init();
digitalWrite(led_r, HIGH);
digitalWrite(led_g, LOW);
digitalWrite(led_b, LOW);
lcd.print("red");
break;
}
//绿色
case color_g:
{
lcd.init();
digitalWrite(led_r, LOW);
digitalWrite(led_g, HIGH);
digitalWrite(led_b, LOW);
lcd.print("green");
break;
}
//蓝色
case color_b:
{
lcd.init();
digitalWrite(led_r, LOW);
digitalWrite(led_g, LOW);
digitalWrite(led_b, HIGH);
lcd.print("blue");
break;
}
//紫色
case color_rb:
{
lcd.init();
digitalWrite(led_r, HIGH);
digitalWrite(led_g, LOW);
digitalWrite(led_b, HIGH);
lcd.print("purple");
break;
}
//黄色
case color_rg:
{
lcd.init();
digitalWrite(led_r, HIGH);
digitalWrite(led_g, HIGH);
digitalWrite(led_b, LOW);
lcd.print("yellow");
break;
}
//青色
case color_gb:
{
lcd.init();
digitalWrite(led_r, LOW);
digitalWrite(led_g, HIGH);
digitalWrite(led_b, HIGH);
lcd.print("cyan");
break;
}
//白色
case color_rgb:
{
lcd.init();
digitalWrite(led_r, HIGH);
digitalWrite(led_g, HIGH);
digitalWrite(led_b, HIGH);
lcd.print("white");
break;
}
default: {
break;
}
}
}
void scan_key() {
//按键扫描
if (digitalRead(key) == 0) {
//查看按键是否按下
delay(20);//延时20ms
if (digitalRead(key) == 0) {
//查看按键是否按下
key_num = 1;
while (digitalRead(key) == 0) {
//松手检测
}
}
}
}