Posts with «button» label

Maker Display to Ubidots MQTT button


See the original project on the ArduinoBasics Blog

 
 

Description

This tutorial will show you how to create a simple MQTT connection to Ubidots. You will also learn to configure the necessary MQTT subscription to a button on the Ubidots dashboard, and control a Maker Display (ESP-12E compitible board) from anywhere in the world. The process may seem a bit daunting at first, but hopefully by the end of this tutorial, you will feel comfortable creating your own Ubidots MQTT subscriptions.

 
 

Parts Required

  1. Maker Display 2 or Node MCU (ESP-12E) module
  2. NOVA programmer
  3. USB mini-B cable
  4. WiFi internet connection
  5. Ubidots account (free)

The Maker display 2 has an inbuilt ESP8266MCD WiFi module which will be used to create the MQTT connection to the Ubidots broker (online).

 
 

Ubidots Setup

This tutorial requires a FREE Ubidots account.
Go to this site to sign up: https://ubidots.com/education/
Once signed up, you will need to configure Ubidots using the following instructions.

Create a device

  1. Select: Devices > Devices
  2. Select: Create a Device (button)
  3. Select: Blank (from the available device list)
  4. Enter the "Maker Display" into the "Device name" field, "maker-display" into the "Device label" field, and click on "Create" button
  5. Select: the "Maker Display" device

Create a variable

  1. Select: "Add Variable" button, then select "Raw" from the two available options.
  2. Select: the "New Variable" to edit it
  3. Change the name to "Button 1", the description to "button1 variable" and the API label to "button1"

Create a dashboard

  1. Select: Data > Dashboard
  2. Select: Add new dashboard
  3. Change the Name to "Maker Display Dashboard", and update the date format to a suitable format. (press tick)

Add a Widget

  1. Select: "Add new Widget"
  2. Select: Switch (from the available widgets)
  3. Select: Add Variables
  4. Select: Maker Display > Button1 > tick
  5. Accept the default values for the Switch (Off=0, On=1), and press the tick
  6. You should now have a button called "Button1" associated with the "Maker Display" device, visible on the "Maker Display Dashboard"
  7. The button is "off".

Create a Ubidots TOKEN

  1. Select: "API Credentials" from the profile drop-down box in the top right corner.
  2. Click the blue "More" - located below the Tokens section
  3. Click on the round blue (+) button to create a NEW TOKEN.
  4. Change the name to "Maker Display Token" - and keep a record of TOKEN value. There is an icon which will allow you copy the TOKEN value to the clipboard.

Take note of key information

Now that the Ubidots Dashboard is set up, you will need to ensure you have 3 sets of information to insert into the code.

  1. Maker Display Token Value
  2. Button1 API label: "button1"
  3. Maker Display Device API Label: "maker-display"

 
 

Ubidots slideshow of the setup process

Slide Set created by Scott C with GoConqr

 
 

Arduino IDE

While there are many Arduino IDE alternatives out there, I would recommend that you use the official Arduino IDE for this project. I used the official Arduino IDE app (v1.8.5) for Windows 10.
Make sure to get the most up-to-date version for your operating system here.

Additional Boards Manager URLS

Make sure to add the following URLs to your "additional boards manager URL" setting:
  • File > Preferences > Additional Boards Manager URLS:
    • http://arduino.esp8266.com/stable/package_esp8266com_index.json
    • https://dl.espressif.com/dl/package_esp32_index.json

Select Tools > Board: "NodeMCU 1.0 (ESP-12E Module)" board.
Then check that you have the following settings:

  • Board:"NodeMCU 1.0 (ESP-12E Module)"
  • Flash Size:"4M(no SPIFFS)"
  • Debug port:"Disabled"
  • Debug Level:"None"
  • IwIP Variant:"v2 Lower Memory"
  • VTables:"Flash"
  • CPU Frequency:"80 MHz"
  • Exceptions:"Disabled"
  • Upload Speed:"115200"
  • Erase Flash:"Only Sketch"
  • Port: (Select your port)
  • Get Board Info
  • Programmer:"AVRISP mkII"


 
 

Libraries required

This tutorial makes use of two libraries: ESP8266WiFi.h and PubSubClient.h.

  • ESP8266WiFi.h : This library is required for the WiFi connection to the internet. More info.
  • PubSubClient.h : Is used to create an MQTT Client to handle the communication between the Ubidots MQTT broker and the Maker Display2 (or ESP-12E).

Both libraries can be installed via the library manager: Sketch > Include library > Manage Libraries



 
 
 
 

Arduino Code

Connect the NOVA programmer to the Maker Display 2

Remember that you will need to insert the 3 bits of information from the "Ubidots" section, into the code. You will also need to know your WiFI SSID name, and password. Copy the code below into the Arduino IDE, make the necessary changes in the sketch to reflect the API labels and tokens from your Ubidots account. Connect the USB cable to the computer, select the correct COM port (Tools > Port), then upload the code to the Maker display board.

The code is available on my GitHub repository. Or you can have a look at the fully commented code below.

 
 

Open the Serial monitor (ctrl + shift + M), ensure the Baud is set to 9600, and then press the button on the Ubidots Maker Display Dashboard. You should see messages appear in the Serial monitor that correspond with the state of the button.

 
 

Code Explained

A number of different information sources were utilised to construct the code above. These sources were acknowledged within. As noted before, the code uses two libraries, one to simplify the WiFi connection to the internet, and the other to simplify the connection of the Maker Display to the Ubidots MQTT broker.

setup()

The setup() function is used to establish the WiFi connection, set the MQTT broker, and define the callback function - which will be called each time the button on the Ubidots dashboard is pressed.

loop()

The loop() function is responsible for connecting to the MQTT broker, and polling for messages from the MQTT broker using the client.loop() function.

callback()

The callback() function first checks the "topic" message coming from the MQTT broker, and compares it to the buttonTopic variable. The buttonTopic variable in this sketch is equal to "/v1.6/devices/maker-display/button1/lv". You will notice that the variable is constructed using the "device API label", and the "button API label". The other components of the buttonTopic are always the same. eg.

"/v1.6/devices/{device label}/{variable label}/lv"

This comparison allows us to differentiate this particular button from other potential components on the Ubidots dashboard. The value of the button (on=1/off=0), is transmitted from the MQTT broker each time the button is pressed on the Ubidots Maker Display dashboard. It is captured by the "payload" variable in the callback function. If the payload variable is equal to 1 (on), then a Serial message will be transmitted "BUTTON ON". If the payload variable is equal to 0 (off), then a Serial message will be transmitted "BUTTON OFF". You will be able to see this message come through by opening the Serial Monitor (ctrl+shift+M) within the Arduino IDE.

MQTTconnect()

The MQTTconnect() function is responsible for connecting to the MQTT broker. It requires a Ubidots TOKEN, a unique MQTT client name and a pre-defined port (1883). In order to receive messages from the button on the Ubidots Maker Display dashboard, we need to subscribe to button. But first we need to construct the string location of the button variable.  
 
We do this using the sprintf() function.  
 
If you would like to learn more about the sprintf function have a look at my tutorial here.  
 
The sprintf function is used to construct the string in a specific format, and in this case it uses the DEVICE_LABEL, and VARIABLE_LABEL1, and assigns the string to the buttonTopic variable. Once constructed the buttonTopic variable is used to subscribe to the button on the Ubidots dashboard.

The program is instructed to retry the connection attempt every 2 seconds if it fails to connect for any reason.

 
 

Project in Action


 
 

Conclusion

Setting up the Ubidots dashboard and the Arduino IDE takes up the majority of the time in this project. Once all the configurations are made, the rest is pretty simple. I hope by the end of this tutorial, you will have learnt how to create a button on a Ubidots dashboard, and interface it with a Maker Display (ESP-12 compatible board).

While there are plenty of examples on the Ubidots website that will show you how to push data to the dashboard, I found that the opposite was not true. There are limited examples that show you how to control your device from a Ubidots widget. I know that this example is not that exciting, but hopefully, you understand the significance of the information, and understand how easy it would be to modify the sketch above to make it more exciting. However, I did not want to over-complicate the tutorial with other complexities. Perhaps in the next tutorial we will use the information gained here, to do something a bit more thrilling. But at least now you know the basics. We can now:

  • Program a Maker Display
  • Add widgets to a Ubidots dashboard
  • Control the Maker Display using widgets from a Ubidots dashboard (using MQTT)

If you found this tutorial helpful, please consider supporting me by buying me a virtual coffee/beer.

$3.00 AUD only
 

Social Media

You can find me on various social networks:

Follow me on Twitter: ScottC @ArduinoBasics.
I can also be found on Instagram, Pinterest, and YouTube.
And if all else fails, I have a server on Discord.



             

Universal Remote a Grove Infrared project


 
 

Description

This project will convert an ordinary Keyes infra-red (IR) remote
into a programmable universal remote.

 
A single button press on the Keyes remote will be converted into precise Sony IR signal combinations using an Arduino UNO and an assortment of Seeedstudio Grove modules.
You can assign signal combinations from more than one remote if desired.
An example combination could be to:
  • Turn on the TV and then switch channels.
  • Turn on the TV, sound system, and air-conditioner.
  • Turn up the volume x 3.
With only one button press of the Keyes remote, the entire cascade of Sony signals ensues. This project can be customised for other IR methodologies, however, you may have to modify the Arduino code to accommodate them.

 
 

Parts Required

  1. Arduino Uno (or compatible board)
  2. Grove Base Shield (v2)
  3. Grove Infrared Receiver
  4. Grove Infrared Emitter
  5. Grove Button
  6. Grove 16x2 LCD (White on Blue)
  7. Grove Universal 4 pin buckled cable: one supplied with each module.
  8. KEYES IR Remote Control
  9. SONY IR remote control
  10. USB cable - to power and program the Arduino
  11. Battery pack / Power bank

 
 

More information about the Grove modules can be found here:

**Please Note: The Grove Base shield has 14 pins on the Analog side, and 18 pins on the digital side. Check the number of pins on your Arduino UNO (or compatible board) to ensure the shield will sit nicely on top. NOT compatible with Arduino boards that have the Arduino Duemilanove pin header layout.

 
 

Arduino IDE

While there are many Arduino IDE alternatives out there, I would recommend that you use the official Arduino IDE for this project. I used the official Arduino IDE app (v1.8.5) for Windows 10.
Make sure to get the most up-to-date version for your operating system here.


 
 

Libraries required

The following libraries will be used in the Arduino code:

  1. Wire Library
  2. IRLib2 Library
  3. rgb_lcd Library

Wire Library

The Wire library is used for I2C communication for the Grove LCD screen and is built into the Arduino IDE - no additional download required for this library.
 

IRLib2 Library

The IRLib2 Library is actually a "set" of IR libraries, which can be downloaded from GitHub - here. In this project, I will be transmitting and receiving NEC and Sony IR remote signals.
The required libraries (within the set) will be:
  • IRLibRecv.h
  • IRLibDecodeBase.h
  • IRLibSendBase.h
  • IRLib_P01_NEC.h
  • IRLib_P02_Sony.h
  • IRLibCombo.h
Please see the IRLib2 GitHub Page for installation instructions.
 

rgb_lcd Library

The rgb_lcd.h library simplifies the operation of the LCD screen.
Download the rgb_lcd.h library from GitHub. Install the rgb_lcd.h library ZIP file into the Arduino IDE:
  1. Load the Arduino IDE
  2. Navigate to Sketch >Include library > Add .ZIP library...
  3. Select the downloaded zip file from GitHub, and press the "Open" button
  4. Check that it installed correctly by navigating to File > Examples > Grove-LCD RGB Backlight

 
 
 
 

Arduino Code

It is always best to upload the Arduino code to the board before you make any of the connections. This way you prevent the Arduino from sending current to a component accidentally. The code is available on my GitHub repository. Or you can have a look below. This code was written for an Arduino UNO, and may need to be modified if you are using a different board.

 
 
 
 

Connection instructions

If you are using the Grove Base Shield (v2). The connections are extremely simple. Use the following table as a guide. Please note that the code above assumes the following connections.
 

 

As per the table above, you would use a Grove universal 4-pin buckled cable and connect one side to D2 on the Grove base shield, and the other side would connect to the Grove Infrared Emitter.
D3 on the base shield would connect to the Grove Infrared Receiver, and so on.
You can connect the 16x2 LCD module to ANY of the four I2C connectors on the Grove base shield.

If you do not have a Grove Base shield, you have the option to use female-to-male jumper wires (together with a breadboard). But it is easier just to get the base shield and use the universal connectors.

 
 
 
 
 
 

Project Explained

When you apply power to the Arduino, the first thing that appears on the LCD screen is:
 


 
After pressing the Grove button (connected to D5), it displays the following message:
 

 
This is the cue to press and send a signal from the Keyes remote to the Infrared receiver (which is connected to D2). The Arduino will decode the Keyes remote signal, store the value in an array, and display the signal briefly on the LCD. The LCD should now show a message:
 

 
This message is a cue to press and send the FIRST signal from the Sony remote to the Infrared receiver. The Arduino will decode and store the Sony remote signal in a different array, and display it briefly on the LCD. You have the option to send a maximum of THREE Sony signal combinations to the Infrared receiver at this step in the process. The minimum number of Sony signals you can send is zero. The way to tell the Arduino that you do not want to send any further Sony signals to the receiver in this step, is by pressing the Grove Button (connected to D5).
 
The Arduino is programmed to receive a total of 5 Keyes signals, and each signal can be paired with a maximum of 3 Sony signal combinations. Once you have recorded all of the signal combinations, you will get a message:
 

 
The Arduino will now enter the final "Universal remote mode". In this mode, it will listen out for ANY of the 5 Keyes IR remote signals recorded previously, and will send the associated Sony signal combination in return. For example, if you press the number 1 on the Keyes remote, you could potentially have it so that the Arduino will transmit a Sony signal combination to turn on the TV and jump to a specific channnel.
 
The LCD will display each of the signals being transmitted. You will know you are in "Universal remote" mode because the LCD will display:
 

 
While you may be tempted to throw your Sony remote away at this stage (because you no longer have a use for it)... I would hold on to it just in case. The signals are not stored permanently. They disappear when the Arduino is powered off. But it doesn't have to be that way. You can easily modify the code to store it in eeprom memory or something.
 
That is not the only thing you can change.Technically, you could record the signal for any remote, however, you may need to include additional libraries or code to accommodate the alternate remote symbology. You can also modify the text messages on the LCD screen to make more sense to you. The LCD can only display 16 characters per row. So keep that it mind, when you come up with creative captions.
 
I would also like to mention the reason I chose not to use Seeedstudio's IR library, was because it took up too much memory. Their library probably accommodates for a wide range of symbologies. I chose the IRLib2 Library because I could select only the symbologies that I used (Sony and NEC). Thereby reducing the total amount of memory necessary to run the project. In fact, I have been finding that many of Seeedstudio's libraries to be very memory hungry. I originally wanted to create a gesture controlled remote. But the library combinations eliminated that possibility due to the cumulative memory requirements.
 
 
 
 

Conclusion

The IRLib2 library is the key to the success of this project. Without that library, this project would have been ten times harder. I was quite amazed by the effectiveness of this record / playback technique. It felt very weird to be operating my SONY TV with a cheap and nasty Keyes remote. It was quite surreal. While I chose to control my TV in this way, I could have just as easily recorded signals from one of my other remotes that use infrared signals. As more and more devices become controllable by remotes, the more I will consider turning this project into a permanent fixture in my house. A gesture controlled remote would have been nice, however, it looks like I will have to find some other use for that module now.

If you found this tutorial helpful, please consider supporting me by buying me a virtual coffee/beer.

$3.00 AUD only
 

Social Media

You can find me on various social networks:

Follow me on Twitter: ScottC @ArduinoBasics.
I can also be found on Instagram, Pinterest, and YouTube.
And if all else fails, I have a server on Discord.



             

Arduino BeatBox

Create your very own Arduino BeatBox !

Home-made capacitive touch sensors are used to trigger the MP3 drum sounds stored on the Grove Serial MP3 player. I have used a number of tricks to get the most out of this module, and I was quite impressed on how well it did. Over 130 sounds were loaded onto the SDHC card. Most were drum sounds, but I added some farm animal noises to provide an extra element of surprise and entertainment. You can put any sounds you want on the module and play them back quickly. We'll put the Grove Serial MP3 module through it's paces and make it into a neat little BeatBox !!


Key learning objectives

  • How to make your own beatbox
  • How to make capacitive drum pad sensors without using resistors
  • How to speed up Arduino's Analog readings for better performance
  • How to generate random numbers on your Arduino


Parts Required:

Making the drum pads


 
 

Fritzing Sketch


 


 
 

Grove Connections


 


 
 

Grove Connections (without base shield)


 


 
 

Arduino Sketch


 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

/* =================================================================================================
      Project: Arduino Beatbox
       Author: Scott C
      Created: 9th April 2015
  Arduino IDE: 1.6.2
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This project uses home made capacitive sensors to trigger over 130 MP3 sounds
               on the Grove Serial MP3 player. 
               
               The ADCTouch library is used to eliminate the resistors from the Capacitive sensing circuit. 
               The code used for capacitive sensing was adapted from the ADCTouch library example sketches. 
               You can find the ADCTouch library and relevant example code here:
               http://playground.arduino.cc/Code/ADCTouch
               
               "Advanced Arduino ADC" is used to improve the analogRead() speed, and enhance the
               drum pad or capacitive sensor response time. The Advanced Arduino ADC code 
               was adapted from this site:
               http://www.microsmart.co.za/technical/2014/03/01/advanced-arduino-adc/
               
               
=================================================================================================== */
  #include <ADCTouch.h>
  #include <SoftwareSerial.h>
  
  
  //Global variables
  //===================================================================================================
  int potPin = A4; //Grove Sliding potentiometer is connected to Analog Pin 4
  int potVal = 0;
  byte mp3Vol = 0; //Variable used to control the volume of the MP3 player
  byte oldVol = 0;
  
  int buttonPin = 5; //Grove Button is connected to Digital Pin 5
  int buttonStatus = 0;
  
  byte SongNum[4] = {0x01,0x02,0x03,0x04}; //The first 4 songs will be assigned to the drum pads upon initialisation
  byte numOfSongs = 130; //Total number of MP3 songs/sounds loaded onto the SDHC card
  
  long randNumber; //Variable used to hold the random number - used to randomise the sounds.
  
  int ledState[4]; //Used to keep track of the status of all LEDs (on or off)
  int counter = 0;
  
  SoftwareSerial mp3(3, 4); // The Grove MP3 Player is connected to Arduino digital Pin 3 and 4 (Serial communication)
       
  int ref0, ref1, ref2, ref3; //reference values to remove offset
  int threshold = 100;
      
  // Define the ADC prescalers
  const unsigned char PS_64 = (1 << ADPS2) | (1 << ADPS1);
  const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
  
  
  
  //Setup()
  //===================================================================================================
  void setup(){
    //Initialise the Grove MP3 Module
    delay(2500); //Allow the MP3 module to power up
    mp3.begin(9600); //Begin Serial communication with the MP3 module
    setPlayMode(0x00);                        //0x00 = Single song - played once ie. not repeated. (default)
    
    //Define the Grove Button as an INPUT
    pinMode(buttonPin, INPUT);
    
    //Define the 4 LED Pins as OUTPUTs
    pinMode(8, OUTPUT); //Green LED
    pinMode(9, OUTPUT); //Blue LED
    pinMode(10, OUTPUT); //Red LED
    pinMode(11, OUTPUT); //Yellow LED
    
    //Make sure each LED is OFF, and store the state of the LED into a variable.
    for(int i=8;i<12;i++){
      digitalWrite(i, LOW);
      ledState[i-8]=0;
    } 
    
    //Double our clock speed from 125 kHz to 250 kHz
    ADCSRA &= ~PS_128;   // set up the ADC
    ADCSRA |= PS_64;    // set our own prescaler to 64
    
    //Create reference values to account for the capacitance of each pad.
    ref0 = ADCTouch.read(A0, 500);
    ref1 = ADCTouch.read(A1, 500); //Take 500 readings
    ref2 = ADCTouch.read(A2, 500);
    ref3 = ADCTouch.read(A3, 500);
    
     //This helps to randomise the drum pads.
     randomSeed(analogRead(0));
  }
  
  
  
  // Loop()
  //===================================================================================================
  void loop(){
     
    //Take a reading from the Grove Sliding Potentiometer, and set volume accordingly
    potVal = analogRead(potPin);
    mp3Vol = map(potVal, 0, 1023, 0,31); // Convert the potentometer reading (0 - 1023) to fit within the MP3 player's Volume range (0 - 31)
    if((mp3Vol>(oldVol+1))|(mp3Vol<(oldVol-1))){ // Only make a change to the Volume on the Grove MP3 player when the potentiometer value changes
      oldVol = mp3Vol;
      setVolume(mp3Vol);
      delay(10); // This delay is necessary with Serial communication to MP3 player
    }
    
    //Take a reading from the Pin attached to the Grove Button. If pressed, randomise the MP3 songs/sounds for each drum pad, and make the LEDs blink randomly.
    buttonStatus = digitalRead(buttonPin);
    if(buttonStatus==HIGH){
      SongNum[0]=randomSongChooser(1, 30);
      SongNum[1]=randomSongChooser(31, 60);
      SongNum[2]=randomSongChooser(61, 86);
      SongNum[3]=randomSongChooser(87, (int)numOfSongs);
      randomLEDBlink();
    }
    
    //Get the capacitive readings from each drum pad: 50 readings are taken from each pad. (default is 100)
    int value0 = ADCTouch.read(A0,50); // Green drum pad
    int value1 = ADCTouch.read(A1,50); // Blue drum pad
    int value2 = ADCTouch.read(A2,50); // Red drum pad
    int value3 = ADCTouch.read(A3,50); // Yellow drum pad
    
    //Remove the offset to account for the baseline capacitance of each pad.
    value0 -= ref0;       
    value1 -= ref1;
    value2 -= ref2;
    value3 -= ref3;
    
    
    //If any of the values exceed the designated threshold, then play the song/sound associated with that drum pad.
    //The associated LED will stay on for the whole time the drum pad is pressed, providing the value remains above the threshold.
    //The LED will turn off when the pad is not being touched or pressed.
    if(value0>threshold){
      digitalWrite(8, HIGH);
      playSong(00,SongNum[0]);
    }else{
      digitalWrite(8,LOW);
    }
    
    if(value1>threshold){
      digitalWrite(9, HIGH);
      playSong(00,SongNum[1]);
    }else{
      digitalWrite(9,LOW);
    }
    
    if(value2>threshold){
      digitalWrite(10, HIGH);
      playSong(00,SongNum[2]);
    }else{
      digitalWrite(10,LOW);
    }
    
    if(value3>threshold){
      digitalWrite(11, HIGH);
      playSong(00,SongNum[3]);
    }else{
      digitalWrite(11,LOW);
    }
  }
      
   
  // writeToMP3:
  // a generic function that simplifies each of the methods used to control the Grove MP3 Player
  //===================================================================================================
  void writeToMP3(byte MsgLEN, byte A, byte B, byte C, byte D, byte E, byte F){
    byte codeMsg[] = {MsgLEN, A,B,C,D,E,F};
    mp3.write(0x7E); //Start Code for every command = 0x7E
    for(byte i = 0; i<MsgLEN+1; i++){
      mp3.write(codeMsg[i]); //Send the rest of the command to the GROVE MP3 player
    }
  }
  
  
  //setPlayMode: defines how each song is to be played
  //===================================================================================================
  void setPlayMode(byte playMode){
    /* playMode options:
          0x00 = Single song - played only once ie. not repeated.  (default)
          0x01 = Single song - cycled ie. repeats over and over.
          0x02 = All songs - cycled 
          0x03 = play songs randomly                                           */
    writeToMP3(0x03, 0xA9, playMode, 0x7E, 0x00, 0x00, 0x00);  
  }
  
  
  //playSong: tells the Grove MP3 player to play the song/sound, and also which song/sound to play
  //===================================================================================================
  void playSong(byte songHbyte, byte songLbyte){
    writeToMP3(0x04, 0xA0, songHbyte, songLbyte, 0x7E, 0x00, 0x00);            
    delay(100);
  }
  
  
  //setVolume: changes the Grove MP3 player's volume to the designated level (0 to 31)
  //===================================================================================================
  void setVolume(byte Volume){
    byte tempVol = constrain(Volume, 0, 31); //Volume range = 00 (muted) to 31 (max volume)
    writeToMP3(0x03, 0xA7, tempVol, 0x7E, 0x00, 0x00, 0x00); 
  }
  
  
  //randomSongChooser: chooses a random song to play. The range of songs to choose from
  //is limited and defined by the startSong and endSong parameters.
  //===================================================================================================
  byte randomSongChooser(int startSong, int endSong){
    randNumber = random(startSong, endSong);
    return((byte) randNumber);
  }
  
  
  //randomLEDBlink: makes each LED blink randomly. The LEDs are attached to digital pins 8 to 12.
  //===================================================================================================
  void randomLEDBlink(){
   counter=8;
   for(int i=0; i<40; i++){
     int x = constrain((int)random(8,12),8,12);
     toggleLED(x);
     delay(random(50,100-i));
   }
     
    for(int i=8;i<12;i++){
      digitalWrite(i, HIGH);
    }
    delay(1000);
    for(int i=8;i<12;i++){
      digitalWrite(i, LOW);
      ledState[i-8]=0;
    }
  }
  
  
  //toggleLED: is used by the randomLEDBlink method to turn each LED on and off (randomly).
  //===================================================================================================
  void toggleLED(int pinNum){
    ledState[pinNum-8]= !ledState[pinNum-8];
    digitalWrite(pinNum, ledState[pinNum-8]);
  }


 

Arduino Code Discussion

You can see from the Arduino code above, that it uses the ADCTouch library. This library was chosen over the Capacitive Sensing Library to eliminate the need for a high value resistor which are commonly found in Capacitive Sensing projects).
 
To increase the speed of the Analog readings, I utilised one of the "Advanced Arduino ADC" techniques described by Guy van den Berg on this Microsmart website.
 
The readings are increased by modifying the Arduino's ADC clock speed from 125kHz to 250 kHz. I did notice an overall better response time with this modification. However, the Grove Serial MP3 player is limited by it's inability to play more than one song or sound at a time. This means that if you hit another drum pad while the current sound is playing, it will stop playing the current sound, and then play the selected sound. The speed at which it can perform this task was quite impressive. In fact it was much better than I thought it would be. But if you are looking for polyphonic playability, you will be dissapointed.
 
This Serial MP3 module makes use of a high quality MP3 audio chip known as the "WT5001". Therefore, you should be able to get some additional features and functionality from this document. Plus you may find some extra useful info from the Seeedstudio wiki. I have re-used some code from the Arduino Boombox tutorial... you will find extra Grove Serial MP3 functions on that page.
 
I will warn you... the Grove Serial MP3 player can play WAV files, however for some reason it would not play many of the sound files in this format. Once the sounds were converted to the MP3 format, I did not look back. So if you decide to take on this project, make sure your sound files are in MP3 format, you'll have a much better outcome.
 
I decided to introduce a random sound selection for each drum pad to extend the novelty of this instrument, which meant that I had to come up with a fancy way to illuminate the LEDs. I demonstrated some of my other LED sequences on my instagram account. I sometimes use instagram to show my work in progress.
 
Have a look at the video below to see this project in action, and putting the Grove Serial MP3 player through it's paces.
 

The Video


 


First there was the Arduino Boombox, and now we have the Arduino Beatbox..... who knows what will come next !
 
Whenever I create a new project, I like to improve my Arduino knowledge. Sometimes it takes me into some rather complicated topics. There is a lot I do not know about Arduino, but I am enjoying the journey. I hope you are too !! Please Google plus one this post if it helped you in any way. These tutorials are free, which means I survive on feedback and plus ones... all you have to do is just scroll a little bit more and click that button :)

 
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 

 
 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

Arduino BeatBox

Create your very own Arduino BeatBox !

Home-made capacitive touch sensors are used to trigger the MP3 drum sounds stored on the Grove Serial MP3 player. I have used a number of tricks to get the most out of this module, and I was quite impressed on how well it did. Over 130 sounds were loaded onto the SDHC card. Most were drum sounds, but I added some farm animal noises to provide an extra element of surprise and entertainment. You can put any sounds you want on the module and play them back quickly. We'll put the Grove Serial MP3 module through it's paces and make it into a neat little BeatBox !!


Key learning objectives

  • How to make your own beatbox
  • How to make capacitive drum pad sensors without using resistors
  • How to speed up Arduino's Analog readings for better performance
  • How to generate random numbers on your Arduino


Parts Required:

Making the drum pads


 
 

Fritzing Sketch


 


 
 

Grove Connections


 


 
 

Grove Connections (without base shield)


 


 
 

Arduino Sketch


 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

/* =================================================================================================
      Project: Arduino Beatbox
       Author: Scott C
      Created: 9th April 2015
  Arduino IDE: 1.6.2
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This project uses home made capacitive sensors to trigger over 130 MP3 sounds
               on the Grove Serial MP3 player. 
               
               The ADCTouch library is used to eliminate the resistors from the Capacitive sensing circuit. 
               The code used for capacitive sensing was adapted from the ADCTouch library example sketches. 
               You can find the ADCTouch library and relevant example code here:
               http://playground.arduino.cc/Code/ADCTouch
               
               "Advanced Arduino ADC" is used to improve the analogRead() speed, and enhance the
               drum pad or capacitive sensor response time. The Advanced Arduino ADC code 
               was adapted from this site:
               http://www.microsmart.co.za/technical/2014/03/01/advanced-arduino-adc/
               
               
=================================================================================================== */
  #include <ADCTouch.h>
  #include <SoftwareSerial.h>
  
  
  //Global variables
  //===================================================================================================
  int potPin = A4; //Grove Sliding potentiometer is connected to Analog Pin 4
  int potVal = 0;
  byte mp3Vol = 0; //Variable used to control the volume of the MP3 player
  byte oldVol = 0;
  
  int buttonPin = 5; //Grove Button is connected to Digital Pin 5
  int buttonStatus = 0;
  
  byte SongNum[4] = {0x01,0x02,0x03,0x04}; //The first 4 songs will be assigned to the drum pads upon initialisation
  byte numOfSongs = 130; //Total number of MP3 songs/sounds loaded onto the SDHC card
  
  long randNumber; //Variable used to hold the random number - used to randomise the sounds.
  
  int ledState[4]; //Used to keep track of the status of all LEDs (on or off)
  int counter = 0;
  
  SoftwareSerial mp3(3, 4); // The Grove MP3 Player is connected to Arduino digital Pin 3 and 4 (Serial communication)
       
  int ref0, ref1, ref2, ref3; //reference values to remove offset
  int threshold = 100;
      
  // Define the ADC prescalers
  const unsigned char PS_64 = (1 << ADPS2) | (1 << ADPS1);
  const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
  
  
  
  //Setup()
  //===================================================================================================
  void setup(){
    //Initialise the Grove MP3 Module
    delay(2500); //Allow the MP3 module to power up
    mp3.begin(9600); //Begin Serial communication with the MP3 module
    setPlayMode(0x00);                        //0x00 = Single song - played once ie. not repeated. (default)
    
    //Define the Grove Button as an INPUT
    pinMode(buttonPin, INPUT);
    
    //Define the 4 LED Pins as OUTPUTs
    pinMode(8, OUTPUT); //Green LED
    pinMode(9, OUTPUT); //Blue LED
    pinMode(10, OUTPUT); //Red LED
    pinMode(11, OUTPUT); //Yellow LED
    
    //Make sure each LED is OFF, and store the state of the LED into a variable.
    for(int i=8;i<12;i++){
      digitalWrite(i, LOW);
      ledState[i-8]=0;
    } 
    
    //Double our clock speed from 125 kHz to 250 kHz
    ADCSRA &= ~PS_128;   // set up the ADC
    ADCSRA |= PS_64;    // set our own prescaler to 64
    
    //Create reference values to account for the capacitance of each pad.
    ref0 = ADCTouch.read(A0, 500);
    ref1 = ADCTouch.read(A1, 500); //Take 500 readings
    ref2 = ADCTouch.read(A2, 500);
    ref3 = ADCTouch.read(A3, 500);
    
     //This helps to randomise the drum pads.
     randomSeed(analogRead(0));
  }
  
  
  
  // Loop()
  //===================================================================================================
  void loop(){
     
    //Take a reading from the Grove Sliding Potentiometer, and set volume accordingly
    potVal = analogRead(potPin);
    mp3Vol = map(potVal, 0, 1023, 0,31); // Convert the potentometer reading (0 - 1023) to fit within the MP3 player's Volume range (0 - 31)
    if((mp3Vol>(oldVol+1))|(mp3Vol<(oldVol-1))){ // Only make a change to the Volume on the Grove MP3 player when the potentiometer value changes
      oldVol = mp3Vol;
      setVolume(mp3Vol);
      delay(10); // This delay is necessary with Serial communication to MP3 player
    }
    
    //Take a reading from the Pin attached to the Grove Button. If pressed, randomise the MP3 songs/sounds for each drum pad, and make the LEDs blink randomly.
    buttonStatus = digitalRead(buttonPin);
    if(buttonStatus==HIGH){
      SongNum[0]=randomSongChooser(1, 30);
      SongNum[1]=randomSongChooser(31, 60);
      SongNum[2]=randomSongChooser(61, 86);
      SongNum[3]=randomSongChooser(87, (int)numOfSongs);
      randomLEDBlink();
    }
    
    //Get the capacitive readings from each drum pad: 50 readings are taken from each pad. (default is 100)
    int value0 = ADCTouch.read(A0,50); // Green drum pad
    int value1 = ADCTouch.read(A1,50); // Blue drum pad
    int value2 = ADCTouch.read(A2,50); // Red drum pad
    int value3 = ADCTouch.read(A3,50); // Yellow drum pad
    
    //Remove the offset to account for the baseline capacitance of each pad.
    value0 -= ref0;       
    value1 -= ref1;
    value2 -= ref2;
    value3 -= ref3;
    
    
    //If any of the values exceed the designated threshold, then play the song/sound associated with that drum pad.
    //The associated LED will stay on for the whole time the drum pad is pressed, providing the value remains above the threshold.
    //The LED will turn off when the pad is not being touched or pressed.
    if(value0>threshold){
      digitalWrite(8, HIGH);
      playSong(00,SongNum[0]);
    }else{
      digitalWrite(8,LOW);
    }
    
    if(value1>threshold){
      digitalWrite(9, HIGH);
      playSong(00,SongNum[1]);
    }else{
      digitalWrite(9,LOW);
    }
    
    if(value2>threshold){
      digitalWrite(10, HIGH);
      playSong(00,SongNum[2]);
    }else{
      digitalWrite(10,LOW);
    }
    
    if(value3>threshold){
      digitalWrite(11, HIGH);
      playSong(00,SongNum[3]);
    }else{
      digitalWrite(11,LOW);
    }
  }
      
   
  // writeToMP3:
  // a generic function that simplifies each of the methods used to control the Grove MP3 Player
  //===================================================================================================
  void writeToMP3(byte MsgLEN, byte A, byte B, byte C, byte D, byte E, byte F){
    byte codeMsg[] = {MsgLEN, A,B,C,D,E,F};
    mp3.write(0x7E); //Start Code for every command = 0x7E
    for(byte i = 0; i<MsgLEN+1; i++){
      mp3.write(codeMsg[i]); //Send the rest of the command to the GROVE MP3 player
    }
  }
  
  
  //setPlayMode: defines how each song is to be played
  //===================================================================================================
  void setPlayMode(byte playMode){
    /* playMode options:
          0x00 = Single song - played only once ie. not repeated.  (default)
          0x01 = Single song - cycled ie. repeats over and over.
          0x02 = All songs - cycled 
          0x03 = play songs randomly                                           */
    writeToMP3(0x03, 0xA9, playMode, 0x7E, 0x00, 0x00, 0x00);  
  }
  
  
  //playSong: tells the Grove MP3 player to play the song/sound, and also which song/sound to play
  //===================================================================================================
  void playSong(byte songHbyte, byte songLbyte){
    writeToMP3(0x04, 0xA0, songHbyte, songLbyte, 0x7E, 0x00, 0x00);            
    delay(100);
  }
  
  
  //setVolume: changes the Grove MP3 player's volume to the designated level (0 to 31)
  //===================================================================================================
  void setVolume(byte Volume){
    byte tempVol = constrain(Volume, 0, 31); //Volume range = 00 (muted) to 31 (max volume)
    writeToMP3(0x03, 0xA7, tempVol, 0x7E, 0x00, 0x00, 0x00); 
  }
  
  
  //randomSongChooser: chooses a random song to play. The range of songs to choose from
  //is limited and defined by the startSong and endSong parameters.
  //===================================================================================================
  byte randomSongChooser(int startSong, int endSong){
    randNumber = random(startSong, endSong);
    return((byte) randNumber);
  }
  
  
  //randomLEDBlink: makes each LED blink randomly. The LEDs are attached to digital pins 8 to 12.
  //===================================================================================================
  void randomLEDBlink(){
   counter=8;
   for(int i=0; i<40; i++){
     int x = constrain((int)random(8,12),8,12);
     toggleLED(x);
     delay(random(50,100-i));
   }
     
    for(int i=8;i<12;i++){
      digitalWrite(i, HIGH);
    }
    delay(1000);
    for(int i=8;i<12;i++){
      digitalWrite(i, LOW);
      ledState[i-8]=0;
    }
  }
  
  
  //toggleLED: is used by the randomLEDBlink method to turn each LED on and off (randomly).
  //===================================================================================================
  void toggleLED(int pinNum){
    ledState[pinNum-8]= !ledState[pinNum-8];
    digitalWrite(pinNum, ledState[pinNum-8]);
  }


 

Arduino Code Discussion

You can see from the Arduino code above, that it uses the ADCTouch library. This library was chosen over the Capacitive Sensing Library to eliminate the need for a high value resistor which are commonly found in Capacitive Sensing projects).
 
To increase the speed of the Analog readings, I utilised one of the "Advanced Arduino ADC" techniques described by Guy van den Berg on this Microsmart website.
 
The readings are increased by modifying the Arduino's ADC clock speed from 125kHz to 250 kHz. I did notice an overall better response time with this modification. However, the Grove Serial MP3 player is limited by it's inability to play more than one song or sound at a time. This means that if you hit another drum pad while the current sound is playing, it will stop playing the current sound, and then play the selected sound. The speed at which it can perform this task was quite impressive. In fact it was much better than I thought it would be. But if you are looking for polyphonic playability, you will be dissapointed.
 
This Serial MP3 module makes use of a high quality MP3 audio chip known as the "WT5001". Therefore, you should be able to get some additional features and functionality from this document. Plus you may find some extra useful info from the Seeedstudio wiki. I have re-used some code from the Arduino Boombox tutorial... you will find extra Grove Serial MP3 functions on that page.
 
I will warn you... the Grove Serial MP3 player can play WAV files, however for some reason it would not play many of the sound files in this format. Once the sounds were converted to the MP3 format, I did not look back. So if you decide to take on this project, make sure your sound files are in MP3 format, you'll have a much better outcome.
 
I decided to introduce a random sound selection for each drum pad to extend the novelty of this instrument, which meant that I had to come up with a fancy way to illuminate the LEDs. I demonstrated some of my other LED sequences on my instagram account. I sometimes use instagram to show my work in progress.
 
Have a look at the video below to see this project in action, and putting the Grove Serial MP3 player through it's paces.
 

The Video


 


First there was the Arduino Boombox, and now we have the Arduino Beatbox..... who knows what will come next !
 
Whenever I create a new project, I like to improve my Arduino knowledge. Sometimes it takes me into some rather complicated topics. There is a lot I do not know about Arduino, but I am enjoying the journey. I hope you are too !! Please Google plus one this post if it helped you in any way. These tutorials are free, which means I survive on feedback and plus ones... all you have to do is just scroll a little bit more and click that button :)

 
 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 

 
 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

Arduino Boombox

Add sound or music to your project using the "Grove Serial MP3 Player".

An Arduino UNO will be used to control the Grove Serial MP3 player by sending it specific serial commands. The Grove Base Shield allows for the easy connection of Grove sensor modules to an Arduino UNO without the need for a breadboard. A sliding potentiometer, switch and button will be connected to the Base shield along with the Serial MP3 player. A specific function will be assigned to each of the connected sensor modules to provide a useful interface:

  • Sliding Potentiometer – Volume control
  • Button – Next Song
  • Switch – On/Off (toggle)
Once the MP3 module is working the way we want, we can then build a simple enclosure for it. Grab a shoe-box, print out your favourite design, and make your very own Arduino BOOMBOX!


 

Video

Watch the following video to see the project in action
 


 
 

Parts Required:

Optional components (for the BoomBox Enclosure):
  • Empty Shoe Box
  • Paper
  • Printer
  • Glue
If I had a 3D printer - I would have printed my own enclosure, but a shoebox seems to work just fine.


 

Putting it Together

Place the Grove Base shield onto the Arduino UNO,
and then connect each of the Grove Modules as per the table below.
 


 

If you do not have a Grove Base shield,
you can still connect the modules directly to the Arduino as per the table below:
 


 

When you are finished connecting the modules, it should look something like this:
  (ignore the battery pack):
 

As you can see from the picture above. You can cut holes out of the shoebox and stick the modules in place. Please ignore the battery pack, because you won't use it until after you have uploaded the Arduino code.


 
 

Arduino Sketch


 
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193


/* ===============================================================================
      Project: Grove Serial MP3 Player overview
       Author: Scott C
      Created: 9th March 2015
  Arduino IDE: 1.6.0
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html

  Description: The following Arduino sketch will allow you to control a Grove Serial MP3 player
               with a Grove Sliding Potentiometer (volume), a Grove button (next song), 
               and a Grove Switch (on/off). It will also show you how to retrieve some useful information from the player. 
               Some functions are not used in this sketch,but have been included for your benefit. 
               
               Additional features and functionality can be found on the WT5001 voice chip datasheet 
               which I retrieved from here: http://goo.gl/ai6oQ9
               
               The Seeedstudio wiki was a very useful resource for getting started with the various Grove modules:
               http://goo.gl/xOiSCl
=============================================================================== */

#include <SoftwareSerial.h>
SoftwareSerial mp3(2, 3); // The Grove MP3 Player is connected to Arduino digital Pin 2 and 3 (Serial communication)
int potPin = A0; // The Sliding Potentiometer is connected to AnalogPin 0
int potVal = 0; // This is used to hold the value of the Sliding Potentiometer
byte mp3Vol = 0; // mp3Vol is used to calculate the Current volume of the Grove MP3 player
byte oldVol = 0; // oldVol is used to remember the previous volume level
int ledPin = A1; // The Grove sliding potentiometer has an onboard LED attached to Analog pin 1.

int switchPin = 12; // The Grove Switch(P) is connected to digital Pin 12
int switchStatus = 0; // This is used to hold the status of the switch
int switchChangeStatus = 0; // Used to identify when the switch status has changed

int buttonPin = 5; // The Grove Button is connected to digital pin 5
int buttonStatus = 0; // This is used to hold the status of the button



void setup(){
  //Initialise the Grove MP3 Module
  delay(2500);
  mp3.begin(9600);
  
        
  // initialize the pushbutton and switch pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(switchPin, INPUT);
  
  // set ledPin on the sliding potentiometer to OUTPUT
  pinMode(ledPin, OUTPUT);
  
  //You can view the following demostration output in the Serial Monitor
  demonstrate_GET_FUNCTIONS();     
}


void loop(){
  switchStatus = digitalRead(switchPin);
  if(switchStatus==HIGH){
    if(switchChangeStatus==LOW){ // When Arduino detects a change in the switchStatus (from LOW to HIGH) - play song
      setPlayMode(0x02);                     // Automatically cycle to the next song when the current song ends
      playSong(00,01);                       // Play the 1st song when you switch it on
      switchChangeStatus=HIGH;
    }
    
    potVal = analogRead(potPin); // Analog read values from the sliding potentiometer range from 0 to 1023
    analogWrite(ledPin, potVal/4); // Analog write values range from 0 to 255, and will turn LED ON once potentiometer reaches about half way (or more).
    mp3Vol = map(potVal, 0, 1023, 0,31); // Convert the potentometer reading (0 - 1023) to fit within the MP3 player's Volume range (0 - 31)
    if((mp3Vol>(oldVol+1))|(mp3Vol<(oldVol-1))){ // Only make a change to the Volume on the Grove MP3 player when the potentiometer value changes
      oldVol = mp3Vol;
      setVolume(mp3Vol);
      delay(10); // This delay is necessary with Serial communication to MP3 player
    }

    buttonStatus = digitalRead(buttonPin);
    if(buttonStatus==HIGH){ // When a button press is detected - play the next song
      playNextSong();
      delay(200); // This delay aims to prevent a "skipped" song due to slow button presses - can modify to suit.
    }
  } else {
    if(switchChangeStatus==HIGH){ // When switchStatus changes from HIGH to LOW - stop Song.
      stopSong();
      switchChangeStatus=LOW;
    }
  } 
}


// demonstrate_GET_FUNCTIONS  will show you how to retrieve some useful information from the Grove MP3 Player (using the Serial Monitor).
void demonstrate_GET_FUNCTIONS(){
        Serial.begin(9600);
        Serial.print("Volume: ");
        Serial.println(getVolume());
        Serial.print("Playing State: ");
        Serial.println(getPlayingState());
        Serial.print("# of Files in SD Card:");
        Serial.println(getNumberOfFiles());
        Serial.println("------------------------------");
}


// writeToMP3: is a generic function that aims to simplify all of the methods that control the Grove MP3 Player

void writeToMP3(byte MsgLEN, byte A, byte B, byte C, byte D, byte E, byte F){
  byte codeMsg[] = {MsgLEN, A,B,C,D,E,F};
  mp3.write(0x7E); //Start Code for every command = 0x7E
  for(byte i = 0; i<MsgLEN+1; i++){
    mp3.write(codeMsg[i]); //Send the rest of the command to the GROVE MP3 player
  }
}


/* The Following functions control the Grove MP3 Player : see datasheet for additional functions--------------------------------------------*/

void setPlayMode(byte playMode){
  /* playMode options:
        0x00 = Single song - played only once ie. not repeated.  (default)
        0x01 = Single song - cycled ie. repeats over and over.
        0x02 = All songs - cycled 
        0x03 = play songs randomly                                           */
        
  writeToMP3(0x03, 0xA9, playMode, 0x7E, 0x00, 0x00, 0x00);  
}


void playSong(byte songHbyte, byte songLbyte){ // Plays the selected song
  writeToMP3(0x04, 0xA0, songHbyte, songLbyte, 0x7E, 0x00, 0x00);            
}


void pauseSong(){ // Pauses the current song
  writeToMP3(0x02, 0xA3, 0x7E, 0x00, 0x00, 0x00, 0x00);
}


void stopSong(){ // Stops the current song
  writeToMP3(0x02, 0xA4, 0x7E, 0x00, 0x00, 0x00, 0x00);
}


void playNextSong(){ // Play the next song
  writeToMP3(0x02, 0xA5, 0x7E, 0x00, 0x00, 0x00, 0x00);
}


void playPreviousSong(){ // Play the previous song
  writeToMP3(0x02, 0xA6, 0x7E, 0x00, 0x00, 0x00, 0x00);
}


void addSongToPlayList(byte songHbyte, byte songLbyte){
  //Repeat this function for every song you wish to stack onto the playlist (max = 10 songs)
  writeToMP3(0x04, 0xA8, songHbyte, songLbyte, 0x7E, 0x00, 0x00);
}


void setVolume(byte Volume){ // Set the volume
  byte tempVol = constrain(Volume, 0, 31);
  //Volume range = 00 (muted) to 31 (max volume)
  writeToMP3(0x03, 0xA7, tempVol, 0x7E, 0x00, 0x00, 0x00); 
}



/* The following functions retrieve information from the Grove MP3 player : see data sheet for additional functions--------------*/

// getData: is a generic function to simplifly the other functions for retieving information from the Grove Serial MP3 player
byte getData(byte queryVal, int dataPosition){
  byte returnVal = 0x00;
  writeToMP3(0x02, queryVal, 0x7E, 0x00, 0x00, 0x00, 0x00);
  delay(50);
  for(int x = 0; x<dataPosition; x++){
    if(mp3.available()){
      returnVal = mp3.read();
      delay(50);
    }
  }
  return(returnVal);
}

byte getVolume(){ //Get the volume of the Grove Serial MP3 player
  //returns value from 0 - 31
  return(getData(0xC1, 4));
}

byte getPlayingState(){ //Get the playing state : Play / Stopped / Paused
  //returns 1: Play, 2: Stop, 3:Paused
  return(getData(0xC2, 2));
}


byte getNumberOfFiles(){ //Find out how many songs are on the SD card
  //returns the number of MP3 files on SD card
  return(getData(0xC4, 3));
}

You will notice from the code, that I did not utilise every function. I decided to include them for your benifit. This Serial MP3 module makes use of a high quality MP3 audio chip known as the "WT5001". Therefore, you should be able to get some additional features and functionality from this document. Plus you may find some extra useful info from the Seeedstudio wiki.
 
IMPORTANT: You need to load your MP3 sounds or songs onto the SDHC card before you install it onto the Serial MP3 player.
 
Once the SDHC card is installed, and your code is uploaded to the Arduino, all you have to do now is connect the MP3 player to some headphones or a powered speaker. You can then power the Arduino and modules with a battery pack or some other portable power supply.
 
You can design and decorate the shoebox in any way you like. Just print out your picture, glue them on, and before you know it, you will have your very own Arduino Boombox.
 


Comments

I was very surprised by the quality of the sound that came from the MP3 module. It is actually quite good.

This tutorial was an introduction to the Grove Serial MP3 module in it's most basic form. You could just as easily use some other sensor to trigger the MP3 module. For example, you could get it to play an alert if a water leak was detected, or if a door was opened, or if the temperature got too high or too low. You could get it to play a reminder when you walk into your room. The possibilities are endless.

I really liked this module, and I am sure it will appear in a future tutorial.


 



If you like this page, please do me a favour and show your appreciation :

 
Visit my ArduinoBasics Google + page.
Follow me on Twitter by looking for ScottC @ArduinoBasics.
I can also be found on Pinterest and Instagram.
Have a look at my videos on my YouTube channel.


 
 

 
 
 



However, if you do not have a google profile...
Feel free to share this page with your friends in any way you see fit.

Dial is a Simple and Effective Wireless Media Controller

[Patrick] was looking for an easier way to control music and movies on his computer from across the room. There is a huge amount of remote control products that could be purchased to do this, but as a hacker [Patrick] wanted to make something himself. He calls his creation, “Dial” and it’s a simple but elegant solution to the problem.

Dial looks like a small cylindrical container that sits on a flat surface. It’s actually split into a top and bottom cylinder. The bottom acts as a base and stays stationary while the top acts as a dial and a push button. The case was designed in SOLIDWORKS and printed on a 3D printer.

The Dial runs on an Arduino Pro mini with a Bluetooth module. The original prototype used Bluetooth 2.0 and required a recharge after about a day. The latest version uses the Bluetooth low energy spec and can reportedly last several weeks on a single charge. Once the LiPo battery dies, it can be recharged easily once plugged into a USB port.

The mechanical component of the dial is actually an off-the-shelf rotary encoder. The encoder included a built-in push button to make things easier. The firmware is able to detect rotation in either direction, a button press, a double press, and a press-and-hold. This gives five different possible functions.

[Patrick] wrote two pieces of software to handle interaction with the Dial. The first is a C program to deal with the Bluetooth communication. The second is actually a set of Apple scripts to actually handle interaction between the Dial and the various media programs on his computer. This allows the user to more easily write their own scripts for whatever software they want. While this may have read like a product review, the Dial is actually open source!


Filed under: Arduino Hacks, peripherals hacks

Grove Button Tutorial

The Grove Button is a handy little component which simplifies the push-button experience. It doesn't take much programming to get this component to work. And while the button works extremely well with the Grove Base Shield, we will be connecting this button directly to the Arduino UNO.

The button will be LOW in its normal resting state, and report HIGH when the button is pressed. Have a look at the video below to see this project in action.

Video






Parts Required




Sketch







Arduino Sketch




 1
2
3
4
5
6
7
8
9
10
11
12
/* Grove Button Sketch - Written by ScottC 22nd Dec 2013 
http://arduinobasics.blogspot.com
--------------------------------------------------------- */

void setup(){
pinMode(8, INPUT);
pinMode(13, OUTPUT);
}

void loop(){
digitalWrite(13, digitalRead(8));
}

The signal pin of the Grove Button attaches to digital pin 8 on the Arduino, and the LED is connected to digital pin 13 on the Arduino. When the button is pressed, it will send a HIGH signal to digital pin 8, which will turn the LED on. When the button is released, the signal will change to LOW and the LED will turn off.

Live your life like there's no tomorrow with David Lee Roth in a box (video)

Seriously, guys, when was the last time you ran with the devil? It's been a while, hasn't it? Leave it to David Lee Roth to show us all the way, yet again, this time courtesy of Arduino-based soundbox created with help from the Adafruit Wave Shield. The box runs on a nine-volt battery and has a big trigger button on the top that plays what sounds like Roth's infamous "Runnin' With the Devil" isolated vocal tracks through a speaker on the bottom. The box's builder has promised more to come -- we'd like to request a Murry Wilson "I'm a genius, too" box, if one isn't already in the pipeline.

Continue reading Live your life like there's no tomorrow with David Lee Roth in a box (video)

Live your life like there's no tomorrow with David Lee Roth in a box (video) originally appeared on Engadget on Thu, 22 Mar 2012 15:44:00 EST. Please see our terms for use of feeds.

Permalink | Email this | Comments