Stap 2: Het toevoegen van fundamentele digitale ingangen
Nu dat we de basisprincipes van een instructie switch weet, kunnen we in een basic digitale ingang toevoegen. Gebruiken we een knop voor het activeren van de beweging over naar het volgende frame.
In het eerste geval, zullen wij een teller gebruiken om te slaan hoe lang de knop is ingedrukt. Zodra het heeft plaatsgevonden gedurende 5 seconden, gaan we naar het volgende frame. Bekijk de seriële monitor om te zien wanneer het programma wordt gedaan.
Zie de onderstaande code, en vervolgens uploaden om te zien hoe het werkt voordat u naar de volgende stap.
Aangezien dit slechts test programma's, kunt u het bord aangesloten op de computer, zodat de Arduino macht kan ontvangen.
/* This code is to show how a digital input can move through cases in a switch statement. The button must be pressed 5 times to move on. Written by Progressive Automations Sept 21, 2015 This code is in the public domain */ const int button = 5;//attach the button on pin 5 int programCount = 0;//variable to move through the program int buttonCount = 0;//variable to hold the button presses int buttonState = 1;//variable to hold the state of the button void setup() { Serial.begin(9600);// initialize serial communication: programCount = 0;//start at the beginning buttonCount = 0;//set to 0 to start pinMode(button,INPUT);//set the button as an input digitalWrite(button, HIGH);//enable internal pullup resistor Serial.println("Hold the button for 5 seconds to complete the program"); }//end setup void loop() { switch (programCount) { case 0: buttonState = digitalRead(button); if (buttonState==0) { buttonCount = buttonCount+1;//count up every time the button is pressed delay(1);//small delay for counting milliseconds } if (buttonCount == 5000) programCount = 1;//once the button is pressed enough times, move on break; case 1: Serial.println("Button has been held for 5 seconds");//print the number delay(1000); programCount = 2; break; default: Serial.println("Program complete"); while(1); //freeze the program here }//end switch }//end loop