Posts with «arduinobasics» label

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.

Weather Reporter - Temboo, Ethernet and Arduino


 

Arduino is well known for the large variety of sensors / modules that can be connected. It is quite easy to hook up a temperature or humidity sensor to get instant feedback about the surrounding environmental conditions. However, sometimes you do not have a temperature sensor. Sometimes you have a sensor, but would like to know the temperature in other cities ! Or you would like to know what the temperature will be tomorrow?

Well now you can !!

All you need is a Temboo account, an internet connection and the following components:

Parts Required


 
 

Project Description


An Arduino UNO (and Ethernet Shield) queries Yahoo using a Temboo account, and retrieves weather information. The data is filtered and processed, and then passed on to another Arduino UNO to be displayed on a TFT LCD module. Two Arduino UNOs are used because the Ethernet library and the UTFT library are both memory hungry, and together consume more memory than one Arduino UNO can handle. Yes - I could have used a different board such as the Arduino MEGA, but where is the fun in that ?? This project will teach you many things:
  • How to use an Ethernet Shield with a Temboo account to retrieve internet data
  • How to use a TFT LCD module (ITDB02-1.8SP)
  • How to reduce memory consumption when using the UTFT library
  • How to power two Arduinos with a single USB cable
  • How to transmit data from one Arduino to another (via jumper wires)
All of this and a whole lot more !!


 
 

Video

Have a look at the following video to see the project in action.
 




You will need to create a Temboo account to run this project:

Temboo Account Creation

Step 1:

Visit the Temboo website : https://www.temboo.com/ Create an account by entering a valid email address. Then click on the Sign Up button.

 

 

Step 2:

Verify your email address by clicking on the link provided in the email sent by Temboo.

 

Step 3:

You will be directed to the account setup page: Create an Account Name, and Password for future access to your Temboo Account Check the terms of service and if you agree, then tick the box Press the Go! button

 

 

Step 4:

You will then encounter the "Welcome!" screen:

 

 

Step 5:

Navigate to the top right of the screen and select the LIBRARY tab

 

 

Step 6:

On the left hand side you will see a list of choreos. Type Yahoo into the search box on the top left of the screen. Navigate to the GetWeatherByAddress Choreo by clicking on...     Yahoo _ Weather _ GetWeatherByAddress

 

 

Step 7:

Turn the IoT Mode to ON (in the top right of screen)

 

 

Step 8:

What's your platform / device? : Arduino How is it connected? : Arduino Ethernet   The following popup box will appear:

 

 

Step 9:

Name: EthernetShield - you can choose any name. Letters and numbers only. No spaces. Shield Type: Arduino Ethernet MAC Address : You can normally find the MAC address of the Ethernet shield on the underside. Enter the MAC address without the hyphens. Then click SAVE.

 

 

Step 10:

Move to the INPUT section. Enter the Address of the place you want the Temperature for. Address = Perth, Western Australia Expand the Optional INPUT for extra functionality Units = c - If you want the temperature in Celcius.

 

 

Step 11:

This will automatically generate some Arduino CODE and a HEADER FILE. Don't worry about the Arduino code for now... because I will provide that for you. However, you will need the automatically generated HEADER file. I will show you what to do with that soon. So don't lose it !'



Temboo Library Install

The Temboo library will need to be installed before you copy the Arduino code in the sections below. To install the Temboo library into your Arduino IDE, please follow the link to their instructions:   Installing the Temboo Arduino Library

   

UTFT Library Install

Download the UTFT library from this site: http://www.henningkarlsen.com/electronics/library.php?id=51 Once downloaded and extracted. Go into the UTFT folder and look for the memorysaver.h file. Open this file in a text editor, and "uncomment" all of the TFT modules that are not relevant to this project. I disabled all of the TFT modules except the last 3 (which made reference to ST7735) - see picture below. The TFT module we are using in this project is the ITDB02-1.8SP from ITEAD Studio. Save the memorysaver.h file, and then IMPORT the library into the Arduino IDE as per the normal library import procedure.   If you do not modify the memorysaver.h file, the Arduino SLAVE sketch will not compile.

   

Arduino Code (MASTER)

  This project uses 2 Arduino UNOs. One will be the Master, and one will be the Slave. The following code is for the Arduino MASTER.   Open up the Arduino IDE. (I am using Arduino IDE version 1.6) Paste the following code into the Arduino IDE code window.   PLEASE NOTE: You may need to change some of the lines to accomodate your INPUTS from step 10. Have a look around line 36 and 37.  
  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
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


/* ===============================================================================
      Project: Weather Reporter: Temboo, Ethernet, Arduino
        Title: ARDUINO MASTER: Get temperature from Yahoo using Temboo
       Author: Scott C
      Created: 27th February 2015
  Arduino IDE: 1.6.0
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: The following sketch was designed for the Arduino MASTER device. 
               It will retrieve temperature/weather information from Yahoo using your
               Temboo account (https://www.temboo.com/), which will then be sent to the
               Arduino Slave device to be displayed on a TFT LCD module.
               
   Libraries : Ethernet Library (that comes with Arduino IDE)
               Temboo Arduino Library - https://www.temboo.com/sdk/arduino
               
   Temboo Library installation instructions for Arduino: 
               https://www.temboo.com/arduino/others/library-installation

  You will also need to copy your Temboo Account information into a new tab and call it TembooAccount.h.
  Please follow the instructions on the ArduinoBasics blog for more information.
---------------------------------------------------------------------------------- */

#include <SPI.h>
#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <Temboo.h>
#include "TembooAccount.h" // Contains Temboo account information - in a new tab.
#include <Wire.h>

byte ethernetMACAddress[] = ETHERNET_SHIELD_MAC; //ETHERNET_SHIELD_MAC variable located in TembooAccount.h
EthernetClient client;

String Address = "Perth, Western Australia"; // Find temperature for Perth, Western Australia
String Units = "c"; // Display the temperature in degrees Celcius

String ForeCastDay[7]; //String Array to hold the day of the week
String ForeCastTemp[7]; //String Array to hold the temperature for that day of week.

int counter1=0; //Counters used in FOR-LOOPS.
int counter2=0;

boolean downloadTemp = true; // A boolean variable which controls when to query Yahoo for Temperature information.



void setup() {
  Wire.begin(); // join i2c bus : Used to communicate to the Arduino SLAVE device.
 
  // Ethernet shield must initialise properly to continue with sketch.
  if (Ethernet.begin(ethernetMACAddress) == 0) {
    while(true);
  }
  
  //Provide some time to get both Arduino's ready for Temperature Query.
    delay(2000);
}




void loop() {
  if (downloadTemp) {
    downloadTemp=false; //Stop Arduino from Querying Temboo repeatedly
    getTemperature();       //Retrieve Temperature data from Yahoo
    transmitResults();      //Transmit the temperature results to the Slave Arduino
  }
}




/* This function will Query Yahoo for Temperature information (using a Temboo account) */

void getTemperature(){
    TembooChoreo GetWeatherByAddressChoreo(client);

    // Invoke the Temboo client
    GetWeatherByAddressChoreo.begin();

    // Set Temboo account credentials
    GetWeatherByAddressChoreo.setAccountName(TEMBOO_ACCOUNT); //TEMBOO_ACCOUNT variable can be found in TembooAccount.h file or tab
    GetWeatherByAddressChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); //TEMBOO_APP_KEY_NAME variable can be found in TembooAccount.h file or tab
    GetWeatherByAddressChoreo.setAppKey(TEMBOO_APP_KEY); //TEMBOO_APP_KEY variable can be found in TembooAccount.h file or tab

    // Set Choreo inputs
    GetWeatherByAddressChoreo.addInput("Units", Units); // Set the Units to Celcius
    GetWeatherByAddressChoreo.addInput("Address", Address); // Set the Weather Location to Perth, Western Australia

    // Identify the Choreo to run
    GetWeatherByAddressChoreo.setChoreo("/Library/Yahoo/Weather/GetWeatherByAddress");

    // This output filter will extract the expected temperature for today
    GetWeatherByAddressChoreo.addOutputFilter("Temperature", "/rss/channel/item/yweather:condition/@temp", "Response");
    
    // These output filters will extract the forecasted temperatures (we need to know the day and temperature for that day)
    GetWeatherByAddressChoreo.addOutputFilter("ForeCastDay", "/rss/channel/item/yweather:forecast/@day", "Response");
    GetWeatherByAddressChoreo.addOutputFilter("ForeCastHigh", "/rss/channel/item/yweather:forecast/@high", "Response");

    // Run the Choreo;
    GetWeatherByAddressChoreo.run();

    //Reset our counters before proceeding
    counter1 = 0;
    counter2 = 0;
    
    while(GetWeatherByAddressChoreo.available()) {
      // This will get the first part of the output
      String name = GetWeatherByAddressChoreo.readStringUntil('\x1F');
      name.trim(); // get rid of newlines

      // This will get the second part of the output
      String data = GetWeatherByAddressChoreo.readStringUntil('\x1E');
      data.trim(); // get rid of newlines

      //Fill the String Arrays with the Temperature/Weather data
      if (name == "Temperature") {
        ForeCastDay[counter1] = "Today";
        ForeCastTemp[counter2] = data;
        counter1++;
        counter2++;
      }
      
      if(name=="ForeCastDay"){
        ForeCastDay[counter1] = data;
        counter1++;
      }
      
      if(name=="ForeCastHigh"){
        ForeCastTemp[counter2] = data;
        counter2++;
      }
    }
  
    //Close the connection to Temboo website
    GetWeatherByAddressChoreo.close();
  }
  
  
  
  
  /* This function is used to transmit the temperature data to the Slave Arduino */
  
  void transmitResults(){
    char tempData[10];
    int tempStringLength = 0;
    
    //Modify the current temp to "Now"
    ForeCastDay[0] = "Now";
    
    //Send * to Slave Arduino to prepare for Temperature Transmission
    Wire.beginTransmission(4); // Transmit to device #4 (Slave Arduino)
    Wire.write("*");
    delay(500);
    Wire.endTransmission();
    delay(500);
    
    //Send the temperatures on the Slave Arduino to be displayed on the TFT module.
    for (int j=0; j<20; j++){
      for (int i=0; i<6; i++){
        memset(tempData,0,sizeof(tempData));   //Clear the character array
        String tempString = String(ForeCastDay[i] + "," + ForeCastTemp[i] + ".");
        tempStringLength = tempString.length();
        tempString.toCharArray(tempData, tempStringLength+1);
        Wire.beginTransmission(4); // Transmit to device #4 (Slave Arduino)
        Wire.write(tempData);
        delay(1000);
        Wire.endTransmission();
        delay(4000);
      }
    }
    
    /* ----------------------------------------------------------------------
    // You can use this to send temperature results to the Serial Monitor.
    // However, you will need a Serial.begin(9600); statement in setup().
    
    Serial.println("The Current Temperature is " + ForeCastTemp[5] + " C");
    Serial.println();
    Serial.println("The Expected Temperature for");
    for (int i=0; i<5; i++){
      Serial.println(ForeCastDay[i] + " : " + ForeCastTemp[i] + " C");
    }
    ---------------------------------------------------------- */
  }
  

 
 
 
Select "New Tab" from the drop-down menu on the top right of the IDE. Name the file: TembooAccount.h

Paste the contents of the HEADER file from the Temboo webpage (Step 11 above) into the TembooAccount.h tab. If you do not have the TembooAccount.h tab with the contents of this HEADER file next to your Arduino Master sketch, then it will NOT work.  
Make sure to SAVE the Arduino Sketch and upload the code to the Arduino (MASTER)

   

Arduino Code (SLAVE)

  This project uses 2 Arduino UNOs. One will be the Master, and one will be the Slave. The following code is for the Arduino SLAVE.   Make sure to disconnect the Arduino MASTER from your computer, and keep it to one side. Connect the Arduino SLAVE to your computer, and upload the following code to it. Make sure to create a new sketch for this code (File _ New).  
  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


/* ===============================================================================
      Project: Weather Reporter: Temboo, Ethernet, Arduino
        Title: ARDUINO SLAVE: Display temperature on TFT LCD Module
       Author: Scott C
      Created: 27th February 2015
  Arduino IDE: 1.6.0
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: The following sketch was designed for the Arduino SLAVE device. 
               It will receive temperature information from the Arduino MASTER
               and then display this information on the ITDB02-1.8SP TFT LCD 
               Module. Please read the important notes below.

----------------------------------------------------------------------------------
NOTES:
This sketch makes use of the UTFT.h library from : 
http://www.henningkarlsen.com/electronics/library.php?id=51
Please note: You will need to modify the memorysaver.h file in the UTFT folder 
with a text editor to disable any unused TFT modules. This will save memory, 
and allow you to run this sketch on an Arduino UNO. I disabled all TFT modules in
that file except the last 3 (which made reference to ST7735).
I used a ITDB02-1.8SP TFT LCD Module from ITEAD Studio.
PinOut:

Arduino SLAVE      ITDB02-1.8SP TFT
         3.3V ---- VDD33
 Digital9 (D9)---- CS
 Digital8 (D8)---- SCL
 Digital7 (D7)---- SDA
 Digital6 (D6)---- RS
 Digital5 (D5)---- RST
          GND ---- GND
           5V ---- VIN

Usage: UTFT myGLCD(<model code>, SDA, SCL, CS, RST, RS);
Example: UTFT myGLCD(ITDB18SP,7,8,9,5,6);

-----------------------------------------------------------------------------------
This sketch also makes use of the Wire.h library. 
The Wire.h library comes with the Arduino IDE.
This enables communication between Arduino Master and Arduino Slave.
PinOut:

Arduino MASTER      Arduino SLAVE
   Analog4(A4) ---- Analog4 (A4) 
   Analog5(A5) ---- Analog5 (A5) 
           GND ---- GND

-----------------------------------------------------------------------------------
The Arduino Slave is powered by the Arduino Master:
PinOut:

Arduino MASTER      Arduino SLAVE
            5V ---- VIN

==================================================================================
*/

#include <UTFT.h>
#include <Wire.h>

//Declare all of the fonts
extern uint8_t SmallFont[];
extern uint8_t BigFont[];
extern uint8_t SevenSegNumFont[];

// Usage: UTFT myGLCD(<model code>, SDA, SCL, CS, RST, RS);
UTFT myGLCD(ITDB18SP,7,8,9,5,6);

boolean tempDisplay = false; //Helps with processing the data from the Arduino MASTER
boolean readTemp = false; //Helps to differentiate the day from the temperature values
String dayOfWeek=""; //Variable used to hold the Day of the Week
String tempReading=""; //Variable used to hold the Temperature for that day

String Units = "'C "; //Display Temperature in Celcius
String Address = "Perth, WA"; //Address to show at top of Display


void setup(){
  // Initialise the TFT LCD
  myGLCD.InitLCD();
  initialiseLCD();
  delay(5000);
  
  //Setup the Serial communication between the Arduino MASTER and SLAVE
  Wire.begin(4); // join i2c bus with address #4
  Wire.onReceive(receiveEvent); // register event
}



void loop(){
  delay(50);
}


/*
  This function initialises the TFT LCD, and draws the initial screen.
*/
void initialiseLCD(){
  //Clear the screen
  myGLCD.clrScr();
  
  //Draw the borders (top and bottom)
  myGLCD.setColor(25, 35, 4);
  myGLCD.fillRect(0, 0, 159, 13);
  myGLCD.fillRect(0, 114, 159, 127);
  myGLCD.drawLine(0,18,159,18);
  myGLCD.drawLine(0,109,159,109);
  
  //Header and Footer Writing
  myGLCD.setColor(255, 255, 255);
  myGLCD.setBackColor(25, 35, 4);
  myGLCD.setFont(SmallFont);
  myGLCD.print("arduinobasics", CENTER, 1);
  myGLCD.print("blogspot.com", CENTER, 114);
}




/* This function executes whenever data is received from Arduino master
   It will ignore all data from the Master until it receives a '*' character.
   Once this character is received, it will call the receiveTemp() function
   in order to receive Temperature data from the Arduino Master.
*/
void receiveEvent(int howMany){
  if(tempDisplay){
    receiveTemp();
  }else{
    while(0 < Wire.available()){
      char c = Wire.read(); // receive byte as a character
      if(c=='*'){ // Searching for a '*' character
        tempDisplay=true; // If '*' received, then call receiveTemp() function
      }
    }
  }
}



/* This function is used to receive and process the Temperature data 
   from the Arduino Master and pass it on to the  displayTemp() funtion.
*/
void receiveTemp(){
  tempReading="";
  dayOfWeek = "";
  
  while(0 < Wire.available()){
    char c = Wire.read(); // receive byte as a character
    if(readTemp){
      if(c=='.'){ // If a . is detected. It is the end of the line.
        readTemp=false;
      }else{
        tempReading=tempReading+c;
      }
    }else{
      if(c==','){
      } else {
        dayOfWeek=dayOfWeek+c;
      }
    }
    if(c==','){
      readTemp=true;
    }
  }
  displayTemp();
}



/*
  Display the Temperature readings on the TFT LCD screen.
*/
void displayTemp(){
  //Clear the writing on top and bottom of screen
  myGLCD.setColor(25, 35, 4);
  myGLCD.fillRect(0, 0, 159, 13);
  myGLCD.fillRect(0, 114, 159, 127);
  
  //Small writing on top and bottom of screen
  myGLCD.setColor(255, 255, 255);
  myGLCD.setBackColor(25, 35, 4);
  myGLCD.setFont(SmallFont);
  myGLCD.print(Address, CENTER, 1);
  myGLCD.print(dayOfWeek, CENTER, 114);
  
  //Write the big temperature reading in middle of screen
  myGLCD.setBackColor(0, 0, 0);
  myGLCD.setFont(SevenSegNumFont);
  myGLCD.print(tempReading, CENTER, 40);
  
  //Write the Units next to the temperature reading
  myGLCD.setFont(BigFont);
  myGLCD.print(Units, RIGHT, 40);
}

 
 
 

Wiring it up

Once the code has been uploaded to both Arduinos (Master and Slave), I tend to label each Arduino so that I don't mix them up. You will notice an 'S' marked on the SLAVE in some of the photos/videos. Then it is time to piggy-back the shields onto the Arduinos and wire them up. Make sure you disconnect the USB cable from the Arduinos before you start doing this.

 

Step 1: Ethernet Shield

Place the Ethernet shield onto the Arduino MASTER. Connect an Ethernet cable (RJ45) to the Ethernet shield. The other end will connect to your internet router.

 
 

Step 2: Arduino SLAVE and TFT LCD module

 
You can either wire up the TFT LCD module on a breadboard, or you can use a ProtoShield with mini-breadboard. It doesn't really matter how you hook it up, but make sure you double check the connections and the TFT specifications before you power it up. I have powered the Arduino Slave by connecting it to the Arduino Master (see fritzing sketch below).  
There is no reason why you couldn't just power the slave seperately. In fact this is probably the safer option. But I read that this power-sharing setup was ok, so I wanted to give it a go. I have no idea whether it would be suitable for a long term power project... so use it at your own risk. I tried using 4 x AA batteries to power this circuit, but found that the LCD screen would flicker. So then I tried a 9V battery, and noticed that the 5V voltage regulator was heating up more than I felt comfortable with. In the end, I settled with the USB option, and had no further issues. I am sure there are other possible options, and feel free to mention them in the comments below.  
Use the following fritzing sketch and tables to help you wire this circuit up.

 

Fritzing sketch

 

 
 

 

Arduino MASTER to SLAVE connection table

 

 
 

 

Arduino SLAVE to ITDB02-1.8SP TFT LCD

 

 
 

ITDB02-1.8SP TFT LCD Module Pictures

 

 

 
 

Project Pictures

 

 

 

 



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.
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.

E-Paper Barcode 39

E-Paper (or Electronic paper) is a display technology that mimics the appearance of ordinary ink on paper. E-paper displays do not emit light, rather they reflect light, thus making them much more comfortable to read and provide a wider viewing angle than most light emitting displays (source: Wikipedia).

I printed something to an E-paper display, unplugged it, and could still read the message clearly months later. These E-paper displays are great for showing information that is static for long periods. You only need to provide power when the data or information needs updating.

Barcodes are used everywhere, and one of the simplest Barcodes to generate is the Code 39 format (also known as Code 3 of 9). I used an E-paper shield and E-paper module to display a number in this barcode format. I then tested it with a Barcode reader and it worked perfectly.
This tutorial will show you how to send a number to the Arduino from the Serial Monitor, and display the Barcode on the E-paper module.

Note: If you are using an Arduino UNO (or compatible), you will also need to get a micro SDHC card.
 

The Video


The video will show you how to assemble the shield and the module onto the Arduino, and also how to install the SDHC card.


 
 

Parts Required:

Library Download


To use the e-paper shield, you will need to download the Small e-paper Shield library.
This library will allow you to use the following functions on the e-paper shield:
  • begin : to set up the size of the e-paper panel
  • setDirection : to set up the display direction
  • drawChar : to display a Character at a specified position
  • drawString : to display a String of characters at a specified position
  • drawNumber and drawFloat : to display a number
  • drawLine : to draw a line
  • drawHorizontalLine : to draw a horizontal line
  • drawVerticalLine : to draw a vertical line
  • drawCircle : to draw a circle
  • fillCircle : to draw and fill a circle
  • drawRectangle : to draw a rectangle
  • fillRectangle : to draw and fill a rectangle
  • drawTriangle : to draw a triangle
You can also draw an image to the e-paper shield.

For more information on how to use these functions, please visit the seeedstudio wiki. If you are unfamiliar with installing libraries - then have a look at the following sites:

Barcode 39 Info

Barcode 39 (or Code 3 of 9) is a barcode that consists of black and white vertical lines. These lines can be thick or thin. Each character can be coded using 9 alternating black and white bars. The barcode always starts with a black bar, and ends with a black bar.

If you code using thin lines only, then each character can be coded using a total of 12 bars. A wide black line is essentially two thin black lines next to each other. Same goes for a wide white line. Because there are now only 2 options (black or white), you can create a binary code. I used a 1 for black bars, and 0 for white bars. If there was a thick black bar, then this would be represented with a 11. A thick white bar would be 00.

Each barcode sequence starts and ends with a hidden * character. Therefore if you were to display just the number 1, you would have to provide the code for *1*.

  • * = 100101101101
  • 1 = 110100101011
  • * = 100101101101
Notice that each character starts with a 1 and ends with a 1.
Something also to take note of: is that each character is separated by a thin white line (and not represented in the binary code).

All of these 0's and 1's can get a bit confusing, so I decided to represent these binary numbers as decimals. For example, the picture below shows how a 0 and an 8 would be coded (without the *):

 



The table below provides the binary and decimal codes for each number used in this tutorial. I have also included for your own reference, each letter of the alphabet, however I did not use these in this tutorial.

The binary representation of each character in this table was obtained from this site.
www.barcodeisland.com is a great resource of information about barcodes.

I adapted their binary code into a decimal equivalent, and therefore had to create my own table.

 
 

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


/* ===============================================================
      Project: Display Barcodes on an e-Paper Panel
       Author: Scott C
      Created: 6th January 2015
  Arduino IDE: 1.0.5
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: This project will allow you to send a number from the Serial 
               Monitor to the Arduino. The number will then be displayed on 
               the e-Paper panel as a Code-39 barcode (and text).
================================================================== */

#include <ePaper.h>
#include <SPI.h>
#include <SD.h>
#include "GT20L16_drive.h"

const int maxBarcodeSize = 10; // set the maximum barcode size to 10 digits
int barcode[maxBarcodeSize]; // initialise the barcode array to the maximum 10 digits
int barcodeText[maxBarcodeSize]; // initialise the barcodeText array to the maximum 10 digits
int barcodePos; // Used to identify each digit within the barcode
int barcodeLength; // Used to identify the actual length of the barcode

/*  The following array holds the decimal code for each digit (0-9). 
    Each digit can be converted to binary and then drawn as a barcode.
                         0     1     2     3     4     5     6     7     8     9         */
int barcodeDecimal[] = {2669, 3371, 2859, 3477, 2667, 3381, 2869, 2651, 3373, 2861};

int astrix = 2413; // "*" character decimal code used at beginning and end of barcode sequence


/*  When drawBarcode = "no", the program will not draw the barcode on the e-paper panel
    When drawBarcode = "yes", the command to draw the barcode on the e-paper panel will be triggered. */
String drawBarcode = "no";


/*  This variable is the x Position on the e-Paper panel screen */
int xPosition;


void setup(){
    Serial.begin(9600); // Initialise Serial communication
    EPAPER.begin(EPD_2_0); // Set the e-Paper panel size to 2 inches
    EPAPER.setDirection(DIRNORMAL); // Set the e-Paper panel display direction (to Normal)
    eSD.begin(EPD_2_0); // Prepares the SD card
    GT20L16.begin(); // Initialise the GT20L16 font chip on the e-Paper panel
    barcodePos = 0;                    // Set the barcode digit to the first digit in the barcode
    EPAPER.clear_sd(); // Clear the screen when starting sketch
    
    EPAPER.drawString("http://arduinobasics", 10, 20); //splash screen text
    EPAPER.drawString(".blogspot.com", 60, 40);
    
    EPAPER.display(); // Display the splash screen
}


void loop(){
  
    // The Arduino will wait until it receives data from the Serial COM port
    
    while (Serial.available()>0){
      barcodeText[barcodePos] = Serial.read();
        
      if(barcodeText[barcodePos]>47 && barcodeText[barcodePos]<58){ // A number was sent
         barcode[barcodePos] = barcodeText[barcodePos]-48;            // Convert the decimal value from the serial monitor to a Number
      } 
      
      if(barcodeText[barcodePos]==46){ // If a "." is detected, then barcode is complete
        barcodeLength = barcodePos;                   // Set the length of the barcode (used later)
        drawBarcode = "yes"; // We can now draw the barcode
        
      }
      
      if(barcodePos>(maxBarcodeSize-1)){ // Check if maximum barcode length has been reached
       barcodeLength = barcodePos;                    // Set the length of the barcode (used later)
       drawBarcode = "yes"; // We can now draw the barcode
      }
     
       barcodePos++;                                  // Move to the next barcode digit
    }
    
    if(drawBarcode == "yes"){ // Only draw the barcode when drawBarcode = "yes"
      
      EPAPER.clear_sd(); // Clear the e-Paper panel in preparation for barcode
      xPosition = 15;                                 // Set the initial white-space on the left
      drawBCode(astrix, ' '); // Each barcode starts with an invisible *
      
      for(int digit=0; digit<barcodeLength; digit++){ // Start drawing the barcode numbers
        drawBCode(barcodeDecimal[barcode[digit]], barcodeText[digit]);  // Call the drawBCode method (see below)
      }
      
      drawBCode(astrix, ' '); // Each barcode ends with an invisible *
      EPAPER.display(); // Show the barcode image and text
      
      drawBarcode = "no"; // Stop it from drawing again until next barcode sequence sent
      barcodePos=0;                                   // Re-initialise the position back to first digit (in preparation for the next barcode)
    }
}


//The drawBCode method is the key method for drawing the barcode on the e-paper panel
void drawBCode(int bCode, char bCodeText){
  xPosition++;                                        // There is a white space between each digit
  for (int barPos = 11; barPos > -1; barPos--){ // Cycle through the binary code for each digit. Each digit is made up of 11 bars
    xPosition++;                                      // Advance the xPosition to draw the next bar (white or black)
    if(bitRead(bCode, barPos)==1){ // If the binary digit at this position is a 1, then draw a black line
      EPAPER.drawVerticalLine(xPosition, 10, 60); // This draws the individual Bar (black - only)
    }                                                 // If the binary digit is a 0, then it is left blank (or white).
  }
  EPAPER.drawChar(bCodeText, xPosition-9, 75); // Draw the human readable (text) portion of the barcode
}


 


 

There is something weird about the E-paper shield library which tends to display the word "temperature:" in the Serial monitor when opened, and with each serial transmission. Don't worry about this. Just ignore it.'


This tutorial shows you how to create your own renewable barcodes. While this only handles numbers at this stage, it could just as easily be upgraded to handle text as well. If you liked this tutorial, please give it a google+ thumbs up, share it with your friends, or just write a comment. Thankyou for visiting my blog.



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.
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.

DIY Canon Intervalometer using Arduino



An intervalometer allows you to take photos at set intervals to view a slow process in super fast speed. Watching paint dry is just as boring in fast motion as it is at normal speed, however, when you point your camera to the clouds in the sky, you can get some amazing effects.
 
By taking a picture every 3 seconds, and then playing the sequence back at 30 frames a second, you will get to see a 10 minute event in just 7 seconds.To get a nice flowing motion picture, you need to get a good balance between the recording frame rate, and the play-back frame rate.
 


 
The recording frame rate is limited by the amount of memory you have in your camera, the length of the captured event, battery charge, and the camera's general capabilities. The playback frame rate needs to be fast enough to prevent jittering, but not so fast that you lose the event in a blink of an eye. The more you practice with different subject matters, the more you get a feel for how long you need to keep the camera running and how long to leave between shots.
 
When taking pictures of the clouds, you can generally use a 3-5 second frame rate, depending on their speed across the sky. To capture the flow of traffic, I would recommend a picture every 1-2 seconds. However, for really slow events like a plant growing, you may need to extend the frame capture rate significantly. You will get a better idea once you try it for yourself.
 
 

 
This tutorial follows on from the Arduino selfie tutorial, so you might notice some similarities. However, in this tutorial, we will have more control over the intervalometer by using a sliding potentiometer and an LED bar. The pin layout is slightly different from the Arduino Selfie tutorial - so best to start from scratch to avoid pin misconfigurations.
 

Warning : Any circuit you build for your camera (including this one) is at your own risk. I will not take responsibility for any damage caused to any of your equipment.
 
I found out that my Canon Powershot SX50 HS camera has a port on the side for a remote switch. In the "Optional Accessories" section of the camera brochure, it identifies the remote switch model as RS-60E3. I then looked up the model number on this website to find out the size of the jack (3 core, 2.5mm), and the pinout (Ground, focus and shutter) required to emulate the remote switch. Once I had this information, I was able to solder some really long wires to the jack and connect up the circuit (as described below).
 
I use Time-Lapse tool to stitch all of the pictures together to create a movie/animation.
 
You will need to download and install the LED_Bar library from Seeedstudio into your Arduino IDE libraries folder in order to use the LED Bar in this tutorial. For more information about the LED Bar - visit the LED Bar Seeed-Studio wiki.
 

Parts Required:





 

Fritzing Sketch


 

 

 

 


 
 

Connection Tables


 
Arduino to Relay Module:
 

 
 
Relay Module to Camera:
 

 
 
Arduino to Slide Potentiometer:
 

 
 
Arduino to LED Bar:
 


 
 

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
    
/* ===============================================================
      Project: DIY Canon Intervalometer using Arduino
       Author: Scott C
      Created: 9th October 2014
  Arduino IDE: 1.0.5
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: Use Arduino as an intervalometer for Canon PowerShot SX50 HS
               A slide potentiometer is used to control the time between photos.
               The LED Bar is used to display the delay between photos.
               A 3 core 2.5mm jack is used to connect the Arduino and Relay module to the Camera.
================================================================== */

 /* You will need to download and install the LED_Bar library from here: https://github.com/Seeed-Studio/Grove_LED_Bar */
 #include <LED_Bar.h>

 /* Connect 5V on Arduino to VCC on Relay Module
    Connect GND on Arduino to GND on Relay Module */

 #define CH1 7   // Connect Digital Pin 7 on Arduino to CH1 on Relay Module
 #define CH3 6   // Connect Digital Pin 6 on Arduino to CH3 on Relay Module
 
 int potPin=A0; //Connect Slide potentiometer to Analog Pin 0 on Grove Base Shield
 int potValue=0; //The variable used to hold the value of the potentiometer

 LED_Bar bar1(9,8); //Connect LED Bar to Digital I/O 8 on Grove base shield.
                   //The LED Bar actually uses digital pin 8 and 9.

 void setup(){
   pinMode(CH1, OUTPUT);
   pinMode(CH3, OUTPUT);
   
   //Turn OFF any power to the Relay channels
   digitalWrite(CH1,LOW);
   digitalWrite(CH3,LOW);
   delay(2000); //Wait 2 seconds before starting sequence
   
   //Focus camera by switching Relay 1
   digitalWrite(CH1, HIGH);
   delay(2000);
   digitalWrite(CH1, LOW); //Stop focus
   delay(3000);
 }

 void loop(){
      // Read the slide potentiometer and convert the reading to a value between 0 and 10.
      potValue=constrain(map(analogRead(potPin),0,1000,0,10),0,10);
      
      //Use the pot value to create a visual count-down display on the LED bar.
      for(int i = potValue; i>0; i--){
        bar1.setLevel(i);
        delay(1000);
      }
      
      //If the pot value is less than 1, then delay for 30 seconds.
      if(potValue<1){
        delay(30000);
      }
      
      //Turn LED Bar off when taking photo
      bar1.setLevelReverse(0);
      
      //Press shutter button for 0.1 seconds. Modify delay if required.
      digitalWrite(CH3, HIGH);
      delay(100);
      digitalWrite(CH3,LOW); //Release shutter button
 }



 


The Video


 



This project shows how to make your Canon Powershot SX50 HS a whole lot smarter using an Arduino. There are so many things that look so different with an intervalometer. While I connected a slide potentiometer to the Arduino to provide extra flexibility, and an LED Bar for visual feedback, there are many other sensors out there that can be combined with the camera. For example, you could use a PIR sensor to take a picture when movement is detected. Or take a picture when a laser trip-wire is broken. What about sound activation, light activation, leak detection.... the options are limitless.
 
This has been one of my favorite projects, it was a lot of fun, and very interesting.
I highly recommend that you try it out!



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.
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 Selfie


 

My attention is drawn towards the noise behind me....
I cannot believe it.
There it is.

  The Arduino is taking a SELFIE !!


 

How did this happen?
 
Well actually, it is not that difficult for an Arduino.
 
I found out that my Canon Powershot SX50 HS camera has a port on the side for a remote switch. In the "Optional Accessories" section of the camera brochure, it identifies the remote switch model as RS-60E3. I then looked up the model number on this website to find out the size of the jack (3 core, 2.5mm), and the pinout (Ground, focus and shutter) required to emulate the remote switch. Once I had this information, I was able to solder some really long wires to the jack and connect up the circuit (as described below).
 

And before I knew it, the Arduino was taking Selfies !!!


 
Warning : Any circuit you build for your camera (including this one) is at your own risk. I will not take responsibility for any damage caused to any of your equipment.
 

Parts Required:


 

Fritzing Sketch


 


 
 

Connection Table


 


 
 

Three core, 2.5 mm jack


 


 
 

Camera Connection to Relays


 


 
 

Jack pinout


 


 
 

Completed Circuit


 


 
 

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

/* ===============================================================
      Project: Arduino Selfie
       Author: Scott C
      Created: 14th Sept 2014
  Arduino IDE: 1.0.5
      Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html
  Description: Arduino takes selfie every 30 seconds
================================================================== */

 /*
  Connect 5V on Arduino to VCC on Relay Module
  Connect GND on Arduino to GND on Relay Module */
 
 #define CH1 8   // Connect Digital Pin 8 on Arduino to CH1 on Relay Module
 #define CH3 7   // Connect Digital Pin 7 on Arduino to CH3 on Relay Module
 
 void setup(){
   //Setup all the Arduino Pins
   pinMode(CH1, OUTPUT);
   pinMode(CH3, OUTPUT);
   
   //Turn OFF any power to the Relay channels
   digitalWrite(CH1,LOW);
   digitalWrite(CH3,LOW);
   delay(2000); //Wait 2 seconds before starting sequence
 }
 
 void loop(){
   digitalWrite(CH1, HIGH); //Focus camera by switching Relay 1
   delay(2000);
   digitalWrite(CH1, LOW); //Stop focus
   delay(100);
   digitalWrite(CH3, HIGH); //Press shutter button for 0.5 seconds
   delay(500);
   digitalWrite(CH3,LOW); //Release shutter button
   delay(30000); //Wait 30 seconds before next selfie
 }


 

By connecting up the camera to an Arduino, the camera just got smarter !!
The Arduino connects to 2 different channels on the relay board in order to control the focus and the shutter of the camera. The relays are used to isolate the camera circuit from that of the Arduino. I have also included a couple of diodes and resistors in the circuit as an extra precaution, however they may not be needed.

Warning : Any circuit you build for your camera (including this one) is at your own risk. I will not take responsibility for any damage caused to any of your equipment. Do your research, and take any precautions you see fit.


 
 

The Video


 


 


 
 

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.
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.

Relay Module

WARNING: Mishandling or incorrect or improper use of relays could result in

  • serious personal injury or DEATH
  • possible physical damage of the product
  • faulty operation
  • or create serious/dangerous hazards.

Please make sure that you read and understand how your relay/relay module board works, the voltage and current it is rated for, and the risks involved in your project BEFORE you even attempt to start putting it together. Seek professional and qualified assistance BEFORE you undertake ANY high power projects.

If you choose to follow the instructions in this tutorial, you do so at your own risk. I am not an electrician, and am not a qualified electrical engineer - so please do your research and seek advice BEFORE undertaking a project using a relay. Please check your connections and test them BEFORE turning the power on.

I accept no responsibility for your project, or the risk/damage/fire/shock/injury/death/loss that it causes. You take full responsibility for your actions/project/creation, and do so at YOUR OWN RISK !!!

Please note: It is illegal in some countries to wire up a high power project without an electrician. Please check your country's rules/laws/regulations before you undertake your project. If you have any doubts - don't do it.


 

What is a relay

A Relay is an electrically operated switch. Many relays use an electromagnet to mechanically operate the switch and provide electrical isolation between two circuits. In this project there is no real need to isolate one circuit from the other, but we will use an Arduino UNO to control the relay. We will develop a simple circuit to demonstrate and distinguish between the NO (Normally open) and NC (Normally closed) terminals of the relay. We will then use the information gained in this tutorial to make a much more exciting circuit. But we have to start somewhere. So let's get on with it.

Parts Required:

Fritzing Sketch


 


 
 

Table of Connections



 
 

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


/* ===============================================================
      Project: 4 Channel 5V Relay Module
       Author: Scott C
      Created: 7th Sept 2014
  Arduino IDE: 1.0.5
      Website: http://arduinobasics.blogspot.com.au
  Description: Explore the difference between NC and NO terminals.
================================================================== */

 /*
  Connect 5V on Arduino to VCC on Relay Module
  Connect GND on Arduino to GND on Relay Module 
  Connect GND on Arduino to the Common Terminal (middle terminal) on Relay Module. */
 
 #define CH1 8   // Connect Digital Pin 8 on Arduino to CH1 on Relay Module
 #define CH3 7   // Connect Digital Pin 7 on Arduino to CH3 on Relay Module
 #define LEDgreen 4 //Connect Digital Pin 4 on Arduino to Green LED (+ 330 ohm resistor) and then to "NO" terminal on relay module
 #define LEDyellow 12 //Connect Digital Pin 12 on Arduino to Yellow LED (+ 330 ohm resistor) and then to "NC" terminal on relay module
 
 void setup(){
   //Setup all the Arduino Pins
   pinMode(CH1, OUTPUT);
   pinMode(CH3, OUTPUT);
   pinMode(LEDgreen, OUTPUT);
   pinMode(LEDyellow, OUTPUT);
   
   //Provide power to both LEDs
   digitalWrite(LEDgreen, HIGH);
   digitalWrite(LEDyellow, HIGH);
   
   //Turn OFF any power to the Relay channels
   digitalWrite(CH1,LOW);
   digitalWrite(CH3,LOW);
   delay(2000); //Wait 2 seconds before starting sequence
 }
 
 void loop(){
   digitalWrite(CH1, HIGH); //Green LED on, Yellow LED off
   delay(1000);
   digitalWrite(CH1, LOW); //Yellow LED on, Green LED off
   delay(1000);
   digitalWrite(CH3, HIGH); //Relay 3 switches to NO
   delay(1000);
   digitalWrite(CH3,LOW); //Relay 3 switches to NC
   delay(1000);
 }


 

The Red light on the Relay board turns on when power is applied (via the VCC pin). When power is applied to one of the Channel pins, the respective green light goes on, plus the relevant relay will switch from NC to NO. When power is removed from the channel pin, the relay will switch back to NC from NO. In this sketch we see that power is applied to both LEDs in the setup() method. When there is no power applied to the CH1 pin, the yellow LED will be on, and the Green LED will be off. This is because there is a break in the circuit for the green LED. When power is applied to CH1, the relay switches from NC to NO, thus closing the circuit for the green LED and opening the circuit for the yellow LED. The green LED turns on, and the yellow LED turns off.

I also show what happens when you apply power to a channel (eg. CH3) when there is nothing connected to the relay terminals. The respective onboard LED illuminates. This is useful for troubleshooting the relays, and knowing what state the relay is in (NC or NO). NC stands for Normally closed (or normally connected) NO stands for Normally open (or normally disconnected)

Here is a circuit diagram for two of the relays on the relay module (CH1 and CH2).
This was taken from the iteadstudio site.

 


 
 

The Video


 



 

This tutorial will become very useful in the future. I now have an easy way of switching a circuit electronically. Yes, I could do this with a transistor, but sometimes it is nice to hear that mechanical click. I am not sure why I like relays, but I find them to be quite fun !!

If you liked this tutorial - please show your support :


 
 

 
 

Grove Water Sensor


Connecting a water sensor to an Arduino is a great way to detect a leak, spill, flood, rain etc. It can be used to detect the presence, level, volume and/or the absence of water. While this could be used to remind you to water your plants, there is a better Grove sensor for that. The sensor has an array of exposed traces which will read LOW when water is detected. In this tutorial, we will connect the Water Sensor to Digital Pin 8 on the Arduino, and will enlist the very handy Grove Piezo buzzer and an LED to help identify when the Water sensor comes into contact with a source of water.


 

Parts Required:

Putting it together


If you have a Grove Base Shield, you just have to connect the Grove Water Sensor to D8 on the shield, and the Buzzer to D12 on the Shield. My Grove base shield obstructs the onboard LED, so I will attach an LED to Digital pin 13. If you do not have a Grove base shield, then you should connect the Sensors as described in the tables below:
 


 

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


/* 
  Grove Water Sensor sketch 
     Written by ScottC 5th August 2014
     Arduino IDE version 1.0.5
     Website: http://arduinobasics.blogspot.com
     Description: Use Grove Water Sensor to detect leaks, floods, spills, rain etc.
     Credits: This sketch was inspired by this website:
              http://www.seeedstudio.com/wiki/Grove_-_Water_Sensor     
 ------------------------------------------------------------- */
#define Grove_Water_Sensor 8     //Attach Water sensor to Arduino Digital Pin 8
#define Grove_Piezo_Buzzer 12    //Attach Piezo Buzzer to Arduino Digital Pin 12
#define LED 13                   //Attach an LED to Digital Pin 13 (or use onboard LED)
void setup(){
pinMode(Grove_Water_Sensor, INPUT); //The Water Sensor is an Input
pinMode(Grove_Piezo_Buzzer, OUTPUT); //The Piezo Buzzer is an Output
        pinMode(LED, OUTPUT); //The LED is an Output
}

void loop(){
        /* The water sensor will switch LOW when water is detected.
           Get the Arduino to illuminate the LED and activate the buzzer
           when water is detected, and switch both off when no water is present */
if(digitalRead(Grove_Water_Sensor) == LOW){
                digitalWrite(LED,HIGH);
digitalWrite(Grove_Piezo_Buzzer, HIGH);
                delay(2);
                digitalWrite(Grove_Piezo_Buzzer, LOW);
                delay(40);
        }else{
                digitalWrite(Grove_Piezo_Buzzer, LOW);
                digitalWrite(LED,LOW);
        }
}


 

The Video


 


If you liked this tutorial - please show your support :

ScottC 05 Aug 16:38

433 MHz RF module with Arduino Tutorial 4:

WARNING: Please check whether you can legally use RF transmitters and receivers at your location before attempting this project (or buying the components). This project is aimed at those who are looking to automate their home.

Carrying on from my previous "433MHz transmitter and receiver" tutorials (1,2 & 3): I have thrown away the need to process the signal with a computer. This means that we can now get the Arduino to record the signal from an RF remote (in close proximity), and play it back in no time at all.

The Arduino will forget the signal when powered down or when the board is reset. The Arduino does not have an extensive memory - there is a limit to how many signals can be stored on the board at any one time. Some people have opted to create a "code" in their projects to help maximise the number of signals stored on the board. In the name of simplicity, I will not encode the signal like I did in my previous tutorials.

I will get the Arduino to record the signal and play it back - with the help of a button. The button will help manage the overall process, and control the flow of code.

Apart from uploading the sketch to the Arduino, this project will not require the use of a computer. Nor will it need a sound card, or any special libraries. Here are the parts required:


 

Parts Required:

Fritzing Sketch


 


 
 

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



/* 
  433 MHz RF REMOTE REPLAY sketch 
     Written by ScottC 24 Jul 2014
     Arduino IDE version 1.0.5
     Website: http://arduinobasics.blogspot.com
     Receiver: XY-MK-5V      Transmitter: FS1000A/XY-FST
     Description: Use Arduino to receive and transmit RF Remote signal          
 ------------------------------------------------------------- */
 
 #define rfReceivePin A0     //RF Receiver data pin = Analog pin 0
 #define rfTransmitPin 4  //RF Transmitter pin = digital pin 4
 #define button 6           //The button attached to digital pin 6
 #define ledPin 13        //Onboard LED = digital pin 13
 
 const int dataSize = 500; //Arduino memory is limited (max=1700)
 byte storedData[dataSize]; //Create an array to store the data
 const unsigned int threshold = 100; //signal threshold value
 int maxSignalLength = 255; //Set the maximum length of the signal
 int dataCounter = 0; //Variable to measure the length of the signal
 int buttonState = 1; //Variable to control the flow of code using button presses
 int buttonVal = 0; //Variable to hold the state of the button
 int timeDelay = 105; //Used to slow down the signal transmission (can be from 75 - 135)

 void setup(){
   Serial.begin(9600); //Initialise Serial communication - only required if you plan to print to the Serial monitor
   pinMode(rfTransmitPin, OUTPUT);
   pinMode(ledPin, OUTPUT);
   pinMode(button, INPUT);
 }
 
 void loop(){
   buttonVal = digitalRead(button);
  
   if(buttonState>0 && buttonVal==HIGH){
     //Serial.println("Listening for Signal");
     initVariables();
     listenForSignal();
   }
   
   buttonVal = digitalRead(button);
   
   if(buttonState<1 && buttonVal==HIGH){
     //Serial.println("Send Signal");
     sendSignal();
   }
   
   delay(20);
 }
 
 
 /* ------------------------------------------------------------------------------
     Initialise the array used to store the signal 
    ------------------------------------------------------------------------------*/
 void initVariables(){
   for(int i=0; i<dataSize; i++){
     storedData[i]=0;
   }
   buttonState=0;
 }
 
 
 /* ------------------------------------------------------------------------------
     Listen for the signal from the RF remote. Blink the RED LED at the beginning to help visualise the process
     And also turn RED LED on when receiving the RF signal 
    ------------------------------------------------------------------------------ */
 void listenForSignal(){
   digitalWrite(ledPin, HIGH);
   delay(1000);
   digitalWrite(ledPin,LOW);
   while(analogRead(rfReceivePin)<threshold){
     //Wait here until an RF signal is received
   }
   digitalWrite(ledPin, HIGH);
   
   //Read and store the rest of the signal into the storedData array
   for(int i=0; i<dataSize; i=i+2){
     
      //Identify the length of the HIGH signal---------------HIGH
      dataCounter=0; //reset the counter
      while(analogRead(rfReceivePin)>threshold && dataCounter<maxSignalLength){
        dataCounter++;
      }  
      storedData[i]=dataCounter;    //Store the length of the HIGH signal
    
      
      //Identify the length of the LOW signal---------------LOW
      dataCounter=0;//reset the counter
      while(analogRead(rfReceivePin)<threshold && dataCounter<maxSignalLength){
        dataCounter++;
      }
      storedData[i+1]=dataCounter;  //Store the length of the LOW signal
   }
   
     storedData[0]++;  //Account for the first AnalogRead>threshold = lost while listening for signal
     digitalWrite(ledPin, LOW);
 }
 
 
 /*------------------------------------------------------------------------------
    Send the stored signal to the FAN/LIGHT's RF receiver. A time delay is required to synchronise
    the digitalWrite timeframe with the 433MHz signal requirements. This has not been tested with different
    frequencies.
    ------------------------------------------------------------------------------ */
 void sendSignal(){
   digitalWrite(ledPin, HIGH);
   for(int i=0; i<dataSize; i=i+2){
       //Send HIGH signal
       digitalWrite(rfTransmitPin, HIGH);
       delayMicroseconds(storedData[i]*timeDelay);
       //Send LOW signal
       digitalWrite(rfTransmitPin, LOW);
       delayMicroseconds(storedData[i+1]*timeDelay);
   }
   digitalWrite(ledPin, LOW);
   delay(1000);
   
   
   /*-----View Signal in Serial Monitor
   for(int i=0; i<dataSize; i=i+2){
       Serial.println("HIGH,LOW");
       Serial.print(storedData[i]);
       Serial.print(",");
       Serial.println(storedData[i+1]);
   }
   ---------------------------------- */
 }
 


 

Now let's see this project in action !

Have a look at the video below to see the Arduino turning a light and fan on/off shortly after receiving the RF signal from the RF remote. The video will also show you how to put this whole project together - step by step.

The Video


 


This concludes my 433MHz transmitter and receiver tutorials (for now). I hope you enjoyed them.
Please let me know whether this worked for you or not.
I have not tested this project with other remotes or other frequencies - so would be interested to find out whether this technique can be used for ALL RF projects ??

 
  Loading...



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.
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.

ScottC 29 Jul 19:09

433 MHz RF module with Arduino Tutorial 4:




WARNING: Please check whether you can legally use RF transmitters and receivers at your location before attempting this project (or buying the components). This project is aimed at those who are looking to automate their home.
There are 4 parts to this tutorial:
To get the most out of this tutorial - it is best to start at tutorial Part 1, and then progress to Part 2 then Part 3 and then do Part 4 last. Doing the RF tutorials in this order will help you to understand the process better.


Project 4 : 433 Mhz RF remote replacement tutorial

Carrying on from my previous "433MHz transmitter and receiver" tutorials (1,2 & 3): I have thrown away the need to process the signal with a computer. This means that we can now get the Arduino to record the signal from an RF remote (in close proximity), and play it back in no time at all.
The Arduino will forget the signal when powered down or when the board is reset. The Arduino does not have an extensive memory - there is a limit to how many signals can be stored on the board at any one time. Some people have opted to create a "code" in their projects to help maximise the number of signals stored on the board. In the name of simplicity, I will not encode the signal like I did in my previous tutorials.
I will get the Arduino to record the signal and play it back - with the help of a button. The button will help manage the overall process, and control the flow of code.
Apart from uploading the sketch to the Arduino, this project will not require the use of a computer. Nor will it need a sound card, or any special libraries. Here are the parts required:


 

Parts Required:





Fritzing Sketch


 


 
 

Arduino Sketch


 

 
Now let's see this project in action !
Have a look at the video below to see the Arduino turning a light and fan on/off shortly after receiving the RF signal from the RF remote. The video will also show you how to put this whole project together - step by step.

The Video


 


This concludes my 433MHz transmitter and receiver tutorials (for now). I hope you enjoyed them.
Please let me know whether this worked for you or not.
I have not tested this project with other remotes or other frequencies - so would be interested to find out whether this technique can be used for ALL RF projects ??

 
 



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.
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.
ScottC 29 Jul 19:09