极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 22350|回复: 3

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

[复制链接]
发表于 2016-3-11 16:53:57 | 显示全部楼层 |阅读模式
本帖最后由 江启明 于 2016-3-11 17:02 编辑

请教一下,我是通过arduino接按键然后控制WS2812闪亮,显示不同效果,但是现在通过按键按下不能马上切换到下一种效果运行,只有当前程序效果运行完然后才执行按键的下一次效果。我是用按键计数然后选择switch case里面执行的,请问该如何修改让按键按下后能立即切换到下一种效果运行。部分程序如下:
const int  buttonPin = 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;
  }
}
回复

使用道具 举报

发表于 2016-3-11 21:54:14 | 显示全部楼层
可以考虑使用中断函数
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-3-12 11:59:39 | 显示全部楼层
因硬件电路中断引脚上没有接按键,所以不好用外部中断进行。
回复 支持 反对

使用道具 举报

发表于 2017-12-4 16:28:00 | 显示全部楼层
这个库是什么  ?Adafruit_NeoPixe??
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-17 00:09 , Processed in 0.043044 second(s), 20 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表