|
本帖最后由 henrypcw 于 2016-3-7 12:12 编辑
闲来无事做了一个电子色子, 和女儿一起玩飞行棋.
所需材料如下:
1. arduino pro mini 一块
2. 倾斜开关 一个
3. 蜂鸣器 一个
4. ws2812 LED灯 九颗
[mw_shl_code=cpp,true]
#include <FastLED.h>
//LED数量
#define NUM_LEDS 9
//ws2812的数据针脚
#define PIN 6
//蜂鸣器针脚
#define BeepPin 4
//倾斜开关针脚
#define inPin 9
CRGB leds[NUM_LEDS];
CRGB Dice[6][9]={{CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Red,CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Black},
{CRGB::Aqua,CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Aqua},
{CRGB:imeGreen,CRGB::Black,CRGB::Black,CRGB::Black,CRGB:imeGreen,CRGB::Black,CRGB::Black,CRGB::Black,CRGB:imeGreen},
{CRGB::Black,CRGB::Blue,CRGB::Black,CRGB::Blue,CRGB::Black,CRGB::Blue,CRGB::Black,CRGB::Blue,CRGB::Black},
{CRGB::Black,CRGB::Green,CRGB::Black,CRGB::Green,CRGB::Green,CRGB::Green,CRGB::Black,CRGB::Green,CRGB::Black},
{CRGB::Orange,CRGB::Orange,CRGB::Orange,CRGB::Black,CRGB::Black,CRGB::Black,CRGB::Orange,CRGB::Orange,CRGB::Orange}};
boolean bb=false;
boolean AA=false;
int count=0;
int AC=0;
static unsigned long printTime=0;
char r=0;
int runLen=0;
void setup(){
pinMode(inPin, INPUT);
pinMode(BeepPin, OUTPUT);
FastLED.addLeds<WS2812B, PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(20);
randomSeed(analogRead(A0)+millis());
printTime=getTick(0,true);
}
void setAll(int rc,int gc,int bc){
for(int i = 0 ; i < NUM_LEDS; i++ ){
if(rc>=0) leds.r=rc;
if(gc>=0) leds.g=gc;
if(bc>=0) leds.b=bc;
}
FastLED.show();
}
void setI(int i,int rc,int gc,int bc){
if(i<0||i>=NUM_LEDS) return;
if(rc>=0) leds.r=rc;
if(gc>=0) leds.g=gc;
if(bc>=0) leds.b=bc;
}
void setICRGB(int i,CRGB cr){
if(i<0||i>=NUM_LEDS) return;
leds=cr;
}
void setAllCRGB(CRGB cr){
for(int i = 0 ; i < NUM_LEDS; i++ ){
leds=cr;
}
FastLED.show();
}
void setAllList(CRGB *cr){
for(int i = 0 ; i < NUM_LEDS; i++ ){
leds=cr;
}
FastLED.show();
}
void loop() {
if(count>1){
AA=true;
printTime=getTick(0,true);
count=0;
}else{
if(digitalRead(inPin)==HIGH&&!bb&&!AA){
count++;
bb=true;
}else if(digitalRead(inPin)==LOW)
bb=false;
}
if(AA&&getTick(printTime,false)>120){
runLen=0;
do{
runLen+=random(50)+random(runLen);
r=random(6);
setAllList(Dice[r]);
if(runLen<500) delay(runLen);
}while(runLen<500);
beep(r);
AA=false;
count=0;
bb=false;
}
}
void beep(char c){
switch(c){
case 0:
beep_short(1,50,50);
break;
case 1:
beep_short(2,200,20);
break;
case 2:
beep_short(3,200,20);
break;
case 3:
beep_short(4,100,20);
break;
case 4:
beep_short(5,100,20);
break;
case 5:
beep_short(1,100,200);
break;
}
}
void beep_short(int n,int len,int l){
for(int j=0;j<n;j++){
for(int i=0;i<2;i++){
digitalWrite(BeepPin, HIGH);
delay(l);
digitalWrite(BeepPin, LOW);
delay(l);
}
delay(len);
}
}
unsigned long getTick(unsigned long pMMillis,boolean getNow) {
if(getNow) return millis();
unsigned long currentMillis = millis();
if(currentMillis < pMMillis) {
return (currentMillis+(4294967295 - pMMillis + 1));
}else
return (currentMillis-pMMillis);
}[/mw_shl_code]
|
|