0% found this document useful (0 votes)
74 views33 pages

Embedded System Programming

The document provides information about embedded system programming using Arduino microcontrollers. It discusses the Arduino Uno microcontroller board, how it can be programmed to sense and control physical objects. It also summarizes the different types of Arduino boards available and how they differ, including components of the boards and how to program and power them. Example code is provided to blink an LED with an Arduino.

Uploaded by

suleman idris
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views33 pages

Embedded System Programming

The document provides information about embedded system programming using Arduino microcontrollers. It discusses the Arduino Uno microcontroller board, how it can be programmed to sense and control physical objects. It also summarizes the different types of Arduino boards available and how they differ, including components of the boards and how to program and power them. Example code is provided to blink an LED with an Arduino.

Uploaded by

suleman idris
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 33

EMBEDDED SYSTEM PROGRAMMING

This section gives a clear introduction to Arduino (atmega family) microcontroller and it’s

Integrated Development Environment (IDE)

ARDUINO UNO MICROCONTROLLER

Arduino is an open source programmable circuit board that can be integrated into a wide variety

of makerspace projects both simple and complex. This board contains a microcontroller which is

able to be programmed to sense and control objects in the physical world. By responding to

sensors and inputs, the Arduino is able to interact with a large array of outputs such as LEDs,

motors and displays. Because of its flexibility and low cost, Arduino has become a very popular

choice for makers and maker-spaces looking to create interactive hardware projects.

Arduino was introduced back in 2005 in Italy by Massimo Banzi as a way for non-engineers to

have access to a low cost, simple tool for creating hardware projects. Since the board is open-

source, it is released under a Creative Commons license which allows anyone to produce their

own board. If you search the web, you will find there are hundreds of Arduino compatible clones

and variations available but the only official boards have Arduino in it’s name.

In the next section, we’re going to discuss a few of the Arduino boards available and how they

differ from each other.


Source Sparkfun.com

Types of Arduino Boards


Arduino is a great platform for prototyping projects and inventions but can be confusing when

having to choose the right board. If you’re brand new to this, you might have always thought that

there was just one “Arduino” board and that’s it. In reality, there are many variations of the

official Arduino boards and then there are hundreds more from competitors who offer clones.

Below are a few examples of the different types of Arduino boards out there. The boards with the

name Arduino on them are the official boards but there are also a lot of really great clones on the

market as well. One of the best reasons to buy a clone is the fact they are generally less

expensive than their official counterpart.


Source Sparkfun.com

Another factor to consider when choosing a board is the type of project you are looking to do.

Arduino Uno

One of the most popular Arduino boards out there is the Arduino Uno. While it was not actually

the first board to be released, it remains to be the most actively used and most widely

documented on the market.

Source Sparkfun.com
Board Breakdown
Here are the components that make up an Arduino board and what each of their functions are.

1. Reset Button – This will restart any code that is loaded to the Arduino board

2. AREF – Stands for “Analog Reference” and is used to set an external reference voltage

3. Ground Pin – There are a few ground pins on the Arduino and they all work the same

4. Digital Input/Output – Pins 0-13 can be used for digital input or output

5. PWM – The pins marked with the (~) symbol can simulate analog output

6. USB Connection – Used for powering up your Arduino and uploading sketches

7. TX/RX – Transmit and receive data indication LEDs

8. ATmega Microcontroller – This is the brains and is where the programs are stored

9. Power LED Indicator – This LED lights up anytime the board is plugged in a power source

10. Voltage Regulator – This controls the amount of voltage going into the Arduino board

11. DC Power Barrel Jack – This is used for powering your Arduino with a power supply

12. 3.3V Pin – This pin supplies 3.3 volts of power to your projects

13. 5V Pin – This pin supplies 5 volts of power to your projects

14. Ground Pins – There are a few ground pins on the Arduino and they all work the same

15. Analog Pins – These pins can read the signal from an analog sensor and convert it to digital

Arduino Power Supply


The Arduino Uno needs a power source in order for it to operate and can be powered in a variety

of ways. You can do what most people do and connect the board directly to your computer via a

USB cable. If you want your project to be mobile, consider using a 9V battery pack to give it

juice. The last method would be to use a 9V AC power supply.


Source Sparkfun.com

Arduino Breadboard
Another very important item when working with Arduino is a solder-less breadboard. This

device allows you to prototype your Arduino project without having to permanently solder the

circuit together. Using a breadboard allows you to create temporary prototypes and experiment

with different circuit designs. Inside the holes (tie points) of the plastic housing, are metal clips

which are connected to each other by strips of conductive material.


Source Sparkfun.com

On a side note, the breadboard is not powered on its own and needs power brought to it from the

Arduino board using jumper wires. These wires are also used to form the circuit by connecting

resistors, switches and other components together.

Here is a visual of what a completed Arduino circuit looks like when connected to a breadboard.

Source Sparkfun.com

On a side note, the breadboard is not powered on its own and needs power brought to it from the

Arduino board using jumper wires. These wires are also used to form the circuit by connecting

resistors, switches and other components together.


Source Sparkfun.com

How to Program Arduino

Once the circuit has been created on the breadboard, you’ll need to upload the program (known

as a sketch) to the Arduino. The sketch is a set of instructions that tells the board what functions

it needs to perform. An Arduino board can only hold and perform one sketch at a time. The

software used to create Arduino sketches is called the IDE which stands for Integrated

Development Environment.
Every Arduino sketch has two main parts to the program:

Void setup() – Sets things up that have to be done once and then don’t happen again.

Void loop() – Contains the instructions that get repeated over and over until the board is turned

off.
Selecting a Communication Port

Uploading an Arduino Sketch

1. Open Arduino IDE.

2. Go to File > Examples > 01.Basics > Blink


By default, the Arduino IDE comes pre-configured for the Arduino UNO. Click the Upload

button and wait a few seconds.

After a few seconds, you should see a Done uploading message.

Arduino Sensors

If you want your Arduino to sense the world around it, you will need to add a sensor. There are a

wide range of sensors to choose from and they each have a specific purpose. Below you will find

Some of the commonly used sensors in projects.

 Ultrasonic Sensor

 PIR Motion Sensor

 Light Sensor

 Degree of Flex Sensor

 Pressure Sensor

 Proximity Sensor

 Acceleration Sensor

 Sound Detecting Sensor


 RGB and Gesture Sensor

 Humidity and Temperature Sensor

Source Sparkfun.com

Difference between Digital, Analog and PWM

In digital pins, you have just two possible states, which are on or off. These can also be referred

as High or Low, 1 or 0 and 5V or 0V.

For example, if an LED is on, then, its state is High or 1 or 5V. If it is off, you’ll have Low, or 0

or 0V.

In analog pins, you have unlimited possible states between 0 and 1023. This allows you to read

sensor values. For example, with a light sensor, if it is very dark, you’ll read 1023, if it is very

bright you’ll read 0 if there is a brightness between dark and very bright you’ll read a value

between 0 and 1023.

PWM pins are digital pins, so they output either 0 or 5V. However these pins can output “fake”

intermediate voltage values between 0 and 5V, because they can perform “Pulse Width

Modulation” (PWM). PWM allows to “simulate” varying levels of power by oscillating the

output voltage of the Arduino.


Controlling an output

To control a digital output you use the digitalWrite() function and between brackets you write,

the pin you want to control, and then HIGH or LOW. To control a PWM pin you use the

analogWrite() function and between brackets you write the pin you want to control and a

number between 0 and 255.

Reading an input

To read an analog input you use the function analogRead() and for a digital input you use

digitalRead(). The best way for you to learn Arduino is practicing. So, choose a project and start

building something.

SOME EXAMPLE CODE AND SIMULATION.

Blinking an LED

LEDs are small, powerful lights that are used in many different applications. It is as simple as

turning a light on and off. Establishing this important baseline will give you a solid foundation as

we work towards experiments that are more complex.

Components Required

 1 × Breadboard
 1 × Arduino Uno R3

 1 × LED

 1 × 330Ω Resistor

 n × Jumper

To find out the polarity of an LED, look at it closely. The shorter of the two legs, towards the flat

edge of the bulb indicates the negative terminal. Components like resistors need to have their

terminals bent into 90° angles in order to fit the breadboard sockets properly. You can also cut

the terminals shorter.

int ledpin = 13;

// the setup function runs once when you pressed reset or power the board

void setup() {

pinMode (ledpin, OUTPUT);

//the loop function runs over and over again forever

void loop (){


digitalWrite(ledpin, HIGH);// turn the LED on (HIGHis the voltage level)

delay(1000); //wait for a second

digitalWrite(ledpin, LOW);// turn the LED off by making the voltage LOW

delay(1000); //wait for a second

pinMode(2, OUTPUT) − Before you can use one of Arduino’s pins, there is a need to tell

Arduino Uno R3 whether it is an INPUT or OUTPUT. A built-in “function” called pinMode() to

do this. digitalWrite(2, HIGH) − When you are using a pin as an OUTPUT, you can command

it to be HIGH (output 5 volts), or LOW (output 0 volts).

Push button with Arduino Uno

Turns on and off a light emitting diode (LED) connected to digital pin 13, when pressing a

pushbutton attached to pin 2.


Note: On most Arduinos there is already an LED on the board attached to pin 13.

Components Required

 1 × Arduino Uno R3
 1 × LED

 1 × 330Ω Resistor

 1 x Push Button

Schematic
Code

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);
}
}

Traffic Lights

In this project we are going to build a traffic lights system:

 There are 3 LEDs with different colors (green, yellow and red) to mimic the traffic lights

for the cars.

 There are 2 LEDs with different colors (green and red) to mimic the traffic lights for the

pedestrians.

 There is a pushbutton to mimic the ones in the pedestrian’s traffic lights.

Components required

 1x Breadboard

 Arduino UNO

 3x 5mm LED (1x red, 1x yellow, 1x green)

 2x 3mm LED (1x red, 1x green)

 5x 220Ohm Resistor

 1x 10kOhm Resistor

 1x pushbutton

 Jumper Wires

Schematic
Code

 The car light is always green, and so the pedestrian light is always red unless someone

presses the button.

 When someone presses the button here’s what happens:

 The car light changes to yellow and then to red.

 The pedestrian light changes to green.

 The lights are in this state for a while (in the code this time is the variable crossTime).

 The pedestrian green light flashes and goes to red.

 The car light changes from red to green.

All these actions will be inside the function changeLights(). Everytime you want to change the

lights, you just need to call the changeLights() function.


int redCar = 13;
int yellowCar = 12;
int greenCar = 11;
int greenPed = 2;
int redPed = 3;
int button = 7;
int crossTime = 2000;
unsigned long changeTime;
void setup() {
// initialize timer
changeTime = millis();
// here we are initializing our pins as outputs
pinMode(redCar, OUTPUT);
pinMode(yellowCar, OUTPUT);
pinMode(greenCar, OUTPUT);
pinMode(redPed, OUTPUT);
pinMode(greenPed, OUTPUT);
pinMode(button, INPUT);
//turn on the green light
digitalWrite(greenCar, HIGH);
digitalWrite(redPed, HIGH);
digitalWrite(redCar, LOW);
digitalWrite(yellowCar, LOW);
digitalWrite(greenPed, LOW);

Serial.begin(9600);
}
void loop() {
// this variable will tell us if the button is pressed
int state = digitalRead(button);
Serial.println(state);
// if the button is pressed and if it has passed 5 seconds since last button
press
if (state == HIGH && (millis() - changeTime) > 5000) {
//call the function to change the lights
changeLights();
}
}
void changeLights() {
digitalWrite(greenCar, LOW); // the green LED will turn off
digitalWrite(yellowCar, HIGH); // the yellow LED will turn on for 2 second
delay(2000);
digitalWrite(yellowCar, LOW); // the yellow LED will turn off
digitalWrite(redCar, HIGH); // the red LED will turn on for 5 seconds
digitalWrite(redPed, LOW);
digitalWrite(greenPed, HIGH);
delay(crossTime);
// flash the ped green
for (int x=0; x<10; x++) {
digitalWrite(greenPed, LOW);
delay(100);
digitalWrite(greenPed, HIGH);
delay(100);
}
digitalWrite(greenPed, LOW);
digitalWrite(redCar, LOW);
digitalWrite(redPed, HIGH);
digitalWrite(greenCar, HIGH);
changeTime = millis();
}

Interfacing 7-segment display (common cathode)

Seven-segments are practical, efficient, and cost-effective devices that are used to display
alphanumeric numbers. You will find many practical applications of these displays around you.
For example, if you go to the market, you will see a large digital clock based on a seven-segment
display. In movies, you have seen a hero trying to deactivate a bomb and at the time he keeps his
eye on the digital clock. If you notice the digital clock, it also uses 7-segment devices.

For example, if we are designing an Ac voltmeter or ac current meter using Arduino, we can use
a seven-segment display instead of a 16X2 liquid crystal display to display voltage and current
values. The seven-segment display has many applications in embedded systems and Arduino
based projects.

One of the popular examples for the use of a seven-segment display is the NASA space shuttle
launch countdown display.

Types of Seven Segment Displays

There are two types of seven segment displays such as common anode and common cathode.

Common Anode Display

In common anode display, all the anodes terminals of eight light emitting diodes are common
and connect with 5 volt power supply. In normal condition, we apply logic high from Arduino to
each segment. Therefore, each segment remains off or does not glow. Similarly, when we want
to turn on a specific LED of a seven-segment device, we provide logic low signal. Because LED
glows only when there will be a logic high signal on anode side and logic low signal on cathode
side such is the case of common anode type display.

Common Cathode Display


In common cathode segment display, all the cathodes of eight light emitting diodes are common
and connect with the ground. In order to turn off any segment of 7-segment, we apply logic low
from Arduino to this segment. Similarly, when we want to turn on a specific LED of a seven-
segment device, we provide logic high signal from an Arduino digital output pin. Because LED
glows only when there will be a logic high signal on anode side and logic low signal on cathode
side such is the case of common cathode type display.

Components required

 1x Breadboard

 Arduino UNO

 1x 7segment common cathode

Schematic

Code
#include "SevSeg.h"
SevSeg sevseg;
void setup()
{
//define number of seven-segment digits to one
byte sevenSegments = 1;
//variable used to define the number of seven segment and common pins
//but we are using only one 7-segment. Hence leave it empty
byte CommonPins[] = {};
//array to store arduino pin connections with LED segments in order: A, B,
C, D, E, F, G, DP
byte LEDsegmentPins[] = {2, 3, 4, 6, 7, 8, 9, 5};
bool resistorsOnSegments = true;
//Initialize sevseg object that created above with input arguments defined
already
sevseg.begin(COMMON_ANODE, sevenSegments, CommonPins, LEDsegmentPins,
resistorsOnSegments);
//uncomment the following line for common cathode type display and comment
the above
//sevseg.begin(COMMON_CATHODE, sevenSegments, CommonPins, LEDsegmentPins,
resistorsOnSegments);
sevseg.setBrightness(90);
}
void loop()
{
//loop display counter values from 0-9
for(int i = 0; i < 10; i++)
{
sevseg.setNumber(i); // Display counter value
sevseg.refreshDisplay(); // refresh required
delay(1000); // delay of one second
}
}

Interfacing Liquid Crystal Display (16x2) in 4-bit mode


16x2 LCD is named so because it has 16 columns and 2 rows. There are a lot of combinations

available like 8x1, 8x2, 10x2, 16x1, 16x2 etc. All the above mentioned LCD display have 16

pins and the programming approach is also the same. The LCD can work in two different modes,

namely the 4-bit and 8-bit mode.

Schematic

Code

#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins


LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.

void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 0);
lcd.print("Hello, World!");
delay(1000);
lcd.clear();

lcd.print("Proteus vs Arduino");
delay(1000);
lcd.clear();
}

Interfacing L293D to control speed and direction of DC motor

There are three different type of motors:

 DC motor

 Servo motor

 Stepper motor

A DC motor (Direct Current motor) is the most common type of motor. DC motors normally

have just two leads, one positive and one negative. If you connect these two leads directly to a

battery, the motor will rotate. If you switch the leads, the motor will rotate in the opposite

direction.

Warning − Do not drive the motor directly from Arduino board pins. This may damage the
board. Use a driver Circuit or an IC (L298D).

Components Requirement

 1x Arduino UNO
 2x Small 5V DC Motor

 1x L293D

Schematic

Code

int ena = 9;
int in1 = 8;
int in2 = 7;
int in3 = 2;
int in4 = 4;
void setup() {
// put your setup code here, to run once:
pinMode(ena, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
}

void loop() {
// for clockwise
analogWrite(ena, 180);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(2000);
// for brake
digitalWrite(in1, HIGH);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, HIGH);
delay(1000);
// for counter clockwise
analogWrite(ena, 255);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(2000);
// for brake
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
delay(1000);
}

Interfacing ultrasonic sensor

The HC-SR04 ultrasonic sensor uses sonar to determine distance to an object like bats do. It

offers excellent non-contact range detection with high accuracy and stable readings in an easy-

to-use package. From 2cm to 400 cm or 1” to 13 feet. Its operation is not affected by sunlight or

black material

The ultrasonic sensor uses sonar to determine the distance to an object. Here’s what happens:

1. The transmitter (trig pin) sends a signal: a high-frequency sound;

2. When the signal finds an object, it is reflected and…

3. The transmitter (echo pin) receives it.


Components required

 Arduino UNO

 Ultrasonic Sensor (HC-SR04)

 Breadboard

 Jumper wires

Schematic
Code

int trigPin = 11; //Trig - green Jumper


int echoPin = 12; //Echo - yellow Jumper
long duration, cm, inches;
void setup() {
//Serial Port begin
Serial.begin (9600);
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose

// duration is the time (in microseconds) from the sending


// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
cm = (duration/2) / 29.1;
inches = (duration/2) / 74;
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(250);
}

Interfacing PIR motion sensor

Components required

 1x PIR Motion Sensor (HC-SR501)

 Arduino UNO

 1x LED

 Jumper wires
Schematic

Code

int led = 13; // the pin that the LED is atteched to


int sensor = 2; // the pin that the sensor is atteched to
int state = LOW; // by default, no motion detected
int val = 0; // variable to store the sensor status (value)
void setup() {
pinMode(led, OUTPUT); // initalize LED as an output
pinMode(sensor, INPUT); // initialize sensor as an input
Serial.begin(9600); // initialize serial
}
void loop(){
val = digitalRead(sensor); // read sensor value
if (val == HIGH) { // check if the sensor is HIGH
digitalWrite(led, HIGH); // turn LED ON
delay(1000); // delay 1000 milliseconds
if (state == LOW) {
Serial.println("Motion detected!");
state = HIGH; // update variable state to HIGH
}
}
else {
digitalWrite(led, LOW); // turn LED OFF
delay(2000); // delay 2000 milliseconds
if (state == HIGH){
Serial.println("Motion stopped!");
state = LOW; // update variable state to LOW
}
}
}

Interfacing MQ-2 gas sensor

The MQ-2 smoke sensor is sensitive to smoke and to the following flammable gases:

 LPG

 Butane

 Propane

 Methane

 Alcohol

 Hydrogen

The resistance of the sensor is different depending on the type of the gas.

The smoke sensor has a built-in potentiometer that allows you to adjust the sensor digital output

(D0) threshold. This threshold sets the value above which the digital pin will output a HIGH

signal.

The voltage that the sensor outputs changes accordingly to the smoke/gas level that exists in the

atmosphere. The sensor outputs a voltage that is proportional to the concentration of smoke/gas.

In other words, the relationship between voltage and gas concentration is as shown:

 The greater the gas concentration, the greater the output voltage

 The lower the gas concentration, the lower the output voltage
The output can be an analog signal (A0) that can be read with an analog input of the Arduino or a

digital output (D0) that can be read with a digital input of the Arduino.

In this example, sensor analog output voltage and when the smoke reaches a certain level is read,

it will make sound a buzzer and a red LED will turn on. When the output voltage is below that

level, a green LED will be on.

Components required

 1 x MQ-2 gas sensor

 Arduino UNO

 1x Breadboard

 1 x red LED

 1 x green LED

 1 x buzzer

 3 x 220Ω resistor

 Jumper wires
Schematic

Code

int redLed = 12;


int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 400;
void setup() {
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(smokeA0, INPUT);
Serial.begin(9600);
}
void loop() {
int analogSensor = analogRead(smokeA0);
Serial.print("Pin A0: ");
Serial.println(analogSensor);
// Checks if it has reached the threshold value
if (analogSensor > sensorThres)
{
digitalWrite(redLed, HIGH);
digitalWrite(greenLed, LOW);
tone(buzzer, 1000, 200);
}
else
{
digitalWrite(redLed, LOW);
digitalWrite(greenLed, HIGH);
noTone(buzzer);
}
delay(100);
}

You might also like