Monday, 15 June 2015

List of Contents

15-June-2015 - Update!
Induino R3 is now replaced by Induino R4. Induino R4 is the same as the R3 excepting the following 2 changes
1) Removal of the General Purpose Prototyping Area
2) Addition of a 4 Pin I2C Header in that Area to Allow Direct Plugging in of 0.96" I2C OLED Displays.

This is the User Guide for the Induino R3 / R4  from Simple Labs. The Induino R3 is the latest in the Induino Series of Low Cost Arduino clone boards from Simple Labs. The user guide focuses on making use of the Induino R3 board effectively & Interfacing different components which are part of various Induino R3 kits. This is a constant work in progress so if something looks incomplete, it means we are working on it and will update it soon. If you are in a hurry, drop us an email. Enjoy!



Induino R3 Blog Overview - List of Contents (For Easy Navigation!!!)
  1. What is Arduino? What is Induino? Lets get Some Clarity
  2. Induino R4 replaces the Induino R3
  3. Induino R3 / R4 - An Overview
  4. Simple Labs' Induino R3 / Induino R4 and Arduino Uno Comparison
  5. Driver Installation
  6. The Basics of Working with Induino R3 / Arduino
  7. Digital Outputs - What, Where & How? - Working with the 3 on-board LEDs
  8. Digital Inputs - What, Where & How? - Working with the 3 on-board Push Buttons
  9. Serial Communication - What, Where & How?
  10. Analog Outputs - What, Where & How? - Working with the RGB LED
  11. Analog Inputs - What, Where & How? - Working with the on-board LDR
  12. Sensor Interface & Interfacing External Sensors - Variable Resistors, LM35 & HC-SR04
  13. Interfacing a TV Remote with the on-board TSOP Remote Control Receiver
  14. Generating Remote Control Signals using the on-board IR LED
  15. Servo Interfacing -  Working with the on-board Servo Interface
  16. LCD Interfacing - Working with the Simple Labs LCD Shield
  17. I2C Communication - What, Where & How? - Interfacing with the Simple Labs RTC Module
  18. I2C Communication - Interfacing Sensors -  MPU6050, BMP085 & HMC5883L 
  19. Interfacing with the Real World - Working with the Simple Labs Relay Control Board
  20. Interrupts - What, Where & How? - Working with the Simple Labs DTMF Control Board
  21. Interfacing Serial Devices - Part 1 - Working with the BTBee PRO / Xbee
  22. Interfacing Serial Devices - Part 2 - Working with a Serial RFID Reader
  23. Interfacing Serial Devices - Part 3 - Working with a Serial GSM Modem
  24. SPI Communication - What, Where & How? - Working with the W5100 Ethernet Shield
  25. Interfacing Sensors - Microphone Sound Detection Sensor
  26. LCD Interfacing - Creating Custom Characters and a Bar Graph
  27. PORT Manipulation & 7 Segment LED Interfacing - Working with the Simple Labs Seven Segment cum DTMF Shield
  28. Interfacing the 0.96" I2C OLED Display

15-June-2015 - Induino R4 replacing the Induino R3

Induino R4 is the latest revision to our Induino series of Boards. The Induino R4 will replace the Induino R3.

Induino R4 is the same as the R3 excepting the following 2 changes

1) Removal of the General Purpose Prototyping Area

2) Addition of a 4 Pin I2C Header in that Area to Allow Direct Plugging in of 0.96" I2C OLED Displays.

All existing code / tutorials / examples for the Induino R3 will work on the Induino R4 as it is. The OLED interface is the only addition. Soon we will publish an OLED version of all example codes using LCD currently.

Here are pictures of the Induino R4. The oled display is just for illustrative purposes and does not come with the Board. However the display is included as part of various kits for the Induino.





Friday, 12 June 2015

Interfacing the 0.96" I2C OLED Display

I2C OLED Display

The 0.96" I2C OLED Display is a simple display with plenty of options for displaying text and graphics in monochrome. The display hooks up to the I2C bus and can be accessed using the Address 0x3C. The display is a 128 x 64 Display where it has 128 pixels for every row with a total of 64 rows.

Hooking it up

All it needs to work is 4 lines of connection (SDA, SCL, Vcc, Gnd). You don't need any pullups. Should you have the latest version of the Induino, The Induino R4, you don't even have to use physical wires! the board comes with a Direct Plug in Header for the 0.96" I2C OLED display. Just plug it in and you are good to go!

For Induino R3 or Arduino

For Induino R3 or Arduino

For Induino R3 or Arduino

Plug in Directly on the Induino R4
One you are done with the connections, download this excellent library from DigiSpark. If You are wondering how to install this library? check this -> http://arduino.cc/en/Guide/Libraries

The Digispark OLED library offers a number of functions that we can use. The library creates a default object called oled and functions can be called through this object.

The Functions
  • oled.begin() - > This function intialises communication with the oled and does the basic oled setup required.
  • oled.fill(fill color) -> This function fills the display with the chosen fill color. In our case since we are working with a monochrome oled. its only possible to fill it with black or blue(white). use oled.fill(0xFF) to fill the screen with white color and oled.fill(0x00) to fill the screen with black color.
  • oled.clear() -> This function clears the display.
  • oled.setCursor(x,y) -> This function sets the cursor in the given x,y position. X is the coloumn value in pixels and Y is the row value. X can have any value starting 0 - 127. Y can have any value from 0-7. Take font sizes into consideration when deiciding on X & Y values
  • oled.setFont(font size) -> This function sets the font size to be used. There are 2 font sizes available. oled.setFont(FONT6X8) sets the font to be used as a smaller font with each font taking up 6 x 8 pixels. So you can have a total of 168 characters.  oled.setFont(FONT8X16) sets the font to be used as a larger font with each font taking up 8 x 16 pixels. So you can have a total of 64 characters. 
  • oled.print(text/value) -> This function prints the text / value given. oled.print("hello world")
  • oled.println(text/value) -> This functions prints the text / value given and then positions the cursor at the beginning of the next line
  • oled.off()-> Turns the display off
  • oled.on() -> Turns the display on if it has been turned off
  • oled.invert(parameter) -> Inverts the display when the parameter passed is 1 and restores the display when the parameter passed is 0. oled.invert(1) or oled.invert(0)

The Code

Here's a simple code to display hello world and explore the various functions



/*  Induino R3 User Guide - Program 22.0 - 0.96"I2C OLED Usage Example using the Induino R3 */

/* This program explore various functions of the DigisparkOLED library using the Induino R4*/

#include <DigisparkOLED.h> // Header for the OLED library
#include <Wire.h>

void setup()
{
  // Initialise Communication with the OLED
  oled.begin();

  // First lets print the line numbers
  // Lets Set the Font to small size. This font takes up one row per character (for the height!)
  oled.setFont(FONT6X8);
  oled.setCursor(0, 0);
  //Print the first number using a println so that the cursor is automatically positioned at the start of the next line. Then repeat this till the last number
  oled.println("1");
  oled.println("2");
  oled.println("3");
  oled.println("4");
  oled.println("5");
  oled.println("6");
  oled.println("7");
  oled.println("8");

  // Set the Font to large size. This font takes up two rows per character (for the height!) as agains the small font that takes up one row per character
  oled.setFont(FONT8X16);

  // Position the Cursor to print Hello in the middle of the Screen. Given the font size and that we have 8 rows in total, printing on the 4th row will take up the 4th and 5th rows
  // leaving the first and last 3 rows empty
  // given that the 5 characters hello take up 40 pixels, we can print from the 45th pixel to keep it at the center
  oled.setCursor(45, 3);
  oled.print("HELLO");
  delay(5000);
  // Lets turn off the display
  oled.off();
  delay(5000);

  // Lets turn on the display
  oled.on();
  delay(5000);

  // Lets invert display
  oled.invert(1);
  delay(5000);

  // Lets restore the inverted display
  oled.invert(0);
  delay(5000);

  // lets wait for some time
  delay(10000);

  // finally clear the screen
  oled.clear();


}

void loop()
{


}


Thats It For This Part! Enjoy... and feel free to drop us an email with questions you might have -> info@simplelabs.co.in

Visit www.simplelabs.co.in for more interesting products

Back to List of Contents

Tuesday, 3 June 2014

PORT Manipulation & 7 Segment LED Interfacing - Working with the Simple Labs Seven Segment cum DTMF Shield

What is Port Manipulation?

So far we have been working on controlling individual pins on the Induino R3. Now we will explore as to how we can use groups of pins together. Pins of a microcontroller are normally grouped together as PORTS. Each PORT can have 6 - 8 Pins (Though 8 Pins is pretty much the standard!). We can control each of these Ports using associated registers and this process of controlling a whole port instead of individual pins is called Port Manipulation.  

Lets take a look at how Pins are mapped on the Atmega 328 Microcontroller on the Induino R3 / Arduino. Take a look at the image here


From the image, we can see that digital pins 0 to 7 are numbered as PD0 to PD7, This denotes they are Part of PORT D. So PORT D consists of pins 0 - 7. Here is how the pins are grouped to ports
  • PORT B => digital pins 8 to 13
  • PORT C => analog input pins A0 - A5
  • PORT D => digital pins 0 to 7

Every PORT has 3 Registers Associated with it
  1. DDR => Data Direction Register - This Register Stores Information as to if a pin is Input or Output
  2. PORT => This Register is a Output Register and all Output states of a pin are written to this register.
  3. PIN => This is a Input Register and Read Only. This register contains the current state of pin configured for Input.

The following are the registers associated with the 3 PORTS of the ATmega328.
  • PORT B => DDRB, PORTB, PINB
  • PORT C => DDRC, PORTC, PINC
  • PORT D => DDRD, PORTD, PIND
Note: Incase of a Board like the Arduino Mega 2560 there are more Ports however the naming convention for the registers will be the same as the above. 

Now Lets look at how these Registers work. Lets take PORT D. All the 3 registers associated with 

Digital Pin 7Digital Pin 6Digital Pin 5Digital Pin 4Digital Pin 3Digital Pin 2Digital Pin 1Digital Pin 0
DDRD1 (OUTPUT) 0  (INPUT)  0  (INPUT)  0  (INPUT)  0  (INPUT)  0  (INPUT)  0  (INPUT)  0  (INPUT) 
PORTD1 (HIGH)1 (Internal Pull up Enabled)0 (Default)0 (Default)0 (Default)0 (Default)0 (Default)0 (Default)
PIND1 (HIGH)1 (HIGH)0 (LOW)0 (LOW)0 (LOW)0 (LOW)0 (LOW)0 (LOW)

In the table above, in the Register DDRD is a 8 bit register with the least significant bit representing pin 0 and the most significant bit representing pin 7. Now in this register the 7th pin is configured as OUTPUT and the remaining pins are configured as INPUTs. When you use the pinMode function, this is the register that gets modified based on the pin number you specify.

The PORTD register has the 7th pin set as a HIGH. This is the register that gets modified when you use the digitalWrite function. Note, The 6th Pin is a Input pin and setting this as HIGH enables the Internal Pullup resistor. The remaining pins are in their default state - LOW.

The PIND register has the value pertaining to the current state of the PIN. In this case it would have HIGH for the 6th & 7th pins,  as they've both been set to HIGH in the PORTD register. However if there is a button connected to PIN 6 (which is configured as INPUT), the value of the 6th pin would vary everytime the button is pressed.

Port Manipulation Example

Lets try a blink program example that uses Port Manipulation. Lets try to Blink all the 3 LEDs on pins 11, 12 & 13 at the same time.


/*  Induino R3 User Guide - Program 21.0 - Port Manipulation Example using the Induino R3 */

/* This program Controls the LEDs 11, 12 & 13 on the Induino R3 using PORT Manipulation*/

void setup()
{
  // Set the 3 Most significant bits corresponding to Pins 11, 12 & 13 as Output in the Data Direction Register
  // You can use binary data directly by preceeding with B
  DDRB = B111000; // This is the same as saying DDRB = 56;
  // Try commenting the above line and uncommenting the below line
  //DDRB = 56;
  // Initialise Serial Communication to see Register Values
  Serial.begin(9600);
}

void loop()
{
  // Set the 3 Most significant bits corresponding to Pins 11, 12 & 13 as HIGH in the PORT Register
  PORTB = B111000;
  // Store the current value of the PIN Register in the variable VAL just to see how the PIN register works
  int val = PINB ;
  Serial.println(val); // Print the value of the variable VAL
  delay(1000); // a delay as in a blink program ;)
  
  // Set the 3 Most significant bits corresponding to Pins 11, 12 & 13 as LOW in the PORT Register
  PORTB = B000000;
  // Store the current value of the PIN Register in the variable VAL
  val = PINB ;
  Serial.println(val); // Print the value of the variable VAL
  delay(1000); // a delay as in a blink program ;) 
  
}


The 7-Segment Display

7-Segment displays are another common component in the world of electronics. These displays have 8 LEDs split into different segments designed to be able to display numerals from 0-9 and a dot.  All The LEDs have a common ground / supply line. There are 5 pins at the top and 5 pins at the bottom. The middle pins in the top and bottom are connected to each other internally and have to be connected to Ground / Supply depending upon the type of the 7-segment Display. You can control each segment like an individual LED. We shall use Port Manipulation to Control these as a set.


The Simple Labs' DTMF / 7-Segment Shield

This shield lets you experiment with DTMF or 7-Segment Displays (You can use only one of these at any given time).  Check here for how to work with the DTMF part.


The shield lets you control up to two Common Cathode type 7-Segment Displays. The shield provides you with options to control the COM pin of the 7-Segment Displays using either an IO or by connecting the COM pin Directly to Ground through a set of jumpers. COM pin of the Digit 1 can be set to be controlled by Digital Pin 10 and COM pin of the Digit 1 can be set to be controlled by Digital Pin 11. See the image below.

Pin Mappings for 7-Segment Displays on the Shield are as per the following image


First Lets try to Control one of 7-Segment Displays. Set the jumper to connect the COM pin of display 1 to ground. (Refer to Jumper Settings image above). You can either remove the other display or set the jumper for it to connect its COM pin to the IO.

Now that we are all set, lets understand what we are about to do.
  • If you noticed, we have used all pins on PORT D to connect to the segments of the 7-Segment Display. This will help us control all the segments at once.
  • To display the number '1' on the 7-segment display, we need to make the segment 'b' (digital Pin 0) & 'c' (digital Pin 4) high and keep all other segments low.

Here's a table with values to display the different numbers

2^7 = 1282^6 = 642^5 = 322^4 = 162^3 = 82^2 = 42^1 = 22^0 = 1
Digital Pin 7Digital Pin 6Digital Pin 5Digital Pin 4Digital Pin 3Digital Pin 2Digital Pin 1Digital Pin 0
DigitDecimal ValueBinary ValueSegment D Segment DP Segment E Segment C  Segment F  Segment G  Segment A  Segment B 
0187101110111 (HIGH)0 (LOW)1 (HIGH)1 (HIGH)1 (HIGH)0 (LOW)1 (HIGH)1 (HIGH)
117000100010 (LOW)0 (LOW)0 (LOW)1 (HIGH)0 (LOW)0 (LOW)0 (LOW)1 (HIGH)
2167101001111 (HIGH)0 (LOW)1 (HIGH)0 (LOW)0 (LOW)1 (HIGH)1 (HIGH)1 (HIGH)
3151100101111 (HIGH)0 (LOW)0 (LOW)1 (HIGH)0 (LOW)1 (HIGH)1 (HIGH)1 (HIGH)
429000111010 (LOW)0 (LOW)0 (LOW)1 (HIGH)1 (HIGH)1 (HIGH)0 (LOW)1 (HIGH)
5158100111101 (HIGH)0 (LOW)0 (LOW)1 (HIGH)1 (HIGH)1 (HIGH)1 (HIGH)0 (LOW)
6190101111101 (HIGH)0 (LOW)1 (HIGH)1 (HIGH)1 (HIGH)1 (HIGH)1 (HIGH)0 (LOW)
719000100110 (LOW)0 (LOW)0 (LOW)1 (HIGH)0 (LOW)0 (LOW)1 (HIGH)1 (HIGH)
8191101111111 (HIGH)0 (LOW)1 (HIGH)1 (HIGH)1 (HIGH)1 (HIGH)1 (HIGH)1 (HIGH)
9159100111111 (HIGH)0 (LOW)0 (LOW)1 (HIGH)1 (HIGH)1 (HIGH)1 (HIGH)1 (HIGH)


We are going to store the above decimal values in an array such that the 0th element of the array will hold the value '187' which is the value to be written to the output register to produce a '0' on the 7 segment display. So anytime we want to display a numeric value, we simply call the array variable with the value of the digit we want to display.

Try the following program. You should see numbers from 0 to 9 being displayed. Ensure you set the jumpers of the Displays to have the common pin connected to GND.


/*  Induino R3 User Guide - Program 21.1 - Controlling a single 7-Segment LED on the Simple Labs 7-Segment / DTMF Shield using the Induino R3 */

/* This program displays the numbers 0 to 9 on the 7 Segment display*/

// An array variable to store the decimal values to be written to the PORT register to produce various digits on the 7 segment.
// The 0th array index holds the value to display '0'. the 1st array index holds the value to display '1' and so on

int seven_seg_val[]={187,17,167,151,29,158,190,19,191,159};

void setup()
{
  // Set all the pins from 0 to 7 as output.
  // You can use binary data directly by preceeding with B
  DDRD = B11111111; // This is the same as saying DDRD = 255;

}

void loop()
{
  // A for loop to iterate through values 0 to 9 that have to be displayed on the 7 segment
  for(int i=0; i< 10; i++)
  {
    // Write the set of values for the current digit to the PORT register
    PORTD = seven_seg_val[i];
    delay(1000);
  }
}

Displaying Multiple Digits

Next lets see how we can produce multiple digits using multiple 7 segments (we will be working with two 7 segment displays however the process will be the same for n number of 7 segment displays!)

To produce multiple digits, we are going to control the common pin and change the values displayed on each of the digits at very high speed so that it appears to the viewer as if a multi digit number is being displayed constantly.

Lets see how to display the number 23.

  1. First control the common pin of the display 1 to turn it ON and control the common pin of the display 2 to turn it OFF
  2. Then Display the number 2 on the display 1 for a short amount of time (very short!). You do this by writing the corresponding value for 2 to the PORT register and adding a delay
  3. At the end of the delay write '0' to the PORT register to clear it
  4. Now control the common pin of the display 1 to turn it OFF and control the common pin of the display 2 to turn it ON
  5. Now Display the number 3 on the display 2 for a short amount of time (very short!). You do this by writing the corresponding value for 3 to the PORT register and adding a delay
  6. At the end of the delay write '0' to the PORT register to clear it
  7. go back and keep repeating from step 1 to 6 
Here's the program to display the number '23'
/*  Induino R3 User Guide - Program 21.2 - Displaying the number 23 using the two 7-Segment LEDs on the Simple Labs 7-Segment / DTMF Shield using the Induino R3 */

/* This program displays the number 23 on the 7 Segment LEDs */

// An array variable to store the decimal values to be written to the PORT register to produce various digits on the 7 segment.
// The 0th array index holds the value to display '0'. the 1st array index holds the value to display '1' and so on

int seven_seg_val[]={187,17,167,151,29,158,190,19,191,159};

void setup()
{
  // Set all the pins from 0 to 7 as output.
  // You can use binary data directly by preceeding with B
  DDRD = B11111111; // This is the same as saying DDRD = 255;
  // set the control pins for the common lines of both the 7 segment displays as OUTPUT
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  // write a LOW signal to the control pins for the common lines to keep them both disabled
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);
}

void loop()
{
  // A for loop to iterate through values 0 to 9 that have to be displayed on the 7 segment
  for(int i=0; i< 100; i++)
  {
    // Turn ON Display 1 using the control Pin
    digitalWrite(10,HIGH);
    // Turn OFF Display 2 using the control Pin
    digitalWrite(11,LOW);
    // Write the set of values for the digit '2' to the PORT register
    PORTD = seven_seg_val[2];
    // A Short Delay
    delay(1);
    // Reset the PORT Register to 0
    PORTD = 0;
    
    // Turn OFF Display 1 using the control Pin
    digitalWrite(10,LOW);
    // Turn ON Display 2 using the control Pin
    digitalWrite(11,HIGH);
    // Write the set of values for the digit '3' to the PORT register
    PORTD = seven_seg_val[3];
    // A Short Delay
    delay(1);
    // Reset the PORT Register to 0
    PORTD = 0;
  }
}

Displaying Multiple Digits - 0 to 99

Here's an extension of the above program to display the numbers from 0 to 99
/*  Induino R3 User Guide - Program 21.3 - Displaying the numbers 0 to 99 using the two 7-Segment LEDs on the Simple Labs 7-Segment / DTMF Shield using the Induino R3 */

/* This program displays the numbers 0 to 99 on the 7 Segment LEDs */

// An array variable to store the decimal values to be written to the PORT register to produce various digits on the 7 segment.
// The 0th array index holds the value to display '0'. the 1st array index holds the value to display '1' and so on

int seven_seg_val[]={ 187,17,167,151,29,158,190,19,191,159};

void setup()
{
  // Set all the pins from 0 to 7 as output.
  // You can use binary data directly by preceeding with B
  DDRD = B11111111; // This is the same as saying DDRD = 255;
  // set the control pins for the common lines of both the 7 segment displays as OUTPUT
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  // write a LOW signal to the control pins for the common lines to keep them both disabled
  digitalWrite(10,HIGH);
  digitalWrite(11,HIGH);
}

void loop()
{
  // A for loop to iterate through values 0 to 9 that have to be displayed on tens position of the 7 segment display
  for(int i=0; i<10;i++)
  {
    // A for loop to iterate through values 0 to 9 that have to be displayed on ones position of the 7 segment display
    for(int j=0; j<10;j++)
    {
      // A for loop to add stability to the display - the display looks more stable if the same value is displayed for more number of times at a higher speed.
      for(int k=0; k< 100; k++)
      {
        // Turn ON Display 1 using the control Pin
        digitalWrite(10,HIGH);
        // Turn OFF Display 2 using the control Pin
        digitalWrite(11,LOW);
        // Write the set of values for the digit '2' to the PORT register
        PORTD = seven_seg_val[i];
        // A Short Delay
        delay(1);
        // Reset the PORT Register to 0
        PORTD = 0;

        // Turn OFF Display 1 using the control Pin
        digitalWrite(10,LOW);
        // Turn ON Display 2 using the control Pin
        digitalWrite(11,HIGH);
        // Write the set of values for the digit '3' to the PORT register
        PORTD = seven_seg_val[j];
        // A Short Delay
        delay(1);
        // Reset the PORT Register to 0
        PORTD = 0;
      }
    }
  }
}

Displaying a sensor value

Lets see how to display a Sensor value. We shall display temperature value using a LM35 temperature sensor. Read this tutorial before proceeding (if you already haven't!)
http://www.induino.com/2013/07/the-on-board-sensor-interface.html

Heres how we are going to do it.
  1. Get the temperature value from the analog value
  2. Split the temperature value into 2 digits -> ones and tens values
  3. First control the common pin of the display 1 to turn it ON and control the common pin of the display 2 to turn it OFF
  4. Then Display the number of the ones value on the display 1 for a short amount of time (very short!). 
  5. At the end of the delay write '0' to the PORT register to clear it
  6. Now control the common pin of the display 1 to turn it OFF and control the common pin of the display 2 to turn it ON
  7. Now Display the number of the tens value on the display 2 for a short amount of time (very short!). 
  8. At the end of the delay write '0' to the PORT register to clear it
  9. go back and keep repeating from step 1 to 6 
Here's the program to do it

/*  Induino R3 User Guide - Program 21.4 - Displaying temperature value from a  lm35 sensor using the two 7-Segment LEDs on the Simple Labs 7-Segment / DTMF Shield using the Induino R3 */

/* This program displays the temperature value from a lm35 sensor on the 7 Segment LEDs */

// An array variable to store the decimal values to be written to the PORT register to produce various digits on the 7 segment.
// The 0th array index holds the value to display '0'. the 1st array index holds the value to display '1' and so on

int seven_seg_val[]={ 187,17,167,151,29,158,190,19,191,159};


void setup()
{
  // Set all the pins from 0 to 7 as output.
  // You can use binary data directly by preceeding with B
  DDRD = B11111111; // This is the same as saying DDRD = 255;
  // set the control pins for the common lines of both the 7 segment displays as OUTPUT
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  // write a LOW signal to the control pins for the common lines to keep them both disabled
  digitalWrite(10,HIGH);
  digitalWrite(11,HIGH);
}

void loop()
{
  // Read the raw sensor value and store it in the variable
  int sensor_val = analogRead(2)/2; 
  int ones = sensor_val%10;
  int tens = sensor_val/10;
      // A for loop to add stability to the display - the display looks more stable if the same value is displayed for more number of times at a higher speed.
      for(int k=0; k< 100; k++)
      {
        // Turn ON Display 1 using the control Pin
        digitalWrite(10,HIGH);
        // Turn OFF Display 2 using the control Pin
        digitalWrite(11,LOW);
        // Write the set of values for the digit '2' to the PORT register
        PORTD = seven_seg_val[ones];
        // A Short Delay
        delay(1);
        // Reset the PORT Register to 0
        PORTD = 0;

        // Turn OFF Display 1 using the control Pin
        digitalWrite(10,LOW);
        // Turn ON Display 2 using the control Pin
        digitalWrite(11,HIGH);
        // Write the set of values for the digit '3' to the PORT register
        PORTD = seven_seg_val[tens];
        // A Short Delay
        delay(1);
        // Reset the PORT Register to 0
        PORTD = 0;
      }
}

Thats It For This Part! Enjoy... and feel free to drop us an email with questions you might have -> info@simplelabs.co.in

Visit www.simplelabs.co.in for more interesting products

Back to List of Contents

Monday, 24 February 2014

LCD Interfacing - Creating Custom Characters

So you have been using an LCD for sometime and now have the need to create a custom character / symbol... How do you do it?
(Please check this before proceeding -   LCD Interfacing - Working with the Simple Labs' LCD Shield)

Before getting onto it, lets understand how an LCD displays characters. If you notice, each character on a LCD display typically is inside a small 5 Rows x 8 Columns array of dots. Depending upon the character to be displayed, the required dots are turned On / Off. Most LCD's come pre-configured to display standard characters. Each character has a definition matrix, which defines which dots are to be On and which dots are to be Off.

Here's an image that will help you understand better. Here's a Custom Smiley and its corresponding Binary definition

Here's how we will define a BYTE variable to hold the definition for the above Character. If you look at it the first row above is stored in the 0th index of the array mySmiley.

byte mySmiley[8] = {
0b00000, 
0b01010, 
0b01010, 
0b01010, 
0b00000, 
0b10001, 
0b01110,
0b00000
};

if Binary is not your game, you can use the below image, to find the decimal equivalent. (both images are using different characters - so use your common sense ;) )


So we can rewrite the definition in decimal as follows
byte mySmiley[8] = { 0, 10,10,10,0,17,14,0};

Here's a simple program to display the Smiley on your LCD

Here's the Program
/*  Induino R3 User Guide - Program 20.0 - LCD Interfacing - Creating Custom Characters on a 16x2 LCD using the Induino R3 */

/* This program uses the Simple Labs LCD Shield, 16x2 LCD from Simple Labs and the Induino R3 Board. Change the pin numbers according your own hardware */

#include <LiquidCrystal.h> //Include the LCD Header

// initialize the lcd
LiquidCrystal lcd(8, 9,10, 11, 12,13);

byte mySmiley[8] = {0,10,10,10,0,17,14,0}; // Define the Smiley Character


void setup()
{
  // add the mySmiley Character to the 0th Location of the LCD's CGRAM 
  // 0-7 are possible values here
  lcd.createChar(0, mySmiley);
  
  // set up number of columns and rows
  lcd.begin(16, 2); 
  
  // Write out Smiley Character.
 // Type casting is required as we are directly mentioning a value
  lcd.write((uint8_t)0); 
}

void loop()
{

}


Now lets play around by creating a set of 8 Characters, each representing a line at a different height (see the output to get a clear understanding)

byte line_0[8] = { 0,0,0,0,0,0,0,31};
byte line_1[8] = { 0,0,0,0,0,0,31,0};
byte line_2[8] = { 0,0,0,0,0,31,0,0};
byte line_3[8] = { 0,0,0,0,31,0,0,0};
byte line_4[8] = { 0,0,0,31,0,0,0,0};
byte line_5[8] = { 0,0,31,0,0,0,0,0};
byte line_6[8] = { 0,31,0,0,0,0,0,0};
byte line_7[8] = { 31,0,0,0,0,0,0,0};

Now the above definition can be optimized by making it an array, so we can redefine it as 

byte line[8][8]={
{ 0,0,0,0,0,0,0,31},
{ 0,0,0,0,0,0,31,0},
{ 0,0,0,0,0,31,0,0},
{ 0,0,0,0,31,0,0,0},
{ 0,0,0,31,0,0,0,0},
{ 0,0,31,0,0,0,0,0},
{ 0,31,0,0,0,0,0,0},
31,0,0,0,0,0,0,0}
};

Here's the Program
/*  Induino R3 User Guide - Program 20.1 - LCD Interfacing - Creating Custom Characters on a 16x2 LCD using the Induino R3 */

/* This program uses the Simple Labs LCD Shield, 16x2 LCD from Simple Labs and the Induino R3 Board. Change the pin numbers according your own hardware */

#include <LiquidCrystal.h> //Include the LCD Header

// initialize the lcd
LiquidCrystal lcd(8, 9,10, 11, 12,13);

byte mySmiley[8] = {0,10,10,10,0,17,14,0}; // Define the Smiley Character


void setup()
{
  // add the custom characters to the LCD's CGRAM 
  lcd.createChar(0, mySmiley);
  
  // set up number of columns and rows
  lcd.begin(16, 2); 
  
  // Write out the custom Characters
  // Type casting is required as we are directly mentioning a value
  lcd.write((uint8_t)0); 
}

void loop()
{

}

Now Lets to try to modify the above program to create a set of characters that can produce a BAR Graph with 8 different levels.

First we redefine the Character Array

byte line[8][8]={
{ 0,0,0,0,0,0,0,31}, // Level 1
{ 0,0,0,0,0,0,31,31}// Level 2
{ 0,0,0,0,0,31,31,31}// Level 3
{ 0,0,0,0,31,31,31,31}// Level 4
{ 0,0,0,31,31,31,31,31}// Level 5
{ 0,0,31,31,31,31,31,31}// Level 6
{ 0,31,31,31,31,31,31,31}// Level 7
31,31,31,31,31,31,31,31// Level 8
};

Here's the Program
/*  Induino R3 User Guide - Program 20.2 - LCD Interfacing - Creating Custom Characters on a 16x2 LCD using the Induino R3 */

/* This program creates a series of Bar Graph Characters- an experimentation with custom characters */

#include <LiquidCrystal.h> //Include the LCD Header

// initialize the lcd
LiquidCrystal lcd(8, 9,10, 11, 12,13);

// Define the Characters for creating a Bar Graph with Various Levels
byte line[8][8]={
{ 0,0,0,0,0,0,0,31}, // Level 1
{ 0,0,0,0,0,0,31,31}, // Level 2
{ 0,0,0,0,0,31,31,31}, // Level 3
{ 0,0,0,0,31,31,31,31}, // Level 4
{ 0,0,0,31,31,31,31,31}, // Level 5
{ 0,0,31,31,31,31,31,31}, // Level 6
{ 0,31,31,31,31,31,31,31}, // Level 7
{ 31,31,31,31,31,31,31,31} // Level 8
};

void setup()
{
  // add the custom characters to the LCD's CGRAM 
  for(int i =0; i <8; i++)
  {
    lcd.createChar(i, line[i]);
  }
  // set up number of columns and rows
  lcd.begin(16, 2); 
}

void loop()
{
  // Show the Bar Graph Characters as increasing
  for(int i =0; i <8; i++)
  {
   // Print the Bar Graph Character on the First Line
   lcd.setCursor(i,0);   
   lcd.write(i);
   
   // Print the Corresponding value on the Second Line
   lcd.setCursor(i,1);   
   lcd.print(i);
   delay(1000); 
  }
  delay(1000); 
  // Clear the display
  lcd.clear();
}

Now lets use the bar graph characters to indicate sensor value. We shall use the value of the LDR on the Induino R3 board and try to represent it using the Bar Graph.

Here's the Program
/*  Induino R3 User Guide - Program 20.3 - LCD Interfacing Custom Characters- Displaying the LDR Value as a Single Bar Graph Character Induino R3 */

/* This program creates a series of Bar Graph Characters- an experimentation with custom characters */

#include <LiquidCrystal.h> //Include the LCD Header

// initialize the lcd
LiquidCrystal lcd(8, 9,10, 11, 12,13);

// Define the Characters for creating a Bar Graph with Various Levels
byte line[8][8]={
{ 0,0,0,0,0,0,0,31}, // Level 1
{ 0,0,0,0,0,0,31,31}, // Level 2
{ 0,0,0,0,0,31,31,31}, // Level 3
{ 0,0,0,0,31,31,31,31}, // Level 4
{ 0,0,0,31,31,31,31,31}, // Level 5
{ 0,0,31,31,31,31,31,31}, // Level 6
{ 0,31,31,31,31,31,31,31}, // Level 7
{ 31,31,31,31,31,31,31,31} // Level 8
};

void setup()
{
  // add the custom characters to the LCD's CGRAM 
  for(int i =0; i <8; i++)
  {
    lcd.createChar(i, line[i]);
  }
  // set up number of columns and rows
  lcd.begin(16, 2); 
}

void loop()
{
 // Read the LDR Value and store it in a variable
 int val = analogRead(3);
 // Map the analog value from the sensor to a scale of 0 to 7 (8 Levels)
 val = map(val, 0, 1023, 0, 7);
 
 // Print the numerical value to the LCD
 lcd.setCursor(0,1);
 lcd.print(val);
 
 //set the cursor
 lcd.setCursor(0,0);
 
  // Write the Bar Graph Level Value corresponding to the Value of the LDR

 lcd.write(val);
 
 delay(100);  
 lcd.clear(); 
}

Now Having a static Bar is not much fun, lets convert this into a realtime BAR graph. A Running Bar Graph based on the last 16 values of the sensor. 16 Values as we can display only 16 characters per line.

/*  Induino R3 User Guide - Program 20.4 - LCD Interfacing Custom Characters- Displaying the LDR Value as a Running Bar Graph using the Induino R3 */

/* This program creates a series of Bar Graph Characters- an experimentation with custom characters */

#include <LiquidCrystal.h> //Include the LCD Header

// initialize the lcd
LiquidCrystal lcd(8, 9,10, 11, 12,13);

// Define the Characters for creating a Bar Graph with Various Levels
byte line[8][8]={
{ 0,0,0,0,0,0,0,31}, // Level 1
{ 0,0,0,0,0,0,31,31}, // Level 2
{ 0,0,0,0,0,31,31,31}, // Level 3
{ 0,0,0,0,31,31,31,31}, // Level 4
{ 0,0,0,31,31,31,31,31}, // Level 5
{ 0,0,31,31,31,31,31,31}, // Level 6
{ 0,31,31,31,31,31,31,31}, // Level 7
{ 31,31,31,31,31,31,31,31} // Level 8
};

// a variable array to store the last 16 values of the sensor
int hist_val[16];

// to count the first 16 values
int cnt = 0;

void setup()
{
  // add the custom characters to the LCD's CGRAM 
  for(int i =0; i <8; i++)
  {
    lcd.createChar(i, line[i]);
  }
  // set up number of columns and rows
  lcd.begin(16, 2); 
}

void loop()
{
 // Read the LDR Value and store it in a variable
 int val = analogRead(3);
 // Map the analog value from the sensor to a scale of 0 to 7 (8 Levels)
 val = map(val, 0, 1023, 0, 7);
 
 lcd.setCursor(0,0);
 lcd.print(val);
 
 // Check if cnt is less than 16, if it is less than 16, we need to increment it
// we also need to store the values of the sensor for the first 16 counts
 if(cnt<16)
 {
   hist_val[cnt] = val;
   // Increment cnt  
   cnt++;
 }
 else
 // if count is greater than 16, we need to push out the oldest of the values and add the latest value to the set of 16 values.
 // the oldest value will be stored in the 0th array index and the latest value in the 15th array index
 // in addition, we also need to move up all other historic values by one position
 {
   // do the moving up of the historic values
   for(int j=0; j<15;j++) 
     hist_val[j] = hist_val[j+1];
     
   // store the latest value in the last position
   hist_val[15] = val; 
 }
 // Displaying the Values as a Running Bar Graph
 for(int i=0; i<cnt; i++)
 {
    lcd.setCursor(i,0);
                  lcd.write(hist_val[i]);
                 /* lcd.setCursor(i,1);
                  lcd.print(hist_val[i]); */
                  delay(10);
 }

}

Thats It For This Part! Enjoy... and feel free to drop us an email with questions you might have -> info@simplelabs.co.in

Visit www.simplelabs.co.in for more interesting products

Monday, 17 February 2014

Interfacing Sensors - Microphone Sound Detection Sensor

Microphone Sound Detection Sensor

The Microphone Sound Detection Sensor is a simple sensor that detects sound using a Condenser Mike. It can give either a RAW analog output or a Comparator based Digital Output. The Analog Output is the Output from a Potential Divider constructed between the Microphone and the Trimpot. The Digital Output is that of a Comparator that takes in the potential divider as one Input and a fixed resistance as the other. 



Connections

If you are using the Induino R3 Board, You can plug the sensor directly onto the Sensor Interface on the Board. Like in the Image Below.



  1. Connect '+' pin of the Sensor module to +5V on the Induino R3 / Arduino Board
  2. Connect the 'G' pin of the Sensor module to the GND pin on the Induino R3 / Arduino Board
  3. Connect the 'DO' pin of the Sensor module to Digital Pin 16 (A2) on the Induino R3 / Arduino Board
Adjusting the Sound Sensor Sensitivity

The Trimpot on the Sensor, lets you adjust the Sound Sensor Sensitivity. The LED marked L2 (below the Trimpot) indicates the digital output of the sensor. To adjust the sensitivity, Adjust the Trimpot using a Screw Driver. Clock Wise Rotation, Decreases the Sensitivity and Anti-Clock Wise Rotation Increases it. Once the sensitivity is set,  Verify by making a sound and checking if the LED L2 Turns On when you make the desired sound. 


Programming for the Microphone Sound Detection Sensor

Here's a Simple Program that toggles On / Off the LED on the 13th Pin everytime a clap is detected.


Here's the Program
/*  Induino R3 User Guide - Program 19.0 - Interfacing Microphone Sound Detection Sensor with the Induino R3 */

#define mic 16 // The Microphone Sound Detection Sensor's Digital Output Pin is Connected to Pin 16 / A2 of Induino R3

boolean state = 0;

void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
  
  // Setup the 13the pin LED for OUTPUT
  pinMode(13, OUTPUT);
  
  // Setup the sensor input pin
  pinMode(mic, INPUT);
  
}

void loop()
{
  if(digitalRead(mic)) // Check if the Sensor Input is HIGH
  {
   state = !state; // Toggle the State Variable
   digitalWrite(13, state); // Set the Current State to the OUTPUT LED
   delay(1000); // Wait for the INPUT to become stable
  }
}

Thats It For This Part! Enjoy... and feel free to drop us an email with questions you might have -> info@simplelabs.co.in

Visit www.simplelabs.co.in for more interesting products

Wednesday, 20 November 2013

SPI Communication - What, Where & How? - Working with the W5100 Ethernet Shield

SPI Communication

SPI stands for Serial Peripheral Interface. Its a type of Serial communication that uses Synchronization. Here's a nice tutorial on this from Sparkfun(its better to share good content than rewrite!) ->  https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi/all

Read the above tutorial before proceeding.

The W5100 Ethernet Shield

The W5100 Ethernet Shield is based on the W5100 chip from Wiznet. There are 2 versions of this available from the Simple Labs website
  1. The Official Arduino Ethernet Shield R3 - This is the Rev3 Version of the Ethernet Shield
  2. The Low Cost W5100 Ethernet Shield - This is a cheap chinese version of the Ethernet Shield. This shield is not a Rev3 shield however will work with all boards including the Rev3 ones.
The shields come with a slot for microSD, which shares the SPI bus along with the Ethernet Controller. The Chip Select Pin for the microSD is Pin 4 and the Chip Select Pin for the  Ethernet Controller is Pin 10. Both of these can be used at the same time. Lets see how to work with both of these one at a time

Working with the MicroSD
Working with the MicroSD is easier as Arduino comes with a SD Library for working with these. The SD Library provides with a number of functions required for us to work with an SD card. You can read more about the library here -> http://arduino.cc/en/Reference/SD (Read Before you Proceed!)

Load and try the following examples from the Arduino IDE -> Examples -> SD
Cardinfo.ino
Datalogger.ino
ReadWrite.ino

Now lets modify the Datalogger example to include a date / time stamp from our RTC, This way the datalogger becomes more meaningful.

Here's the Program
/*  Induino R3 User Guide - Program 18.0 - A SD Datalogger with Time Stamp 
  SD card datalogger
 
 This example shows how to log data from three analog sensors 
 to an SD card using the SD library.
  
 The circuit:
 * analog sensors on analog ins 0, 1, and 2
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4
 
 created  24 Nov 2010
 modified 9 Apr 2012
 by Tom Igoe
 
 This example code is in the public domain.
   
 */

#include <SD.h>
#include <Wire.h> // I2C Library

// On the Ethernet Shield, CS is pin 4. Note that even if it's not
// used as the CS pin, the hardware CS pin (10 on most Arduino boards,
// 53 on the Mega) must be left as an output or the SD library
// functions will not work.
const int chipSelect = 4;

#define myrtc 0x68 // I2C Address of DS1307

char *dow[]={
  " ","MON","TUE","WED","THU","FRI","SAT","SUN"}; // An Array to store the DAY text to match with the DAY parameter of the RTC

char *mode[]={
  "HR","AM","PM"}; // An Array to store the time mode 

char *month[]={
  "","JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"};

int dd,mm,yy,day,hh,mins,ss,mde; // Variables to store the retrieved time value


void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
  
  Wire.begin(); // Initialise Wire Communication - Join the I2C Bus
  delay(100);
  set_time(15,11,13,5,11,10,55,2);
  Serial.print("Initializing SD card...");
  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(10, OUTPUT);
  
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
  
}

void loop()
{
  // make a string for assembling the data to log:
  String dataString = "";
  String dateString ="";
  get_time();// get Date / time value into a String Variable
  dateString +=dow[day];
  dateString +="  ";
  dateString +=String(dd);
  dateString +="-";
  dateString +=month[mm];
  dateString +="-";
  dateString +=String(yy);
  dateString +=" : ";
  dateString +=String(hh);
  dateString +=":";
  dateString +=String(mm);
  dateString +=":";
  dateString +=String(ss);
  dateString +=" ";
  dateString +=mode[mde];
  dateString +=" ";
  
  dataString += dateString; // Append the Date String to the Data String
  // read three sensors and append to the string:
  for (int analogPin = 0; analogPin < 3; analogPin++) {
    int sensor = analogRead(analogPin);
    dataString += String(sensor);
    if (analogPin < 2) {
      dataString += ","; 
    }
  }

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    // print to the serial port too:
    Serial.println(dataString);
  }  
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  } 
}

// The set_time function takes parameters in the order of date, month, year, day of week, hours, minutes, seconds & mode
// the mode can have 3 possible values  (0=>24HR, 1=> AM, 2 => PM)

void set_time(int sdd, int smm, int syy, int sday, int shr, int smin, int ssec, int smode)
{
  Wire.beginTransmission(myrtc); // Initialise transmission to the myrtc I2C address
  Wire.write(0x00); // Write the value of the register to start with, 0 in this case represented in BCD format
  Wire.write(dec_to_bcd(ssec));  // convert the seconds value from decimal to bcd and write it to the seconds register
  // after the write operation the register pointer will be at the next register, so we do not have to set the value of the register again
  Wire.write(dec_to_bcd(smin));  // convert the minutes value from decimal to bcd and write it to the minutes register
  if(smode == 0) // Check if the mode is 24hrs mode
  {
    Wire.write(dec_to_bcd(shr));  // if 24 hours mode is on then convert the hours value from decimal to bcd and write it to the hours register
  }
  else // if the mode is 12 hr mode
  {
    // If 12 hour mode is selected then the 12 Hour mode bit (the 6th bit) has to be set to 1
    // convert the hour value to bcd first and then adding 64(2^6) to the converted hrs value will set the 6th bit HIGH

    shr = dec_to_bcd(shr)+64; 

    if(smode == 1) // check if it is AM
      Wire.write(shr); // if it is AM we can directly write the value of the above modified hours values to the hours register
    if(smode == 2) // check if it is PM
      Wire.write(shr+32); // If it is PM, then adding 32 (2^5) sets the 5th bit (the PM indication bit) HIGH, the calculated value is written to the hours register
  }
  Wire.write(dec_to_bcd(sday));  // convert the day value from decimal to bcd and write it to the day register
  Wire.write(dec_to_bcd(sdd));  // convert the date value from decimal to bcd and write it to the date register
  Wire.write(dec_to_bcd(smm));  // convert the month value from decimal to bcd and write it to the month register
  Wire.write(dec_to_bcd(syy));// convert the year value from decimal to bcd and write it to the year register
  Wire.endTransmission();  // end the transmission with the I2C device

}

// the get_time() function will retrieve the current time from the RTC and store it in the Global Variables declared

void get_time()
{
  Wire.beginTransmission(myrtc); // Initialise transmission to the myrtc I2C address
  Wire.write(0x00); // Write the value of the register to start with, 0 in this case represented in BCD format
  Wire.endTransmission(); // end the transmission with the I2C device
  Wire.requestFrom(myrtc, 7);  // Now ask the I2C device for 7 Bytes of Data // This corresponds to the values of the 7 registers starting with the 0th register 

  ss = bcd_to_dec(Wire.read()); // The first read will retrieve the value from the register address 0x00 or the seconds register, this is in the BCD format, convert this back to decimal
  mins = bcd_to_dec(Wire.read());// The second read will retrieve the value from the register address 0x01 or the minutes register, this is in the BCD format, convert this back to decimal
  hh = Wire.read();// The third read will retrieve the value from the hours register, this value needs to be processed for the 24/12 hr mode

  // Check of if the BCD hours value retrieved is greater than 35 (this indicates that the hours is in 12 hour mode
  // 35 is the maximum BCD value possible in the 24hr mode
  if(hh > 35) 
  {
    hh = hh - 64; // in the 12 Hours Mode the 12 hour mode bit (6th bit) is set to high, so we need to subtract 2^6 from our hours value
    if(hh > 32)// Now check if the hour value is greater than 32 (2^5 = 32) (this indicates that PM bit (5th bit) is high)
    {
      mde = 2; // Set the mde variable to indicate PM
      hh = hh-32; // subtract 32 from the hours value 
    }
    else // if the hour value is less than 32 it means that its in the AM mode
    {
      mde = 1; // Set the mde variable to indicate AM
    }   
  }
  else // if the 12 hour mode bit was not set, then the hour is in the 24 hour mode
  {
    mde = 0; // Set the mde variable to indicate 24 Hours
  }

  hh = bcd_to_dec(hh); // Convert the final hour value from BCD to decimal and store it back into the same variable
  day = bcd_to_dec(Wire.read());// The fourth read will retrieve the value from the register address 0x03 or the day register, this is in the BCD format, convert this back to decimal
  dd = bcd_to_dec(Wire.read());// The fifthread will retrieve the value from the register address 0x04 or the date register, this is in the BCD format, convert this back to decimal
  mm = bcd_to_dec(Wire.read());// The sixth read will retrieve the value from the register address 0x05 or the month register, this is in the BCD format, convert this back to decimal
  yy = bcd_to_dec(Wire.read());// The seventh read will retrieve the value from the register address 0x06 or the year register, this is in the BCD format, convert this back to decimal

}

// The dec_to_bcd() function converts a given decimal number to BCD format

int dec_to_bcd(int dec)
{
  return dec/10*16 + (dec%10); // convert and return the number from decimal to bcd format
}

// The dec_to_bcd() function converts a given BCD number to decimal format

int bcd_to_dec(int bcd)
{
  return bcd/16*10 + (bcd%16); // convert and return the number from bcd to decimal format
}      


Next we will see how to work with the Ethernet Part of the shield.

Ethernet
The Ethernet Shield uses Wiznet W5100 Module for providing ethernet. The Ethernet Capability works out of the box with the Arduino Ethernet Library. To work with the ethernet shield you need to have a clear understanding of networks & HTML. The scope of this tutorial will be limited to getting the ethernet up and running and not venturing into these.  Get yourselves familiar with HTML & the Ethernet Library before proceeding

So lets try an example, Make the following connections

  1. Place the shield on top of your Induino R3 / Arduino Board
  2. Connect a Ethernet Cable Between the Shield and your modem / router - you cannot connect it your computer directly, it will not work!
  3. Upload the example from under Examples -> Ethernet-> WebServer
  4. Open your Browser (Chrome might have issues, try Firefox) and type in 192.168.1.177 in the address bar
  5. You should now see the Values from Analog Pins being displayed in the browser. 

What the example does is, it waits for a client(a browser) to connect to our ethernet shield and then it reads the GET request from the Client. At the end of the Get Request, it responsds with a HTML page which includes the Analog Pin Values

Next, Try the following modified version of the above example. We will build on top of this.

Here's the Program
/* Induino R3 User Guide - Program 18.1 - A Simple Webserver that responds with Analog Values
Modified original Webserver Example
  Web Server
 
 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)
 
 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 
 */

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

// 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(192,168,1,177);

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

String req;                       // a variable to store the GET request

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
  }
  // 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) {                          // Check if there is a client available
    Serial.println("new client");

    while (client.connected()) {        // check if the client is connected
      if (client.available()) {         // Check if there is a request from the client
        
        Serial.print("$$$$");
        req="";                         // reset the request variable
        while(client.available())      // Read data from the client 1 byte at a time as long as there is data
        {
        char c=client.read();          // Read 1 byte of data from the client
        req += c;                      // append the read data to the existing value 
        delay(1);
        }
        Serial.println(req);            
        Serial.println("XXX");
      }
          Serial.println("Sending Data to Client");
          client.println("HTTP/1.1 200 OK");   // start responding with the DATA to the client & Send out the response header
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the responsedelay(1);
  // client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
                    
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) 
          {
            int sensorReading = analogRead(analogChannel);
            client.print("<a href=\"/");
            client.print(analogChannel);
            client.print(".html\">");
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.print("</a>");
            client.println("<br />");       
          }          
          client.println("</html>");
          break;
     }
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  
  }
}

Now open the Serial Monitor and Open your Browser. Try the address 192.168.1.177 from your browser and see the results in the Serial monitor (like in the image below).

The contents of the GET request are printed between the $$$ and the XXX markings. The content of the GET request will vary depending upon the address you type in the browser, for example if you try
192.168.1.177/echo_me you would get a response similar to this in the serial monitor


We need to process the content in the first line between the GET and the HTTP/1.1 to identify the address requested, we can then respond accordingly.  in addition, we would need to use additional string processing functions to extract string information.

Let's try a Simple Example to control a LED. We will try to On / OFF the RED of the RGB LED (we cannot use the LEDS on Pin 11, 12 & 13 as these pins are used for SPI communication with the Ethernet Shield). For this, we will generate a simple html page with a link to ON / OFF (the link keeps toggling based on the current status of the LED)

Here's the HTML code for generating a link
<a href="/?ON">Click Here to Switch ON</a>
<a href="/?OFF">Click Here to Switch OFF</a>

So when the user clicks the link, we will get /?ON or /?OFF as part of the GET request. We need to process the get request, identify this and control accordingly.
Here's the Program
/*Induino R3 User Guide - Program 18.2 - A Simple Webserver that Controls using Links
Modified original Webserver Example
 
 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)
 
 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 
 */

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

// 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(192,168,1,177);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80); 
String req; // a variable to store the GET request

boolean state = 0; // a variable to store the state of the LED 
String state_val[]={"OFF","ON"}; // A Variable to store the State of the LED as String


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
  }


  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  pinMode(6,OUTPUT); // RGB LED RED is on Pin 6
}


void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) { // Check if there is a client available
    Serial.println("new client");
    while (client.connected()) {                    // check if the client is connected
      if (client.available()) {                    // Check if there is a request from the client
        
        Serial.print("$$$$");
        req="";                                    // reset the request variable
        while(client.available())                 // Read data from the client 1 byte at a time as long as there is data
        {  
        char c=client.read();                    // Read 1 byte of data from the client
        if(c==13) // Check if the data read is a Carriage Return a.ka. Enter, This means end of first line - the line starting with GET and ending with HTTP/1.1
          break; // Since we have read the first line, we need not read the remaining data for storage, so exit the while loop
        req += c; // append the read data to the existing value
        delayMicroseconds(1000);
        }
        // if the while loop above exited from the break statement, then there is data in the client buffer, which needs to be read to be removed
        // we need to read this data to empty the buffer
        while(client.available())                 // While loop to read the data to empty buffer
        {
          client.read();
          delayMicroseconds(1000);
        }
        Serial.println(req);                     // print the value of the request to the Serial Monitor for debugging
        Serial.println("XXX");
      }
          if(find_string(req,"GET /?ON"))       // Check if the received Request containts the String ON
          {
            state = 1;                          // Set the State Variable
            digitalWrite(6,state);              // Set the state to the RED LED
          }
          if(find_string(req,"GET /?OFF"))      // Check if the received Request containts the String ON
          {
            state = 0;                          // Set the State Variable
            digitalWrite(6,state);            
          }
        
          Serial.println("here 1");             // for debugging
          client.println("HTTP/1.1 200 OK");    // start responding with the DATA to the client & Send out the response header
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the responsedelay(1);
 
          client.println();
          client.println("<!DOCTYPE HTML>");    // Start of the HTML Page
          client.println("<html>");          
         
          client.println("<br />"); 
          if(state)                             // Check the State and print the LINK on the Page accordingly
          {
            client.println("<a href= \"/?"+state_val[0]+" \">");
          }
          else
          {
            client.println("<a href= \"/?"+state_val[1]+" \">");
          }
          client.println("Click Here to Switch "+state_val[!state]+" -RED of RGB LED");
          client.println("</a>");
          
          client.println("</html>");
          break;
     }
    client.stop();
    Serial.println("client disonnected");
  
  }
}



// A Function to locate a given search string in a given base string
boolean find_string(String base, String search)
{
  int len = search.length(); // find the length of the base string
  for(int m = 0; m<((base.length()-len)+1);m++)// Iterate from the beginning of the base string till the end minus length of the substring
  { 
     
    if(base.substring(m,(m+len))==search) // Check if the extracted Substring Matches the Search String
    {
      return true;        // if it matches exit the function with a true value
    }
    
  }
  return false; // if the above loop did not find any matches, control would come here and return a false value
}

Now open your browser, try the address 192.168.1.177, you should see the text with the link and clicking the text should toggle the state of the LED

Now lets see how to handle numeric values received through a get request, For the HTML Page We'll design 3 sliders that will let the user set values from 0-255. The slider will be set inside a form and when the user clicks the button to submit the form, it will be sent to a preset page along with the slider data as part of the get request, By processing the GET request for this page, we can read the data of the sliders that was submitted and use the values to control the RGB LED.

Here's the Program
/*Induino R3 User Guide - Program 18.2 - A Simple Webserver that Let you set the Intensity of the RGB LED on the Induino R3 Board using a Slider
Modified original Webserver Example

  Web Server
 
 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 
 
 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)
 
 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 
 */

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

// 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(192,168,1,177);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80);
String req;                // a variable to store the GET request

int RGB[]={0,0,0};        // a variable to store the Intensity Value, RGB[0] => RED, RGB[1] => Green, RGB[2]=>Blue

String tmp_rgb ="";       // a temporary variable

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
  }


  // 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) { // Check if there is a client available
    Serial.println("new client");
    while (client.connected()) {                    // check if the client is connected
      if (client.available()) {                    // Check if there is a request from the client
        
        Serial.print("$$$$");
        req="";                                    // reset the request variable
        while(client.available())                 // Read data from the client 1 byte at a time as long as there is data
        {  
        char c=client.read();                    // Read 1 byte of data from the client
        if(c==13) // Check if the data read is a Carriage Return a.ka. Enter, This means end of first line - the line starting with GET and ending with HTTP/1.1
          break; // Since we have read the first line, we need not read the remaining data for storage, so exit the while loop
        req += c; // append the read data to the existing value
        delayMicroseconds(1000);
        }
        // if the while loop above exited from the break statement, then there is data in the client buffer, which needs to be read to be removed
        // we need to read this data to empty the buffer
        while(client.available())                 // While loop to read the data to empty buffer
        {
          client.read();
          delayMicroseconds(1000);
        }
        Serial.println(req);                     // print the value of the request to the Serial Monitor for debugging
        Serial.println("XXX");
      }
      // Check if the GET request contains the text setrgb? 
      // If it contains the text, then we need to extract the values for RED, GREEN & Blue
        if(find_string(req,"GET /setrgb?"))     
          {
            
            int start_loc= find_string_loc(req,"RED=")+4; // Find the starting location of the Value for RED
            int end_loc = find_string_loc(req, "&GREEN"); // Find the ending location of the Value for RED
            RGB[0] = string_to_int(req.substring(start_loc,end_loc)); // Extract the Value and Store it

            start_loc= find_string_loc(req,"GREEN=")+6;   // Find the starting location of the Value for GREEN
            end_loc = find_string_loc(req, "&BLUE");     // Find the ending location of the Value for GREEN
            RGB[1] = string_to_int(req.substring(start_loc,end_loc)); // Extract the Value and Store it
            
            start_loc= find_string_loc(req,"BLUE=")+5;   // Find the starting location of the Value for BLUE
            end_loc = find_string_loc(req, "HTTP/1.1")-1;// Find the ending location of the Value for BLUE
            RGB[2] = string_to_int(req.substring(start_loc,end_loc));// Extract the Value and Store it
            
            analogWrite(3,RGB[1]);analogWrite(5,RGB[2]);analogWrite(6,RGB[0]); // Set the RGB Intensities from the Variable
            
          }
          
          Serial.println("here 1");             // for debugging
          client.println("HTTP/1.1 200 OK");    // start responding with the DATA to the client & Send out the response header
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the responsedelay(1);
 
          client.println();
          client.println("<!DOCTYPE HTML>");    // Start of the HTML Page
          client.println("<html>");          
         
          client.println("<br />"); 
          // Code for Printing Slider
          client.println("<form action=\"/setrgb\" method=\"get\">");
          tmp_rgb = (String) RGB[0];
          // The Sliders are set to have the current RGB[] values as the default values
          client.println("RED  Value: <input type=\"range\" name=\"RED\" min=\"0\" max=\"255\" value=\""+tmp_rgb+"\">");
          tmp_rgb = (String) RGB[1];
          client.println("<br/>GREEN Value: <input type=\"range\" name=\"GREEN\" min=\"0\" max=\"255\" value=\""+tmp_rgb+"\">");
          tmp_rgb = (String) RGB[2];
          client.println("<br/>BLUE   Value: <input type=\"range\" name=\"BLUE\" min=\"0\" max=\"255\" value=\""+tmp_rgb+"\">");
          client.println("<br/><br/><input type=\"submit\" value=\"SET\" />");
          client.println("</form>");
          client.println("</html>");
          break;
     }
    //delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  
  }
}

// A Function to locate a given search string in a given base string
boolean find_string(String base, String search)
{
  int len = search.length(); // find the length of the base string
  for(int m = 0; m<((base.length()-len)+1);m++)// Iterate from the beginning of the base string till the end minus length of the substring
  { 
     
    if(base.substring(m,(m+len))==search) // Check if the extracted Substring Matches the Search String
    {
      return true;        // if it matches exit the function with a true value
    }
    
  }
  return false; // if the above loop did not find any matches, control would come here and return a false value
}


// This function is similar to the String Search function except it returns the starting location of the Search String in the Base String
int find_string_loc(String base, String search)
{
  int len = search.length(); // find the length of the base string
  int m, val=0; // val is used to store the return value and m is a counter
  for(m = 0; m<((base.length()-len)+1);m++)// Iterate from the beginning of the base string till the end minus length of the substring
  {     
    if(base.substring(m,(m+len))==search) // Check if the extracted Substring Matches the Search String
    {
      val= m;        // if it matches set the return value to the current value of m
    }
    if(val!=0) // if the return value is non-zero, exit the for loop
     break;
  }
  return val; // return the retun value
}

//A Function to convert a given String with numerical content to its integer equivalent
int string_to_int(String base)
{
  int len = base.length(); // get the length of the string
  int ret_val=0;
  for(int m=0;m<len;m++) // iterate through each character in the string
  {
    ret_val = (ret_val*10)+ (base[m]-48); // subtract 48 from the ascii value to get the numeric value and add it to the existing value
    // if the string was 225, then when m=0, ret_val would be 2, when m=1, ret_val would be 20+2, when m=2, ret_val would be 220+5,
  }
  return ret_val;
}
  

Now open your browser, try the address 192.168.1.177, you should see 3 Sliders that let you control the RGB Led on the Induino R3.

Thats It For This Part! Enjoy... and feel free to drop us an email with questions you might have -> info@simplelabs.co.in

 Visit www.simplelabs.co.in for more interesting products