MP3 Arduino Project by Stavros

Hi. I’m a newbie at code writing. I want to check something concerning an audio project by Stavros.

http://www.soniconlab.com/blog/item/mp3-arduino

In the following code, I think “int readButtons(int pin)” is a user-defined function, as oppossed to a ready-made function from a library. And that the block of code is the code that performs the task. Is that correct? Thanks.

Actually I’m not sure what the code below produces in a practical sense. It returns the button pressed, but I see no practical result. I obviously don’t quite yet understand the project code.


int readButtons(int pin){
// returns the button number pressed, or zero for none pressed
// int pin is the analog pin number to read
int b,c = 0;
c=analogRead(pin); // get the analog value
if (c>1000 || c<100) {
b=0; // buttons have not been pressed
}
else if (c>450 && c<520){
b=1; // button 1 pressed
}
else if (c>750 && c<860){
b=2; // button 2 pressed
}
else if (c>880 && c<920){
b=3; // button 3 pressed
}
else if (c>930 && c<1000){
b=4; // button 4 pressed
}
return b;
}

You can have multiple buttons attached to the same analog input pin if each button has a different resistor value in it's cirquit (5V => Resistor => Button => Analog Input). analogRead will then return a different value for each button, and the posted function will examine the value "c" and convert it to a button number "b" which is then returned.

Ok, I'll give some thought to the explanation. Is readButtons(int pin) a creation of the code writer? I think it is, and the code after shows it's a user-defined function.

At least, someone wrote it :wink:

So, yes, "readButtons(int pin)" is a user-defined function and the code below it shows that it is. OK.

EDIT: I should have said "user-defined" in my posts, not just "defined". So, I edited. Rich

Hi. I see how the function places a result in b, and that in b is an integer between 0 and 4, but there is no use of b. I mean there is no printing of the value of b, or anything. I cannot see why the function is written, if it serves no useful purpose. Am I missing something? Rich

http://www.soniconlab.com/blog/item/mp3-arduino

Yes, you are missing the last line in "readButton" where the button number is returned. The function should be used something like this:

#define BUTTON_PIN 5

int button = readButton(BUTTON_PIN);

if (button > 0) {
  Serial.print(F("Button "));
  Serial.print(button);
  Serial.println(F(" is pressed"));
}

Hi. OK I now get it. The poject needs to be connected to a PC via a serial connection to make use of the function. Thanks.