江启明 发表于 2016-3-11 16:53:57

关于arduino通过按键控制WS2812灯带闪亮问题

本帖最后由 江启明 于 2016-3-11 17:02 编辑

请教一下,我是通过arduino接按键然后控制WS2812闪亮,显示不同效果,但是现在通过按键按下不能马上切换到下一种效果运行,只有当前程序效果运行完然后才执行按键的下一次效果。我是用按键计数然后选择switch case里面执行的,请问该如何修改让按键按下后能立即切换到下一种效果运行。部分程序如下:
const intbuttonPin = 4;
// 定义用来记录按键次数的整型变量
int num = 0;
// 记录当前按键的状态
int buttonState=0;
// 记录按键之前的状态
int lastButtonState = 0;
// 对Arduino电路板或相关状态进行初始化方法
void setup()
{
// 设置按键的针脚为输入状态
pinMode(buttonPin, INPUT);
// 开启串行通信,并设置其频率为9600。
// 如果没有特别要求,此数值一般都为9600。
//MsTimer2::set(10, flash);      // 中断设置函数,每 10ms 进入一次中断
//MsTimer2::start();                //开始计时
Serial.begin(9600);
strip.begin();
strip.show(); // Initialize all pixels to 'off'
//attachInterrupt(0, stateChange, LOW);//zhong duan
}
// 系统调用,无限循环方法
void loop()
{
digitalWrite(4,HIGH);
// 读取按键的输入状态
buttonState = digitalRead(buttonPin);
// 判断当前的按键状态是否和之前有所变化
   if (buttonState != lastButtonState)
{
    // 判断当前按键是否为按下状态,
    // 如果为按下状态,则记录按键次数的变量加一。
    if(buttonState == LOW)
    {
      // 将记录按键次数的变量加一
      num++;
   if(num>=8)
      {
         num=1;
      }
    }
    // 为了避免信号互相干扰,
    // 此处将每次按键的变化时间间隔延迟50毫秒。
    delay(50);
// 将每次loop结束时最新的按键状态进行更新
lastButtonState = buttonState;
}
    Serial.print("num= ");
    // 接着上一行尾部,打印记录按键次数变量的数值。
    Serial.println(num);
switch(num)
{
    case 1:
      // Some example procedures showing how to display to the pixels:
      colorWipe(strip.Color(255, 0, 0), 50); // Red
      break;
    case 2:
      colorWipe(strip.Color(0, 255, 0), 50); // Green
      break;
    case 3:
      colorWipe(strip.Color(0, 0, 255), 50); // Blue
      break;
    case 4:
      // Send a theater pixel chase in...
      theaterChase(strip.Color(127, 127, 127), 50); // White
      theaterChase(strip.Color(127,   0,   0), 50); // Red
      theaterChase(strip.Color(0,   0, 127), 50); // Blue
      break;
   case 5:
      rainbow(10);
      rainbowCycle(10);
      theaterChaseRainbow(20);
      break;
   case 6:
      StrobA(0xff, 0xff, 0xff, 10, 50, 1000);//white
      StrobB(0xff, 0xff, 0xff, 10, 50, 1000);//white
      StrobC(0xff, 0xff, 0xff, 10, 50, 1000);//white
      break;
   case 7:
      StrobD(0xff, 0xff, 0xff, 10, 50, 1000);//white
      StrobB(0xff, 0xff, 0xff, 10, 50, 1000);//white
      break;
}
}

zjz5717 发表于 2016-3-11 21:54:14

可以考虑使用中断函数

江启明 发表于 2016-3-12 11:59:39

因硬件电路中断引脚上没有接按键,所以不好用外部中断进行。:)

書雲 发表于 2017-12-4 16:28:00

这个库是什么?Adafruit_NeoPixe??
页: [1]
查看完整版本: 关于arduino通过按键控制WS2812灯带闪亮问题