Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

UNIT – VI: Case Studies with Cortex M

Based Microcontroller
STM32F4xx Interfacing with accelerometer MPU 6050, Ultrasonic Sensor HC-SR04, PWM: Controlling
speed and direction of DC Motor CAN Bus: Features, CAN Frame, sequence of transmitting and
receiving data on CAN Bus.

Unit Objectives
1.To Interface sensor using Bus protocol
2.To Understand Industrial Control application like motor control
3.To Understand the different buses and Protocol
4.To Interface of real time devices using Bus protocol
5.To Design case study for real life application using Input/ Output devices.
6.To write the C Programs for the case study.
Unit Outcomes
1. Interface Sensor using buses Mapping With COs :
2. Select the Bus Protocol for interfacing devices. CO6: Recognize the interfacing of real world
3. Interface DC motors using buses. sensors and standard buses. Will also able
4. Design case study for real life application. to design different case studies.
Mapping With POs : 1, 3
Books :
T3: Shujen Chen, Muhammad Ali Mazidi, Eshragh Ghaemi, STM32 Arm Programming for Embedded
Systems: Using C Language with STM32 Nucleo, MicroDigitalEd., 2018
R3: Joseph Yiu, The Definitive Guide to ARM® Cortex®-M3 and Cortex®-M4 Processors, Newnes;
3rd edition
Accelerometer
• There are small devices indicating
changing orientation in smart
phones, video game remotes,
quad-copters, etc.
• These devices contains gyroscopes
combined with accelerometers and
are referred to as IMU, or Inertial
Measurement Unit
• The number of sensor inputs in an
IMU are referred to as “ DOF” (
Degree of Freedom), so a chip with
a 3-axis gyroscope and a 3-axis
accelerometer would be a 6-DOF
IMU.
Gyroscope
• Many different sensory devices are used to
determine the position and orientation of an
object. The most common of these sensors
are the gyroscope and the accelerometer.
• An accelerometer is a compact device
designed to measure non-gravitational
acceleration.
• Though similar in purpose, they measure
different things. When combined into a single
device, they can create a very powerful array
of information
Accelerometers
• When the object it's integrated
into goes from a standstill to any
velocity, the accelerometer is
designed to respond to the
vibrations associated with such
movement.
• Gyroscopes can produce a better
estimate of orientation than
obtained using accelerometer
data alone.
• Digital accelerometers give
information using a serial
protocol like I2C , SPI or USART.
MPU-6050
• The MPU 6050 is the world’s first integrated 6-
axis Motion Tracking device
• It combines a 3-axis gyroscope, 3-axis
accelerometer, and a Digital Motion Processor™
(DMP) all in a small 4x4x0.9mm package.
• It uses a standard I2C bus for data transmission.
– With it’s I2C bus, it can accepts inputs from an external 3-
axis compass to provide a complete 9-axis Motion Fusion
output.
MPU 6050
• The objective is to measure Tilt Angle using MPU6050 &
STM32F4XX Microcontroller by simply interfacing
MPU6050 6 axis Gyro/Accelerometer Sensor with
STM32.
• The Accelerometer sends X, Y, and Z acceleration forces.
We need to convert the forces into X, Y, Z 3D angle to
determine the 3D Orientation of the sensor.

• The gyroscope measures rotational velocity or rate of


change of the angular position over time, along the X, Y
and Z-axis. The sensor uses the I2C-bus to interface with
the STM32F4XX Microcontroller.
6
MPU 6050

• The MPU 6050 Module is Micro


Electro Mechanical System (MEMS)
which consists of a 3 axis accelerometer
and a 3 axis Gyroscope inside it.
•This helps to measure acceleration,
Velocity , orientation, displacement and
many other motion related parameters
of a system or object.

7
The Pinout of MPU 6050

 INT: Interrupt digital output pin.


 AD0: I2C Slave Address LSB pin. This is 0th bit in 7-bit slave
address of device.
 XCL: Auxiliary Serial Clock pin. used to connect other I2C
interface

 XDA: Auxiliary Serial Data pin.


 SCL: Serial Clock pin. Connect this pin to controllers SCL pin.
SDA: Serial Data pin. Connect this pin to controllers SDA pin.
GND: Ground pin. Connect this pin t9o ground connection.
Algorithm for interfacing MPU 6050

 1. Include Header files.

 2. Configure System Clock

 3. Initialize SPI Bus SFR Registers.

 4. Initialize/ Configure GPIO Pins.

 5. Read the X, Y and Z parameters from MPU 6050.

 6. Display it in variable or Serial Terminal.


9
Code for interfacing MPU 6050

 Explain the code of Interfacing

10
 Recording of Accelerometer interfacing

 Recording of Accelerometer interfacing

11
Ultrasonic Sensor HCSR 04

This sensor can be used to measure distance between object and


sensor itself..
It transmits ultrasonic waves and receives it back after reflecting
it from surface of object.
It measures the time during entire process, which is proportional
to distance between object and the sensor itself.

Ultrasonic sensor HCSR04 has 4 pins and very easy to use.

12
PINOUT OF ULTRSONIC SENSOR

13
WORKING PRINCIPLE

14
SPECIFICATION

 Operating Voltage: 5V DC
 Operating Current: 15mA
 Trigger Input Signal: 10uS TTL Pulse
 Measure Angle: 15°
 Ranging Distance: 2cm - 4m
 Working Frequency: 40Hz
 Ranging Accuracy upto 3mm
15
TIMING DIAGRAM

16
Configuration of pins
As shown in the timing diagram, , we will need to send
a 10-microsecond pulse to the Trig pin of the sensor and
detect the pulse width of the pulse sent from the Echo pin
of the module.
Firstly to generate a pulse we will set PA5 low for
some time and then set it to high for the desired duration
of pulse which happens to be 10 microseconds in this
case and then set to PA5 low again.
Next, to detect the pulse coming in from the Echo pin,
we will configure PA6 as an input pin and continuously
monitor it for the duration of time it remains high.
17
Interfacing of HCSR 04 with STM
To interface an ultrasonic sensor, the HC-SR04 with the Cortex-
M4 based micro-controller, we are reading and writing individual
bits of some registers present on the micro-controller known as
Special Function Registers (SFRs).
Now, these acoustic bursts sent out by the transmitter of the
sensor module travel at the rate of 340m/s in air.

To calculate the distance we will be using simple,


Distance = Speed x Time formula

18
Interfacing of HCSR 04 with STM
 In this formula, the time taken by the receiver to receive the
signal back is divided by 2, since the total time includes the time
required by the signal to travel both to and back from the object.

 Clock on the STM32F407 runs on a frequency of 16MHz by


default. So, time is given as 0.0625 micro-seconds which is
1/16MHz.
 Finally, the distance in cm can be calculated by,
 Time = ((Clock Cycles x 0.0625 x 0.000001)/2)
 Distance = (340*100)xTime 20
Algorithm for interfacing HCSR 04

 1. Include Header files.


 2. Configure System Clock
 3. Initialize Timers through SFR Registers.
 4. Initialize/ Configure GPIO Pins.
 5. Send the trigger pulse.
 6. Wait for echo pulse.
 7. Calculate from time and formula.
 8. Display it in variable or Serial Terminal.

21
Ultrasonic Proximity Sensor

ADVANTAGES
Ultrasonic proximity sensors are not affected by
atmospheric dust, snow, rain..etc
Can work in adverse conditions
Sensing distance is more compared to inductive or
capacitive proximity sensors
DISADVANTAGES
Ultrasonic sensors Has More Difficulties Reading
Reflections From Soft, Curved, Thin Or Small Objects.
Code for interfacing HCSR 04

 Explain the code of Interfacing

23
DC Motor Control using PWM
 PWM signal is a modulated digital logic (0 and 1). PWM
signal have a duty cycle. Duty cycle is measured in
percentage.
 PWM signal that has 100% duty cycle would be the same as
setting to fully on. 0% duty cycle would be the same as
ground. Duty cycle in between 0% and 100% are illustrated
on these graphics:
DC Motor Control using PWM
 PWM (Pulse Width Modulation) is a technique for generating analog
voltage (average value) by using microcontroller's digital outputs. PWM is
used in DC motor speed control, servo motor control, dimming LED,
audio generation and many more.
Design of DC Motor control using PWM

Why Motor Drivers ?


• DC Motors requires high H - Bridge
current and high voltage than
a µC can handle.
• We can’t drive a DC Motor
directly with a Microcontroller,
• Moreover interfacing DC
Motors directly with µC may
affect the working of µC due
to the Back EMF of the DC
Motor.

Prof. M. N. Kakatkar,SCOE 25
Design of DC Motor control using PWM

L293D / L298

Prof. M. N. Kakatkar,SCOE 26
Selected DC Motor Characteristics
(http://www.Jameco.com)
28

Part No. Nominal Volts Volt Range Current RPM Torque

154915CP 3V 1.5–3 V 0.070 A 5,200 4.0 g-cm

154923CP 3V 1.5–3 V 0.240 A 16,000 8.3 g-cm

177498CP 4.5 V 3–14 V 0.150 A 10,300 33.3 g-cm

181411CP 5V 3–14 V 0.470 A 10,000 18.8 g-cm


H-Bridge Motor Configuration- Clockwise and Anticlockwise
29
DC Motor Rotation (Permanent Magnet Field)
30
Some H-Bridge Logic Configurations
31

Motor Operation SW1 SW2 SW3 SW4

Off Open Open Open Open

Clockwise Closed Open Open Closed

Counterclockwise Open Closed Closed Open

Invalid Closed Closed Closed Closed


Bidirectional Motor Control Using an L298 Chip
32
DC Motor Connection Using Darlington Transistor
33
DC Motor Connection Using MOSFET Transistor
34
DC Motor Control using PWM
 To generate PWM with STM32F4, we can use timer.
 Timer can count from 0 to a given value and triggering some
events.
 When the timer counter reach 0, max, or compared value, the
output channel value can be changed to create a PWM signal.
 First, we have to setting the timer on STM32F4. We will use
TIM4 because the output channel (TIM4_CH1) is connected
to PD12 (green LED) that we want to control the brightness.
 So, we can initialize TIM4 with these code:
PWM Mode
36
Design of DC Motor control using PWM

Prof. M. N. Kakatkar,SCOE 37
DC Motor Control using PWM
 The PWM option is selected by OCxM bits of the
Imx_CCMR register.
 The OCxM bit can be set in mode 1 or Mode 2.

 Either we can use 32 bit timer or 16 bit timer.


 The channel 1 is configured as PWM mode.

 The output of ch. 1 starts on when counter starts running.

When the counter contents are matching with CCR1, ch1


output contents are turned off.
 When the counter matches ARR register, the counter is cleared

to 0. The output is turned on and counter starts counting again.


TIM8_CCER
39
TIM8_BDTR
40

Bit 15 MOE: Main output enable


This bit is cleared asynchronously by hardware as soon as the break input
is active. It is set by software or automatically depending on the AOE
bit. It is acting only on the channels which are configured in output.
0: OC and OCN outputs are disabled or forced to idle state.
1: OC and OCN outputs are enabled if their respective enable bits are set
(CCxE, CCxNE in TIMx_CCER register).
Code for DC Motor Control using PWM

Explain the code of DC Motor Control using


PWM

41
Serial Bus Overview of STM 32F
 Up to 15 communication interfaces
🞑 Up to 3 × I2C interfaces
🞑 Up to 4 USARTs/2 UARTs (10.5 Mbit/s, ISO 7816
interface, LIN, IrDA, modem control)
🞑 Up to 3 SPIs (42 Mbits/s), 2 with full-duplex I2S to
achieve audio class accuracy via internal audio PLL
or external clock
🞑 2 × CAN interfaces (2.0B Active)
CAN Bus Overview
 CAN (Controller Area Network) is a serial bus
system used to communicate between several
embedded 8-bit and 16-bit microcontrollers.
 It was originally designed for use in the automotive
industry but is used today in many other systems
(e.g. home appliances and industrial machines).
 With the use of CAN, point-to-point wiring is
replaced by a serial bus connecting all control
systems.
CAN Bus Overview
 CAN is a communication protocol that connects all
devices can communicate with each other. CAN
stands for Controller Area Network.
 This technology developed by Bosch Automotive
company to reduce cabling loads and make systems
separates from each other. Because if there is a
problem in any sensor, this problem will harm all
system.
BEFORE CAN

45 2/5/2022
With CAN
The solution to this problem was the connection of the control systems via
serial bus system in a vehicle. Point- to-point wiring is replaced by a serial bus
connecting all control systems. This is done by adding some CAN-specific
hardware to each control unit that provides the "rules" or the protocol for
transmitting and receiving information via the bus.

46
The Development of CAN
The development of CAN began when more and more
electronic devices were implemented into modern motor
vehicles.
Examples include engine management systems, ABS, gear
control, lighting control, air conditioning, and airbags. All this
means more safety and more comfort.
This was usually done by point to point wiring. The
requirement is that a cable network with a length of up to
several miles.
High speed, real-time communication, Error detecting
mechanism and retransmission of faulty massages.
47
The CAN bus
48

 CAN is a broadcast type of bus.


🞑 This means that all nodes can "hear" all transmissions.
There is no way to send a message to just a specific node; all
nodes will invariably pick up all traffic. The CAN
hardware, however, provides local filtering so that each
node may react only on the “interesting” messages.
Message Oriented Transmission Protocol
 Each node – receiver & transmitter
 A sender of information transmits to all devices on the bus
 All nodes read message, then decide if it is relevant to them
 All nodes verify reception was error-free
 All nodes acknowledge reception

CAN bus

49 2/5/2022
Basic Configuration

49
CAN Bus Overview
 The physical layer uses differential transmission on a
twisted pair wire.
 The nodes are connected to the bus in a wired-and
fashion: if just one node is driving the bus to a logical
0, then the whole bus is in that state regardless of the
number.
 Max. transfer rate of 1000 kilobits per second at a
maximum bus length of 40 meters or 130 feet when
using a twisted wire pair.
 Message length is short with a maximum of 8 data
bytes per message. The messages are protected by a
CRC type checksum
50
Network Topology of CAN
 CAN is a broadcast system. Any node can “broadcast” a
message using a CAN frame on a bus. Multiple controllers
tend to start their messages at the same time.
 Every node will see this message. A “message” can be
considered the same as a CAN frame until you need to use
more than one frame to send a long message
CAN Bus Overview
 The bus access is handled via the serial
communications protocol Carrier Sense Multiple
Access/Collision Detection with Non-Destructive
Arbitration. This means that collision of messages is
avoided by bitwise arbitration.
 There is no explicit address in the messages, instead,
each message carries a numeric value which controls
its priority , and may also serve as an identification of
the contents.
 An elaborate error handling scheme that results in
retransmitted messages when they are not properly
received. 53
SAE stands for Society of Automotive Engineers
NMEA stands for National Marine Educators Association

SDS stands for Smart Distributed System


54 2/5/2022
Arbitration – needed when multiple nodes try to transmit at the
same time
Only one transmitter is allowed to transmit at a time.
A node waits for bus to become idle
Nodes with more important messages continue transmitting

CAN bus

55 2/5/2022
A Basic CAN controller
56

 Cheap CAN controller – CPU could get overrun with


messages and can get bogged down quickly with multiple
consecutive messages.
 Limited number of receive buffers and filter.
Implementation (con’t)
 FIFO
🞑 “First In First Out” receive
buffer
🞑 Fixes problem with multiple
consecutive messages
🞑 Cannot allow a high priority
message to move to front.
It has to wait its turn
CAN Bus Overview
 A CAN controller is a sophisticated device. All you
need to do is to configure the controller by writing
to its registers and controller does all the
housekeeping work to get your message .
 The controller will read any frames it sees on
the bus and hold them in a small FIFO memory.
 The controller also contains a hardware filter
mechanism that can be programmed to ignore and
discard. This saves on processor overhead.
Main Features of CAN
 A CAN network consists of physical layer (the
voltages and the wires), a frame consisting of an ID
and a varying number of data bytes all with the
following general attributes.
 1. 11 or 29 bit ID and from zero to 8 data bytes.
These attributes can be dynamically changed “on
the fly”.
 2. Peer to Peer network. Every node can see all
messages from all other nodes but it normally can’t
see its own.
Main Features of CAN
 3. Nodes are really easy to add. Just attach one to
the network with two wires plus a ground.
 4. Higher priority messages are sent. The lower ID
has a higher priority.
 5. Automatic retransmission of defective frames. A
node will “bus-off” if it causes too many errors.
 6. Speeds from approximately 10 Kbps to 1 Mbps.
TIP: All nodes must operate at the same frequency.
Main Features of CAN
 7. The twisted differential pair provides excellent
noise immunity and some decent bus fault
protection.
 8. The CAN system will work with the ground
connection at different DC levels. TIP: Or no
ground at all.
Network Topology of CAN
 This transceiver IC1 connects to the STM32 microprocessor
IC2 which contains an integral CAN controller via two pins:
D (Driver input) and R (Receiver output).
 The corresponding nomenclature on the STM32 is CAN Rx
and CAN Tx. CAN Tx connects to D. CAN Rx connects to R.
The CAN Frame
 The CAN frame has many fields but we can simplify this to a
Programming Model as shown. These fields are accessed by your
software through the CAN controller registers. The configuration
registers are not included here.
 IDE: Identifier Extension: 1 bit - specifies if the ID field to be
transmitted is 11 or 29 bits:
 If IDE = 0, then the ID is 11 bits. If IDE = 1, then the ID is 29 bits
 ID: Identifier: 11 or 29 bits as set by the IDE field. This part of the
CAN frame sets the priority.
 DLC: Data Length Code: 4 bits - specifies number of data bytes in
the frame from 0 through 8.
 Data Bytes: 0 through 8 bytes.
DATA FRAME

SOF – Start of Frame, Identifier – Tells the content of message and priority
RTR – Remote Transmission Request, IDE – Identifier extension
DLC – Data Length Code Data – holds up to 8 bytes of data

CRC – “Cyclic Redundant Check” sum ACK – Acknowledge

64
EOF – End of Frame IFS – Inte2/r5m/2i0s2s2ion Frame
Space.
ID: Identifier: 11 or 29 bits
 The Identifier can be used for any purpose. It is often used as
a node address or to identify requests and responses. 11 bit is
often called Standard CAN and 29 bit is often called Extended
CAN.
 If two or more CAN messages are put on the bus at the same
time; the one with the highest priority (the lowest value) ID
will immediately get through.
 An ID of 0 has the highest priority and will always get
through. When the first 11 bits of an 11 and 29 bit ID are the
same, the 11 bit ID has priority over the 29 bit ID.
ID: Identifier: 11 or 29 bits
 A CAN node is not allowed to start transmitting a
frame in the middle of another node’s frame. This
will cause a bus error.
 CAN controllers can be configured to pass only
certain received messages to its host processor.
Choose your ID values carefully to take advantage of
this if needed. This will reduce workload of CPU.
 This is why some systems use 29 bit IDs even though
they do not need that many addresses. This facilitates
grouping of IDs for easier filtering.
Data Bytes
 You can select from 0 to 8 data bytes using the 4 bit DLC
field.
 You can have any number of data bytes in frames on the CAN

bus. The controller can easily sort this out.


 The data bytes can contain anything. It is not prioritized like

the ID is. CAN does not specify mandatory data.


 Protocols such as J1939
specify these for data
as well as control bits for
multi-frame transmission schemes.
Remote Frames
 A remote frame is a quick method of getting a response from
another node(s). It is a request for data.
 The requesting node sends out a shortened CAN frame
with only a user specified ID number and the number of data
bytes it expects to receive (the DLC is set). No data field is
sent.

 The responding node(s) sees this frame, recognizes that it has


the desired information and sends back a standard CAN frame
with the same ID, DLC and with data bytes attached.
 All of this (except that the response node recognizes the ID
and DLC) is implemented in the CAN controller hardware.
Sequence of Transmitting Data on the CAN Bus

🞑 You give the transmitter the ID, the size of the ID


(IDE), the number of data bytes (DLC) and the data
if any.
🞑 You then set a bit to tell the transmitter in the CAN
controller to send this frame.
🞑 Any node(s), seeing the bus idle for the required
minimum time, can start sending a CAN frame.
🞑 All other nodes start receiving it except those also
starting to transmit a message at the same time.
Sequence of Transmitting Data on the CAN Bus

🞑 If any other node starts transmitting: the arbitration


process starts – the node with the highest priority
(lower ID value) continues and lesser priority nodes
stop sending. And immediately turn into receivers
and receive the priority message.
🞑 When the transmitting node has completed sending
its message, it waits one bit time for the 1 bit ACK
field to be pulled to a logic 0 by any other node
(normally all of them) to signify the frame was
received without errors.
Sequence of Transmitting Data on the CAN Bus

🞑 If this happens, the transmitting node assumes the


message reached its recipient, sends the end-of-frame
bits and goes into receive mode or starts to send its
next message if it has one. The receiving nodes pass
the received message to their host processors for
processing.
🞑 At this time, any node can start sending any message
or the bus goes into the idle state.
🞑 If ACK bit not set, then the transmitting retransmits
the message at the earliest time allowed.
Data Information – Error detection
(con’t)
 Message Level
🞑 CRC = Cyclic Redundant Check sum
🞑 Frame Check = compares message to fixed format and frame size
🞑 ACK errors = if transmitter does not receive an ACK signal from
the receivers
 Bit level
🞑 Monitoring = The transmitter monitors the bus signal as it sends
the message and compares the bit sent to the bit received.
🞑 Bit Stuffing = After five consecutive equal bits, the transmitter
inserts a stuff bit with a compliment value into the bit stream.
The receivers remove this stuff bit.
1. The Data Frame

 Summary: "Hello everyone, here's some data labeled X, hope


you like it!“

2. The Remote Frame


Summary: "Hello everyone, can somebody please produce
the data labeled X?"
3. The Error Frame
Summary: "OH DEAR, LET'S TRY AGAIN" 4 The
Overload Frame

Summary: "I'm a very busy ,could you please wait for a


moment?"
73 2/5/2022
Manufacturers
 Over 20 different chip manufacturers produce
microcontrollers with on-chip CAN interfaces.
 Some more notable ones are:
🞑 Cygnal
🞑 Intel
🞑 Motorola
🞑 NEC
🞑 Phillips
🞑 Toshiba
74 2/5/2022
75 2/5/2022
76 2/5/2022
The CAN Controller is designed to provide implementation of
the CAN-Protocol Version 2.0B. Some microcontrollers are with
this on-chip CAN controller.
The applications are automotive, industrial environments, and
high speed networks as well as low cost multiplex wiring.
The CAN module consists of two elements: the controller and
the Acceptance Filter. All registers are 32-bit words.
CAN controller has physical and Data Link layers.

77 2/5/2022

You might also like