Posts with «lesson» label

Arduino Workshop – A Hands-On Introduction with 65 Projects

Over the last few years you may have noticed a few of my Arduino tutorials, and during this time many people have mentioned that I should write a book. And now thanks to the team from No Starch Press this recommendation has morphed into my first book – “Arduino Workshop“:

Now into the fourth print run, “Arduino Workshop” is one of the few books on the market that can take the reader from zero knowledge to understanding the Arduino development platform, and working with a huge array of add-ons and technologies. You don’t need to buy any other preliminary book – this starts from the absolute beginning. And a huge “thank you” to all those who have purchased and supported the book so far – and it’s now available in Traditional Chinese, Korean, German and Polish.

Arduino Workshop” offers a professionally edited and curated path for the beginner to learn with and have fun. It’s a hands-on introduction to Arduino with 65 projects – from simple LED use right through to RFID, Internet connection, wireless data, working with cellular communications, and much more. Plus the reader also learns about electronics, good coding and other interesting topics.

Each project is explained in detail, explaining how the hardware and Arduino code works together. Plus we teach you how to read and understand circuit schematics and use this clear method of describing circuits which prepares the read for further electronics learning.

The reader doesn’t need any expensive tools or workspaces, and all the parts used are available from almost any electronics retailer. Furthermore all of the projects can be finished without soldering, so it’s safe for readers of all ages.

The editing team at No Starch Press, our technical editor Marc Alexander and myself have worked hard to make the book perfect for those without any electronics or Arduino experience at all, and it makes a great gift for someone to get them started. After working through the 65 projects the reader will have gained enough knowledge and confidence to create many things – and to continue researching on their own.

Or if you’ve been enjoying the results of my thousands of hours of work here at tronixstuff, you can show your appreciation by ordering a copy for yourself or as a gift. If you’re still not sure, review the table of contents, index and download a sample chapter from the Arduino Workshop website.

Arduino Workshop is available from No Starch Press in printed or DRM-free eBook (PDF, Mobi, and ePub) formats. And the eBooks are also included with the printed orders from No Starch Press so you can get started immediately. 

Autographed copies are available from Tronixlabs

Furthermore for readers outside of the United States wishing to save on postage, Arduino Workshop is available from many stores in various countries, for example:

And you can also find Arduino Workshop for sale from all the popular booksellers around the globe such as Amazon, Barnes and Noble, and so on.

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.
Tronixstuff 06 May 08:01

Arduino Workshop – A Hands-On Introduction with 65 Projects

Over the last few years you may have noticed a few of my Arduino tutorials, and during this time many people have mentioned that I should write a book. And now thanks to the team from No Starch Press this recommendation has morphed into my first book – “Arduino Workshop“:

Now into the fourth print run, “Arduino Workshop” is one of the few books on the market that can take the reader from zero knowledge to understanding the Arduino development platform, and working with a huge array of add-ons and technologies. You don’t need to buy any other preliminary book – this starts from the absolute beginning. And a huge “thank you” to all those who have purchased and supported the book so far – and it’s now available in Traditional Chinese, Korean, German and Polish.

Arduino Workshop” offers a professionally edited and curated path for the beginner to learn with and have fun. It’s a hands-on introduction to Arduino with 65 projects – from simple LED use right through to RFID, Internet connection, wireless data, working with cellular communications, and much more. Plus the reader also learns about electronics, good coding and other interesting topics.

Each project is explained in detail, explaining how the hardware and Arduino code works together. Plus we teach you how to read and understand circuit schematics and use this clear method of describing circuits which prepares the read for further electronics learning.

The reader doesn’t need any expensive tools or workspaces, and all the parts used are available from almost any electronics retailer. Furthermore all of the projects can be finished without soldering, so it’s safe for readers of all ages.

The editing team at No Starch Press, our technical editor Marc Alexander and myself have worked hard to make the book perfect for those without any electronics or Arduino experience at all, and it makes a great gift for someone to get them started. After working through the 65 projects the reader will have gained enough knowledge and confidence to create many things – and to continue researching on their own.

Or if you’ve been enjoying the results of my thousands of hours of work here at tronixstuff, you can show your appreciation by ordering a copy for yourself or as a gift. If you’re still not sure, review the table of contents, index and download a sample chapter from the Arduino Workshop website.

Arduino Workshop is available from No Starch Press in printed or DRM-free eBook (PDF, Mobi, and ePub) formats. And the eBooks are also included with the printed orders from No Starch Press so you can get started immediately. 

Autographed copies are available from Tronixlabs

Furthermore for readers outside of the United States wishing to save on postage, Arduino Workshop is available from many stores in various countries, for example:

And you can also find Arduino Workshop for sale from all the popular booksellers around the globe such as Amazon, Barnes and Noble, and so on.

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 Arduino Workshop – A Hands-On Introduction with 65 Projects appeared first on tronixstuff.

Tronixstuff 06 May 08:01

Arduino Tutorials – Chapter 42 – Numeric Keypads

Learn how to use various numeric keypads with your Arduino.

This is chapter forty-two of our huge Arduino tutorial seriesUpdated 16/12/2013

Numeric keypads can provide a simple end-user alternative for various interfaces for your projects. Or if you need a lot of buttons, they can save you a lot of time with regards to construction. We’ll run through connecting them, using the Arduino library and then finish with a useful example sketch.

Getting Started

Numeric keypads are available from many retailers, and no matter where you get them from, make sure you can get the data sheet, as this will make life easier when wiring them up. Here are the two examples for our tutorial, from Futurlec (slow and cheap):

 Again, the data sheet is important as it will tell you which pins or connectors on the keypad are for the rows and columns, for example the black keypad shown above. If you don’t have the data sheet – you will need to manually determine which contacts are for the rows and columns.

This can be done using the continuity function of a multimeter (the buzzer). Start by placing one probe on pin 1, the other probe on pin 2, and press the keys one by one. Make a note of when a button completes the circuit, then move onto the next pin. Soon you will know which is which. For example, on the example keypad pins 1 and 5 are for button “1″, 2 and 5 for “4″, etc…

Furthermore some keypads will have the pins soldered to the end, some will not. With our two example keypads, the smaller unit had the pins – and we soldered pins to the large white unit:

At this point please download and install the keypad Arduino library. Now we’ll demonstrate how to use both keypads in simple examples. 

Using a 12 digit keypad

We’ll use the small black keypad from Futurlec, an Arduino Uno-compatible and an LCD with an I2C interface for display purposes. If you don’t have an LCD you could always send the text to the serial monitor instead.

Wire up your LCD then connect the keypad to the Arduino in the following manner:
  • Keypad row 1 to Arduino digital 5
  • Keypad row 2 to Arduino digital 4
  • Keypad row 3 to Arduino digital 3
  • Keypad row 4 to Arduino digital 2
  • Keypad column 1 to Arduino digital 8
  • Keypad column 2 to Arduino digital 7
  • Keypad column 3 to Arduino digital 6

If your keypad is different to ours, take note of the lines in the sketch from:

// keypad type definition

As you need to change the numbers in the arrays rowPins[ROWS] and colPins[COLS]. You enter the digital pin numbers connected to the rows and columns of the keypad respectively.

Furthermore, the array keys stores the values displayed in the LCD when a particular button is pressed. You can see we’ve matched it with the physical keypad used, however you can change it to whatever you need. But for now, enter and upload the following sketch once you’re satisfied with the row/pin number allocations:

/* Numeric keypad and I2C LCD
   https://tronixstuff.com/tutorials > chapter 42
   Uses Keypad library for Arduino
   http://www.arduino.cc/playground/Code/Keypad
   by Mark Stanley, Alexander Brevig */

#include "Keypad.h"
#include "Wire.h" // for I2C LCD
#include "LiquidCrystal_I2C.h" // for I2C bus LCD module 
// http://www.dfrobot.com/wiki/index.php/I2C/TWI_LCD1602_Module_(SKU:_DFR0063)
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

// keypad type definition
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] =
 {{'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}};

byte rowPins[ROWS] = {
  5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
  8, 7, 6}; // connect to the column pinouts of the keypad

int count=0;

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
  lcd.init();          // initialize the lcd
  lcd.backlight(); // turn on LCD backlight
}

void loop()
{
  char key = keypad.getKey();
  if (key != NO_KEY)
  {
    lcd.print(key);
    count++;
    if (count==17)
    {
      lcd.clear();
      count=0;
    }
  }
}

And the results of the sketch are shown in this video.

So now you can see how the button presses can be translated into data for use in a sketch. We’ll now repeat this demonstration with the larger keypad.

Using a 16 digit keypad

We’ll use the larger white 4×4 keypad from Futurlec, an Arduino Uno-compatible and for a change the I2C LCD from Akafugu for display purposes. (We reviewed these previously). Again, if you don’t have an LCD you could always send the text to the serial monitor instead. Wire up the LCD and then connect the keypad to the Arduino in the following manner:

  • Keypad row 1 (pin eight) to Arduino digital 5
  • Keypad row 2 (pin 1) to Arduino digital 4
  • Keypad row 3 (pin 2) to Arduino digital 3
  • Keypad row 4 (pin 4) to Arduino digital 2
  • Keypad column 1 (pin 3) to Arduino digital 9
  • Keypad column 2 (pin 5) to Arduino digital 8
  • Keypad column 3 (pin 6) to Arduino digital 7
  • Keypad column 4 (pin 7) to Arduino digital 6
Now for the sketch – take note how we have accommodated for the larger numeric keypad:
  • the extra column in the array char keys[]
  • the extra pin in the array colPins[]
  • and the byte COLS = 4.
/* Numeric keypad and I2C LCD
   https://tronixstuff.com/tutorials > chapter 42
   Uses Keypad library for Arduino
   http://www.arduino.cc/playground/Code/Keypad
   by Mark Stanley, Alexander Brevig */

#include "Keypad.h"
#include "Wire.h" // for I2C LCD
#include "TWILiquidCrystal.h"
// http://store.akafugu.jp/products/26
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
 {{'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}};
byte rowPins[ROWS] = {
  5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
  9, 8, 7, 6}; //connect to the column pinouts of the keypad
int count=0;

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Keypad test!");  
  delay(1000);
  lcd.clear();
}

void loop()
{
  char key = keypad.getKey();
  if (key != NO_KEY)
  {
    lcd.print(key);
    Serial.print(key);
    count++;
    if (count==17)
    {
      lcd.clear();
      count=0;
    }
  }
}

And again you can see the results of the sketch above in this video.

And now for an example project, one which is probably the most requested use of the numeric keypad…

Example Project – PIN access system

The most-requested use for a numeric keypad seems to be a “PIN” style application, where the Arduino is instructed to do something based on a correct number being entered into the keypad. The following sketch uses the hardware described for the previous sketch and implements a six-digit PIN entry system. The actions to take place can be inserted in the functions correctPIN() and incorrectPIN(). And the PIN is set in the array char PIN[6]. With a little extra work you could create your own PIN-change function as well. 

// PIN switch with 16-digit numeric keypad
// https://tronixstuff.com/tutorials > chapter 42

#include "Keypad.h"
#include <Wire.h>
#include <TWILiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1','2','3','A'  }
  ,
  {
    '4','5','6','B'  }
  ,
  {
    '7','8','9','C'  }
  ,
  {
    '*','0','#','D'  }
};
byte rowPins[ROWS] = {
  5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
  9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

char PIN[6]={
  '1','2','A','D','5','6'}; // our secret (!) number
char attempt[6]={ 
  '0','0','0','0','0','0'}; // used for comparison
int z=0;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("PIN Lock ");
  delay(1000);
  lcd.clear();
  lcd.print("  Enter PIN...");
}

void correctPIN() // do this if correct PIN entered
{
  lcd.print("* Correct PIN *");
  delay(1000);
  lcd.clear();
  lcd.print("  Enter PIN...");
}

void incorrectPIN() // do this if incorrect PIN entered
{
  lcd.print(" * Try again *");
  delay(1000);
  lcd.clear();
  lcd.print("  Enter PIN...");
}

void checkPIN()
{
  int correct=0;
  int i;
  for ( i = 0;   i < 6 ;  i++ )
  {

    if (attempt[i]==PIN[i])
    {
      correct++;
    }
  }
  if (correct==6)
  {
    correctPIN();
  } 
  else
  {
    incorrectPIN();
  }

  for (int zz=0; zz<6; zz++) 
  {
    attempt[zz]='0';
  }
}

void readKeypad()
{
  char key = keypad.getKey();
  if (key != NO_KEY)
  {
    attempt[z]=key;
    z++;
    switch(key)
    {
    case '*':
      z=0;
      break;
    case '#':
      z=0;
      delay(100); // for extra debounce
      lcd.clear();
      checkPIN();
      break;
    }
  }
}

void loop()
{
  readKeypad();
}

The project is demonstrated in this video.

Conclusion

So now you have the ability to use twelve and sixteen-button keypads with your Arduino systems. I’m sure you will come up with something useful and interesting using the keypads in the near future.

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.

Arduino Tutorials – Chapter 42 – Numeric Keypads

Learn how to use various numeric keypads with your Arduino.

This is chapter forty-two of our huge Arduino tutorial seriesUpdated 16/12/2013

Numeric keypads can provide a simple end-user alternative for various interfaces for your projects. Or if you need a lot of buttons, they can save you a lot of time with regards to construction. We’ll run through connecting them, using the Arduino library and then finish with a useful example sketch.

Getting Started

Numeric keypads are available from many retailers, and no matter where you get them from, make sure you can get the data sheet, as this will make life easier when wiring them up. Here are the two examples for our tutorial, from Futurlec (slow and cheap):

 Again, the data sheet is important as it will tell you which pins or connectors on the keypad are for the rows and columns, for example the black keypad shown above. If you don’t have the data sheet – you will need to manually determine which contacts are for the rows and columns.

This can be done using the continuity function of a multimeter (the buzzer). Start by placing one probe on pin 1, the other probe on pin 2, and press the keys one by one. Make a note of when a button completes the circuit, then move onto the next pin. Soon you will know which is which. For example, on the example keypad pins 1 and 5 are for button “1″, 2 and 5 for “4″, etc…

Furthermore some keypads will have the pins soldered to the end, some will not. With our two example keypads, the smaller unit had the pins – and we soldered pins to the large white unit:

At this point please download and install the keypad Arduino library. Now we’ll demonstrate how to use both keypads in simple examples. 

Using a 12 digit keypad

We’ll use the small black keypad from Futurlec, an Arduino Uno-compatible and an LCD with an I2C interface for display purposes. If you don’t have an LCD you could always send the text to the serial monitor instead.

Wire up your LCD then connect the keypad to the Arduino in the following manner:
  • Keypad row 1 to Arduino digital 5
  • Keypad row 2 to Arduino digital 4
  • Keypad row 3 to Arduino digital 3
  • Keypad row 4 to Arduino digital 2
  • Keypad column 1 to Arduino digital 8
  • Keypad column 2 to Arduino digital 7
  • Keypad column 3 to Arduino digital 6

If your keypad is different to ours, take note of the lines in the sketch from:

// keypad type definition

As you need to change the numbers in the arrays rowPins[ROWS] and colPins[COLS]. You enter the digital pin numbers connected to the rows and columns of the keypad respectively.

Furthermore, the array keys stores the values displayed in the LCD when a particular button is pressed. You can see we’ve matched it with the physical keypad used, however you can change it to whatever you need. But for now, enter and upload the following sketch once you’re satisfied with the row/pin number allocations:

/* Numeric keypad and I2C LCD
   http://tronixstuff.com/tutorials > chapter 42
   Uses Keypad library for Arduino
   http://www.arduino.cc/playground/Code/Keypad
   by Mark Stanley, Alexander Brevig */

#include "Keypad.h"
#include "Wire.h" // for I2C LCD
#include "LiquidCrystal_I2C.h" // for I2C bus LCD module 
// http://www.dfrobot.com/wiki/index.php/I2C/TWI_LCD1602_Module_(SKU:_DFR0063)
LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display

// keypad type definition
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] =
 {{'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}};

byte rowPins[ROWS] = {
  5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
  8, 7, 6}; // connect to the column pinouts of the keypad

int count=0;

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
  lcd.init();          // initialize the lcd
  lcd.backlight(); // turn on LCD backlight
}

void loop()
{
  char key = keypad.getKey();
  if (key != NO_KEY)
  {
    lcd.print(key);
    count++;
    if (count==17)
    {
      lcd.clear();
      count=0;
    }
  }
}

And the results of the sketch are shown in this video.

So now you can see how the button presses can be translated into data for use in a sketch. We’ll now repeat this demonstration with the larger keypad.

Using a 16 digit keypad

We’ll use the larger white 4×4 keypad from Futurlec, an Arduino Uno-compatible and for a change the I2C LCD from Akafugu for display purposes. (We reviewed these previously). Again, if you don’t have an LCD you could always send the text to the serial monitor instead. Wire up the LCD and then connect the keypad to the Arduino in the following manner:

  • Keypad row 1 (pin eight) to Arduino digital 5
  • Keypad row 2 (pin 1) to Arduino digital 4
  • Keypad row 3 (pin 2) to Arduino digital 3
  • Keypad row 4 (pin 4) to Arduino digital 2
  • Keypad column 1 (pin 3) to Arduino digital 9
  • Keypad column 2 (pin 5) to Arduino digital 8
  • Keypad column 3 (pin 6) to Arduino digital 7
  • Keypad column 4 (pin 7) to Arduino digital 6
Now for the sketch – take note how we have accommodated for the larger numeric keypad:
  • the extra column in the array char keys[]
  • the extra pin in the array colPins[]
  • and the byte COLS = 4.

/* Numeric keypad and I2C LCD
   http://tronixstuff.com/tutorials > chapter 42
   Uses Keypad library for Arduino
   http://www.arduino.cc/playground/Code/Keypad
   by Mark Stanley, Alexander Brevig */

#include "Keypad.h"
#include "Wire.h" // for I2C LCD
#include "TWILiquidCrystal.h"
// http://store.akafugu.jp/products/26
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
 {{'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}};
byte rowPins[ROWS] = {
  5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
  9, 8, 7, 6}; //connect to the column pinouts of the keypad
int count=0;

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Keypad test!");  
  delay(1000);
  lcd.clear();
}

void loop()
{
  char key = keypad.getKey();
  if (key != NO_KEY)
  {
    lcd.print(key);
    Serial.print(key);
    count++;
    if (count==17)
    {
      lcd.clear();
      count=0;
    }
  }
}

And again you can see the results of the sketch above in this video.

And now for an example project, one which is probably the most requested use of the numeric keypad…

Example Project – PIN access system

The most-requested use for a numeric keypad seems to be a “PIN” style application, where the Arduino is instructed to do something based on a correct number being entered into the keypad. The following sketch uses the hardware described for the previous sketch and implements a six-digit PIN entry system. The actions to take place can be inserted in the functions correctPIN() and incorrectPIN(). And the PIN is set in the array char PIN[6]. With a little extra work you could create your own PIN-change function as well. 

// PIN switch with 16-digit numeric keypad
// http://tronixstuff.com/tutorials > chapter 42

#include "Keypad.h"
#include <Wire.h>
#include <TWILiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1','2','3','A'  }
  ,
  {
    '4','5','6','B'  }
  ,
  {
    '7','8','9','C'  }
  ,
  {
    '*','0','#','D'  }
};
byte rowPins[ROWS] = {
  5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {
  9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

char PIN[6]={
  '1','2','A','D','5','6'}; // our secret (!) number
char attempt[6]={ 
  '0','0','0','0','0','0'}; // used for comparison
int z=0;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("PIN Lock ");
  delay(1000);
  lcd.clear();
  lcd.print("  Enter PIN...");
}

void correctPIN() // do this if correct PIN entered
{
  lcd.print("* Correct PIN *");
  delay(1000);
  lcd.clear();
  lcd.print("  Enter PIN...");
}

void incorrectPIN() // do this if incorrect PIN entered
{
  lcd.print(" * Try again *");
  delay(1000);
  lcd.clear();
  lcd.print("  Enter PIN...");
}

void checkPIN()
{
  int correct=0;
  int i;
  for ( i = 0;   i < 6 ;  i++ )
  {

    if (attempt[i]==PIN[i])
    {
      correct++;
    }
  }
  if (correct==6)
  {
    correctPIN();
  } 
  else
  {
    incorrectPIN();
  }

  for (int zz=0; zz<6; zz++) 
  {
    attempt[zz]='0';
  }
}

void readKeypad()
{
  char key = keypad.getKey();
  if (key != NO_KEY)
  {
    attempt[z]=key;
    z++;
    switch(key)
    {
    case '*':
      z=0;
      break;
    case '#':
      z=0;
      delay(100); // for extra debounce
      lcd.clear();
      checkPIN();
      break;
    }
  }
}

void loop()
{
  readKeypad();
}

The project is demonstrated in this video.

Conclusion

So now you have the ability to use twelve and sixteen-button keypads with your Arduino systems. I’m sure you will come up with something useful and interesting using the keypads in the near future.

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 42 – Numeric Keypads appeared first on tronixstuff.

Arduino Tutorials – Chapter 22 – the AREF pin

Learn how to measure smaller voltages with greater accuracy using your Arduino.

This is chapter twenty-two of our huge Arduino tutorial seriesUpdated 12/12/2013

In this chapter we’ll look at how you can measure smaller voltages with greater accuracy using the analogue input pins on your Arduino or compatible board in conjunction with the AREF pin. However first we’ll do some revision to get you up to speed. Please read this post entirely before working with AREF the first time.

Revision

You may recall from the first few chapters in our tutorial series that we used the analogRead() function to measure the voltage of an electrical current from sensors and so on using one of the analogue input pins. The value returned from analogRead() would be between zero an 1023, with zero representing zero volts and 1023 representing the operating voltage of the Arduino board in use.

And when we say the operating voltage – this is the voltage available to the Arduino after the power supply circuitry. For example, if you have a typical Arduino Uno board and run it from the USB socket – sure, there is 5V available to the board from the USB socket on your computer or hub – but the voltage is reduced slightly as the current winds around the circuit to the microcontroller – or the USB source just isn’t up to scratch.

This can easily be demonstrated by connecting an Arduino Uno to USB and putting a multimeter set to measure voltage across the 5V and GND pins. Some boards will return as low as 4.8 V, some higher but still below 5V. So if you’re gunning for accuracy, power your board from an external power supply via the DC socket or Vin pin – such as 9V DC. Then after that goes through the power regulator circuit you’ll have a nice 5V, for example:

This is important as the accuracy of any analogRead() values will be affected by not having a true 5 V. If you don’t have any option, you can use some maths in your sketch to compensate for the drop in voltage. For example, if your voltage is 4.8V – the analogRead() range of 0~1023 will relate to 0~4.8V and not 0~5V. This may sound trivial, however if you’re using a sensor that returns a value as a voltage (e.g. the TMP36 temperature sensor) – the calculated value will be wrong. So in the interests of accuracy, use an external power supply.

Why does analogRead() return a value between 0 and 1023?

This is due to the resolution of the ADC. The resolution (for this article) is the degree to which something can be represented numerically. The higher the resolution, the greater accuracy with which something can be represented. We measure resolution in the terms of the number of bits of resolution.

For example, a 1-bit resolution would only allow two (two to the power of one) values – zero and one. A 2-bit resolution would allow four (two to the power of two) values – zero, one, two and three. If we tried to measure  a five volt range with a two-bit resolution, and the measured voltage was four volts, our ADC would return a numerical value of 3 – as four volts falls between 3.75 and 5V. It is easier to imagine this with the following image:

 So with our example ADC with 2-bit resolution, it can only represent the voltage with four possible resulting values. If the input voltage falls between 0 and 1.25, the ADC returns numerical 0; if the voltage falls between 1.25 and 2.5, the ADC returns a numerical value of 1. And so on. With our Arduino’s ADC range of 0~1023 – we have 1024 possible values – or 2 to the power of 10. So our Arduinos have an ADC with a 10-bit resolution.

So what is AREF? 

To cut a long story short, when your Arduino takes an analogue reading, it compares the voltage measured at the analogue pin being used against what is known as the reference voltage. In normal analogRead use, the reference voltage is the operating voltage of the board. For the more popular Arduino boards such as the Uno, Mega, Duemilanove and Leonardo/Yún boards, the operating voltage of 5V. If you have an Arduino Due board, the operating voltage is 3.3V. If you have something else – check the Arduino product page or ask your board supplier.

So if you have a reference voltage of 5V, each unit returned by analogRead() is valued at 0.00488 V. (This is calculated by dividing 1024 into 5V). What if we want to measure voltages between 0 and 2, or 0 and 4.6? How would the ADC know what is 100% of our voltage range?

And therein lies the reason for the AREF pin. AREF means Analogue REFerence. It allows us to feed the Arduino a reference voltage from an external power supply. For example, if we want to measure voltages with a maximum range of 3.3V, we would feed a nice smooth 3.3V into the AREF pin – perhaps from a voltage regulator IC. Then the each step of the ADC would represent around 3.22 millivolts (divide 1024 into 3.3).

Note that the lowest reference voltage you can have is 1.1V. There are two forms of AREF – internal and external, so let’s check them out.

External AREF

An external AREF is where you supply an external reference voltage to the Arduino board. This can come from a regulated power supply, or if you need 3.3V you can get it from the Arduino’s 3.3V pin. If you are using an external power supply, be sure to connect the GND to the Arduino’s GND pin. Or if you’re using the Arduno’s 3.3V source – just run a jumper from the 3.3V pin to the AREF pin.

To activate the external AREF, use the following in void setup():

analogReference(EXTERNAL); // use AREF for reference voltage

This sets the reference voltage to whatever you have connected to the AREF pin – which of course will have a voltage between 1.1V and the board’s operation voltage.

Very important note – when using an external voltage reference, you must set the analogue reference to EXTERNAL before using analogRead(). This will prevent you from shorting the active internal reference voltage and the AREF pin, which can damage the microcontroller on the board.

If necessary for your application, you can revert back to the board’s operating voltage for AREF (that is – back to normal) with the following:

analogReference(DEFAULT);

Now to demonstrate external AREF at work. Using a 3.3V AREF, the following sketch measures the voltage from A0 and displays the percentage of total AREF and the calculated voltage:

#include <LiquidCrystal.h>
LiquidCrystal lcd(8,9,4,5,6,7);

int analoginput = 0; // our analog pin
int analogamount = 0; // stores incoming value
float percentage = 0; // used to store our percentage value
float voltage =0; // used to store voltage value

void setup()
{
  lcd.begin(16, 2);
  analogReference(EXTERNAL); // use AREF for reference voltage
}

void loop()
{
  lcd.clear();
  analogamount=analogRead(analoginput);
  percentage=(analogamount/1024.00)*100;
  voltage=analogamount*3.222; // in millivolts
  lcd.setCursor(0,0);
  lcd.print("% of AREF: ");
  lcd.print(percentage,2);
  lcd.setCursor(0,1);  
  lcd.print("A0 (mV): ");
  lcd.println(voltage,2);
  delay(250);
}

The results of the sketch above are shown in the following video:

Internal AREF

The microcontrollers on our Arduino boards can also generate an internal reference voltage of 1.1V and we can use this for AREF work. Simply use the line:

analogReference(INTERNAL);

For Arduino Mega boards, use:

analogReference(INTERNAL1V1);

in void setup() and you’re off. If you have an Arduino Mega there is also a 2.56V reference voltage available which is activated with:

analogReference(INTERNAL2V56);

Finally – before settling on the results from your AREF pin, always calibrate the readings against a known good multimeter.

Conclusion

The AREF function gives you more flexibility with measuring analogue signals. If you are interested in using specific ADC components, we have tutorials on the ADS1110 16-bit ADC and the NXP PCF 8591 8-bit A/D and D/A IC.

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.

 

Arduino Tutorials – Chapter 22 – the AREF pin

Learn how to measure smaller voltages with greater accuracy using your Arduino.

This is chapter twenty-two of our huge Arduino tutorial seriesUpdated 12/12/2013

In this chapter we’ll look at how you can measure smaller voltages with greater accuracy using the analogue input pins on your Arduino or compatible board in conjunction with the AREF pin. However first we’ll do some revision to get you up to speed. Please read this post entirely before working with AREF the first time.

Revision

You may recall from the first few chapters in our tutorial series that we used the analogRead() function to measure the voltage of an electrical current from sensors and so on using one of the analogue input pins. The value returned from analogRead() would be between zero an 1023, with zero representing zero volts and 1023 representing the operating voltage of the Arduino board in use.

And when we say the operating voltage – this is the voltage available to the Arduino after the power supply circuitry. For example, if you have a typical Arduino Uno board and run it from the USB socket – sure, there is 5V available to the board from the USB socket on your computer or hub – but the voltage is reduced slightly as the current winds around the circuit to the microcontroller – or the USB source just isn’t up to scratch.

This can easily be demonstrated by connecting an Arduino Uno to USB and putting a multimeter set to measure voltage across the 5V and GND pins. Some boards will return as low as 4.8 V, some higher but still below 5V. So if you’re gunning for accuracy, power your board from an external power supply via the DC socket or Vin pin – such as 9V DC. Then after that goes through the power regulator circuit you’ll have a nice 5V, for example:

This is important as the accuracy of any analogRead() values will be affected by not having a true 5 V. If you don’t have any option, you can use some maths in your sketch to compensate for the drop in voltage. For example, if your voltage is 4.8V – the analogRead() range of 0~1023 will relate to 0~4.8V and not 0~5V. This may sound trivial, however if you’re using a sensor that returns a value as a voltage (e.g. the TMP36 temperature sensor) – the calculated value will be wrong. So in the interests of accuracy, use an external power supply.

Why does analogRead() return a value between 0 and 1023?

This is due to the resolution of the ADC. The resolution (for this article) is the degree to which something can be represented numerically. The higher the resolution, the greater accuracy with which something can be represented. We measure resolution in the terms of the number of bits of resolution.

For example, a 1-bit resolution would only allow two (two to the power of one) values – zero and one. A 2-bit resolution would allow four (two to the power of two) values – zero, one, two and three. If we tried to measure  a five volt range with a two-bit resolution, and the measured voltage was four volts, our ADC would return a numerical value of 3 – as four volts falls between 3.75 and 5V. It is easier to imagine this with the following image:

 So with our example ADC with 2-bit resolution, it can only represent the voltage with four possible resulting values. If the input voltage falls between 0 and 1.25, the ADC returns numerical 0; if the voltage falls between 1.25 and 2.5, the ADC returns a numerical value of 1. And so on. With our Arduino’s ADC range of 0~1023 – we have 1024 possible values – or 2 to the power of 10. So our Arduinos have an ADC with a 10-bit resolution.

So what is AREF? 

To cut a long story short, when your Arduino takes an analogue reading, it compares the voltage measured at the analogue pin being used against what is known as the reference voltage. In normal analogRead use, the reference voltage is the operating voltage of the board. For the more popular Arduino boards such as the Uno, Mega, Duemilanove and Leonardo/Yún boards, the operating voltage of 5V. If you have an Arduino Due board, the operating voltage is 3.3V. If you have something else – check the Arduino product page or ask your board supplier.

So if you have a reference voltage of 5V, each unit returned by analogRead() is valued at 0.00488 V. (This is calculated by dividing 1024 into 5V). What if we want to measure voltages between 0 and 2, or 0 and 4.6? How would the ADC know what is 100% of our voltage range?

And therein lies the reason for the AREF pin. AREF means Analogue REFerence. It allows us to feed the Arduino a reference voltage from an external power supply. For example, if we want to measure voltages with a maximum range of 3.3V, we would feed a nice smooth 3.3V into the AREF pin – perhaps from a voltage regulator IC. Then the each step of the ADC would represent around 3.22 millivolts (divide 1024 into 3.3).

Note that the lowest reference voltage you can have is 1.1V. There are two forms of AREF – internal and external, so let’s check them out.

External AREF

An external AREF is where you supply an external reference voltage to the Arduino board. This can come from a regulated power supply, or if you need 3.3V you can get it from the Arduino’s 3.3V pin. If you are using an external power supply, be sure to connect the GND to the Arduino’s GND pin. Or if you’re using the Arduno’s 3.3V source – just run a jumper from the 3.3V pin to the AREF pin.

To activate the external AREF, use the following in void setup():

analogReference(EXTERNAL); // use AREF for reference voltage

This sets the reference voltage to whatever you have connected to the AREF pin – which of course will have a voltage between 1.1V and the board’s operation voltage.

Very important note – when using an external voltage reference, you must set the analogue reference to EXTERNAL before using analogRead(). This will prevent you from shorting the active internal reference voltage and the AREF pin, which can damage the microcontroller on the board.

If necessary for your application, you can revert back to the board’s operating voltage for AREF (that is – back to normal) with the following:

analogReference(DEFAULT);

Now to demonstrate external AREF at work. Using a 3.3V AREF, the following sketch measures the voltage from A0 and displays the percentage of total AREF and the calculated voltage:

#include <LiquidCrystal.h>
LiquidCrystal lcd(8,9,4,5,6,7);

int analoginput = 0; // our analog pin
int analogamount = 0; // stores incoming value
float percentage = 0; // used to store our percentage value
float voltage =0; // used to store voltage value

void setup()
{
  lcd.begin(16, 2);
  analogReference(EXTERNAL); // use AREF for reference voltage
}

void loop()
{
  lcd.clear();
  analogamount=analogRead(analoginput);
  percentage=(analogamount/1024.00)*100;
  voltage=analogamount*3.222; // in millivolts
  lcd.setCursor(0,0);
  lcd.print("% of AREF: ");
  lcd.print(percentage,2);
  lcd.setCursor(0,1);  
  lcd.print("A0 (mV): ");
  lcd.println(voltage,2);
  delay(250);
}

The results of the sketch above are shown in the following video:

Internal AREF

The microcontrollers on our Arduino boards can also generate an internal reference voltage of 1.1V and we can use this for AREF work. Simply use the line:

analogReference(INTERNAL);

For Arduino Mega boards, use:

analogReference(INTERNAL1V1);

in void setup() and you’re off. If you have an Arduino Mega there is also a 2.56V reference voltage available which is activated with:

analogReference(INTERNAL2V56);

Finally – before settling on the results from your AREF pin, always calibrate the readings against a known good multimeter.

Conclusion

The AREF function gives you more flexibility with measuring analogue signals. If you are interested in using specific ADC components, we have tutorials on the ADS1110 16-bit ADC and the NXP PCF 8591 8-bit A/D and D/A IC.

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 22 – the AREF pin 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.

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 30 – twitter

Learn how to tweet from your Arduino.

This is chapter thirty of our huge Arduino tutorial seriesUpdated 16/06/2014

In this article you will learn how to send messages from an Ethernet-enabled Arduino to twitter. For the uninitiated who may be thinking “what is all this twitter nonsense about?”, twitter is a form of microblogging. 

You can create a message with a maximum length of 140 characters, and broadcast this on the twitter service. For people to receive your messages (or tweets) they also need to be a member of twitter and choose to subscribe to your tweets.

Generally people will use the twitter service using one of two methods: either using a web browser, or using the twitter application on a smartphone or tablet computer. For example, here is a typical web browser view:

… and here is an example of a twitter application running on an Android OS smartphone:

The neat thing about twitter on a mobile device is that if your username is mentioned in a tweet, you will be notified pretty well immediately as long as you have mobile data access. More on that later. In some areas, you can set twitter to send tweets from a certain user to your mobile phone via SMS – however if doing so be careful to confirm possible charges to your mobile phone account.

Finally, if you are worried about privacy with regards to your tweets, you can set your account to private and only allow certain people to follow your tweets.

So let’s get started.

First of all – you will need a twitter account. If you do not have one, you can sign up for one here. If you already have a twitter account, you can always open more for other uses – such as an Arduino.

For example, my twitter account is @tronixstuff, but my demonstration machine twitter account is @tronixstuff2. Then I have set my primary account to follow my machine’s twitter account.

Now log into twitter with using the account you will have for your Arduino and visit this page and get yourself a token by following the Step One link. The process will take you through authorising the “tweet library” page to login to your twitter account – this is ok. It will then present you with a long text called a “token”, for example:

Save your token somewhere safe, as you will need to insert it into your Arduino sketch. Finally, don’t give it to others as then they will be able to post onto twitter using your account. Next, follow step two from the same page – which involves download and installation of the required Arduino library.

Now for the hardware.

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:

If you’re looking for an Arduino-twitter solution with WiFi, check out the Arduino Yún tutorials.

From this point it would be a good idea to check your hardware is working. To do so, please run the webserver example sketch as explained in chapter sixteen (Ethernet). While you do that, we’ll have a break…

Sending your first tweet

If you want your Arduino to send a simple tweet consider the following sketch. We have a simple function tweet() which simply sends a line of text (which has a maximum length of 140 characters). Don’t forget to update your IP address, MAC address and token:

// Simple twitter interface

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

// Alter IP address to suit your own network!
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 0, 99}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token

void setup()
{
  delay(5000);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
}

void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()
{
  delay(1000);
  tweet("Purple monkey dishwasher");
  do{} while(1>0); // endless loop
}

You can check the status of the tweeting via the serial monitor. For example, if the tweet was successful you will see:

However if you try to send the same tweet more than once in a short period of time, or another error takes place – twitter will return an error message, for example:

And finally if it works, the tweet will appear:

Previously we mentioned that you can be alerted to a tweet by your mobile device. This can be done by putting your own twitter account name in the contents of the tweet.

For example – my normal twitter account is @tronixstuff. If I put the text “@tronixstuff” in the text tweeted by my Arduino’s twitter account – the twitter app on my smartphone will let me know I have been mentioned – as shown in the following video:

You may have noticed in the video that a text message arrived as well – that service is a function of my cellular carrier (Telstra) and may not be available to others. Nevertheless this is a neat way of getting important messages from your Arduino to a smart phone or other connected device.

Sending data in a tweet

So what if you have  a sensor or other device whose data you want to know about via twitter? You can send data generated from an Arduino sketch over twitter without too much effort.

In the following example we’ll send the value from analogue pin zero (A0) in the contents of a tweet. And by adding your twitter @username you will be notified by your other twitter-capable devices:

// Simple twitter interface

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

// Alter IP address to suit your own network!
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 0, 99}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token

int analogZero;
char tweetText[140];

void setup()
{
  delay(5000);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
}

void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()
{
  // get some data from A0. 
  analogZero=analogRead(0);

  // assemble message to send. This inserts the value of "analogZero" into the variable "tweetText" at point %d
  sprintf(tweetText, "Pin analogue zero reads: %d. @username.", analogZero); // change @username to your twitter account name

  delay(1000);
  tweet(tweetText);
  do{ } 
  while(1>0); // endless loop
}

You may have noticed a sneaky sprintf function in void loop(). This is used to insert the integer analogZero into the character array tweetText that we send with the tweet() function. And the results of the example:

So you can use the previous sketch as a framework to create your own Arduino-powered data twittering machine. Send temperature alerts, tank water levels, messages from an alarm system, or just random tweets to your loved one.

Conclusion

So there you have it, another useful way to send information from your Arduino to the outside world. Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. Big thanks to @neocat for their work with the twitter  Arduino libraries.

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.

In the meanwhile 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? And join our friendly Google Group – 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 Arduino Tutorials – Chapter 30 – twitter appeared first on tronixstuff.

Tronixstuff 04 Dec 01:52

Arduino Tutorials – Chapter 30 – twitter

Learn how to tweet from your Arduino.

This is chapter thirty of our huge Arduino tutorial seriesUpdated 16/06/2014

In this article you will learn how to send messages from an Ethernet-enabled Arduino to twitter. For the uninitiated who may be thinking “what is all this twitter nonsense about?”, twitter is a form of microblogging. 

You can create a message with a maximum length of 140 characters, and broadcast this on the twitter service. For people to receive your messages (or tweets) they also need to be a member of twitter and choose to subscribe to your tweets.

Generally people will use the twitter service using one of two methods: either using a web browser, or using the twitter application on a smartphone or tablet computer. For example, here is a typical web browser view:

… and here is an example of a twitter application running on an Android OS smartphone:

The neat thing about twitter on a mobile device is that if your username is mentioned in a tweet, you will be notified pretty well immediately as long as you have mobile data access. More on that later. In some areas, you can set twitter to send tweets from a certain user to your mobile phone via SMS – however if doing so be careful to confirm possible charges to your mobile phone account.

Finally, if you are worried about privacy with regards to your tweets, you can set your account to private and only allow certain people to follow your tweets.

So let’s get started.

First of all – you will need a twitter account. If you do not have one, you can sign up for one here. If you already have a twitter account, you can always open more for other uses – such as an Arduino.

For example, my twitter account is @tronixstuff, but my demonstration machine twitter account is @tronixstuff2. Then I have set my primary account to follow my machine’s twitter account.

Now log into twitter with using the account you will have for your Arduino and visit this page and get yourself a token by following the Step One link. The process will take you through authorising the “tweet library” page to login to your twitter account – this is ok. It will then present you with a long text called a “token”, for example:

Save your token somewhere safe, as you will need to insert it into your Arduino sketch. Finally, don’t give it to others as then they will be able to post onto twitter using your account. Next, follow step two from the same page – which involves download and installation of the required Arduino library.

Now for the hardware.

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:

If you’re looking for an Arduino-twitter solution with WiFi, check out the Arduino Yún tutorials.

From this point it would be a good idea to check your hardware is working. To do so, please run the webserver example sketch as explained in chapter sixteen (Ethernet). While you do that, we’ll have a break…

Sending your first tweet

If you want your Arduino to send a simple tweet consider the following sketch. We have a simple function tweet() which simply sends a line of text (which has a maximum length of 140 characters). Don’t forget to update your IP address, MAC address and token:

// Simple twitter interface

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

// Alter IP address to suit your own network!
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 0, 99}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token

void setup()
{
  delay(5000);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
}

void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()
{
  delay(1000);
  tweet("Purple monkey dishwasher");
  do{} while(1>0); // endless loop
}

You can check the status of the tweeting via the serial monitor. For example, if the tweet was successful you will see:

However if you try to send the same tweet more than once in a short period of time, or another error takes place – twitter will return an error message, for example:

And finally if it works, the tweet will appear:

Previously we mentioned that you can be alerted to a tweet by your mobile device. This can be done by putting your own twitter account name in the contents of the tweet.

For example – my normal twitter account is @tronixstuff. If I put the text “@tronixstuff” in the text tweeted by my Arduino’s twitter account – the twitter app on my smartphone will let me know I have been mentioned – as shown in the following video:

You may have noticed in the video that a text message arrived as well – that service is a function of my cellular carrier (Telstra) and may not be available to others. Nevertheless this is a neat way of getting important messages from your Arduino to a smart phone or other connected device.

Sending data in a tweet

So what if you have  a sensor or other device whose data you want to know about via twitter? You can send data generated from an Arduino sketch over twitter without too much effort.

In the following example we’ll send the value from analogue pin zero (A0) in the contents of a tweet. And by adding your twitter @username you will be notified by your other twitter-capable devices:

// Simple twitter interface

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

// Alter IP address to suit your own network!
byte mac[] = {   0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // create MAC address for ethernet shield
byte ip[] = {   192, 168, 0, 99}; // choose your own IP for ethernet shield
Twitter twitter("aaaaaaa"); // replace aaaaaaa with your token

int analogZero;
char tweetText[140];

void setup()
{
  delay(5000);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
}

void tweet(char msg[])
{
  Serial.println("connecting ...");
  if (twitter.post(msg))
  {
    // Specify &Serial to output received response to Serial.
    // If no output is required, you can just omit the argument, e.g.
    // int status = twitter.wait();
    int status = twitter.wait(&Serial);
    if (status == 200)
    {
      Serial.println("OK.");
    } 
    else
    {
      Serial.print("failed : code ");
      Serial.println(status);
    }
  } 
  else
  {
    Serial.println("connection failed.");
  }
}

void loop()
{
  // get some data from A0. 
  analogZero=analogRead(0);

  // assemble message to send. This inserts the value of "analogZero" into the variable "tweetText" at point %d
  sprintf(tweetText, "Pin analogue zero reads: %d. @username.", analogZero); // change @username to your twitter account name

  delay(1000);
  tweet(tweetText);
  do{ } 
  while(1>0); // endless loop
}

You may have noticed a sneaky sprintf function in void loop(). This is used to insert the integer analogZero into the character array tweetText that we send with the tweet() function. And the results of the example:

So you can use the previous sketch as a framework to create your own Arduino-powered data twittering machine. Send temperature alerts, tank water levels, messages from an alarm system, or just random tweets to your loved one.

Conclusion

So there you have it, another useful way to send information from your Arduino to the outside world. Stay tuned for upcoming Arduino tutorials by subscribing to the blog, RSS feed (top-right), twitter or joining our Google Group. Big thanks to @neocat for their work with the twitter  Arduino libraries.

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.

In the meanwhile 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? And join our friendly Google Group – 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.

Tronixstuff 04 Dec 01:52