//Incrementing Motor Speed Control
一開始motor=9
const int MOTOR = 9; //Motor connected to digital pin 9
const int BUTTON = 2; //Button connected to pin 2
boolean lastButton = LOW; //Variable containing the previous
//button state
boolean currentButton = LOW; //Variable containing the current
//button state
int speedIncrement = 0;
void setup()
{
pinMode (MOTOR, OUTPUT); //Set the MOTOR pin as an output
pinMode (BUTTON, INPUT); //Set button as an input
}
/*
* Debouncing Funtion
* Pass it the previous button state,
* and get back the current debounced button state.
*/
boolean debounce(boolean last)
{
boolean current = digitalRead(BUTTON); //Read the button state
if (last != current) //if it's different
{
delay(5); //wait 5ms
current = digitalRead(BUTTON); //read it again
}
return current;
}
/*
*Motor Speed Selection
*Pass a number for the Motor speed and set it
*/
void setSpeed(int increment)
{
//speed one
if (increment == 1)
{
analogWrite(MOTOR, 110);
}
else if (increment == 2)
{
analogWrite(MOTOR, 150);
}
else if (increment == 3)
{
analogWrite(MOTOR, 180);
}
else if (increment == 4)
{
analogWrite(MOTOR, 200);
}
else if (increment == 5)
{
analogWrite(MOTOR, 255);
}
//OFF
else
{
analogWrite(MOTOR, 0);
}
}
void loop()
{
currentButton = debounce(lastButton); //read debounce state
&&:且為兩個條件組合起來
if (lastButton == LOW && currentButton == HIGH) //if it was pressed
{
speedIncrement++; //Increment motor speed
}
lastButton = currentButton; //reset button value
//if cycled through all speed increments
//reset the speed to 0
if (speedIncrement == 6) speedIncrement = 0;
setSpeed(speedIncrement);
}
沒有留言:
張貼留言