Arduino Part 1: Topics: Microcontrollers Programming Basics: Structure and Variables Digital Output
Arduino Part 1: Topics: Microcontrollers Programming Basics: Structure and Variables Digital Output
Arduino Part 1: Topics: Microcontrollers Programming Basics: Structure and Variables Digital Output
Topics:
Microcontrollers
Programming Basics: structure
and variables
Digital Output
What is a Microcontroller
• A small computer on a
single chip
• containing a processor,
memory, and
input/output
• Typically "embedded"
inside some device that
they control
• A microcontroller is often
small and low cost
What is a Development Board
• A printed circuit
board designed to
facilitate work with
a particular
microcontroller.
• Typical components include:
• power circuit
• programming interface
• basic input; usually buttons and LEDs
• I/O pins
The Arduino Development Board
Making-robots-with-arduino.pdf
The Arduino Microcontroller: Atmel ARV
Atmega 328
Specification
What is Arduino?
What is Arduino?
• is a programmable multi-purpose
electronic platform with its hardware
and software designed to run in an open-
source environment.
• Arduino comes with its own open-
source Integrated Development
Environment (IDE)
Why is Arduino Popular?
• Easy installation
• The ease of use
• Simple programming language
• Relatively cheaper access
• Good back-up
• Replaceable processor
• Speed of communication
Flaws of Arduino
• Small resolution
• No debugger
• Limited program execution
• Its programming language
• Small RAM and memory (2 kb of RAM and 3
kb of flash memory)
• Usage of 5V.
Arduino Boards (Types)
Arduino Leonardo Board
• Among the first developments of Arduino boards
• one of the cheapest and easy to use among all the
boards.
• fully dependent on ATmega32u4 microcontroller with
a “clock speed” of 16 MHz.
• equipped with 2.5 Kb SRAM memory while it sits on
a 32 Kb flash memory.
Arduino Boards (Types)
Arduino Uno (R3)
• Among the most popular Arduino
boards
• has 14 pins digital input/output
(I/O), with six pins being used as
a “pulse width modulation”
(PWM) output
• come with ATmega328 processor,
a clock speed of 16 MHz
• SRAM memory is 2 KB while the
flash memory is 32 KB.
Arduino Boards (Types)
LilyPad Arduino Board
• board is wearable, and can be in e-
textile technology
• design is for textiles in particular, and
the board is also washable. It can be
sewed into clothes with tread.
• Everything on this board like the sensor
circuits, power and I/O are specifically
designed to serve this purpose.
• consists of an Arduino bootloader with
variable 2V to 5V power supply sitting
on ATMEGA328 microcontroller.
Arduino Boards (Types)
Arduino Mega (R3)
• Among the most popular Arduino
boards
• has 14 pins digital input/output
(I/O), with six pins being used as
a “pulse width modulation”
(PWM) output
• come with ATmega328 processor,
a clock speed of 16 MHz
• SRAM memory is 2 KB while the
flash memory is 32 KB.
Getting Started
todbot.com/blog/bionicarduino
Arduino Integrated Development Environment (IDE)
Parts of the IDE
• Serial Monitor
• Tab Button - This lets you create multiple files in your
sketch.
• Sketch Editor - This is where you write or edit sketches
• Text Console - This shows you what the IDE is currently
doing and is also where error messages display if you make
a mistake in typing your program. (often called a syntax
error)
• Line Number -This shows you what line number your
cursor is on. It is useful since the compiler gives error
messages with a line number
Select Serial Port and Board
Status Messages
Add an External LED to pin 13
www.instructables.com
A Little Bit About Programming
• Code is case
sensitive
• Statements are
commands and
must end with a
semi-colon
Our First Program
// Example 01
/*
Blinking Onboard LED
Turns on the onboard LED on for one second, then off for one second, repeatedly.
*/
// Digital Pin 13 has an LED connected on your Tinkduino.
int LED = 13;
www.mikroe.com/chapters/view/1
pinMode(pin, mode)
Sets pin to either INPUT or OUTPUT
digitalRead(pin)
Reads HIGH or LOW from a pin
digitalWrite(pin, value)
Writes HIGH or LOW to a pin
Electronic stuff
Output pins can provide 40 mA of current
Writing HIGH to an input pin installs a 20KΩ pullup
Arduino Timing
• delay(ms)
– Pauses for a few milliseconds
• delayMicroseconds(us)
– Pauses for a few microseconds
Digital? Analog?
• Digital has two values: on and off
• Analog has many (infinite) values
• Computers don’t really do analog, they quantize
• Remember the 6 analog input pins---here’s how
they work
todbot.com/blog/bionicarduino
Bits and Bytes
Variables
www3.ntu.edu.sg
Putting It Together
• Complete the sketch
(program) below.
• What output will be
generated by this program?
• What if the schematic were
changed?
www.ladyada.net/learn/arduino
ARDUINO LESSON 2
Variables
Place for storing a piece of data
Has a name, value, and type
int iamVariable = 9;
char storeChars;
float saveDecimal;
Variables
Variable Scope
Global – recognized anywhere in the sketch
Variable Qualifiers
CONST – make assigned variable value unchangeable
Types
INT
UNSIGNED INT
LONG
UNSIGNED LONG
FLOAT
CHAR
BYTE
BOOLEAN
Identifiers and Keywords
Keywords
For Ex : sum = a+b. In this equation sum, a and b are the identifiers or
variable names representing the numbers stored in the memory locations.
Rules to be followed for constructing the Variable names (identifiers):
1. They must begin with a letter and underscore is considered as a letter.
2. It must consist of single letter or sequence of letters, digits or underscore
character.
3. Uppercase and lowercase are significant. For ex: Sum, SUM and sum
are three distinct variables.
4. Keywords are not allowed in variable names.
5. Special characters except the underscore are not allowed.
6. White space is also not allowed.
Variable Declarations
Integer - int
Floating point - float
Double floating point - double
Character - char
Variable Declarations
If two are more variables of the same data type has to be declared they can be clubbed as
shown in example given below.
short int a, b, c ;
long int r, s, t ;
The above declarations cab also be written as :
short a, b, c;
long r, s, r;
Assigning Values to Variables
For example:
const int tax_rate = 0.30;
• do while
• for
• while
Basic Repetition
void loop ( ) { }
Basic Repetition
void loop ( ) { }
Basic Repetition
void loop ( ) { }
While Loop
Continue program until a given condition is true
Syntax:
while (condition)
{
// do something here until condition becomes
false
}
Basic Repetition
void setup()
{
pinMode(outLED, OUTPUT);
int count = 0;
while (count <= 2)
{
digitalWrite(outLED, HIGH);
delay(1000);
digitalWrite(outLED, LOW);
delay(1000);
count++;
}
}
void loop()
{
}
Basic Repetition
Logical Operator
Logical Operator
Conditional AND
Symbolized by &&
Conditional OR
Symbolized by ||
Used when either of the conditions need to be satisfied.
Conditional NOT
Symbolized by !
Do-While Loop
Same as While loop however this structure allows the loop
to run once before checking the condition
Syntax:
do
{
// do something here until condition becomes
false
} while (condition) ;
Basic Repetition
For Loop
Distinguished by a increment/decrement
counter for termination
Syntax:
break;
Used to terminate a loop
regardless of the state of the
condition
Required in Switch-Case statements
as an exit command
Timing Controls
delay()
Halts the sequence of execution during the time
specified
Syntax:
delay(milliseconds);
Pull up resistor - connection results in Pull down resistor - used for the
maintaining high state, when the external devices connection of an input and GND.
are disconnected or do not give signals, and
protects against unknown states.
Variables
Array – a collection of variables of the same type
accessed via a numerical index
It is a series of variable instances placed adjacent in
memory, and labeled sequentially with the index
Array
Array
An array is a collection of variables that are indexed with an index number
Example
int timer = 100;
int pins[] = { 2, 3, 4, 5, 6, 7 };
int numpins = 6;
void setup()
{
int i;
for (i = 0; i < num pins; i++) {
pinMode(pins[i], OUTPUT);
}
Latch and Debounce
variables?
Example
ANALOG INPUT
Analog-to-Digital Conversion
Connecting digital circuitry to sensor devices is simple
if the sensor devices are inherently digital themselves.
Switches, relays, and encoders are easily interfaced
with gate circuits due to the on/off nature of their
signals. However, when analog devices are involved,
interfacing becomes much more complex.
Electronically translating analog signals into digital
(binary) quantities is possible with the use of an
analog-to-digital converter.
Analog-to-Digital Conversion
Analog-to-digital conversion is the process of
converting a continuous quantity to a discrete time
digital representation. The electronic device used
for this process is an analog-to-digital converter
(ADC). ADCs convert an input analog voltage or
current to a digital number proportional to the
magnitude of the voltage or current.
ADCs are used virtually everywhere where an
analog signal has to be processed, stored, or
transported in digital form.
Pulse Width Modulation (PWM)
Pulse Width Modulation, or PWM, is a technique for
getting analog results with digital means. Digital control
is used to create a square wave, a signal switched
between on and off. This on-off pattern can simulate
voltages in between full on (5 Volts) and off (0 Volts) by
changing the portion of the time the signal spends on
versus the time that the signal spends off. The duration
of "on time" is called the pulse width.
To get varying analog values, you change, or modulate,
that pulse width. If you repeat this on-off pattern fast
enough with an LED for example, the result is as if the
signal is a steady voltage between 0 and 5v controlling
the brightness of the LED.
Analog Input
analogRead()
Function to perform ADC
Returns value from 0-1023
Syntax:
analogRead(pin)
Reads the value from the specified analog pin. The Arduino
board contains a 6 channel 10-bit analog to digital
converter (A0 – A5) . This means that it will map input
voltages between 0 and 5 volts into integer values between
0 and 1023. This yields a resolution between readings of: 5
volts / 1024 units or, .0049 volts (4.9 mV) per unit.
Analog Output
analogWrite()
Supported pins: 3, 5, 6, 9, 10 and 11
value: ranges from 0 - 255
Syntax:
analogWrite(pin, value)
pin: the pin to write to
Ex: analogWrite(9, 255);
A potentiometer is a simple knob that provides a
variable resistance, which we can read into the
Arduino board as an analog value
Example: Blinking
int sPin = A5; sValue = analogRead(sPin);
int led = 5; digitalWrite(led, HIGH);
int sValue = 0; delay(sValue);
void setup() { digitalWrite(led, LOW);
pinMode(sPin, INPUT); delay(sValue);
pinMode(led, OUTPUT); Serial.print(“delay=”);
Serial.begin(9600); Serial.println( sValue);
} delay(100);
void loop() }
{
Serial Monitor
All Arduino boards have at least one serial port (also
known as a UART or USART): Serial. It communicates on
digital pins 0 (RX) and 1 (TX) as well as with the
computer via USB. Thus, if you use these functions, you
cannot also use pins 0 and 1 for digital input or output.
Arduino environment’s Serial Monitor lets you
communicate with the Arduino board. In Serial Monitor
you could see anything the Arduino sends to its serial
port. It is very useful for debugging purposes, like
tracking variable values and reading input and output
values coming to and from the Arduino.
Serial Monitor
The common functions used in Serial Monitor:
begin(speed) – sets the data rate in bits per second (baud) for serial
data transmission. For communicating with the computer, use one of
these rates: 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800,
38400, 57600, or 115200. You can, however, specify other rates -
for example, to communicate over pins 0 and 1 with a component
that requires a particular baud rate. The common setting for the
baud rate is 9600 bps.
Computer
is a programmable machine that receives input,
stores and manipulates data, and provides output
in a useful format.
Hardware
a. Application software
is computer software designed to help the user to
perform singular or multiple related specific tasks
Examples:
Enterprise software, Accounting software, Office
suites, Graphics software and media players
b. System software
computer software designed to operate the
computer hardware and to provide and maintain a
platform for running application software.
Peopleware
computer operator / user
Procedure
a set of coded instructions that tell a computer
how to run a program or calculation.
Connectivity
how hardware or software devices can
communicate with other devices
COMPONENTS OF COMPUTER SYSTEMc
• Input Unit/Devices
• Output Unit/Devices
• Central Processing Unit
• Memory Unit/Storage Devices
COMPONENTS OF COMPUTER SYSTEM
Control Unit
The control unit is responsible for controlling the transfer of
data and instructions among other units of a Computer. It is
considered as the “Central Nervous System” of computer, as
it manages and coordinates all the units of the computer. It
obtains the instructions from the memory, interprets them
and directs the operation of the computer. It also performs
the physical data transfer between memory and the
peripheral device.
COMPONENTS OF COMPUTER SYSTEM
Registers
Registers are small high-speed circuits (memory locations), which are
used to store data, instructions and memory addresses (memory location
numbers).
Buses
2. External bus
Known as expansion bus, allows peripherals to connect
and communicate with the motherboard and its
components.
BUS STRUCTURE
Microprocessor System
Introduction
• The word ‘system’ is used to
describe any organization or
device that includes three
features.
• A system must have at least
one input, one output and
must do something, i.e. it
must contain a process.
• Often there are many inputs
and outputs. Some of the
outputs are required and
some are waste products. To
a greater or lesser extent, all
processes generate some
waste heat.
Example
A motor car will usually require fuel, water for cooling purposes and a battery to
start the engine and provide for the lights and instruments.
Its process it to burn the fuel and extract the energy to provide transportation for
people and goods.
The outputs are the wanted movement and the unwanted pollutants such as
gases, heat, water vapour and noise.
The motor car contains other systems within it. An electricity is required as an
input to start the engine and provide the lights
A microprocessor system
• Integrated circuits
An electronic circuit fabricated out of a solid block of
semiconductor material. This design of circuit, often
called a solid state circuit, allows for very complex
circuits to be constructed in a small volume. An
integrated circuit is also called a ‘chip’.
• Microprocessor (µp)
This is the device that you buy: just an integrated
circuit
On its own, without a surrounding circuit and applied
voltages it is quite useless. It will just lie on your
workbench staring back at you.
Terminology
• Microprocessor-based system
This is any system that contains a microprocessor, and does not
necessarily have anything to do with computing. In fact, despite all
the hype, computers use only a small proportion of all the
microprocessors manufactured. The garage door opening system is
a microprocessor-based system or is sometimes called a
microprocessor controlled system.
• Microcomputer
The particular microprocessor-based systems that happen to be
used as a computer are called microcomputers. The additional
circuits required for a computer can be built into the same integrated
circuit giving rise to a single chip microcomputer.
• Microcontroller
This is a complete microprocessor-based
control system built onto a single chip. It is
small and convenient but doesn’t do
anything that could not be done with a
microprocessor and a few additional
components.
What is microprocessor?
1. RISC
2. CISC
3. Hybrid processor – combination of RISC
and CISC
4. Special purpose processor – for
networking
Types of Automation
Program Counter
Program Counter
Inside CPUs
(cont’)
Instruction Register
Flags ALU Instruction Register
Instruction decoder,
Flags ALU timing,
Instruction and control
decoder,
timing, and control
Internal Register A
buses
Internal
buses Register A Register B
Register C
Register B
Register D
Register C
Department of Computer Science and Information Engineering
HANEL Register D
National Cheng Kung University, TAIWAN 30
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
CPU Execution Cycle
INSIDE CPUs
•ALU (arithmetic/logic unit)
•Program counter
Instruction decoder
• Accessing memory
– Each location in a memory is given a number,
called an address
– the 16 locations of memory would be numbered from 0 to
15, or in binary 0000–1111
2
Peripheral
devices I/O
input output
Microcontroller
• It is simply a computer on a chip. It is entirely self-contained
computers built on a single piece of silicon that incorporate
all of the functions of a traditional Computer.
• It is a special device generally found in a stand alone system
wherein medium to large scale computing is required. The
microcontroller serve as the data acquisition/analysis and
processing device in such applications
– a processing unit
– program (permanent) memory
– data (temporary) memory
– a clock/oscillator circuit
– a timer/counter circuit
– general purpose I/O ports
Central Processing Unit (CPU)
Back
Memory Unit
Memory Chips
• Serve as the prime storage for each data that shall and has
undergone processing
• Used as the storage register for I/O functions
• Contains the CORE control systems of the microcontroller
Industry Application
• Logging Functions
• Control Functions
• Timing Functions
• Display Functions
• Sensor Information Processing
Household Application
• Microwaves
• Televisions
• Television remote control units
Dominant Microcontroller Brands
• Motorola
• Siemens
• ZILOG
• ATMEL
• Microchip