Category: ARDUINO


 

In the previous post we’ve seen how to program ESP8266 using Arduino IDE by installing the Boards Manager.

This post is on using the powerful ESP8266 WiFi Library which is automatically installed while using the Boards Manager.When you proceed with the  board package for the ESP8266,as explained in previous post, the ESP8266 WiFi library is automatically installed for you.

             Now, any time you want to use the classes and the functions from that ESP8266 WiFi library,  use the Include statement at the top of the program first, followed by the header name

#include <ESP8266WiFi.h>

at the starting of Arduino code & start using the Classes associated with this library.

ESP8266 WiFi library is designed after the the standard Arduino WiFi library but has even more functionality than the standard Arduino library .The standard Arduino WiFi library is used for the WiFi shield or with the Arduino boards like YUN with inbuilt WiFi.

With the introduction of ESP8266 , the WiFi functionality has become much cheaper & easy to use.

The WiFi library has many classes that you can use. Each class has functions in it that are specific to that class. There’s the WiFi class, the IP address class, the server class, the client class and the UDP class.

 

class1

 

In this post we’re going to explore the WiFi class & its functions.

The WiFi class allows to establish a connection with an access point.

What’s cool about the WiFi class is that we don’t  have to create an instance of this class. We can  go ahead and start using it. It’s like the serial library of Arduino. We don’t need to create an instance of the serial library.

class2

 

First Function of the library is WiFi.begin().

The usage of this function is similar to our Serial.begin().

Just like Serial.begin() , we use WiFi.begin() .WiFi.begin() requires 2 strings as arguments. You need to pass the SSID and the password of the Access point you wish to connect.You need to pass the arguments as character arrays or strings with a lower case s.

WiFi.begin(ssid,pass);

The possible return values are

WL_CONNECTED      after successful connection is established with the Access Point

WL_IDLE_STATUS       when Wi-Fi is in process of changing between statuses

WL_NO_SSID_AVAIL     in case configured SSID cannot be reached

WL_CONNECT_FAILED  if password is incorrect

WL_DISCONNECTED        if module is not configured in station mode

 

The status function in the WiFi class, doesn’t take any arguments but it returns stuff depending on the status of the network that you’re connected to.

Usually, first, you call WiFi.begin, you pass the SSID and the password because you’re trying to establish a connection with the network. Then, what you do is you wait in a loop until WiFi.status returns the value WL_CONNECTED.

——————————

WiFi.begin(ssid,password);

while (WiFi.status() != WL_CONNECTED)

{

delay(500);

Serial.print(“.”);

}

——————————

 

WiFi.SSID();

WiFi.SSID doesn’t take any arguments but it returns the name of the SSID that you’re connected to.

 

WiFi.RSSI()

Returns the current signal strength in  dB

 

WiFi.scanNetworks()

Returns the number of discovered networks.It will not list the network names , but returns the number of networks.

WiFi.macAddress()

Returns the MAC address of the ESP device

There is a specific function available to print out key Wi-Fi diagnostic information:

WiFi.printDiag(Serial);

Here is a sample sketch to demonstrate the WiFi library.

—————————————————-

#include <ESP8266WiFi.h>

void setup()
{
  Serial.begin(115200);
  Serial.println();

//disconnect any previous connections
  WiFi.disconnect();
  delay(1000);

//scan for number of nearby networks & print SSIDs

  Serial.print("Nearby networks found  :");
  Serial.println(WiFi.scanNetworks());
  delay(500);

Serial.println("List of surrounding Network SSIDs…:");
  int n = WiFi.scanNetworks();
  for (int i = 0; i < n; i++)
{
  Serial.println(WiFi.SSID(i));
}
  Serial.println();

//connect to preferred SSID
  
  WiFi.begin("SARAVANA-ACT", "mypass123");

  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

// print SSID name,local IP allotted ,MAC address & signal strength

  Serial.println();
  Serial.print("Connected to SSID          : ");
  Serial.println(WiFi.SSID());

  Serial.print("IP address allotted to ESP : ");
  Serial.println(WiFi.localIP());
 
  Serial.print("MAC Address of ESP         : ");
  Serial.println(WiFi.macAddress());

  Serial.print("Signal strength is         : ");
  Serial.println(WiFi.RSSI());

  }

void loop()
{
}

——————————————————–

The screenshot shows the result in the serial monitor of Arduino IDE

scan3

 

The Client & Server classes & their methods are shown in screen shots below :

class3

 

 

class4

Download PDF tutorial file for the WiFi library from

https://www.gitbook.com/download/pdf/book/krzychb/esp8266wifi-library

 

cooltext753793315   cooltext753790696

The ESP8266 by itself hosts a 32 bit Microcontroller on it & you can now program your ESP using Arduino IDE. Best part is that NO Arduino board is required.You can upload your code from Arduino IDE , as if you were upgrading the Firmware on ESP.

You can pretty much write any code  for an Arduino and run it on the ESP8266. Of course there is a limit to the I/O on some of the modules, but the Flash on the ESP-12E (Black) module is 4MB and the RAM is 80kB! Add to that the 80MHz 32-bit processor and you have a pretty impressive little cute Arduino.

A sample Blink example program on the ESP8266 turns out to be around 225kB, but that includes the core code.So it’s advisable to use an ESP8266 with more FLASH Memory.Generally the BLACK ones are with higher memory than the Blue ones.The new ESP12E has a Flash of whooping 4MB !!  The Arduino UNO has just 32k Flash & Mega 256k.

esp_blue_black

 

esp12e_bl_black

 

Program uploading is done at 115,200 Baud, the default for the module. But It still takes a while to upload a sketch to the module , unlike a regular Arduino.

To begin, you must install the ESP8266 board files in the Arduino IDE.

That is easy enough to do. Make sure that your Arduino IDE is latest

Open the Arduino preferences from File  —> Preferences

Image 1

 

Add the following URL to the “Additional Boards Manager URLs” seen at the bottom of Preferences Window

http://arduino.esp8266.com/stable/package_esp8266com_index.json

Image 2

 

Click OK to close the Preferences Window.

Click on TOOLS –. BOARDS—> BOARDS MANAGER

Image 4

When the Boards Manager opens, scroll to the bottom. You should see the esp8266 entry.

Select the latest version & then click on INSTALL button.

Image5

It takes a while to download & install .

 

Image 6

Once installation is over , close the IDE & start again,

Under Tools –> Boards you can now see a new list of ESP8266 Modules.

Image 7

Its time to test some example code.

While using the ESP module make sure that

Power source is 3.3v DC

CH_PD & RESET pins pulled HIGH through resistor.

You can use a development board available at

http://www.alselectro.com/wifi-esp8266-esp-12-demo-board.html

Image26

An LED is connected to GPIO4 through a resistor.

Image 22

An USB-TTL board is used to connect ESP with USB port of PC.

Rx of USB-TTL board goes to Tx of ESP board

Tx of USB-TTL goes to Rx (3.3v level) of ESP board

GND is made common.

5v of USB-TTL is connected to Vcc of ESP board.As the ESP board has a built in 3.3v regulator we can connect to 5v safely.

Connect the GPIO0 pin to GND.

IMG_20161107_080700

 

Open the Arduino IDE & select the COM port allotted to the USB-TTL board.

Other settings are done under Tools tab as seen in screenshot below :

Image23

From File —> Examples —> ESP8266 select the BLINK sketch.

As we’ve connected an LED at GPIO4 pin , change the pinMode & digitalWrite pin to 4.

Ensure that GPIO0 is connected to GND & click on UPLOAD button.

It takes a while to compile & then uploading starts.

Image25

Once the Uploading is done the LED connected at pin 4 , starts blinking.

Remember to upload another sketch, you need to ground GPIO0 and push the reset switch. The ESP8266 will be put in UPLOAD mode.

When the upload is done, the sketch will start running. If you reset with GPIO0 still grounded, the sketch will not start running because the ESP8266 will be in PROGRAMMING mode. To exit programming mode, remove the ground from GPIO0.

WATCH THIS VIDEO :

 

 

In the next post we shall see how to use the built in WIFI library in your code.

cooltext753793315   cooltext753790696

This post is a practical demo on controlling an LED from a browser.

Arduino ETHERNET SHIELD is used here. The Browser acts as a CLIENT & the SHIELD acts as a SERVER listening on HTTP PORT 80.

This demo is done on a Local Area Network .This means that the PC from where Browser is operated & the ETHERNET shield both are connected to the same NETWORK. You may have a Router in top of your Network.The Ethernet shield is connected to one of the RJ45 connector of the Router using a STRAIGHT Ethernet cable.The PC from where you start your browser is also connected to the same Router , to another RJ45 connecter or through WIFI , if your Router is WIFI enabled.

Once you connect the RJ45 cable to Ethernet shield, the left LED on RJ45 socket glows Green.This indicates a successful link made to Router.

 

IMG_20161030_153619

 

 

Image 5

Digital pin 2 is used to connect to an LED through a resistor.

Digital pin 13 is occupied by Ethernet shield , so the built in LED on pin13 cannot be used.

When the Ethernet shield is connected to the Router an IP address is allotted by DHCP of the Router.As it is Dynamic & keeps changing on every boot up , we assign the IP using the code :

byte ip[] = { 192, 168, 0, 150 };

Note that , this IP should be in the same range of your Network.

To know the range , Open Network sharing center

Click on your connection & then the DETAILS tab

Here you can see the Gateway IP & IPV4 of your PC.You should assign an IP in the same range

In my case the gateway IP is 192.168.0.1

So I’m assigning the IP of Ethernet shield by changing the last byte of the address , say, 192.168.0.150

Image 1

 

Here is the sketch used in this demo :

————————————————–

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 0, 150 }; // IP address in LAN – need to change according to your Network address
byte gateway[] = { 192, 168, 0, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port

String readString;
int ledPin = 2;

void setup(){

    pinMode(ledPin, OUTPUT); //pin selected to control
    // Test LED
    digitalWrite(ledPin, HIGH); // set pin high
    delay(500);
    digitalWrite(ledPin, LOW); // set pin low
   
    //start Ethernet
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();
}

void loop(){
    // Create a client connection
    EthernetClient client = server.available();
    if (client) {
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();

                //read char by char HTTP request
                if (readString.length() < 100) {

                    //store characters to string
                    readString += c;
                }

                //if HTTP request has ended– 0x0D is Carriage Return \n ASCII
                if (c == 0x0D) {
                    client.println("HTTP/1.1 200 OK"); //send new page
                    client.println("Content-Type: text/html");
                    client.println();

                    client.println("<HTML>");
                    client.println("<HEAD>");
                    client.println("<TITLE> ARDUINO ETHERNET SHIELD</TITLE>");
                    client.println("</HEAD>");
                    client.println("<BODY>");
                    client.println("<hr>");
                    client.println("<hr>");
                    client.println("<br>");
                    client.println("<H1 style=\"color:green;\">ARDUINO ETHERNET SHIELD — LED ON/OFF FROM WEBPAGE</H1>");
                    client.println("<hr>");
                    client.println("<br>");

                    client.println("<H2><a href=\"/?LEDON\"\">Turn On LED</a><br></H2>");
                    client.println("<H2><a href=\"/?LEDOFF\"\">Turn Off LED</a><br></H2>");

                    client.println("</BODY>");
                    client.println("</HTML>");

                    delay(10);
                    //stopping client
                    client.stop();

                    // control arduino pin
                    if(readString.indexOf("?LEDON") > -1) //checks for LEDON
                    {
                        digitalWrite(ledPin, HIGH); // set pin high
                    }
                    else{
                        if(readString.indexOf("?LEDOFF") > -1) //checks for LEDOFF
                        {
                            digitalWrite(ledPin, LOW); // set pin low
                        }
                    }
                    //clearing string for next read
                    readString="";

                }
            }
        }
    }
}

——————————————————————————

  The Arduino talks to Ethernet shield over SPI Serial Peripheral Interface. So to work with the shield you need to include both the Ethernet & SPI libraries in the top of the sketch.

#include <SPI.h>

#include <Ethernet.h>

 

The next piece of information is the MAC address of the shield , usually expressed as 6 bytes.

If your Shield has the address printed , use that MAC address.Otherwise you can settle for a random 6 bytes , as it is unlikely that another device of same address exists in the same network.

The MAC address is typically included in the Arduino sketch as global array of bytes.

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

The server is assigned on  HTTP port 80

EthernetServer server(80);

PIN 2 is assigned to LED & a string variable readString is assigned to store the request.

Under void SETUP

The method begin() in the Ethernet class attempts to connect to the Network using the details passed into its arguments.

Here we pass an IP address & the Ethernet shield makes a Network connection using a STATIC IP address.

Ethernet.begin(mac, ip, gateway, subnet);

server.begin()

starts listening on the HTTP port 80

To check the IP connection press WIN Logo key +R & then type in CMD

Ping the IP address of the Shield.

If you get back result , then you’re ready to connect the client.

Image 6

On computer Networks the machines or devices play 2 different roles : CLIENT & SERVER.

For e.g a web browser is a CLIENT that connects to other machines to request web pages or files.

The device or machine that serves the information is the SERVER.

SERVERs wait until a CLIENT connects & starts conversation with them.

PORTS allow different types of messages to be received by different pieces of software running on same server.For e.g Server software that accepts connection over FTP will usually run on port 21.WEB server software usually accepts connection over HTTP on port 80. In this demo we use he WEB SERVER.

Now open up the browser on a PC which is in the same network as Shield.

Type in the address 192.168.0.150

The following CLIENT REQUEST & SERVER RESPONSE happens in the background.

Client Request :

When you surf to the IP address of the Arduino server, the web browser (client) will send a request, such as the one shown below, to the server.

GET / HTTP/1.1\r\n

Host: 10.0.0.20\r\n

The information in the request will differ, depending on the browser and operating system that the request is sent from.

The \r\n characters that you see at the end of every line of text in the request are non-visible characters (non-printable characters). \r is the carriage return character and \n is the linefeed character (or newline character).

The last line of the request is simply \r\n without and preceding text. This is the blank line that the Arduino sketch checks for before sending a response to the client web browser.

In other words, the sketch reads every character from the above request and knows when the end of the request has been reached because it finds the blank line.

Server Response :

After receiving the request for a web page from the client, the server first sends a standard HTTP response and then the web page itself.

The response sent from the Arduino is as follows:

HTTP/1.1 200 OK\r\n

Content-Type: text/html\r\n

Connection: close\r\n

\r\n

Again the non-visible characters \r\n are shown in the above response.

The println() function in the the sketch automatically adds the \r\n characters to the end of each line. The empty println() function at the end of the HTTP response simply sends the \r\n with no text in front of it.

The above request and response are part of HTTP

Web Page

After the server has sent the HTTP response, it sends the actual web page which is then displayed in the browser.

The web page consists of text with HTML tags. You do not see the tags in the browser as these tags are interpreted by the browser.

The actual HTML markup tags are shown below.

————————————————-

<html><head>

<title> ARDUINO ETHERNET SHIELD</title>

</head>

<body>

<hr>

<br>

<h1 style="color:green;">ARDUINO ETHERNET SHIELD — LED ON/OFF FROM WEBPAGE</h1>

<hr>

<br>

<h2><a href="/?LEDON" "="">Turn On LED</a><br></h2>

<h2><a href="/?LEDOFF" "="">Turn Off LED</a><br></h2>

</body></html>

—————————————————–

In the Arduino sketch you can see these HTML tags sent using

client.println command

Now the browser displays the WEB PAGE sent as response from the Server.

Click on

Turn On LED   -  to see the LED going ON

Turn Off LED   – to make the LED OFF

indexOf String function is used to search for the string LEDON or LEDOFF.

The indexOf function returns a –1 if it doesn’t find the wanted string.This function is used to make the LED ON or OFF accordingly.

0Image 2

 

Image 3

 

Image 4

 

Instead of LED you can connect a Relay board & then control any home device through the contacts of the Relay.The above setup is the basic to start with Home Automation.

This demo is done on Local Area Network .It can be extended to Internet of Things through Port Forwarding & DDNS set up which is explained in another post.

 

 

This post is on retrieving particular Data from a web page using SIM900A & Arduino.

For e.g we shall retrieve the Blog Status hits of my blog in which you’re reading this.

We’ve to create an API link for this data so that data can be retrieved using SIM900A.

To create API link we use the THINGSPEAK.com website.

First let us read the XPATH details of the data wanted as below :

The procedure is related to Google Chrome WebBrowser

 

Image 1

 

Right click on the data to be retrieved & click on INSPECT .

 

inspect

 

A highlighted code will be displayed on which Right click & then select COPY  –> COPY XPATH

XPATH

 

The copied XPATH detail has to be used in THINSPEAK account to create the API link.

Open your thingspeak account & click on APPS –> THINGHTTP

 

thing1

Click on NEW THINGSPEAK to create a new “thing”.

thing2

 

You can provide a suitable Name for the App & under URL provide the website link from where you want the data from.

Method is GET & version is 1.1

thing3

 

Scroll down to bottom & under the PARSE STRING field paste the XPATH copied from the website.

thing4

Click on SAVE & you see the API LINK generated.

thing5

 

You can use this API link in your browser to confirm the data retrieved.

Image 15

Now let us see the practical application using SIN900A GSM & ARDUINO.

The connections between Arduino & GSM are :

Rx of GSM —> pin 8 (Tx) of Arduino   (since we use the SoftSerial in Arduino code , we declare pins 7 & 8 for Serial communication)

Tx of GSM –> pin 7 (Rx) of Arduino

GND –> GND

A separate power source is required for the GSM.

Following are the AT commands used

http

DOWNLOAD Arduino code HERE

————————————————————

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

void setup()
{
myGsm.begin(9600);
Serial.begin(9600);
delay(500);

myGsm.println(“AT+CGATT=1”);
delay(200);
printSerialData();

myGsm.println(“AT+SAPBR=3,1,\”CONTYPE\”,\”GPRS\””);//setting the SAPBR,connection type is GPRS
delay(1000);
printSerialData();

myGsm.println(“AT+SAPBR=3,1,\”APN\”,\”\””);//setting the APN,2nd parameter empty works for all networks
delay(5000);
printSerialData();

myGsm.println();
myGsm.println(“AT+SAPBR=1,1”);
delay(10000);
printSerialData();

myGsm.println(“AT+HTTPINIT”); //init the HTTP request
delay(2000);
printSerialData();

myGsm.println(“AT+HTTPPARA=\”URL\”,\”http://api.thingspeak.com/apps/thinghttp/send_request?api_key=VV7WQ9DS19E2BNNI\””);// setting the httppara,
//the second parameter is the website from where you want to access data
delay(1000);
printSerialData();

myGsm.println();
myGsm.println(“AT+HTTPACTION=0”);//submit the GET request
delay(8000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
myGsm.println(“AT+HTTPREAD=0,20”);// read the data from the website you access
delay(3000);
printSerialData();

myGsm.println(“”);
delay(1000);
myGsm.println(“AT+HTTPTERM”);// terminate HTTP service
printSerialData();

}

void loop()
{
}

void printSerialData()
{
while(myGsm.available()!=0)
Serial.write(myGsm.read());
}

—————————————————————-

AT+CGATT=1  enables the GPRS CONNECTION

AT+SAPBR is used to declare the Connection Type as GPRS

& Then the APN –Access Point Name of the mobile service provider is given.

An empty string also will work.Or you can slide the SIM into your Android mobile

under Settings –. More –> Cellular Networks  –> Access Point Names

you get the APN details

AT+SAPBR=1,1  enables the GPRS & APN settings & then HTTP is initialized with AT+HTTPINIT

HTTP parameters are then provided as “URL” & the API link we created earlier.

Note to use HTTP ( not HTTPS) in the link, as we use AT commands for HTTP only here.

AT+HTTPACTION=0 enables GET action

The GSM respons with

+HTTPACTION:0,200,12

Here 0 means GET action & 200 means OK , 12 bytes are retrieved.

If you get 600 instaed of 200 ,then it means a Network Error.

AT+HTTPREAD command is used to read the Data.

 

Image 11

cooltext753793315   cooltext753790696

 

A regular LCD requires a lot of wires (parallel interface) to be connected with a Microcontroller.The Serial LCD  backpack built on PCF8574 IC uses the I2C bus to convert  the parallel interface to a serial one.This needs only 2 wires SDA & SCL , apart from the power connections.

The I2C backpack can be soldered on to the LCD .It can be used for 16 x 2 , 16 x 4  &  20 x 4 LCDs that have HD44780 IC .

 

I2C

 

The blue preset is to adjust the contrast of the LCD. The black jumper on the left is to enable the Backlight of LCD. The I2C device has a HEX address by which a microcontroller can communicate with it.This is set by the 3 bits A0,A1 ,A2 .If no jumper is present , it is HIGH &  a jumper means LOW. By default all the 3 jumpers are open . ie., A0,A1 A2 all are 1s.

By setting this address lines you can connect upto 8 devices to the same I2C bus.

Eight programmable slave addresses possible using these three address pins.

 

I2CLCD

The I2C bus has 2 bidirectional active wires SDA & SCL .They are joined to positive supply through a pull up resistor of 4k7.When the bus is  idle both lines are pulled high.

The expanders can be configured to have a unique 7 bit address. The first 4 bits are factory configured to

0100 for PCF8574/PCF8574T

0111 for PCF8574A

The lower 3 bits are settings on device pins A2,A1,A0.

The eighth bit specifies whether the following data is a Read  or Write operation.

Following table describes how the address is arrived.By default the factory setting is A2,A1,A0 all open leading to all 111.

First 4 bits are factory set to 0100 for PCF8574T/PCF8574 .If the port expander IC is PCF8574A , the first 4 bits will be 0111.

For calculating the address a 0 is added at the MSB (R/W bit not taken into account for calculation)

Hence the default I2C address of the module is HEX 0x27 .

 

ADDRESS

 

jumper

 

Now let us see how to use this backpack with Arduino UNO.

To start with download the latest Library from this link :

https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads

NewliquidCrystal_1.3.4 is the latest file at the time of writing this blog

lib1

Unzip the downloaded file & copy the folder NewliquidCrystal.

Paste this folder into your Arduino libraries folder.

Generally the path is C:\ProgramFiles\Arduino\libraries

 

lib2

 

lib3

Now open the Arduino IDE (make sure your Arduino IDE is the latest version).

Under File –> Examples , you can see the NewliquidCrystal

lib4

 

To know the I2C address of the device there is a scan code in Arduino forum.

Before starting the test , make sure that the I2C back pack is soldered properly on to the LCD.Here we make use of a 16 x 2 LCD.

Connections between Arduino & I2C LCD  are done as below :

CONN

 

Upload the scanner code on to the Arduino. Open the Serial monitor & set the baud rate to 115200.

The code scans for the I2C devices & lists the address in HEX format.

In our test we’ve connected a backpack I2C with no jumpers on A2,A1,A0 , which results in 0x27

This is the Slave address of the device.

scan1

 

The LCD Library & some sample code can be downloaded from :

http://www.alselectro.com/files/Library_codeexamples.zip

 

Once the connections are made, open the Arduino IDE .Make sure that you use the IDE later than 1.6.0 version.

The Hello world sketch includes 2 header files – wire.h &  LiquidCrystal_I2C.h

A new object named lcd is instantiated using the constructor LiquidCrystal_I2C which takes parameters 0x27,2,1,0,4,5,6,7

Here 0x27 is the slave address of I2C backpack.

 

eg1

The next parameter 2 represents P2 pin of PCF8574 which is connected to EN of the LCD.

The parameter 1 is the P1 pin connected to R/W of LCD.

The parameter 0 is the P0 pin connected to RS of LCD.

4,5,6,7 are the 4 data pins connected to D4,D5,D6,D7 of LCD.

Inside setup , lcd.begin(16,2) ;   initializes the 16 x 2 LCD .Then the lcd.setBacklightPin(3,POSITIVE);

makes the P3 pin makes the P3 pin to control the backlight of LCD.

lcd.setBacklightPin(HIGH);  makes the P3 pin go High, which turns on the NPN transistor.This provides GND to the LED pin of LCD As the other LED pin is already connected to Vcc through the jumper , the LCD backlight glows.

lcd.home(); takes the cursor to 1st column , 1st Row of LCD.

lcd.print() prints the message.

lcd.setCursor(0,1); takes the cursor to 1st Column , 2nd Row. Make note that the counting starts from 0.

The following is the connection diagram between PCF8574 IC & the LCD .Once you solder the backpack on to LCD, these connections come into effect.

 

Image 2

 

 

Image 3

 

The next sketch is lcd_serialprint.

This code waits for you to type in message in the serial monitor of Arduino & then displays it on the LCD.

 

eg2

 

Next code shows the capability of connecting more than 1 device to the same I2C bus.

2 LCDs are connected to the same I2C bus A4,A5 of Arduino.External power source is used as Arduino can’t source power to both LCDds.

The backpack connected to 16 x2 LCD has no jumpers soldered to A0,A1,A2 .Hence the address is the default 0x 27.

jumper

The backpack connected to 20 x 4 LCD has A0 pin soldered, which makes the address 0x26.

By initiating the LCDs with their slave address, messages can be displayed on to the correct slave LCD.

eg3

 

 

VIDEO TUTORIAL :

 

 

 

cooltext753793315   cooltext753790696

ethernet1

 

Watch this support Video :

 

The Arduino board can be connected to the Internet using this Ethernet Shield which is based on the

WIZNET W5100 Ethernet chip . The Wiznet W5100 provides a network (IP) stack capable of both TCP and UDP.

WIZNET W5100 is the classic one , widely used by Arduino.CC .

WIZNET W5500 is used by Arduino.ORG & is referred as Ethernet shield 2.

We shall use the classic Ethernet shield W5100 in this post.

The shield has long pin headers to plug on the Arduino (UNO or MEGA). Other shields can be stacked on top of this board.There is an onboard micro-SD card slot, which can be used to store larger files.

The Ethernet Library is used to write sketches which connect to the internet using the shield. You need not download the library , as it is inbuilt in Arduino IDE.

The on-board micro SD card reader is accessible through the SD Library. Both the SD card reader & Ethernet board work on SPI bus .

The shield also includes a reset controller, to ensure that the W5100 Ethernet module is properly reset on power-up.

This board is different from the economy version using ENC28J60 device.The library for this ENC is different , ETHERSHIELD library hosted by NANODE project.Libraries are different for WIZNET board & ENC board.

Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega.

On both boards, pin 10 is used to select the W5100 and pin 4 for the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, 53, is not used to select either the W5100 or the SD card, but it must be kept as an output or the SPI interface won’t work.

As the W5100 and SD card share the SPI bus, only one can be active at a time. If you’re not using one of the peripherals in your program, however, you’ll need to explicitly deselect it. To do this with the SD card, set pin 4 as an output and write a high to it. For the W5100, set digital pin 10 as a high output.

The shield provides a standard RJ45 Ethernet jack.A straight RJ45 cable is used to connect the shield to the Router.

A RESET  button is on the shield which resets both the W5100 and the Arduino board.

The shield contains a number of informational LEDs:

  • PWR: indicates that the board and shield are powered
  • LINK: indicates the presence of a network link and flashes when the shield transmits or receives data
  • FULLD: indicates that the network connection is full duplex
  • 100M: indicates the presence of a 100 Mb/s network connection (as opposed to 10 Mb/s)
  • RX: flashes when the shield receives data
  • TX: flashes when the shield sends data
  • COLL: flashes when network collisions are detected

Apart from these LED s , there are 2 more LEDs seen below the RJ45 jack.When Ethernet cable is inserted from a working Router , you can see these LEDs glowing below the RJ45 jack, one glows steadily & the other blinks as per data flow.

The examples in this section will all make use of the Arduino Ethernet Library.This library comes with Arduino, so no downloading or installing required

You can see the examples under File –> Examples –> ETHERNET

eth1

 

The Ethernet library allows the Arduino to turn into one of two Ethernet devices: a client or a server. Turning your Arduino into client allows you to connect to and request data from servers.

Another  example included with Arduino’s Ethernet library is WebServer.  This sketch sets up the Arduino as a server device, and hosts up a webpage whenever a client connects to it. The webpage is simple – it shows the status of the analog pins.

Open the WEBSERVER sketch

Webserver is a simple sketch which will display on a web browser, the data gathered from the analogue inputs. However don’t upload it yet, it needs a slight modification.

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

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

eth5

 

You can alter it to match your own setup. For example, in my home the router’s IP address is 192.168.1.1, the pc is assigned 192.168.1.6 , the tablet is assigned 192.168.1.3  , .. As the IP address is in the range 192.168.1.xxx , I just leave this to 192.168.1.177

You also have the opportunity to change your MAC address.As we use only one shield , we can leave this as it is.

To know the IP address , go to Control panel –> Network & Internet –> Network & Sharing Center

Click on your Internet connection .On the next window click Details to see the IPV4 address of your PC.

eth3

 

 

eth4

 

You can also use a IP SCANNER tool to know all the IP address allotted by your Router

http://www.advanced-ip-scanner.com/download.php?lng=en

eth7

 

Now upload the sketch to your Arduino.

Open your web bowser & type in the IP address 192.168.1.177:80 , the port address 80 is default for HTTP.Hence you need to type just the address 192.168.1.177 in the URL bar ,skipping the :80 part.

The web browser will query the ethernet shield, which will return the values from the analogue ports on the Arduino board.As such we’ve not connected anything to the Analog pins of Arduino, you get random values refreshed every second.

 

eth6

 

Remember , this is from a local browser & not from outside world.If you like to see the webserver from anywhere in the world , you need to PORT FORWARD your Static IP address to this local IP address 192.168.1.177 .This is set inside the Router’s configuration.

If your IP is not Static (mostly Dynamic which changes on every reboot) , you need to register with a service like www.noip.com

For more details of port forwarding , consider reading this post & video

https://alselectro.wordpress.com/2015/07/04/port-forwarding-part-2-solution/

https://www.youtube.com/watch?v=CyjWgqS8z2w

 

A simple sketch to print out the Gateway IP, IP of your Ethernet board, DNS is given below :

//<code>

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

byte mac[] = { 0x00, 0xC3, 0xA2, 0xE6, 0x3D, 0x57 };

void setup() {

Serial.begin(9600);
while (!Serial);
Serial.print(“Establishing network connection… “);

if (Ethernet.begin(mac) == 0) {
Serial.println(“FAILED!”);
}
else {
Serial.println(“OK!”);

Serial.print(“IP Address: “);
Serial.println(Ethernet.localIP());

Serial.print(“Default Gateway: “);
Serial.println(Ethernet.gatewayIP());

Serial.print(“Subnet Mask: “);
Serial.println(Ethernet.subnetMask());

Serial.print(“DNS Server: “);
Serial.println(Ethernet.dnsServerIP());
}
}

void loop() {
}

//</code>

 

Upload the sketch & open the Serial monitor to see the result.

ETH9

 

Example Sketch 2 : Display a web page from Arduino

 

———————————

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177); // change IP address according to your network
EthernetServer server(80);  // create a server at port 80
void setup()
{
Ethernet.begin(mac, ip);  // initialize Ethernet device
server.begin();           // start to listen for clients
}

void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {        // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {   // client data available to read
char c = client.read(); // read 1 byte (character) from client
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == ‘\n’ && currentLineIsBlank) {
// send a standard http response header
client.println(“HTTP/1.1 200 OK”);
client.println(“Content-Type: text/html”);
client.println(“Connection: close”);
client.println();
// send web page
client.println(“<!DOCTYPE html>”);
client.println(“<html>”);
client.println(“<head>”);
client.println(“<title>Arduino Web Page</title>”);
client.println(“</head>”);
client.println(“<body>”);
client.println(“<h1>Hello from Arduino!</h1>”);
client.println(“<p>A web page from the Arduino server</p>”);
client.println(“</body>”);
client.println(“</html>”);
break;
}
// every line of text received from the client ends with \r\n
if (c == ‘\n’) {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != ‘\r’) {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1);      // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
}
———————————————————

RF ID with Arduino

 

RF ID is Radio Frequency Identification which is used to make track of every physical object.

The frequency of operation widely used at present are LF –Low Frequency 125 KHz & UHF (Mifare) 13.5MHz.

In this post our focus is on 125KHz RF ID.

The main components of the RF ID system are :

1) The RF ID Reader  – EM-18 type of RFID reader is used for demo in this post.

2) RF ID tag – The Tag contains an Integrated circuit for memory & an Antenna coil.

         There are 2 types of Tags – Passive & Active. We make use of Passive tags here .As the name implies these tags do not have a power source .When the passive Tag is near a RF ID reader , the energy is induced by electromagnetic waves.The tag “wakes up” & responds by sending the data stored in its memory. The RANGE of passive tag access is below 10 cm.

Active tags have their own battery source & offer a long range of access.Active tags are costlier than the passive ones.

rfid2

 

Tags are available in different Encasements.Widely used are the Visiting card type tags.

If you remove the cover of this tag you can see a Microchip & an Antenna coil.

The Antenna coil may be in Rectangle or a Round shaped as seen in fig. below :

Image 7

The Microchip is CMOS IC EM4102 manufactured by the company EM MicroElectronic.

These chips have internal rectifier & filter to convert Electromagnetic waves from RFID reader to DC power required for its operation.While in vicinity of a RFID reader the tag responds by sending information contained in the factory programmed memory array.

These EM type tags are READ ONLY & you can’t write your own data on it. For Read & write operation consider using Mifare tags at 13.5MHz.But remember that an EM tag can be Read by an EM RF ID Reader only .

 

Image 3

 

The EM-18 RF ID Reader too has an inbuilt antenna coil .When power is applied , the reader generates an electromagnetic field which is induced by the antenna present inside the tag.

The EM-18 reader provides 2 types of data

1) WIEGAND Formatted (EM26 bit version) DATA at pins Data 0 & Data 1

WIEGAND Protocol :

Uses 3 wires : GND , DATA 0 (Data Low) , DATA 1 (Data High).

When data lines are idle , the lines are at logic high (+5v). When binary 0 is being sent , DATA 0 wire will move from High to Low , while Data 1 remains High.

When binary 1 is sent , DATA 1 will move from High to Low , while Data 0 remains High.

2) TTL level RS232 Format Data at 9600 baud (UART TTL interface) on pin TXD.

Here we concentrate on RS232 data , as the UART output at TXD pin can be directly interfaced with a Microcontroller.

Pin configuration of EM-18 RFID module is as seen in fig. below :

rfid2

 

For card detection response, a mini buzzer is used .This is driven by a PNP transistor  connected at the BUZZ pin of the reader. When a card is detected this BUZZ pin goes LOW making the transistor conduct.The LED will glow along with the buzzer sound.

This detector response circuit is built on a base board , over which the EM-18 module is plugged on.

Image 3

 

Understanding the code printed on RF ID Tags :

tag

 

The tag has a 10 digit Decimal number printed followed by  8 digit number.Most of the RFID readers convert this 10 digit Decimal to HEX value & output at the TX pin.

To see the actual output we upload an empty code on to Arduino

void setup() {}

void loop() {}

Now the boot loader of Arduino is by passed & the Serial monitor of Arduino can be used as a Hyper terminal to read the serial port.

After uploading the empty code connect Tx of RFID reader to Tx (pin1) of Arduino.  +5v of RFID  to  +5v of Arduino , GND to GND.

Remember that this connection is Tx to Tx  (not Reverse).

usb

 

Open the Serial monitor of Arduino . Show the tag near the reader.

The decimal number printed on Tag 0006907246  is printed in Hex as  100069656E72

 usb2

To verify, open the calculator of windows &  set View – > Programmer mode.

Select Dec option & feed in the Decimal code seen on the card 0006907246 .

Now select the HEX to get the HEX value result.

calc1

 

But in Arduino serial monitor the hex code displayed is 12 bytes of data –>    1000 6965E 72

The trailing value 72 is the XOR value of check sum.

( 10 || 00 || 69 || 65|| 6E = 72 )  .Use the windows calculator  to arrive at the checksum. || represents XOR function.

The leading 10 is the START byte ,which varies according to card manufacturers.

This 12 bytes of data displayed on Arduino serial monitor is used in the code later, to compare the tags & identify the “ wanted tag”.

Further if you calculate the decimal conversion of 69 , you get 105

Decimal value of 656E is 25966 . This 105, 25966 is the last 8 digits you see on the tag.

calc2

 

calc3

 

Now we shall connect a Servo motor to Arduino .When “wanted Tag” is identified ,the servo is given a pulse to operate.By this way we can control a door lock connected to the Servo arm .When correct TAG is shown , the Servo operates to open & close the door lock.

It is suggested to use a separate power source for the Servo & Reader.Your Arduino cannot source enough power to both.

A dual 5v supply source is used in this demo.

Connect the Vcc of RFID to 5v of Power source &  Gnd to Gnd.

The Tx of RFID is connected to Rx of Arduino . Note that the connection now is reverse (Tx –> Rx).

Remember to disconnect this pin while uploading the Code.

A Servo motor is attached to PWM pin 9 of Arduino.The power is supplied from 5v of Power Source & Gnd to Gnd.

The GND of Power source must be connected to GND of Arduino.

Generally all Servos have 3 wires , the center one always RED , is connected to +5v .

Servo-Motor-Connector      ServoJR

 

The Brown or Black wire is GND.

The Orange or Yellow  wire is the Signal wire , which is connected to pin 9 of Arduino.

 

rf2

Upload the following code to Arduino. Always remove connections at Rx/Tx pins of Arduino while uploading code.

——————————————————–

char tagOk[] ="100069656E72"; // Replace with your wanted Tag ID
char inputTag[12];        // A variable to store the Tag ID being presented

#include <Servo.h>      // include the Servo library
Servo myServo;             // create an instance object myServo of Class Servo

void setup()
{
Serial.begin(9600);    //begin serial communication at baud 9600
myServo.attach(9);    // attach servo at pin 9  
myServo.write(0);      // initial position of servo at angle 0 
}

void loop()
{
  if (Serial.available()){
   
  int count = 0;
      while(Serial.available() && count < 12) {
         inputTag[count] = Serial.read();
         count++;
         delay(10);
         }
      Serial.print(inputTag);
      int compare = 1;
      compare = (strncmp(tagOk, inputTag,12)) ; // if both tags are equal strncmp returns a 0
      if (compare == 0){
         Serial.println( "   TAG OK  ");
        myServo.write(180);
        delay(2000);  //  delay of 2 secs  a must for servo to respond
        myServo.write(0);
       delay(100);
        Serial.println("…..door.open..");
          }
      else Serial.println (" TAG Not recognized ");
     
       }
      
}

————————————————-

After uploading the code , show the Tag near the Reader.If the correct tag is shown , the Servo will respond & open the door for a moment & close again.

Touch Screen TFT Shield for Arduino Uno

The 2.4″ Colour TFT display with micro SD card slot is now available as a SHIELD for Arduino UNO.

It has a four wire resistive touch screen, a micro SD card socket,a reset switch and a convenient arduino Uno shield footprint.

Specifications:

2.4 inch LCD TFT display has Bright, 4 white-LED backlight .
Colorful, 18-bit 262,000 different shades
4-wire resistive touchscreen
240 x 320 resolution
Spfd5408 controller with built in video RAM buffer
8 bit digital interface, plus 4 control lines
Uses digital pins 5-13 and analog 0-3. Digital pins 2, 3 and analog 4 and 5 are available  for user defined purpose.. Pin 12 is available if  micro SD is not used.
5V compatible, can be used  with 3.3V or 5V logic
Size: 71 x 52 x 7mm

lcd2

 

lcd1       lcd5

 

For using this shield with Arduino we need a suitable library.The preinstalled TFT library that comes with the Arduino IDE uses SPI interface.

As SPI is slow for a screen size of 2.4” , this LCD uses parallel interface,though more pins are required.

LCD panel takes eight I/O pins ( 8-bit parallel data bus )  LCD_D0 to LCD_D7.

SD card needs another four — select, DI data in, DO data out and SCK  data clock.

But the LCD panel needs another five pins (RST,CS,RS,WR,RD) to control the eight-bit data bus, taking up five of the six analog I/O pins. So in the end, there’s just one analog I/O and two digital I/O pins left for other uses in your project

ADAFRUIT is the only TFTLCD library available.In this demo I’ve used the Adafruit library , as well as the modified library from

  http://www.smokeandwires.co.nz/blog/a-2-4-tft-touchscreen-shield-for-arduino/ 

 

Download the following libraries :

1. Modified TFT SHIELD Library from Smoke and Wires

https://github.com/Smoke-And-Wires/TFT-Shield-Example-Code/archive/master.zip

Extract the downloaded zip file & copy the folder named SWTFT-Shield  to the Arduino Libraries.

 

2. Adafruit GFX graphics core library, this is the ‘core’ class that all  other graphics libraries derive from

https://github.com/adafruit/Adafruit-GFX-Library/archive/master.zip

Rename the uncompressed folder as  Adafruit_GFX .It has a .cpp & a .h file .

Ensure that the Library folder name and the file names of .cpp & .h files inside the folder are the SAME.

If the name of the folder is different (even if you leave out the underscore) Arduino won’t recognize the keywords from the library.

 

3.Arduino library for 4-wire resistive touchscreens

https://github.com/adafruit/Touch-Screen-Library/archive/master.zip

Rename the uncompressed folder as TouchScreen.

 

Copy these 3 folders to C:\ProgramFiles\Arduino\Libraries

lcd4

 

You can download the library with all examples and bitmap image samples from HERE .

Unzip the downloaded folder & copy the 3 folders to libraries folder as seen in image above.The images inside the bitmap_images folder should be copied to the ROOT of Micro SD card.Do not copy as folder.Copy and paste inside SD card only the bitmap images.

 

—————————

Fix the LCD SHIELD on to the Arduino UNO carefully matching the pins.

       lcd6

Connect the USB cable to PC & open the Arduino IDE. Feed in the COM port allotted & select the board type as UNO.

Under File—>Examples –> SWTFT-Shield

you can see 4 sample codes for testing.If you do not see this under examples , check your Arduino Libraries directory for the folder SWTFT-Shield.The folder name  must be the same as that of the .cpp & .h files .

Let us test the sample examples now.

           LCD7

1. Load the sample code “graphicstest” on to the Arduino.

You can see the screen color changes and graphics display effect on LCD.

IMG_20141127_220854311      IMG_20141127_220903214

 

2. Now upload the second file “rotationtest

 

Open the Serial monitor of Arduino IDE & select Baud Rate as 9600  & New Line at the bottom .

On clicking on the Send button you can see Line,circle,dotted circle & Text at corners of the screen.Every click displays at corners of the screen one by one.

 

lcd8

 

     IMG_20141127_221019436             IMG_20141127_221043195

 

3. Now let us test the 3rd example “ttfbmp

It takes any 320-pixel wide 24-bit BMP image located in the root of the MicroSD card, loads it up & displays it.

Save any bitmap image BMP from your PC on to a Micro SD card using card reader.Make sure that the .bmp FILE SIZE does not exceed 250KB.You can make use of PC application like IRFANVIEW to resize the image & save as .bmp file of required size.If the file size is large “File not found” error will be the response.

Slide the Micro SD card into the slot at the back of the shield.

Load the 3rd example “ttfbmp” & see the result on the LCD screen.

 

IMG_20141128_081644380 

 

IMG_20141128_081653823

IMG_20141128_081703487

 

4. Now upload the 4th example “ttfpaint “

Color pattern with 6 colors appear horizontally on the left side of screen.You can pick any color and draw or write on the touch screen.Do not use any sharp object to write as it will damage the screen.Use a round edge stick and apply nominal pressure to write on screen.

 

IMG_20141127_220546623

 

Let us test a modified example to write on LCD screen from the Serial monitor of Arduino.

Upload the following code on to Arduino.

——————————————–

#include <Adafruit_GFX.h>    // Core graphics library
#include <SWTFT.h> // Hardware-specific library
char dataRx;

// Assign readable names to some common 16-bit color values:
#define    BLACK   0x0000
#define    BLUE    0x001F
#define    RED     0xF800
#define    GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

SWTFT tft;

void setup(void) {
  Serial.begin(9600);
  Serial.println(F("Type character in Arduino Serial port"));
delay(1000);

  tft.reset();

  uint16_t identifier = tft.readID();

 
  tft.begin(identifier);

  tft.fillScreen(BLACK);

  Serial.println(F("This is a serial data send Test!"));
  Serial.println(F("Type character in Arduino serial port & press <SEND> "));
}

void loop(void) {
 
    while (!Serial.available());
    dataRx=Serial.read();
    tft.setTextColor(YELLOW);
    tft.setTextSize(2);
tft.print(dataRx);
   
    }
————————————————————–

Open the Serial monitor .

Image 4

 

Type in some character & click on Send button.

You can see the characters displayed on the LCD screen.

IMG_20141128_081426269

 

 

Contact for availability of this TFT Shield :

 

cooltext753793315    cooltext753790696

LOGO2

Stepper motors are not like simple DC motors and cannot be driven by providing just DC voltage.Driver circuit & a microcontroller  are needed to control the speed & direction of a stepper.

With a stepper motor you can “step” exactly a given angle. Further the stepper motor has the   advantage of having a holding torque.Steppers are able hold their position when they are not moving.

Stepper motors are available in two varieties : unipolar or bipolar.

Bipolar motors are the strongest type of stepper motor and usually have four leads. They have two sets of electromagnetic coils internally, and stepping is achieved by changing the direction of current within those coils.

Unipolar motors, identifiable by having 5,6 or even 8 wires, also have two coils, but each one has a center tap. Unipolar motors can step without having to reverse the direction of current in the coils, making the electronics simpler. However, because the center tap is used to energize only half of each coil at a time they typically have less torque than bipolar.

Unipolar motors typically have two coils per phase, one for each direction of magnetic field.

Bipolar motors typically have one coil per phase, and current flows in both directions through this coil. Thus,  the bipolar motor will be able to produce twice as much torque, since at any given time, the unipolar motor is only using half of its windings

 

stepper2

 

 

stepper3

 

BIPOLAR steppers generally have 4 wires & are best driven by a H BRIDGE IC like L293 (500 ma current) or L298 ( 2 amps).

One thing you’ve to keep in mind is that when using a stepper driver, you are powering the driver, not the motor. The driver will take over powering the motor for you.

To find out the phase of coils in a 6 wire Stepper , we shall make use of a simple Multi meter.

Put one lead of Meter on any of the 6 wires of Stepper & look out for continuity with other 5 wires.You can find 2 sets of 3 wires having continuity .

 

stepper_find_coils

As seen in above screenshot , keeping one end of meter probe on any of the wires you can identify the continuous wires.The meter will show some resistance value if there is a continuity.

Identify the set of 3 wires & make a knot to separate the 2 set of 3 wires.

 

stepper_end_coils

 

Now you can easily identify the center tap of the 3 wires.With respect to the center tap wire the other ends show an equal resistance value.

Here the green wire of one set of 3 wires is the center wire & it shows exactly half the value of total resistance with other 2 wires of the coil .

On the other set of 3 wires , the black wire is the center one.

To use this motor as a Bipolar one , simply leave out the center wires (here it is the green & the black ones).

Now each phase of coil has only 2 wires , which can be easily driven by a H bridge IC L298.

 

stepper_center_tap

 

 

Leave out the 2 center tap wires & then connect the 2 sets of wires to M1,M2  &  M3,M4 of the L298 board.M1/M2 is for first coil & M3/M4 for the second coil.

 

stepper_connect_motor

 

We shall make use of an Arduino UNO board to control the Stepper .

An external power supply of 12v/1Amp is required for the L298 board.If you try to power the L298 from Arduino it will cause damage to  your Arduino.

Following is the code to be uploaded on to Arduino. Before uploading , we shall understand the code so that the connections are made accordingly between Arduino & L298 board.

—————————————————

#include <Stepper.h>

int clockwise= 2;
int anticlockwise= 3;
int steps =200;
int enable=8;
Stepper motor(steps, 10,11,12,13);

void setup() {
pinMode(clockwise,INPUT);
pinMode(anticlockwise,INPUT);
pinMode(enable,OUTPUT);
Serial.begin(9600);
}

void loop() {
int Speed = analogRead(A0);
int RPM = map(Speed, 0, 1023, 0, 100);
int forward = digitalRead(clockwise);
int reverse = digitalRead(anticlockwise);
digitalWrite(enable,LOW);
if(forward == 1 && reverse == 0 && RPM > 5){
digitalWrite(enable,HIGH);
motor.step(1);
motor.setSpeed(RPM);
delay(10);
}
if(reverse == 1 && forward == 0  && RPM > 5){
digitalWrite(enable,HIGH);
motor.step(-1);
motor.setSpeed(RPM);
delay(10);
}
delay(5);
Serial.println(“Speed of motor is “);
Serial.println(RPM );
}

————————————————————

Initially we’re including the Stepper library  Stepper.h.

An instance called “motor” is initiated for the Stepper class, with Steps = 200 (generally step angle of Stepper is 1.8 deg.For a full rotation of 360 deg we need 200 steps 200 x 1.8  = 360).

Pins 10,11 of Arduino assigned to control coil 1 & connected to IN1,IN2 of L298.

Pins 12,13 of Arduino assigned to control coil 2 & connected to IN3,IN4 of L298 board.

Two push switches are used to control the direction of Stepper.One switch is connected to pin 2 (clockwise) & the other one to pin3 (anticlockwise).The connections are made so that when a switch is pressed , a HIGH (5v) is applied to Arduino pins 2 or 3 accordingly.

The speed of Stepper is controlled by a 10k potentiometer which is connected to A0 of Arduino.The analog value of potentiometer is mapped to a value between 0 and 100 & assigned to a variable RPM.

According to the conditions of Switches (clockwise or Anticlockwise)  & RPM set by the potentiometer the Stepper will move accordingly.

 

Important point to take note:

Pin 8 of Arduino is assigned to ENABLE ,which is connected to both EN1,EN2 of L298 board.While starting the loop Enable is made LOW & it’s made HIGH only when a switch is pressed.This ensures that the Stepper is not enabled at idle conditions.If you’re not controlling the ENABLE pin , the L298 IC will heat up even when the Stepper motor is not running.This will damage the L298 IC and the Stepper motor , as well.

 

Image2

 

Connection Details

L298 BOARD              Arduino Board

EN1 & EN2   —–>    8

IN1              —–>   10

IN2             —–>     11

IN3             —–>     12

IN4              —–>     13

M1/M2  —  2 wires of first coil of stepper.

M3/M4  —  2wires of second coil of stepper.

CW switch     —–>    2 ,  one end of switch connected to +5v, other end grounded through 10k .

CCW switch     —–>   3

12V/1A adapter connected to GND/12V of L298

Both GND pins of L298 & Arduino made common

10k Potentiometer – center pin to A0 , top pin to +5v & bottom pin to GND

 

Watch this support Video :

 

BIPOLAR Stepper control with HBRIDGE

 

www.alselectro.com

 

cooltext753793315    cooltext753790696

Generally in Embedded programming you create the HEX file after compiling the C code .This Hex file is fused on to the Microcontroller for use in applications.For e.g for a PIC microcontroller you use MPLAB IDE to build the HEX file from C code .

But in case of Arduino , you may not even know that the IDE is generating a HEX file.The process is hidden and you just Compile & simply Upload.

If you’re using Proteus  Design Suite for simulation of Arduino , you need to use the HEX file .Here is how to retrieve the HEX file generated by Arduino IDE.

Open the Arduino IDE & go to File –> Preferences

prob6

 

Check mark the box against “Show verbose output during Compilation” & click OK.

Verbose output will print debugging messages.It will print the complete command line of each external command executed as part of the build process.

prob7

 

Open the sketch to compile.

Now instead of simply clicking on the Tick mark to Verify  press

 

SHIFT  +   Image 1       or        CTRL+  Image 1

 

Image9

Now you can see the build process messages at the bottom of the IDE (black area for messages).

The last but one line before Binary sketch size is the path to the HEX file.

 

prob9

Here the Path is

  C:\Users\UserName\AppData\Local\Temp\buildxxxx.tmp\Blink.cpp.hex

 

Image 10

 

Image 11

Copy the HEX file & store in a different location to use in Proteus.In upcoming posts we shall see how to install Arduino inside Proteus & link this Hex file for Simulation.