Arduino UNO Pinout and Arduino Mega Pinout (Best Tutorial 2019)

Arduino UNO Pinout

Arduino UNO Pinout and Arduino Mega Pinout or GPIO Pins

Now that you are familiar with the Arduino IDE and how to create, edit, and upload a program, this blog will now turn your focus to the HW. You'll get a chance to learn how to connect to and access the capabilities of the general purpose input/output (GPIO) pins from the SW. 

 

This tutorial explains the Arduino UNO Pinout and Arduino Mega Pinout with best examples. Each Arduino board has a different set of GPIO pins, so in this tutorial, we provide details on the GPIO pins of Arduino UNO.

 

In this blog, I'll start by explaining the GPIO pins, what they can and can't do, and then show you how to make Arduino access the outside world with the help of some very basic circuits and very simple programming examples.

 

The GPIO capability of Arduino

Arduino was built to access the outside world. Much of that access is through the GPIO pins. Each Arduino board has a different set of GPIO pins, so in this section, I'll provide details on the GPIO pins available on the most common variant of Arduino: Arduino Uno.

 

Then, I'll also document the additional capability of the Arduino Mega. Finally, I'll show the GPIO capability of a more limited Arduino: Arduino FLORA.

 

First, let's focus on the Arduino Uno, Powering on Arduino, the Arduino Uno comes with a set of 14 digital and six analogs I/O pins, along with some additional pins to provide power and serial I/O.

 

 Fortunately, the pins are actually well labeled on the board itself. The following table shows a list of pins that are available and a brief description of what each pin can do, starting at the upper-right side of the board and going clockwise.  The Mega provides a bit more from an I/O pin perspective.

 

You'll first notice that the pins on the left side of the Arduino Mega are labeled the same as with the Arduino Uno. And they do have the same functionality. However, you'll also notice some additional pins on the right side of the board.

Arduino Mega Pinout

The first external hardware connection

Now that you are aware of all of the GPIO capabilities, you can start putting them to work. In order to do this, it is best to purchase a small breadboard and some jumper wires; this will make connecting to the outside world easier.

 

They are easy to find. You can purchase one at almost any electronics store or on any online electronics site. The jumper wires you want are male-to-male solderless jumper wires.

 

These jumper cables plug easily into the header pins on the Arduino Uno or Mega and the breadboard. If you are working with FLORA, you will want to purchase some alligator clip style wires. These will make connecting to FLORA easy.

Arduino Mega Pinout GPIO

There are also many starter kits which come with breadboards and jumper cables, along with additional sensors and HW capabilities that you can use with your Arduino board.

 

There are too many to list here; simply search Arduino starter kits on the Internet and you'll get an idea of the many choices. Just make sure they come with a breadboard and male-to-male solderless jumper wires.

 

Your first project will use the digital I/O pins to light up an LED. To do this, you'll need to gather two more hardware pieces. The first is a light emitting diode (LED).

 

This is a small part with two leads that lights up when a voltage is applied to it. They come in a wide variety of colors. If you want to buy them online, search for a 3 mm LED. You can also get them at most electronics shops.

 

You'll also need a resistor to limit the current to the LEDa 220-ohm resistor would be the right size. Again, you can get them online or at most electronics shops. If you get three LEDs and three resistors, you can exercise several of the digitals I/O pins.

 

Now that you have all the bits and bobs, let's build our first hardware project. Before you plug anything in, let's look at the breadboard for a moment so that you can understand how you are going to use it to make connections.

 

You'll be plugging your wires into the holes on the breadboard. The holes on the breadboard are connected in a unique way to make the connections you desire. In the middle of the board, the holes are connected across the board. So, if you plug in a wire, and another wire in the hole right next to it, these two wires will be connected.

 

The two rows on each side of the board are generally designed to provide power, so they are connected up and down.

So, let's place the electronic parts on the breadboard. Place the LEDs so that one wire is on one side of the middle split of the breadboard. The direction of the LED is important; make sure the length of the two wires is on the left side of the hole.

 

Now, place the resisters on the holes on one side. The direction of the resistor does not make any difference, but make sure the second wire lead is placed in the row of holes at the end of the board. These will all be connected together and will be connected to the GND of your Arduino using one of the jumper cables.

 

Finally, use jumper wires to connect the digital I/O pins 13, 12, and 11 to the holes on the breadboard. Now that the HW is configured correctly, you'll need to add code to activate the LEDs.

 

The Arduino IDE and LED code

In this code, setting led 13 lit the orange LED on the board. It turns out that the led output pin 13 is also the connection to pin 13 on the connector of the Arduino Uno. If you upload and run this program, the LED connected to pin 13 should flash at the same rate as the LED on the Arduino Uno.

 

You'll need to add a similar bit of code to get the LEDs connected to pins 12 and 11. Add the code snippet that can be seen in the following screenshot to the sketch on the Arduino IDE:

 

Here, you are replicating the code for the led connected to pin 13 to the second led1 connected to pin 12 and the third led2 connected to pin 13. You then program them all to be output pins, and then in the main loop, toggle between high and low.

 

Note that I have two toggling together (pins 13 and 11) with the other (pin 12) toggling in the exact opposite sequence. First, the two outer LEDs should light for one second, and then the inner LED should light.

 

If one or more of the LEDs don't light, check to make sure that they are pushed firmly down into the board. You can also change the direction of the LED; perhaps you have the leads in the wrong direction on the board.

 

You can do the same thing with the FLORA board, but you'll need to use alligator clips to connect from FLORA to the breadboard. To do this, build the breadboard as shown earlier.

 

Then, connect the first alligator clip to the right side of one of the resistors on the breadboard. After this, connect it to the GND connector on FLORA.

 

Then, connect the alligator clips to LED 10 and the left side of the top of the breadboard. Once you have done that, connect the other two LEDs to the LED 12 and LED 9 pins.

 

Now, bring up the Arduino IDE associated with FLORA. Create the code shown in the following screenshot, patterned after the code you created in Blog 1, Powering on Arduino:

 

In this case, you are going to use D12, D10, and D9 to flash the LEDs on the breadboard. On the IDE, make sure that Adafruit FLORA is set up on the correct COM port. Upload the code and you should see your flashing LEDs.

 

Working with Displays

In this blog section, you'll learn different connection approaches to show how you can connect an additional capability to Arduino using hardware shields designed for Arduino.

 

Specifically, I'll cover two topics: how to add functionality by adding hardware that is designed to plug into Arduino or shields and how to connect several types of displays to Arduino.

 

We'll use several different types of display shields to illustrate the different communication modes that can be used to address the different types of hardware.

 

A simple serial display

In order to understand how to use a shield, let's start with one of the most basic of the display modules available for Arduino: the serial LCD display. There are several different versions out there, but most provide a simple 2 x 16 character display that can be driven by the serial port on Arduino.

 

This particular display is manufactured by a company called SeeedStudio; other manufacturers make a similar display. It is important that the device documents are compatible with Arduino.

 

This means that the manufacturer has evaluated the unit and is suggesting that it is electrically and mechanically compatible with Arduino. These displays are available at most locations where Arduinos are offered.

 

Working with Displays

In order to connect this display to your Arduino, perform the following steps:

 

1. First, you'll need some cabling. In order to connect the LCD to your Arduino, you'll need to add one more cable; this is a four-wire cable that should come with your display, as shown in the following image:

 

2. Now, you'll need to connect the display to Arduino using these jumper wires. The following image shows a picture of the connection you'll need on the display:

 

3. The preceding image shows the four pins you need to connect to the display.

 

They are GND and VCC pins, and RX and TX pins from Arduino. The VCC and GND will come from the 5 V and GND pins on Arduino. The RX and TX will come from two pins that you will specify in the code.

 

In this case, looking at the documentation, the code will use pin 11 as RX and pin 12 as TX. So, to connect your Arduino to the display, first plug the four-wire connector into the display; then, use the male-to-male jumpers to connect the four connectors to the proper connections on the board, as shown in the following image:

 

This should complete the hardware connections to the board. You should see the green and red LEDs on the display. This particular type of communication connection is a simple serial connection.

 

The data will be transmitted onto the two pins that you will select in a serial fashion. The display will then take this serial data and translate it to the electrical drive signals needed for the display.

 

Enabling the serial display in the IDE Now, let's bring up the Arduino IDE. Before you start coding, you'll need to get the library associated with your display and install it in the IDE.

 

For this display, the library is found at http://www.seeedstudio. com/wiki/Grove_-_Serial_LCD. If you go to this website and select the library, it will take you to another web page that will allow you to download a .zip file with the library.

 

Working with Displays

Arduino Mega Display

Here are the steps:

 

1. Download the library. The .zip file should then exist in your Downloads directory. Now, you'll need to place these files in the libraries directory of your Arduino installation. The following screenshot shows the directory structure of the most common installation of the Arduino IDE:

 

2. Note the location of this directory. Now, go to your Downloads directory and unzip the .zip file that holds your library. When it asks for the directory to unzip to, select this directory. When complete, this library should be added as a subdirectory in your libraries directory, as shown in the following screenshot:

 

3. Note that the files are in the libraries directory under SerialLCD. If you'd like to do this automatically, open the Arduino IDE. Select Sketch, click on Import Library…, and then click on Add Library.

 

4. This will open up a file dialog box. Go to the directory where you downloaded the file and select the .zip file. Once the library is installed, go back to the main IDE screen and you should be able to select one of the examples from the SerialLCD library, for example, the HelloWorld example, as seen in the following screenshot:

 

5. This should open the sketch of the HelloWorld example.

Note that the slcd.print("hello, world!"); statement is the way to send a string text to the serially connected LCD.

The slcd.setCursor(0, 1); command sets the cursor to the start of the second line of the display.

The slcd.print(millis()/1000); statement is an example of how to print a number to the display, in this case, the number of seconds.

 

6. Now upload the sketch and you should see the hello, world! statement on the display.

Now, you can add all sorts of text by simply editing the slcd.print("hello, world!");

line in the setup() function or adding this same function to the loop() function.

Make sure that if you place a message in the loop, use the delay(2000) function after it to give the user some time to read the display before you change it.

 

Connecting a display using the SPI interface

While the serial display is interesting, it has some limitations. It is difficult to display pictures or graphics, and it is somewhat slower than other interfaces available to you. So, let's add a display with a different communications interface. 

 

This particular display is available from a company called SainSmart; it is available directly from the company or other online retailers such as Amazon.com. There are others that are very similar.

 

Finding support for these displays can be difficult, as the interface is significantly more complex; so, check to make sure the libraries are also supplied with the display. To connect to this display, perform the following steps:

 

1. The first step is to connect the display to your Arduino

2. This display uses the SPI interface, so you'll be connecting to the top seven pins. The SI interface is a serial interface but is synchronous, so it provides a more robust communication path. Here is the wiring table that shows which pins to connect to between your Arduino and the display:

 

Arduino pin Display pin

+5 VCC

GND GND

Pin 13 SCL

Pin 11 SDA

Pin 9 RS/DC

Pin 8 RESET

Pin 10 CS

 

3. To make these connections, you'll want a different type of jumper wire, one with a female connection at one end and a male connection at the other. You can purchase these types of jumper wires at most electronics stores or online.

 

4. Once the two devices are connected, you can plug your Arduino into the USB cable and the USB cable into your computer; once done, you should see the LCD light up. Now you're ready to add the code.

 

Enabling the SPI display in the IDE

Just as in the case of SerialLCD, you'll need to add the supporting code library for your device. In order to do so, perform the following steps:

 

1. Go to the site and then click on the Download link. This will download the TFT18.rar file. Use an archive tool such as 7-Zip to unpack this file to the libraries directory.

 

2. Now the library will be available for use. You will need to make one change. Go to the library directory where you installed TFT18 and look for a file called ST7735.h, as shown in the following screenshot:

 

3. You're going to edit the ST7735.h file. You can do that in Notepad if you are working on a Windows system. You are going to change one line, as follows:

 

4. You are going to comment out the line that reads #include <WProgram.h> using two // characters. Then, you will add the #include <Arduino.h> the line as shown in the preceding screenshot. This change is required for the newer

 

5. When you have made the change, go back and navigate to File | Examples | TFT18 | graphics test. This will open an example program that will run on your Arduino and drive the display. Upload this, and you should see a graphical set of test patterns on the display.

 

By the way, you may need to exercise a bit of patience; it can take some time for the graphics to display. Now, you can present information on your display. You can also use the example programs under the TFT library as well.

 

Select the TFTDisplayText example by navigating to Examples | TFT | Arduino | TFTDisplayText. This example program shows you how to display text and a simple number on your display. Here is what this example will look like on the display:

 

An LCD shield

There is yet another option available to add a display to your projects. The unique part of this solution is that this shield will connect directly to your Arduino, making it a single hardware unit.

 

The concept of a shield is a hardware capability that connects directly into an Arduino board at the header pins available. Connecting this unit is as simple as pressing its connections into the connections on your Arduino. 

 

The other nice characteristic of this display is that it comes with a joystick for user input. This unit is available from Amazon.com or other online retailers. The following image shows an LCD shield:

Arduino Mega Pinout LCD_shield

Note how the connections on the shield exactly match the proper pins on Arduino. Now that the HW is connected, you can add some code to access the functionality of the shield. Plug your Arduino into the USB cable and the USB cable into the computer. The shield should light up and indicate that power is applied.

 

Enabling the LCD display in the IDE

As with the last two shields, the first step is to add library support for the device. Finding a functional set of libraries for this particular shield is a bit difficult, as this particular shield has been available for some time. Some versions of the libraries for this shield are for older versions of the IDE.

 

The correct libraries for Version 1.05 of the Arduino IDE are available at http://www.dfrobot.com/wiki/index.php/ LCD4884_Shield_For_Arduino_%28SKU:DFR0092%29.

 

To work with this device and the IDE, perform the following steps:

1. Go to the previously mentioned page and navigate to the Sample Code section. Right below this is a library selection that, if you select it, will download the library.

 

2. Now, open the Arduino IDE and select Sketch. Click on the Import Library… and then click on the LCD4884 V1.2.zip file. This will import this library into the IDE.

 

3. Now you can use one of the example programs in your Arduino. To bring up the simplest of these example programs, navigate to File | Examples | LCD4884 | int_to_String_display.

 

4. This is the simplest set of code to drive the display, and it shows how to display both a string and a number.

 

In the preceding example, there are two statements that interface with the graphical display:

• lcd.LCD-clear();: This statement initializes and clears the LCD.

• lcd.LCD_write_string(MENU_X, MENU_Y, "test screen", MENU_ HIGHLIGHT): This function writes the test screen string to the display.

 

The MENU_X and MENU_Y variables set where the string will be written and the MENU_HIGHLIGHT variable causes the string to be in the highlight mode (with a black background and light text).

 

Now you can use your display to interact with the world. Feel free to check out the other two example programs for more display capabilities and also examples of how to use the joystick.

 

Internet-Controlled PowerSwitch

For many years, people physically interacted with electrical appliances using hardware switches. Now that things have changed, thanks to the advances in technology and hardware, controlling a switch over the Internet without any form of physical interaction has become possible.

 

In this blog, we will incrementally build a web server-enabled smart power switch that can be controlled through the Internet with a wired Internet connection. Let's move to Arduino's IoT (Internet of Things).

 

In this blog, you will do the following:

  • Learn about Arduino UNO and Arduino Ethernet Shield basics
  • Learn how to connect a PowerSwitch Tail with Arduino UNO
  • Build a simple web server to handle client requests and control the PowerSwitch accordingly
  • Build a simple mains electricity (general purpose alternating current) sensor with 5V DC wall power supply
  • Develop a user-friendly UI (User Interface) with HTML (Hyper Text Markup Language) and Metro UI CSS (Cascade Style Sheet)

 

[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]

 

Getting started

This project consists of a DC (Direct Current) activated relay switch with an embedded web server that can be controlled and monitored through the Internet and the integrated mains electricity sensor that can be used to get the status of the availability of mains electricity.

The possible applications are:

  • Controlling electrical devices such as lamp posts, water pumps, gates, doors, and so on, in remote locations
  • Sensing the availability of mains electricity in houses, offices, and factories remotely
  • Detecting whether a door, window, or gate is open or shut

 

Hardware and software requirements

All the hardware and software requirements are mentioned in each experiment. Most of the hardware used in this project is open source, which allows you to freely learn and hack them to make more creative projects based on the blueprints of this blog.

 

Arduino Ethernet Shield

Arduino Mega Pinout Ethernet_shield

Arduino Ethernet Shield is used to connect your Arduino UNO board to the Internet. It is an open source piece of hardware and is exactly the same size as the Arduino UNO board.

 

The latest version of the Arduino Ethernet Shield is R3 (Revision 3).

The official Arduino Ethernet Shield is currently manufactured in Italy and can be ordered through the official Arduino website (https://store.arduino.cc).

 

Also, there are many Arduino Ethernet Shield clones manufactured around the world that may be cheaper than the official Arduino Ethernet Shield. This project is fully tested with a clone of Arduino Ethernet Shield manufactured in China.

 

Internet-Controlled PowerSwitch

Plug your Arduino Ethernet Shield into your Arduino UNO board using wire wrap headers so that it's exactly intact with the pin layout of the Arduino UNO board. The following image shows a stacked Arduino UNO and Arduino Ethernet Shield together:

Arduino Ethernet Shield R3 (top) is stacked with Arduino UNO R3 (bottom) (Front View)

 

Arduino Ethernet Shield consists of an Ethernet controller chip—WIZnet W5100— the only proprietary hardware used with the shield. The WIZnet W5100 includes a fully hardwired TCP/IP stack, integrated Ethernet MAC (Media Access Control), and PHY (Physical Layer).

 

The hardwired TCP/IP stack supports the following protocols:

  • TCP (Transport Control Protocol)
  • UDP (User Datagram Protocol)
  • IPv4 (Internet Protocol Version 4)
  • ICMP (Internet Control Message Protocol)
  • ARP (Address Resolution Protocol)
  • IGMP (Internet Group Management Protocol)
  • PPPoE (Point-to-Point Protocol over Ethernet)
  • The WIZnet W5100 Ethernet controller chip also simplifies the Internet connectivity without using an operating system.
  • The WIZnet W5100 Ethernet controller (Top View)

Throughout this blog, we will only work with TCP and IPv4 protocols.

 

The Arduino UNO board communicates with the Arduino Ethernet Shield using digital pins 10, 11, 12, and 13. Therefore, we will not use these pins in our projects to make any external connections.

 

Also, digital pin 4 is used to select the SD card that is installed on the Arduino Ethernet Shield, and digital pin 10 is used to select the Ethernet controller chip.

 

This is called SS (Slave Select) because the Arduino Ethernet Shield is acting as the slave and the Arduino UNO board is acting as the master. However, if you want to disable the SD card and use digital pin 4, or disable the Ethernet controller chip and use digital pin 10 with your projects, use the following code snippets inside the setup() function:

 

To disable the SD card:

pinMode(4,OUTPUT);

digitalWrite(4, HIGH);

 

2. To disable the Ethernet Controller chip:

pinMode(10,OUTPUT);

digitalWrite(10, HIGH);

 

The Arduino Ethernet board

The Arduino Ethernet board is a new version of the Arduino development board with the WIZnet Ethernet controller built into the same board. The USB to the serial driver is removed from the board to keep the board size the same as Arduino UNO and so that it can be stacked with any Arduino UNO compatible shields on it.

 

You need an FTDI cable compatible with 5V to connect and program your Arduino Ethernet board with a computer.

You can visit the following links to get more information about the Arduino Ethernet board and FTDI cable:

The Arduino Ethernet board (https://store.arduino.cc/product/ A000068)

FTDI cable (https://www.sparkfun.com/products/9717)

 

You can build all the projects that are explained in this blog and other blogs throughout the blog with the Arduino Ethernet board using the same pin layout.

 

Connecting Arduino Ethernet Shield to the Internet

arduino_ethernet

To connect your Ethernet shield to the Internet, you require the following hardware:

  • An Arduino UNO R3 board (https://store.arduino.cc/product/ A000066)
  • A 9VDC 650mA wall adapter power supply. The barrel connector of the power supply should be center positive 5.5 x 2.1 mm. (Here is the link for a perfect fit: https://www.sparkfun.com/products/298)
  • A USB A-to-B male/male-type cable. These types of cables are usually used for printers (https://www.sparkfun.com/products/512)
  • A Category 6 Ethernet cable (https://www.sparkfun.com/products/8915)
  • A router or switch with an Internet connection

 

Use the following steps to make connections between each hardware component:

  • Plug your Ethernet shield into your Arduino board using soldered wire wrap headers:
  • Fritzing representation of Arduino and Ethernet shield stack
  • Get the Ethernet cable and connect one end to the Ethernet jack of the Arduino Ethernet Shield.
  • One end of the Ethernet cable is connected to the Arduino Ethernet board
  • Connect the other end of the Ethernet cable to the Ethernet jack of the network router or switch.
  • The other end of the Ethernet cable is connected to the router/switch
  • Connect the 9VDC wall adapter power supply to the DC barrel connector of the Arduino board.

 

  • Use the USB A-to-B cable to connect your Arduino board to the computer. Connect the type A plug end to the computer and the type B plug end to the Arduino board.

 

  • One end of the Ethernet cable is connected to the Ethernet shield (top) and the power connector and USB cable are connected to the Arduino board (bottom) Image courtesy of SparkFun Electronics (https://www.sparkfun.com)

 

Testing your Arduino Ethernet Shield

arduino-test

To test you, Arduino Ethernet Shield, follow these steps:

 

Open your Arduino IDE and navigate to File | Examples | Ethernet | WebServer: The sample sketch WebServer will open in a new Arduino IDE:

 

You can also paste the code from the sketch named B04844_01_01.ino from the code folder of this blog. The following header files should be included for serial communication and Ethernet communication at the beginning of the sketch:

#include <SPI.h> //initiates Serial Peripheral Interface #include <Ethernet.h> //initiates Arduino Ethernet library

 

Replace the MAC address with your Ethernet shield's MAC address if you know it. You can find the printed sticker of the MAC address affixed to the back of your Ethernet shield. If you don't know the MAC address of your Arduino Ethernet Shielduse the one mentioned in the sample code or replace it with a random one.

 

But don't use network devices with the same MAC address on your network; it will cause conflicts and your Ethernet shield will not function correctly. (Read Finding the MAC address and obtaining a valid IP address for more information on MAC addresses).

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

 

Replace the IP address with a static IP in your local network IP range.

(Read the Finding the MAC address and obtaining a valid IP address section for selecting a valid IP address).

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

Then, create an instance of the Arduino Ethernet Server library and assign port number 80 to listen to incoming HTTP requests.

EthernetServer server(80);

 

Inside the setup() function, open the serial communications and wait for the port to open. The computer will communicate with Arduino at a speed of 9600 bps.

Serial.begin(9600);

 

The following code block will start the Ethernet connection by using the MAC address and IP address (we have assigned a static IP address) of the Arduino Ethernet Shield and start the server.

 

Then it will print the IP address of the server on Arduino Serial Monitor using Ethernet.localIP():

Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
Inside the loop() function, the server will listen for incoming clients.
EthernetClient client = server.available();

 

If a client is available, the server will connect with the client and read the incoming HTTP request. Then, reply to the client by the standard HTTP response header. The output can be added to the response header using the EthernetClient class's println() method:

if (client) {

Serial.println("new client");
an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) {
if (client.available()) { char c = client.read(); Serial.write(c);
if you've gotten to the end of the line (received a newline character) and the line is blank, the http request has ended,
so you can send a reply
if (c == '\n' && currentLineIsBlank) {
send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 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("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
you're starting a new line currentLineIsBlank = true;
}
else if (c != '\r') {
you've gotten a character on the current line currentLineIsBlank = false;
} }
}
give the web browser time to receive the data delay(1);

 

Finally, close the connection from the client using the EthernetClient class's stop() method:

client.stop();

Serial.println("client disconnected");
  • Verify the sketch by clicking on the Verify button located in the toolbar.

 

  • On the menu bar, select the board by navigating to Tools | Board | Arduino UNO. If you are using an Arduino Ethernet board, select Tools | Board | Arduino Ethernet.

 

  • On the menu bar, select the COM port by navigating to Tools | Port and then selecting the port number.

 

  • Upload the sketch into your Arduino UNO board by clicking on the Upload button located in the toolbar.

 

  • Open your Internet browser (such as Google Chrome, Mozilla Firefox, or Microsoft Internet Explorer) and type the IP address(http://192.168.1.177/) assigned to your Arduino Ethernet Shield in the sketch, and hit the Enter key.

 

  • The web browser will display analog input values (impedance) of all the six analog input pins (A0-A5). The browser will refresh every 5 seconds with the new values. Use the following code to change the automatic refresh time in seconds:
client.println("Refresh: 5");

 

Output for Arduino UNO + Arduino Ethernet ShieldAnalog input values are displaying on the Google Chrome browser, refreshing every 5 seconds

  • Arduino Serial Monitor prints the static IP address of Arduino Ethernet Shield

 

To make your sketch more stable and to ensure that it does not hang, you can do one of the following:

  •  Remove the SD card from the slot.
  • Add the following two lines inside your setup() function:
pinMode(4,OUTPUT);

digitalWrite(4, HIGH);

Now you can be assured that your Arduino Ethernet Shield is working properly and can be accessed through the Internet.

 

Selecting a PowerSwitch Tail

Powertail

PowerSwitch Tail has a built-in AC relay that is activated between 3-12 VDC. This is designed to easily integrate with many microcontroller platforms, such as Arduino, Raspberry Pi, BeagleBone, and so on. Usually, Arduino digital output provides 5VDC that allows it to activate the AC (Alternative Current) relay inside the PowerSwitch Tail.

 

Using a PowerSwitch Tail with your microcontroller projects provides safety since it distinguishes between AC and DC circuitry by using an optocoupler which is an optically activated switch.

 

PowerSwitch Tail ships in several variants. At the time of writing this blog, the product website lists various PowerSwitch Tails, assembled and in kit form, that can be used with this project. To build this project, we will use a 240V AC PowerSwitch Tail that can be purchased as a kit and assembled.

 

PN PSSRKT-240

If you are in a country that has a 120V AC connection, you can purchase an assembled version of the PowerSwitch Tail. PN80135 Refer to http://www.powerswitchtail.com/Pages/default.aspx. 

 

PN80135 Normally Open (NO) version—120V AC (left-hand side plug for LOAD and right-hand side plug for LINE) Image courtesy of SparkFun Electronics (https://www.sparkfun.com)

 

Wiring PowerSwitch Tail with Arduino Ethernet Shield

Wiring the PowerSwitch Tail with Arduino is very easy. Use any size of wire range between gauge #14-30 AWG to make the connection between Arduino and PowerSwitch Tail. 

 

PowerSwitch Tail has a terminal block with three terminals. Use a small flat screwdriver and turn the screws CCW (Counter Clock Wise) to open the terminal contacts.

 

With the Arduino Ethernet Shield mounted on the Arduino UNO board, do the following:

  • Use the red hookup wire to connect the positive terminal of the PowerSwitch Tail to digital pin 5 on your Arduino.
  • Use the black hookup wire to connect the negative terminal of the PowerSwitch Tail to the GND pin on your Arduino.

 

  • Connect the wall adapter power supply (9V DC 650mA) to the DC power jack on your Arduino board. The ground terminal is connected internally to the AC-side electrical safety ground (the green conductor) and can be used if needed.

 

Turning PowerSwitch Tail into a simple web server

In this topic, we will look into how to convert our Arduino connected PowerSwitch Tail into a simple web server to handle client requests, such as the following:

  • Turn ON the PowerSwitch Tail
  • Turn OFF the PowerSwitch Tail
  • And other useful information such as:
  • Display the current status of the PowerSwitch Tail
  • Display the presence or absence of the main electrical power

 

What is a web server?

A web server is a piece of software which serves to connected clients. An Arduino web server uses HTTP on top of TCP and UDP. But remember, the Arduino web server can't be used as a replacement for any web server software running on a computer because of the lack of processing power and a limited number of multiple client connectivity.

 

A step-by-step process for building a web-based control panel. In this section, you will learn how to build a web-based control panel for controlling the PowerSwitch Tail through the Internet. We will use the Arduino programming language and HTML that's running on the Arduino web server. Later, we will add HTML radio button controls to control the power switch.

 

Handling client requests by HTTP GET

Using the HTTP GET method, you can send a query string to the server along with the URL. The query string consists of a name/value pair. The query string is appended to the end of the URL and the syntax is http://example.com?name1=value1.

Also, you can add more name/value pairs to the URL by separating them with the & character, as shown in the following example: http://example.com?name1=value1&name2=value2.

 

So, our Arduino web server can actuate the PowerSwitch Tail using the following URLs:

To turn ON the PowerSwitch Tail: http://192.168.1.177/?switch=1

To turn OFF the PowerSwitch Tail: http://192.168.1.177/?switch=0

The following sketch can be used by the web server to read the incoming client requests, process them, and actuate the relay inside the PowerSwitch Tail:

 

Open your Arduino IDE and type or paste the code from the B04844_01_02. into sketch.

In the sketch, replace the MAC address with your Arduino Ethernet Shield's MAC address: byte mac[] = { 0x90, 0xA2, 0xDA, 0x0B, 0x00 and 0xDD };

 

Replace the IP address with an IP valid static IP address in the range of your local network: IPAddress ip(192,168,1,177);

 

If you want the IP address dynamically assigned by the DHCP to the Arduino Ethernet Shield, do the following:

1. Comment the following line in the code: //IPAddress ip(192,168,1,177);

2. Comment the following line in the code: //Ethernet.begin(mac, ip);

3. Uncomment the following line in the code: Ethernet.begin(mac);

 

The following two lines will read the incoming HTTP request from the client using the EthernetClient class's read() method and store it in a string variable http_Request:

char c = client.read();
http_Request += c;

The following code snippet will check whether the HTTP request string contains the query string that is sent to the URL. If found, it will turn on or off the PowerSwitch Tail according to the name/value pair logically checked inside the sketch.

 

The indexOf() function can be used to search for the string within another string. If it finds the string switch=1 inside the HTTP request string, the Arduino board will turn digital pin 5 to the HIGH state and turn on the PowerSwitch Tail.

 

If it finds the text switch=0, the Arduino board will turn the digital pin 5 to the LOW state and turn off the PowerSwitch Tail.

 

if (httpRequest.indexOf("GET /?switch=0 HTTP/1.1") > -1) { relayStatus = 0;

digitalWrite(5, LOW);

Serial.println("Switch is Off");

} else if (httpRequest.indexOf("GET /?switch=1 HTTP/1.1") > -1) {

relayStatus = 1; digitalWrite(5, HIGH); Serial.println("Switch is On");

}

Select the correct Arduino board and COM port from the menu bar.

Verify and upload the sketch into your Arduino UNO board (or the Arduino Ethernet board). If you have to choose DHCP to assign an IP address to your Arduino.

 

Ethernet Shield, it will be displayed on the Arduino Serial Monitor. On the menu bar, go to Tools | Serial Monitor. The Arduino Serial Monitor window will be displayed with the IP address assigned by the DHCP.

 

The IP address assigned by the DHCP

Plug the PowerSwitch Tail LINE side into the wall power socket and connect the lamp into the LOAD side of the PowerSwitch Tail. Make sure that the lamp switch is in the ON position and all the switches of the wall power socket are in the ON position.

 

Open your Internet browser and type the IP address of your Arduino Ethernet Shield with HTTP protocol. For our example it is http://192.168.1.177. Then hit the Enter key on your keyboard.

 

The web browser sends an HTTP request to the Arduino web server and the web server returns the processed web content to the web browser. The following screen capture displays the output in the web browser.

Type http://192.168.1.177/?switch=1 and hit the Enter key. The lamp will turn on.
Type http://192.168.1.177/?switch=0 and hit the Enter key. The lamp will turn off.

 

If you have connected your Arduino Ethernet Shield to your home wireless network, you can test your PowerSwitch Tail using your Wi-Fi connected smartphone as well.

 

If you have the idea to add port forwarding to your router, you can then control your switch from anywhere in the world. Explaining about port forwarding is out of the scope of this blog.

 

Electric lamp controlled by PowerSwitch Tail

  • PowerSwitch Tail control panel accessed by Google Chrome browser Sensing the availability of mains electricity.
  • You can sense the availability of mains electricity in your home and read the status before actuating the PowerSwitch Tail.

 

You will need the following hardware to build the sensor:

  • A 5VDC 2A wall adapter power supply (https://www.sparkfun.com/ products/12889)
  • A 10 kilo Ohm resistor (https://www.sparkfun.com/products/8374)
  • Follow the next steps to attach the sensor to the Arduino Ethernet Shield:
  • Connect the positive wire of the 5V DC wall adapter power supply to the Ethernet shield digital pin 2.
  • Connect the negative wire of the wall adapter power supply to the Ethernet shield GND pin.
  • Connect the 10-kilo-ohm resistor between the Ethernet shield digital pin 2 and the GND pin.
  •  Plug the wall adapter power supply into the wall.

 

Testing the mains electricity sensor

The previous sketch is modified to check the availability of the mains electricity and operate PowerSwitch Tail accordingly. The 5V DC wall adapter power supply plugged into the wall keeps the Arduino digital pin 2 in the HIGH state if mains electricity is available. If mains electricity is not available, the digital pin 2 switches to the LOW state.

 

Open your Arduino IDE and paste the code from the sketch named B04844_01_03.ino from the code folder of this blog.

Power up your Arduino Ethernet Shield with a 9V battery pack so that it will work even without mains electricity. The Arduino digital pin 2 is in its HIGH state if mains electricity is available.

 

The electricity boolean variable holds the state of availability of the electricity. If only the mains electricity is available, the PowerSwitch Tail can be turned ON. If not, the PowerSwitch Tail is already in its OFF state.

 

Building a user-friendly web user interface

The following Arduino sketch adds two radio buttons to the web page so the user can easily control the switch without typing the URL with the query string into the address bar of the web browser.

 

The radio buttons will dynamically build the URL with the query string depending on the user selection and send it to the Arduino web server with the HTTP request.

 

Open your Arduino IDE and paste the code from the sketch named B04844_01_04.ino from the code folder of this blog.

Replace the IP address with a new IP address in your local area network's IP address range. IPAddress ip(192,168,1,177);

 

Verify and upload the sketch on your Arduino UNO board.

Open your web browser and type your Arduino Ethernet Shield's IP address into the address bar and hit the Enter key. The following code snippet will submit your radio button selection to the Arduino web server as an HTTP request using the HTTP GET method.

The radio button group is rendered inside the <form method="get"></form> tags.

 

client.println("<form method=\"get\">");

if (httpRequest.indexOf("GET /?switch=0
HTTP/1.1") > -1) {
relayStatus = 0;
digitalWrite(9, LOW);
Serial.println("Off Clicked");
} else if (httpRequest.indexOf("GET /?switch=1 HTTP/1.1") > -1) {
relayStatus = 1; digitalWrite(9, HIGH); Serial.println("On Clicked");
}
if (relayStatus) {
client.println("<input type=\"radio\" name=\"switch\" value=\"1\" checked>ON");
client.println("<input type=\"radio\" name=\"switch\" value=\"0\" onclick=\"submit();\">OFF");
}
else {
client.println("<input type=\"radio\" name=\"switch\" value=\"1\" onclick=\"submit();\">ON");
client.println("<input type=\"radio\" name=\"switch\" value=\"0\" checked>OFF");
}
client.println("</form>");

 

Also, depending on the radio button selection, the browser will re-render the radio buttons using the server response to reflect the current status of the PowerSwitch Tail.

 

Adding a Cascade Style Sheet to the web user interface

Cascade Style Sheet (CSS) defines how HTML elements are to be displayed. Metro UI CSS (https://metroui.org.ua/) is a cascade style sheet that can be used to apply Windows 8-like style to your HTML elements.

 

The following Arduino sketch applies Windows 8-like style to the radio button group:

Open your Arduino IDE and paste the code from the sketch named B04844_01_05.ino from the code folder of this blog.

Between the <head></head> tags we have first included the JQuery library which consists of a rich set of JavaScript functions:

client.println("<script class='lazy' data-src=\"https://metroui.org.ua/js/jquery-2.1.3.min.js\"></script>");

Then, we have included metro.js and metro.css from the https:// metroui.org.ua website:
client.println("<script class='lazy' data-src=\"https://metroui.org.ua/js/metro.js\"></script>");
client.println("<link rel=\"stylesheet\" href=\"https://metroui.org.ua/css/metro.css\">");

 

Upload the sketch on your Arduino board and play with the new look and feel. You can modify the other HTML elements and even use the radio buttons by referring to the MetroUI CSS website documentation at https://metroui.org.ua/.

MetroUI CSS style applied to radio buttons

 

Finding the MAC address and obtaining a valid IP address

To work with this project, you must know your Arduino Ethernet Shield's MAC address and IP address to communicate properly over the Internet.

 

Current Arduino Ethernet Shields come with a dedicated and uniquely assigned 48-bit MAC (Media Access Control) address which is printed on the sticker.

 

Write down your Ethernet shield's MAC address so you can refer to it later. The following image shows an Ethernet shield with the MAC address of 90-A2-DA-0D-E2-CD:

 

You can rewrite your Arduino Ethernet Shield's MAC address using hexadecimal notations, as in 0x90, 0xA2, 0xDA, 0x0D, 0xE2 and 0xCD, with the leading 0x notation recognized by C compilers (remember that the Arduino programming language is based on C) and assembly languages.

 

If not present, you can use one that does not conflict with your network. For example:

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

 

Obtaining an IP address

You can assign an IP address to your Arduino Ethernet Shield by one of the following methods:

 

  • Using the network router or switch to assign a static IP address to your Ethernet shield.
  • Using DHCP (Dynamic Host Configuration Protocol) to dynamically assign an IP address to your Ethernet shield. In this blog, we will only discuss how to assign an IP address using DHCP.

 

The network devices we will use in this experiment are the following:

  • Huawei E517s-920 4G Wi-Fi Router
  • DELL computer with Windows 8.1 installed and Wi-Fi connected
  • Nokia Lumia phone with Windows 8.1 installed and Wi-Fi connected
  • Arduino Ethernet Shield connected to the Wi-Fi router's LAN port using an Ethernet cable

 

Assigning a static IP address

The following steps will explain how to determine your network IP address range with a Windows 8.1 installed computer, and select a valid static IP address.

 

Open Network and Sharing Center in Control Panel:

Click on Connections. The Connection Status dialog box will appear. Click on the Details… button. The Network Connection Details dialog box will appear.

 

The IPv4 address assigned to the Windows 8.1 computer by the Wireless router is 192.168.1.2. The IPv4 subnet mask is 255.255.255.0. So, the IP address range should be 192.168.1.0 to 192.168.1.255.

 

The Wi-Fi network used in this example currently has two devices connected, that is, a Windows 8.1 computer, and a Windows phone. After logging in to the wireless router product information page, under the device list, all the IP addresses currently assigned by the router to the connected devices can be seen, as shown here:

Now, we can choose any address except 192.168.1.1, 192.168.1.2, and 192.168.1.3.

 

Let's assign 192.168.1.177 to the Arduino Ethernet Shield as a static IP address. Upload the following sketch into your Arduino board and open the Serial Monitor to verify the static IP address assigned.

 

Open your Arduino IDE and type or paste the following code from the sketch named B04844_01_06.ino from the code folder of this blog.

#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte ip[] = { 192, 168, 1, 177 };
EthernetServer server(80);
void setup()
{
Serial.begin(9600);
Ethernet.begin(mac, ip);
server.begin();
Serial.print("IP Address: ");
Serial.println(Ethernet.localIP());
}
void loop () {}
A static IP address

 

Obtaining an IP address using DHCP

The DHCP can be used to automatically assign a valid IP address to the Arduino Ethernet Shield. The only address you need is the MAC address of the Ethernet shield. Pass the MAC address as a parameter to the Ethernet.begin() method.

 

Upload the following Arduino sketch to your Arduino board, and open the Arduino Serial Monitor to see the auto-assigned IP address by the DHCP. Use this IP address to access your Ethernet shield through the Internet. Remember, this IP address may be changed at the next startup or reset.

 

Open your Arduino IDE and type or paste the following code from the sketch named B04844_01_07.ino from the code folder of this blog:

#include <SPI.h>

#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetServer server(80);
void setup()
{
Serial.begin(9600);
Ethernet.begin(mac);
server.begin();
Serial.print("IP Address: ");
Serial.println(Ethernet.localIP());
}
void loop () {}
DHCP assigned IP address

 

USE ARDUINO TO INTERACT AND RUN CODE

Arduino is the latest sensation in the computer world. Forging a congenial environment through the use of a separate programming language, this interactive computing tool helps programmers detect and devise new methods for assessing and regulating various parameters. The system envisages the use of microcontrollers to assist in physical computing.

 

Arduino is a creative tool that helps you build something more with just an ordinary desktop computer or circuits. It senses and thereby helps you control things in your physical world.

 

It merges all needed software writing-development environments with a simple yet effective microcontroller board. In this e-book, we will see Arduino products, hot selling items from the Arduino store and the method of programming the Arduino to create your own home automation system.

 

ARDUINO PRODUCTS

Arduino produces boards, accessories, kits, and shields. Currently, they have 21 boards, 8 shields, 2 kits, and 5 accessories.

 

The boards are named Arduino Uno, Arduino Yun, Arduino Tre, Arduino Esplora, Arduino Mega ADK, Arduino Robot, Arduino Mini, LilyPad Arduino Simple, Fio, Leonardo, LilyPad Arduino, Zero, Micro, Due, Arduino Ethernet, Mega 2560, LilyPad Arduino USB, Gemma, Nano, Arduino Pro Mini and Arduino Pro.

 

The shields are Arduino GSM Shield, Arduino WiFi Shield, Arduino USB Host shield, Arduino Wireless Proto shield, Arduino Ethernet shield, Arduino Wireless SD shield, Arduino Motor shield, and LilyPad Arduino SimpleSnap.

 

The kits are the Arduino Starter kit and the Arduino Materia 101Accessories available are USB/Serial Light adapter, mini USB/Serial adapter, TFT LCD screen, Arduino ISP and Arduino Proto shield.

 

Arduino AtHeart is a versatile and highly adaptable program for configuring programs and devices to control various parameters you need for your project. These programs benefit makers who want something more from Arduino.

 

By joining in the program, you get the Arduino logo on your product, the support of the Arduino community and the chance to display your product on the Arduino store.

 

You can describe your product on the Arduino website. Small makers have to remit a small fee for licensing the product while wholesalers would have to pay a royalty.

The supported processors are:

  • Chip Name Clocked at MHz
  • AtMega328
  • 8 or 16
  • AtMega1280 16
  • AtMega2560 16
  • AtMega32U4 16
  • SAM3X

 

Arduino AtHeart devices have the basic simplicity to allow users to assemble various models on their own. The functionality of these devices goes beyond the reach of ordinary computer-based applications. Here is a look at some Arduino AtHeart products that are in hot demand at the Arduino store.

 

Primo

Primo is an Arduino AtHeart product aimed at teaching children in the learning phase the basics of programming. This physical interface programming device teaches children in the age group 4 – 7 years programming logic. Children will guide a smiling robot to a prescribed destination by passing on instructions.

 

These instructions are delivered in the form of colorful blocks with messages. It makes children involved in a developmental experience that is both exciting and challenging. Children learn through playing with their Cubetto Playset.

 

Tsunami

Tsunami is an Arduino AtHeart product signal generator powerful yet flexible and gives users a way to experiment with projects using analog signals. It is amazingly straightforward since it combines the Direct Digital Synthesis chip with Arduino Leonardo.

 

When combined with a software library that is easy to use and an input-output circuitry that is incredibly flexible, working with analog signals becomes a snip. 

 

Arachnid Labs designed the Tsunami and is currently in use in over a thousand projects covering fields like music, design dance, publishing, theater, technology, photography, and fashion. To preorder the Tsunami go here.

 

Nix Color Sensor

This Arduino AtHeart device will tickle the senses of art lovers. Nix color sensor allows one to collect colors from any object they see in real life. Take the sensor close to the object and touch it and you will find the color automatically registered inside the Nix color sensor.

 

Organize them into palettes using your smartphone. You can share these on the social media and make comparisons to other colors. This proves very useful for those in the fashion, style or review of products sections of the media. Never go wrong when you choose the color of the paint for your walls.

 

Bare conductive touch board

Serious people who like to ‘wire’ the place up will definitely fall for this one. Here in this Arduino AtHeart product, you can make any surface respond to touch sensation. Okay, even fun lovers will have a ball with the Touch Board.

 

All you have to do is connect one of the twelve electrodes to anything conductive and then use the signal to trigger some sound that will play through an MP3 player. Think of all the fun you can have with the electric paint that you can apply on your wall, your girl’s teddy bear…This is called the Touch Board and…better think before you touch it.

 

EZBoard Home Automation

Control the various devices around the house with your EZBoard. Think thermostat, light control, controlling sprinkler and temperature besides your garage door. All the necessary code, libraries, and basic programs have been installed making it very simple for you to use this Arduino AtHeart product. You have a connected home at a very affordable cost.

 

This Arduino AtHeart home automation device comes in a box, and nothing is as simply getting the package out, setting up the connection to the Wi-Fi and…begin to control the appliances. The board does not draw much power and you can use it extended periods just on batteries pegging 3.7V.

 

It uses an Ethernet controller and consumes very less power. In addition, it has a power relay, temperature sensor, and a microSD card socket. Its Lelylan’s platform helps you interact with any hardware one normally uses in one’s house.

 

Lelylan makes use of the same protocol Facebook uses to update application that is used in mobile messaging known as MQTT protocol. You can adapt this program for any platform.

 

NEWTC Prototyping Board

You can either buy a preassembled board from NEWTC or you can get a board and assemble the individual parts yourself. The second option obviously is more exciting and offers you the chance to dabble in some experiments in designing. Don’t worry if things come unstuck, the Arduino community is always ready to back you and answer all your questions.

 

The CPU used in the Prototyping board is the ATMEGA328P-PU. You will also find that the Arduino Uno bootloader is already burned into the chip. Typical behavior of the Do-It-Yourself kit is as listed below. 

 

Has the prototyping board self-assembled variety Arduino AtHeart having Arduino Uno bootloader pre-burned into it. Gives support for HC-06 Bluetooth connector interface TTL Level (5V) 4-pin connector Supports MCU and compatible connectors Power external 12 V with 3.3V and 5 V internal

 

Get the individual parts and begin to solder them. You can order your kit from online stores. You can solder the individual parts on the board and test it with DM-USB2Serial. Upload the program for the DM-USTYLE V1.0 DIY version board from the sketch software. Plug the board in and click on Program Compile and Upload menu.

 

For those who wish to use the board as an AVR board, you have a choice of compilers ranging from WINAVR and IAR to CodeVision AVR and ICC AVR. Normally, users will employ the board ISP to download the output generated by the compiler.

 

You can use the AD-ISPRO or the AD-USBISP for doing the download. The former is useful for parallel port type STK200/300 while the latter proves useful for USB type STK500.

 

USING THE IMAGECRAFT IDE

Now we will see how to establish the compiler to render code in a hex file and how we should download it to the device. This example will show you how to use the STK200 starter kit for the AT90S23 13. You can get more details from ImageCraft website. Be sure to get the “unlock code” from ICC. This makes your program licensed.

 

You then have to install the program to a default drive say C, the shortcut to the program — ICC AVR will be installed to the “c:\icc” directory. Search in the Menu program and find the group ImageCraft Development Tools.

 

Begin your project

When you start up the ICC AVR program, you will see three distinct areas – the project file liststatus window, and editors. In the beginning, all are empty. All project files are stored in the project file list. Every editor window that is syntax-aware will be allocated on a separate tab in the editor section.

 

During the project building process, every message will be displayed in your status window. You can maximize space for your project file list by choosing not to display the status window or the editor.

 

Select Project New and in the dialog box make a new folder c:\icctest. Type in First for the file name in the file name window.

 

Your project now has the name First. To write and compile code, your compiler must have the correct options. Projects need to have settings and you can choose the options from the Options tab under the Projects.

 

From the options box, choose the Paths tab. The directory path for the output directory, libraries and header files will be specified here.

The paths for library path and include path will automatically get set to “c:\icc\lib” and “c:\icc\include”.

 

In the output directory, you will find files related to the project along with the output. Unless specified as absolute, it remains relative to the project directory.

In the edit box, if you enter “objs”, IDE will “c:\icctest\first\objs” for outputting files.

 

Compiler

Go to the compiler page in the dialog box and choose the option. In the list box, click on Output Format and click on Intel HEX. Keep the box next to the “Accept C++ Comments” checked.

 

Target

Next click on the target tab. Here you can make options specific to the target. In this particular tutorial, you have to click on the Device Configuration tab and select 2313.

 

This ImageCraft IDE becomes very simplified as it as it shows the options that are required alone for the entire toolchain in the compiler. This will include linker, assembler, and compiler.

 

A simple program will be in use by the application note to increment PORTB where you have the 8 LEDs attached. One 8-bit timer will generate delay for each increment. You will now be able to see the lights flashing. Begin by creating a new file and type:

 

#include <io2313.h>
void initialization (void);
void delay (void);
void initialization (void)
{
DDRB = 0xff;
// set PORTB as output
TCCR0 = 0x05;
// Count clock/1024
}
void delay (void)
65 ms at 4 MHz
//Produce a delay of
{
while (! (TIFR&0x02));
// Wait for timer () overflow flag to be set
TIFR = 0x02;
// Clear overflow flag
}
void main (void)
{
initialization ();
// Initialize Peripherals
while (1)
// Forever
{
PORTB++;
//Increment
PORTB
delay ();
//Short delay
}
}

Save this file as “avrc031.c” under the File. In addition, you can also save it to project folder “c:\icctest\First” but this is optional.

 

About the program

The program runs in three modes. The main loop is separated from the other two operations delay and initialization. The main clock divided by 1024 begins counting TIMER () while PORTB acts as the output.

 

The controller waits in the delay subroutine until the Overflow Flag of TIMER () gets set. It then clears this flag and exits. The main loop begins with the increment in PORTB of the content. Then the delay is called so that the change is visible in the PORTB.

 

Make The Inclusion For The Source File In The Project

To include the source code for any project, open the Add Files under

Projects. Open the working file “avr031.c” inside “c:\icctest\first” and click OK.

 

Compiling the code: Select Make Project under Project. The toolbar will display the icon for Build Project. If the code does not have any errors then the code will compile and the HEX code will get allocated to “c:\icctest\first\objs\first.hex”. Now all you have to do is to place the file inside the starter kit.

 

Loading File Into STK200 Starter Kit

Before we run the code, we convert the file into AT90S2313 in the STK200 starter kit. We use software known as AVR ISP. Open a new project once you have mounted the STK dongle in a parallel port.

 

Select New Project under Project. Highlight and click OK on AT90S2313. You have extra options for setting “Lock Bit” and “Fuse” under “Project Manager” but it will not be useful for this tutorial. Click the title frame and activate Program Memory window.

 

Go to File tab and click on Load. A dialog box will open where you can see the “c:\icctest\first\objs” file. Open this and click on the “first.hex” file. Now load this program on the AT90S2313 in the starter kit by selecting the Auto-Program option under Program.

 

Check the boxes next to “Reload Files”, “Program Device” and “Erase Device”. Click on OK now. The LED lights should be functioning well now.

 

RECAP OF THE TUTORIAL

  • Begin by creating a destination folder.
  • Project New Write Project name and path
  • Project Options
  • Enter Objs
  • Compiler Options: under output format
  • check both Intel HEX and
  • Accept C++ Comments
  • Click Device Configurations and choose 2313
  • Write source code
  • Project Add Files and add source code to project; choose the file you just wrote
  • Click on build icon and compile the code; alternatively, you can compile by selecting Make Project under Project
  • Open AVR ISP. Download hex file present in “objs” folder.

 

BUILD THE IN-SYSTEM PROGRAMMER

USING ARDUINO

Here you will learn how to use your Arduino board to be your In-System Programmer. That means you make use of the board as AVR ISP.

 

When you do this you get the capacity to burn the ATMEGA328 or ATMEGA168 bootloader on some AVR. Randall Bohn designed the mega-isp firmware on which we base the code for this tutorial. Here is the instructions step by step.

 

Plug your Arduino board in and go to Examples.

Click on ArduinoISP Firmware (Please note that those who use Arduino 1.0 have to make one change in their ArduinoISP code.

 

Check the heartbeat () function. You will see that it says delay (40). Make it delay (20). According to the board you use, select items in Serial Port and Board menus under the Tools. Now upload Arduino sketch to the board. 

 

Use the figure shown below to wire the Arduino board.  When you next select the Board under the Tools, it actually means you are selecting the board on which you intend to burn the bootloader.

 

It does not mean the board you are currently using to work the program. Then click on the Arduino as ISP under Burn Bootloader.

 

WORK WITH ARDUINO

I) EXAMPLES FROM BRIDGE LIBRARY

Here are the examples (read more at Arduino Learning Examples that will help you work with your Arduino. All the examples written here are for Arduino 1.0 and later versions. This will help you develop an understanding of how your Arduino can adapt to different circumstances and how you can develop your skills in this direction.

 

A) CHECK WIFI STATUS OF ARDUINO YUN

For this example, you need to have an Arduino Yun microprocessor board. It comes with Ethernet, digital pins for input-output numbering 20 and WiFi so that you can begin straight away unless there are legal restrictions in your country for use of WiFi-enabled devices.

 

Arduino Yun has a slot for micro-SD card, another for micro-USB-connectivity, then 3 reset-buttons and the UCSP header. The Atheros processor in your Yun supports Linux distribution OpenWrt-Yun. This allows the users a good degree of computer networking power along with working ease brought by Arduino.

 

Start Check Status of Yun WiFi project

When you run the script “pretty-wifi-info.lua” depicted in the sketch given in your Yun in folder /user/bin, you will get information about the status of your Yun WiFi.

 

Be careful, however, to connect the Yun in serial connection otherwise, it will not print. Connect the computer USB cable to the Yun and choose the right port from the Port Menu.

 

Hardware and Circuitry

You do not have to make any connections or circuits for this project. You will require these pieces of hardware.

  • a)Wireless network
  • b)Arduino Yun

 

Code for the WiFi Status project

First, you need to include Process class in the header.

#include <Process.h>
Next, you need to start Bridge and serial communication. If you fail to connect the computer in serial, sketch will fail to run.
void setup () {
Serial.begin (9600);
while (!Serial)
Serial.println(“Starting bridge…\n“);
pinMode(13,OUTPUT);
digitalWrite(13, LOW);
Bridge.begin();
digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready
delay(2000);
}
New process is initialized in loop (). This will run the check script for the WiFi. Script is run when you call runShellCommand () after setting path to script.
void loop () {
Process wifiCheck;
wifiCheck.runShellCommand (“/usr/bin/pretty-wifi-info.lua”);
Check the characters returned to serial monitor by the script. After a few seconds, run it again.
while (wifiCheck.available() > 0) {
char c = wifiCheck.read();
Serial.print(c);
}
Serial.println();
delay(5000);
}

Here is the entire code once again.

 

Status of WiFi

This sketch runs a script called “pretty-wifi-info.lua” installed on your Yún in folder /user/bin. It will print information regarding the status of your wifi connection. It uses Serial to print, so you need to connect your Yún to your computer using a USB cable and select the appropriate port from the Port menu

 

#include <Process.h>

void setup() {
Serial.begin(9600); // initialize serial communication while(!Serial); // do nothing until the serial monitor is opened
Serial.println(“Starting bridge…\n“);
pinMode(13,OUTPUT);
digitalWrite(13, LOW);
Bridge.begin(); // make contact with the Linux processor
digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready
delay(2000); // wait 2 seconds
}
void loop() {
Process wifiCheck; // initialize a new process
wifiCheck.runShellCommand(“/usr/bin/pretty-wifi-info.lua”); // command you want to run
//
while there’s any characters coming back from the
//
process, print them to the serial monitor:
while (wifiCheck.available() > 0) {
char c = wifiCheck.read();
Serial.print(c);
}
Serial.println();
delay(5000);
}

 

FILE WRITE SCRIPT

This example tells you how to use FileIO classes to write to some file within the filesystem of Yun. First, in /temp a shell script file will be created. Then you execute it.

 

Hardware and Circuit required

You do not have to make any circuits and only require your Arduino Yun board.

 

Code for File Write Script

To communicate with the filesystem, you have to include FileIO header.

#include <FileIO.h>
Next, you have to initialize FileSystem Serial communication and Bridge in setup (). Once the serial connection has been made, start loop () after you
upload file after you initiate a custom call function uploadScript ().
void setup () {
Bridge.begin ();
Serial.begin (9600);
while (!Serial); // wait for Serial port to connect.
Serial.println (“File Write Script example\n\n“);
FileSystem.begin();
uploadScript ();
}
One more custom function will run your script. This runScript () will execute every 5 seconds.
void loop () {
runScript ();
delay (5000);
}

 

Create a file with the upload script () function. The shell script is created inside the Linux file system. This will check your WiFi interface network traffic. After you have finished creating the file, you may open it by creating an instance of File@ class.

 

You call it by invoking FileSystem.open ()@ the precise location where you create the script is indicated by @. Put the script in /tmp inside RAM. This will preserve the cycles of reading/write that are limited in FLASH memory.

void uploadScript() {

File script = FileSystem.open(“/tmp/wlan-stats.sh”, FILE_WRITE);

Print the header #!/bin/s.

Then print utility ifconfig.

The @ifconfig@ command line utility controls network interfaces. This brings you to the WiFi interface wlano

Write the script contents using File. print ().

 

Since you require the received number of bytes look for keywords RX bytes. Now you can close the file.

script.print(“#!/bin/sh\n“);
script.print(“ifconfig wlan0 | grep ‘RX bytes’\n“);
script.close(); // close the file
In order to make script executable, you must instantiate some Process.
Now, chmod@ command changes file modes; send chmod@ with filepath
and command. Shell script now will run like an application.
Process chmod;
chmod.begin(“chmod”); // chmod: change mode
chmod.addParameter(“+x”); // x stays for executable
chmod.addParameter(“/tmp/wlan-stats.sh”);
chmod.run();
}

 

Create Process through runScript () function. This will run your script and then print the result to Serial Monitor. Start the script after creating it by calling the two functions Process.begin (file path) along with Process.run ().

void runScript() {
Process myscript;
myscript.begin(“/tmp/wlan-stats.sh”);
myscript.run();
Now use String function to read and hold output.
String output = ””;
while (myscript.available()) {
output += (char)myscript.read();
}
Now get rid of blank spaces that precede or are present at the string end and then print the output to serial monitor.
output.trim();
Serial.println(output);
Serial.flush();
}

 

The complete code will look like this:

#include <FileIO.h>

void setup() {
// Setup Bridge (needed every time we communicate with the Arduino
Yún)
Bridge.begin();
// Initialize the Serial
Serial.begin(9600);
while(!Serial); // wait for Serial port to connect.
Serial.println(“File Write Script example\n\n“);
// Setup File IO
FileSystem.begin();
// Upload script used to gain network statistics uploadScript();
}
void loop() {
// Run stats script every 5 secs.
runScript();
delay(5000);
}
//
this function creates a file into the Linux processor that contains a shell
script
//
to check the network traffic of the WiFi interface
void uploadScript() {
//
Write our shell script in /tmp
//
Using /tmp stores the script in RAM this way we can preserve
//
the limited amount of FLASH erase/write cycles
File script = FileSystem.open(“/tmp/wlan-stats.sh”, FILE_WRITE); // Shell script header
script.print(“#!/bin/sh\n“);
//
shell commands:
//
ifconfig: is a command line utility for controlling the network interfaces.
//
wlan0 is the interface we want to query
//
grep: search inside the output of the ifconfig command the “RX bytes” keyword
//
and extract the line that contains it
script.print(“ifconfig wlan0 | grep ‘RX bytes’\n“); script.close(); // close the file
// Make the script executable
Process chmod;
chmod.begin(“chmod”); // chmod: change mode chmod.addParameter(“+x”); // x stays for executable chmod.addParameter(“/tmp/wlan-stats.sh”); // path to the file to make it
executable
chmod.run();
}
// this function run the script and read the output data void runScript() {
// Run the script and show results on the Serial
Process myscript;
myscript.begin(“/tmp/wlan-stats.sh”);
myscript.run();
String output = ””;
// read the output of the script
while (myscript.available()) {
output += (char)myscript.read();
}
// remove the blank spaces at the beginning and the ending of the string
output.trim();
Serial.println(output);
Serial.flush();
}

 

HTTP CLIENT

This tutorial will show how to use the Arduino Yun for creating HTTP client. Using this you can go online and download content. In our example, we go to the Arduino website to download any one version of the Arduino logo in the form of ASCII characters.

 

Hardware and Circuit Required

  • Arduino Yun
  • Connection to the internet
  • You do not require any other circuit for this example.

 

Code

Begin by including libraries of HTTPClient as well as Bridge.

#include <Bridge.h>

#include <HttpClient.h>
Start Bridge in setup () and ensure serial connection has been made. Then you can begin the loop ().
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
Bridge.begin();
Serial.begin(9600);
while(!Serial);
}
Create an instance of HTTPClient in loop (). Call the URL of your choice with client.get (URL) function.
void loop() {
HttpClient client;
client.get(“http://arduino.cc/asciilogo.txt”);
Check the memory of client buffer server and read bytes to print them in your serial monitor. Use a cycle of 5 seconds.
while (client.available()) {
char c = client.read();
Serial.print(c);
}
Serial.flush();
delay(5000);
}
The entire code for sketch is given here.
#include <Bridge.h>
#include <HttpClient.h>
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
Bridge.begin();
Serial.begin(9600);
while(!Serial);
}
void loop() {
HttpClient client;
client.get(“http://arduino.cc/asciilogo.txt”);
while (client.available()) {
char c = client.read();
Serial.print(c);
}
Serial.flush();
delay(5000);
}

 

READ ASCII STRING

In this sketch, we see how to use the Serial.parseInt () function. This helps you locate values that have alphanumeric character separation. One common method of representation is the comma-separated-value where the comma is made use of to separate the different pieces of information.

 

You can also use other characters like period or space for this purpose. You will change the RGB LED color when you pass strings having values such as “15, 140, 220”. The color changes because of the parsed values of ints.

 

Hardware and Circuit required

  • Arduino Board
  • Three 220-ohm resistors
  • Breadboard
  • The common anode RGB LED
  • Hookup wire

 

To make the circuit shown above, take 5 wires. Use a red wire to connect the 5V pin to one end of one of the long vertical rows present on your breadboard. Take an RGB LED and check the datasheet in order to identify the pins.

 

To the LED common anode, connect power rail you created now. Now use the wires that remain to make a connection to pin 5 and green cathode, pin 3 and red cathode and pin 6 with blue cathode along with resistors. All RGB LEDs share power pin that is common if they have a common cathode.

 

Now, make a pin LOW instead of HIGH and across that diode, some voltage difference will happen. Now, if you send 255 using analogWrite () the LED will turn off, while the value 0 will turn it on full brightness.

 

In effect, you will call analogWrite (pin, 255-brightness) instead of analogWrite (pin, 255). There is nothing complicated in mathematics.

 

Code for the Read ASCII String

You need to set up global variables for the pins to which you connect the LED. This will help you identify easily which one of them is red, which is green and which is blue when you move on to the main program part.

const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
Serial communication will begin between your computer and Arduino in setup () at 9600 bits per second. Also, configure the pins to be outputs.
Serial.begin(9600);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);

 

You need to make sure that every data present in serial buffer is read. For this, we use while function.

while (Serial.available() > 0) {

 

Now you come to the main portion where you note the brightness of the LED, which is the main serial information. Declare any local variable and use it to store the value. You separate every value by commas using the Serial.parseInt (). Then you read information into variables.

int red = Serial.parseInt();

int green = Serial.parseInt();

int blue = Serial.parseInt();

After this is done, you can use the newline character to proceed to the next step.

if (Serial.read() == ‘\n‘) {

 

In order to maintain PWM control, try to keep values within acceptable range through constraining (). So, whenever the value lies outside your accepted PWM range, it will be limited to some particular valid number.

 

If you subtract this from 255 you will format value for use with LED with common anode. You already know that the LED will light up when there is a difference of voltage between pin connected for Arduino and anode.

 

red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);
After formatting PWM values, make use of analogWrite () and change LED color. Since you already subtracted the value of output from 255, you get:
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
Make the entire set of value of LED into one string and send back to serial monitor.
Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);
Lastly, you have to close those brackets from your while statement, if statement and main loop.
}
}
}

Now that Arduino has been programmed, go back to the Serial monitor. Start your message in a newline and send values for lights between 0 and 255 as Red, Green, Blue. Once this is done, LEDs connected will turn to the specified color and you can read HEX values from the Serial monitor.

 

Reading a serial ASCII-encoded string. This sketch demonstrates the Serial parseInt() function. It looks for an ASCII string of comma-separated values. It parses them into ints and uses those to fade an RGB LED.

*

Red cathode: digital pin 3
*
Green cathode: digital pin 5
*
blue cathode: digital pin 6
*
anode: +5V
created 13 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
// pins for the LEDs:
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
void setup() {
// initialize serial:
Serial.begin(9600);
// make the pins outputs:
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// if there’s any serial available, read it:
while (Serial.available() > 0) {
// look for the next valid integer in the incoming serial stream:
int red = Serial.parseInt();
// do it again:
int green = Serial.parseInt();
// do it again:
int blue = Serial.parseInt();
// look for the newline. That’s the end of your
// sentence:
if (Serial.read() == ‘\n‘) {
//
constrain the values to 0 - 255 and invert
//
if you’re using a common-cathode LED, just use “constrain(color, 0,
255);”
red = 255 - constrain(red, 0, 255);
green = 255 - constrain(green, 0, 255);
blue = 255 - constrain(blue, 0, 255);
// fade the red, green, and blue legs of the LED: analogWrite(redPin, red); analogWrite(greenPin, green); analogWrite(bluePin, blue);
// print the three numbers in one string as hexadecimal:
Serial.print(red, HEX);
Serial.print(green, HEX);
Serial.println(blue, HEX);
}
}
}

 

VIRTUAL COLOR MIXER

In this example, we see how we send different values from your Arduino board to the computer. The background color of the Max/MSP patch or processing sketch gives the readings. The potentiometers set blue, green or red components.

Hardware Required

  • Arduino Board
  • Breadboard
  • (3) Analog Sensors (potentiometer, photocell, FSR, etc.) Hook-up wire
  • (3) 10K ohm resistors

 

Software Required

 

Circuit

Here we have a circuit comprising of force-sensing resistors. Three sub-circuits that are voltage dividers generate analog voltages. Analog-Input pins 0, 1, and 2 are connected to the analog sensors. Voltage dividers have resistors connected in series and according to their value, they have voltage in each.

 

Code

Sensor values pass from Arduino to the computer as decimal numbers that are ASCII-encoded. ASCII characters for each number from 0 to 9 are used to pass the number. For instance, you would get the ASCII bytes to value 51, 52 and 56 for the number 348. (3 has the byte value of 51,…and so on).

 

const int redPin = A0; // sensor to control red color const int greenPin = A1; // sensor to control green color const int bluePin = A2; // sensor to control blue color

void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(analogRead(redPin));
Serial.print(“,”);
Serial.print(analogRead(greenPin));
Serial.print(“,”);
Serial.println(analogRead(bluePin));
}
/* Processing code for this example
//
This example code is in the public domain. import processing.serial.*;
float redValue = 0; // red value
float greenValue = 0; // green value
float blueValue = 0; // blue value
Serial myPort;
void setup() {
size(200, 200);
//
List all the available serial ports println(Serial.list());
//
I know that the first port in the serial list on my Mac
//
is always my Arduino, so I open Serial.list()[0].
//
Open whatever port is the one you’re using. myPort = new Serial(this, Serial.list()[0], 9600);
//
don’t generate a serialEvent() unless you get a newline character: myPort.bufferUntil(‘\n’);
}
void draw() {
//
set the background color with the color values: background(redValue, greenValue, blueValue);
}
void serialEvent(Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil(‘\n’);
if (inString != null) {
//
trim off any whitespace: inString = trim(inString);
//
split the string on the commas and convert the
//
resulting substrings into an integer array: float[] colors = float(split(inString, “,”));
//
if the array has at least three elements, you know
//
you got the whole thing. Put the numbers in the
//
color variables:
if (colors.length >=3) {
// map them to the range 0-255:
redValue = map(colors[0], 0, 1023, 0, 255); greenValue = map(colors[1], 0, 1023, 0, 255); blueValue = map(colors[2], 0, 1023, 0, 255); }
}
}

 

Processing Code

Use the code sample above to copy your Processing sketch. When you change the analog sensor values, the background color will keep changing.

Max Code

You, Max Patch, will resemble this. Using the code sample above, copy its text and paste to new Max window.

DIMMER

Here in this project, you will learn what to do to control how bright the LED shines. You send data as individual bytes in the range 0 to 255. When the Arduino reads these values, it sets the LED brightness.

 

Arduino takes values from any software that can communicate with the Arduino through the serial port of the computer. Here we see how it was done using Max/MSP version 5 and Processing.

 

Hardware and Circuit Required

  • Arduino Board
  • 220-ohm resistor
  • LED

Software Required

Max/MSP version 5 or Processing

 

Circuit

Using a suitable resistor connect pin 9 to an LED. For most cases, a 220 W to 330 W resistor will do fine.

 

Schematic Code

Demonstrates the sending data from the computer to the Arduino board, in this case, to control the brightness of an LED. The data is sent in individual bytes, each of which ranges from 0 to 255. Arduino reads these bytes and uses them to set the brightness of the LED.


const int ledPin = 9; // the pin that the LED is attached to
void setup()
{
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
byte brightness;
// check if data has been sent from the computer:
if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255):
brightness = Serial.read();
// set the brightness of the LED:
analogWrite(ledPin, brightness);
}
}
/* Processing code for this example
//
Dimmer - sends bytes over a serial port
//
by David A. Mellis
//This example code is in the public domain.
import processing.serial.*;
Serial port;
void setup() {
size(256, 150);
println(“Available serial ports:”);
println(Serial.list());
//
Uses the first port in this list (number 0). Change this to
//
select the port corresponding to your Arduino board. The last
//
parameter (e.g. 9600) is the speed of the communication. It
//
has to correspond to the value passed to Serial.begin() in your
//
Arduino sketch.
port = new Serial(this, Serial.list()[0], 9600);
//
If you know the name of the port used by the Arduino board, you
//
can specify it directly like this.
//port = new Serial(this, “COM1”, 9600);
}
void draw() {
//
draw a gradient from black to white for (int i = 0; i < 256; i++) { stroke(i);
line(i, 0, i, 150);
}
//
write the current X-position of the mouse to the serial port as
//
a single byte
port.write(mouseX);
}

 

Processing Code

Use the connection shown in the code sample. This will send the bytes that dim the LED. The connection is through the serial port to Arduino.

Max Code

The Max/MSP patch is shown in the above code sample. You have to copy and paste it into a new window.

 

LED SHOW

In this tutorial, we learn how to get the values directly from the joystick. The Serial monitor displays output in terms of RGB LED color.

You can move the joystick along two perpendicular axes X or Y. Each one of the axes controls one color that the RGB LED displays – X-axis depicts red while the Y-axis depicts green. The blue element will have its control by the relative position of the linear potentiometer.

 

Hardware and Circuit Required

Arduino Esplora

The brightness of the RGB LED light may be controlled individually through the Esplora Library functions. The light consists of three colors Red, Green, and Blue.

You may also control all of the colors with one single command using writeRGB (); Values generated will differ when the joystick moves. You can also shift the position of the linear potentiometer to create new outputs. One output is by the serial monitor while the other you see as the RGB LED light.

#include <Esplora.h>
void setup() {
// initialize the serial communication:
Serial.begin(9600);
}
void loop() {
// read the sensors into variables:
int xAxis = Esplora.readJoystickX();
int yAxis = Esplora.readJoystickY();
int slider = Esplora.readSlider();
// convert the sensor readings to light levels: byte red = map(xAxis, -512, 512, 0, 255); byte green = map(yAxis, -512, 512, 0, 255); byte blue = slider / 4;
// print the light levels:
Serial.print(red);
Serial.print(‘ ‘);
Serial.print(green);
Serial.print(‘ ‘);
Serial.println(blue);
// write the light levels to the LED.
Esplora.writeRGB(red, green, blue);
// add a delay to keep the LED from flickering:
delay(10);
}

 

EXAMPLES FROM ROBOT LIBRARY

This is a fun-filled project where you can race your robot against others. The means of controlling your robot is by a line drawn on a large paper. Your robot will search for the line and then it will follow it. Think of the fun you can have when you have more robots!

 

Hardware and Circuit required

  • Arduino Robot
  • A large white sheet of paper
  • Black marker pen
  • Tape

 

Procedure

1. Make tracks for the robot. These tracks will go winding on a piece of paper. They have to be 1 inch (about 2 ½ cm) thick. The line must not intersect and the end of the line must join the starting point. Join several pieces of paper if the track area is not big enough.

 

2. Not fix the paper to the ground with some tape. This will prevent it from slipping when the robot runs around on it. Try to keep the surface light in color.

 

3. Upload the code, unplug the USB and switch on the power.

4. Put the robot on the ground such that it is facing the line.

5. For the first few trials (starting screen), the robot will make the calibrations required and then it will orient itself to detect the line.

 

6. Once the robot detects the line, it will carry on following it without stop. 

Try to run it

Now your robot is ready to race!

 

Code

/* Robot Line Follow

This sketch demonstrates the line following capabilities of the Arduino Robot. On the floor, place some black electrical tape along the path you wish the robot to follow. To indicate a stopping point, place another piece of tape perpendicular to the path.

#include <ArduinoRobot.h> // include the robot library

#include <Wire.h>
#include <SPI.h>
long timerOrigin; // used for counting elapsed time
void setup() {
// initialize the Robot, SD card, display, and speaker
Robot.begin();
Robot.beginTFT();
Robot.beginSD();
Robot.beginSpeaker();
// show the logots on the TFT screen
Robot.displayLogos();
Robot.drawBMP(“lf.bmp”, 0, 0); // display background image
Robot.playFile(“chase.sqm”); // play a song from the SD card
// add the instructions
Robot.text(“Line Following\n\n place the robot on\n the track and \n see it run”, 5, 5);
Robot.text(“Press the middle\n button to start…”, 5, 61);
Robot.waitContinue();
//
These are some general values that work for line following
//
uncomment one or the other to see the different behaviors of the robot //Robot.lineFollowConfig(14, 9, 50, 10);
Robot.lineFollowConfig(11, 7, 60, 5);
//set the motor board into line-follow mode Robot.setMode(MODE_LINE_FOLLOW);
// start
Robot.fill(255, 255, 255);
Robot.stroke(255, 255, 255);
Robot.rect(0, 0, 128, 80); // erase the previous text
Robot.stroke(0, 0, 0);
Robot.text(“Start”, 5, 5);
Robot.stroke(0, 0, 0); // choose color for the text Robot.text(“Time passed:”, 5, 21); // write some text to the screen
timerOrigin = millis(); // keep track of the elapsed time
while (!Robot.isActionDone()) { //wait for the finish signal
Robot.debugPrint(millis() - timerOrigin, 5, 29); // show how much time has passed
}
Robot.stroke(0, 0, 0);
Robot.text(“Done!”, 5, 45);
}
void loop() {
//nothing here, the program only runs once. Reset the robot
//to do it again!
}

 

Working Principle

The robot senses the ground beneath it with five sensors. Light reflects back to the sensors. In order to detect the line, the wheels of the robot must turn. This it does when it does not detect any line and all five sensors produce white light.

 

Stopping

When the robot detects black in all five sensors, it will stop. This is the method to stop the robot.

 

B) WRITING A LIBRARY FOR ARDUINO

In this tutorial, we will see what goes into the creation of an Arduino library. First, we write a sketch that will flash Morse code and then use the function to create the library. This way, people can easily use your code and update it.

 

It will help the library to improve. You will get more information in API Style Guide.

 

Let us begin with the simple sketch that does the Morse code.

int pin = 13;

void setup()
{
pinMode(pin, OUTPUT);
}
void loop()
{
dot(); dot(); dot();
dash(); dash(); dash();
dot(); dot(); dot();
delay(3000);
}
void dot()
{
digitalWrite(pin, HIGH);
delay(250);
digitalWrite(pin, LOW);
delay(250);
}
void dash()
{
digitalWrite(pin, HIGH);
delay(1000);
digitalWrite(pin, LOW);
delay(250);
}

 

The code above when run will flash the distress code SOS through pin 13. The sketch does not have any significantly different parts other than the functions dot () and dash (), which of course do the actual blinking.

 

Now, the functions use the ledPin () variable that will tell functions, which pin to use. Finally, one has the pinMode () a call to initialize pin as an output. You have started your library from the sketch!

 

Every library has at least two files – the header file that has extension .h and source file having extension .cpp. Header file comprises of definitions stating everything that the library contains. Source file comprises of the actual code. Let us name our library 

 

Morse. This will make our header file Morse.h…should be interesting to see its contents. You will find it difficult to understand it all at the beginning, but it will get easier as you go along.

 

Header file core will be made of one line representation for every function in the library. It is represented in class together with any variables you might need.

class Morse

{
public:
Morse(int pin);
void dot();
void dash();
private:
int _pin;
};

To understand class, you need to think of it as function collection alongside variables where you can easily access it. When this agglomeration can be accessed by anyone using the library, it is termed public. When it is private, it can only be accessed from within that class alone.

 

Special function constructor exists within a class to help create an instance of the class. Name of the constructor will remain the same as the class name but it will not have a return value.

 

To complete the header file, you will also need #include statement in order to let you access constants and standard types in Arduino language. In sketches, this is normally included but it is not in libraries. This is how you write it.

#include “Arduino.h”

 

Lastly, you wrap your header file in the construct:

#ifndef Morse_h

#define Morse_h

// the #include statement and code go here…

#endif

This helps you avert problems like repetition as it happens with two #includes. You round up your library by putting a comment on top of it. This will tell what is present, the library name, the name of the author, the date and license.

The complete header file would be like this.

#ifndef Morse_h
#define Morse_h
#include “Arduino.h”
class Morse
{
public:
Morse(int pin);
void dot();
void dash();
private:
int _pin;
};
#endif

 

Let us now see what goes into the making of the source file – the Morse.cpp. You begin with include statements that give the code you write access to Arduino standard functions as defined inside in the library.

#include “Arduino.h”
#include “Morse.h”
After this, you make constructors. This lets users choose specific instances of classes. They do this by choosing a pin that is configured as an output.
Morse::Morse (int pin)
{
pinMode (pin, OUTPUT);
_pin = pin;
}

 

In these lines of code, you will notice that there is a slightly different convention of naming. One is the:: operator, which is the scope operator. It gives global visibility to the chosen variable.

 

Another change you see is the underscore that is assigned before the pin class. Adding underscore helps you name a class or variable without breaking the naming convention.

 

You get a clearer view of your code and help you group all those classes you want with an underscore so that you can work easier. For instance, you may need some group to be private. You can add underscore in front of their class names. Now, proceed with the code for the library.

void Morse::dot()
{
digitalWrite(_pin, HIGH);
delay(250);
digitalWrite(_pin, LOW);
delay(250);
}
void Morse::dash()
{
digitalWrite(_pin, HIGH);
delay(1000);
digitalWrite(_pin, LOW);
delay(250);
}

 

You then round off your code by writing the comment on top. It helps you understand what you have written.

#include “Arduino.h”
#include “Morse.h”
Morse::Morse(int pin)
{
pinMode(pin, OUTPUT);
_pin = pin;
}
void Morse::dot()
{
digitalWrite(_pin, HIGH);
delay(250);
digitalWrite(_pin, LOW);
delay(250);
}
void Morse::dash()
{
digitalWrite(_pin, HIGH);
delay(1000);
digitalWrite(_pin, LOW);
delay(250);
}

 

Now that you have written the code, you must know how to access and use it. Begin by making a Morse directory in the library subdirectory in your sketch. Copy Morse.h along with Morse.cpp files and do the Arduino environment launch. It means just open the Arduino and then go to Sketch>Import Library menu. Here you will find Morse inside.

#include <Morse.h>

Morse morse(13);
void setup()
{
}
void loop()
{
morse.dot(); morse.dot(); morse.dot();
morse.dash(); morse.dash(); morse.dash();
morse.dot(); morse.dot(); morse.dot();
delay(3000);
}

 

Let us see what differences exist after we made the duplication. The first thing to notice is the #include statement at the top. Doing this includes this sketch in code that will be sent to the board and make the library accessible to the sketch.

 

You do not have to include the library. Delete the #include statement for the library to save space. Next, you can see a new instance of Morse class has been created named morse.

Morse morse (13);

 

During the execution process, the constructor class is called even before setup () function and it will be given an argument, 13 in this example. The setup () will not have anything because the call taking place to the pinMode () occurs within the library.

 

In a similar fashion, we need to prefix morse in order to call the functions dot () and dash (). For each instance of Morse class, you can add the pin and store it in the private variable _pin. When we call some particular instance of any function, we are specifying exactly what the variable should be for that instance for the duration of the call. So, if we had:

Morse morse(13);

Morse morse2(12);

 

a call to morse2.dot () would have the value 12. You might notice too that Arduino does not automatically recognize your definitions in the library and update the environment and color. In order to do this, you make use of the keywords.txt file that you create within that Morse directory.

Morse KEYWORD1
dash KEYWORD2
dot KEYWORD2

 

Each class you mention is written in this way. Name of the class and the keyword you assign to it. Then use a tab without space to go to the next class. Here again, you write the next keyword and so on.

 

KEYWORD1 will all have orange color while the KEYWOR2 will take up the brown color. Restart the Arduino environment and the new keywords will take effect.

 

Now if you plan to include working examples within your sketch, do place example directory within Morse directory. Now, move the sketch (say SOS) to the examples directory. It is easy to negotiate with this by pulling down Sketch>Show Sketch Folder.

 

Again restart Arduino and you will see Library-Morse inside File>Sketchbook>Examples. You can use comments to explain what your example does. You can download Arduino for your operating system.

 

EXAMPLES FROM SENSORS KNOCK

This tutorial will tell you how to use a Piezo element for detecting knock on any surface – a table, the door or the top of a device. As you might have guessed the Piezo would be any electronic device, you use for detecting the knock.

 

How does it do this? The Piezo element possesses the property of generating electricity when you vibrate it…meaning you knock it. The output is a sound with a particular tone. Therefore, you can use the piezo element to both generate and detect tones.

 

We use analog-to-digital conversion (ADC) process that outputs numerals from 0—1023 for voltage ranges between 0V and 5V. The sketch reads the voltage with analogRead () function. In case the output is greater than the prescribed threshold, Arduino sends a string “Knock!” which you can see by opening the serial monitor.

 

Hardware and Circuit Required

Arduino board

Megohm resistor – 1

Piezo-electric disc –1

Any solid surface (to knock)

 

Circuit

Piezos have polarized structures. This allows current to pass through them in one direction only. Make a connection with the black wire (lower voltage) to the ground and the higher voltage red wire to the 0 analog pin.

 

In order to limit voltage/current produced by piezo, use a 1-megohm resistor in parallel. If possible, get piezo elements that do not have plastic coverings. Now tape the bare metallic body to the surface you want to take the reading from.

 

Schematic

1-Megohm resistor connected to piezo at pin 0

 

Code

The user sets a threshold and studies data generated by the piezo element. One can change the threshold value to modify the sensitivity of the element.

* Knock Sensor

You can use this sketch to detect knocking sound with a piezo element. Reading from the analog pin compares results that user predetermines for some threshold. When the result shows bigger value, ‘knock’ will be written to the serial port and the pin 13 LED will be toggled.

 

Details of the circuit:

In analog at 0 piezo positive connection is attached Ground attaches to – piezo connection 1-megohm connected between ground and 0 in analog. This example code is in the public domain.

 

*/
// these constants won’t change:
const int ledPin = 13; // led connected to digital pin 13
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 100; // threshold value to decide when the detected
sound is a knock or not
// these variables will change:
int sensorReading = 0; // variable to store the value read from the sensor pin
int ledState = LOW; // variable used to store the last LED status, to toggle the light
void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as OUTPUT Serial.begin(9600); // use the serial port }
void loop() {
// read the sensor and store it in the variable sensorReading:
sensorReading = analogRead(knockSensor);
// if the sensor reading is greater than the threshold:
if (sensorReading >= threshold) {
// toggle the status of the ledPin:
ledState = !ledState;
// update the LED pin itself:
digitalWrite(ledPin, ledState);
// send the string “Knock!” back to the computer, followed by newline
Serial.println(“Knock!”);
}
delay(100); // delay to avoid overloading the serial port buffer

 

 EXAMPLES FROM STRINGS

 

A) STRING ADDITION OPERATOR

Concatenation is defined as the process of combining a character or several characters or an ASCII representation (constant or variable) to a string and outputting the result. This resultant string is longer than either the length of characters used or the original string. To add Strings you use the + operator.

 

// adding string with a constant integer:
stringThird = stringFirst + 678;
// adding string with a constant long integer:
stringThird = stringFirst + 975312468;
// adding string with a constant character:
stringThird = stringFirst + ‘D’;
// adding string with a constant string:
stringThird = stringFirst + “gfd”;
// adding together two Strings:
stringThird = stringFirst + stringSecond;

 

Another thing you can do is to add the result of some operation to some string. The only restriction is that the data type returned by the string must be valid.

stringThird = stringFirst + millis();

Here millis () returns long integer, which may be added to any string. You can write the code like this too.

stringThird = stringFirst + analogRead(A0);

 

In the last, analogRead () returns an integer that can be added to the string. This kind of concatenation proves useful in situations where you need to display more than one value as in LCD displays for advertising products. They need to display the price and details including the name and packaging weight.

int sensorValue = analogRead(A0);
String stringFirst = “Sensor value: “;
String stringThird = stringFirst + sensorValue;
Serial.println(stringThird);
This will give you some sensor value output. However, if you run the code below, it will not give you any valid output.
int sensorValue = analogRead(A0);
String stringThird = “Sensor value: ” + sensorValue;
Serial.println(stringThird);
The result will be unpredictable since you have not initially given value to stringThird. Check another kind of improper initialization here.
Serial.println(“I want ” + analogRead(A0) + ” donuts”);
The operator precedence is wrong and so the code will not compile. The following example will compile but the results will not be what are expected.
int sensorValue = analogRead(A0);
String stringThird = “I want ” + sensorValue;
Serial.println (stringThird + ” donuts”);
The reason for the error is again clear. The stringThird never was initialized.
Hardware and Circuit required
Arduino board
You do not require any other circuit for this example.
Image developed by Fritzing
Code
Here is the code for several examples of concatenation types.
/*
Adding Strings together
Examples of how to add strings together
You can also add several different data types to string, as shown here:
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
Arduino - StringAdditionOperator
This example code is in the public domain.
*/
// declare three strings:
String stringOne, stringTwo, stringThree;
void setup() {
// initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
;
// wait for serial port to connect. Needed for Leonardo only
}
stringOne = String(“stringThree = “);
stringTwo = String(“this string”);
stringThree = String ();
// send an intro:
Serial.println(“\n\nAdding strings together (concatenation):”); Serial.println();
}
void loop() {
// adding a constant integer to a string: stringThree = stringOne + 123; Serial.println(stringThree); // prints “stringThree = 123”
// adding a constant long integer to a string: stringThree = stringOne + 123456789; Serial.println(stringThree); // prints ” You added 123456789”
// adding a constant character to a string: stringThree = stringOne + ‘A’; Serial.println(stringThree); // prints “You added A”
// adding a constant string to a string:
stringThree = stringOne + “abc”; Serial.println(stringThree); // prints “You added abc”
stringThree = stringOne + stringTwo; Serial.println(stringThree); // prints “You added this string”
// adding a variable integer to a string: int sensorValue = analogRead(A0); stringOne = “Sensor value: “; stringThree = stringOne + sensorValue;
Serial.println(stringThree); // prints “Sensor Value: 401” or whatever
value analogRead(A0) has
// adding a variable long integer to a string:
long currentTime = millis();
stringOne=“millis() value: “;
stringThree = stringOne + millis();
Serial.println(stringThree); // prints “The millis: 345345” or whatever value currentTime has
// do nothing while true:
while(true);
}

 

B) STRING COMPARISON OPERATORS

You can make comparisons between various strings using operators for String comparison such as equals () or equalIgnoresCase () and ==, <=, >, !=, >=, <. Sorting and sequencing are important activities when creating databases.

 

Many functions are interchangeable such as equals () and == operators. You may use either one since the answer will be the same. That is why you will that:

if (stringOne.equals(stringTwo)) {

will perform the same operation as

if (stringOne ==stringTwo) {

Greater than and less than operators will check the first alphabet or number in the string. This is why you get “a” < “b” and “1” < “2”, but “999”> “1000” because 9 comes after 1.

 

Take note: When you use operators for string comparison, do not think the strings as numbers. If you want mathematical values, you have to use a variable such as floats, ints.

 

Hardware and Circuit Required

Arduino board

You will not require any circuit in this tutorial. The only connection you need to make is between the Arduino board and your computer.

 

Code
/*
Comparing Strings
Examples of how to compare strings using the comparison operators
created 27 July 2010
modified 2 Apr 2012
by Tom Igoe
Arduino - StringComparisonOperators
This example code is in the public domain.
*/
String stringOne, stringTwo;
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
}
stringOne = String(“this”);
stringTwo = String(“that”);
// send an intro:
Serial.println(“\n\nComparing Strings:”);
Serial.println();
}
void loop() {
// two strings equal:
if (stringOne == “this”) {
Serial.println(“StringOne == "this"“);
}
// two strings not equal:
if (stringOne != stringTwo) {
Serial.println(stringOne + ” =! ” + stringTwo);
}
// two strings not equal (case sensitivity matters):
stringOne = “This”;
stringTwo = “this”;
if (stringOne != stringTwo) {
Serial.println(stringOne + ” =! ” + stringTwo);
}
// you can also use equals() to see if two strings are the same:
if (stringOne.equals(stringTwo)) {
Serial.println(stringOne + ” equals ” + stringTwo);
}
else {
Serial.println(stringOne + ” does not equal ” + stringTwo);
}
// or perhaps you want to ignore case:
if (stringOne.equalsIgnoreCase(stringTwo)) {
Serial.println(stringOne + ” equals (ignoring case) ” + stringTwo);
}
else {
Serial.println(stringOne + ” does not equal (ignoring case) ” + stringTwo);
}
// a numeric string compared to the number it represents:
stringOne = “1”;
int numberOne = 1;
if (stringOne.toInt() == numberOne) {
Serial.println(stringOne + ” = ” + numberOne);
}
// two numeric strings compared:
stringOne = “2”;
stringTwo = “1”;
if (stringOne >= stringTwo) {
Serial.println(stringOne + ” >= ” + stringTwo);
}
// comparison operators can be used to compare strings for alphabetic sorting too:
stringOne = String(“Brown”);
if (stringOne < “Charles”) {
Serial.println(stringOne + ” < Charles”);
}
if (stringOne > “Adams”) {
Serial.println(stringOne + ” > Adams”);
}
if (stringOne <=“Browne”) { Serial.println(stringOne + ” <=Browne”); } if (stringOne>= “Brow”) {
Serial.println(stringOne + ” >= Brow”);
}
//
the compareTo() operator also allows you to compare strings
//
it evaluates on the first character that’s different.
//
if the first character of the string you’re comparing to
//
comes first in alphanumeric order, then compareTo() is greater than 0:
stringOne = “Cucumber”;
stringTwo = “Cucuracha”;
if (stringOne.compareTo(stringTwo) < 0 ) {
Serial.println(stringOne + ” comes before ” + stringTwo);
}
else {
Serial.println(stringOne + ” comes after ” + stringTwo);
}
delay(10000); // because the next part is a loop:
// compareTo() is handy when you’ve got strings with numbers in them too:
while (true) {
stringOne = “Sensor: “;
stringTwo= “Sensor: “;
stringOne += analogRead(A0);
stringTwo += analogRead(A5);
if (stringOne.compareTo(stringTwo) < 0 ) {
Serial.println(stringOne + ” comes before ” + stringTwo);
}
else {
Serial.println(stringOne + ” comes after ” + stringTwo);
}
}
}

 

ARDUINO IN HARDWARE INTERFACE

Arduino comes into play for interfacing devices that are used as input, output or user interfaces. They also help devices used in communication and an ISP programmer. In order to use the kit or assemble it, you have to be aware of the full capabilities of this revolutionary computing device.

 

See all that is possible and begin a project that interests you. They help in governing physical systems and in regulating the audio systems. You can use them in multiplexing and controlling and distributing electrical power.

 

They are used as input devices in power, audio, and automobiles. Scientists use them in environmental sciences and distance sensing devices. Other uses include their use in human interfacing, game controllers, keypads and light sensors. Here we are going to see how to use the Arduino for some basic functions.

 

SIMPLE BASIC CONTROLS

A) Fading an LED

For this experiment, you need the following equipment.

  • Breadboard
  • 220-ohm resistor
  • Arduino board
  • An LED

Select the 9 pins of your Arduino and solder a 220-ohm resistor to it. Connect the other end of the resistor to anode the positive leg of your LED. The shorter cathode leg in the LED should be directly connected to the ground. Now to write the code.

 

First, declare the ledPin is your 9 pin. This will be all there is in your setup () portion of the code. Next comes the analog write () function. Here you need to pass two functions – one that tells which pin it has to write to and one that tells what PWM value it has to write.

 

To make the LED fade off, you need to increase the PWM value that is at 0 all the way to 255. Now decrease the value all the way back to 0. You can use any variable to change the PWM value. In this example, we use full or off. For each loop, the increment is done by a variable goDark.

 

When the full Or Off is at one end of the value scale, either 0 or 255, the goDark value is changed to negative. This means that if the full riff is at 10, then go dark is assigned -10 and if it reaches 250, then the goDark value is given +10 value. The analogWrite will do the steps very fast.

 

To control the speed of your fade, you use delay at the sketch ends. To see the difference actually, change the delay value and check how the program responds. Here is the program.

/*

Fade
You will see in this example how you fade the LED on the pin 9
You use the analogWrite () function
You are reading the function written in public domain.
*/
int led = 9; // the pin that the LED is attached to int fullOrOff = 0; // how bright the LED is
int goDark = 5; // how many points to fade the LED by
//
when you press the reset the setup routine runs void setup () {
//
declare pin 9 to be an output: pinMode (led, OUTPUT);
}
//
the loop will not stop executing, it goes on void loop () {
// set the fullOrOff of pin 9:
analogWrite (led, fullOrOff);
//
change the fullOrOff for next time through the loop: fullOrOff = fullOrOff + goDark;
//
when the loop reaches the end reverse its direction of fading
if (fullOrOff == 0 || fullOrOff == 255) { goDark = -goDark;
}
//
dimming will occur at the end of 30 seconds delay (30);
}

 

B) Blink the LED

In this example too we use the same material as before. You can use 220 Ω to 1000 Ω resistance. You may sometimes find that the LED is already attached to your Arduino board. Otherwise, solder the LED to the 13 pins like before.

To begin the code, initialize the 13 pins to be your output pin: pinMode (13, OUTPUT);

To turn the LED on, use this code in the main loop. digitalWrite(13, HIGH);

 

Once the voltage comes to the 13 pins, it will light up the LED. Now you have to turn off the voltage by using the line:

digitalWrite(13, LOW);

Now the voltage in pin 13 drops back to zero and the LED light will switch off. If you want to really appreciate the work your program does, set the delay for 1000 milliseconds. During this period, nothing happens. Take a look at the program:

 

/*
Blink
You will see a repeat of this cycle – ON for one second, OFF the other You are reading this example code written expressly in the public domain */
// Most Arduino boards have pin 13 attached to LED
//
give it a name: int led = 13;
//
on pressing reset the setup routine starts again.
void setup() {
//
initialize the digital pin as an output. pinMode(led, OUTPUT);
}
//
the loop routine runs over and over again forever: void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

 

C) Set up Button control

The button is used to connect two points when you press on it. In this example, we see how to make use of a button to turn on a LED connected to pin 13. For this example, you will need:

  • Momentary button
  • Breadboard
  • Arduino board
  • 10K Ω resistor
  • Hook-up wire

 

You have to make three wire connection to begin your button control. The breadbox side has two rows that are long and vertical. This will be the red and black wire connecting the 5V ground and supply.

 

From pin 2 connect one wire to pushbutton leg. From the same button leg, make a connection to 10K Ω pull-down resistor to ground. The other leg button will be given the 5V supply.

 

When the button is not depressed, the connection between the legs of the button remains open. The pin has a connection only to the ground and so it returns the LOW reading. When you press the button down, the reading now goes to 5V and so you get a HIGH reading.

 

Note that you can reverse the functionality of the Button by reversing the connection. This makes the LED button to always be on but will go off when you press the button.

 

If you disconnect the i/o pin entirely, you will see the light blinking very randomly. The reason is that the input has now got a floating value and thus returns HIGH or LOW randomly. It is for this reason we include the pull-down resistor.

/*

Button
Turns on and off a light emitting diode(LED) connected to digital pin 13, when pressing a pushbutton attached to pin 2.
The circuit:
*
LED attached from pin 13 to ground
*
pushbutton attached to pin 2 from +5V
*
10K resistor attached to pin 2 from ground
*
Note: on most Arduinos there is already an LED on the board attached to pin 13.
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Button
*/
//
constants won’t change. They’re used here to
//
set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
//
initialize the LED pin as an output: pinMode(ledPin, OUTPUT);
//
initialize the pushbutton pin as an input: pinMode(buttonPin, INPUT);
}
void loop(){
//
read the state of the pushbutton value: buttonState = digitalRead(buttonPin);
//
check if the pushbutton is pressed.
//
if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
//
turn LED on: digitalWrite(ledPin, HIGH);
}
else {
//
turn LED off: digitalWrite(ledPin, LOW);
}
}

 

D) Simple Keyboard

This example will see the use of the tone function. Tone () command will generate sounds with different pitches. Here you will need the following material.

  • 3 numbers force-resisting sensors
  • 1 number 100 Ω resistor
  • 3 numbers 10K Ω resistors
  • Hook up wire
  • 8 Ω speaker
  • Breadboard

 

Connect the three force resisting sensors to 5V supply in parallel. Connect each of them to the pins 0 –2 with 10K Ω resistor to ground. When you run the code, it will check whether any of the FSRs are above the threshold assigned to it.

The sketch will assign one note to each FSR from an array of notes. Here is the code.

 

/*
keyboard
Plays a pitch that changes based on a changing analog input
circuit:
*
3 force-sensing resistors from +5V to analog in 0 through 5
*
3 10K resistors from analog in 0 through 5 to ground
*
8-ohm speaker on digital pin 8
created 21 Jan 2010
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain
http://arduino.cc/en/Tutorial/Tone3
*/
#include “pitches.h”
const int threshold = 10; // minimum reading of the sensors that generates a note
//
notes to play, corresponding to the 3 sensors: int notes[] = {
NOTE_A4, NOTE_B4,NOTE_C3 };
void setup() {
}
void loop() {
for (int thisSensor = 0; thisSensor < 3; thisSensor++) { // get a sensor reading:
int sensorReading = analogRead(thisSensor);
//
if the sensor is pressed hard enough: if (sensorReading > threshold) {
//
play the note corresponding to this sensor: tone(8, notes[thisSensor], 20);
}
}
}

You will see that there is a file pitch.h that contains all the pitches for each note. The notes are denoted by their key and a number according to the ascending of the pitch.

 

This table was originally made by Brett Hagmann who is famous for his work that resulted in the tone () function. You have to make a new tab and paste the following code to make the file.

 

E) Ultrasonic Sensor NewPing

You can use the Arduino to construct a simple ultrasonic sensor. This model is very slow and cannot be used with interrupt code. You can set a delay of 1 second if that is absolutely necessary. This program returns the distance (inches) and you can use the result for other calculations.

unsigned long echo = 0;

int ultraSoundSignal = 9; // Ultrasound signal pin
unsigned long ultrasoundValue = 0;
void setup ()
{
Serial.begin(9600);
pinMode(ultraSoundSignal, OUTPUT);
}
unsigned long ping(){
pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
digitalWrite(ultraSoundSignal, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignal, LOW); // Holdoff
pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
//
please note that pulseIn has a 1sec timeout, which may
//
not be desirable. Depending on your sensor specs, you
//
can likely bound the time like this — marcmerlin
//
echo = pulseIn(ultraSoundSignal, HIGH, 38000)
echo = pulseIn(ultraSoundSignal, HIGH); //Listen for echo
ultrasoundValue = (echo / 58.138) * .39; //convert to CM then to inches
return ultrasoundValue;
}
void loop()
{
int x = 0;
x = ping();
Serial.println(x);
delay(250); //delay 1/4 seconds.
}

 

F) Example Sketch for NewPing

#include <NewPing.h>
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping
results.
}
void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec).
29ms should be the shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print(“Ping: “);
Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo) Serial.println(“cm”);
}

 

Conditions For Building A Commercial Product

You can fashion your own commercial product but be sure to follow these conditions. If you make use of the design from some Arduino board Eagle files, then you are obliged to resubmit the modified files under the same Creative Commons Attribution Share-Alike license.

 

 The GPL covers the Arduino environment and this does not limit the sale of the software thus derived or selling the product commercially, the only condition being that it must keep any modification under the same Creative Commons license.

 

Design of the product need not be open source if you use an Arduino board in your commercial product. You do not have to disclose any information regarding the product.

 

 You can use the libraries and the Arduino core without being under any obligation to disclose information regarding the firmware. However, if you make modifications to the libraries or the core or

 

if you require updates from future version Arduino libraries or cores, you need to you need to submit modification under LGPL and make available object files which you use for relinking the firmware against updated versions.

 

Arduino Counterfeit Boards Learning To Spot The Fake

First off, check the color. Color must be teal. You can turn the board around and see the graphics on the back.

 

The typical logo will be an eight lying on its side with a negative and positive sign within the two orbs. Duplicates will be blue to deep blue in color. The font will not be Silk as it is in the original.

 

The printing is clear and symmetrical in the original. If the printing is not clear or does not have symmetry, then it is probably a fake. You will also see the map of Italy. This also must be clear. 

 

Look for the 501K component. Most fakes will have a green colored component that is available over the counter. The brown component is specially made for Arduino. Lastly, check if the Arduino is sold by an authorized dealer.

 

Use C to program your Arduino board

Arduino language, for the most part, consists of C/C++ functions that you call. The sketch will be changed in a minor way (for example when you create function prototypes automatically) and is then taken up by the C/C++ compiler avr-g++. So every C or C++ construct that is working for avr-g++ will work on Arduino. 

Recommend