Posts with «tronixstuff» label

Tutorial – Arduino and Color LCD

Learn how to use an inexpensive colour LCD shield with your Arduino. This is chapter twenty-eight of our huge Arduino tutorial series.

Updated 03/02/2014

There are many colour LCDs on the market that can be used with an Arduino, and for this tutorial we’re using a relatively simple model available that is available from suppliers such as Tronixlabs, based on a small LCD originally used in Nokia 6100 mobile phones:

These are a convenient and inexpensive way of displaying data, or for monitoring variables when debugging a sketch. Before getting started, a small amount of work is required.

From the two examples we have seen, neither of them arrive fitted with stacking headers (or in Sparkfun’s case – not included) or pins, so before doing anything you’ll need to fit your choice of connector. Although the LCD shield arrived with stacking headers, we used in-line pins as another shield would never be placed on top:

Which can easily be soldered to the shield in a few minutes:

 While we’re on the subject of pins – this shield uses D3~D5 for the three buttons, and D8, 9, 11 and 13 for the LCD interface. The shield takes 5V and doesn’t require any external power for the backlight. The LCD module has a resolution of 128 x 128 pixels, with nine defined colours (red, green, blue, cyan, magenta, yellow, brown, orange, pink) as well as black and white.

So let’s get started. From a software perspective, the first thing to do is download and install the library for the LCD shield. Visit the library page here. Then download the .zip file, extract and copy the resulting folder into your ..\arduino-1.0.x\libraries folder. Be sure to rename the folder to “ColorLCDShield“. Then restart the Arduino IDE if it was already open.

At this point let’s check the shield is working before moving forward. Once fitted to your Arduino, upload the ChronoLCD_Color sketch that’s included with the library, from the IDE Examples menu:

This will result with a neat analogue clock you can adjust with the buttons on the shield, as shown in this video.

It’s difficult to photograph the LCD – (some of them have very bright backlights), so the image may not be a true reflection of reality. Nevertheless this shield is easy to use and we will prove this in the following examples. So how do you control the color LCD shield in your sketches?

At the start of every sketch, you will need the following lines:

#include "ColorLCDShield.h"
LCDShield lcd;

as well as the following in void setup():

lcd.init(PHILIPS); 
lcd.contrast(63); // sets LCD contrast (value between 0~63)

With regards to lcd.init(), try it first without a parameter. If the screen doesn’t work, try EPSON instead. There are two versions of the LCD shield floating about each with a different controller chip. The contrast parameter is subjective, however 63 looks good – but test for yourself.

Now let’s move on to examine each function with a small example, then use the LCD shield in more complex applications.

The LCD can display 8 rows of 16 characters of text. The function to display text is:

lcd.setStr("text", y,x, foreground colour, background colour);

where x and y are the coordinates of the top left pixel of the first character in the string. Another necessary function is:

lcd.clear(colour);

Which clears the screen and sets the background colour to the parameter colour.  Please note – when referring to the X- and Y-axis in this article, they are relative to the LCD in the position shown below. Now for an example – to recreate the following display:

… use the following sketch:

// Example 28.1
#include "ColorLCDShield.h"
LCDShield lcd;

void setup()
{
 // following two required for LCD
 lcd.init(PHILIPS); 
 lcd.contrast(63); // sets LCD contrast (value between 0~63)
}

void loop()
{
 lcd.clear(BLACK);
 lcd.setStr("ABCDefghiJKLMNOP", 0,2, WHITE, BLACK);
 lcd.setStr("0123456789012345", 15,2, WHITE, BLACK);
 lcd.setStr("ABCDefghiJKLMNOP", 30,2, WHITE, BLACK);
 lcd.setStr("0123456789012345", 45,2, WHITE, BLACK);
 lcd.setStr("ABCDefghiJKLMNOP", 60,2, WHITE, BLACK);
 lcd.setStr("0123456789012345", 75,2, WHITE, BLACK);
 lcd.setStr("ABCDefghiJKLMNOP", 90,2, WHITE, BLACK);
 lcd.setStr("0123456789012345", 105,2, WHITE, BLACK);
 do {} while (1>0);
}

In example 28.1 we used the function lcd.clear(), which unsurprisingly cleared the screen and set the background a certain colour.

Let’s have a look at the various background colours in the following example. The lcd.clear()  function is helpful as it can set the entire screen area to a particular colour. As mentioned earlier, there are the predefined colours red, green, blue, cyan, magenta, yellow, brown, orange, pink, as well as black and white. Here they are in the following example:

// Example 28.2

int del = 1000;
#include "ColorLCDShield.h"
LCDShield lcd; 
void setup() 
{ 
  // following two required for LCD 
  lcd.init(PHILIPS); 
  lcd.contrast(63); // sets LCD contrast (value between 0~63) 
}

void loop()
{
 lcd.clear(WHITE);
 lcd.setStr("White", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(BLACK);
 lcd.setStr("Black", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(YELLOW);
 lcd.setStr("Yellow", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(PINK);
 lcd.setStr("Pink", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(MAGENTA);
 lcd.setStr("Magenta", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(CYAN);
 lcd.setStr("Cyan", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(BROWN);
 lcd.setStr("Brown", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(ORANGE);
 lcd.setStr("Orange", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(BLUE);
 lcd.setStr("Blue", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(RED);
 lcd.setStr("Red", 39,40, WHITE, BLACK);
 delay(del);
 lcd.clear(GREEN);
 lcd.setStr("Green", 39,40, WHITE, BLACK);
 delay(del);
}

And now to see it in action. In this demonstration video the colours are more livid in real life, unfortunately the camera does not capture them so well.

 

Now that we have had some experience with the LCD library’s functions, we can move on to drawing some graphical objects. Recall that the screen has a resolution of 128 by 128 pixels. We have four functions to make use of this LCD real estate, so let’s see how they work. The first is:

lcd.setPixel(int colour, Y, X);

This function places a pixel (one LCD dot) at location x, y with the colour of colour.

Note – in this (and all the functions that have a colour parameter) you can substitute the colour (e.g. BLACK) for a 12-bit RGB value representing the colour required. Next is:

lcd.setLine(x0, y0, x1, y1, COLOUR);

Which draws a line of colour COLOUR, from position x0, y0 to x1, y1. Our next function is:

lcd.setRect(x0, y0, x1, y1, fill, COLOUR);

This function draws an oblong or square of colour COLOUR with the top-left point at x0, y0 and the bottom right at x1, y1. Fill is set to 0 for an outline, and 1 for a filled oblong. It would be convenient for drawing bar graphs for data representation. And finally, we can also create circles, using:

lcd.setCircle(x, y, radius, COLOUR);

X and Y is the location for the centre of the circle, radius and COLOUR are self-explanatory. We will now use these graphical functions in the following demonstration sketch:
// Example 28.3

#include "ColorLCDShield.h"
LCDShield lcd;
int del = 1000;
int xx, yy = 0;

void setup()
{
  lcd.init(PHILIPS); 
  lcd.contrast(63); // sets LCD contrast (value between 0~63)
  lcd.clear(BLACK);
  randomSeed(analogRead(0));
}

void loop()
{
  lcd.setStr("Graphic Function", 40,3, WHITE, BLACK);
  lcd.setStr("Test Sketch", 55, 20, WHITE, BLACK); 
  delay(5000);
  lcd.clear(BLACK);
  lcd.setStr("lcd.setPixel", 40,20, WHITE, BLACK);
  delay(del);
  lcd.clear(BLACK);
  for (int a=0; a<500; a++)
  {
    xx=random(160);
    yy=random(160);
    lcd.setPixel(WHITE, yy, xx);
    delay(10);
  }
  delay(del);
  lcd.clear(BLACK);
  lcd.setStr("LCDDrawCircle", 40,10, WHITE, BLACK);
  delay(del);
  lcd.clear(BLACK); 
  for (int a=0; a<2; a++)
  {
    for (int b=1; b<6; b++)
    {
      xx=b*5;
      lcd.setCircle(32, 32, xx, WHITE);
      delay(200);
      lcd.setCircle(32, 32, xx, BLACK);
      delay(200);
    }
  }
  lcd.clear(BLACK); 
  for (int a=0; a<3; a++)
  {
    for (int b=1; b<12; b++)
    {
      xx=b*5;
      lcd.setCircle(32, 32, xx, WHITE);
      delay(100);
    }
    lcd.clear(BLACK);
  }
  lcd.clear(BLACK); 
  for (int a=0; a<3; a++)
  {
    for (int b=1; b<12; b++)
    {
      xx=b*5;
      lcd.setCircle(32, 32, xx, WHITE);
      delay(100);
    }
    lcd.clear(BLACK);
  }
  delay(del);
  lcd.clear(BLACK);
  lcd.setStr("LCDSetLine", 40,10, WHITE, BLACK);
  delay(del);
  lcd.clear(BLACK); 
  for (int a=0; a<160; a++)
  {
    xx=random(160);
    lcd.setLine(a, 1, xx, a, WHITE);
    delay(10);
  }
  lcd.clear(BLACK);
  lcd.setStr("LCDSetRect", 40,10, WHITE, BLACK);
  delay(del);
  lcd.clear(BLACK); 
  for (int a=0; a<10; a++)
  {
    lcd.setRect(32,32,64,64,0,WHITE);
    delay(200);
    lcd.clear(BLACK);
    lcd.setRect(32,32,64,64,1,WHITE);
    delay(200);
    lcd.clear(BLACK); 
  }
  lcd.clear(BLACK); 
}

The results of this sketch are shown in this video. For photographic reasons, I will stick with white on black for the colours.

So now you have an explanation of the functions to drive the screen – and only your imagination is holding you back.

Conclusion

Hopefully this tutorial is of use to you. and you’re no longer wondering “how to use a color LCD with Arduino”. They’re available from our tronixlabs store. And if you enjoyed this article, 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 Color LCD appeared first on tronixstuff.

Review – Iteaduino Lite “nearly 100% Arduino-compatible” board

Introduction

Over the last year there have been a few crowd-funded projects that offered very inexpensive Arduino-compatible boards. Frankly most of them weren’t anything out of the ordinary, however one of them is quite interesting due to the particular design of the board, and is the subject of this review.

An established company Iteadstudio ran a successful Indiegogo campaign last December to fund their Iteaduino Lite – Most inexpensive full-sized Arduino derivative board”. Having a spare US$5 we placed an order and patiently waited for the board. Being such a low price it was guaranteed to raise the funding – but was it worth the money? Or the effort? Possibly.

The board

In typical fashion the board arrived in bare packaging:

 The Iteaduino Lite isn’t that surprising at first glance:

To the new observer, it looks like an Arduino board of some sort. Nice to see all those GPIO pins with double breakouts. No surprises underneath:

The URL on the bottom is incorrect, instead visit http://imall.iteadstudio.com/iteaduino-lite.html. Looking at the board in more detail, there are some interesting points of difference with the usual Arduino Uno and compatibles.

The USB interface is handled with the Silabs CP2102 USB to UART bridge IC:

The next difference is the power circuitry – instead of using a linear voltage regulator, Itead have used a contemporary DC-DC converter circuit which can accept between 7 and 24V DC:

Furthermore, the entire board can operate at either 5V or 3.3V, which is selected with the slide switch in the above image. Finally – the microcontroller. Instead of an Atmel product, Itead have chosen the LogicGreen LGT8F88 microcontroller, a domestic Chinese product:

And there are only two LEDs on the Iteaduino Lite, for power and D13. The LED on D13 ins’t controlled via a MOSFET like other Arduino-compatibles, instead it’s simply connected to GND via a 1kΩ resistor.

Getting started with the Iteaduino Lite

The stacking header sockets will need to be soldered in – the easiest way is to insert them into the board, use an shield to hold them in and flip the lot upside down:

Which should give you neatly-installed headers:

Watch out for the corners of the board, they’re quite sharp. Next, you need to install the USB driver for the CP2102. My Windows 7 machine picked it up without any issues, however the drivers can be downloaded if necessary.

Finally a new board profile is required for the Arduino IDE. At the time of writing you’ll need Arduino IDE v1.0.5 r2. Download this zip file, and extract the contents into your ..\Arduino-1.0.5-r2\hardware folder. The option should now be available in the Tools > Board menu in the IDE, for example:

From this point you can run the blink example to check all is well. At this point you will realise one of the limitations of the Iteaduino Lite – memory. For example:

You only have 7168 bytes of memory for your sketches – compared to 32, 256 for an Arduino Uno or compatible. The reason for this is the small capacity of  …

The LogicGreen LGT8F88 microcontroller

This MCU is a Chinese company’s answer to the Atmel ATmega88A. You can find more details here, and Itead also sells them separately. The LGT8F88 offers us 8Kbyte of flash memory of which 0.7KB is used by bootloader, 1 KB of SRAM and 504 bytes (count ’em) of EEPROM. Apparently it can run at speeds of up to 32 MHz, however the LGT8F88 is set to 16 MHz for the Iteaduino Lite.

According to Logic Green, their LGT8F88 “introduce a smart instruction cache, which can fetch more instructions one time, effectively decrease memory accessing operations“. So to see if there’s a speed bump, we uploaded the following sketch – written by Steve Curd from the Arduino forum. It calculates Newton Approximation for pi using an infinite series:

//
// Pi_2
//
// Steve Curd
// December 2012
//
// This program approximates pi utilizing the Newton's approximation.  It quickly
// converges on the first 5-6 digits of precision, but converges verrrry slowly
// after that.  For example, it takes over a million iterations to get to 7-8
// significant digits.
//
// I wrote this to evaluate the performance difference between the 8-bit Arduino Mega,
// and the 32-bit Arduino Due.
// 

#define ITERATIONS 100000L    // number of iterations
#define FLASH 1000            // blink LED every 1000 iterations

void setup() {
  pinMode(13, OUTPUT);        // set the LED up to blink every 1000 iterations
  Serial.begin(57600);
}

void loop() {

  unsigned long start, time;
  unsigned long niter=ITERATIONS;
  int LEDcounter = 0;
  boolean alternate = false;
  unsigned long i, count=0;
  float x = 1.0;
  float temp, pi=1.0;

  Serial.print("Beginning ");
  Serial.print(niter);
  Serial.println(" iterations ...");
  Serial.println();

  start = millis();  
  for ( i = 2; i < niter; i++) {
    x *= -1.0;
    pi += x / (2.0f*(float)i-1.0f);
    if (LEDcounter++ > FLASH) {
      LEDcounter = 0;
      if (alternate) {
        digitalWrite(13, HIGH);
        alternate = false;
      } 
      else {
        digitalWrite(13, LOW);
        alternate = true;
      }
      temp = 40000000.0 * pi;
    }
  }
  time = millis() - start;

  pi = pi * 4.0;

  Serial.print("# of trials = ");
  Serial.println(niter);
  Serial.print("Estimate of pi = ");
  Serial.println(pi, 10);

  Serial.print("Time: "); 
  Serial.print(time); 
  Serial.println(" ms");

  delay(10000);
}

For a baseline comparison, an Arduno Uno R3 completes the calculations in 5563 ms:

… and the Iteaduino Lite completed it in 5052 ms:

So that’s around a 10% speed increase. Not bad at all. The LGT8F88 also has the requisite GPIO, SPI, and I2C available as per normal Arduino Uno boards. You can download the data sheet with more technical details from here. Frankly the LGT8F88 is an interesting contender in the marketplace, and if Logic Green can offer a DIP version at a good price, the ATtiny fans will have a field day. Time will tell.

Power Circuit

The DC-DC circuit promises 5V output, with up to 24V DC input – so we cranked the input to 24V,  put a 1A load on the 5V output – and put the DSO over 5V to measure the variations – with a neat result:

So no surprises there at all, the Iteaduino Lite gives you more flexible power supply options than the usual Arduino board. However an eagle-eyed reader notes that a few of the capacitors are only rated at 25V – especially the two right after the DC socket/Vin. You can see this in the schematic (.pdf). So take that into account, or drop your Vin to something more regular such as below 12V.

Conclusion

The Iteaduino Lite is an interesting experiment in bargain Arduino-compatible boards. However we say “why bother?” and just get a Uno R3-compatible board.

At the end of the day – why bother with this board? For a little extra you can get boards with the ATmega328P or 32U4 which gives you 100% compatibility. Nevertheless, this was an interesting experiment. Full-sized images are available on flickr. And if you enjoyed this article, 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 Review – Iteaduino Lite “nearly 100% Arduino-compatible” board appeared first on tronixstuff.

Tronixstuff 30 Jan 23:01

Easily test and experiment with GSM modules using AT Command Tester

Introduction

Working with GSM modules and by extension Arduino GSM shields can either be a lot of fun or bring on a migraine. This is usually due to the quality of module, conditions placed on the end user by the network, reception, power supply and more.

Furthermore we have learned after several years that even after following our detailed and tested tutorials, people are having trouble understanding why their GSM shield isn’t behaving. With this in mind we’re very happy to have learned about a free online tool that can be used to test almost every parameter of a GSM module with ease – AT Command Tester. This software is a Java application that runs in a web browser, and communicates with a GSM module via an available serial port.

Initial Setup

It’s simple, just visit http://m2msupport.net/m2msupport/module-tester/ with any web browser that can run Java. You may need to alter the Java security settings down to medium. Windows users can find this in Control Panel> All Control Panel Items  > Java – for example:

Once the security settings have been changed, just visit the URL, click ‘accept’ and ‘run’ in the next dialogue box that will appear, for example:

And after a moment, the software will appear:

Once you’re able to run the AT Command Tester software, the next step is to physically connect the hardware. If you’re just using a bare GSM module, a USB-serial adaptor can be used for easy connection to the PC. For Arduino GSM shield users, you can use the Arduino as a bridge between the shield and PC, however if your GSM shield uses pins other than D0/D1 for serial data transmission (such as our SIM900 shield) then you’ll need to upload a small sketch to bridge the software and hardware serial ports, for example:

//Serial Relay – Arduino will patch a serial link between the computer and the GPRS Shield
//at 19200 bps 8-N-1 Computer is connected to Hardware UART
//GPRS Shield is connected to the Software UART

#include <SoftwareSerial.h>

SoftwareSerial mySerial(7,8); // change these paramters depending on your Arduino GSM Shield

void setup()
{
  Serial.begin(19200);
  //Serial.println(“Begin”);
  mySerial.begin(19200);

}

void loop()
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Using the software

Once you have the hardware connected and the Arduino running the required sketch, run the software – then click “Find ports” to select the requried COM: port, set the correct data speed and click “Connect”. After a moment the software will interrogate the GSM module and report its findings in the yellow log area:

 As you can see on the left of the image above, there is a plethora of options and functions you can run on the module. By selecting the manufacturer of your GSM module form the list, a more appropriate set of functions for your module is displayed.

When you click a function, the AT command sent to the module and its response is shown in the log window – and thus the magic of this software. You can simply throw any command at the module and await the response, much easier than looking up the commands and fighting with terminal software. You can also send AT commands in batches, experiment with GPRS data, FTP, and the GPS if your module has one.

To give you a quick overview of what is possible, we’ve made this video which captures us running a few commands on a SIM900-based Arduino shield. If possible, view it in 720p.

Conclusion

Kudos to the people from the M2Msupport website for bringing us this great (and free) tool. It works – so we’re happy to recommend it. And if you enjoyed this article, 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 Easily test and experiment with GSM modules using AT Command Tester appeared first on tronixstuff.

Easily test and experiment with GSM modules using AT Command Tester

Introduction

Working with GSM modules and by extension Arduino GSM shields can either be a lot of fun or bring on a migraine. This is usually due to the quality of module, conditions placed on the end user by the network, reception, power supply and more.

Furthermore we have learned after several years that even after following our detailed and tested tutorials, people are having trouble understanding why their GSM shield isn’t behaving. With this in mind we’re very happy to have learned about a free online tool that can be used to test almost every parameter of a GSM module with ease – AT Command Tester. This software is a Java application that runs in a web browser, and communicates with a GSM module via an available serial port.

Initial Setup

It’s simple, just visit http://m2msupport.net/m2msupport/module-tester/ with any web browser that can run Java. You may need to alter the Java security settings down to medium. Windows users can find this in Control Panel> All Control Panel Items  > Java – for example:

Once the security settings have been changed, just visit the URL, click ‘accept’ and ‘run’ in the next dialogue box that will appear, for example:

And after a moment, the software will appear:

Once you’re able to run the AT Command Tester software, the next step is to physically connect the hardware. If you’re just using a bare GSM module, a USB-serial adaptor can be used for easy connection to the PC. For Arduino GSM shield users, you can use the Arduino as a bridge between the shield and PC, however if your GSM shield uses pins other than D0/D1 for serial data transmission (such as our SIM900 shield) then you’ll need to upload a small sketch to bridge the software and hardware serial ports, for example:

//Serial Relay – Arduino will patch a serial link between the computer and the GPRS Shield
//at 19200 bps 8-N-1 Computer is connected to Hardware UART
//GPRS Shield is connected to the Software UART

#include <SoftwareSerial.h>

SoftwareSerial mySerial(7,8); // change these paramters depending on your Arduino GSM Shield

void setup()
{
  Serial.begin(19200);
  //Serial.println(“Begin”);
  mySerial.begin(19200);

}

void loop()
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Using the software

Once you have the hardware connected and the Arduino running the required sketch, run the software – then click “Find ports” to select the requried COM: port, set the correct data speed and click “Connect”. After a moment the software will interrogate the GSM module and report its findings in the yellow log area:

 As you can see on the left of the image above, there is a plethora of options and functions you can run on the module. By selecting the manufacturer of your GSM module form the list, a more appropriate set of functions for your module is displayed.

When you click a function, the AT command sent to the module and its response is shown in the log window – and thus the magic of this software. You can simply throw any command at the module and await the response, much easier than looking up the commands and fighting with terminal software. You can also send AT commands in batches, experiment with GPRS data, FTP, and the GPS if your module has one.

To give you a quick overview of what is possible, we’ve made this video which captures us running a few commands on a SIM900-based Arduino shield. If possible, view it in 720p.

Conclusion

Kudos to the people from the M2Msupport website for bringing us this great (and free) tool. It works – so we’re happy to recommend it. And if you enjoyed this article, 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.

Tutorial – pcDuino GPIO with Arduino IDE

Introduction

In this tutorial we’ll explain how to use the GPIO pins of the Arduino implementation in the pcDuino v2 and v3. As the v3 is now available you can use it as well, and it’s interchangeable with the v2. Although the pcDuino v2 is Arduino-compatible, there are a few differences that you need to be aware of – in order to make your projects a success and also to avoid any costly mistakes.

This tutorial builds on the knowledge from the initial review, so if pcDuino v2 is new to you please review this article before moving on. In this instalment we’ll run through the following:

  • ADC (analogue to digital)
  • Digital input and outputs
  • PWM (pulse-width modulation)
  • I2C bus
  • SPI bus

Using ADC pins

Just like an Arduino Uno or compatible, the pcDuino v2 has six ADC pins, in the expected locations:

Using the pcDuino v2’s ADC pins is quite straight forward, however you just need to remember a few things about the hardware – that the maximum input voltage on A0 and A1 is 2V – and 3.3V for A2~A5.

Although there is an AREF pin on the board, this function isn’t supported at the time of writing. From the software perspective A0 and A1’s values have a 6-bit resolution and can fall between 0 and 63 (0~2V), otherwise the others have a 12-bit resolution and thus return values between 0 and 4095 (0~3.3V). Using the ADC pins is simple, and demonstrated in the following sketch:

// pcDuino v2 ADC demonstration

#include <core.h> // for pcDuino

int a0, a1, a2, a3, a4, a5;

void setup() 
{
}

void loop() 
{
  // read all the ADCs
  a0 = analogRead(0);
  a1 = analogRead(1);
  a2 = analogRead(2);
  a3 = analogRead(3);
  a4 = analogRead(4);
  a5 = analogRead(5);
  // display ADC values to console
  printf(A0, A1,   A2,   A3,   A4,   A5\n);
  printf(%d  %d  %d  %d  %d  %d\n, a0, a1, a2, a3, a4, a5);
  printf(n);
  delay(1000);
}

… which results with the following in the console:

Digital outputs

The pcDuino v2’s implementation of digital outputs aren’t anything out of the ordinary – except that you are limited to a maximum voltage of 3.3V instead of the usual 5V. Furthermore you can only source 4mA from each pin. However if you have some 5V-only shields that you must use with your pcDuino v2 – there is a Voltage Translation board that can be used to solve the problem:

However using 3.3V for new designs shouldn’t be an issue – new sensors, ICs and so on should be 3.3V-compatible. And with the pcDuino v2 you get an extra four digital I/O pins, located next to the SPI grouping as shown below:

These are simply addressed as D14~D17. Now back for a quick demonstration with the typical LEDs. As the current sourced from each GPIO pin cannot exceed 4mA, you need to use a resistor to keep things under control. Using the LED wizard, by entering a 3.3V supply, 2.1V forward voltage for our LEDs and a 4mA current – the resistor value to use is 330Ω.

If you’re having a lazy attack and use 560Ω, the current will be around 2.5mA with acceptable results. We’ve done just that with the following demonstration sketch:

// pcDuino v2 digital output demonstration

#include <core.h> // for pcDuino

void setup() 
{
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);  
  digitalWrite(4, LOW);  
  digitalWrite(5, LOW);
  digitalWrite(6, LOW);
  digitalWrite(7, LOW);  
}

void loop() 
{
  for (int i = 4; i < 8; i++)
  {
    digitalWrite(i, HIGH);
    delay(250);
    digitalWrite(i, LOW);
  }
}

… and the results in this video.

Digital inputs

When using the digital pins as inputs, just treat them as normal except they have a maximum input voltage of 3.3V for HIGH. Again – just keep thinking “3.3V”.

Using the I2C data bus

The I2C bus (or “two wire interface”) is a common serial data bus used for interfacing all manner of devices with a microcontroller. You can find a background on the I2C bus and Arduino tutorial here. Just like an Arduino Uno R3, the I2C bus pins are both A4 and A5 (for SCL and SDA) and can also be found up near D13, for example.

The limitations for the pcDuino v2’s version of I2C bus are few – the maximum speed is 200 kHz, it only uses 7-bit addresses and you can’t use the pcDuino in slave mode. However there are 2.2kΩ pullup resistors which can save using them with external circuitry.

We demonstrate the I2C bus by writing data to and reading it from a Microchip 24LC256 EEPROM (which is handy in itself as there isn’t any EEPROM function on the pcDuino v2). This is demonstrated with an Arduino Uno in part two of our I2C tutorials.

Connection is very easy – pins 1 to 4 of the EEPROM are connected to GND, pin 5 to SDA, pin 6 to SCL, pin 7 to GND and pin 8 to 3.3V. Finally a 0.1uF capacitor is placed across 3.3V and GND.

The sketch to read and write values to the EEPROM is simple, and apart from the #include <core.h> for the pcDuino all the other functions operate as normal.

// pcDuino I2C demonstration

#include <core.h> // for pcDuino
#include <Wire.h>   for I2C
#define chip1 0x50  device bus address for EEPROM

// always have your values in variables
unsigned int pointer = 69;  // we need this to be unsigned, as you may have an address  32767
byte d=0;  // example variable to handle data going in and out of EERPROMS

void setup()
{
  Wire.begin();  // wake up, I2C!
}

void writeData(int device, unsigned int add, byte data) 
// writes a byte of data 'data' to the chip at I2C address 'device', in memory location 'add'
{
  Wire.beginTransmission(device);
  Wire.write((int)(add  8)); // left-part of pointer address
  Wire.write((int)(add & 0xFF)); // and the right
  Wire.write(data);
  Wire.endTransmission();
  delay(10);
}

byte readData(int device, unsigned int add) 
// reads a byte of data from memory location 'add' in chip at I2C address 'device' 
{
  byte result;  // returned value
  Wire.beginTransmission(device);  // these three lines set the pointer position in the EEPROM
  Wire.write((int)(add  8));  // left-part of pointer address
  Wire.write((int)(add & 0xFF)); // and the right
  Wire.endTransmission();
  Wire.requestFrom(device,1); // now get the byte of data...
  result = Wire.read();
  return result;  // and return it as a result of the function readData
}

void loop()
{
  printf(Writing data...\n);
  for (int a=0; a10; a++)
  {
    writeData(chip1,a,a);
  }
  printf(Reading data...\n);
  for (int a=0; a10; a++)
  {
    d=readData(chip1,a);    
    printf(Pointer %d holds %d.\n,a,d);
  }
}

… which results with the following output in the console:

As you now know, using I2C isn’t hard at all. A lot of beginners shy away from it – or run screaming for the nearest library for their part. You don’t need libraries – spend a little time now learning about I2C and you’re set for life.

Using the SPI data bus

Again we have some SPI tutorials for Arduino, so check them out first if the concept is new to you. Writing to an SPI device with the pcDuino v2 isn’t tricky at all, you have the 3.3V hardware limitation and the SPI pins are in the same location (D10~D13) or in a separate group on the board:

Furthermore the maximum SPI speed is 12 MHz and the pcDuino v2’s  implementation of SPI can only work as a master. However in the sketch there are a few differences to note. To demonstrate this we’ll control a Microchip MCP4162 digital rheostat via SPI to control the brightness of an LED. Here is the circuit:

And now for the sketch. Take note of the fourth line in void setup() –  this is used to set the SPI bus speed to 12 MHz. You can also reduce the speed with other multipliers such as 32, 64 and 128 to slow it down even further. The other point to note is the use of SPI.transfer(). With the pcDuino v2 there are two parameters – the first is the data to send to the SPI device, and the second is either

SPI_CONTINUE

if there is another byte of data following immediately, or

SPI_LAST

if that is the last byte for that immediate transfer. You can see this use of the paramters within the function setValue() in the demonstration sketch below.

// pcDuino SPI demonstration

#include <core.h>  // for pcDuino
#include <SPI.h>
int ss = 10;
int del = 1000;

void setup()
{
  SPI.begin();
  SPI.setDataMode(SPI_MODE3);
  SPI.setBitOrder(MSBFIRST);
  SPI.setClockDivider(SPI_CLOCK_DIV16);
  pinMode(ss, OUTPUT);
  digitalWrite(ss, HIGH);
}

void setValue(int value)
{
  digitalWrite(ss, LOW);
  SPI.transfer(0, SPI_CONTINUE);
  SPI.transfer(value, SPI_LAST);
  digitalWrite(ss, HIGH);
}

void loop()
{
  setValue(255);
  delay(del);
  setValue(223);
  delay(del);
  setValue(191);
  delay(del);
  setValue(159);
  delay(del);
  setValue(127);
  delay(del);
  setValue(95);
  delay(del);
  setValue(63);
  delay(del);
  setValue(31);
  delay(del);
  setValue(0);
  delay(del);
}

When using the SPI bus, relevant data will appear in the console, for example:

And finally the demonstration video to show you it really works – you can see the output voltage from the rheostat and the matching LED brightness.

Receiving data from the SPI bus is equally as simple, however at the time of writing we don’t have an SPI device to demonstrate this, so please refer the SPI part of the pcDuino guide. Finally, you can’t use PWM on D10 or D11 when using the SPI bus in your sketch.

Pulse-width modulation

You can simulate analogue output using PWM with a pcDuino v2 – however there are two types of PWM pins available. The first is found on digital pins D3, D9, D10 and D11 – they are simulated PWM – and have a low range of zero to twenty at 5 Hz. There are two hardware PWM pins – D5 and D6, which  run at 520Hz and have the full range of 0~255 available in analogWrite(). Once again – they output 3.3V. Furthermore, you can’t use pinMode() functions or the SPI bus if using D10 and/or D11 for PWM.

Conclusion

Now you should have an understanding of the features and limitations of using GPIO pins with your pcDuino v2 Arduino sketches. And finally a plug for my own store – tronixlabs.com – offering a growing range and Australia’s best value for supported hobbyist electronics from adafruit, DFRobot, Freetronics, Seeed Studio and much more.

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.

The post Tutorial – pcDuino GPIO with Arduino IDE appeared first on tronixstuff.

Tronixstuff 29 Jan 04:12
adc  arduino  gpio  i2c  input  output  pcduino  pwm  review  spi  tronixlabs  tronixstuff  tutorial  

Kit Review – Altronics/Silicon Chip ISD2590 Digital Message Recorder

Introduction

Every month Australian electronics magazine Silicon Chip publishes a variety of projects, and in February 1994 they published the “90 Second Digital Message Recorder” project. That was a long time ago, however you can still find the kit today at Altronics (and at the time of writing, on sale for AU$26), and thus the subject of our review.

The kit offers a simple method of recording and playing back 90 seconds of audio, captured with an electret microphone. When mounted in a suitable enclosure it will make a neat way of leaving messages or instructions for others at home.

Assembly

The kit arrives in typical Altronics fashion:

… and includes everything required including IC sockets for the ISD2590 and the audio amplifier:

The PCB missed out on silk-screening – which is a pity:

however it is from an original design from twenty years ago. The solder mask is neat and helps prevent against lazy soldering mistakes:

Finally the detailed instructions including component layout and the handy Altronics reference guide are also included. After checking and ordering the resistors, they were installed first along with the links:

 If you have your own kit, there is a small error in the instructions. The resistor between the 2k2 and the 10uF electrolytic at the top of the board is 10k0 not 2k2. Moving on, these followed by the capacitors and other low-profile components:

The rest of the components went in without any fuss, and frankly it’s a very easy kit to assemble:

 The required power supply is 6V, and a power switch and 4 x AA cell holder is included however were omitted for the review.

How it works

Instead of some fancy microcontrollers, the kit uses an ISD2590P single chip voice recording and playback IC:

It’s a neat part that takes care of most of the required functions including microphone preamp, automatic gain control, and an EEPROM to store the analogue voltage levels that make up the voice sample. The ISD2590 samples audio at 5.3 kHz which isn’t CD quality, but enough for its intended purpose.

Apart from some passive components for power filtering, controls and a speaker amplifier there isn’t much else to say. Download the ISD2590 data sheet (pdf), which is incredibly detailed including some example circuits.

Operation

Once you apply power it’s a simple matter of setting the toggle switch on the PCB down for record, or up for playback. You can record in more than one session, and each session is recorded in order until the memory is full. Then the sounds can be played back without any fuss.

The kit is supplied with the generic 0.25W speaker which is perhaps a little weak for the amplifier circuit in the kit, however by turning down the volume a little the sound is adequate. In this video you can see (and hear) a quick recording and playback session.

Conclusion

This kit could be the base for convenient message system – and much more interesting than just scribbling notes for each other. Or you could built it into a toy and have it play various tunes or speech to amuse children. And for the price it’s great value to experiment with an ISD2590 – just use an IC socket. Or just have some fun  – we did.  Full-sized images are available on flickr

And if you enjoyed this article, 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 Kit Review – Altronics/Silicon Chip ISD2590 Digital Message Recorder appeared first on tronixstuff.

Tronixstuff 23 Jan 03:34

Kit Review – Altronics/Silicon Chip ISD2590 Digital Message Recorder

Introduction

Every month Australian electronics magazine Silicon Chip publishes a variety of projects, and in February 1994 they published the “90 Second Digital Message Recorder” project. That was a long time ago, however you can still find the kit today at Altronics (and at the time of writing, on sale for AU$26), and thus the subject of our review.

The kit offers a simple method of recording and playing back 90 seconds of audio, captured with an electret microphone. When mounted in a suitable enclosure it will make a neat way of leaving messages or instructions for others at home.

Assembly

The kit arrives in typical Altronics fashion:

… and includes everything required including IC sockets for the ISD2590 and the audio amplifier:

The PCB missed out on silk-screening – which is a pity:

however it is from an original design from twenty years ago. The solder mask is neat and helps prevent against lazy soldering mistakes:

Finally the detailed instructions including component layout and the handy Altronics reference guide are also included. After checking and ordering the resistors, they were installed first along with the links:

 If you have your own kit, there is a small error in the instructions. The resistor between the 2k2 and the 10uF electrolytic at the top of the board is 10k0 not 2k2. Moving on, these followed by the capacitors and other low-profile components:

The rest of the components went in without any fuss, and frankly it’s a very easy kit to assemble:

 The required power supply is 6V, and a power switch and 4 x AA cell holder is included however were omitted for the review.

How it works

Instead of some fancy microcontrollers, the kit uses an ISD2590P single chip voice recording and playback IC:

It’s a neat part that takes care of most of the required functions including microphone preamp, automatic gain control, and an EEPROM to store the analogue voltage levels that make up the voice sample. The ISD2590 samples audio at 5.3 kHz which isn’t CD quality, but enough for its intended purpose.

Apart from some passive components for power filtering, controls and a speaker amplifier there isn’t much else to say. Download the ISD2590 data sheet (pdf), which is incredibly detailed including some example circuits.

Operation

Once you apply power it’s a simple matter of setting the toggle switch on the PCB down for record, or up for playback. You can record in more than one session, and each session is recorded in order until the memory is full. Then the sounds can be played back without any fuss.

The kit is supplied with the generic 0.25W speaker which is perhaps a little weak for the amplifier circuit in the kit, however by turning down the volume a little the sound is adequate. In this video you can see (and hear) a quick recording and playback session.

Conclusion

This kit could be the base for convenient message system – and much more interesting than just scribbling notes for each other. Or you could built it into a toy and have it play various tunes or speech to amuse children. And for the price it’s great value to experiment with an ISD2590 – just use an IC socket. Or just have some fun  – we did.  Full-sized images are available on flickr

And if you enjoyed this article, 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.
Tronixstuff 23 Jan 03:34

Online data analysis with Arduino and plotly

Introduction

It’s 2014 and the Internet-of-Things is flying along at a rapid rate with all sorts of services and devices that share data and allow control via the Internet. In the spirit of this we look a new service called plotly.

This is a “collaborative data analysis and graphing tool” which allows you to upload your own data to be analysed in many ways, and then graph the results using all sorts of plot types.

With plotly you can run your own mathematical functions over your data, run intense statistical analysis and use or edit one of the many APIs (PythonMATLABRJuliaRESTArduino, or Perl) to increase the level of customisation. Plotly works in conjunction with Google Drive to store your data, however this can be exported and imported without any issues. Futhermore plotly works best in Google Chrome.

For our review we’ll look at using plotly to quickly display and analyse data received from an Internet-connected Arduino – our EtherTen, or you can use almost any Arduino and Ethernet shield. The system isn’t completely documented however by revieiwng our example sketch and some experimenting with the interface plotly is very much usable, even in its current beta format.

Getting started with plotly

You will need to setup a plotly account, and this is simply accomplished from their main site. Some of you may be wondering what plotly costs – at the time of writing plotly is free for unlimited public use (that is – anyone can see your data with the right URL), but requires a subscription for extended private use. You can find the costs at the plans page.

Once you have a plotly account, visit your plotly home page, whose URL is https://plot.ly/~yourusername/# – then click “edit profile”. Another window will appear which amongst other things contains your plotly API key – make a note of this as you will need it and your username for the Arduino sketch.

Next, you’ll need some Arduino or compatible hardware to capture the data to log and analyse. An Arduino with an Ethernet or WiFi connection, and appropriate sensors for your application. We have our EtherTen that takes readings from a temperature/humidity sensor and a light level sensor:

Now you need a new Arduino library, which is available from the plotly API page. Lots of APIs there… Anyhow, click “Arduino” and you will arrive at the github page. Download the entire .zip file, and extract the plotly_ethernet folder into Arduino libraries folder which in most installations can be found at ..\Arduino-1.0.x\libraries. 

Finally we’ll use a demonstration sketch provided by plotly and modify this to our needs, which can be downloaded from github. We’ll go through this sketch and show you what to update – so have a quick look and then at out example sketch at the end of this section.

First, insert any code required to get data from your sensors and store the data in a variable – do this so the values can be used in void loop. Next, update the MAC address and the IP address of your Ethernet-enabled Arduino with the following lines:

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

and change the MAC and IP if necessary. If Arduino and Ethernet is new to you, check out the tutorial. Now look for the following two lines and enter your plotly username and API key:

plotly.username = "yourplotlyusername";
plotly.api_key = "yourplotlyAPIkey";

Next – it’s a good idea to set your time zone, so the time in plots makes sense. Add the following two lines in void setup():

plotly.timestamp = true; 
plotly.timezone = "Australia/Melbourne";

You can find a list of time zones available for use with plotly here. Now you need to determine how many traces and points to use. A trace is one source of data, for example temperature. For now you will have one point, so set these parameters using the following lines:

int nTraces=x; // x = number of traces
int nPoints=1;

For example, we will plot temperature, humidity and light level – so this requires three traces. The next step is to set the filename for the plot, using the following line:

char filename[] = "simple_example";

This will be sent to plotly and your data will be saved under that name. At the point in your sketch where you want to send some data back to plotly, use:

plotly.open_stream(nPoints, nTraces, filename, layout);

… then the following for each trace:

plotly.post(millis(),data);

where data is the variable to send back to plotly. We use millis() as our example is logging data against time.

To put all that together, consider our example sketch with the hardware mentioned earlier:

// Code modified from example provied by plot.ly

#include <SPI.h>
#include <Ethernet.h>
#include "plotly_ethernet.h"
#include "DHT.h"

// DHT Sensor Setup
#define DHTPIN 2               // We have connected the DHT to Digital Pin 2
#define DHTTYPE DHT22          // This is the type of DHT Sensor (Change it to DHT11 if you're using that model)
DHT dht(DHTPIN, DHTTYPE);      // Initialize DHT object
plotly plotly;                 // initialize a plotly object, named plotly

//initialize plotly global variables
char layout[]="{}";
char filename[] = "Office Weather and Light"; // name of the plot that will be saved in your plotly account -- resaving to the same filename will simply extend the existing traces with new data

float h, t, ll;
int lightLevel;

// Ethernet Setup
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // doesn't really matter
byte my_ip[] = { 192, 168, 1, 77 }; // google will tell you: "public ip address"

void startEthernet(){
  Serial.println("Initializing ethernet");
  if(Ethernet.begin(mac) == 0){
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, my_ip);
  }
  Serial.println("Done initializing ethernet");
  delay(1000);
}

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  dht.begin(); // initialize dht sensor reading
  startEthernet();    // initialize ethernet

    // Initialize plotly settings
  plotly.VERBOSE = true; // turn to false to suppress printing over serial
  plotly.DRY_RUN = false; // turn to false when you want to connect to plotly's servers 
  plotly.username = "yourplotlyusername"; // your plotly username -- sign up at https://plot.ly/ssu or feel free to use this public account. password of the account is "password"
  plotly.api_key = "yourplotlyapikey"; // "public_arduino"'s api_key -- char api_key[10]
  plotly.timestamp = true; // tell plotly that you're stamping your data with a millisecond counter and that you want plotly to convert it into a date-formatted graph
  plotly.timezone = "Australia/Melbourne"; // full list of timezones is here:https://github.com/plotly/arduino-api/blob/master/Accepted%20Timezone%20Strings.txt
}

void loop() 
{
  // gather data to plot
  h = dht.readHumidity(); // read humitidy from DHT pin
  t = dht.readTemperature();
  lightLevel = analogRead(A5);
  ll = lightLevel / 100; // reduce the value from the light sensor

  // Open the Stream
  plotly.open_stream(1, 3, filename, layout); // plotlystream(number_of_points, number_of_traces, filename, layout)

  plotly.post(millis(),t); // post temperature to plotly (trace 1)
  delay(150);
  plotly.post(millis(),h); // post humidity to plotly (trace 2)
  delay(150);
  plotly.post(millis(),lightLevel); // post light sensor readout to plotly (trace 3)

  for(int i=0; i<300; i++)
  { // (once every five minutes)
    delay(1000);
  }
}

After wiring up the hardware and uploading the sketch, the data will be sent until the power is removed from the Arduino.

Monitoring sensor data

Now that your hardware is sending the data off to plotly, you can check it out in real time. Log into plotly and visit the data home page – https://plot.ly/plot – for example:

Your data file will be listed – so just click on the file name to be presented with a very basic graph. Over time you will see it develop as the data is received, however you may want to alter the display, headings, labels and so on. Generally you can click on trace labels, titles and so on to change them, the interface is pretty intuitive after a few moments. A quick screencast of this is shown in this video.

To view and analyse the raw data – and create all sorts of custom plots, graphs and other analysis – click the “view data in grid” icon which is the second from the left along the bar:

At which point your data will be displayed in a new tab:

From this point you can experiment to your heart’s content – just don’t forget to save your work. In a short amount of time your data can be presented visually and analysed with ease:

Conclusion

Although plotly is still in beta form, it works well and the developers are responsive to any questions – so there isn’t much more to say but give it a try yourself, doing so won’t cost you anything and you can see how useful plotly is for yourself. And if you enjoyed this article, 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 Online data analysis with Arduino and plotly appeared first on tronixstuff.

Tronixstuff 21 Jan 05:29
analysis  api  arduino  data  ethernet  internet  iot  of  online  plotly  things  tronixstuff  tutorial  

Online data analysis with Arduino and plotly

Introduction

It’s 2014 and the Internet-of-Things is flying along at a rapid rate with all sorts of services and devices that share data and allow control via the Internet. In the spirit of this we look a new service called plotly.

This is a “collaborative data analysis and graphing tool” which allows you to upload your own data to be analysed in many ways, and then graph the results using all sorts of plot types.

With plotly you can run your own mathematical functions over your data, run intense statistical analysis and use or edit one of the many APIs (PythonMATLABRJuliaRESTArduino, or Perl) to increase the level of customisation. Plotly works in conjunction with Google Drive to store your data, however this can be exported and imported without any issues. Futhermore plotly works best in Google Chrome.

For our review we’ll look at using plotly to quickly display and analyse data received from an Internet-connected Arduino – our EtherTen, or you can use almost any Arduino and Ethernet shield. The system isn’t completely documented however by revieiwng our example sketch and some experimenting with the interface plotly is very much usable, even in its current beta format.

Getting started with plotly

You will need to setup a plotly account, and this is simply accomplished from their main site. Some of you may be wondering what plotly costs – at the time of writing plotly is free for unlimited public use (that is – anyone can see your data with the right URL), but requires a subscription for extended private use. You can find the costs at the plans page.

Once you have a plotly account, visit your plotly home page, whose URL is https://plot.ly/~yourusername/# – then click “edit profile”. Another window will appear which amongst other things contains your plotly API key – make a note of this as you will need it and your username for the Arduino sketch.

Next, you’ll need some Arduino or compatible hardware to capture the data to log and analyse. An Arduino with an Ethernet or WiFi connection, and appropriate sensors for your application. We have our EtherTen that takes readings from a temperature/humidity sensor and a light level sensor:

Now you need a new Arduino library, which is available from the plotly API page. Lots of APIs there… Anyhow, click “Arduino” and you will arrive at the github page. Download the entire .zip file, and extract the plotly_ethernet folder into Arduino libraries folder which in most installations can be found at ..Arduino-1.0.xlibraries. 

Finally we’ll use a demonstration sketch provided by plotly and modify this to our needs, which can be downloaded from github. We’ll go through this sketch and show you what to update – so have a quick look and then at out example sketch at the end of this section.

First, insert any code required to get data from your sensors and store the data in a variable – do this so the values can be used in void loop. Next, update the MAC address and the IP address of your Ethernet-enabled Arduino with the following lines:

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

and change the MAC and IP if necessary. If Arduino and Ethernet is new to you, check out the tutorial. Now look for the following two lines and enter your plotly username and API key:

plotly.username = "yourplotlyusername";
plotly.api_key = "yourplotlyAPIkey";

Next – it’s a good idea to set your time zone, so the time in plots makes sense. Add the following two lines in void setup():

plotly.timestamp = true; 
plotly.timezone = "Australia/Melbourne";

You can find a list of time zones available for use with plotly here. Now you need to determine how many traces and points to use. A trace is one source of data, for example temperature. For now you will have one point, so set these parameters using the following lines:

int nTraces=x; // x = number of traces
int nPoints=1;

For example, we will plot temperature, humidity and light level – so this requires three traces. The next step is to set the filename for the plot, using the following line:

char filename[] = "simple_example";

This will be sent to plotly and your data will be saved under that name. At the point in your sketch where you want to send some data back to plotly, use:

plotly.open_stream(nPoints, nTraces, filename, layout);

… then the following for each trace:

plotly.post(millis(),data);

where data is the variable to send back to plotly. We use millis() as our example is logging data against time.

To put all that together, consider our example sketch with the hardware mentioned earlier:

// Code modified from example provied by plot.ly

#include <SPI.h>
#include <Ethernet.h>
#include "plotly_ethernet.h"
#include "DHT.h"

// DHT Sensor Setup
#define DHTPIN 2               // We have connected the DHT to Digital Pin 2
#define DHTTYPE DHT22          // This is the type of DHT Sensor (Change it to DHT11 if you're using that model)
DHT dht(DHTPIN, DHTTYPE);      // Initialize DHT object
plotly plotly;                 // initialize a plotly object, named plotly

//initialize plotly global variables
char layout[]="{}";
char filename[] = "Office Weather and Light"; // name of the plot that will be saved in your plotly account -- resaving to the same filename will simply extend the existing traces with new data

float h, t, ll;
int lightLevel;

// Ethernet Setup
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // doesn't really matter
byte my_ip[] = { 192, 168, 1, 77 }; // google will tell you: "public ip address"

void startEthernet(){
  Serial.println("Initializing ethernet");
  if(Ethernet.begin(mac) == 0){
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, my_ip);
  }
  Serial.println("Done initializing ethernet");
  delay(1000);
}

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  dht.begin(); // initialize dht sensor reading
  startEthernet();    // initialize ethernet

    // Initialize plotly settings
  plotly.VERBOSE = true; // turn to false to suppress printing over serial
  plotly.DRY_RUN = false; // turn to false when you want to connect to plotly's servers 
  plotly.username = "yourplotlyusername"; // your plotly username -- sign up at https://plot.ly/ssu or feel free to use this public account. password of the account is "password"
  plotly.api_key = "yourplotlyapikey"; // "public_arduino"'s api_key -- char api_key[10]
  plotly.timestamp = true; // tell plotly that you're stamping your data with a millisecond counter and that you want plotly to convert it into a date-formatted graph
  plotly.timezone = "Australia/Melbourne"; // full list of timezones is here:https://github.com/plotly/arduino-api/blob/master/Accepted%20Timezone%20Strings.txt
}

void loop() 
{
  // gather data to plot
  h = dht.readHumidity(); // read humitidy from DHT pin
  t = dht.readTemperature();
  lightLevel = analogRead(A5);
  ll = lightLevel / 100; // reduce the value from the light sensor

  // Open the Stream
  plotly.open_stream(1, 3, filename, layout); // plotlystream(number_of_points, number_of_traces, filename, layout)

  plotly.post(millis(),t); // post temperature to plotly (trace 1)
  delay(150);
  plotly.post(millis(),h); // post humidity to plotly (trace 2)
  delay(150);
  plotly.post(millis(),lightLevel); // post light sensor readout to plotly (trace 3)

  for(int i=0; i<300; i++)
  { // (once every five minutes)
    delay(1000);
  }
}

After wiring up the hardware and uploading the sketch, the data will be sent until the power is removed from the Arduino.

Monitoring sensor data

Now that your hardware is sending the data off to plotly, you can check it out in real time. Log into plotly and visit the data home page – https://plot.ly/plot – for example:

Your data file will be listed – so just click on the file name to be presented with a very basic graph. Over time you will see it develop as the data is received, however you may want to alter the display, headings, labels and so on. Generally you can click on trace labels, titles and so on to change them, the interface is pretty intuitive after a few moments. A quick screencast of this is shown in this video.

To view and analyse the raw data – and create all sorts of custom plots, graphs and other analysis – click the “view data in grid” icon which is the second from the left along the bar:

At which point your data will be displayed in a new tab:

From this point you can experiment to your heart’s content – just don’t forget to save your work. In a short amount of time your data can be presented visually and analysed with ease:

Conclusion

Although plotly is still in beta form, it works well and the developers are responsive to any questions – so there isn’t much more to say but give it a try yourself, doing so won’t cost you anything and you can see how useful plotly is for yourself. And if you enjoyed this article, 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.
Tronixstuff 21 Jan 05:29
analysis  api  arduino  data  ethernet  internet  iot  of  online  plotly  things  tronixstuff  tutorial  

Tutorial – Arduino Mega and SM5100B GSM Cellular

Connect your Arduino Mega or compatible to the cellular network with the SM5100 GSM module shield from Tronixlabs. If you have an Arduino Uno or compatible, visit this page. If you are looking for tutorials using the SIMCOM SIM900 GSM module, click here.

This is chapter twenty-seven of a series originally titled “Getting Started/Moving Forward with Arduino!” by John Boxall – A tutorial on the Arduino universe. The first chapter is here, the complete series is detailed here.

Updated 18/01/2014

Introduction

The purpose of this tutorial is to have your Arduino Mega to communicate over a GSM mobile telephone network using a shield based on the SM5100B module from Tronixlabs. We’ve written this as the shield from Sparkfun used in the previous tutorial was somewhat fiddly for use with an Arduino Mega – so this shield is a more convenient alternative:

Our goal is to illustrate various methods of interaction between an Arduino Mega and the GSM cellular network using the shield shown above, with which you can then use your existing knowledge to build upon those methods. Doing so isn’t easy – but it isn’t that difficult.

Stop! Please read first:

  • It is assumed that you have a solid understanding of how to program your Arduino. If not, start from chapter zero
  • Sending SMS messages and making phone calls cost real money, so it would be very wise to use a prepaid cellular account or one  that allows a fair amount of calls/SMS
  • The GSM shield only works with “2G” GSM mobile networks operating on the 850, 900 and PCS1800 MHz frequencies. If in doubt, ask your carrier first
  • Australians – you can use any carrier’s SIM card
  • Canadians – this doesn’t work with Sasktel
  • North Americans – check with your cellular carrier first if you can use third-party hardware (i.e. the shield)
  • I cannot offer design advice for your project nor technical support for this article.
  • If you are working on a college/university project and need specific help – talk to your tutors or academic staff. They get paid to help you.
  • Please don’t make an auto-dialler…

 

Getting started

Before moving forward there us one vital point you need to understand – the power supply. The GSM shield can often require up to 2A of current in short bursts – especially when turned on, reset, or initiating a call.

However your Arduino board can only supply just under 1A. It is highly recommended that you use an external regulated power supply of between 9 and 12 VDC capable of delivering 2A of current – from an AC adaptor, large battery with power regulator, etc. Otherwise there is a very strong probability of damaging your shield and Arduino. When connecting this supply use the Vin and GND pins. Do not under any circumstances power the Arduino and shield from just the USB power.

Next – use an antenna! The wire hanging from the shield is not an antenna. YOU NEED THE ANTENNA! For example:

Furthermore, care needs to be taken with your GSM shield with regards to the aerial lead-module connection, it is very fragile:

Pressing the hardware reset button on the shield doesn’t reset the GSM module – you need to remove the power for a second. And finally, download this document (.pdf). It contains all the AT and ERROR codes that will turn up when you least expect it. Please review it if you are presented with a code you are unsure about.

Wow – all those rules and warnings?

The sections above may sound a little authoritarian, however I want your project to be a success. With the previous iterations of the tutorial people just didn’t follow the instructions – so we hope you do.

Initial check – does it work?

This may sound like a silly question, but considering the cost of the shield and the variables involved, it is a good idea to check if your setup is functioning correctly before moving on. From a hardware perspective for this article, you will need your Arduino board, the GSM shield with activated SIM card and an aerial, and the power supply connected.

Next you need to set the serial line jumpers. These determine which of the four hardware serial ports we use to communicate with the GSM module. Place a jumper over each of the RX1 and TX1 pairs as shown in the following image. By doing this the communication with the GSM module is via Serial1 in our sketches, leaving Serial for normal communications such as the serial monitor.

Make sure your SIM card is set to not require a PIN when the phone is turned on. You can check and turn this requirement off with your cellphone. 

For our initial test, upload the following sketch:

// Example 27.1

char incoming_char=0;      // Will hold the incoming character from the Serial Port.
void setup()
{
  //Initialize serial ports for communication.
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial.println("Starting SM5100B Communication...");
}
void loop()
{
  //If a character comes in from the cellular module...
  if(Serial1.available() >0)
  {
    incoming_char=Serial1.read();    // Get the character from the cellular serial port.
    Serial.print(incoming_char);  // Print the incoming character to the terminal.
  }
  //If a character is coming from the terminal to the Arduino...
  if(Serial.available() >0)
  {
    incoming_char=Serial.read();  // Get the character coming from the terminal
    Serial1.print(incoming_char);    // Send the character to the cellular module.
  }
}

Then connect the GSM shield, aerial, insert the SIM card and apply power. Open the serial monitor box in the Arduino IDE and you should be presented with the following:

It will take around fifteen to thirty seconds for the text above to appear in full. What you are being presented with is a log of the GSM module’s actions. But what do they all mean?

  • +SIND: 1 means the SIM card has been inserted;
  • the +SIND: 10 line shows the status of the in-module phone book. Nothing to worry about there for us at the moment;
  • +SIND: 11 means the module has registered with the cellular network
  • +SIND: 3 means the module is partially ready to communicate
  • and +SIND: 4 means the module is registered on the network, and ready to communicate

All the SIND data and other codes the module will give you are listed in the AT command guide we suggested you download. Please use it – any comments such as “What’s +SIND:5?” will be deleted.

From this point on, we will need to use a different terminal program, as the Arduino IDE’s serial monitor box isn’t made for full two-way communications. You will need a terminal program that can offer full two-way com port/serial communication. For those running MS Windows, an excellent option is available here.

It’s free, however consider donating for the use of it. For other operating systems, people say this works well. So now let’s try it out with the terminal software. Close your Arduino IDE serial monitor box if still open, then run your terminal, set it to look at the same serial port as the Arduino IDE was. Ensure the settings are 9600, 8, N, 1. Then reset your Arduino and the following should appear:

The next step is to tell the GSM module which network frequency(ies) to use. View page 127 of the AT command document. There is a range of frequency choices that our module can use. If you don’t know which one to use, contact the telephone company that your SIM card came from. Australia – use option 4. Find your option, then enter:

AT+SBAND=x

(where X is the value matching your required frequency) into the terminal software and click SEND. Then press reset on the Arduino and watch the terminal display. You should hopefully be presented with the same text as above, ending with +SIND: 4. If your module returns +SIND: 4, we’re ready to move forward.

If your terminal returned a +SIND: 8 instead of 4, double-check your hardware, power supply, antenna, and the frequency band chosen. If all that checks out call your network provider to see if they’re rejecting the GSM module on their network.

Our next test is to call our shield. So, pick up a phone and call it. Your shield will return data to the terminal window, for example:

As you can see, the module returns what is happening. I let the originating phone “ring” three times, and the module received the caller ID data (sorry, blacked it out). Some telephone subscribers’ accounts don’t send caller ID data, so if you don’t see your number, no problem. “NO CARRIER” occurred when I ended the call. +SIND: 6,1 means the call ended and the SIM is ready.

Have your Arduino “call you”

The document (.pdf) you downloaded earlier contains a list of AT commands – consider this a guide to the language with which we instruct the GSM module to do things. Let’s try out some more commands before completing our initial test. The first one is:

ATDxxxxxx

which dials a telephone number xxxxxx. For example, to call (212)-8675309 use:

ATD2128675309

The next one is:

ATH

which “hangs up” or ends the call. So, let’s reach out and touch someone. In the terminal software, enter your ATDxxxxxxxx command, then hit send. Let your phone ring. Then enter ATH to end the call. If you are experimenting and want to hang up in a hurry, you can also hit reset on the Arduino and it will end the call as well as resetting the system.

So by now you should realise the GSM module is controlled by these AT commands. To use an AT command in a sketch, we use the function:

Serial1.println()

Remember that we used Serial1 as the jumpers on the shield board are set to connect the GSM module to the Serial1 hardware serial port. For example, to dial a phone number, we would use:

Serial1.println("ATD2128675309");

To demonstrate this in a sketch, consider the following simple sketch which dials a telephone number, waits, then hangs up. Replace xxxxxxxx with the number you wish to call:

// Example 27.2

void setup()
{ 
  Serial.begin(9600);
  Serial1.begin(9600);
  delay(10);
  Serial.println("starting delay");
  delay(30000); // give the GSM module time to initialise, locate network etc.
  // this delay time varies. Use example 27.1 sketch to measure the amount
  // of time from board reset to SIND: 4, then add five seconds just in case
}

void loop()
{
  Serial.println("dialling");
  Serial1.println("ATDxxxxxxxxxx"); // dial the phone number xxxxxxxxx
  // change xxxxxxxxxx to your desired phone number (with area code)
  delay(20000); // wait 20 seconds.
  Serial.println("hang up");
  Serial1.println("ATH"); // end call
  do // remove this loop at your peril
  { 
    delay(1); 
  }
  while (1>0);
}

The sketch in example 27.2 assumes that all is well with regards to the GSM module, that is the SIM card is ok, there is reception, etc. The long delay function in void setup() is used to allow time for the module to wake up and get connected to the network. Later on we will read the messages from the GSM module to allow our sketches to deal with errors and so on. However, you can see how we can simply dial a telephone. And here’s a quick video for the non-believers.

Send an SMS from your Arduino

Another popular function is the SMS or short message service, or text messaging. Before moving forward, download and install Meir Michanie’s SerialGSM Arduino library from here. Some of you might be thinking “why are we using a software serial in the following sketch?”. Short answer – it’s just easier.

Sending a text message is incredibly simple – consider the following sketch:

// Example 27.3

#include <SerialGSM.h>
#include <SoftwareSerial.h>
SerialGSM cell(19,18);

void setup()
{ 
  delay(30000); // wait for GSM module
  cell.begin(9600);
}

void sendSMS()
{
  cell.Verbose(true); // used for debugging
  cell.Boot(); 
  cell.FwdSMS2Serial();
  cell.Rcpt("+xxxxxxxxx"); // replace xxxxxxxxx with the recipient's cellular number
  cell.Message("Contents of your text message");
  cell.SendSMS();
}
void loop()
{
  sendSMS();
  do // remove this loop at your peril
  { 
    delay(1); 
  }
  while (1>0);
}

It’s super-simple – just change the phone number to send the text message, and of course the message you want to send. The phone numbers must be in international format, e.g. Australia 0418 123456 is +61418123456 or USA (609) 8675309 is +16098675309. And the results:

Reach out and control something

Now let’s discuss how to make something happen by a simple telephone call. And the best thing is that we don’t need the the GSM module to answer the telephone call (thereby saving money) – just let the module ring a few times. How is this possible? Very easily. Recall Example 27.1 above – we monitored the activity of the GSM module by using our terminal software.

In this case what we need to do is have our Arduino examine the text coming in from the serial output of the GSM module, and look for a particular string of characters.

When we telephone the GSM module from another number, the module returns the text as shown in the image below:

We want to look for the text “RING”, as (obviously) this means that the GSM shield has recognised the ring signal from the exchange. Therefore need our Arduino to count the number of rings for the particular telephone call being made to the module. (Memories – Many years ago we would use public telephones to send messages to each other.

For example, after arriving at a foreign destination we would call home and let the phone ring five times then hang up – which meant we had arrived safely). Finally, once the GSM shield has received a set number of rings, we want the Arduino to do something.

From a software perspective, we need to examine each character as it is returned from the GSM shield. Once an “R” is received, we examine the next character. If it is an “I”, we examine the next character. If it is an “N”, we examine the next character. If it is a “G”, we know an inbound call is being attempted, and one ring has occurred.

We can set the number of rings to wait until out desired function is called. In the following example, when the shield is called, it will call the function doSomething() after three rings.

The function doSomething() controls two LEDs, two red,  two green. Every time the GSM module is called for 3 rings, the Arduino alternately turns on or off the LEDs. Using the following sketch as an example, you now have the ability to turn basically anything on or off, or call your own particular function:

// Example 27.4

char inchar; // Will hold the incoming character from the Serial Port.
int numring=0;
int comring=3; 
int onoff=0; // 0 = off, 1 = on

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

void setup()
{
  // prepare the digital output pins
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);

  //Initialize GSM module serial port for communication.
  Serial1.begin(9600);
  delay(30000); // give time for GSM module to register on network etc.
}

void doSomething()
{
  if (onoff==0)
  {
    onoff=1;
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);    
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);    

  } 
  else
    if (onoff==1)
    {
      onoff=0;
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);    
      digitalWrite(led3, HIGH);
      digitalWrite(led4, HIGH);  
    }
}

void loop() 
{
  //If a character comes in from the cellular module...
  if(Serial1.available() >0)
  {
    inchar=Serial1.read(); 
    if (inchar=='R')
    {
      delay(10);
      inchar=Serial1.read(); 
      if (inchar=='I')
      {
        delay(10);
        inchar=Serial1.read();
        if (inchar=='N')
        {
          delay(10);
          inchar=Serial1.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'
            numring++;
            if (numring==comring)
            {
              numring=0; // reset ring counter
              doSomething();
            }
          }
        }
      }
    }
  }
}

And now for a quick video demonstration. Each time a call to the shield is made, the pairs of LEDs alternate between on and off. Although this may seem like an over-simplified example, with your existing Arduino knowledge you now have the ability to run any function by calling your GSM shield.

 

Control Digital I/O via SMS

Now although turning one thing on or off is convenient, how can we send more control information to our GSM module? For example, control four or more digital outputs at once? These sorts of commands can be achieved by the reception and analysis of text messages.

Doing so is similar to the method we used in example 27.4. Once again, we will analyse the characters being sent from the GSM module via its serial out. However, there are two AT commands we need to send to the GSM module before we can receive SMSs, and one afterwards. The first one you already know:

AT+CMGF=1

Which sets the SMS mode to text. The second command is:

AT+CNMI=3,3,0,0

This command tells the GSM module to immediately send any new SMS data to the serial out. An example of this is shown in the terminal capture below:

Two text messages have been received since the module was turned on. You can see how the data is laid out. The blacked out number is the sender of the SMS. The number +61418706700 is the number for my carrier’s SMSC (short message service centre). Then we have the date and time. The next line is the contents of the text message – what we need to examine in our sketch.

The second text message in the example above is how we will structure our control SMS. Our sketch will wait for a # to come from the serial line, then consider the values after a, b, c and d – 0 for off, 1 for on. Finally, we need to send one more command to the GSM module after we have interpreted our SMS:

AT+CMGD=1,4

This deletes all the text messages from the SIM card. As there is a finite amount of storage space on the SIM, it is prudent to delete the incoming message after we have followed the instructions within. But now for our example. We will control four digital outputs, D9~12. For the sake of the exercise we are controlling an LED on each digital output, however you could do anything you like.

Although the sketch may seem long and complex, it is not – just follow it through and you will see what is happening:

// Example 27.5

char inchar; // Will hold the incoming character from the Serial Port.

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

void setup()
{
  // prepare the digital output pins
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);

  //Initialize GSM module serial port for communication.
  Serial1.begin(9600);
  delay(30000); // give time for GSM module to register on network etc.
  Serial1.println("AT+CMGF=1"); // set SMS mode to text
  delay(200);
  Serial1.println("AT+CNMI=3,3,0,0"); // set module to send SMS data to serial out upon receipt 
  delay(200);
}

void loop() 
{
  //If a character comes in from the cellular module...
  if(Serial1.available() >0)
  {
    inchar=Serial1.read(); 
    if (inchar=='#')
    {
      delay(10);
      inchar=Serial1.read(); 
      if (inchar=='a')
      {
        delay(10);
        inchar=Serial1.read();
        if (inchar=='0')
        {
          digitalWrite(led1, LOW);
        } 
        else if (inchar=='1')
        {
          digitalWrite(led1, HIGH);
        }
        delay(10);
        inchar=Serial1.read(); 
        if (inchar=='b')
        {
          inchar=Serial1.read();
          if (inchar=='0')
          {
            digitalWrite(led2, LOW);
          } 
          else if (inchar=='1')
          {
            digitalWrite(led2, HIGH);
          }
          delay(10);
          inchar=Serial1.read(); 
          if (inchar=='c')
          {
            inchar=Serial1.read();
            if (inchar=='0')
            {
              digitalWrite(led3, LOW);
            } 
            else if (inchar=='1')
            {
              digitalWrite(led3, HIGH);
            }
            delay(10);
            inchar=Serial1.read(); 
            if (inchar=='d')
            {
              delay(10);
              inchar=Serial1.read();
              if (inchar=='0')
              {
                digitalWrite(led4, LOW);
              } 
              else if (inchar=='1')
              {
                digitalWrite(led4, HIGH);
              }
              delay(10);
            }
          }
          Serial1.println("AT+CMGD=1,4"); // delete all SMS
        }
      }
    }
  }
}

And a demonstration video showing this in action.

Conclusion

So there you have it – controlling your Arduino Mega’s digital outputs via a normal telephone or SMS. Now it is up to you and your imagination to find something to control, sensor data to return, or get up to other shenanigans. This shield and antenna is available from Tronixlabs. If you enjoyed this article, you may find this of interest – controlling AC power outlets via SMS. And if you enjoyed this article, 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 Mega and SM5100B GSM Cellular appeared first on tronixstuff.

Tronixstuff 18 Jan 07:04