Posts with «remote» label

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

433 MHz RF module with Arduino Tutorial 3



 
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 3: RF Remote Control Emulation

In the first tutorial, I introduced the 433 MHz Transmitter and Receiver with a simple sketch to test their functionality. In the second tutorial, the 433MHz receiver was used to receive a signal from an RF remote. The RF remote signal was coded based on the pattern and length of its HIGH and LOW signals. The signals received by the remote can be described by the code below:

 
Code comparison table



The RF remote that I am using transmits the same signal 6 times in a row. The signal to turn the light on is different from that used to turn the light off. In tutorial 2, we were able to "listen to" or receive the signal from the RF remote using the RF receiver. I thought it would be possible to just play back the signal received on the Arduino's analogPin, but the time it takes to perform a digital write is different to the time it takes to do an AnalogRead. Therefore it won't work. You need to slow down the digitalWrite speed.
I would like to find out if it is possible to apply this delay to all 433 MHz signal projects, however, I only have one 433 MHz remote.

If the delay in your project is the same as mine (or different) I would be keen to know - please leave a comment at the end of the tutorial.

We are going to use trial and error to find the optimal digitalWrite delay time. We will do this by slowly incrementing the delay until the transmission is successful. The transmission is considered successful if the fan-light turns on/off. All we have to do is count the number of transmissions until it is successful, then we should be able to calculate the delay.

 

Parts Required




 

The Transmitter Fritzing Sketch



 
 

RF Calibration - Arduino Sketch


I used an array to hold the RF code for light ON and light OFF. Each number within the code represents a specific sequence of HIGH and LOW lengths. For example, 2 represents a SHORT HIGH and a LONG LOW combination. A short length = 3, a long length = 7, and a very long length = 92. You need to multiply this by the timeDelay variable to identify how much time to transmit the HIGH and LOW signals for.
The short and long lengths were identified from the experiments performed in tutorial 2 (using the RF receiver). Each code is transmitted 6 times. The LED is turned on at the beginning of each transmission, and then turned off at the end of the transmission. The timeDelay variable starts at 5 microseconds, and is incremented by 10 microseconds with every transmission.
In the video, you will notice that there is some flexibility in the timeDelay value. The Mercator Fan/Light will turn on and off when the timeDelay variable is anywhere between 75 and 135 microseconds in length. It also seems to transmit successfully when the timeDelay variable is 175 microseconds.
So in theory, if we want to transmit a signal to the fan/light, we should be able to use any value between 75 and 135, however in future projects, I think I will use a value of 105, which is right about the middle of the range.


Video




  Now that I have the timeDelay variable, I should be able to simplify the steps required to replicate a remote control RF signal. Maybe there is room for one more tutorial on this topic :)

Update: Here it is - tutorial 4
Where you can record and playback an RF signal (without using your computer).


433 MHz RF module with Arduino Tutorial 3



 

Project 3: RF Remote Control Emulation

In the first tutorial, I introduced the 433 MHz Transmitter and Receiver with a simple sketch to test their functionality. In the second tutorial, the 433MHz receiver was used to receive a signal from an RF remote. The RF remote signal was coded based on the pattern and length of its HIGH and LOW signals. The signals received by the remote can be described by the code below:

 
Code comparison table



The RF remote that I am using transmits the same signal 6 times in a row. The signal to turn the light on is different from that used to turn the light off. In tutorial 2, we were able to "listen to" or receive the signal from the RF remote using the RF receiver. I thought it would be possible to just play back the signal received on the Arduino's analogPin, but the time it takes to perform a digital write is different to the time it takes to do an AnalogRead. Therefore it won't work. You need to slow down the digitalWrite speed.
I would like to find out if it is possible to apply this delay to all 433 MHz signal projects, however, I only have one 433 MHz remote.

If the delay in your project is the same as mine (or different) I would be keen to know - please leave a comment at the end of the tutorial.

We are going to use trial and error to find the optimal digitalWrite delay time. We will do this by slowly incrementing the delay until the transmission is successful. The transmission is considered successful if the fan-light turns on/off. All we have to do is count the number of transmissions until it is successful, then we should be able to calculate the delay.

 

Parts Required




 

The Transmitter Fritzing Sketch



 
 

RF Calibration - 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
/* 
  Transmit sketch - RF Calibration
     Written by ScottC 17 July 2014
     Arduino IDE version 1.0.5
     Website: http://arduinobasics.blogspot.com
     Transmitter: FS1000A/XY-FST
     Description: A simple sketch used to calibrate RF transmission.          
 ------------------------------------------------------------- */

 #define rfTransmitPin 4  //RF Transmitter pin = digital pin 4
 #define ledPin 13        //Onboard LED = digital pin 13
 
 const int codeSize = 25; //The size of the code to transmit
 int codeToTransmit[codeSize]; //The array used to hold the RF code
 int lightON[]={2,2,2,2,1,4,4,4,4,5,1,4,4,4,4,4,4,5,2,2,1,4,4,4,6}; //The RF code that will turn the light ON
 int lightOFF[]={2,2,2,2,1,4,4,4,4,5,1,4,4,4,4,4,4,5,2,2,2,2,2,2,3}; //The RF code that will turn the light OFF
 int codeToggler = 0; //Used to switch between turning the light ON and OFF
 int timeDelay=5; // The variable used to calibrate the RF signal lengths.

 
 
 void setup(){
   Serial.begin(9600); // Turn the Serial Protocol ON
   pinMode(rfTransmitPin, OUTPUT); //Transmit pin is an output
   pinMode(ledPin, OUTPUT);
  
 //LED initialisation sequence - gives us some time to get ready
  digitalWrite(ledPin, HIGH);
  delay(3000);
  digitalWrite(ledPin, LOW);
  delay(1000);
 }
 
 
 
  void loop(){
    toggleCode();    // switch between light ON and light OFF
    transmitCode();  // transmit the code to RF receiver on the Fan/Light
    
    timeDelay+=10;    //Increment the timeDelay by 10 microseconds with every transmission
    delay(2000); //Each transmission will be about 2 seconds apart.
  }
  
  
  
  
  /*----------------------------------------------------------------
     toggleCode(): This is used to toggle the code for turning 
                   the light ON and OFF 
  -----------------------------------------------------------------*/
  void toggleCode(){
    if(codeToggler){
       for(int i = 0; i<codeSize; i++){
         codeToTransmit[i]=lightON[i];
       } 
      
    } else{
      for(int i = 0; i<codeSize; i++){
         codeToTransmit[i]=lightOFF[i];
       } 
    }
    codeToggler=!codeToggler;
  }
   
   
   
   
  /*-----------------------------------------------------------------
    transmitCode(): Used to transmit the signal to the RF receiver on
                    the fan/light. There are 6 different HIGH-LOW signal combinations. 
                    
                    SH = short high   or  LH = long high   
                                     PLUS
         SL = short low    or    LL = long low    or    VLL = very long low
                    
  -------------------------------------------------------------------*/
   void transmitCode(){
    // The LED will be turned on to create a visual signal transmission indicator.
    digitalWrite(ledPin, HIGH);
   
   //initialise the variables
    int highLength = 0;
    int lowLength = 0;
    
    //The signal is transmitted 6 times in succession - this may vary with your remote.
    for(int j = 0; j<6; j++){
      for(int i = 0; i<codeSize; i++){
        switch(codeToTransmit[i]){
          case 1: // SH + SL
            highLength=3;
            lowLength=3;
          break;
          case 2: // SH + LL
            highLength=3;
            lowLength=7;
          break;
          case 3: // SH + VLL
            highLength=3;
            lowLength=92;
          break;
          case 4: // LH + SL
            highLength=7;
            lowLength=3;
          break;
          case 5: // LH + LL
            highLength=7;
            lowLength=7;
          break;
          case 6: // LH + VLL
            highLength=7;
            lowLength=92;
          break;
        }
           
         /* Transmit a HIGH signal - the duration of transmission will be determined
            by the highLength and timeDelay variables */
         digitalWrite(rfTransmitPin, HIGH);
         delayMicroseconds(highLength*timeDelay);
         
         /* Transmit a LOW signal - the duration of transmission will be determined
            by the lowLength and timeDelay variables */
         digitalWrite(rfTransmitPin,LOW);
         delayMicroseconds(lowLength*timeDelay);
      }
    }
    //Turn the LED off after the code has been transmitted.
    digitalWrite(ledPin, LOW);
 }
I used an array to hold the RF code for light ON and light OFF. Each number within the code represents a specific sequence of HIGH and LOW lengths. For example, 2 represents a SHORT HIGH and a LONG LOW combination. A short length = 3, a long length = 7, and a very long length = 92. You need to multiply this by the timeDelay variable to identify how much time to transmit the HIGH and LOW signals for.
The short and long lengths were identified from the experiments performed in tutorial 2 (using the RF receiver). Each code is transmitted 6 times. The LED is turned on at the beginning of each transmission, and then turned off at the end of the transmission. The timeDelay variable starts at 5 microseconds, and is incremented by 10 microseconds with every transmission.
In the video, you will notice that there is some flexibility in the timeDelay value. The Mercator Fan/Light will turn on and off when the timeDelay variable is anywhere between 75 and 135 microseconds in length. It also seems to transmit successfully when the timeDelay variable is 175 microseconds.
So in theory, if we want to transmit a signal to the fan/light, we should be able to use any value between 75 and 135, however in future projects, I think I will use a value of 105, which is right about the middle of the range.


Video




  Now that I have the timeDelay variable, I should be able to simplify the steps required to replicate a remote control RF signal. Maybe there is room for one more tutorial on this topic :)

Update: Here it is - tutorial 4
Where you can record and playback an RF signal (without using your computer).
 


433 MHz RF module with Arduino Tutorial 2




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 2: RF Remote Copy

In the previous project, we transmitted a signal wirelessly from one Arduino to another. It was there to help troubleshoot communication between the modules. It was important to start with a very short distance (1-2 cm) and then move the RF modules further apart to test the range. The range can be extended by soldering an antenna to the module, or by experimenting with different voltage supplies to the modules (making sure to keep within the voltage limits of the modules.)
In this project - we aim to receive a signal from an RF remote. The remote that I am using is a Mercator Remote Controller for a Fan/Light. (Remote controller code is FRM94). It is important that you use a remote that transmits at the same frequency as your receiver. In this case, my remote just happens to use a frequency of 433MHz. I was able to receive RF signals from from a distance of about 30cm without an antenna (from my remote to the receiver).


Video





Here are the parts that you will need to carry out this project:
 

Parts Required


Remote Controller


You can quickly test your remote, by pressing one of the buttons in close proximity to the RF receiver (using the same sketch as in Project 1), and you should see the LED flicker on an off in response to the button press. If you don't see the LED flickering, then this project will not work for you.

Here is a picture of the remote controller that I am using:

 
 

Arduino Sketch - Remote Receiver

The following sketch will make the Arduino wait until a signal is detected from the remote (or other 433 MHz RF device). Once triggered, it will turn the LED ON, and start to collect and store the signal data into an array.
I did my best to keep the signal reading section of the sketch free from other functions or interruptions.The aim is to get the Arduino to focus on reading ONLY... and once the reading phase is complete, it will report the signal data to the Serial monitor. So you will need to have the Serial monitor open when you press the remote control button.
The remote control signal will be made up of HIGH and LOW signals - which I will try to illustrate later in the tutorial. But for now, all you need to know is that the Signal will alternate between HIGH and LOW signals, and that they can be different lengths.
This sketch aims to identify how long each LOW and HIGH signal is (to make up the complete RF remote signal). I have chosen to capture 500 data points(or 250 LOW/HIGH combinations).You may wish to increase or decrease the dataSize variable to accomodate your specific RF signal. In my case, I only really needed 300 data points, because there was a "flat" signal for the last 200 data points (characterised by 200 repetitions of a LOW signal length of 0 and HIGH signal length of 255)

--------------------------------------------------


Receiver Fritzing Sketch



Results

After pressing the button on the RF remote, the data signal is printed to the Serial Monitor. You can copy the data to a spreadsheet program for review. This is an example of the signal produced after pushing the button on the remote for turning the fan/light on.
The following code was produced from pushing the button responsible for turning the light off:
The code sequence above may seem a bit random until you start graphing it. I grabbed the LOW column - and produced the following chart:
The chart above is a bit messy - mainly because the timing is slightly out... in that sometimes it can squeeze an extra read from a particular signal. But what is important to note here is that you can differentiate a LONG signal from a SHORT signal. I have drawn a couple of red dotted lines where I believe most of the readings tend to sit. I then used a formula in the spreadsheet to calibrate the readings and make them a bit more uniform. For example, if the length of the signal was greater than 4 analogReads, then I converted this to 6. If it was less than 4 analogReads, then I converted it to 2. I used a frequency table to help decide on the cutoff value of 4, and just decided to pick the two values (2 for short, and 6 for long) based on the frequency tables below. I could have chosen 5 as the LONG value, but there were more 6's overall.

  **The meaning of "frequency" in the following tables relate to the "number of times" a specific signal length is recorded.


And this is the resulting chart:

You will notice that the pattern is quite repetitive. I helped to identify the sections with vertical red lines (near the bottom of the chart). In other words, the signal produced by the remote is repeated 6 times.
I then did the same for the HIGH signal column and combined the two to create the following chart:



 
You will notice that the HIGH signals also have a repetitive pattern, however have a Very long length at the end of each section. This is almost a break to separate each section.
This is what a single section looks like zoomed in:



SL = [Short LOW] signal. - or short blue bar
SH = [Short HIGH] signal - or short yellow bar
LL = [Long LOW] signal - or long blue bar
LH = [Long HIGH] signal - or long yellow bar
VLH = [Very long HIGH} signal - or very long yellow bar (~92 analogReads in length)


  You will notice that there are only about 6 different combinations of the signals mentioned above. We can use this to create a coding system as described below:


 
We can use this coding system to describe the signals. The charts below show the difference between turning the LIGHT ON and LIGHT OFF.


 


 
PLEASE NOTE: You may notice when you copy the signals from the Serial monitor that you get a series of (0,255) combinations. This is actually a timeout sequence - which generally occurs after the signal is complete.

 Here is an example of what I mean.



This is the end of tutorial 2. In the next tutorial, we will use the code acquired from the remote to turn the FAN LIGHT on and off (using the 433 MHz RF transmitter).

Click here for Tutorial 3

ScottC 26 Jun 18:05

433 MHz RF module with Arduino Tutorial 2

Project 2: RF Remote Copy

In the previous project, we transmitted a signal wirelessly from one Arduino to another. It was there to help troubleshoot communication between the modules. It was important to start with a very short distance (1-2 cm) and then move the RF modules further apart to test the range. The range can be extended by soldering an antenna to the module, or by experimenting with different voltage supplies to the modules (making sure to keep within the voltage limits of the modules.)

In this project - we aim to receive a signal from an RF remote. The remote that I am using is a Mercator Remote Controller for a Fan/Light. (Remote controller code is FRM94). It is important that you use a remote that transmits at the same frequency as your receiver. In this case, my remote just happens to use a frequency of 433MHz. I was able to receive RF signals from from a distance of about 30cm without an antenna (from my remote to the receiver).


Video




Here are the parts that you will need to carry out this project:
 

Parts Required


Remote Controller

You can quickly test your remote, by pressing one of the buttons in close proximity to the RF receiver (using the same sketch as in Project 1), and you should see the LED flicker on an off in response to the button press. If you don't see the LED flickering, then this project will not work for you.

Here is a picture of the remote controller that I am using:


 
 

Arduino Sketch - Remote Receiver

The following sketch will make the Arduino wait until a signal is detected from the remote (or other 433 MHz RF device). Once triggered, it will turn the LED ON, and start to collect and store the signal data into an array.

I did my best to keep the signal reading section of the sketch free from other functions or interruptions.The aim is to get the Arduino to focus on reading ONLY... and once the reading phase is complete, it will report the signal data to the Serial monitor. So you will need to have the Serial monitor open when you press the remote control button.

The remote control signal will be made up of HIGH and LOW signals - which I will try to illustrate later in the tutorial. But for now, all you need to know is that the Signal will alternate between HIGH and LOW signals, and that they can be different lengths.

This sketch aims to identify how long each LOW and HIGH signal is (to make up the complete RF remote signal). I have chosen to capture 500 data points(or 250 LOW/HIGH combinations).You may wish to increase or decrease the dataSize variable to accomodate your specific RF signal. In my case, I only really needed 300 data points, because there was a "flat" signal for the last 200 data points (characterised by 200 repetitions of a LOW signal length of 0 and HIGH signal length of 255)


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



/* 
  RF Remote Capture sketch 
     Written by ScottC 24 Jun 2014
     Arduino IDE version 1.0.5
     Website: http://arduinobasics.blogspot.com
     Receiver: XY-MK-5V
     Description: Use Arduino to Receive RF Remote signal          
 ------------------------------------------------------------- */

 const int dataSize = 500; //Arduino memory is limited (max=1700)
 byte storedData[dataSize]; //Create an array to store the data
 #define ledPin 13           //Onboard LED = digital pin 13
 #define rfReceivePin A0     //RF Receiver data pin = Analog pin 0
 const unsigned int upperThreshold = 100; //upper threshold value
 const unsigned int lowerThreshold = 80; //lower threshold value
 int maxSignalLength = 255; //Set the maximum length of the signal
 int dataCounter = 0; //Variable to measure the length of the signal
 unsigned long startTime=0; //Variable to record the start time
 unsigned long endTime=0; //Variable to record the end time
 unsigned long signalDuration=0; //Variable to record signal reading time
 

 void setup(){
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  
  /* The following code will only run ONCE --------------
  ---Press the reset button on the Arduino to run again-- */
  
  while(analogRead(rfReceivePin)<1){
      //Wait here until a LOW signal is received
      startTime=micros(); //Update start time with every cycle.
  }
  digitalWrite(ledPin, HIGH); //Turn LED ON
  
  
  //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 LOW signal---------------LOW
    dataCounter=0; //reset the counter
    while(analogRead(rfReceivePin)>upperThreshold && dataCounter<maxSignalLength){
      dataCounter++;
    }
    storedData[i]=dataCounter;
    
    //Identify the length of the HIGH signal---------------HIGH
    dataCounter=0;//reset the counter
    while(analogRead(rfReceivePin)<lowerThreshold && dataCounter<maxSignalLength){
      dataCounter++;
    }
    storedData[i+1]=dataCounter;
    
    //Any readings between the two threshold values will be ignored.
    //The LOW or HIGH signal length must be less than the variable "maxSignalLength"
    //otherwise it will be truncated. All of the HIGH signals and LOW signals combined
    //must not exceed the variable "dataSize", otherwise it will be truncated.
    //The maximum number of signals is 1700 - if you try to extend this variable to a higher
    //number than 1700 - then the Arduino will freeze up and sketch will not work.
    //-------------------------------------------------------------
  }
  
  endTime=micros(); //Record the end time of the read period.
  signalDuration = endTime-startTime;
  
  digitalWrite(ledPin, LOW);//Turn LED OFF
  
  //Send report to the Serial Monitor
  Serial.println("=====================");
  Serial.print("Read duration: ");
  Serial.print(signalDuration);
  Serial.println(" microseconds");
  Serial.println("=====================");
  Serial.println("LOW,HIGH");
  delay(20);
  for(int i=0; i<dataSize; i=i+2){
    Serial.print(storedData[i]);
    Serial.print(",");
    Serial.println(storedData[i+1]);
    delay(20);
  }
 }

 void loop(){
   //Do nothing here
 }
  



Receiver Fritzing Sketch

Results

After pressing the button on the RF remote, the data signal is printed to the Serial Monitor. You can copy the data to a spreadsheet program for review. This is an example of the signal produced after pushing the button on the remote for turning the fan/light on.
The following code was produced from pushing the button responsible for turning the light off:
The code sequence above may seem a bit random until you start graphing it. I grabbed the LOW column - and produced the following chart:
 
The chart above is a bit messy - mainly because the timing is slightly out... in that sometimes it can squeeze an extra read from a particular signal. But what is important to note here is that you can differentiate a LONG signal from a SHORT signal. I have drawn a couple of red dotted lines where I believe most of the readings tend to sit. I then used a formula in the spreadsheet to calibrate the readings and make them a bit more uniform. For example, if the length of the signal was greater than 4 analogReads, then I converted this to 6. If it was less than 4 analogReads, then I converted it to 2. I used a frequency table to help decide on the cutoff value of 4, and just decided to pick the two values (2 for short, and 6 for long) based on the frequency tables below. I could have chosen 5 as the LONG value, but there were more 6's overall.
 
  **The meaning of "frequency" in the following tables relate to the "number of times" a specific signal length is recorded.

 
And this is the resulting chart:

You will notice that the pattern is quite repetitive. I helped to identify the sections with vertical red lines (near the bottom of the chart). In other words, the signal produced by the remote is repeated 6 times.
I then did the same for the HIGH signal column and combined the two to create the following chart:
 
 

 
 
You will notice that the HIGH signals also have a repetitive pattern, however have a Very long length at the end of each section. This is almost a break to separate each section.
This is what a single section looks like zoomed in:
 

 
 
SL = [Short LOW] signal. - or short blue bar
SH = [Short HIGH] signal - or short yellow bar
LL = [Long LOW] signal - or long blue bar
LH = [Long HIGH] signal - or long yellow bar
VLH = [Very long HIGH} signal - or very long yellow bar (~92 analogReads in length)

 
  You will notice that there are only about 6 different combinations of the signals mentioned above. We can use this to create a coding system as described below:
 

 
 
We can use this coding system to describe the signals. The charts below show the difference between turning the LIGHT ON and LIGHT OFF.
 

 
 

 
 
PLEASE NOTE: You may notice when you copy the signals from the Serial monitor that you get a series of (0,255) combinations. This is actually a timeout sequence - which generally occurs after the signal is complete.
 
 Here is an example of what I mean.



This is the end of tutorial 2. In the next tutorial, we will use the code acquired from the remote to turn the FAN LIGHT on and off (using the 433 MHz RF transmitter).

Click here for Tutorial 3

ScottC 26 Jun 18:05

Bare Bones Arduino IR Receiver

Old infrared remote controls can be a great way to interface with your projects. One of [AnalysIR's] latest blog posts goes over the simplest way to create an Arduino based IR receiver, making it easier than ever to put that old remote to good use.

Due to the popularity of their first IR receiver post, the silver bullet IR receiver, [AnalysIR] decided to write a quick post about using IR on the Arduino. The part list consists of one Arduino, two resistors, and one IR emitter. That’s right, an emitter. When an LED (IR or otherwise) is reverse biased it can act as a light sensor. The main difference when using this method is that the IR signal is not inverted as it would normally be when using a more common modulated IR receiver module. All of the Arduino code you need to get up and running is also provided. The main limitation when using this configuration, is that the remote control needs to be very close to the IR emitter in order for it to receive the signal.

What will you control with your old TV remote? It would be interesting to see this circuit hooked up so that a single IR emitter can act both as a transmitter and a receiver. Go ahead and give it a try, then let us know how it went!


Filed under: Arduino Hacks

Tutorial – Arduino and SIM900 GSM Modules

Use the SIM900 GSM modules with Arduino in Chapter 55 of our Arduino Tutorials. The first chapter is here, the complete series is detailed here. Updated 14/02/2014

Introduction

The goal of this tutorial is to illustrate various methods of interaction between an Arduino Uno (or compatible) and the GSM cellular network using a SIM900 GSM shield, with which you can then use your existing knowledge to build upon those methods. Updated 08/01/2014.

Apart from setting up the shield we’ll examine:

  • Making a telephone call from your Arduino
  • Sending an SMS text message
  • Receiving text messages with the shield and displaying them on the serial monitor
  • Simple controlling of the host Arduino by calling it from another telephone
  • Controlling the Arduino via SMS text message

We’ll be using a SIMCOM SIM900 GSM module shield. (If you’re looking for tutorials on the Spreadtrum SM5100 modules, start here). There must be scores of Arduino shields or modules using the SIM900, so as you can imagine each one may be a little bit different with regards to the hardware side of things – so we’re assuming you have an understanding of how hardware and software serial works as well as supply voltages and the hardware side of the Arduino world.

As for the specific shield to use, we just chose the cheapest one available at the time – which turned out to be the “SIM900 GPRS/GSM Arduino shield” from tronixlabs.com:

However with a little research and work on your part, the sketches provided should also work with any SIM900 module/shield and Arduino – as long as you have the appropriate serial and power settings.

Getting Started

A little preparation goes a long way, so make sure you’ve covered the following points:

  • Regarding your cellular provider. Do you have coverage on a GSM 850 MHz, GSM 900 MHz, DCS 1800 MHz or PCS 1900 MHz network?  When we say GSM that means 2G – not 3G, 4G or LTE. Will they allow the use of non-supported devices on the network? Some carriers will block IMEI numbers that were not provided by their sales channel. Or you may have to call the provider and supply the IMEI of your GSM module to allow it on the network. Finally, it would be wise to use either a prepaid or an account that offers unlimited SMS text messaging – you don’t want any large bills if things go wrong.
  • Power. Do you have adequate power for your SIM900 module? Some shields will use more current than the Arduino can supply (up to 2A), so you may need an external high-current supply. The Linksprite shield we use needs 5V up to 2A into the onboard DC socket. Otherwise, check with your supplier.
  • Antenna. If your module/shield etc. doesn’t have an antenna – get one. You do need it.
  • Turn off the PIN lock on the SIM card. The easiest way to do this is to put the SIM in a handset and use the menu function.
  • And as always, please don’t make an auto-dialler…

Furthermore, download the SIM900 hardware manual (.pdf) and the AT command manual (.pdf), as we’ll refer to those throughout the tutorial.

Power

There is a DC socket on the shield, which is for a 5V power supply:

Although the data from Linksprite claims the shield will use no more than 450 mA, the SIMCOM hardware manual (page 22) for the module notes that it can draw up to 2A for short bursts. So get yourself a 5V 2A power supply and connect it via the DC socket, and also ensure the switch next to the socket is set to “EXT”.

Furthermore, you can turn the GSM module on and off with the power button on the side of the shield, and it defaults to off during an initial power-up. Therefore you’ll need to set D9 to HIGH for one second in your sketch to turn the module on (or off if required for power-saving). Don’t panic, we’ll show how this is done in the sketches below.

Software Serial

We will use the Arduino software serial library in this tutorial, and the Linksprite shield has hard-wired the serial from the SIM900 to a set of jumpers, and uses a default speed of 19200. Make sure you your jumpers are set to the “SWserial” side, as shown below:

And thus whenever an instance of SoftwareSerial is created, we use 7,8 as shown below:

SoftwareSerial SIM900(7, 8); // RX, TX

If you shield is different, you’ll need to change the TX and RX pin numbers. This also means you can’t use an Arduino Leonardo or Mega (easily). Finally – note this for later – if your shield is having problems sending data back to your Arduino you may need to edit the SoftwareSerial library – read this for more information.

Wow – all those rules and warnings?

The sections above may sound a little authoritarian, however we want your project to be a success. Now, let’s get started…

A quick test…

At this point we’ll check to make sure your shield and locate and connect to the cellular network. So make sure your SIM card is active with your cellular provider, the PIN lock is off, and then insert it and lock the SIM card  to the carrier on the bottom of the shield:

Then plug the shield into your Uno, attach 5V power to the DC socked on the GSM shield, and USB from the Uno to the PC. Press the “PWRKEY” button on the side of the shield for a second, then watch the following two LEDs:

The bright “STATUS” LED will come on, and then the “NETLIGHT” LED will blink once every 800 milliseconds- until the GSM module has found the network, at which point it will blink once every three seconds. This is shown in the following video:

Nothing can happen until that magic three-second blink – so if that doesn’t appear after a minute, something is wrong. Check your shield has the appropriate power supply, the antenna is connected correctly, the SIM card is seated properly and locked in- and that your cellular account is in order. Finally, you may not have reception in that particular area, so check using a phone on the same network or move to a different location.

Making a telephone call from your Arduino

You can have your Arduino call a telephone number, wait a moment – then hang up. This is an inexpensive way of alerting you of and consider the following sketch:

// Example 55.1

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8); // configure software serial port

void setup()
{
  SIM900.begin(19200);               
  SIM900power();  
  delay(20000);  // give time to log on to network. 
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(5000);
}

void callSomeone()
{
  SIM900.println("ATD + +12128675309;"); // dial US (212) 8675309
  delay(100);
  SIM900.println();
  delay(30000);            // wait for 30 seconds...
  SIM900.println("ATH");   // hang up
}

void loop()
{
  callSomeone(); // call someone
  SIM900power();   // power off GSM shield
  do {} while (1); // do nothing
}

The sketch first creates a software serial port, then in void setup() starts the software serial port, and also turns on the GSM shield with the function SIM900power (which simply sets D9 high for a second which is the equivalent of pressing the power button). Notice the delay function in void setup – this gives the GSM module a period of time to locate and log on to the cellular network. You may need to increase (or be able to decrease) the delay value depending on your particular situation. If in doubt, leave it as a long period.

The process of actually making the call is in the function callSomeone(). It sends a string of text to the GSM module which consists of an AT command. These are considered the “language” for modems and thus used for various tasks. We use the ATD command to dial (AT… D for dial) a number. The number as you can see in the sketch needs to be in world-format. So that’s a “+” then the country code, then the phone number with area code (without the preceding zero).

So if your number to call is Australia (02) 92679111 you would enter +61292679111. Etcetera. A carriage return is then sent to finalise the command and off it goes dialling the number. Here’s a quick video demonstration for the non-believers:

After thirty seconds we instruct the module to hand up with another AT command – “ATH” (AT… H for “hang up”), followed by turning off the power to the module. By separating the call feature into a function – you can now insert this into a sketch (plus the preceding setup code) to call a number when required.

Sending an SMS text message

This is a great way of getting data from your Arduino to almost any mobile phone in the world, at a very low cost. For reference, the maximum length of an SMS text message is 160 characters – however you can still say a lot with that size limit. First we’ll demonstrate sending an arbitrary SMS. Consider the following sketch:

// Example 55.2

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
  SIM900.begin(19200);
  SIM900power();  
  delay(20000);  // give time to log on to network. 
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(5000);
}

void sendSMS()
{
  SIM900.print("AT+CMGF=1\r");                                                        // AT command to send SMS message
  delay(100);
  SIM900.println("AT + CMGS = \"+12128675309\"");                                     // recipient's mobile number, in international format
  delay(100);
  SIM900.println("Hello, world. This is a text message from an Arduino Uno.");        // message to send
  delay(100);
  SIM900.println((char)26);                       // End AT command with a ^Z, ASCII code 26
  delay(100); 
  SIM900.println();
  delay(5000);                                     // give module time to send SMS
  SIM900power();                                   // turn off module
}

void loop()
{
  sendSMS();
  do {} while (1);
}

The basic structure and setup functions of the sketch are the same as the previous example, however the difference here is the function sendSMS(). It used the AT command “AT+CMGF” to tell the GSM module we want to send an SMS in text form, and then “AT+CMGS” followed by the recipient’s number. Once again note the number is in international format. After sending the send SMS commands, the module needs  five seconds to do this before we can switch it off. And now for our ubiquitous demonstration video:

 

You can also send text messages that are comprised of numerical data and so on – by compiling the required text and data into a string, and then sending that. Doing so gives you a method to send such information as sensor data or other parameters by text message.

For example, you might want to send daily temperature reports or hourly water tank levels. For our example, we’ll demonstrate how to send a couple of random numbers and some text as an SMS. You can then use this as a framework for your own requirements. Consider the following sketch:

// Example 55.3

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);
int x,y;
String textForSMS;

void setup()
{
  SIM900.begin(19200);
  SIM900power();  
  delay(20000);  // give time to log on to network. 
  randomSeed(analogRead(0));
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void sendSMS(String message)
{
  SIM900.print("AT+CMGF=1\r");                     // AT command to send SMS message
  delay(100);
  SIM900.println("AT + CMGS = \"+12128675309\"");  // recipient's mobile number, in international format
  delay(100);
  SIM900.println(message);                         // message to send
  delay(100);
  SIM900.println((char)26);                        // End AT command with a ^Z, ASCII code 26
  delay(100); 
  SIM900.println();
  delay(5000);                                     // give module time to send SMS
  SIM900power();                                   // turn off module
}

void loop()
{
  x = random(0,255);
  y = random(0,255);
  textForSMS = "Your random numbers are ";
  textForSMS.concat(x);
  textForSMS = textForSMS + " and ";
  textForSMS.concat(y);
  textForSMS = textForSMS + ". Enjoy!";  
  sendSMS(textForSMS);
  do {} while (1);
}

Take note of the changes to the function sendSMS(). It now has a parameter – message, which is a String which contains the text to send as an SMS. In void loop() the string variable textForSMS is constructed. First it contains some text, then the values for x and y are added with some more text. Finally the string is passed to be sent as an SMS. And here it is in action:

Receiving text messages and displaying them on the serial monitor 

Now let’s examine receiving text messages. All we need is to send two AT commands inside void setup() and then repeat every character sent from the shield to the serial monitor. The first command to use is AT+CMGF=1  which sets the SMS mode to text (as used in the previous example) and the second is AT+CNMI=2,2,0,0 – which tells the GSM module to send the contents of any new SMS out to the serial line. To demonstrate this, set up your hardware as before, upload the following sketch:

// Example 55.4

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

char incoming_char=0;

void setup()
{
  Serial.begin(19200); // for serial monitor
  SIM900.begin(19200); // for GSM shield
  SIM900power();  // turn on shield
  delay(20000);  // give time to log on to network.

  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r"); 
  // blurt out contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop()
{
  // Now we simply display any text that the GSM shield sends out on the serial monitor
  if(SIM900.available() >0)
  {
    incoming_char=SIM900.read(); //Get the character from the cellular serial port.
    Serial.print(incoming_char); //Print the incoming character to the terminal.
  }
}

… then open the serial monitor, check it’s set to 19200 bps and wait around thirty seconds. You will see some odd characters, then the “OK” responses from the GSM module. Now send a text message to the shield – the time/date stamp, sender and message will appear, for example:

To preserve my sanity the number used in the demonstrations will be blanked out.

Simple controlling of the host Arduino by calling it from another telephone

When we call our shield from another telephone, it sends the text “RING” out to serial, then “NO CARRIER” when you hang up – which can be harnessed to create a simple dial-in remote control. Use the sketch from the previous example to test this – for example:

You can also display the number calling in by using the AT command AT+CLIP=1. To do this, just add the following lines to void setup() in the previous sketch:

SIM900.print("AT+CLIP=1\r"); // turn on caller ID notification
delay(100);

Now when a call is received, the caller’s number appears as well – for example:

Note that the caller ID data for incoming calls isn’t in the international format as it was with SMSs. This will vary depending on your country, so check it out for yourself.

So how can we control the Arduino by calling in? By counting the number of times the shield sends “RING” to the Arduino (just as we did with the other GSM shield). To do this we simply count the number of times the word “RING” comes in from the shield, and then after the third ring – the Arduino will do something.

For our example we have two LEDs connected (via 560Ω resistors) to D12 and D13. When we call the shield and let it ring three times, they will alternate between on and off. Enter and upload the following sketch:

// Example 55.5

#include <SoftwareSerial.h> 
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900(7, 8);

int numring=0;
int comring=3; 
int onoff=0; // 0 = off, 1 = on

void setup()
{
  Serial.begin(19200);
  // set up the digital pins to control
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT); // LEDs - off = red, on = green
  digitalWrite(12, HIGH);
  digitalWrite(13, LOW);

  // wake up the GSM shield
  SIM900power(); 
  SIM900.begin(19200);
  SIM900.print("AT+CLIP=1\r"); // turn on caller ID notification
  delay(100);  
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void doSomething()
{
  if (onoff==0)
  {
    onoff=1;
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);
    Serial.println("D12 high D13 low");
  } 
  else
    if (onoff==1)
    {
      onoff=0;
      digitalWrite(12, LOW);
      digitalWrite(13, HIGH);
      Serial.println("D12 low D13 high");
    }
}

void loop() 
{
  if(SIM900.available() >0)
  {
    inchar=SIM900.read(); 
    if (inchar=='R')
    {
      delay(10);
      inchar=SIM900.read(); 
      if (inchar=='I')
      {
        delay(10);
        inchar=SIM900.read();
        if (inchar=='N')
        {
          delay(10);
          inchar=SIM900.read(); 
          if (inchar=='G')
          {
            delay(10);
            // So the phone (our GSM shield) has 'rung' once, i.e. if it were a real phone
            // it would have sounded 'ring-ring' or 'blurrrrr' or whatever one cycle of your ring tone is
            numring++;
            Serial.println("ring!");
            if (numring==comring)
            {
              numring=0; // reset ring counter
              doSomething();
            }
          }
        }
      }
    }
  }
}

You can change the number of rings before action with the variable comring, and the action to take is in the function void doSomething(). Finally you can watch a short video of this in action.


We can also modify this system so it only allows control by callers from one number  –  as long as caller ID works on your system (well it should… it’s 2014 not 1996). So in the next example the system will only call the function doSomething if the call is from a certain number. The sketch works in the same manner as last time – but instead of counting the word “RING”, it will compare the incoming caller’s ID number against one in the sketch.

It may look a little clunky, but it works. In the following example sketch, the number is 2128675309 – so just change the digits to check in void loop():

// Example 55.6

#include <SoftwareSerial.h> 
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900(7, 8);

int onoff=0; // 0 = off, 1 = on

void setup()
{
  Serial.begin(19200);
  // set up the digital pins to control
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT); // LEDs - off = red, on = green
  digitalWrite(12, HIGH);
  digitalWrite(13, LOW);

  // wake up the GSM shield
  SIM900power(); 
  SIM900.begin(19200);
  delay(20000);  // give time to log on to network.
  SIM900.print("AT+CLIP=1\r"); // turn on caller ID notification
  delay(100);  
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void doSomething()
{
  if (onoff==0)
  {
    onoff=1;
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);
    Serial.println("D12 high D13 low");
  } 
  else
    if (onoff==1)
    {
      onoff=0;
      digitalWrite(12, LOW);
      digitalWrite(13, HIGH);
      Serial.println("D12 low D13 high");
    }
}

void loop() 
{
  if(SIM900.available() >0)
  {   
    inchar=SIM900.read(); 
    if (inchar=='2')
    {
      delay(10);
      inchar=SIM900.read(); 
      if (inchar=='1')
      {
        delay(10);
        inchar=SIM900.read(); 
        if (inchar=='2')
        {
          delay(10);
          inchar=SIM900.read(); 
          if (inchar=='8')
          {
            delay(10);
            inchar=SIM900.read(); 
            if (inchar=='6')
            {
              delay(10);
              inchar=SIM900.read(); 
              if (inchar=='7')
              {
                delay(10);
                inchar=SIM900.read(); 
                if (inchar=='5')
                {
                  delay(10);
                  inchar=SIM900.read(); 
                  if (inchar=='3')
                  {
                    delay(10);
                    inchar=SIM900.read();
                    if (inchar=='0')
                    {
                      delay(10);
                      inchar=SIM900.read(); 
                      if (inchar=='9')
                      {
                        Serial.println("do sometehing");
                        delay(10);
                        // now the number is matched, do something
                        doSomething();
                        // arbitrary delay so the function isn't called again on the same phone call
                        delay(60000);
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

The large delay after calling doSomething() exists to stop the same action being called twice (or more) on the same inbound call. Anyhow, you should now have a grasp on interrogating the data from the shield. Which leads us to the final section…

Controlling the Arduino via SMS text message

As you did with the caller ID data, you can also control the Arduino via SMS fairly easily, and have more options. In our example we’ll explain how to control four digital output pins via SMS. The example works in two stages. First it will wait for an SMS to be received, and then have the contents sent to the Arduino via serial just as we did earlier with the example 55.4. The next stage is to filter out the commands in the text message as we did with example 55.6.

The commands (that is, the contents of your text message to the Arduino) will be in the form

#axbxcxdx

where ‘x’ will be 0 (for off) and 1 (for on) – and a, b, c and d will relate to digital pins 10, 11, 12 and 13. For example, to turn on D10, 11 and turn off D12, D13 you would compose your SMS as #a1b1c0d0. After processing the SMS we use the AT command AT+CMGD=1,4 to delete all the SMSs from the SIM card, otherwise it will fill up and reject further commands. Moving on, here’s the example sketch:

// Example 55.7

#include <SoftwareSerial.h> 
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900(7, 8);

int led1 = 10;
int led2 = 11;
int led3 = 12;
int led4 = 13;

void setup()
{
  Serial.begin(19200);
  // set up the digital pins to control
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);

  // wake up the GSM shield
  SIM900power(); 
  SIM900.begin(19200);
  delay(20000);  // give time to log on to network.
  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r"); 
  // blurt out contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
  Serial.println("Ready...");
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop() 
{
  //If a character comes in from the cellular module...
  if(SIM900.available() >0)
  {
    inchar=SIM900.read(); 
    if (inchar=='#')
    {
      delay(10);

      inchar=SIM900.read(); 
      if (inchar=='a')
      {
        delay(10);
        inchar=SIM900.read();
        if (inchar=='0')
        {
          digitalWrite(led1, LOW);
        } 
        else if (inchar=='1')
        {
          digitalWrite(led1, HIGH);
        }
        delay(10);
        inchar=SIM900.read(); 
        if (inchar=='b')
        {
          inchar=SIM900.read();
          if (inchar=='0')
          {
            digitalWrite(led2, LOW);
          } 
          else if (inchar=='1')
          {
            digitalWrite(led2, HIGH);
          }
          delay(10);
          inchar=SIM900.read(); 
          if (inchar=='c')
          {
            inchar=SIM900.read();
            if (inchar=='0')
            {
              digitalWrite(led3, LOW);
            } 
            else if (inchar=='1')
            {
              digitalWrite(led3, HIGH);
            }
            delay(10);
            inchar=SIM900.read(); 
            if (inchar=='d')
            {
              delay(10);
              inchar=SIM900.read();
              if (inchar=='0')
              {
                digitalWrite(led4, LOW);
              } 
              else if (inchar=='1')
              {
                digitalWrite(led4, HIGH);
              }
              delay(10);
            }
          }
          SIM900.println("AT+CMGD=1,4"); // delete all SMS
        }
      }
    }
  }
}

The example hardware has four LEDs via 560Ω resistors on the digital outputs being controlled. Finally, you can watch a short demonstration in this video.

Conclusion

After working through this tutorial you should have an understanding of how to use the SIM900 GSM shields to communicate and control with an Arduino. And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop”.

Have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column, or join our forum – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The post Tutorial – Arduino and SIM900 GSM Modules appeared first on tronixstuff.

Arduino Tutorials – Chapter 16 – Ethernet

Learn how to connect your Arduino to the outside world via Ethernet

This is chapter sixteen of our huge Arduino tutorial seriesUpdated 06/12/2013

In this chapter we will introduce and examine the use of Ethernet networking with Arduino over local networks and the greater Internet. It will be assumed that you have a basic understanding of computer networking, such as the knowledge of how to connect computers to a hub/router with RJ45 cables, what an IP and MAC address is, and so on. Furthermore, here is a good quick rundown about Ethernet.

Getting Started

You will need an Arduino Uno or compatible board with an Ethernet shield that uses the W5100 Ethernet controller IC (pretty much all of them):

…or consider using a Freetronics EtherTen – as it has everything all on the one board, plus some extras:

Furthermore you will need to power the board via the external DC socket – the W5100 IC uses more current than the USB power can supply. A 9V 1A plug pack/wall wart will suffice. Finally it does get hot – so be careful not to touch the W5100 after extended use. In case you’re not sure – this is the W5100 IC:

Once you have your Ethernet-enabled Arduino, and have the external power connected – it’s a good idea to check it all works. Open the Arduino IDE and selectFile > Examples > Ethernet > Webserver. This loads a simple sketch which will display data gathered from the analogue inputs on a web browser. However don’t upload it yet, it needs a slight modification.

You need to specify the IP address of the Ethernet shield – which is done inside the sketch. This is simple, go to the line:

IPAddress ip(192,168,1, 177);

And alter it to match your own setup. For example, in my home the router’s IP address is 10.1.1.1, the printer is 10.1.1.50 and all PCs are below …50. So I will set my shield IP to 10.1.1.77 by altering the line to:

IPAddress ip(10,1,1,77);

You also have the opportunity to change your MAC address. Each piece of networking equipment has a unique serial number to identify itself over a network, and this is normall hard-programmed into the equipments’ firmware. However with Arduino we can define the MAC address ourselves.

If you are running more than one Ethernet shield on your network, ensure they have different MAC addresses by altering the hexadecimal values in the line:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

However if you only have one shield just leave it be. There may be the very, very, statistically rare chance of having a MAC address the same as your existing hardware, so that would be another time to change it.

Once you have made your alterations, save and upload the sketch. Now open a web browser and navigate to the IP address you entered in the sketch, and you should be presented with something similar to the following:

 

What’s happening? The Arduino has been programmed to offer a simple web page with the values measured by the analogue inputs. You can refresh the browser to get updated values.

At this point – please note that the Ethernet shields use digital pins 10~13, so you can’t use those for anything else. Some Arduino Ethernet shields may also have a microSD card socket, which also uses another digital pin – so check with the documentation to find out which one.

Nevertheless, now that we can see the Ethernet shield is working we can move on to something more useful. Let’s dissect the previous example in a simple way, and see how we can distribute and display more interesting data over the network. For reference, all of the Ethernet-related functions are handled by the Ethernet Arduino library. If you examine the previous sketch we just used, the section that will be of interest is:

for (int analogChannel = 0; analogChannel < 6; analogChannel++) 
          {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");       
          }
          client.println("</html>");

Hopefully this section of the sketch should be familiar – remember how we have used serial.print(); in the past when sending data to the serial monitor box? Well now we can do the same thing, but sending data from our Ethernet shield back to a web browser – on other words, a very basic type of web page.

However there is something you may or may not want to  learn in order to format the output in a readable format – HTML code. I am not a website developer (!) so will not delve into HTML too much.

However if you wish to serve up nicely formatted web pages with your Arduino and so on, here would be a good start. In the interests of simplicity, the following two functions will be the most useful:

client.print(" is ");

Client.print (); allows us to send text or data back to the web page. It works in the same way as serial.print(), so nothing new there. You can also specify the data type in the same way as with serial.print(). Naturally you can also use it to send data back as well. The other useful line is:
client.println("<br />");

which sends the HTML code back to the web browser telling it to start a new line. The part that actually causes the carriage return/new line is the <br /> which is an HTML code (or “tag”) for a new line. So if you are creating more elaborate web page displays, you can just insert other HTML tags in the client.print(); statement. If you want to learn more about HTML commands, here’s a good tutorial site. Finally – note that the sketch will only send the data when it has been requested, that is when it has received a request from the web browser.

Accessing your Arduino over the Internet

So far – so good. But what if you want to access your Arduino from outside the local network?

You will need a static IP address – that is, the IP address your internet service provider assigns to your connection needs to stay the same. If you don’t have a static IP, as long as you leave your modem/router permanently swiched on your IP shouldn’t change. However that isn’t an optimal solution.

If your ISP cannot offer you a static IP at all, you can still move forward with the project by using an organisation that offers a Dynamic DNS. These organisations offer you your own static IP host name (e.g. mojo.monkeynuts.com) instead of a number, keep track of your changing IP address and linking it to the new host name. From what I can gather, your modem needs to support (have an in-built client for…) these DDNS services. As an example, two companies are No-IP andDynDNS.com. Please note that I haven’t used those two, they are just offered as examples.

Now, to find your IP address… usually this can be found by logging into your router’s administration page – it is usually 192.168.0.1 but could be different. Check with your supplier or ISP if they supplied the hardware. For this example, if I enter 10.1.1.1 in a web browser, and after entering my modem administration password, the following screen is presented:

What you are looking for is your WAN IP address, as you can see in the image above. To keep the pranksters away, I have blacked out some of my address.

The next thing to do is turn on port-forwarding. This tells the router where to redirect incoming requests from the outside world. When the modem receives such a request, we want to send that request to the port number of our Ethernet shield. Using the:

EthernetServer server(125);

function in our sketch has set the port number to 125. Each modem’s configuration screen will look different, but as an example here is one:

So you can see from the line number one in the image above, the inbound port numbers have been set to 125, and the IP address of the Ethernet shield has been set to 10.1.1.77 – the same as in the sketch.

After saving the settings, we’re all set. The external address of my Ethernet shield will be the WAN:125, so to access the Arduino I will type my WAN address with :125 at the end into the browser of the remote web device, which will contact the lonely Ethernet hardware back home.

Furthermore, you may need to alter your modem’s firewall settings, to allow the port 125 to be “open” to incoming requests. Please check your modem documentation for more information on how to do this.

Now from basically any Internet connected device in the free world, I can enter my WAN and port number into the URL field and receive the results. For example, from a phone when it is connected to the Internet via LTE mobile data:

So at this stage you can now display data on a simple web page created by your Arduino and access it from anywhere with unrestricted Internet access. With your previous Arduino knowledge (well, this is chapter sixteen) you can now use data from sensors or other parts of a sketch and display it for retrieval.

Displaying sensor data on a web page

As an example of displaying sensor data on a web page, let’s use an inexpensive and popular temperature and humidity sensor – the DHT22. You will need to install the DHT22 Arduino library which can be found on this page. If this is your first time with the DHT22, experiment with the example sketch that’s included with the library so you understand how it works.

Connect the DHT22 with the data pin to Arduino D2, Vin to the 5V pin and GND to … GND:

Now for our sketch – to display the temperature and humidity on a web page. If you’re not up on HTML you can use online services such as this to generate the code, which you can then modify to use in the sketch.

In the example below, the temperature and humidity data from the DHT22 is served in a simple web page:

#include <SPI.h>
#include <Ethernet.h>

// for DHT22 sensor
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10,1,1,77);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(125);
DHT dht(DHTPIN, DHTTYPE);

void setup() 
{
  dht.begin();
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() 
{
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) 
        {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
	  client.println("Refresh: 30");  // refresh the page automatically every 30 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");

          // get data from DHT22 sensor
          float h = dht.readHumidity();
          float t = dht.readTemperature();
          Serial.println(t);
          Serial.println(h);

          // from here we can enter our own HTML code to create the web page
          client.print("<head><title>Office Weather</title></head><body><h1>Office Temperature</h1><p>Temperature - ");
          client.print(t);
          client.print(" degrees Celsius</p>");
          client.print("<p>Humidity - ");
          client.print(h);
          client.print(" percent</p>");
          client.print("<p><em>Page refreshes every 30 seconds.</em></p></body></html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }
}

It is a modification of the IDE’s webserver example sketch that we used previously – with a few modifications. First, the webpage will automatically refresh every 30 seconds – this parameter is set in the line:

client.println("Refresh: 30");  // refresh the page automatically every 30 sec

… and the custom HTML for our web page starts below the line:

// from here we can enter our own HTML code to create the web page

You can then simply insert the required HTML inside client.print() functions to create the layout you need.

Finally – here’s an example screen shot of the example sketch at work:

You now have the framework to create your own web pages that can display various data processed with your Arduino.

Remote control your Arduino from afar

We have a separate tutorial on this topic, that uses the teleduino system.

Conclusion

So there you have it, another useful way to have your Arduino interact with the outside world. Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop” from No Starch Press.

The post Arduino Tutorials – Chapter 16 – Ethernet appeared first on tronixstuff.

Arduino Tutorials – Chapter 16 – Ethernet

Learn how to connect your Arduino to the outside world via Ethernet

This is chapter sixteen of our huge Arduino tutorial seriesUpdated 06/12/2013

In this chapter we will introduce and examine the use of Ethernet networking with Arduino over local networks and the greater Internet. It will be assumed that you have a basic understanding of computer networking, such as the knowledge of how to connect computers to a hub/router with RJ45 cables, what an IP and MAC address is, and so on. Furthermore, here is a good quick rundown about Ethernet.

Getting Started

You will need an Arduino Uno or compatible board with an Ethernet shield that uses the W5100 Ethernet controller IC (pretty much all of them):

…or consider using a Freetronics EtherTen – as it has everything all on the one board, plus some extras:

Furthermore you will need to power the board via the external DC socket – the W5100 IC uses more current than the USB power can supply. A 9V 1A plug pack/wall wart will suffice. Finally it does get hot – so be careful not to touch the W5100 after extended use. In case you’re not sure – this is the W5100 IC:

Once you have your Ethernet-enabled Arduino, and have the external power connected – it’s a good idea to check it all works. Open the Arduino IDE and selectFile > Examples > Ethernet > Webserver. This loads a simple sketch which will display data gathered from the analogue inputs on a web browser. However don’t upload it yet, it needs a slight modification.

You need to specify the IP address of the Ethernet shield – which is done inside the sketch. This is simple, go to the line:

IPAddress ip(192,168,1, 177);

And alter it to match your own setup. For example, in my home the router’s IP address is 10.1.1.1, the printer is 10.1.1.50 and all PCs are below …50. So I will set my shield IP to 10.1.1.77 by altering the line to:

IPAddress ip(10,1,1,77);

You also have the opportunity to change your MAC address. Each piece of networking equipment has a unique serial number to identify itself over a network, and this is normall hard-programmed into the equipments’ firmware. However with Arduino we can define the MAC address ourselves.

If you are running more than one Ethernet shield on your network, ensure they have different MAC addresses by altering the hexadecimal values in the line:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

However if you only have one shield just leave it be. There may be the very, very, statistically rare chance of having a MAC address the same as your existing hardware, so that would be another time to change it.

Once you have made your alterations, save and upload the sketch. Now open a web browser and navigate to the IP address you entered in the sketch, and you should be presented with something similar to the following:

 

What’s happening? The Arduino has been programmed to offer a simple web page with the values measured by the analogue inputs. You can refresh the browser to get updated values.

At this point – please note that the Ethernet shields use digital pins 10~13, so you can’t use those for anything else. Some Arduino Ethernet shields may also have a microSD card socket, which also uses another digital pin – so check with the documentation to find out which one.

Nevertheless, now that we can see the Ethernet shield is working we can move on to something more useful. Let’s dissect the previous example in a simple way, and see how we can distribute and display more interesting data over the network. For reference, all of the Ethernet-related functions are handled by the Ethernet Arduino library. If you examine the previous sketch we just used, the section that will be of interest is:

 for (int analogChannel = 0; analogChannel < 6; analogChannel++) 
          {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");       
          }
          client.println("</html>");

Hopefully this section of the sketch should be familiar – remember how we have used serial.print(); in the past when sending data to the serial monitor box? Well now we can do the same thing, but sending data from our Ethernet shield back to a web browser – on other words, a very basic type of web page.

However there is something you may or may not want to  learn in order to format the output in a readable format – HTML code. I am not a website developer (!) so will not delve into HTML too much.

However if you wish to serve up nicely formatted web pages with your Arduino and so on, here would be a good start. In the interests of simplicity, the following two functions will be the most useful:

client.print(" is ");

Client.print (); allows us to send text or data back to the web page. It works in the same way as serial.print(), so nothing new there. You can also specify the data type in the same way as with serial.print(). Naturally you can also use it to send data back as well. The other useful line is:

client.println("<br />");

which sends the HTML code back to the web browser telling it to start a new line. The part that actually causes the carriage return/new line is the <br /> which is an HTML code (or “tag”) for a new line. So if you are creating more elaborate web page displays, you can just insert other HTML tags in the client.print(); statement. If you want to learn more about HTML commands, here’s a good tutorial site. Finally – note that the sketch will only send the data when it has been requested, that is when it has received a request from the web browser.

Accessing your Arduino over the Internet

So far – so good. But what if you want to access your Arduino from outside the local network?

You will need a static IP address – that is, the IP address your internet service provider assigns to your connection needs to stay the same. If you don’t have a static IP, as long as you leave your modem/router permanently swiched on your IP shouldn’t change. However that isn’t an optimal solution.

If your ISP cannot offer you a static IP at all, you can still move forward with the project by using an organisation that offers a Dynamic DNS. These organisations offer you your own static IP host name (e.g. mojo.monkeynuts.com) instead of a number, keep track of your changing IP address and linking it to the new host name. From what I can gather, your modem needs to support (have an in-built client for…) these DDNS services. As an example, two companies are No-IP andDynDNS.com. Please note that I haven’t used those two, they are just offered as examples.

Now, to find your IP address… usually this can be found by logging into your router’s administration page – it is usually 192.168.0.1 but could be different. Check with your supplier or ISP if they supplied the hardware. For this example, if I enter 10.1.1.1 in a web browser, and after entering my modem administration password, the following screen is presented:

What you are looking for is your WAN IP address, as you can see in the image above. To keep the pranksters away, I have blacked out some of my address.

The next thing to do is turn on port-forwarding. This tells the router where to redirect incoming requests from the outside world. When the modem receives such a request, we want to send that request to the port number of our Ethernet shield. Using the:

EthernetServer server(125);

function in our sketch has set the port number to 125. Each modem’s configuration screen will look different, but as an example here is one:

So you can see from the line number one in the image above, the inbound port numbers have been set to 125, and the IP address of the Ethernet shield has been set to 10.1.1.77 – the same as in the sketch.

After saving the settings, we’re all set. The external address of my Ethernet shield will be the WAN:125, so to access the Arduino I will type my WAN address with :125 at the end into the browser of the remote web device, which will contact the lonely Ethernet hardware back home.

Furthermore, you may need to alter your modem’s firewall settings, to allow the port 125 to be “open” to incoming requests. Please check your modem documentation for more information on how to do this.

Now from basically any Internet connected device in the free world, I can enter my WAN and port number into the URL field and receive the results. For example, from a phone when it is connected to the Internet via LTE mobile data:

So at this stage you can now display data on a simple web page created by your Arduino and access it from anywhere with unrestricted Internet access. With your previous Arduino knowledge (well, this is chapter sixteen) you can now use data from sensors or other parts of a sketch and display it for retrieval.

Displaying sensor data on a web page

As an example of displaying sensor data on a web page, let’s use an inexpensive and popular temperature and humidity sensor – the DHT22. You will need to install the DHT22 Arduino library which can be found on this page. If this is your first time with the DHT22, experiment with the example sketch that’s included with the library so you understand how it works.

Connect the DHT22 with the data pin to Arduino D2, Vin to the 5V pin and GND to … GND:

Now for our sketch – to display the temperature and humidity on a web page. If you’re not up on HTML you can use online services such as this to generate the code, which you can then modify to use in the sketch.

In the example below, the temperature and humidity data from the DHT22 is served in a simple web page:

#include <SPI.h>
#include <Ethernet.h>

// for DHT22 sensor
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10,1,1,77);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(125);
DHT dht(DHTPIN, DHTTYPE);

void setup() 
{
  dht.begin();
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
   while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() 
{
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == 'n' && currentLineIsBlank) 
        {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
	  client.println("Refresh: 30");  // refresh the page automatically every 30 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");

          // get data from DHT22 sensor
          float h = dht.readHumidity();
          float t = dht.readTemperature();
          Serial.println(t);
          Serial.println(h);

          // from here we can enter our own HTML code to create the web page
          client.print("<head><title>Office Weather</title></head><body><h1>Office Temperature</h1><p>Temperature - ");
          client.print(t);
          client.print(" degrees Celsius</p>");
          client.print("<p>Humidity - ");
          client.print(h);
          client.print(" percent</p>");
          client.print("<p><em>Page refreshes every 30 seconds.</em></p></body></html>");
          break;
        }
        if (c == 'n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        else if (c != 'r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }
}

It is a modification of the IDE’s webserver example sketch that we used previously – with a few modifications. First, the webpage will automatically refresh every 30 seconds – this parameter is set in the line:

client.println("Refresh: 30");  // refresh the page automatically every 30 sec

… and the custom HTML for our web page starts below the line:

// from here we can enter our own HTML code to create the web page

You can then simply insert the required HTML inside client.print() functions to create the layout you need.

Finally – here’s an example screen shot of the example sketch at work:

You now have the framework to create your own web pages that can display various data processed with your Arduino.

Remote control your Arduino from afar

We have a separate tutorial on this topic, that uses the teleduino system.

Conclusion

So there you have it, another useful way to have your Arduino interact with the outside world. Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop” from No Starch Press.