|
本帖最后由 topdog 于 2021-12-22 00:34 编辑
本例采用Nano,按键使用中断,第2、3管脚为中断口,分别对应中断0、中断1。本例接到第2管脚,当引脚电平由低电平变为高电平时触发中断服务程序,特别注意按钮开关的接法。实现呼吸灯就要用到PWM功能,Nano板子上有六个引脚支持PWM输出,分别是引脚3,5,6,9,10,11。本例发光二极管正极接到第3管脚。多彩灯选用一颗WS2812,采用Adafruit NeoPixel库,原件的VDD:D=device 表示器件的意思, 即器件内部的工作电压(接电源),VSS:S=series 表示公共连接的意思,通常指电路公共接地端电压(接地),din接第4管脚。旋转电位器接A0。
接线图如下:
程序如下:
[pre]//https://github.com/adafruit/Adafruit_NeoPixel
#include <Adafruit_NeoPixel.h>
const int ButtonPin = 2;
const int LedPin = 3;
const int PIXEL_PIN = 4;
const int PIXEL_COUNT = 1;
volatile int potentiometer = 0;
volatile boolean state = false;
Adafruit_NeoPixel PIXEL(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);
void setup() {
Serial.begin(9600);
pinMode(ButtonPin, INPUT_PULLUP);
pinMode(LedPin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(ButtonPin), Button, RISING);
PIXEL.begin();
PIXEL.show();
}
void loop() {
potentiometer = analogRead(A0);
Serial.println(potentiometer);
delay(100);
if (state == true) {
Blink();
ShowRGB();
}
}
void Button() {
state = !state;
}
void colorWipe(uint32_t color, int wait) {
PIXEL.setPixelColor(PIXEL_COUNT, color);
PIXEL.show();
delay(wait);
}
void Blink() {
for (int i = 0; i <= 255; i += 10) {
analogWrite(LedPin, i);
delay(100);
}
for (int i = 255; i >= 0; i -= 10) {
analogWrite(LedPin, i);
delay(100);
}
}
void ShowRGB() {
PIXEL.setBrightness(255); //Brightness
if (potentiometer <= 350) {
colorWipe(PIXEL.Color(255, 0, 0), 50); // Red
} else if (potentiometer > 350 || potentiometer <= 700) {
colorWipe(PIXEL.Color(51, 204, 0), 50); // Yellow
} else if (potentiometer > 700 ||potentiometer <= 1024) {
colorWipe(PIXEL.Color(0, 255, 0), 50); // Green
}
}[/pre] |
|