EasyManua.ls Logo

SunFounder 3in1 Kit - Page 145

Default Icon
351 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
SunFounder 3in1 Kit
1 the next, and so on alternately.
buttonState and lastButtonState are used to record the state of the button this time and the
last time, to compare whether the button was pressed or released.
2. Initialize each pin and set the baud rate of the serial monitor.
void setup() {
pinMode(buttonPin, INPUT);
Serial.begin(9600);
pinMode(motorPinA,OUTPUT);
pinMode(motorPinB,OUTPUT);
}
3. First read the state of the button, and if the button is pressed, the variable detectionState will switch its value
from 0 to 1 or 1 to 0. When detectionState is 1, the motor will be turned. It has the effect that this time the
button is pressed, the motor turns, the next time the button is pressed, the motor stops, and so on alternately.
void loop() {
// Toggle the detectionState each time the button is pressed
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
detectionState=(detectionState+1)%2;
Serial.print("The detection state is: ");
Serial.println(detectionState);
}
delay(50);
}
lastButtonState = buttonState;
// According to the detectionState, start the motor
if(detectionState==1){
digitalWrite(motorPinA,HIGH);
digitalWrite(motorPinB,LOW);
}else{
digitalWrite(motorPinA,LOW);
digitalWrite(motorPinB,LOW);
}
}
The entire workflow is as follows.
Read the button value.
buttonState = digitalRead(buttonPin);
If buttonState and lastButtonState are not equal, it means that the button state has
changed, continue with the next judgment, and store the button state at this time into the variable
lastButtonState. delay(50) is used to eliminate jitter.
if (buttonState != lastButtonState) {
...
delay(50);
}
lastButtonState = buttonState;
4.5. 5. More Syntax 141

Related product manuals