#define ledR (12)
#define ledG (11)
#define ledBrd (13)
#define sw1 (2)
#define SW_ON (0)
#define SW_OFF (1)
#define LED_ON (1)
#define LED_OFF (0)
#define interval (500)
// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;
// will store last time LED was updated
//现在状态
unsigned char swState;
//过去状态
unsigned char swPrevState;
unsigned char ledState;
unsigned char ledBlinkState;
// the setup function runs once when you press reset or power the board
void
setup() {
// initialize digital pin 13 as an output.
pinMode(ledBrd, OUTPUT);
pinMode(ledR, OUTPUT);
pinMode(ledG, OUTPUT);
pinMode(ledB, OUTPUT);
pinMode(sw1, INPUT);
ledAllOff();
digitalWrite(ledBrd,LOW);
delay(100);
swState=swPrevState=digitalRead(sw1);
ledState=LED_OFF;
ledBlinkState=LOW;
}
void ledAllOff()
{
digitalWrite(ledR,HIGH);
digitalWrite(ledG,HIGH);
digitalWrite(ledB,HIGH);
}
// the loop function runs over and over again forever
void loop() {
swState=digitalRead(sw1);
if(swState ==SW_ON && swPrevState==SW_OFF)
{
if(ledState == LED_ON)
{
ledState = LED_OFF;
}
else
{
ledState = LED_ON;
}
}
swPrevState = swState;
if(ledState == LED_ON)
{
//blink();
blinkWithoutDelay();
}
else
{
ledAllOff();
}
}
void blink()
{
digitalWrite(ledBrd, HIGH);
// turn the LED on (HIGH is the voltage level)
digitalWrite(ledB,LOW);
delay(500);
// wait for a second
digitalWrite(ledBrd, LOW);
// turn the LED off by making the voltage LOW
digitalWrite(ledB,HIGH);
delay(500);
// wait for a second
}
void blinkWithoutDelay()
{
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval)
{
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledBlinkState == LOW)
{
ledBlinkState = HIGH;
}
else
{
ledBlinkState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(ledBrd, ledBlinkState); // turn the LED on (HIGH is the voltage level)
digitalWrite(ledB,ledBlinkState);
}
}