本帖最后由 i7456 于 2014-1-23 15:51 编辑
[mw_shl_code=c,true]
// constants won't change. Used here to
// set pin numbers:
const int ledPin = 13; // the number of the LED pin
const int buttonPin = 7;
// Variables will change:
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated
boolean state = false;
// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 100; // interval at which to blink (milliseconds)
void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop()
{
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
if(digitalRead(buttonPin)==LOW)
{
delay(40);
if(digitalRead(buttonPin)==HIGH)
state = !state;
}
//增加下面两行,解决常亮的问题
if(!state)
digitalWrite(ledPin,LOW);
if((currentMillis - previousMillis > interval) && state){
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
if(ledState == LOW)
Serial.println(LOW);
else Serial.println (HIGH);
}
[/mw_shl_code]
|