Stap 3: Het toevoegen van fundamentele analoge ingangen
De volgende input die we zullen proberen is een analoge ingang. De meeste sensoren geven een soort analoge signaal, voor dit voorbeeld zullen we met behulp van een potentiometer. De code zal lezen de potentiometer, en alleen verder zodra de gewenste waarde wordt bereikt.
Draad van de potentiometer volgens het diagram en upload de onderstaande code.
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 an analog input can be used to move through a switch statement. The potentiometer must be moved to the desired value before advancing to the next stage in the program. Written by Progressive Automations Sept 21, 2015 This code is in the public domain */ const int pot = A0;//attach the pot to pin A0 int potValue = 0;//variable to hold the pots reading int programCount = 0;//variable to move through the program void setup() { Serial.begin(9600);// initialize serial communication: pinMode(pot, INPUT); //set the pot as an input programCount = 0;//start at the beginning of the program Serial.println("Move the potentiometer to the desired locations to advance"); }//end setup void loop() { switch (programCount) { case 0: potValue = analogRead(pot);//read the pot's value Serial.println("Move the potentiometer fully to one side to get the max reading"); while (potValue <= 1000)//1023 is max value { potValue = analogRead(pot);//read the pot's value delay(10);//small delay between readings } Serial.println(potValue);//show what the reading is Serial.println("One limit reached!"); Serial.println("");//print an extra line if (potValue >= 1000) programCount = 1;//once the value is at the desired position, move on break; case 1: potValue = analogRead(pot);//read the pot's value Serial.println("Move the potentiometer to the middle"); while (potValue >= 500)//~512 is the middle { potValue = analogRead(pot);//read the pot's value delay(10);//small delay between readings } Serial.println(potValue);//show what the reading is Serial.println("Middle position reached!"); Serial.println("");//print an extra line if (potValue <= 500) programCount = 2;//once the value is at the desired position, move on break; case 2: potValue = analogRead(pot);//read the pot's value Serial.println("Move the potentiometer fully to the other side to get the min reading"); while (potValue >= 10)//0 is min value { potValue = analogRead(pot);//read the pot's value delay(10);//small delay between readings } Serial.println(potValue);//show what the reading is Serial.println("Final limit reached!"); Serial.println("");//print an extra line if (potValue <= 10) programCount = 3;//once the value is at the desired position, move on break; default: Serial.println("Program complete"); while (1); //freeze the program here }//end switch }//end loop