0% found this document useful (0 votes)
23 views212 pages

Lec 1

Uploaded by

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

Lec 1

Uploaded by

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

Microprocessor Based process control

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.

• Examples of microcontroller protection:


1. Fuses can be used to keep the current at a safe level
2. Zener diode
3. Galvanic Isolation
Zener diode protection
• Zener diode can be used to protect against high
voltage and wrong polarity (clipping and clamping)
Operation
• High voltage :The Zener diode will conduct once the
voltage exceeds the Zener voltage, VZ ,.
Vi
• Wrong polarity: The output voltage will follow the input
until the input goes below about −0.7V. then Zener will
conduct and the output will not decrease (This slight
negative voltage will not be a problem for most Vo
microcontrollers.)
• The resistor should be chosen so that the maximum current
through the diode is within the specified limits.
Single and Double Zener Clipping.
Galvanic Isolation
In low-power electronics systems, it is possible to use measurement
systems electrically coupled with the control system. However, usually
in high-power systems galvanic isolation in measurements is required.

Reasons for the use of galvanic isolation include:


• Break ground loop.
• High common voltage.
• Safety reasons.
• Increased noise immunity.
1-Opto-isolator
• Operation similar to relays
• Excellent noise isolation because switching circuits are
electrically isolated, since the photons eliminates the need for a
common ground.
• It is ideal for applications requiring High isolation surge voltage,
Noise isolation, and Small size.
• Signal cannot travel in opposite direction.
• The resistors are used because effectively the LED and the
phototransistor are current devices, and usually signals are
processed as voltages, the values chosen for the resistors should
be consistent with the current specifications for the device.
• Used to control motors, solenoids, etc.
• 4N25, 4N35 & 4N137
Isolation using voltage transformer
• The different numbers of windings in the
two coils allow the input signal to be
increased or decreased while any DC offset
is removed.

• cannot transmit DC (ie. steady-state) values


• 2 way power flow
• can transmit power
• Care must be taken as voltage spikes can be
transmitted to the controller.
Isolation using current transformer
• Current transformers are relatively simple and
passive devices. The primary current (AC) will
generate a magnetic field. The field is
concentrated by magnetic core. The secondary
coil is coupled with the primary coil by magnetic
field.
• Current transformers are designed to measure
AC current and typically operate between 20 and
100 Hz.
• The secondary current magnitude is proportional
to ratio of the primary number of turns zp
(typically from one to several) to secondary
number of turns zs (typically thousands); thus,
the secondary current is for an ideal transformer
can be calculated by the equation
Hall effect insolation
• The sensor measures DC, AC, and complex
current waveforms while providing
galvanic isolation. The Hall effect current
sensor consists of three basic components:
the magnetic core, the Hall effect sensor,
and signal conditioning circuitry. The Hall
sensor is located in the magnetic core gap.
ACS752SCA-100
Features and Benefits
▪ Monolithic Hall IC for high reliability
▪ Single +5 V supply
▪ 3 kVRMS isolation voltage between terminals 4/5 and
pins 1/2/3 for up to 1 minute
▪ 50 kHz bandwidth
▪ Automotive temperature range
▪ End-of-line factory-trimmed for gain and offset
▪ Ultra-low power loss: 130 μΩ internal conductor
resistance
▪ Ratiometric output from supply voltage
▪ Extremely stable output offset voltage
▪ Small package size, with easy mounting capability
▪ Output proportional to AC and DC currents
Hall Effect current sensor
Hall Effect Voltage sensor
Signal condition using passive elements

Passive
elements

Voltage Level Weston


shifting
Filter
divider bridge
Voltage divider
Level shifting

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

Band Pass filter Band stop filter (Twin-T Notch Filter


Design)
Fr  FL * FH 2R 2R
1
FN 
4 RC
C C
Vin Vout
R 2C
A band pass filter is to be constructed using RC components that will only allow a
range of frequencies to pass above 1kHz and below 30kHz. Assuming that both the
resistors have values of 10kΩ´s, calculate the values of the two capacitors required,
and the central frequency.
Solution:

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.

• Design a signal conditioning circuit to adjust the sensor output voltage to be


connected to the A/D converter. With full range voltage.
• The total analog to digital conversion time
• The digital number range, The resolution
• If the analog input from sensor was 0.36V, calculate the corresponding digital
number.
• A current Transducer (CT) is used to measure a current from 0 to 25 A
the transfer function of the sensor is 0.1 V/A. Design a single supply
signal conditioning circuit to make the output range from 0 to 5v
Active Low Pass filter
+Vs
1
- Fc 
2 RC
Vi R Vo

+
-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

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 on 90° to 135°

4 off on off 135° to 180°

5 on on off 180° to 225°

6 on on on 225° to 270°

7 on off on 270° to 315°

8 on off off 315° to 360°


Microcontroller Digital Outputs
5V supply

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

New Program Open


Arduino IDE ( Integrated Development Environment)

• The basic function has two required subroutines


Void setup():Is called when a sketch starts. Use it to initialize variables, pin
modes, start using libraries, etc. The setup function will only run once, after each
powerup or reset of the Arduino board.
Void loop(): Use it to actively control the Arduino board.
Part 1: Arduino Language Reference

• 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.)

• digitalWrite(pin, value): Write a HIGH or a LOW value to a digital pin.


pin: the pin number
value: HIGH or LOW

• 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)

• delayMicroseconds(us):Pauses the program for the amount of time (in


microseconds)
us: the number of microseconds to pause (unsigned int)

• millis():Returns the number of milliseconds since the Arduino board began


running the current program. This number will overflow (go back to zero), after
approximately 50 days.

• micros():Returns the number of microseconds since the Arduino board began


running the current program. This number will overflow (go back to zero), after
approximately 70 minutes.
Example 2:
• write an led blinking program, where the LED turned on for 1sec and
turned off for 0.5sec
• Solution
Program I/os:
LED output connected to pin 7.
Port Registers
• Port registers allow for lower-level and faster manipulation of the i/o
pins of the microcontroller on an Arduino board.

B (digital pin 8 to 13)


C (analog input pins)
D (digital pins 0 to 7)
PORTD maps to Arduino digital pins 0 to 7
DDRD - The Port D Data Direction Register - read/write
DDRD = B11111110; // sets Arduino pins 1 to 7 as outputs, pin 0 as input
PORTD - The Port D Data Register - read/write PORTD = B10101000; // sets digital pins 7,5,3 HIGH
PIND - The Port D Input Pins Register - read only

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").

• Byte: A byte stores an 8-bit unsigned number, from 0 to 255.

• Int: Data-type for number storage.


On the Arduino Uno (and other ATMega based boards) an int stores a 16-bit (2-byte) value. This yields a
range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).

• 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.

• max(x, y):Calculates the maximum of two numbers.

• abs(x): Computes the absolute value of a number.

• constrain(x, a, b):Constrains a number to be within a range.

• map(value, fromLow, fromHigh, toLow, toHigh):Re-maps a number from one range to another.

• pow(base, exponent): Calculates the value of a number raised to a power.

• sq(x):Calculates the square of a number: the number multiplied by itself.

• sqrt(x):Calculates the square root of a number.


Comparison Operators:
x == y (x is equal to y)

x != y (x is not equal to y)

x < y (x is less than y)

x > y (x is greater than y)

x <= y (x is less than or equal to y)

x >= y (x is greater than or equal to y)


Boolean Operators
&& (and)
|| (or)
! (not)
Bitwise Operators
& (bitwise and)
| (bitwise or)
^ (bitwise xor)
~ (bitwise not)
<< (bitshift left)
>> (bitshift right)
Control Structures
• if (conditional)
Used in conjunction with a comparison operator, tests whether a certain condition has been reached, such as an input being
above a certain number.

• 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

See also: switch case, break, continue and return


Example 4
• A zebra crossing operate according to the following sequence.
1-At the normal condition the green lamp and no-passing lamp are on.
2-When the passing-button is pressed, after a delay of 3sec the green lamp
turned off and the yellow lamp turned on for 3sec. then the yellow lamp turned
off and the red lamp turned on.
3-After 5sec delay the passing lamp is on and no-passing lamp is off for 20 sec.
Then the passing lamp turned off and no-passing lamp will turned on.
4- After 5 sec the system will returns back to its normal condition.
5-the process will not repeated before 100 sec pass

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

• Once the water level reaches the maximum level the


pump will turned off and the outlet value will turned on Outlet valve
again.
Mention which type of proximity sensor is suitable for this
application, write the microcontroller code and draw the
circuit connection.
Note: the approximately sensors supplied from 24V dc
supply, and the pump requires 220V ac to operate, and the
realyes coils requires 24V dc.
• Program key:
• Pin 2 output Water_pump
• Pin 3 output outlet_valve
• Pin 4 input max_level_sensor
• Pin 5 input min_level_sensor

Capacitive proximity is suitable for this application


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

• lcd.begin(cols, rows):Initializes the interface to the LCD screen.


• lcd.clear():Clears the LCD screen and positions the cursor in the upper-left corner.
• lcd.home(): Positions the cursor in the upper-left of the LCD.
• lcd.setCursor(col, row): Position the LCD cursor.
• lcd.write(data): Write a character to the LCD.
• print(): Prints text to the LCD.
lcd.print(data)
lcd.print(data, BASE),
BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for
hexadecimal (base 16).

• lcd.cursor(): Display the LCD cursor.


• lcd.noCursor(): Hides the LCD cursor.
• lcd.blink(): Turns on the blinking LCD cursor.
• lcd.noBlink(): Turns off the blinking LCD cursor.
• lcd.scrollDisplayLeft():Scrolls the contents of the display (text and cursor) one space to the left.
• lcd.scrollDisplayRight():Scrolls the contents of the display (text and cursor) one space to the right.
Example 7
• Write a programme to prints "Hello World!" to the LCD and shows the
time in seconds since the Arduino was reset.
• Program key:
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
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.

It takes about 100 microseconds (0.0001 s) to read an analog input, so


the maximum reading rate is about 10,000 times a second.
analogReference(type): Configures the reference voltage used for
analog input, to changed the input range and resolution.The options
are:
• DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V
Arduino boards)
• INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56
volts on the ATmega8(not available on the Arduino Mega)
• INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)
• INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only)
• EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.


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)

• write():controlling the shaft accordingly. On a standard servo, this will set


the angle of the shaft (in degrees 0 to 180°),
servo.write(angle)

• read():Read the current angle of the servo


servo.read()

• writeMicroseconds():Writes a value in microseconds (uS) to the servo,


controlling the shaft accordingly, On standard servos a parameter value of
1000 is fully counter-clockwise, 2000 is fully clockwise, and 1500 is in the
middle.
servo.writeMicroseconds(uS)
SG90 9g Micro Servo

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 wire 1 wire 2 wire 3 wire 4


1 High low high low
2 low high high low
3 low high low high
4 high low low high
bipolar stepper motor
• The bipolar stepper motor usually has four wires coming out of it. Unlike unipolar steppers,
bipolar steppers have no common center connection. They have two independent sets of coils
instead. You can distinguish them from unipolar steppers by measuring the resistance between
the wires. You should find two pairs of wires with equal resistance. If you’ve got the leads of your
meter connected to two wires that are not connected (i.e. not attached to the same coil), you
should see infinite resistance (or no continuity).
Stepper motor library
• This library allows you to control unipolar or bipolar stepper motors.
To use it you will need a stepper motor, and the appropriate hardware
to control it
• Stepper(steps, pin1, pin2)
Stepper(steps, pin1, pin2, pin3, pin4)
This function creates a new instance of the Stepper class that represents a particular stepper motor attached
to your Arduino board. Use it at the top of your sketch, above setup() and loop(). The number of parameters
depends on how you've wired your motor - either using two or four pins of the Arduino board.
steps: the number of steps in one revolution of your motor. If your motor gives the number of degrees per
step, divide that number into 360 to get the number of steps (e.g. 360 / 3.6 gives 100 steps). (int)
pin1, pin2: two pins that are attached to the motor (int)
pin3, pin4: optional the last two pins attached to the motor, if it's connected to four pins (int)
• setSpeed(rpms):Sets the motor speed in rotations per minute (RPMs). This function doesn't make
the motor turn, just sets the speed at which it will when you call step().

• 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.

• Wire.beginTransmission(address): Begin a transmission to the I2C slave device


with the given address.
• Wire.send(string):Sends data from a slave device in response to a request from a
master, or queues bytes for transmission from a master to slave device.
• Wire.requestFrom(address, quantity): Used by the master to request bytes from a
slave device.
• Wire.available():The number of bytes available for reading.
• Wire.receive() Retrieve a byte: that was transmitted from a slave device to a
master after a call to request From or was transmitted from a master to a slave.
• Wire.endTransmission(): Ends a transmission to a slave device. (return
0:success,
1:data too long to fit in transmit buffer,
2:received NACK on transmit of address,
3:received NACK on transmit of data,
4:other error)
Different voltage level
Example 18
• Two digital temperature sensor are used in a specific application, the
Communication with the sensors is accomplished via a 2-wire I2C
compatible serial port sensors, 1st and 2nd sensor address are 0x72, 0x52
respectively, and the temperature are stored in one bye the register
address 0x11 and 0x00 respectively. Its required to read the temperature
from each sensor and send it through the serial bus (RS232), in the
following form, ‘TTt1t2XY’.
• Where :
TT is the message header
T1 is The 8bit data from the 1st sensor
T2 is the 8bit data from the 2nd sensor
XY is the message trailer
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
External interrupts
Most microprocessors have interrupts. Interrupts let microcontroller respond to external events
while doing something else.

BOARD DIGITAL PINS USABLE FOR INTERRUPTS


Uno, Nano, Mini, other 328-based 2, 3
Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21
Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7
Zero all digital pins, except 4
MKR1000 Rev.1 0, 1, 4, 5, 6, 7, 8, 9, A1, A2
Due all digital pins
all digital pins (Only pins 2, 5, 7, 8, 10, 11, 12,
101
13 work with CHANGE)
Interrupt Service Routines (ISR)
• Short function
• If your sketch uses multiple ISRs, only one can run at a time, other
interrupts will be executed after the current one finishes in an order
that depends on the priority they have
• Don’t used delay( except delayMicroseconds() does not use any
counter, so it will work as normal)
• Don’t do serial prints
• Make variables shared with the main code volatile
• attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); (recommended)
• attachInterrupt(interrupt, ISR, mode); (not recommended)
• attachInterrupt(pin, ISR, mode); (Due, Zero, MKR1000, 101 only)

interrupt: the number of the interrupt (int)


pin: the pin number (Arduino Due, Zero, MKR1000 only)
ISR: the ISR to call when the interrupt occurs.
mode: defines when the interrupt should be triggered. Four constants are
predefined as valid values:
LOW to trigger the interrupt whenever the pin is low,
CHANGE to trigger the interrupt whenever the pin changes value
RISING to trigger when the pin goes from low to high,
FALLING for when the pin goes from high to low.
HIGH to trigger the interrupt whenever the pin is high
Interrupt Numbers
• Normally you should use digitalPinToInterrupt(pin), rather than place
an interrupt.

BOARD INT.0 INT.1 INT.2 INT.3 INT.4 INT.5

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.setPeriod(period):Sets the period in microseconds.


The minimum is 1 microsecond , and The maximum
period is 8388480 microseconds. Note that setting the
period will change the attached interrupt and both pwm
outputs' frequencies and duty cycles simultaneously.
Timer1.pwm(pin, duty, period) Output pins for Timer1 are
digital pins 9 and 10. so those aliases also work. Output pins
for Timer3 are from PORTE and correspond to 2,3 & 5 on the
Arduino Mega.
The duty cycle is specified as a 10 bit value, so anything
between 0 and 1023.
Timer1.attachInterrupt(function, period) Calls a function at the specified interval in microseconds.

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.detachInterrupt() Disables the attached interrupt.

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.

• In this diagram x(t) represents a continuous-time signal that is


sampled every T seconds, the resulting signal is called x*(t). This
represents a continuous-time signal that is measured by a
microcontroller every T seconds that results in a sampled signal.
This sampling process can be clarified with an
image. The graph below shows x(t),

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

analog signal 0.50

0.25
sine wave 50Hz 0.00

y
-0.25

-0.50
-0.75

500 sample per


-1.00

...
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 ...
... ...
... ...

2000 sample 5000 sample


per sec Main : Graphs
per sec
<Untitled>
Main : Graphs
1.00
<Untitled>
1.00
0.50

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 )

Now we can get the discrete equation

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

• Returns: Ethernet.begin(mac), returns an int: 1 on a successful DHCP


connection, 0 on failure. The other versions don't return anything.
Server class:
Server class:
• server.begin():Tells the server to begin listening for incoming connections.
• server.available(): Gets a client that is connected to the server and has data
available for reading. The connection persists when the returned client object
goes out of scope; you can close it by calling client.stop().
• write():Write data to all the clients connected to a server. This data is sent as
a byte or series of bytes.
• print():Print data to all the clients connected to a server. Prints numbers as a
sequence of digits, each an ASCII character (e.g. the number 123 is sent as
the three characters '1', '2', '3').
• println():Print data, followed by a newline, to all the clients connected to a
server. Prints numbers as a sequence of digits.
Client class
• Client • setConnectionTimeout()
• EthernetClient() • write()
• if (EthernetClient) • print()
• connected() • println()
• connect() • available()
• localPort() • read()
• remoteIP() • flush()
• remotePort() • stop()
• client.EthernetClient(): Creates a client which can connect to a
specified internet IP address and port.
• client.connected() :Whether or not the client is connected.
• client.connect(): Connects to a specified IP address and port.
client.connect(ip, port)
client.connect(URL, port)
• ip: the IP address that the client will connect to (array of 4 bytes)
• URL: the domain name the client will connect to (string, ex.:"arduino.cc")
• port: the port that the client will connect to (int)

• client.write(val) :Write data to the server the client is connected to.


• client.print(data):Print data to the server that a client is connected
to. Prints numbers as a sequence of digits,
• client.println(data): Print data, followed by a carriage return and
newline,
• client.available():Returns the number of bytes available for reading
(that is, the amount of data that has been written to the client by the
server it is connected to).
• client.read():Read the next byte received from the server the client is
connected to (after the last call to read()).
• flush():Waits until all outgoing characters in buffer have been sent.
• stop():Disconnect from the server.
Example 25
• Write a programme that establish and Ethernet between a server and
client. Such as the client sending a number vary from 0 to 1000;
Example 25
• Write a programme that establish and Ethernet between a server and
client. Such as the client sending a number vary from 0 to 1000;

• Upgrade the programme such as the server and cliet can detect a
failure in the connection

You might also like