Lec 1
Lec 1
EE416
BY Ibrahim Abdelsalam
Microprocessor Based process control
EE416
Course Objective
• Understand embedded system main components.
• Learn how to interface the microcontroller analog /digital inputs and
output devices (signal conditioner and actuator )
• Use the microcontroller to build a closed loop automatic system
• Write and troubleshoot C++ code for microcontroller
What is Embedded system
• A combination of hardware and
software ,which makes a system
dedicated for an application or
specific part of an application or
part of a larger system.
When it is appropriate to use embedded
system (or microcontroller)?
• Intelligence is required.
• Reduce the complexity of the system.
• If the cost of the microcontroller is less than using individual
components.
• The high number of sensors and actuators need to be integrated into
the system.
• If it is required to perform communication with other devices.
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Signal condition
• Signal conditioning: are the circuit used to process the output signal
from sensors of a measurement system to be suitable for the next stage
of operation Signal
condition
Amplification, Impedance
attenuation, level shifting Clipping Clamping Filtering
changing
and inversion
Amplification Attenuation Inversion Level shifting
Clipping Clamping
Filtering
Filtering is the process of removing a
certain band of frequencies from a
signal and permitting others to be
transmitted.
• The Pass Band: the range of
frequencies passed by the filter
• The Stop Band: the range not passed
by the filter.
• CUT OFF frequency: the boundary
between stopping and passing Characteristics of ideal filters: (a) low-pass filter, (b) high-pass
filter, (c) band-pass filter, (d) band-stop filter
Technically CUTOFF frequency is defined as the frequency
at which the output voltage is 70.7% of that in the pass
band.
Microcontroller protection
Normally protection is provided against high current and high voltage
which may damage the microcontroller.
Passive
elements
R
5 DC supply 0 to 5V DC
output signal
±5 AC input R
signal
Weston bridge
• It can be used to convert a resistance change to a voltage change as in the following
RC filters
• The Low Pass Filter – the low pass filter only allows low frequency signals from 0Hz to its cut-
off frequency, ƒc point to pass while blocking those any higher.
• The High Pass Filter – the high pass filter only allows high frequency signals from its cut-off
frequency, ƒc point and higher to infinity to pass through while blocking those any lower.
• The Band Pass Filter – the band pass filter allows signals falling within a certain frequency
band setup between two points to pass through while blocking both the lower and higher
frequencies either side of this frequency band.
Low Pass filter High Pass filter
R C
1 1
Vin C Vout Fc Vout Fc
2 RC Vin R
2 RC
1 1
CLPF 510 PF
2 fC 2 R 2 *30, 000*10, 000
The nearest preferred value of the calculated capacitor value of 510pF is 560pF
DC_fault
1 1
CHPF 15.8nF
2 fC1 R 2 *1, 000*10, 000
The nearest preferred value of the calculated capacitor value of 15.8nF is 15.0pF
1 1
Fr FL * FH *
2 * *10 * 510 *10
4 12
2 * *10 4 *15 *10 9
Fr FL * FH 1060 * 28420 5.48 Hz
Signal condition using Active elements
(Operational Amplifier)
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
+Vs
V- I-
-
Ideal OpAmp A o= Vo
V+
I+ +
• Infinite gain -Vs
• Infinite input resistance (I-=I+)
• V+=V-
Comparator Voltage follower[buffer]
+Vs
V2
V1 - Vo
+Vs
Vi +
V2 - Vo Vo -Vs
+Vs
V1 +
-Vs -Vs
Vo Vi
Non-Inverting
Inverting Amplifier
R2 Amplifier R2
Io Io
R1 +Vs R1 +Vs
Vi I-
V- V-
- Vo
I-
-
Ii A o= Vo
Ig A o=
V+ V+
I+ + Vi +
-Vs I+
-Vs
Ig I I o
Ii I I o
V Vo V
Vi V V Vo 0
0 R1 R2
R1 R2
V V Vi
R2
Vo Vi R2
R1 Vo 1 Vi
R1
Summing Inverter Difference Amplifier
R2
R1
Vi2 R2
Io
I2 R1 +Vs
Io
Vi1 I-
V-
Vi1
R1 +Vs - Vo
V- I- I1 A o=
- V+
I1 A o= Vo Vi2
I+ +
I2 R1 -Vs
V+
I+ + Ig
R2
-Vs
I 0 I1 I 2 R2
V Vi 2 (1)
R1 R2
V Vo V1 V V2 V
Vi1 V V Vo
R2 R1 R1 (2)
R1 R2
V V 0
1 in 2
R2
Vo V1 V2 R2
R1 Vo V 1 V 2
R1
• The grid voltage (220V) is a feedback to the microcontroller, a
220V/6V step-down transformer is used as a voltage transducer.
Design a signal condition circuit such as the microcontroller input
voltage must be in a range from 0 to 5 V. also it required in your
design to protect the microcontroller from high voltage spikes and
from inverse polarity.
Natural gas is stored in a tank. Its temperature is monitored using a temperature
sensor with sensitivity 10 mV/C. The gas is stored at a temperature of 25C, and due
to pressure changes the gas temperature may reach 100 C. The sensor range is
0~150 C & is to be connected to a A/D converter with the following characteristics:
1-10-bit resolution, 2-Conversion time=100μsec, 3-Clock frequency of 20 KHz, 4-
Sample & Hold 2 cycles, and 5-Range of analog signal 0 to 5V.
+
-Vs
C
The main advantage of this configuration is that the Op-Amp high input impedance
prevent excessive loading on the filter output
C
R2
R2
Io
R1 +Vs Io
R1 +Vs
V- I-
- Vo
Vi
V- I-
-
Ig A o= A o= Vo
V+ Ii
Vi
I+ + V+
I+ +
Rf -Vs -Vs
C
Active High Pass Filter
R2
R2
Io
+Vs R1 +Vs Io
V- I- R1 +Vs
Vi
- Vo - C
C Vi I-
V-
+ Ig
C V+
A o= Vo - Vo
Ii A o=
R
-Vs Vi
I+ + V+
+
-Vs I+
Rf -Vs
1
Fc
2 RC
Active Band Pass Filter
C2
R2
Io
R1 +Vs
C1
Vi V- I-
- Vo
Ii A o=
V+
I+ +
-Vs
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Microcontroller Digital Inputs
• Pull down resistance Pull up resistance
5V supply 5V supply
Microcontroller
Microcontroller
active high active low
Push Button (normally open or normally closed)
Switches
Limit switches
Inductive Proximity Switch
Capacitive Proximity Switch
Photocell Switch
Rotary Encoder
Shaft Encoder
• A shaft encoder rotary encoder, is an electro-mechanical device used to convert
the angular position of a shaft or axle to an angle or digital code, making it a sort
of transducer.
Standard Binary Encoding
Sector Contact 1 Contact 2 Contact 3 Angle
1 off Off off 0° to 45°
2 off Off on 45° to 90°
3 off On off 90° to 135°
4 off On on 135° to 180°
5 on Off off 180° to 225°
6 on Off on 225° to 270°
7 on On off 270° to 315°
8 on On on 315° to 360°
Gray encoding
• This is a system of binary counting in which two adjacent codes differ
in only one position.
Gray Coding
6 on on on 225° to 270°
Microcontroller
Microcontroller
Active High Active Low
Relay Output
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Introduction to Arduino
• Arduino UNO
• Arduino IDE (integrated development environment )
[ WWW.Arduino.cc]
Arduino V.S conventional microcontroller
• Computational power
• Ease of programming
• Ease of interfacing
• Over all time required
• Speed if operation
• Open source system
Arduino UNO
Arduino UNO
Microcontroller ATmega328P
Operating Voltage 5V
Input Voltage (recommended) 7-12V
Input Voltage (limit) 6-20V
14 (of which 6 provide PWM
Digital I/O Pins
output)
PWM Digital I/O Pins 6
Analog Input Pins 6
DC Current per I/O Pin 20 mA
DC Current for 3.3V Pin 50 mA
32 KB (ATmega328P)
Flash Memory of which 0.5 KB used by
bootloader
SRAM 2 KB (ATmega328P)
EEPROM 1 KB (ATmega328P)
Clock Speed 16 MHz
LED_BUILTIN 13
Length 68.6 mm
Width 53.4 mm
Weight 25 g
Arduino IDE
• Based on wiring-based C/C++
Code Verify
Upload Save
• Digital I/O
• Time
• Port Registers
Digital I/O
• pinMode(pin, mode): Configures the specified pin to behave either as an input or
an output.
pin: the number of the pin whose mode you wish to set
mode: INPUT, OUTPUT, or INPUT_PULLUP. (see the digital pins page for a more complete description of the functionality.)
• digitalRead(pin): Reads the value from a specified digital pin, either HIGH or LOW.
pin: the number of the digital pin you want to read (int)
Example 1:
• Two push buttons (b1 and b2) are connected to the microcontroller through a pull-down resistances. When
the first button pressed the LED output turned on, and when the second button pressed the LED output
turned off. Draw the microcontroller circuit connection and write the code.
• Solution
Program I/os:
b1 input connected to pin 2
b2 input connected to pin 3
LED output connected to pin 7
Time
• delay(ms):Pauses the program for the amount of time (in miliseconds).
ms: the number of milliseconds to pause (unsigned long)
PORTB maps to Arduino digital pins 8 to 13 The two high bits (6 & 7) map to the crystal
pins and are not usable
DDRB - The Port B Data Direction Register - read/write
PORTB - The Port B Data Register - read/write
PINB - The Port B Input Pins Register - read only
PORTC maps to Arduino analog pins 0 to 5. Pins 6 & 7 are only accessible on the
Arduino Mini
DDRC - The Port C Data Direction Register - read/write
PORTC - The Port C Data Register - read/write
PINC - The Port C Input Pins Register - read only
Example 3
• Write a program that count from 0 to 7 with incremental step 1000ms
, and display the count in PORTB.
Part 2: Arduino Language Reference
• Data Types
• Math
• Comparison Operators
• Boolean Operators
• Bitwise Operators
• Control Structures
Data Types
• Char: A data type that takes up 1 byte of memory that stores a character value.
• Character literals are written in single quotes, like this: 'A' (for multiple characters - strings - use double
quotes: "ABC").
• Float : Datatype for floating-point numbers, a number that has a decimal point. Floating-point numbers
can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of
information.
See Also: void, Boolean, unsigned char, unsigned int, word, long, unsigned long, short, double, string, and array
https://www.arduino.cc/en/Reference/HomePage
Math
• min(x, y): Calculates the minimum of two numbers.
• map(value, fromLow, fromHigh, toLow, toHigh):Re-maps a number from one range to another.
x != y (x is not equal to y)
• if / else
allows greater control over the flow of code than the basic if statement, by allowing multiple tests to be grouped together.
• for statements
The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to
increment and terminate the loop.
• while loops
while loops will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false.
• do - while
The do loop works in the same manner as the while loop, with the exception that the condition is tested at the end of the
loop, so the do loop will always run at least once
• goto
Transfers program flow to a labelled point in the program
All the lamps are supplied from 220V ac source and the push button is
connected to the microcontroller through a pull down resistance and its supply
is 24V.
Draw the circuit schematic and write the micro controller code.
• Program KEY:
• Pin2 input passing_button
• Pin3 output Green_lamp
• Pin4 output Yellow_Lamp
• Pin5 output Red_lamp
• Pin6 output passing_lamp
• Pin7 ouput no_passing_lamp
Example 5
In a fire alarm system, there are three fire sensors for three different
zones provide inputs to a set-reset function block so that if one of the
sensors is activated the alarm is set and remain set until it is cleared by
using rest button. also, there are three indication Lamps used to
determine which zone has a fire and will turn off until the sensors
sense no fire.
The fire sensors, the alarm, Lamps, and set-reset button requires a 24v
supply.
Draw the microcontroller connection circuit ,and write the
microcontroller code
• Program KEY:
• Pin2 input reset_button
• Pin3 input zone1_fire_sensor
• Pin4 input zone2_fire_sensor
• Pin5 input zone3_fire_sensor
• Pin6 output Alarm
• Pin7 output zone1_ indication _lamp
• Pin8 output zone2_ indication _lamp
• Pin9 output zone3_ indication _lamp
Correction
Example 6
It’s required to keep the water level in the tank between
the maximum level and minimum level.
The program operates as following: Maximum level
• If the water level is above the minimum level the outlet proximity sensor
valve is open.
• If the water level in the take reaches the minimum level,
the outlet valve will turned off and the pump will operate Pump
Minimum level
to fill the tank. proximity sensor
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Liquid Crystal Display (LCD)
Arduino Liquid Crystal Library
This library allows an Arduino board to control LiquidCrystal displays (LCDs). The library works with in either 4-
or 8-bit.
• LiquidCrystal():Creates a variable of type LiquidCrystal. The display can be controlled using 4 or 8 data lines.
LiquidCrystal(rs, enable, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)
LiquidCrystal(rs, enable, d0, d1, d2, d3, d4, d5, d6, d7)
LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Analog to digital converter
analogRead(pin): Reads the value from the specified analog pin
using 10-bit analog to digital converter resolution. 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.
•
Example 8
• Write a programme to read the input voltage from a potentiometer and display the
corresponding ADC value, and the input voltage on the LCD.
• Program key:
Pin A0 analog input POT
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Example 9
It required to protect a semiconductor devices from overheat, using two fans attached in the heat sink and
temperature sensor.
The program operates as following :
• All the time the temperature displayed on the first line of the LCD.
• If the temperature is less than 50° , ‘ normal condition’ will be written on the second line of the LCD.
• If the temperature between 50° and 55° the first fan will turned on, and ‘ 1st fan is on’ will be written on the
second line.
• If the temperature between 55° and 60° the first and second fans will turned on, and ‘1st & 2nd fan are on’
will be written on the second line.
• If the temperature is more than 60° , and alarm will turned on and ‘Over heat’ will be written on the second
line.
temperature is monitored using a temperature sensor with sensitivity 3mV/C, and the sensor range is 0~150 C.
a)Design a signal conditioning circuit to adjust the temperature sensor output voltage to be in range from 0 to
5V.
b) write the microcontroller code and draw the circuit connection.
• Program key
Pin A0 analog input POT
Pin 8 digital output fan1
Pin 9 digital output fan2
Pin 10 digital output alarm
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Pulse Width Modulation (PWM)
• analogWrite(pin, value):
pin: the pin to write to.
value: the duty cycle: between 0 (always off) and 255 (always on).
The frequency of the PWM signal on most pins is approximately 490 Hz. On the
Uno and similar boards, pins 5 and 6 have a frequency of approximately 980
Hz.
Example 10
In a specific application it is required to control dc motor as following:
• Once the start signal received the microcontroller will perform a soft start-
up in 15sec.
• Then the motor will run at full speed for 10sec.
• Then the microcontroller will perform as soft shutdown in 15 sec, and wait
for the next start signal.
Write the microcontroller code and draw the circuit connection, note that
the motor supply is 200V dc and the input signal pushbutton need 5V to
operate.
Dc Motor control using H-bridge
• The H-Bridge is designed to drive a motor clockwise and
anticlockwise.
• To reverse a motor, the supply must be reversed and this is what the
H-Bridge does.
S1 S3 S1 S3
S2
S2 S4 S4
S1 S2 S3 S4 Result
1 0 0 1 Motor moves right
0 1 1 0 Motor moves left
0 0 0 0 Motor coasts
0 1 0 1 Motor brakes
1 0 1 0 Motor brakes
1 1 0 0 Short circuit
0 0 1 1 Short circuit
1 1 1 1 Short circuit
N and P channel semiconductors
• A soil state H bridge is typically constructed using opposite polarity devices, such
as PNP BJTs or P-channel MOSFETs connected to the high voltage bus and NPN
BJTs or N-channel MOSFETs connected to the low voltage bus
• Suitable for low voltage application .
Example 11
It required to drive a dc motor using n and p channel semiconductor H-
bridge draws the circuit connection and writes the microcontroller code that
performs the following sequence.
• Once the start signal received the microcontroller will perform a soft start-
up in 15sec and the motor will run in the clockwise direction.
• Then the motor will run at full speed for 10sec.
• Then the microcontroller will perform as soft shutdown in 15 sec. and
perform another soft start-up in 15 sec in a counter-clockwise direction.
• Then the motor will run at full speed for 10sec and then the motor will
shutdown in 15 sec and wait for the next start-up signal to repeat the same
sequence.
• note that the motor supply is 12V dc and the input signal pushbutton need
5V to operate.
N channel-only semiconductors
• The most efficient MOSFET designs use N-channel MOSFETs on both the high side and low side
because they typically have a third of the ON resistance of P-channel MOSFETs. This requires a
more complex design since the gates of the high side MOSFETs must be driven positive with
respect to the DC supply rail. Many integrated circuit MOSFET gate drivers include a charge pump
within the device to achieve this.
H Bridge Circuit Using Relay
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Servo library
This library allows an Arduino board to control servo motors.
Servos have integrated gears and a shaft that can be precisely
controlled.
Standard servos allow the shaft to be positioned at various angles,
usually between 0 and 180 degrees.
• attach():Attach the Servo variable to a pin.
servo.attach(pin)
Specifications
• Weight: 9 g
• Dimension: 22.2 x 11.8 x 31 mm approx.
• Stall torque: 1.8 kgf·cm
• Operating speed: 0.1 s/60 degree
• Operating voltage: 4.8 V (~5V)
• Dead band width: 10 μs
• Temperature range: 0 ºC – 55 ºC
Example 12
Use the potentiometer to control the angle of the servomotor, such as
potentiometer input voltage vary from 0 to 5V and the corresponding
servomotor angle vary from 0 to 180°, also display the servomotor
angle on the LCD.
• Write the microcontroller code and draws the circuit connection. The
servo is supplied from 5V supply.
Stepper Motor
• A stepper motor is a motor controlled by a series of electromagnetic coils. The center shaft has a
series of magnets mounted on it, and the coils surrounding the shaft are alternately given current
or not, creating magnetic fields which repulse or attract the magnets on the shaft, causing the
motor to rotate.
• This design allows for very precise control of the motor: by proper pulsing, it can be turned in very
accurate steps of set degree increments (for example, two-degree increments, half-degree
increments, etc.). They are used in printers, disk drives, and other devices where precise
positioning of the motor is necessary.
• There are two basic types of stepper motors, unipolar steppers and bipolar steppers.
unipolar stepper motor
• The unipolar stepper motor has five or six wires and four coils
(actually two coils divided by center connections on each coil). The
center connections of the coils are tied together and used as the
power connection. They are called unipolar steppers because power
always comes in on this one pole.
To control the stepper, apply voltage to each of the coils in a
specific sequence. The sequence would go like this:
• step(steps):Turns the motor a specific number of steps, at a speed determined by the most recent
call to setSpeed(). This function is blocking; that is, it will wait until the motor has finished moving to pass
control to the next line in your sketch. For example, if you set the speed to, say, 1 RPM and called step(100)
on a 100-step motor, this function would take a full minute to run. For better control, keep the speed high
and only go a few steps with each call to step().
• Phase : 4
• Current : 160 mA per winding (320 mA in 4-step mode) Measured: 250mA stopped,
200 mA running fast
• Resistance : 31 Ω per coil winding (from Red wire to any coil) (Some 24-28 ohms)
• Voltage : 5V DC
• Step Angle (8-Step sequence: Internal Motor alone): 5.625° (64 steps per revolution)
• Step Angle (4-Step sequence: Internal Motor alone): 11.25° (32 steps per revolution)
• Gear Reduction ratio: 1 / 64 (Not really exact: probably 63.68395.:1 )
• SO: it takes (64*64 = 4096 steps per output shaft revolution.. In 8-step sequence.
• SO: it takes (32*64 = 2048 steps per output shaft revolution.. In 4-step sequence.
• NOTE: Arduino "Stepper Library" runs in 4-step mode
Example 13
Use the microcontroller to drive the stepper motor in the following
sequence:
• Rotate half a cycle CW in low speed (50 rpm).
• Rotate half a cycle CCW in high speed(700 rpm).
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Serial communication (RS232)
Serial is used for communication between the
Arduino board and a computer or other
devices. 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.
• Serial.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,
600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.
• Serial.available(): Get the number of bytes (characters) available for reading from
the serial port. This is data that's already arrived and stored in the serial receive
buffer (which holds 64 bytes).
• Serial.read():Reads incoming serial data. read() inherits from the Stream utility
class.
• parseInt(): Looks for the next valid integer in the incoming serial stream.
• Serial.parseFloat():returns the first valid floating point number from the Serial
buffer.
• Serial.flush(): removed any buffered incoming serial data.
• Serial.setTimeout(): sets the maximum milliseconds to wait for serial data when
using Serial.readBytesUntil(), Serial.readBytes(), Serial.parseInt()
or Serial.parseFloat(). It defaults to 1000 milliseconds.
• Serial.print: Prints data to the serial port .
• Serial.println(val) :Prints data to the serial port and and a newline
character .
Serial.print(78, BIN) gives "1001110"
Serial.print(78, OCT) gives "116"
Serial.print(78, DEC) gives "78"
Serial.print(78, HEX) gives "4E"
Serial.println(1.23456, 0) gives "1"
Serial.println(1.23456, 2) gives "1.23"
Serial.println(1.23456, 4) gives "1.2346"
Max232 (RS232 Level to TTL Level)
Example 14
• Write a program that receive serial decimal number from the computer seral port
, and send it back to the computer.
Set the serial port data rate to 9600
Code correction
Example 15
• It is require to control the Servo motor through the computer serial
port. The user will send the require position in range from 000 to 180
degree. And the microcontroller will drive the servo motor to the
required position, if the required position is in the operating rang the
microcontroller will move the servo to the required position and
display the following message “servo position =“. If the requires
position is out of range the microcontroller will not move the servo
and will send the following message “invalid data!”.
Write the microcontroller code and draw the microcontroller
connection circuit.
Code correction 1
Code correction 2
Code correction 3
Code correction 4
Serial Plotter
• The Arduino Serial Plotter is a software utility
within the IDE that takes incoming serial
values over the USB connection. Instead of
just displaying the raw values to a TTY
monitor, it graphs them against an X/Y axis.
The vertical Y axis auto adjusts as the value
of your output increases or decreases, and
the X axis is a fixed 500 point axis with each
tick of the axis equal to an executed
Serial.println() command.
Example 16
• Plot a sawtooth wave using serial plotter, that change from zero to
255 with incremental step of 10ms?
Example 17
• Plot a sin and cose wave using serial plotter.
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Two Wire-communication (I2C)
• The I2C communication bus is very popular and broadly used
by many electronic devices because it can be easily
implemented in many electronic designs which require
communication between a master and multiple slave devices.
• Only two wires are required for communication between up
to almost 128 devices when using 7 bits addressing.
• Each device has a unique device address so the master can
choose with which devices will be communicating.
• The two wires are: Serial Clock (or SCL) and Serial Data (or
SDA)
I2C Protocol
• The first 8 bits sequence which indicates the address of the slave to which the
data is being sent, and R/W .
• After each 8 bits sequence follows a bit called Acknowledge.
• After the first Acknowledge bit in most cases comes another addressing sequence
but this time for the internal registers of the slave device.
• After the addressing sequences follows the data sequences as many until the
data is completely sent and it ends with a special stop condition.
I2C pins location on various Arduino boards.
Board I2C / TWI pins
• Uno, Ethernet A4 (SDA), A5 (SCL)
• Mega2560 20 (SDA), 21 (SCL)
• Leonardo 2 (SDA), 3 (SCL)
• Due 20 (SDA), 21 (SCL), SDA1, SCL1
Functions
• Wire.begin(address): Initiate the Wire library and join the I2C bus as a master or
slave.
address: the 7-bit slave address (optional); if not specified, join the bus as a master.
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
External interrupts
Most microprocessors have interrupts. Interrupts let microcontroller respond to external events
while doing something else.
Uno, Ethernet 2 3
Mega2560 2 3 21 20 19 18
32u4 based
(e.g Leonardo, 3 2 0 1 7
Micro)
Example 19: Write a programme that uses
interrupt to toggle the led coition
Example 20
In a specific application, the heat of the industrial oven is continuously
monitored using a digital programmable temperature sensor, that gives
high if the temperature is below 150c, and low if the temperature is
180c. unfourtuanly the microcontroller is busy on performance other
tasks, so its required to use an interrupt to turn on and turn off the
heater.
• write the microcontroller code and draw the circuit connection.
• the heater needs 220V to operate.
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Timer One
Timer1.initialize(period) You must call this method first to
use any of the other methods. You can optionally specify
the timer's period here (in microseconds). Note that this
breaks analogWrite() for digital pins 9 and 10 on Arduino.
Timer1.setPwmDuty(pin, duty)A fast shortcut for setting the pwm duty for a given pin if you have
already set it up by calling pwm() earlier.
Timer1.disablePwm(pin)Turns PWM off for the specified pin so you can use that pin for
something else.
Example 21
• Use timer1 interrupt to blink
led once per 100usec.
Example 22
• Generate 2kHz PWM signal that increment its duty cycle once every
interrupt.
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Microcontroller & Discrete control
What is a discrete-time system and why do
we care about it?
• Until now we have assumed that time is continuous. In other words,
time can take on any value, and this is generally true of linear physical
systems involving components as capacitors, masses, thermal
resistances.
• For the microcontrollers, time is not continuous, it passes in discrete
intervals. So whenever a microcontrollers is being used, it is
important to understand the ramifications of the inherently discrete
nature of time.
Where does discrete time data come from?
• the sampling process is usually carried out in practice through the use
of an analog-to-digital convertor.
The key insight of this whole process is that the sampled function, x*(t), is simply a train of impulses whose
magnitude is given by the height of the function x(t) (at the times x(kT)).We can rewrite the sampled signal as
where x[k] is the magnitude of the kth element in the sequence and x[k]=x(kT). Generally when we consider a
sequence we will implicitly assume a sampling interval, T, and simply use x[k].
Main : Graphs
<Untitled>
1.00
0.75
0.25
sine wave 50Hz 0.00
y
-0.25
-0.50
-0.75
...
1000 sample
0.2000 0.2050 0.2100 0.2150 0.2200 0.2250 0.2300 0.2350 0.2400
sec
...
... per sec
Main : Graphs Main : Graphs
<Untitled> <Untitled>
1.00 1.00
0.50 0.50
0.00 0.00
y
y
-0.50 -0.50
-1.00 -1.00
0.2000 0.2050 0.2100 0.2150 0.2200 0.2250 0.2300 0.2350 0.2400 ... 0.2000 0.2050 0.2100 0.2150 0.2200 0.2250 0.2300 0.2350 0.2400 ...
... ...
... ...
0.50
0.00
y
0.00
y
-0.50
-0.50
-1.00
-1.00 0.2000 0.2050 0.2100 0.2150 0.2200 0.2250 0.2300 0.2350 0.2400 ...
...
0.2000 0.2050 0.2100 0.2150 0.2200 0.2250 0.2300 0.2350 0.2400 ... ...
...
...
Z-transform
• As you recall, we talked first about differential equations.
• We then learned about the Laplace transform, which is a useful tool for
solving differential equations and for doing system analysis on
continuous-time systems.
• Our development now continues to the Z-transform. This is a transform
technique used for discrete time signals and systems.
• The Z-transform is simply a power series representation of a discrete-
time sequence.
Example 23
The microcontroller receives analog signal contain much noise, it is
required to develop a low pass filter program of 500Hz cut off
frequency .
Step 1 get the system transfer function
R
Vin C Vout
1
Vi
Vo CS
1
R
CS
Vi
Vo
RCS 1
1
TF
S 1
Step 2 Use matlab to convert the transfer
function from S_domain to Z_domain
clc
clear all
TC=1/500; Sampling time or
1/interrupt frequency
F_TF_s_domain=tf(1,[TC 1])
F_TF_Z_domin=c2d(F_TF_s_domain,1/2000 )
0.2212
F_TF_Z_domin = -------------
z - 0.7788
Step 3 Find the discrete equation
0.2212
F _ TF _ Z _ domin 𝑅(𝑧) 𝐹_𝑇𝐹_𝑍_𝑑𝑜𝑚𝑖𝑛 𝐶(𝑧)
z 0.7788
C ( z) 0.2212 Z 1
R( z ) 1 0.7788 Z 1
1 1
0.2212 Z R( z ) C ( z ) 0.7788 Z C ( z )
C ( K ) 0.2212 R( K 1) 0.7788 C ( K 1)
Example 24
In a repeated sequential application, it is required to run motor for 15sec in CW
direction and anther 15sec in CCW direction, the motor speed is 2000rpm. Due to
mechanical constrains the motor Reference speed must increase gradually by
passing the step speed to a low pass filter with 0.5Hz cut off frequency.
The motor deriver receives the reference speed through RS232, and its massage
must be in the following form
S=S4S3S2S0
Where:
S= is the message header
S4S3S2S0:are four decimal motor reference speed
Write the microcontroller code and use the serial plotter to confirm your code.
Basic Embedded System components
User interface
And Display
Battery
and
Power supply
Microcontroller
ALU ADC I/Os
Flash Memory Actuators and
Sensors Signal Process
condition EEPROM PWM gate driver
Timers Counters
Interrupt controller
Communication
signals
Ethernet library
• This library is designed to work with the
Arduino Ethernet Shield, Arduino
Ethernet Shield 2, Leonardo Ethernet,
and any other W5100/W5200/W5500-
based devices
• The Arduino board communicates with
the shield using the SPI bus. This is on
digital pins 11, 12, and 13 on the Uno
and pins 50, 51, and 52 on the Mega.
Classes
• Ethernet class: The Ethernet class initializes the ethernet library and
network settings.
• IP Address class: The IP Address class works with local and remote IP
addressing.
• Server class: The Server class creates servers which can send data to
and receive data from connected clients (programs running on other
computers or devices).
• Ethernet UDP class: The Ethernet UDP class enables UDP message to
be sent and received.
Ethernet class
Ethernet class
begin() setGatewayIP()
dnsServerIP()
setLocalIP()
gatewayIP()
hardwareStatus() setMACAddress()
init() setRetransmissionCount()
linkStatus() setRetransmissionTimeout()
localIP()
setSubnetMask()
MACAddress()
maintain() subnetMask()
setDnsServerIP()
• Ethernet.begin():Initializes the Ethernet library and network settings.
Ethernet.begin(mac);
Ethernet.begin(mac, ip);
Ethernet.begin(mac, ip, dns);
Ethernet.begin(mac, ip, dns, gateway);
Ethernet.begin(mac, ip, dns, gateway, subnet);
• mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware
address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For
older shields, choose your own.
• ip: the IP address of the device (array of 4 bytes)
• dns: the IP address of the DNS server (array of 4 bytes). optional: defaults to the device IP address with the
last octet set to 1
• gateway: the IP address of the network gateway (array of 4 bytes). optional: defaults to the device IP address
with the last octet set to 1
• subnet: the subnet mask of the network (array of 4 bytes). optional: defaults to 255.255.255.0
• Upgrade the programme such as the server and cliet can detect a
failure in the connection