Embedded MCU's Getting Started and Peripheral Coding STM32 MCU's

Table of Contents

Overview

Okay so hello guys and hope u are doing great; in the last 2 Blogs we get to know about Debug Trace Features in Embedded Systems and about ARM CoreSight Architecture for Debug and Trace in ARM based SoC/MCU.

Now, in this Blog we will implement the theoretical knowledge of previous blogs to action and do them practically! We will do so by exploring the Trace Features in STM32MCU practically (STM32F103 Blue pill) using STLINKv2-B ( Official one white one) in STM32CubeIDE. 

This Topic has been divided into 2 Blogs.

In this Blog Hardware connections between STLINKv2-STM32MCU  and Code Generation is explained. The Video For that is also Uploaded on Gettobyte YouTube channel here.

In next Blog How to use Trace Features using SWV is explained. The Video for that too is Uploaded on Gettobyte YouTube Channel here.

Intro on STLINKv2 Programmers and Debuggers

Now STLINKv2 which you can see in the above image is different from USB based STLINKv2 Programmer and debugger( Chinese clone one). It is different in terms of more features and JTAG support for Debugging the Firmware’s. 

Original STLINKv2 can be used for Programming and Debugging Both STM8 and STM32 MCU. For STM8 it uses SWIM Protocol and for STM32 it has SWD, JTAG Communication Protocol and SWO pin for trace features.

In USB based STLINKv2 Programmer Chinese cloned one also both STM8 and STM32 MCU can be programmed and debugged. For STM8 it also uses SWI Protocol but for STM32 MCU it has only SWD Protocol and pins available.

For using the trace features, In USB based Chinese cloned one STLINKv2 (which is relatively cheaper than above STLINKv2) we must solder the 5V pin of Programmer by one of the pins of the onboard pin of the MCU used in Programmer. And it is a kind of long and Cumbersome Process. 

But in Official STLINKv2 which is shown in above pic, we do not have to solder any of the pins for using Trace Features, The Programmer has Pinout and dedicated pins for using Trace feature using (SWD + SWO pins) and it has JTAG Dedicated pins too for Doing Debugging .

Now as given u some comparisons between Official and Unofficial STLINKv2 Programmer and Debugger let us dive into some Practical Part. In the rest of the doc,  STLINKv2 programmer and Debugger will signify the Official white in one derivative which is shown in above pic.

Hardware Connections for STLINKv2 and MCU

The STLINKv2 Programmer comes in with following things as u open its Box.

  • Main STLINKv2 Programmer and Debugger
  •  
  • 20 Pin JTAG connector
  • USB 2.0 A to USB 2.0 Mini B
  • 2 x Connecting Cable for STM8 SWIM

Now coming to the pain Connections for connecting STM32 MCU with STLINKv2.
Programmer has the following pins for connecting it to STM32 MCU(Blue Circle).

These Pins have Pinout like these:

STLINKV2 Pinout

Right side from the Embarked Area (Orange Color), is pin 1 of the Programmer and then the pinout goes as shown in above pic.

Now the Essential Pins out of these 20 pins of the STLINKv2 programmer to Program and Debug STM32 MCU using ARM Proprietary SWD Protocol are only 5 pins.

  • SWIO/TMS(Pin 7) à SWD PIN
  • SWCLK/TCK(Pin 9) à SWD PIN
  • TDO/SWO(Pin 13) à SWO PIN
  • STM32 RESET(Pin 15) à RESET PIN
  • VCC(Pin1&2) à POWER PIN
  • GND(Below Horizontal line’s any pin can be used as GND except 2) à POWER PIN
STLINKV2 Connection for STM32

SWD Pins of STM32 MCU will be connected to SWD PIN if we want to only use Debugging features alongside Programming the Microcontroller. Like as shown in PIC. 

Now for Using the Trace Features we must connect one additional Pin from the Programmer to OUR Microcontroller and that is SWO Pin (13th pin) of Programmer to the Respective Trace SWO Pin Of our STM32 Microcontroller.

In STM32F103 SWO PIN is PB3 as shown in this schematic.

So, for Using Trace Features Connections will be like this.

SWO Connection for STM32

To be noted down:

  • Any pin from the below horizontal line except the VCC pin of that line can be taken as GND pin when using SWD/SWD+SWO pins and can be connected to GND pin of our STM32 MCU.
  •  Sometimes or in some Programmers we have to short all the VCC pins by Jumper wire for Proper connections or encase device isn’t able to power up MCU or Program it.
  •  In some cases, VCC pins 1&2 can be wrongly mapped in Some Programmer, and they can be at left hand side of the programmer that is at pins 19 and 20. So in case MCU does not Power up by above connections, then do not panic just change the VCC Pins and it might work out. ( This is in my case, so below pitcher is according to that)

Now so after successful Connections between STLINKv2 and STM32 MCU, Connect the USB cable between STLINKv2 and Laptop and LED light on the programmer will lighten up in RED color.

         Figure 5 (These are the Final Connections For SWD+SWO)

Software Part used

Now I will be Showing STM32CubeProgrammer and STM32Cube IDE In this blog in software part.

First with STM32CubeProgarmmer:

As u connect your STLINKv2 Programmer to your computer, IN STM32CubeProgrammer u will see the Serial Number of Programmer if all goes well. As shown in Pic.

Figure 6

Now as u click on Connect Button by selecting STLINK, u will see all the details of Your respective MCU details and showing its memory Content. (In doing so Your programmer will start blinking in red, green color and Screen of STM32CubeProgrammer might take 1-2 secs of time for showing Memory contents and MCU details.)

Figure 7

This is just Demonstration of Successful connections of STLINKv2 and MCU for SWO+SWO pins and established Communication between Programmer and Laptop via STM32Cube Programmer.

As if now, we have not used the trace features, for using that we must create a project and Upload in MCU by things mentioned in below section.

For STM32CubeIDE also follow the below section

If any Error comes in while connecting the STLINKV2 , FOLLOW  this video for solving all kinds of Errors and to get Solutions for them.

Code for using Trace Features in STM32 MCU

Create a New Project in STM32CubeIDE by choosing your corresponding Workspace (Figure 1), select Your MCU in Board Configuration Window (Figure2) by selecting the MCU you are using.

Figure 8

\"\"

Figure 9

Now name Your Project in next window and choose the targeted language according to your choice and Select Executable in Targeted Binary Type.

In Target Project type their will be 2 Options,

STM32Cube and Empty.

(In this Blog I will be telling things according to STM32cube project type. By selecting STM32Cube, Auto generated code STM 32 HAL initializes all the Processor registers for using Debug and Trace features according to the configurations made in STM32CubeMX window.)

Now in Cube MX configuration window we must Select RCC Mode for HSE as Crystal/Ceramic Resonator and Debug Mode as Serial Wire,

Under Pinout and Configuration window select the System Core and in it Select the RCC and SYS. Select the corresponding Options as shown in pics below.


Figure 10

And then in the clock Configuration window Select the Clock Frequency according to your choice. I am selecting 32Mhz in my case for STM32F103 using HSE (which has input frequency of 8 MHz and selecting PLL as clock Source for System clock).

I am configuring the Onboard LED on STM32F103 Blue Pill as GPIO OUTPUT just for demonstration purpose. That is pin PC13.

Figure 11

And then save the file and Autogenerated code Process using STM32HAL will be started.

Figure 12

Now open the main.c file of Your project from the Project explorer window.

Figure 13

That is all for this Blog, second part of the Topic is in next Blog.

Follow the next Part for NEXT Part of the blog.

Playlist for Debugging techniques in Firmware development: https://www.youtube.com/playlist?list=PLb_Q-Ps0nJou2Ped93q02JRfiMCJorLYX

Previous and Next Blog

Other blogs to explore

UART Peripheral in S32K144

Introduction –> UART Peripheral is one of the most common communication modules present in every series of microcontrollers. For Crisp and Short UART understanding as a concept, redirect yourself to this BLOG, it might take a couple of minutes to have an overlayed understanding. Now, UART is used in GPS modules or other wireless modules like Bluetooth and WiFi. GPS Modules- Use UART to exchange NMEA strings for positioning data. Bluetooth (e.g., HC-05)- Employs UART for wireless data transfer and pairing. Wi-Fi Modules (e.g., ESP8266, ESP32)- Use UART for sending AT commands and receiving responses. –> In S32K144, we’ll be referring to the UART as LPUART because the UART supported in S32K144 is a low-power UART called LPUART(Low Power Universal Asynchronous Receiver/Transmitter). –> NOTE: A single instance of UART contains a pair of a TX pin and an RX pin.  –> Below are mentioned table of LPUART instances supported in different series with highlighted sections of our development board:  Features of UART > Full-Duplex, standard Non-Return-to-Zero (NRZ) format Full-duplex: Communication happens in both directions at the same time. One device can send data while receiving data simultaneously. Yes, as you might be thinking about Half-Duplex Communication and it also exists where the channel can either send or receive data, but not both at the same time. At the same time, there also exists a last type of this which you might not think, that is Simplex Communication where only one-way communication is possible.  Standard Non-Return-to-Zero (NRZ) Format: Data is represented as high (1) or low (0) voltage levels. Voltage doesn’t return to zero between bits, ensuring efficient use of the signal without gaps.  > Programmable baud rates (13-bit modulo divider) Baud Rate: The baud rate is the number of signal changes or symbols transmitted per second in a communication system. For example, a baud rate of 9600 means 9600 bits are sent every second. Baud Rate in LPUART: In LPUART, a 13-bit counter generates the baud rate by dividing the LPUART clock. The division factor is set using the BAUD[SBR] register, with values ranging from 1 to 8191. The baud rate generator is always active when the transmitter or receiver is enabled, and for the transmitter, each character aligns with the next edge of the transmit bit clock. This ensures continuous operation despite minor errors. But there’s a catch that you might see in development, our IDE only gives some preset group of baud rates like 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, and 921600, then “what is the use of this baud-rate generator?”. The generator’s role is to provide flexibility to derive these preset baud rates from the main LPUART clock. While only specific baud rates may be officially supported (due to hardware limits or design constraints), the generator’s configuration ensures these values can be accurately achieved by adjusting the divisor (SBR) and oversampling ratio (OSR), which improves accuracy by sampling each bit multiple times. We’ll be discussing the sampling technique in a further section.   > Transmission Functionality Now, we’ll be learning how characters are sent over LPUART where we’ll also learn different other features of LPUART. Below mentioned is the Block Diagram of LPUART Transmission: No need to worry by viewing this block diagram, after this go-through you’ll be able to teach others about this block diagram seamlessly.  Idle State and Configuration: The transmitter output (TXD) is idle at a logic high by default. To invert this behavior, set the CTRL[TXINV] bit. The transmitter is enabled by setting CTRL[TE], which queues a preamble (idle state) character. Data Transmission: Data is written to the transmit buffer via the DATA register. The transmit shift register (9–13 bits long based on configuration) sends a start bit, data bits, and a stop bit. In 8-bit mode, the shift register handles 1 start bit, 8 data bits, and 1 stop bit. Operation Flow: When the shift register is free, it fetches data from the transmit buffer and synchronizes it with the baud rate clock. The STAT[TDRE] flag is set, indicating readiness for new data. If no new data is available after sending the stop bit, the transmitter enters idle mode (TXD high). Disabling the Transmitter: Writing 0  CTRL[TE] doesn’t stop the transmitter immediately. Current activity (data, idle, or break character) must finish first. Sending Break and Queued Idle in LPUART(Feature offered by LPUART)–> Sending break and queued idle refers to transmitting a break character (a full character of logic 0) or an idle character (logic 1) to manage communication flow, often to signal the end of a message or to wake up sleeping receivers. These actions can be queued by setting control bits in the LPUART, ensuring proper synchronization and transmission. Break Characters: A break character forces the TX line to logic 0 for a full character time (9–12 bits, including start and stop bits). For a longer 13-bit break, set STAT[BRK13]. To send a break: Wait for STAT[TDRE] (Transmit Data Register Empty) to ensure the last character has been shifted out. Set CTRL[SBK] to 1, then clear it to 0. This queues a break for transmission. If CTRL[SBK] remains 1, additional break characters will be queued automatically. Break characters received on RX are detected as all 0s with a framing error (STAT[FE] = 1). Alternative Break Transmission: Writing to DATA with bit 13 set and all data bits cleared can send a break as part of the data stream. This method also works with DMA to transmit a break character. Idle Characters: An idle character (logic 1 for a full character time) can wake up sleeping receivers during idle-line wakeup. To send an idle character: Wait for STAT[TDRE]. Clear and then set CTRL[TE]. This queues an idle character. The transmitter holds TXD high until the queued idle is sent. Alternative Idle Transmission: Writing to DATA with bit 13 and all data bits set can send an idle character as part of the data stream. DMA can also be used for idle transmission. Control Bits for Break Length: The length of break characters depends

Read More »
ARM processors
Kunal Gupta

ARM Coresight: Debug and Trace in Embedded System

Table of Contents Definition of ARM CoreSight \”CoreSight is the Debug Architecture from ARM for Debugging and Trace Solutions in Complex SoC designs (Single core and Multi core)\” CoreSight Provides all the Infrastructure that is required to Debug, Trace, Monitor, and optimize the performance of a Complete System on Chip (SoC)Design. The Debug and Trace Features of the ARM Cortex M processors (M3/M4/M33/M7/M0, etc.) are designed based on the CoreSight Debug Architecture. This Architecture Covers a Wide Area Including Debug Interface protocols, on chip bus for debug access, Control of debug components, security features, trace data interface and more. Debug and Trace in Embedded Systems By now one obvious question to beginners or newbies that must have come in their mind is what is Debug and Trace. What are these features for which we have a whole complete Architecture called CoreSight? Why do we need Debug and Trace solutions in our Processors/Embedded Controllers? Is it not? For those readers They can check out this blog, providing you clarity and understanding of all such questions. One can Understand Debug and Trace Feature/Functionality as one of the Block/Unit of the Processor. Just like We have UART, SPI, I2C, etc. peripherals for our Microcontrollers for which we have separate Block, Architecture, Peripheral Memory Registers for accessing them and Communication Protocol pins in our Microcontroller. Same Way-out Debug/Trace is one of the peripherals which is present in our Processor for which it has its whole architecture and above Marked things. ARM Processor has CoreSight Architecture. MIPS Processor has EJTAG Architecture. IBM PowerPC processor has COP. (Units/Block of the Processor are not called peripherals, I have used the above term just to make u understand the analogy) What are Debug Features?? Features are used to observe or modify the state of parts of the design. This is also Called Invasive Debugging Execute instructions line by line function i.e., halting the processor after execution of each line of code(single stepping). Execute Instructions Function by function i.e., halting the processor after execution of each functions (Step Over) Return from the Function (Step Return/Step Out) Stop the processor (halting) Stop the Processor at a particular à line of code (called Breakpoint) àmemory address (Called Watchpoint) à coded condition of a variable or memory address is achieved (Conditional Breakpoint/Watchpoint) On can control the program execution (By points 1-5)so as to examine(Both read or Write) the change in value of bits of the MCU Peripheral registers and Core Processor Registers (like examining the contents of UART peripheral Registers to mark at which line of code data is received or transmitted by seeing the UART Status registers which has corresponding bits to indicate the event of receiving and transmit data). Debug frequently involves halting execution once a failure has been observed and collecting state information retrospectively to investigate the problem. There are 2 Communication Protocols For using Debug Features: SWD & JTAG JTAG is an industry Standard protocol (IEEE 1149.1) which is used for debugging and boundary scan testing. It is the de facto Serial Protocol which is present in almost every Processor Family other than ARM also like AVR 8 core, MIPS, PowerPC, etc. To be noted down: JTAG Requires 4 pins: TCK, TDI, TMS, TDO; the recent signal TRST is optional. ARM CoreSight Technology introduced the 2 wire Protocol SWD (Serial Wire Debug): SWCK and SWDIO which is used for Debugging all the ARM based Processors. The Serial Wire debug(SWD) protocol provides the same debug access features and supports parity error detection, which enables better reliability in systems with higher electrical noise. Therefore, the Serial Wire debug protocol is more favorable then JTAG Interface. Also, SWD and JTAG debug protocols share the same Connections: TCK and SWCL use the same pin, TMS and STDIO use the same pin.  The SWD port alone does not allow real-time tracing. What are Trace Features?? Trace refers to the process of capturing data that shows information about how the components in a design of a firmware are operating, executing, and performing. This is also Called Non-invasive Debugging. It is real-time (with a small timing delay) and can provide a lot of useful information without stopping the processor. Information like: Amount of execution time for each function(Statistical Profiling) Call hierarchy and execution time sequence of functions Event Execution timing(Timestamp) Clock cycles taken for execution of a particular Instruction. Examine or change the contents of the memory or peripherals at any time, even when the processor is running. This feature is often called on-the-fly memory access. Data Trace(Monitoring the Variable or Memory address in Real Time execution of Code  and Plotting their graph). Instruction Trace(information about Instruction execution of a Core)ETM & PTM). Instrumentation Trace (Printf () Statement via ITM). System trace Trace is an advanced version of Debugging as it analyzes the performance of our firmware code and how efficient it is in terms of memory and efficiency by capturing the various kinds of data when the CPU is running. For Trace features there are 2 Modes: 1 Serial-Pin model called Serial Wire Viewer à Using Serial Wire Output (SWO) with Serial Wire Debug (SWD) interface. The Serial Wire Output (SWO) pin can be used in combination with SWD. It is used by the processor to emit real-time trace data, thus extending the two SWD pins with a third pin. The combination of the two SWD pins and SWO pin enables Serial Wire Viewer (SWV) real-time tracing in compatible Arm® processors.  The Serial Wire Viewer (SWV) is a real-time trace technology that uses the Serial Wire Debug (SWD) port and the Serial Wire Output (SWO) pin. The Serial Wire Viewer provides advanced system analysis and real-time tracing without the need to halt the processor to extract the debug information. 2 Multi-pin Trace Port interface (4 data pins + 1 clock pin). For Capturing the Data There must be à  Source for generating the Trace data àSinks are the endpoints of trace data à Links provide Connection, triggering and flow of traced data between

Read More »

I2C Peripheral in STM32F103

Overview In this blog we will be discussing another special functionality of GPIO pins I2C or Inter-Integrated Circuit or I2c functionality . I2C is a two wire interface or TWI which was developed by the Philips corporation for use in consumer products . It is a bidirectional bus that can be easily implemented in an IC process.I2C combines best features of SPI as well as UART it lets the user control multiple slaves via multiple masters which is useful when logging data to sd cards or displaying on LCD. Just like SPI the output data bits are synchronized to sampling of the clock shared by both the parties involved in the communication . The master always generates the clock.The protocol finds applications in hardware sensors or displays , reading memory ICs , communicating with microcontrollers , ADC or DACs. I2C Theory I2C consists of 2 lines SCL and SDA  1.SCL (Serial Clock ) – For synchronizing data transfer between master and slave   2, SDA (Serial Data ) – The data transmission or receiving line Multiple Master and Slave lines are connected to the SDA and SCL lines and both these lines are pulled up using resistors to Vdd (5v) Operation Modes In I2C  Master Transmitter Master Receiver Slave Transmitter  Slave Receiver  I2C Clock Speed The speed of the I2C bus should be in reference to the one provided in the datasheet The modes of I2C clock speed are as follows:- Standard-mode : 100 KHZ max Fast-mode: 400 KHz max Fast-mode Plus:1MHz High-speed mode: 3.4 MHz I2C duty cycle specifies the ratio between Tlow and Thigh of the I2C SCL line The values being: I2C_DUTYCYCLE_2=2:1 I2C_DUTYCYCLE_16_9= 16:9  The desired clock speed can be achieved using the appropriate duty cycle to prescale How data is transmitted in I2C Protocol Transactions are initiated and completed by master All the messages have an address frame and data frame Data is placed on SDA when SCL goes low and is sampled after SCL goes HIGH All transactions begin with START and are terminated by STOP A START is defined when SDA goes low from high and SCL is still HIGH A STOP is define when SDA goes HIGH from LOW while SCL is still HIGH Both START and STOP conditions are generated by the master itself Both START and STOP conditions are generated by the master itself Any information on the SDA lines should be 8 Bits long. Each byte must be followed by Acknowledge(ACK) bit. Data is transferred with the MSB first The address frame is sent out first  The 7 bit address frame is sent out with the MSB first followed by R/W indicating a read(1) or write(0) operation. The data frame begins transmission after the address frame is sent The SCL will keep on generating clock pulses at regular interval and data will be placed at SDA at regular interval by either master or slave depending it is a write operation or read operation   I2C Features in STM32F103 Parallel-bus/I2C protocol converter   Multimaster capability: the same interface can act as Master or Slave     I 2C Master features:  – Clock generation  – Start and Stop generation   I 2C Slave features:  – Programmable I2C Address detection  – Dual Addressing Capability to acknowledge 2 slave addresses  – Stop bit detection   Generation and detection of 7-bit/10-bit addressing and General Call   Supports different communication speeds:  – Standard Speed (up to 100 kHz)  – Fast Speed (up to 400 kHz)  Analog noise filter   Status flags:  – Transmitter/Receiver mode flag – End-of-Byte transmission flag   Error flags:  – Arbitration lost condition for master mode  – Acknowledgment failure after address/ data transmission  – Detection of misplaced start or stop condition  – Overrun/Underrun if clock stretching is disabled   2 Interrupt vectors:  – 1 Interrupt for successful address/ data communication  – 1 Interrupt for error condition   Optional clock stretching  1-byte buffer with DMA capability   Configurable PEC (packet error checking) generation or verification:  – PEC value can be transmitted as last byte in Tx mode  – PEC error checking for last received byte SMBus 2.0 Compatibility:  – 25 ms clock low timeout delay  – 10 ms master cumulative clock low extend time  – 25 ms slave cumulative clock low extend time  – Hardware PEC generation/verification with ACK control  – Address Resolution Protocol (ARP) supported   PMBus Compatibility I2C Instances in STM32F103 The I2C instances vary from microcontroller to microcontroller i.e the stm32f103c676A has one I2c instance with stm32 f411 RE having I2C1 and I2C2 . The pins for I2C1 are  PB7 – This is used as SDA  PB6 – This is used as SCL The pins for I2C2 are:- PB3 – This is used as SDA PB10 – This is used as SCL I2C configuration Parameters in STM32F103 Clock Speed This parameter defines the clock speed which as mentioned previously can be 100000 in standard mode and 400000 fast mode. Duty cycle This parameter helps in configuring the HIGH and LOW ratio of the clock and has value 2:1 and 16:9 Ownaddress This parameter takes in the address of the first device which can be 7 bit or 10 bit long Addressing mode This parameter suggests the type of the address size being chosen which can be 7 bit or 10 bit Dualaddressing mode This parameter is used to disable or enable the dual addressing mode of I2C Generalcall addressing mode This parameter is used to disable or enable the general call addressing mode. NOstrech mode This parameters checks the nostrech mode Applications of I2C It is used to scan sensors such as – MPU6050 , BMP280 , PCA 9685 PWM controller, TSL2561 luminosity measurements ADXL345 3 axis accelerometer Ssoled display , 16 x 2 led display CAT24C512  EEPROM 64KB SSD1306 OLED Screen with STM32F103 GEsture sensor with STM32F103 Time of Flight Sensor with STM32F103 INA219 DC Current Sensor with STM32F103 How to configure the I2C peripheral in STM32F103 We would be using STM32 HAL and STM32CubeIDE for using the I2C peripheral in STM32F103 in this blog tutorial series. I2C BLOCK DIAGRAM I2C

Read More »
Kunal Gupta
Author: Kunal Gupta

Author

Kunal Gupta

Leave a comment

Stay Updated With Us

Error: Contact form not found.

      Blog