Posts with «control» label

MT8870 DTMF - Dual Tone Multi Frequency Decoder

Project Description

We will be using an MT8870 DTMF module with an Arduino UNO to control a small servo motor in this project. The DTMF module gives the Arduino super-powers and allows you to control the Servo motor in so many ways. For example, this tutorial will show you how to control the servo motor using:
  • a YouTube Video
  • a voice recorder
  • A web application (Online tone generator)
  • A smart phone app (DTMF Pad)
  • A touch-tone phone to cell-phone call
All of these control methods will take advantage of the same exact Arduino code/sketch. But how???
The MT8870 DTMF decoder is quite a neat little module that allows you incorporate DTMF technology into your arduino projects. DTMF stands for Dual-Tone Multi-Frequency. DTMF tones are commonly associated with touch-tone phones and other telecommunication systems. When you press the number "1" on a touch-tone phone, two sine waves with frequencies: 697Hz and 1209Hz are combined to produce a unique DTMF signal which can be transmitted through the phone line. The MT8870 DTMF module can take this signal as an input, and decode it to produce a binary output.
 
 

 
The DTMF module does not care how you produce the DTMF tone. However, if it receives this tone, it will decode it. We can take advantage of this feature to supply the module with tones from different sources. The module has a 3.5mm port for line input. Providing you can connect your DTMF source to this line input in some way, it should work. I must warn you, however that this is a line input and NOT a microphone input. If you wanted to use a microphone, you will need to boost or amplify the signal before sending it to the DTMF module.
 
You will need the following parts for this project
 

Parts Required:

Software/Apps Required

Arduino Sketch


Upload the following sketch to the Arduino.
 

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
/* ================================================================================================================================================== Project: MT8870 DTMF Servo sketch Author: Scott C Created: 4th August 2015 Arduino IDE: 1.6.4 Website: http://arduinobasics.blogspot.com/p/arduino-basics-projects-page.html Description: This project will allow you to control a Servo motor using an Arduino UNO and a MT8870 DTMF Module. The DTMF signal is received through the 3.5mm port of the DTMF module and is decoded. We will use the decoded output to control the position of the Servo. A SG-5010 Servo motor was used in this project. ===================================================================================================================================================== *///This sketch uses the Servo library that comes with the Arduino IDE #include <Servo.h> //Global variables----------------------------------------------------------------------------------------- Servo SG5010; // The SG5010 variable provides Servo functionality int servoPosition = 0; // The servoPosition variable will be used to set the position of the servo byte DTMFread; // The DTMFread variable will be used to interpret the output of the DTMF module. const int STQ = 3; // Attach DTMF Module STQ Pin to Arduino Digital Pin 3 const int Q4 = 4; // Attach DTMF Module Q4 Pin to Arduino Digital Pin 4 const int Q3 = 5; // Attach DTMF Module Q3 Pin to Arduino Digital Pin 5 const int Q2 = 6; // Attach DTMF Module Q2 Pin to Arduino Digital Pin 6 const int Q1 = 7; // Attach DTMF Module Q1 Pin to Arduino Digital Pin 7 /*========================================================================================================= setup() : will setup the Servo, and prepare the Arduino to receive the MT8700 DTMF module's output. ========================================================================================================== */void setup() { SG5010.attach(9); // The Servo signal cable will be attached to Arduino Digital Pin 9 SG5010.write(servoPosition); // Set the servo position to zero. //Setup the INPUT pins on the Arduino pinMode(STQ, INPUT); pinMode(Q4, INPUT); pinMode(Q3, INPUT); pinMode(Q2, INPUT); pinMode(Q1, INPUT);} /*========================================================================================================= loop() : Arduino will interpret the DTMF module output and position the Servo accordingly ========================================================================================================== */void loop() { if(digitalRead(STQ)==HIGH){ //When a DTMF tone is detected, STQ will read HIGH for the duration of the tone. DTMFread=0; if(digitalRead(Q1)==HIGH){ //If Q1 reads HIGH, then add 1 to the DTMFread variable DTMFread=DTMFread+1; } if(digitalRead(Q2)==HIGH){ //If Q2 reads HIGH, then add 2 to the DTMFread variable DTMFread=DTMFread+2; } if(digitalRead(Q3)==HIGH){ //If Q3 reads HIGH, then add 4 to the DTMFread variable DTMFread=DTMFread+4; } if(digitalRead(Q4)==HIGH){ //If Q4 reads HIGH, then add 8 to the DTMFread variable DTMFread=DTMFread+8; } servoPosition = DTMFread * 8.5; //Set the servoPosition varaible to the combined total of all the Q1 to Q4 readings. Multiply by 8.5 to amplify the servo rotation. } SG5010.write(servoPosition); //Set the servo's position according to the "servoPosition" variable. }


 
 
 

Fritzing Sketch


Connect the Arduino to the MT8870 DTMF module, and to a Servo.
Use the following Fritzing sketch as a guide.
 
(Click the image above to enlarge it)



Discussion


You will need to connect a cable from the DTMF module's 3.5mm port to that of your smart phone, computer, voice recorder or any other DTMF source of your choice.
 

 

When you power up your Arduino, the Servo motor should turn all the way to the left to it's zero position. Once the DTMF module receives a DTMF signal, it will identify the relevant frequecies as described in the table at the beginning of this tutorial, and produce a binary like output. You will notice the DTMF module's onboard LEDs light up when a tone is detected. Onboard LED (D5) will turn on for the length of the DTMF tone it just received, and turn off when the tone has stopped. On the other hand, the onboard LEDs (D1 to D4) will light up depending on the tone received, and will remain lit until the module receives another tone. The onboard LEDs are a visual representation of the voltages applied to the DTMF module's pins (Q1 to Q4, and STQ). Q1 matches D1, Q2 matches D2 etc etc. and STQ matches D5.
 
You will notice that there are two STQ pins on the DTMF module. The STQ pin that is closest to Q4 will only go high when a DTMF tone is detected, and will remain high for the duration of the tone. The other STQ pin is the exact opposite. It will switch LOW when a tone is received and remain LOW for the duration of the tone. When there is no tone, this STQ pin will remain HIGH. The table below provides a summary of the DTMF module outputs, with a blue box representing a voltage applied to that pin (HIGH), whereas a black box indicates no voltage applied (LOW).


 
In order to follow this project, you need a source of DTMF tones. You can produce DTMF tones using a touch-tone phone, or through the use of a DTMF Pad app. If you are feeling creative, you can create a DTMF song/tune like the one I posted on YouTube. You can see the video below:
 

 
As you can see from the video, I also recorded the DTMF tune onto a voice recorder, and was able to control the servo that way. If you are not feeling creative, you can visit this website to create DTMF tones from your browser.

Concluding comments


This project was very fun, and shows some novel ways to control your Arduino. After completing the project, I realised that I could use this module to alert me when new emails or messages arrive on my phone or computer. If you have the ability to change the email or message notification sound to a DTMF tone, you should be able to get the module and Arduino to respond accordingly. Oh well, maybe I'll save that project for another day.
 
If this project helped you in anyway or if you use my code within your project, please let me know in the comments below. I would be interested to see what you did.


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

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


 
 
             

 



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

A Remote for CHDK Cameras Made Possible with Arduino

[AlxDroidDev] built himself a nice remote control box for CHDK-enabled cameras. If you haven’t heard of CHDK, it’s a pretty cool software modification for some Canon cameras. CHDK adds many new features to inexpensive cameras. In this case, [AlxDroidDev] is using a feature that allows the camera shutter to be activated via USB. CHDK can be run from the SD card, so no permanent modifications need to be made to the camera.

[AlxDroidDev’s] device runs off of an ATMega328p with Arduino. It operates from a 9V battery. The circuit contains an infrared receiver and also a Bluetooth module. This allows [AlxDroidDev] to control his camera using either method. The device interfaces to the camera using a standard USB connector and cable. It contains three LEDs, red, green, and blue. Each one indicates the status of a different function.

The Arduino uses Ken Shirrif’s IR Remote library to handle the infrared remote control functions. SoftwareSerial is used to connect to the Bluetooth module. The Arduino code has built-in functionality for both Canon and Nikon infrared remote controls. To control the camera via Bluetooth, [AlxDroidDev] built a custom Android application. The app can not only control the camera’s shutter, but it can also control the level of zoom.


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.

Create an internet controlled robot using Livebots

Hi everone!

read more

Arduino IR Remote Control

This is a good example of hacking devices with Arduino. [sspence65] has put on oa good tutorial to start from something easy and simple: IR hack.

Capturing codes from any tv remote, and using them to control devices attached to Arduino Outputs. Press a button on a TV Remote, and the code appears in the serial monitor, Add that code to the case/switch statements in the sketch to control an output pin.

On the [website] there is the full explanation and code to build the same experience, but nothing prevent you to implement a custom way for your IR devices.

Arduino Blog 19 Dec 09:57
arduino  control  gallery  remote  tv  

RC Sega Rally @ Codebits VI

 

 

 

Codebits is the most geekest event in Portugal and surroundings!

read more

Let's Make Robots 25 Nov 09:24
arcade  arduino  camera  car  control  game  rc  sega rally  xbee  

Ben Heck makes Super Glove mod for Kinect, takes strain out of gestures (video)

Sick of trying to control your 360 using Kinect, semaphore and advanced flailing? Modgod Ben Heck, deciding he wanted to be more Minority Report and less lunatic, has been working on Power Glove 2.0 to improve the console's navigation experience. The prototype glove is tricked out with Arduino, an accelerometer, a gyroscope and some fingertip buttons. With the addition of IR and a little coding magic, the 360's interface can be controlled via subtle gestures, with increased functionality / style points also apparent. Check out the latest episode of The Ben Heck Show after the break for a detailed walkthrough of the project and a demo of the glove in action.

Continue reading Ben Heck makes Super Glove mod for Kinect, takes strain out of gestures (video)

Ben Heck makes Super Glove mod for Kinect, takes strain out of gestures (video) originally appeared on Engadget on Mon, 04 Jun 2012 17:33:00 EST. Please see our terms for use of feeds.

Permalink | Email this | Comments

Jumper: Arduino controlled animation

In this project, I have connected an Arduino to my computer and used a photoresistor to control an animation on the screen. Other sensors could have been used, but I chose a photoresistor because it feels like magic!!

The photoresistor responds to changes in ambient light as my hand moves up and down. The Arduino sends the reading to a Processing sketch on the computer via a Serial command (through the USB cable). The processing sketch interprets the signal from the Arduino and selects the appropriate picture to display.

I took a series of screenshots from the following YouTube video: http://www.youtube.com/watch?v=h6nE8m74kDg  And after borrowing a bit of code from these sites (1,2), the project was born.
This idea is not new, nor my own. There are many people who have done this project before, but I thought to blog about how I have done it, just for fun.

The Project Movie




Components Required


  • Arduino Uno (and associated software), and USB cable
  • Photoresistor or Photocell
  • 10K resistor
  • Wires to put it all together
  • Processing IDE from http://processing.org
  • Computer/laptop


The Arduino Sketch






The Arduino Code:

You can download the Arduino IDE from this site.
 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
/* Jumper: Using an Arduino to animate:
Written by ScottC on 02/06/2012 */

int photoRPin = 0;
int minLight;
int maxLight;
int lightLevel;
int adjustedLightLevel;
int oldLightLevel;

void setup() {
Serial.begin(9600);

//Setup the starting light level limits
lightLevel=analogRead(photoRPin);
minLight=lightLevel-10;
maxLight=lightLevel;
oldLightLevel=lightLevel;
}

void loop(){
lightLevel=analogRead(photoRPin);
delay(10);

//auto-adjust the minimum and maximum limits in real time
if(minLight>lightLevel){
minLight=lightLevel;
}
if(maxLight<lightLevel){
maxLight=lightLevel;
}

//Map the light level to produce a result between 1 and 28.
adjustedLightLevel = map(lightLevel, (minLight+20), (maxLight-20), 1, 28);
adjustedLightLevel = constrain (adjustedLightLevel, 1,28);

/*Only send a new value to the Serial Port if the
adjustedLightLevel value changes.*/
if(oldLightLevel==adjustedLightLevel){
//do nothing if the old value and the new value are the same.
}else{
//Update the oldLightLevel value for the next round
oldLightLevel=adjustedLightLevel;

/*Send the adjusted Light level result
to Serial port (processing)*/
Serial.println(adjustedLightLevel);
}
}

The code above was formatted using this site.



The Processing Code:

You can download the Processing IDE from this site.

 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
/* Jumper: Using an Arduino to animate
Written by ScottC on 02/06/2012

Source code derived from :
http://processing.org/learning/topics/sequential.html
http://processing.org/discourse/beta/num_1267080062.html

Pictures captured from:
http://www.youtube.com/watch?v=h6nE8m74kDg

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

import processing.serial.*;
Serial myPort;
String sensorReading="";

// Create the array that will hold the images
PImage[] movieImage = new PImage[29];

/* The frame variable is used to control which
image is displayed */
int frame = 1;



/* Setup the size of the window. Initialise serial communication with Arduino
and pre-load the images to be displayed later on. This is done only once.
I am using COM6 on my computer, you may need replace this value with your
active COM port being used by the Arduino.*/

void setup(){
size(700,600);

myPort = new Serial(this, "COM6", 9600);
myPort.bufferUntil('\n');

for(int i=0;i<28;i++){
movieImage[i] = loadImage("Jumper" + (i+1) + ".jpg");
}
}




// The draw function controls the animation sequence.

void draw(){

//this draws the relevant image to the window
image(movieImage[frame-1],0,0,width,height);
}

void serialEvent (Serial myPort){
sensorReading = myPort.readStringUntil('\n');
if(sensorReading != null){
sensorReading=trim(sensorReading);
if (sensorReading.length()<2){
frame = integerFromChar(sensorReading.charAt(0));
}else{
frame = integerFromChar(sensorReading.charAt(0))*10;
frame += integerFromChar(sensorReading.charAt(1));
}
}
}



/* This function used to convert the character received from the
serial port (Arduino), and converts it to a number */

int integerFromChar(char myChar) {
if (myChar < '0' || myChar > '9') {
return -1;
}else{
return myChar - '0';
}
}

The code above was formatted using this site.


The pictures 

Captured from this YouTube Video: http://www.youtube.com/watch?v=h6nE8m74kDg