Embedded Processer - Merged PDF

You might also like

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

UNIT 3 These are 8-bit read-write registers.

Q.1 Features of UART in LPC2148 UART0 Divisor Latch holds the value by
• 16 byte Receive and Transmit FIFOs • which the PCLK(Peripheral Clock) will be
Register locations conform to ‘550 industry divided. This value must be 1/16 times the
standard. • Receiver FIFO trigger points at 1, desired baud rate.
4, 8, and 14 bytes. • Built-in fractional baud A 0x0000 value is treated like a 0x0001 value
rate generator with autobauding capabilities. as division by zero is not allowed.
• Mechanism that enables software and The Divisor Latch Access Bit (DLAB) in
hardware flow control implementation. U0LCR must be one in order to access the
UART0 Registers- UART0 Divisor Latches. (DLAB = 1)
1.U0RBR (UART0 Receive Buffer
Register)
1. It is an 8-bit read only register.
2. This register contains the received data.
3. It contains the “oldest” received byte in
the receive FIFO.
4. If the character received is less than 8 4. U0FDR (UART0 Fractional Divider
bits, the unused MSBs are padded with Register)
zeroes. It is a 32-bit read write register.
5. The Divisor Latch Access Bit (DLAB) in It decides the clock pre-scalar for baud rate
U0LCR must be zero in order to access generation.
the U0RBR. (DLAB = 0) If fractional divider is active (i.e.
DIVADDVAL>0) and DLM = 0, DLL must
be greater than 3.
U0FDR (UART0 Fractional Divider
Register)
2. U0THR (UART0 Transmit Holding U0FDR (UART0 Fractional Divider
Register) Register)
1. It is an 8-bit write only register. If DIVADDVAL is 0, the fractional baudrate
2. Data to be transmitted is written to this generator will not impact the UART0
register. baudrate.
3. It contains the “newest” received byte in Reset value of DIVADDVAL is 0.
the transmit FIFO. MULVAL must be greater than or equal to 1
4. The Divisor Latch Access Bit (DLAB) in for UART0 to operate properly, regardless of
U0LCR must be zero in order to access whether the fractional baudrate generator is
theU0THR. (DLAB = 0) used or not.
Reset value of MULVAL is 1.
The formula for UART0 baudrate is given
below
3. U0DLL and U0DLM (UART0 Divisor MULVAL and DIVADDVAL should have
Latch Registers) values in the range of 0 to 15. If this is not
U0DLL is the Divisor Latch LSB. ensured, the output of the fractional divider is
U0DLM is the Divisor Latch MSB. undefined.
The value of the U0FDR should not be Bit 0 - Interrupt Pending
modified while transmitting/receiving data. 0 = At least one interrupt is pending
This may result in corruption of data. 1 = No interrupts pending
Bit 3:1 - Interrupt Identification
Identifies an interrupt corresponding to
theUART0 Rx FIFO.
5. U0IER (UART0 Interrupt Enable 011 = Receive Line Status (RLS) Interrupt
Register) 010 = Receive Data Available (RDA)
It is a 32-bit read-write register. Interrupt
It is used to enable UART0 interrupt sources. 110 = Character Time-out Indicator (CTI)
DLAB should be zero (DLAB = 0). Interrupt
U0IER (UART0 Interrupt Enable Register) 001 = THRE Interrupt
U0IER (UART0 Interrupt Enable Register) Bit 7:6 - FIFO Enable These bits are
Bit 0 - RBR Interrupt Enable. It also controls equivalent to FIFO enable bit in FIFO
the Character Receive Time-Out interrupt. Control Register,
0 = Disable Receive Data Available interrupt 0 = If FIFOs are disabled
1 = Enable Receive Data Available interrupt 1 = FIFOs are enabled
Bit 1 - THRE Interrupt Enable Bit 8 - ABEO Interrupt
0 = Disable THRE interrupt If interrupt is enabled,
1 = Enable THRE interrupt 0 = No ABEO interrupt
Bit 2 - RX Line Interrupt Enable 1 = Auto-baud has finished successfully
0 = Disable UART0 RX line status interrupts Bit 9 - ABTO Interrupt
1 = EnableUART0 RX line status interrupts If interrupt is enabled,
Bit 8 - ABEO Interrupt Enable 0 = No ABTO interrupt
0 = Disable auto-baud time-out interrupt 1 = Auto-baud has timed out
1 = Enable auto-baud time-out interrupt
Bit 9 - ABTO Interrupt Enable
0 = Disable end of auto-baud interrupt
1 = Enable the end of auto-baud interrupt 7. U0LCR (UART0 Line Control
Register)
It is an 8-bit read-write register.
It determines the format of the data character
that is to be transmitted or received.
6. U0IIR (UART0 Interrupt
U0LCR (UART0 Line Control Register)
Identification Register)
U0LCR (UART0 Line Control Register)
It is a 32-bit read only register.
Bit 1:0 - Word Length Select
U0IIR (UART0 Interrupt Identification
00 = 5-bit character length
Register)
01 = 6-bit character length
U0IIR (UART0 Interrupt Identification
10 = 7-bit character length
Register)
11 = 8-bit character length
It provides a status code that denotes the
Bit 2 - Number of Stop Bits
priority and source of a pending interrupt.
0 = 1 stop bit
It must be read before exiting the Interrupt
1 = 2 stop bits
Service Routine to clear the interrupt.
Bit 3 - Parity Enable 0 = Break interrupt status inactive
0 = Disable parity generation and checking 1 = Break interrupt status active
1 = Enable parity generation and checking This bit is cleared when U0LSR is read.
Bit 5:4 - Parity Select Bit 5 - Transmitter Holding Register
00 = Odd Parity Empty
01 = Even Parity 0 = U0THR has valid data
10 = Forced “1” Stick Parity 1 = U0THR empty
11 = Forced “0” Stick Parity Bit 6 - Transmitter Empty
Bit 6 - Break Control 0 = U0THR and/or U0TSR contains valid
0= Disable break transmission data
1 = Enable break transmission 1 = U0THR and U0TSR empty
Bit 7 - Divisor Latch Access Bit (DLAB) Bit 7 - Error in RX FIFO (RXFE)
0 = Disable access to Divisor Latches 0 = U0RBR contains no UART0 RX errors
1 = Enable access to Divisor Latches 1 = U0RBR contains at least one UART0 RX
error
This bit is cleared when U0LSR is read.
9. U0TER (UART0 Transmit Enable
Register)
8. U0LSR (UART0 Line Status Register)

It is an 8-bit read-write register.


It is an 8-bit read only register. The U0TER enables implementation of
U0LSR (UART0 Line Status Register) software flow control. When TXEn=1,
U0LSR (UART0 Line Status Register) UART0 transmitter will keep sending data as
It provides status information on UART0 RX long as they are available. As soon as TXEn
and TX blocks. becomes 0, UART0 transmission will stop.
Bit 0 - Receiver Data Ready Software implementing software-
0 = U0RBR is empty handshaking can clear this bit when it
1 = U0RBR contains valid data receives an XOFF character (DC3). Software
Bit 1 - Overrun Error can set this bit again when it receives an XON
0 = Overrun error status inactive (DC1) character.
1 = Overrun error status active Bit 7 : TXEN
This bit is cleared when U0LSR is read. 0 = Transmission disabled
Bit 2 - Parity Error 1 = Transmission enabled
0 = Parity error status inactive If this bit is cleared to 0 while a character is
1 = Parity error status active being sent, the transmission of that character
This bit is cleared when U0LSR is read. is completed, but no further characters are
Bit 3 - Framing Error sent until this bit is set again.
0 = Framing error status inactive Q.2 features of ON chip ADC of LPC2148
1 = Framing error status active • 10 bit successive approximation analog to
This bit is cleared when U0LSR is read. digital converter (two in LPC2148) • Input
Bit 4 - Break Interrupt multiplexing among 6 or 8 pins (ADC0 and ADC1).
• Power-down mode. • Measurement range 0 V for(AoutValue = 0 ; AoutValue < 1024 ;
to VREF (typically 3 V; not to exceed VDDA AoutValue ++)
voltage level). • 10 bit conversion time 2.44 s. {
LPC2148 has two inbuilt ADC Modules, • DACR = AoutValue << 6 ;
named as ADC0 & ADC1. • ADC0 has 6- }
Channels • ADC1 has 8-Channels • ADC for(AoutValue = 1023 ;
operating frequency is 4.5 MHz (max.), AoutValue > 0 ; AoutValue --)
operating frequency decides the conversion {
time. • Supports power down mode. • Burst DACR = AoutValue << 6 ;
conversion mode for single or multiple }
inputs. }
}
Q.3 Write features of DAC in LPC2148.
•LPC2148 has 10-bit DAC with resistor string Algorithm of Square wave-
architecture. •It also works in Power down 1. Initialize the DAC by configuring the
mode. • The DAC has a single analog output pin P0.25/AOUT pin as a DAC output using the
(AOUT) that can be used to output the converted PINSEL register.
analog voltage. • The DAC has a voltage 2. Set the DACR register to output the maximum
reference pin (VREF) that provides the reference voltage.
voltage for the conversion process. •The DAC 3. Start a timer with a frequency of the desired
has two analog power and ground pins (VDDA square wave frequency.
and VSSA) that provide the power and ground 4. In the timer interrupt handler, toggle the
for the DAC circuitry. • The DAC uses a resistor DACR register.
string to convert digital values to analog 5. Repeat steps 4 and 5 until the desired number
voltages. This architecture is relatively simple of square waves have been generated.
and inexpensive to implement. Program-
Algorithm – Triangular waveform #include <Philips\LPC2148.h>
1. Initialize the DAC by configuring the DACR #define DACR
register. unsigned int AoutValue = 0 ;
2. Set the DAC output to the minimum voltage. void Delay(void)
3. Repeat the following steps: {
* Increase the DAC output by 1 step. int k,j;
* Wait for the DAC to settle. for(k = 0 ; k < 5 ; k ++)
4. Repeat step 3 until the DAC output reaches {
the maximum voltage. for(j = 0 ; j < 100 ; j ++);
5. Repeat steps 2-4 continuously. }
Program- }
#include <Philips\LPC2148.h> int main (void)
#define DACR {
unsigned int AoutValue = 0 ; PINSEL1 = 0x00080000 ;
int main (void) while(1)
{ {
PINSEL1 = 0x00080000 ; AoutValue =1023;
while(1) DACR = AoutValue << 6 ;
{ Delay();
AoutValue =0; rates to communicate via one serial bus. • Serial
DACR = AoutValue << 6 ; clock synchronization can be used as a
Delay(); handshake mechanism to suspend and resume
} serial transfer. • The I2C bus may be used for test
Algorithm for staircase- and diagnostic purposes.
1. Initialize the DAC.
2. Set the DAC output pin as an output.
3. Create a loop that iterates from 0 to 1023.
4. In each iteration of the loop, write the current
value to the DAC register.
5. Wait for the DAC to settle.
6. Repeat steps 3-5 until the desired number of
samples have been generated.
7. Disable the DAC.
Algorithm for positive ramp waveform
1. Initialize the DAC register to 0.
2. Set a timer to trigger every millisecond.
3. In the timer interrupt handler, increment the Algorithm - 1) Start 2) Initialize I2C bus interface
value of the DAC register by 1. 3)Transmit the slave address 4)Enable I2C bus
4. If the value of the DAC register reaches 1023, interface 5)Master (LPC2148) will transmit
reset it to 0. START signal 6) Transmit slave address 7) Wait
5. Repeat steps 3 and 4 indefinitely. for acknowledgement 8) Tansmit Page address
Algorithm for negative ramp waveform and page offset at which data is to be written 9)
1. Initialize the DAC registers. Wait for acknowledment 10) Transmit data using
2. Set the DAC output voltage to the maximum I2CDAT register 11) Wait for acknowledge
value. 12)After successful transmission of data , master
3. Start a timer. will transmit STOP condition 13)Disable I2C
4. While the timer is running: interface 14) END
* Decrement the DAC output voltage by 1. Q.5 Draw and explain interfacing of DHT11with
* Update the DAC registers. LPC2148. Write algorithm/ flowchart to display
5. Stop the timer. temperature and humidity
6. Repeat steps 3-5 until the DAC output voltage
reaches 0.
Q.4 Explain interfacing of EEPROM using I2C &
Features
Features of EEPROM • Standard I2C compliant
bus interfaces that may be configured as Master,
Slave, or Master/Slave. • Arbitration between
simultaneously transmitting masters without
corruption of serial data on the bus. •
Programmable clock to allow adjustment of I2C
transfer rates. • Bidirectional data transfer
between masters and slaves. • Serial clock
synchronization allows devices with different bit
The DHT11 sensor sends its data in a single-
wire, half-duplex format. The sensor starts by
sending a 80 microsecond low pulse,
followed by a 80 microsecond high pulse.
This is the start signal. After the start signal,
the sensor sends 40 bits of data, 8 bits for the
humidity and 8 bits for the temperature. Each
bit is represented by a high pulse of 50
microseconds or a low pulse of 26
microseconds. To receive the data from the
DHT11 sensor, the LPC2148 microcontroller
must poll the P0.2 pin. When the pin is high, The GSM module communicates with the
the microcontroller should store the data bit LPC2148 microcontroller through a UART
as a 1. When the pin is low, the interface. The UART TXD pin of the
microcontroller should store the data bit as a LPC2148 is connected to the TXD pin of the
0. The temperature and humidity values can GSM module. The UART RXD pin of the
be calculated from the received data using the LPC2148 is connected to the RXD pin of the
following formulas: GSM module.
Temperature = (data[15] * 16 + data[14]) * Steps To interface the GSM module with the
0.1 LPC2148
Humidity = (data[7] * 16 + data[6]) * 0.1 1.Configure the UART0 peripheral in the
LPC2148 microcontroller. 2.Configure the
The temperature and humidity values can be
GSM module to use UART mode. 3.Send AT
displayed on a serial terminal or LCD display commands to the GSM module to initialize it.
Algorithm- 4. Send the text message to the GSM module.
1. START 5. Wait for the GSM module to send an
2. Initialize the DHT11 sensor. acknowledgement.
3. Send a start signal to the DHT11 sensor. Algorithm to send message
4. Receive the 40-bit data from the DHT11 1. Initialize the UART0 peripheral in the
sensor. LPC2148 microcontroller.
5. Calculate the temperature and humidity 2. Configure the GSM module to use UART
values from the received data. mode.
6. Display the temperature and humidity 3. Send AT commands to the GSM module to
values on a serial terminal or LCD initialize it.
display. 4. Get the phone number of the recipient.
7. END 5. Send the AT command to send a message.
Q.6 Draw interfacing diagram of GSM using 6. Enter the recipient's phone number.
UART with LPC 2148. Write algorithm to send 7. Enter the text message.
message using GSM Module 8. Send the AT command to end the message.
9. Wait for the GSM module to send an
acknowledgement.
Q.7 Write algorithm/flowchart to display 3. Set the PWM frequency to the desired
location received from GPS interfaced with frequency.
LPC2148. 4. Set the PWM duty cycle to the desired position
1. Initialize the GPS module. of the servo motor.
2. Wait for the GPS module to acquire a signal. 5. Start the PWM timer.
3. Read the latitude and longitude data from the 6. Wait for the servo motor to reach the desired
GPS module. position.
4. Convert the latitude and longitude data to 7. Stop the PWM timer.
decimal format.
5. Display the latitude and longitude data on a
serial terminal or LCD display.
Q.8 Draw and explain interfacing of servomotor
with LPC2148. Write algorithm/flowchart to
rotate the motor.

Interfacing Servo Motor With LPC2148

The servo motor's signal wire is typically


connected to the LPC2148's P0.1 pin. The PWM
frequency is typically set to 50 Hz. The PWM duty
cycle is typically set between 1 ms and 2 ms. The
PWM duty cycle determines the position of the
servo motor. For example, a PWM duty cycle of
1 ms will cause the servo motor to rotate to 0
degrees, while a PWM duty cycle of 2 ms will
cause the servo motor to rotate to 180 degrees.
Once the PWM timer has been started, the servo
motor will rotate to the position determined by
the PWM duty cycle. The servo motor will
continue to rotate until the PWM timer is
stopped.
Algorithm-
1. Initialize the PWM peripheral in the LPC2148
microcontroller.
2. Configure the P0.1 pin as a PWM output pin.
UNIT – 4 CMSIS-RTOS: This component provides a
Q.1 Write features of STM32F4XX processor. software abstraction layer for real-time
All devices offer three 12-bit ADCs, two DACs, a operating systems (RTOSes). The RTOS
low-power RTC, twelve general-purpose 16-bit abstraction layer provides a consistent interface
timers including two PWM timers for motor to different RTOSes, making it easier to write
control, two general-purpose 32-bit timers. a software that can be reused across different
true random number generator (RNG). They also RTOSes.
feature standard and advanced communication CMSIS-Pack: This component is a package
interfaces. 1) Up to three I2Cs 2) Three SPIs, two manager for CMSIS components. CMSIS-Pack
I2Ss full duplex. To achieve audio class accuracy, makes it easy to find, download, and install
the I2S peripherals can be clocked via a CMSIS components. CMSIS is a valuable tool for
dedicated internal audio PLL or via an external developers of microcontroller software. It can
clock to allow synchronization. 3) Four USARTs help to simplify the development process,
plus two UARTs 4) An USB OTG full-speed and a improve code portability, and reduce the time to
USB OTG high-speed with full-speed capability market for new products.
(with the ULPI), 5) Two CANs 6) An SDIO/MMC Q.3 How CMSIS Standard is used for firmware
interface 7) Ethernet and the camera interface. development?
STM32F40XX Applications – 1) The CMSIS is a set of tools, APIs, frameworks,
 STM32F407xx microcontroller family suitable and work flows that help to simplify software re-
for a wide range of applications:  Motor drive use, reduce the learning curve for
and application control  Medical equipment  microcontroller developers, speed-up project
Industrial applications: PLC, inverters, circuit build and debug, and thus reduce the time to
breakers  Printers, and scanners  Alarm market for new applications. 2) CMSIS started as
systems, video intercom, and HVAC  Home a vendor-independent hardware abstraction
audio appliances layer Arm® Cortex®-M based processors and was
Q.2 Explain CMSIS standard. later extended to support entry-level Arm
CMSIS is stands for Cortex Microcontroller
Cortex-A based processors. To simplify access,
Software Interface Standard. It is a set of
CMSIS defines generic tool interfaces and
software libraries and tools that simplify the
development of software for microcontrollers enables consistent device support by providing
based on the ARM Cortex-M processor line. simple software interfaces to the processor and
CMSIS provides a consistent and portable the peripherals. 3) CMSIS is defined in close
interface to the processor's core and cooperation with various silicon and software
peripherals, making it easier to write software vendors and provides a common approach to
that can be reused across different interface to peripherals, realtime operating
microcontrollers. systems, and middleware components. It is
CMSIS includes the following components: intended to enable the combination of software
CMSIS-Core: This is the core of the CMSIS components from multiple vendors. 4) CMSIS is
standard, and it provides a portable interface to open-source and collaboratively developed on
the Cortex-M processor core. CMSIS-Core
GitHub.
includes definitions for the processor's registers,
5) The aims of CMSIS include: 1) Enhanced
interrupts, and exception handling.
CMSIS-Device: This component provides a software reusability - makes it easier to reuse
hardware abstraction layer (HAL) for a specific software code in different Cortex-M projects,
microcontroller device. The HAL provides a set of reducing time to market and verification efforts.
functions that abstract the hardware details of 2) Enhanced software compatibility - by having a
the device, making it easier to write software consistent software infrastructure (e.g., API for
that can be reused across different devices. processor core access functions, system
initialization method, common style for defining Q.5 Explain programmer model of ARM CORTEX
peripherals), software from various sources can M4.
work together, reducing the risk in integration.  Operation states :  Debug state: When the
3) Easy to learn - the CMSIS allows easy access to processor is halted (e.g., by the debugger, or
processor core features from the C language. In after hitting a breakpoint), it enters debug state
addition, once you learn to use one Cortex-M and stops executing instructions.
microcontroller product, starting to use another  Thumb state: If the processor is running
Cortex-M product is much easier because of the program code (Thumb instructions), it is in the
consistency in software setup. 4) Toolchain Thumb state.
independent - CMSIS-compliant device drivers
can be used with various compilation tools,
providing much greater freedom. 5) Openness -
the source code for CMSIS core files can be
downloaded and accessed by everyone, and
everyone can develop software products with
CMSIS.
Q.4 Describe Memory Map of ARM CORTEX M4.

 Operation modes
 Handler mode: When executing an exception
handler such as an Interrupt Service Routine
(ISR). When in handler mode, the processor
always has privileged access level.
 Thread mode: When executing normal
application code, the processor can be either in
privileged access level or unprivileged access
level. This is controlled by a special register
 The 4GB address space of the Cortex-M called “CONTROL.”
processors is partitioned into a number of Programmer’s model : Registers
memory regions . The partitioning is based on
typical usages so that different areas are
designed to be used primarily for:  Program
code accesses (e.g., CODE region)  Data
accesses (e.g., SRAM region)  Peripherals (e.g.,
Peripheral region)  Processor’s internal control
and debug components (e.g., Private Peripheral
Bus)  The architecture also allows high
flexibility to allow memory regions to be used for
other purposes. For example, programs can be
executed from the CODE as well as the SRAM
region, and a microcontroller can also integrate
SRAM blocks in CODE region.
The register bank in the Cortex-M4 processors (e.g., using data transfer/processing
has 16 registers. Thirteen of them Parikrama instructions) causes a branch operation.  Since
COE are purpose general 32-bit registers, and the instructions must be aligned to half-word or
the other three have special uses. word addresses, the Least Significant Bit (LSB) of
 R0 - R12  Registers R0 to R12 are general the PC is zero.
purpose registers.  The first eight (R0 - R7) are Programmer’s model : Special registers
also called low registers.  Due to the limited  Program status registers  The Program Status
available space in the instruction set, many 16- Register is composed of three status registers: 
bit instructions can only access the low registers. Application PSR (APSR)  Execution PSR (EPSR) 
 The high registers (R8 - R12) can be used with Interrupt PSR (IPSR)
32-bit instructions, and a few with 16-bit
instructions, like MOV (move). The initial values
of R0 to R12 are undefined.
 R13, stack pointer (SP)  It is used for
accessing the stack memory via PUSH and POP
operations.  Physically there are two different
Stack Pointers: the Main Stack Pointer (MSP, or
SP_main in some ARM documentation) is the
default Stack Pointer. It is selected after reset, or
when the processor is in Handler Mode.  The
other Stack Pointer is called the Process Stack
Pointer (PSP, or SP_process in some ARM
documentation). The PSP can only be used in
Thread Mode. The selection of Stack Pointer is
determined by a special register called
Q.6 What are different exceptions and nested
CONTROL.
Vector interrupt Controller in STM32F4xx
 R14, link register (LR)  R14 is also called the controller?
Link Register (LR). This is used for holding the
return address when calling a function or
subroutine.  At the end of the function or
subroutine, the program control can return to
the calling program and resume by loading the
value of LR into the Program Counter (PC). 
When a function or subroutine call is made, the
value of LR is updated automatically.  If a
function needs to call another function or
subroutine, it needs to save the value of LR in the Exceptions—
stack first.  Otherwise, the current value in LR  In Cortex-M processors, there are a number of
will be lost when the function call is made. exception sources:  Exceptions are processed
 R15, program counter (PC)  It is readable and by the NVIC. The NVIC can handle a number of
writeable: a read returns the current instruction Interrupt Requests (IRQs) and a Non-Maskable
address plus 4 (this is due to the pipeline nature Interrupt (NMI) request.  Usually IRQs are
of the design, and compatibility requirement generated by on-chip peripherals or from
with theARM7TDMI processor).  Writing to PC external interrupt inputs though I/O ports.  The
NMI could be used by a watchdog timer or Vectored exception/interrupt entry  Interrupt
brownout detector (a voltage monitoring unit masking.
that warns the processor when the supply Q. 7 Reset and resetsequence
voltage drops below a certain level).  Inside the  In typical Cortex-M microcontrollers, there can
processor there is also a timer called SysTick, be three types of reset:  Power on reset - reset
which can generate a periodic timer interrupt everything in the microcontroller. This includes
request, which can be used by embedded OSs for the processor and its debug support component
timekeeping, or for simple timing control in and peripherals.  System reset - reset just the
applications that don’t require an OS. processor and peripherals, but not the debug
 The processor itself is also a source of support component of the processor. 
exception events.  These could be fault events Processor reset - reset the processor only.  The
that indicate system error conditions, or duration of Power on reset and System reset
exceptions generated by software to support depends on the microcontroller design.  In
embedded OS operations.  As opposed to some cases the reset lasts a number of milli
classic ARM processors such as the ARM7TDMI, seconds as the reset controller needs to wait for
there is no FIQ (Fast Interrupt) in the Cortex-M a clock source such as a crystal oscillator to
processor. However, the interrupt latency of stabilize.
Corex-M4 is very low, only 12 clock cycles, so this
does not cause problems.
Vector interrupt Controller—
 Nested exception/interrupt support  Each
exception has a priority level. Some exceptions,
such as interrupts, have programmable priority
levels and some others (e.g., NMI) have a fixed
priority level.  When an exception occurs, the
 The setup of the MSP is necessary because
NVIC will compare the priority level of this
some exceptions such as the NMI or HardFault
exception to the current level.  If the new
handler could potentially occur shortly after the
exception has a higher priority, the current
reset, and the stack memory and hence the MSP
running task will be suspended.  Some of the
will then be needed to push some of the
registers will be stored on the stack memory, and
processor status to the stack before exception
the processor will start executing the exception
handling.
handler of the new exception.  This process is
Q.8 What are advantages & disadvantages of
called “preemption.” When the higher priority
ARM Cortex over ARM Processor?
exception handler is complete, it is terminated
Advantages:
with an exception return operation and the
Higher performance: ARM Cortex processors
processor automatically restores the registers
typically have a higher clock speed than ARM
from stack and resumes the task that was
processors, which can lead to improved
running previously.  This mechanism allows
performance in applications that are CPU-
nesting of exception services without any
intensive.
software overhead.
More features: ARM Cortex processors typically
 The NVIC has the following features:
have more features than ARM processors, such
 Flexible exception and interrupt management as a floating-point unit (FPU), which can be used
 Nested exception/interrupt support  for high-precision mathematical operations.
Lower power consumption: ARM Cortex redundancy check) calculation unit  The CRC
processors typically have lower power (cyclic redundancy check) calculation unit is used
consumption than ARM processors, which can to get a CRC code from a 32-bit data word and a
extend the battery life of devices that use them. fixed generator polynomial.
Smaller size: ARM Cortex processors typically Embedded SRAM
have smaller size and silicon footprint than ARM All STM32F40xxx products embed:  Up to 192
processors, which can make them suitable for Kbytes of system SRAM including 64 Kbytes of
use in devices with limited space, such as CCM (core coupled memory) data RAM RAM
wearables and Internet of Things (IoT) devices memory is accessed (read/write) at CPU clock
Disadvantages: speed with 0 wait states.
More expensive: ARM Cortex processors Multi-AHB bus matrix
typically cost more than ARM processors. The 32-bit multi-AHB bus matrix interconnects
Less compatibility: ARM Cortex processors may all the masters (CPU, DMAs, Ethernet, USB HS)
not be compatible with some older ARM and the slaves (Flash memory, RAM, FSMC, AHB
processors or software. and APB peripherals) and ensures a seamless
Higher learning curve: ARM Cortex processors and efficient operation even when several high-
may have a higher learning curve than ARM speed peripherals work simultaneously
processors, due to their more complex features. DMAcontroller (DMA)
Q.9 With the block diagram explain the  The devices feature two general-purpose dual-
STM32F4xx Architecture. port DMAs (DMA1 and DMA2) with 8 streams
Adaptivereal each. They are able to manage memory-to-
timememoryaccelerator(ARTAccelerator™) memory, peripheral-to-memory and memory-
The ART Accelerator™ is a memory accelerator to-peripheral transfers. They feature dedicated
which is optimized for STM32 industry-standard FIFOs for APB/AHB peripherals, support burst
ARM® Cortex®-M4 with FPU processors. It transfer and are designed to provide the
balances the inherent performance advantage of maximum peripheral bandwidth (AHB/APB)
the ARM Cortex-M4 with FPU over Flash memory DMAcontroller (DMA)
technologies, which normally requires the Each stream is connected to dedicated hardware
processor to wait for the Flash memory at higher DMA requests, with support for software trigger
frequencies. on each stream. Configuration is made by
Memory protection unit software and transfer sizes between source and
The memory protection unit (MPU) is used to destination are independent.
manage the CPU accesses to memory to prevent Clocks and startup
one task to accidentally corrupt the memory or On reset the 16 MHz internal RC oscillator is
resources used by any other active task. This selected as the default CPU clock. The 16 MHz
memory area is organized into up to 8 protected internal RC oscillator is factorytrimmed to offer
areas that can in turn be divided up into 8 1% accuracy over the full temperature range. 
subareas. The protection area sizes are between The application can then select as system clock
32 bytes and the whole 4 gigabytes of either the RC oscillator or an external 4-26 MHz
addressable memory clock source. Boot modes
Embedded Flash memory At startup, boot pins are used to select one out
 The STM32F40xxx devices embed a Flash of three boot options:  Boot from user Flash 
memory of 512 Kbytes or 1 Mbytes available for Boot from system memory  Boot from
storing programs and data.  CRC (cyclic embedded SRAM
Q.10 ARM Processor Families data, while the RAM is used to store temporary
Cortex-A series (Application) – High data and variables.
performance processors capable of full I/O ports: The STM32F4xx has 16 general-
Operating System (OS) support; – Applications purpose I/O ports, which can be used to control
include smartphones, digital TV, smart books, a variety of external devices. The I/O ports can
home gateways etc. be configured to operate in a variety of modes,
Cortex-R series (Real-time) – High performance including digital input, digital output, analog
for real-time applications; – High reliability – input, and analog output.
Applications include automotive braking system, Serial communication peripherals: The
powertrains etc. STM32F4xx has a variety of serial
Cortex-M series (Microcontroller) – Cost- communication peripherals, including:
sensitive solutions for deterministic UARTs: The STM32F4xx has up to 10 UARTs,
microcontroller applications; – Applications which can be used for serial communication with
include microcontrollers, mixed signal devices, other devices. UARTs are a simple and efficient
smart sensors, automotive body electronics and way to transmit and receive data between
airbags; devices.
Q.11 features of ARM cortex Series SPI: The STM32F4xx has up to 3 SPI peripherals,
1) Advanced three stage pipeline. which can be used for high-speed serial
2) harvard Architecture communication with external devices. SPI is
3)Two operating modes (thread & handler) often used for communication with devices such
4) single cycle multiply & hardware divide as memory cards, sensors, and displays.
5) Thumb-2 instruction set. I2C: The STM32F4xx has up to 2 I2C peripherals,
6) Nested vectored interrup controller (NVIC) which can be used for low-speed serial
7) integrated debug & trace communication with external devices. I2C is
8) MPU (Memory protection Unit) often used for communication with devices such
9) working smarter to sleep longer. as sensors and displays.
10) power management through NVIC USB: The STM32F4xx has a USB 2.0 Full Speed
Q.12 Explain different peripherals in controller, which can be used to connect the
STM32F4XX. device to a host computer or other USB device.
CPU: The STM32F4xx is powered by a 32-bit ARM The USB controller can be used to transfer data,
Cortex-M4 CPU, which can run at up to 168 MHz. connect to the internet, and control external
The Cortex-M4 CPU is a high-performance devices.
processor that can be used for a variety of Q.13 Explain different clocks of STM32F4XX
applications, including real-time control, The STM32 has an internal clock circuit that has
embedded vision, and audio processing. the objective of generating and distributing the
FPU: The STM32F4xx also has a floating-point clock signal for the CPU and all the peripherals
unit (FPU), which can be used for high-precision The clock circuit is programmable, meaning that
mathematical operations. The FPU is especially it can use different clock source and may apply
useful for applications that require complex division and multiplication factors
calculations, such as digital signal processing Each family of STM32 MCUs has a different clock
(DSP) and image processing. circuit with different features: here we consider
Memory: The STM32F4xx has up to 2 MB of the clock of STM32F4
Flash memory and 1 MB of RAM. The Flash The STM32F4 manages two different clock
memory is used to store the program code and signals
HS: High Speed Cortex-M4 processors have:  Three-stage
LS: Low Speed pipeline design  Harvard bus architecture with
Each clock signal is generated by clock source unified memory space: instructions and data use
that can be: the same address space  32-bit addressing,
Internal: Generated by a Resistor-Capacitor net supporting 4GB of memory space  On-chip bus
External: Generated by a quartz crystal interfaces based on ARM AMBA (Advanced
resonator Microcontroller Bus Architecture) Technology,
Therefore, we have the following signal names: which allow pipelined bus operations for higher
HSI: High Speed Internal throughput  An interrupt controller called NVIC
HSE: High Speed External supporting up to 240 interrupt requests and
LSI: Low Speed Internal from 8 to 256 interrupt priority levels .
LSE: Low Speed External Support for various features for OS (Operating
Low Speed Clock (LSI and LSE) must run at a fixed System) implementation such as a system tick
frequency of 32.768 KHz timer, shadowed stack pointer  Sleep mode
It is used to feed the Real-Time Clock circuit HSI support and various low power features 
(Internal High Speed) runs at a fixed frequency of Support for an optional MPU (Memory
16 MHz HSE (External High Speed) can run at a Protection Unit) to provide memory protection
frequency that goes from 4 MHz to 26 MHz. features like programmable memory, or access
The frequency of the HSI or HSE can be speed-up permission control  Support for bit-data
by using a circuit called PLL = Phase Locked Loop accesses in two specific memory regions using a
It is a standard circuit that can act as a frequency feature called Bit Band  The option of being
multiplier/divisor used in single processor or multi-processor
List of Clock: designs.
1. CPU Clock The ISA used in Cortex-M4 processors provides a
2. HCLK to AHB BUS, CORE, MEMORY, DMA
wide range of instructions:  General data
3. FCLK Cortex free running clock
processing, including hardware divide
4. APB peripheral clock
instructions  Memory access instructions
5. APB Timer clock
supporting 8-bit, 16-bit, 32-bit, and 64-bit data,
6. RTC
as well as instructions for transferring multiple
Q.14 ARM Cortex M4Architecture
32-bit data  Instructions for bit field processing
 MultiplyAccumulate (MAC) and saturate
instructions  Instructions for branches,
conditional branches and function calls 
Instructions for system control, OS support, etc.
UNIT – 5 6. Set the 7 segment display pins to the 7
Q.1 Draw an interfacing diagram and algorithm segment display pattern for the current digit.
to interface push button and LED using 7. Repeat step 4 until the user exits the program.
STM32F4XX. END
Q.3 Draw and explain interfacing diagram of
seven segment display with STM32F4xx.

The seven segment display is connected to the


STM32F4XX's GPIOA pins. The A through G
segments of the seven segment display are
connected to GPIOA.1 through GPIOA.7,
respectively. The common cathode of the seven
Algorithm – segment display is connected to ground. To
Start display a number on the seven segment display,
1. Initialize the push button and LED pins as you need to set the corresponding GPIO pins to
inputs and outputs, respectively. HIGH or LOW. For example, to display the
2. Set the pull-up resistor on the push button pin. number 0, you would set GPIOA.1, GPIOA.3,
3. Start a loop. GPIOA.4, GPIOA.6, and GPIOA.7 to HIGH, and set
4. Read the state of the push button pin. the remaining GPIO pins to LOW.
5. If the push button is pressed, turn on the LED. Algorithm:- 1) Configure Port D as output port to
6. If the push button is not pressed, turn off the drive the segments, 2) Configure PortB0-1 as
LED. output port to select the digits, 3) Write the
7. Repeat step 4 until the user exits the program. pattern of numeral 7 on Port D, 4) Turn on the
END select pin to HIGH to activate the tens digit, 5)
Q.2 Write an algorithm to display 0 to 9 on 7 Delay for some time, 6) Write the pattern of
segment display numeral 5 on Port D, 7) Turn on the select pin to
START HIGH to activate the ones digit, 8) Delay for some
1. Initialize the 7 segment display pins as time, 9) Repeat from step 3 to 8
outputs.
2. Create a lookup table that maps each digit
from 0 to 9 to a 7 segment display pattern.
3. Start a loop.
4. Read the current digit from the user.
5. Use the lookup table to get the 7 segment
display pattern for the current digit.
Q.4 Draw and explain interfacing diagram of 6. **Read ADC Value:** Read the converted
LDR and MQ3 sensor with ARM Cortex analog value from the ADC's data register. The
Microcontroller. converted value represents the alcohol
MQ3 interfacing concentration detected by the MQ3 sensor. The
ADC conversion result can be obtained from the
ADC's data register (ADCx_DR).
7. **Process Data:** Process the ADC value as
per your requirements. The MQ3 sensor output
is typically linearly proportional to the alcohol
concentration. You may need to calibrate the
sensor readings based on your application
requirements and the sensor datasheet
LDR interfacing –

To interface the MQ3 sensor (alcohol gas sensor)


with the STM32F4xx microcontroller, follow
these steps: 1. **Hardware Connections:**
Connect the MQ3 sensor to the STM32F4xx
microcontroller. The MQ3 sensor typically has
four pins: Vcc (power supply), GND (ground),
Analog Out (analog output), and Digital Out
(digital output). Connect the Vcc pin of the
sensor to a suitable power supply voltage (e.g.,
5V), the GND pin to ground, and the Analog Out
pin to an analog input pin of the microcontroller.
2. **GPIO Configuration:** Configure the GPIO
pin connected to the Analog Out pin of the MQ3 1. **Hardware Connections:** Connect one leg
sensor as an analog input. Set the of the LDR to a GPIO pin of the STM32F4xx
GPIOx_MODER register bits to the analog mode microcontroller and the other leg to a voltage
for the corresponding pin. source (Vcc) and a ground (GND). Use a pull-up
3. **ADC Configuration:** Configure the ADC or pull-down resistor depending on the circuit
(Analog-to-Digital Converter) peripheral in the configuration. 2. **GPIO Configuration:**
STM32F4xx microcontroller to read the analog Configure the GPIO pin connected to the LDR as
voltage from the MQ3 sensor. Set the desired an analog input. Set the GPIOx_MODER register
resolution, sampling rate, and conversion mode. bits to the analog mode for the corresponding
4. **ADC Channel Selection:** Select the ADC pin. 3. **ADC Configuration:** Configure the
channel associated with the GPIO pin connected ADC (Analog-to-Digital Converter) peripheral in
to the MQ3 sensor. This is done by configuring the STM32F4xx microcontroller to read the
the ADC's channel selection register analog voltage from the LDR. Set the desired
(ADCx_SQR3 or ADCx_SQR1). resolution, sampling rate, and conversion mode.
5. **Start Conversion:** Enable the ADC and 4. **ADC Channel Selection:** Select the ADC
initiate the conversion process. Set the channel associated with the GPIO pin connected
appropriate bits in the ADC's control registers to the LDR. This is done by configuring the ADC's
(e.g., ADCx_CR2) to start the ADC conversion. channel selection register (ADCx_SQR3 or
ADCx_SQR1). 5. **Start Conversion:** Start the 1. **USART/UART Control Register 1
ADC conversion by enabling the ADC and (USARTx_CR1):** This register is used to
initiating the conversion process. This can be configure various parameters related to the
done by setting the appropriate bits in the ADC's USART/UART communication. It includes
control registers (e.g., ADCx_CR2). settings such as enabling the transmitter and
6. **Read ADC Value:** Read the converted receiver, selecting the word length (8 bits, 9
analog value from the ADC's data register. The bits), enabling parity, configuring the stop bits,
converted value represents the intensity of light enabling hardware flow control, and enabling
detected by the LDR. The ADC conversion result interrupt generation. Example: The USART_CR1
can be obtained from the ADC's data register register can be used to enable the transmitter
(ADCx_DR). 7. **Process Data:** Process the and receiver by setting the TE (Transmit Enable)
ADC value as per your requirements. You can use and RE (Receive Enable) bits.
the ADC value to determine the intensity or - Example usage: To enable the USART
brightness of light, implement threshold transmitter and receiver, you can set the TE
detection, or any other necessary logic. (Transmit Enable) and RE (Receive Enable) bits in
Q.5 Explain an algorithm to send “SPPU” serially this register. This can be done as follows:
via STM32F4XX controller to desktop PC with code ```c
baudrate 9600. USARTx>CR1|=USART_CR1_TE|USART_CR1_RE;
1) Enable the Clock to GPIOA. ```
2) Enable the Clock to USART2. 2. **USART/UART Control Register 2
3) Select the peripheral function AF7 for PA2 (USARTx_CR2):** This register is used to
(USART2_TxD) pin using the configure additional parameters of the
GPIO_MODER and GPIO_AFRL registers. USART/UART communication. It includes
4) Set the baud rate for USART2 using settings such as configuring the number of stop
USART2_BRR register. bits (1 bit, 0.5 bit, 2 bits), enabling the receiver
5) Configure the CR1 (Control 1) register for timeout feature, and enabling the LIN (Local
oversampling rate, character Interconnect Network) mode. Example: The
size (8-bit or 9-bit) and enabling transmit (TE). USART_CR2 register can be used to configure the
6) Configure the CR2 (Control 2) register for number of stop bits by setting the STOP[1:0] bits.
number of stop bit(s) and so on. 3. **USART/UART Control Register 3
7) Configure the CR3 (Control 3) register for no (USARTx_CR3):** This register is used to
hardware flow control and configure more advanced features of the
so on. USART/UART communication. It includes
8) Enable USART2 after configuration complete. settings such as enabling the DMA (Direct
9) Wait until the TXE (Transmit Empty) bit of the Memory Access) mode, enabling the Smartcard
USART_SR mode, enabling the IrDA (Infrared Data
register is set. Association) mode, and configuring the RTS
10) Write a byte to DR Register to be (Request to Send) and CTS (Clear to Send) pins.
transmitted. Example: The USART_CR3 register can be used to
11) To transfer the next character, go to step 9. enable the DMA mode for both transmission and
Q. 6 Enlist various registers required to reception by setting the DMAT and DMAR bits.
configure serial communication of STM32F4XX 4. **USART/UART Baud Rate Register
Microcontroller. Explain any two registers with (USARTx_BRR):** This register is used to set the
suitable example. baud rate for USART/UART communication. The
baud rate determines the rate at which data is data to be transmitted or received through the
transmitted and received. Example: The peripheral. Reading from or writing to these
USART_BRR register can be configured to set the registers allows you to transfer data between the
baud rate by writing the appropriate value microcontroller and the peripheral.
calculated based on the desired baud rate and 4. **Configuration Registers (CFGR):**
the system clock frequency. Configuration registers store various
- Example usage: To configure the baud rate to configuration parameters or settings related to a
115200, assuming the system clock frequency is peripheral or a specific feature. These registers
16 MHz, you can calculate and set the value in allow you to customize the behavior, timing, and
the BRR register as follows: other characteristics of the peripheral or feature
code ```c according to your specific requirements.
uint32_t baudRate = 115200; 5. **Interrupt Registers (IR):** Interrupt
uint32_t systemClock = 16000000; registers are used to configure and control the
uint32_t baudRateDivisor = (systemClock + interrupts associated with a peripheral. They
(baudRate / 2 )) / baudRate; often contain interrupt enable/disable bits,
USARTx->BRR = baudRateDivisor; interrupt status flags, and priority settings.
``` Reading from or writing to these registers allows
5.**USART/UART Data Register you to handle interrupts generated by the
(USARTx_DR):** This register is used to read or peripheral. 6. **Address Registers (AR):**
write data during USART/UART communication. Address registers are used in certain peripherals
When writing, data is transmitted through the that require memory-mapped access or
USART/UART interface, and when reading, addressing, such as DMA controllers. These
received data is read from this register. Example: registers hold the memory addresses or pointers
The USART_DR register can be used to write data used for data transfer between the peripheral
to be transmitted by assigning the data value to and the memory. 7. **Prescaler Registers
this register. (PSR):** Prescaler registers are used in some
Q.7 Write note on a different types of registers peripherals, like timers or ADCs, to divide the
of STM32F4XX. clock frequency before it is used for specific
1. **Control Registers (CR):** Control registers operations. These registers allow you to adjust
are used to configure and control the overall the clock frequency and thus control the timing
behavior of a peripheral or a specific feature or performance of the corresponding peripheral.
within it. They typically provide control bits or Q.8 How to program UART in the STM32F4xx
flags to enable/disable features, set operational microcontroller
modes, and configure other parameters. 1. **Peripheral Clock Configuration:** Enable
2. **Status Registers (SR):** Status registers the clock for the UART peripheral you intend to
provide information about the current status or use. For example, to use USART1, you need to
condition of a peripheral or a specific feature. enable the USART1 clock by configuring the
They often contain flags or bits that indicate the corresponding RCC register. 2. **GPIO
occurrence of specific events, errors, or Configuration:** Configure the GPIO pins for
conditions. Reading these registers allows you to UART communication. You need to configure the
monitor the status of the corresponding UART's TX (transmit) and RX (receive) pins as
peripheral or feature. 3. **Data Registers alternate function mode and select the
(DR):** Data registers are used for data transfer appropriate alternate function for each pin.
or storage within a peripheral. They hold the
3. **UART Configuration:** Configure the channel(s) to connect to the analog signal
UART peripheral by setting the desired source. - Set up any necessary GPIO pins for the
parameters such as baud rate, data bits, parity, ADC input channel(s) and configure them as
and stop bits. The configuration is done by analog inputs. - Enable the ADC and start the
modifying the registers of the UART peripheral. conversion process. - Read the converted digital
4. **Enable UART and values from the ADC's data register. - Process the
Transmission/Reception:** Enable the UART digital values to generate the desired waveform
transmitter and/or receiver by setting the or perform any required calculations. The
appropriate bits in the UART's control registers. specific configuration and usage of the ADC
This enables the UART to start transmitting depend on the STM32F4xx microcontroller
and/or receiving data. variant and the specific ADC module being used.
5. **Data Transmission:** To transmit data via It's important to consult the microcontroller's
UART, you can use the UART's data register (DR) reference manual and datasheet for detailed
to write the data to be transmitted. You can information on configuring and using the ADC, as
either use blocking or non-blocking methods to well as the available features and limitations.
transmit data. In blocking mode, you wait until 2. **On-Chip DAC (Digital-to-Analog
the transmission is complete before proceeding Converter):** The DAC allows you to convert
with the next data. In non-blocking mode, you digital values into analog signals. To generate
can use interrupts or polling to check the waveforms using the DAC, you can follow these
transmission status. 6. **Data Reception:** To steps: - Configure the DAC peripheral by setting
receive data via UART, you can read the UART's the output voltage range, trigger source, and
data register (DR) to obtain the received data. conversion mode. - Set up any necessary GPIO
Similar to transmission, you can use blocking or pins for the DAC output and configure them as
non-blocking methods for receiving data. In analog outputs. - Enable the DAC and start the
blocking mode, you wait until data is available in conversion process by writing digital values to
the receive buffer before reading it. In non- the DAC's data register. - The DAC will convert
blocking mode, you can use interrupts or polling the digital values into analog voltages that can be
to check for received data. 7. **Interrupt used to generate waveforms. - Adjust the digital
Handling:** If you are using interrupts for UART, values being written to the DAC to generate
you need to configure the NVIC (Nested Vector different amplitudes or wave shapes. - Use
Interrupt Controller) to handle UART interrupts. timers or software delays to control the timing
Implement the corresponding interrupt handler and frequency of the generated waveform.
function to process UART interrupts and handle Q.10 Timers in STM32F4xx
data transmission and reception. 1. **General-Purpose Timers (TIM2-TIM5):**
Q.9 on chip ADC and Onchip DAC for waveform These timers are versatile and can be used for a
generation. wide range of applications. They feature multiple
1. **On-Chip ADC (Analog-to-Digital channels for generating PWM signals, capturing
Converter):** The ADC allows you to convert input signals, or generating output waveforms.
analog signals into digital values that can be They also support various operating modes, such
processed by the microcontroller. To generate as up-counting, down-counting, or center-
waveforms using the ADC, you can follow these aligned counting. These timers are suitable for
steps: - Configure the ADC peripheral by setting general-purpose timing applications.
the resolution, sampling rate, and conversion 2. **Advanced-Control Timers (TIM1 and
mode. - Select the appropriate ADC input TIM8):** These timers provide additional
features compared to the general-purpose features such as velocity measurement and
timers. They include advanced control features position capture.
such as advanced PWM generation, Q.12 features of GPIO
synchronization, and complementary PWM • Up to 16 I/Os under control • Output states:
outputs. These timers are suitable for motor push-pull or open drain + pull-up/down • Output
control, power conversion, or any application data from output data register (GPIOx_ODR) or
that requires advanced timing control. peripheral (alternate functionoutput) • Speed
3. **Basic Timers (TIM6 and TIM7):** These selection for each I/O • Input states: floating,
timers are simple 16-bit timers that can be used pull-up/down • Input data to input data register
for basic timing or periodic interrupt generation. (GPIOx_IDR) or peripheral (alternate
They are particularly useful for generating functioninput) • Bit set and reset register
interrupts at fixed time intervals without (GPIOx_BSRR) for bitwise write access to
complex configurations. 4. **Low-Power Timers GPIOx_ODR • Each I/O port bit is freely
(TIM9-TIM14):** These timers are low-power, programmable
16-bit timers designed for power-constrained Q.13 Write the two common methods for timer
applications. They offer basic timing and event and delay generation in the STM32F4xx
counting functionality and are often used for microcontroller
low-power applications or for generating simple 1. **Timer Interrupt Method:** - Configure the
periodic interrupts. desired timer peripheral in the appropriate
Q.11 counters in STM32F4xx mode (e.g., one-shot or periodic). - Set the
1. **General-Purpose Timers (TIM2-TIM5):** desired timer prescaler and period values to
These timers can function as counters in addition achieve the desired timing interval. - Enable the
to their timer capabilities. They can count timer interrupt. - Implement the timer interrupt
external events or input pulses and provide a handler function, which will be executed when
flexible solution for measuring frequency, the timer reaches the desired period. - In the
period, or pulse width. These timers offer interrupt handler, perform the required actions
multiple capture/compare channels to capture or set flags to indicate that the desired delay or
input events and can generate interrupts upon timing interval has elapsed. - Start the timer by
specific counting conditions. 2. **External enabling the timer peripheral. - The
Interrupt Event Controller (EXTI):** The EXTI microcontroller will automatically generate an
module allows for external event counting. It is interrupt when the timer reaches the
primarily used to handle external interrupts from programmed period, allowing you to execute
GPIO pins, but it can also be configured as a code or perform actions at the desired timing
counter to count external events. The EXTI interval.
module provides linebased counting, where 2. **Busy-Wait/Delay Method:** - Configure
each line can be individually enabled and the desired timer peripheral in the appropriate
configured for rising edge, falling edge, or both mode (e.g., one-shot). - Set the desired timer
edge detection. 3. **Quadrature Encoder prescaler and period values to achieve the
Interface (QEI):** The QEI module is specifically desired delay duration. - Start the timer by
designed for decoding rotary encoders. It can enabling the timer peripheral. - Implement a
count the number of pulses generated by an busy-wait loop or use the microcontroller's delay
encoder and determine the direction of rotation. function to continuously check the timer status
The QEI module supports both incremental and until the timer reaches the desired period. - Once
absolute encoders and provides advanced the timer reaches the programmed period, the
microcontroller will exit the busywait loop, Block dig of DAC
indicating that the desired delay has elapsed. -
Perform the required actions or proceed with
the code execution after the delay has
completed.
Q.14 Enlist the features of on chip ADC of
STM32F4xx controller.
• The 12-bit ADC is a successive approximation
analog-to-digital converter. • It has up to 18
multiplexed channels allowing it to measure
signals from 16 external sources, two internal
The DAC integrates two output buffers that can
sources. • 12-bit, 10-bit, 8-bit or 6-bit
be used to reduce the output impedance, and to
configurable resolution • Single and continuous
drive external loads directly without having to
conversion modes • Interrupt generation at the
add an external operational amplifier.
end of conversion • The STM32F4xxArm chip has
Vref should be at 1.8 V ≤ VREF+ ≤ VDDA
three on-chip ADC modules: theADCs are
The output voltage from the DAC can be
designated asADC1 (master),ADC2 (slave) and
calculated using the following formula
ADC3 (slave).
Q.15 Algorithm FOR Configuring ADC and
reading ADC channel
1. Enable ADC clock to ADC in DAC REGISTER
RCC_APB2ENRregister. 2.Configure ADC right 1.DAC_CR (DAC Control Register): The most
adjusted result (ALIGN), free running conversion important bit in DAC_CR is the enable bit. Bit 0
(CONT, continuous conversion)using ADC_CR2 EN1: DAC channel1 enable ; where 0: DAC
register. 3. Using ADC_CR1 register, select the channel1 disabled, 1: DAC channel1 enabled Bit
resolution and the analog input channel. 4. Use 1 BOFF1: DAC channel1 output buffer disable
GPIOx_MODER register to configure input pin for Bits 5:3 TSEL1[2:0]: DAC channel1 trigger
analog input channel. 5. Using ADC_CR2 register selection
Enable the ADC (ADON) and START (SWSTART) to 2. DAC Data Holding Registers (DAC_DHR):
start theconversion. 6. Monitor the EOC flag in • There are 8 registers according to Data Holding
the ADC_SR register forend-of-conversion. 7. Position • For eg: - DAC channel1 12-bit right-
When the EOC flag goes HIGH, read the ADC data aligned data holding register (DAC_DHR12R1)
result from theADC_DR register and save it. 8. • DAC channel1 12-bit left aligned data holding
Repeat steps 6 through 7 for the next conversion register (DAC_DHR12L1)• Writing new data into
Q.16 Features of DAC DAC holing register starts a conversion. • Data
• Two DAC converters: one output channel each stored in the DAC_DHRx register are
as DAC1 and DAC2. • They are available at the automatically transferred to the Data Output
analog out pins “PA4 and PA5” for chan1 and registers (DAC_DOR) register after one clock
chan2 • Left or right data alignment in 12-bit cycle.
mode • Synchronized update capability • Noise- 3. DAC- Data Output registers
wave generation • Triangular-wave generation • (DAC_DOR)register
Dual DAC channel for independent or • Data stored in the DAC_DHRx register are
simultaneous conversions • DMA capability for automatically transferred to the Data Output
each channel • DMA underrun error detection. registers (DAC_DOR) register after one clock
cycle. • The Digital inputs are converted to 3. Write the characters "NUMBER" to the UART
output voltages on a linear conversion between transmit buffer.
0 and VREF+ 4. Start the UART transmit.
5. Wait for the UART transmit to complete.
Q.17 What are different SFRs related with GPIO. 6. Close the UART.
The STM32F4XX microcontroller has a number of
special function registers (SFRs) that are related
to the GPIO (General-Purpose Input/Output)
peripheral. These SFRs are used to configure the
GPIO pins, read and write data to the GPIO pins,
and control the GPIO interrupts.
GPIOx_MODER: This SFR is used to configure the
mode of the GPIO pins. The mode of a GPIO pin
can be set to input, output, alternate function, or
analog input.
GPIOx_OTYPER: This SFR is used to configure the
output type of the GPIO pins. The output type of
a GPIO pin can be set to push-pull or open-drain.
GPIOx_OSPEEDR: This SFR is used to configure
the output speed of the GPIO pins. The output
speed of a GPIO pin can be set to low speed,
medium speed, or high speed.
GPIOx_PUPDR: This SFR is used to configure the
pull-up/pull-down resistor of the GPIO pins. The
pull-up/pull-down resistor of a GPIO pin can be
set to pull-up, pull-down, or no pull-up/pull-
down.
GPIOx_IDR: This SFR is used to read the input
data of the GPIO pins.
GPIOx_ODR: This SFR is used to write data to the
output pins.
GPIOx_AFR[0:1]: These SFRs are used to
configure the alternate function of the GPIO
pins. The alternate function of a GPIO pin can be
set to a variety of peripherals, such as UART, SPI,
I2C, and CAN.
GPIOx_BSRR: This SFR is used to clear the output
data of the GPIO pins.

Q.18 Write algorithm/flowchart to transmit


serially. ‘NUMBER’ on hyper terminal using
UART of STM32F4xx.
1. Initialize the UART peripheral.
2. Set the baudrate of the UART to 9600.
UNIT – 6 Building automation: CAN bus is used in building
Q.1 Advantages & Disadvantages of ultrasonic automation to communicate between sensors,
proximity sensor actuators, and controllers.
ADVANTAGES- 1) Ultrasonic proximity sensors Transportation: CAN bus is used in
are not affected by atmospheric dust, snow, transportation systems, such as trains and buses,
rain..etc 2) Can work in adverse conditions to communicate between different components.
3)Sensing distance is more compared to Features of CAN-
inductive or capacitive proximity sensors. 4) Can 1)11 or 29 bit ID and from zero to 8 data bytes.
measure distance to objects in all weather These attributes can be dynamically changed “on
conditions. 5) Can measure distance to objects the fly”. 2. Peer to Peer network. Every node can
over a wide range. 6) Ultrasonic sensors are see all messages from all other nodes but it
relatively inexpensive. normally can’t see its own. 3. Nodes are really
DISADVANTAGES1) Ultrasonic sensors Has easy to add. Just attach one to the network with
More Difficulties Reading Reflections From Soft, two wires plus a ground. 4. Higher priority
Curved, Thin Or Small Objects. 2) Ultrasonic messages are sent. The lower ID has a higher
sensors can be affected by noise. 3)Ultrasonic priority. 5. Automatic retransmission of
sensors can be slow to respond. 4)Not suitable defective frames. A node will “bus-off” if it
for measuring distance to transparent objects. causes too many errors. 6. Speeds from
Q.2 Explain CAN bus & its application. approximately 10 Kbps to 1 Mbps. TIP:All nodes
CAN is a communication protocol that connects must operate at the same frequency.
all devices can communicate with each other. The CAN Frame—
CAN stands for ControllerArea Network. This The CAN frame has many fields but we can
technology developed by Bosch Automotive simplify this to a Programming Model as shown.
company to reduce cabling loads and make These fields are accessed by your software
systems separates from each other. Because if through the CAN controller registers. The
there is a problem in any sensor, this problem configuration registers are not included here. 
will harm all system. The development of CAN IDE: Identifier Extension: 1 bit - specifies if the ID
began when more and more electronic devices field to be transmitted is 11 or 29 bits:  If IDE =
were implemented into modern motor vehicles. 0, then the ID is 11 bits. If IDE = 1, then the ID is
Examples include engine management 29 bits  ID: Identifier: 11 or 29 bits as set by the
systems, ABS, gear control, lighting control, air IDE field. This part of the CAN frame sets the
conditioning, and airbags. All this means more priority.  DLC: Data Length Code: 4 bits -
safety and more comfort. This was usually done specifies number of data bytes in the frame from
by point to point wiring. The requirement is that 0 through 8.  Data Bytes: 0 through 8 bytes
a cable network with a length of up to several
miles. High speed, real-time communication,
Error detecting mechanism and retransmission
of faulty massages.
APPLICATIONS –
Automotive: CAN bus is used in most modern
vehicles to communicate between electronic
control units (ECUs).
Industrial automation: CAN bus is used in
industrial automation to communicate between
sensors, actuators, and controllers. SOF – Start of Frame, Identifier – Tells the
Medical devices: CAN bus is used in medical content of message and priority, RTR – Remote
devices to communicate between different Transmission Request, DLC – Data Length Code,
components. CRC – “Cyclic Redundant Check” sum, IDE –
Identifier extension, Data – holds up to 8 bytes measure Tilt Angle using MPU6050 &
of data, ACK –Acknowledge, EOF – End of STM32F4XX Microcontroller by simply
Frame, IFS –intermission Frame Space. interfacing MPU6050 6 axis Gyro/Accelerometer
The sequence of transmitting and receiving a Sensor with STM32. • The Accelerometer sends
character on CAN bus : X, Y, and Z acceleration forces. We need to
1)The sender node prepares the message to be convert the forces into X, Y, Z 3D angle to
sent. This includes setting the message header determine the 3D Orientation of the sensor. •
and the data payload. 2)The sender node The gyroscope measures rotational velocity or
transmits the message on the bus. 3)All nodes on rate of change of the angular position over time,
the bus receive the message. 4)The receiver along the X, Y and Z-axis. The sensor uses the I2C-
node checks the message header to see if it is bus to interface with the STM32F4XX
intended for it. 5)If the message is intended for Microcontroller.
the receiver node, it decodes the data payload. Algorithm for interfacing MPU 6050
5) The receiver node acknowledges the message 1.Include Header files. 2. Configure System Clock
to the sender node. 3. Initialize SPI Bus SFR Registers. 4. Initialize/
Q.3 Draw and Explain interfacing diagram of Configure GPIO Pins. 5. Read the X, Y and Z
STM32F4XX with accelerometer MPU 6050. parameters from MPU 6050. 6. Display it in
variable or Serial Terminal.
Q.4 Draw and explain an interfacing of
STM32F4xx with Ultrasonic Sensor HC-SR04.

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
To interface an ultrasonic sensor, the HC-SR04
movement. • Gyroscopes can produce a better
with the CortexM4 based micro-controller, we
estimate of orientation than obtained using
are reading and writing individual bits of some
accelerometer data alone. • Digital
registers present on the micro-controller known
accelerometers give information using a serial
as Special Function Registers (SFRs). Now, these
protocol like I2C , SPI or USART.
acoustic bursts sent out by the transmitter of the
MPU-6050 • The MPU 6050 is the world’s first
sensor module travel at the rate of 340m/s in air.
integrated 6- axis Motion Tracking device • It
To calculate the distance we will be using simple,
combines a 3-axis gyroscope, 3-axis
Distance = Speed x Time formula
accelerometer, and a Digital Motion Processor™
In this formula, the time taken by the receiver to
(DMP) all in a small 4x4x0.9mm package. • It uses
receive the signal back is divided by 2, since the
a standard I2C bus for data transmission. – With
total time includes the time required by the
it’s I2C bus, it can accepts inputs from an
signal to travel both to and back from the object.
external 3-axis compass to provide a complete 9-
Clock default. on the STM32F407 runs on a
axis Motion Fusion output. • The objective is to
frequency of 16MHz by So, time is given as
0.0625 micro-seconds which is 1/16MHz. Finally, PWM signal.  First, we have to setting the timer
the distance in cm can be calculated by, on STM32F4. We will use TIM4 because the
Time = ((Clock Cycles x 0.0625 x 0.000001)/2) output channel (TIM4_CH1) is connected to
Distance = (340*100)xTime PD12 (green LED) that we want to control the
Algorithm for interfacing HCSR 04 brightness.
1.Include Header files. 2. Configure System Clock Q.5 Explain how PWM of STM32F4xx used to
3. Initialize Timers through SFR Registers. 4. control the diretion of DC motor.
Initialize/ Configure GPIO Pins. 5. Send the PWM (Pulse Width Modulation) can be used to
trigger pulse. 6. Wait for echo pulse. 7. Calculate control the direction of a DC motor by changing
from time and formula. 8. Display it in variable or the polarity of the PWM signal. The polarity of
Serial Terminal. the PWM signal refers to whether the signal is
Q.5 Explain how PWM of STM32F4xx used to positive or negative. A positive polarity signal will
control the speed of DC motor. cause the motor to rotate in one direction, and a
 PWM signal is a modulated digital logic (0 and negative polarity signal will cause the motor to
1). PWM signal have a duty cycle. Duty cycle is rotate in the opposite direction.
measured in percentage.  PWM signal that has To control the direction of a DC motor using
100% duty cycle would be the same as setting to PWM
fully on. 0% duty cycle would be the same as Configure the PWM peripheral to generate a
ground. Duty cycle in between 0% and 100% are square wave signal with a variable duty cycle.
illustrated on these graphics Connect the PWM output to the motor.
Reverse the polarity of the PWM signal to change
the direction of the motor.
Q.6 Write an algorithm to rotate the motor in
clockwise direction using PWM of STM32F4xx.
1. START
2. Initialize the PWM peripheral.
3. Set the PWM frequency to 100 Hz.
4. Set the PWM duty cycle to 50%.
 PWM (Pulse Width Modulation) is a technique 5. Connect the PWM output to the motor.
for generating analog voltage (average value) by 6. Start the PWM signal.
using microcontroller's digital outputs. PWM is 7. Wait for 5 seconds.
used in DC motor speed control, servo motor 8. Stop the PWM signal.
control, dimming LED, audio generation and 9. END
many more. Q.7 Write an algorithm to rotate the motor in
Anticlockwise direction using PWM of
STM32F4xx.
1. START
2. Initialize the PWM peripheral.
3. Set the PWM frequency to 100 Hz.
4. Set the PWM duty cycle to 50%.
5. Reverse the polarity of the PWM signal.
6. Start the PWM signal.
7. Wait for 5 seconds.
To generate PWM with STM32F4, we can use 8. Stop the PWM signal.
timer.  Timer can count from 0 to a given value 9. END
and triggering some events.  When the timer Q.8 Explain MPU 6050
counter reach 0, max, or compared value, the • The MPU 6050 is the world’s first integrated 6-
output channel value can be changed to create a axis Motion Tracking device • It combines a 3-
axis gyroscope, 3-axis accelerometer, and a As shown in the timing diagram, , we will need to
Digital Motion Processor™ (DMP) all in a small send a 10-microsecond pulse to the Trig pin of
4x4x0.9mm package. • It uses a standard I2C bus the sensor and detect the pulse width of the
for data transmission. – With it’s I2C bus, it can pulse sent from the Echo pin of the module.
accepts inputs from an external 3-axis compass Firstly to generate a pulse we will set PA5 low
to provide a complete 9-axis Motion Fusion for some time and then set it to high for the
output. desired duration of pulse which happens to be
• The objective is to measure Tilt Angle using 10 microseconds in this case and then set to PA5
MPU6050 & STM32F4XX Microcontroller by low again. Next, to detect the pulse coming in
simply interfacing MPU6050 6 axis from the Echo pin, we will configure PA6 as an
Gyro/Accelerometer Sensor with STM32. • The input pin and continuously monitor it for the
Accelerometer sends X, Y, and Z acceleration duration of time it remains high.
forces. We need to convert the forces into X, Y, Z Q.11 Network Topology of CAN
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.
• 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  CAN is a broadcast system. Any node can
, orientation, displacement and many other “broadcast” a message using a CAN frame on a
motion related parameters of a system or object. bus. Multiple controllers tend to start their
Q.9 The Pinout of MPU 6050 messages at the same time.  Every node will
INT: Interrupt digital output pin. AD0: I2C Slave see this message. A “message” can be
Address LSB pin. This is 0th bit in 7-bit slave considered the same as a CAN frame until you
address of device. XCL: Auxiliary Serial Clock pin. need to use more than one frame to send a long
used to connect other I2C interface XDA: message
Auxiliary Serial Data pin. SCL: Serial Clock pin.  This transceiver IC1 connects to the STM32
Connect this pin to controllers SCL pin. SDA: microprocessor IC2 which contains an integral
Serial Data pin. Connect this pin to controllers CAN controller via two pins: D (Driver input) and
SDA pin. GND: Ground pin. Connect this pin t R (Receiver output).  The corresponding
9oground connection. nomenclature on the STM32 is CAN Rx and CAN
Q.10 pin configruration of HCSR 04 Tx. CAN Tx connects to D. CAN Rx connects to R.
Compare ARM Cortex A, M and R
Parameters Cortex A Cortex R Cortex M
Performance Highest Very good Medium
Response time Very good Best Medium
Power Consumption 80µW/MHz 120µW/MHz 8µW/MHz
Processor Application based RTOS based Embedded system
based
Pipeline Long pipeline Medium pipeline Short pipeline
Clock High High Less Relative
Memory Cache memory with Cache memory + Cache memory with
more size tightly coupled less size
memory
ISA ARM ARM Thumb

Compare ARM cortex M3 with ARM7TDMI.


Parameters ARM7TDMI cortex M3
Architecture ARMv4T (von Neumann) ARMv7 –M (Hardvard)
ISA support Thumb / ARM Thumb
Pipeline 3 - stage 3 – stage + branch
speculation
Interrupts FIQ / IRQ NIM + 1 to 240 physical
interrupts
Interrupt latency 24 – 42 cycles 12 cycles
Sleep modes None Integrated
Memory protection None 8 region memory protection
unit
Dhrystone 0.95 DMIPS / MHz 1.25 DMIPS / MHz
Power consumption 0.28 mW/MHz 0.86 mW/MHz

Compare ARM Cortex M3 with ARM cortex M4 and M0


Parameters Cortex M0 Cortex M3 cortex M4
Architecture version V6M V7M V7ME
Bus interface 1 3 3
DMIPS/ MHz 0.9 1.25 1.25
Maximum no. of 32 240 480
interrupts
Power consumption Low Moderate High
Cost Low Moderate High
Floating point unit No Optional optional
(FPU)
Clock speed Up to 48 MHz Up to 120 MHz Up to 168 MHz
block diagram of STM32F4xx

You might also like