Hi all,
I am new to Arduino and am trying to port some old PIC Basic code to Arduino.
I include three working snippets. The first sketch uses goto's and is similar to the original basic version.
The second sketch uses a do..while loop. The third uses a function which is what I want to use.
Am I going in the right direction or can it be done smarter??
Thanks in advance!
/*
File: wait4Key.ino
sketch ported from Basic using goto's
determines button key number
tested ok
*/
const int BENTER = 11; // ENTER BUTTON
const int BDOWN = 12; // DOWN BUTTON
const int BUP = 13; // UP BUTTON
int key, i;
void setup() {
pinMode(BENTER, INPUT_PULLUP);
pinMode(BUP, INPUT_PULLUP);
pinMode(BDOWN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop(){
wait4Key: // Capture button key
key = 0;
if (digitalRead(BUP) == LOW) key = 1; // Up button pressed
if (digitalRead(BDOWN) == LOW) key = 2;
if (digitalRead(BENTER) == LOW) key = 3;
if (key == 0) goto wait4Key;
debounce: // Wait for button release and debounce
if (digitalRead(BUP) == LOW) i = 0;
if (digitalRead(BDOWN) == LOW) i = 0;
if (digitalRead(BENTER) == LOW) i = 0;
i++;
delay (10);
if (i < 10) goto debounce;
Serial.print("key = "); Serial.println(key);
}
/*
File: wait4key2.ino
sketch now using do...while instead of goto's
determines button key number
tested ok
*/
const int BENTER = 11; // ENTER BUTTON
const int BDOWN = 12; // DOWN BUTTON
const int BUP = 13; // UP BUTTON
int key, i;
void setup() {
pinMode(BENTER, INPUT_PULLUP);
pinMode(BUP, INPUT_PULLUP);
pinMode(BDOWN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop(){
do {
key = 0;
if (digitalRead(BUP) == LOW) key = 1; // Up button pressed etc
if (digitalRead(BDOWN) == LOW) key = 2;
if (digitalRead(BENTER) == LOW) key = 3;
} while (key == 0);
do {
if (digitalRead(BUP) == LOW) i = 0;
if (digitalRead(BDOWN) == LOW) i = 0;
if (digitalRead(BENTER) == LOW) i = 0;
i++;
delay (10);
} while (i < 10); // Wait for button release and debounce
Serial.print("key = "); Serial.println(key);
}
/*
File: wait4Key3.ino
sketch now using a function
determines button key number and debounce
tested ok
*/
const int BENTER = 11; // ENTER BUTTON TO PIN 11
const int BDOWN = 12; // DOWN BUTTON
const int BUP = 13; // UP BUTTON
int key;
void setup() {
pinMode(BENTER, INPUT_PULLUP);
pinMode(BUP, INPUT_PULLUP);
pinMode(BDOWN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop(){
wait4Key();
Serial.print("key = "); Serial.println(key);
}
int wait4Key() {
int i;
do {
key = 0;
if (digitalRead(BUP) == LOW) key = 1; // Up button pressed
if (digitalRead(BDOWN) == LOW) key = 2;
if (digitalRead(BENTER) == LOW) key = 3;
} while (key == 0);
do {
if (digitalRead(BUP) == LOW) i = 0;
if (digitalRead(BDOWN) == LOW) i = 0;
if (digitalRead(BENTER) == LOW) i = 0;
i++;
delay (10);
} while (i < 10); // Wait for button release and debounce
}