Arduino之炫彩RGB LED

文章介绍了共阳极RGBLED的基本原理,展示了如何通过随机颜色变化、炫彩效果以及制作交通灯来运用RGBLED。使用了PWM控制LED亮度,并提供了相应的代码示例。
摘要由CSDN通过智能技术生成

共阳RGB就是把阳极拉到一个公共引脚,其他三个端则是阴极。

共阴RGB就是把阴极拉到一个公共引脚,其他三个端则是阳极。

本实验采用共阳极RGB,共用端需要接5V,而不是GND,否则LED不能被点亮。

一、LED颜色随机变化

原理图:

实物图:

参考代码:

int redPin = 9;
int greenPin = 10;
int bluePin = 11;

void setup(){
    pinMode(redPin, OUTPUT);
    pinMode(greenPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
}

void loop(){
//R:0-255 G:0-255 B:0-255
    colorRGB(random(0,255),random(0,255),random(0,255));
    delay(1000);
}

void colorRGB(int red, int green, int blue){
    analogWrite(redPin,constrain(red,0,255));
    analogWrite(greenPin,constrain(green,0,255));
    analogWrite(bluePin,constrain(blue,0,255));
}

二、炫彩LED

用红色、绿色、蓝色、黄色、青色、品红色和白色交替点亮RGB LED,并在每种颜色上暂停1秒。

不同的PWM值所组合产生的颜色(共阳极RGB LED)

颜色

红色

绿色

蓝色

红色

0

255

255

绿色

255

0

255

蓝色

255

255

0

黄色

0

0

255

青色

255

0

0

品红

0

255

0

白色

0

0

0

参考代码:

int redPin=9;
int greenPin=11;
int bluePin=10;

void setup() {
  // put your setup code here, to run once:
  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
  pinMode(bluePin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  colorRGB(0,255,255);//red
  delay(1000);
  colorRGB(255,0,255);//green
  delay(1000);
  colorRGB(255,255,0);//blue
  delay(1000);
  colorRGB(0,0,255);//yellow
  delay(1000);
  colorRGB(255,0,0);//青色
  delay(1000);
  colorRGB(0,255,0);//品红
  delay(1000);
  colorRGB(0,0,0);//白
  delay(1000);
}

void colorRGB(int red,int green,int blue)
{
  analogWrite(redPin,constrain(red,0,255));
  analogWrite(greenPin,constrain(green,0,255));
  analogWrite(bluePin,constrain(blue,0,255));
}

三、由RGB LED制作的交通灯。

要求实现红灯亮10秒,绿灯亮10秒,黄灯亮3

参考代码:

int redPin=9;
int greenPin=11;
int yellowPin=10;

void setup() {
  // put your setup code here, to run once:
  pinMode(redPin,OUTPUT);
  pinMode(greenPin,OUTPUT);
  pinMode(yellowPin,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  colorRGB(0,255,255);//red
  delay(10000);
  colorRGB(255,0,255);//green
  delay(10000);
  //yellow
  for(int i = 0; i < 3; i++) { // 闪烁3次,每次闪烁持续500ms,间隔500ms
    colorRGB(0, 0, 255); // 黄色亮
    delay(500);
    colorRGB(0, 0, 0); // 黄色灭
    delay(500);
  }
}
void colorRGB(int red,int green,int yellow)
{
  analogWrite(redPin,constrain(red,0,255));
  analogWrite(greenPin,constrain(green,0,255));
  analogWrite(yellowPin,constrain(yellow,0,255));
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值