Key Knowledge Points for STM32 Embedded Interviews

I am Lao Wen, an embedded engineer who loves learning.

Answer:

Differences between STM32F1 and F4:
Different cores: F1 has Cortex-M3 core, F4 has Cortex-M4 core; Different main frequencies: F1 has 72MHz, F4 has 168MHz; Floating-point operations: F1 has no floating-point unit, F4 has one; Functional performance: F4 peripherals are richer and more powerful than F1, such as GPIO toggle rate, pull-up and pull-down resistor configuration, ADC precision, etc.; Memory size: F1 has a maximum of 64K internal SRAM, while F4 has 192K (112+64+16).

2. Describe the STM32 startup process.

Answer:

Set the Boot pin to find the initial address, initialize the stack pointer __initial_sp pointing to the reset program Reset_Handler, set the exception interrupt HardFault_Handler, set the system clock SystemInit, and call the C library function _main.

3. Describe GPIO.

Answer:

GPIO has 8 working modes (gpio_init.GPIO_Mode): (1) GPIO_Mode_AIN Analog Input (2) GPIO_Mode_IN_FLOATING Floating Input (3) GPIO_Mode_IPD Pull-Down Input (4) GPIO_Mode_IPU Pull-Up Input (5) GPIO_Mode_Out_OD Open-Drain Output (6) GPIO_Mode_Out_PP Push-Pull Output (7) GPIO_Mode_AF_OD Alternate Function Open-Drain Output (8) GPIO_Mode_AF_PP Alternate Function Push-Pull Output.

APB2 is responsible for AD, I/O, advanced TIM, and UART1. APB1 is responsible for DA, USB, SPI, I2C, CAN, UART2345, general TIM, and PWR.

GPIO Block Diagram Analysis:

Key Knowledge Points for STM32 Embedded Interviews

4. UART

  • Question 1: Describe serial communication methods? Synchronous communication: I2C half-duplex, SPI full-duplex; Asynchronous communication: RS485 half-duplex, RS232 full-duplex.

  • Question 2: UART configuration? The general steps for UART setup can be summarized as follows:

    (1) Enable UART clock, enable GPIO clock (2) Reset UART (3) Set GPIO port mode TX’s GPIO working mode is: GPIO_Mode_AF_PP; // Alternate function push-pull output RX’s GPIO working mode is: GPIO_Mode_IN_FLOATING; // Floating input (4) UART parameter initialization mainly includes: baud rate setting (115200), 8 data bits, 1 stop bit, no parity bit, no hardware flow control, transmit and receive mode. (5) Enable interrupts and initialize NVIC (if interrupts need to be enabled, this step is necessary) (6) Enable UART (7) Write interrupt handler function.

  • Question 3: Main features of USART? (1) Full-duplex operation (independent reception and transmission of data); (2) In synchronous operation, can synchronize master clock or slave clock; (3) Independent high-precision baud rate generator, does not occupy timer/counter; (4) Supports 5, 6, 7, 8, and 9 data bits, 1 or 2 stop bits serial data frame structure; (5) Hardware-supported parity bit generation and checking; (6) Data overflow detection; (7) Frame error detection; (8) Noise filter and digital low-pass filter including detection of erroneous start bits; (9) Three completely independent interrupts: TX transmission complete, TX data register empty, RX reception complete; (10) Supports multi-master communication mode; (11) Supports double-speed asynchronous communication mode.

5. I2C

  • Question 1: What are the three types of signals in the I2C bus during data transmission? (1) Start signal: When SCL is high, SDA transitions from high to low to start data transmission. (2) Stop signal: When SCL is high, SDA transitions from low to high to end data transmission. (3) Acknowledge signal: The receiving IC sends a specific low-level pulse to the sending IC after receiving 8 bits of data, indicating data has been received. The CPU sends a signal to the controlled unit, waiting for the controlled unit to send an acknowledgment signal. After receiving the acknowledgment signal, the CPU decides whether to continue transmitting signals based on the actual situation. If no acknowledgment signal is received, it is judged that the controlled unit has failed.

  • Question 2: How to configure the I2C master mode port? Hardware mode: Alternate function open-drain output, neither pull-up nor pull-down. (Fast mode: 400 Kbit/s) Software simulation: Push-pull output, configure pull-up resistors.

  • Question 3: I2C arbitration mechanism? Refer to: S5PV210 development – How much do you know about I2C? (3) I2C arbitration mechanism, understanding the “wired-AND” makes it clear. In simple terms, it follows the principle of “low level first,” meaning whoever sends the low level first will take control of the bus.

Answer:

Hardware mode: There is a communication rate setting.

/* STM32 I2C Fast Mode */#define I2C_Speed 400000/* Communication speed */
I2C_InitStructure.I2C_ClockSpeed = I2C_Speed;

Software simulation: If there is no communication rate set, how to calculate it? By using the I2C bus bit delay function i2c_Delay:

static void i2c_Delay(void){
  uint8_t i;
  /* The following time is obtained through the Anfu Lai AX-Pro logic analyzer test. When the CPU frequency is 72MHz, running in internal Flash, MDK project not optimized, the loop count is 10, SCL frequency = 205KHz, loop count is 7, SCL frequency = 347KHz, SCL high level time 1.5us, SCL low level time 2.87us, loop count is 5, SCL frequency = 421KHz, SCL high level time 1.25us, SCL low level time 2.375us. IAR project compilation efficiency is high, cannot be set to 7 */
  for (i = 0; i < 10; i++);
}

Application scenarios: PMIC, accelerometers, gyroscopes.

6. SPI

  • Question 1: How many lines does SPI need? The SPI interface generally uses 4 lines for communication: MISO master device data input, slave device data output; MOSI master device data output, slave device data input; SCLK clock signal generated by the master device; CS slave device chip select signal controlled by the master device.

  • Question 2: What are the four modes of SPI communication? SPI has four working modes, and the difference in each mode is due to the different SCLK, specifically determined by CPOL and CPHA. (1) CPOL: (Clock Polarity), clock polarity: SPI’s CPOL indicates whether the level of SCLK is low (0) or high (1) when idle; CPOL=0 means the idle level is low, so when SCLK is valid, it is high, known as active-high; CPOL=1 means the idle level is high, so when SCLK is valid, it is low, known as active-low.

Key Knowledge Points for STM32 Embedded Interviews

(2) CPHA: (Clock Phase), clock phase: phase corresponds to data sampling at which edge (first or second edge); 0 corresponds to the first edge, 1 corresponds to the second edge. For: CPHA=0, the first edge corresponds to the low level to high level transition; for CPOL=0, the idle state is low, so the first edge is rising; for CPOL=1, the idle state is high, so the first edge is falling; CPHA=1 indicates the second edge: for CPOL=0, the idle state is low, so the second edge is falling; for CPOL=1, the idle state is high, so the first edge is rising.

Key Knowledge Points for STM32 Embedded Interviews

  • Question 3: How to determine which mode to use? (1) First confirm the SCLK polarity required by the slave, whether it is low or high when not working, thereby confirming whether CPOL is 0 or 1. Looking at the schematic, we set the idle state of the serial synchronous clock to high level, so we choose SPI_CPOL_High, meaning CPOL is 1. (2) Then confirm from the slave chip datasheet timing diagram whether the slave chip samples data on the falling or rising edge of SCLK.

    Translate: W25Q32JV accesses the SPI-compatible bus, which includes four signals: serial clock (CLK), chip select (/CS), serial data input (DI), and serial data output (DO). The standard SPI command uses the DI input pin to serially write commands, addresses, or data to the device on the rising edge of CLK. The DO output pin is used to read data or status from the device on the falling edge of CLK.

    Supports SPI bus operations in modes 0 (0,0) and 3 (1,1). Modes 0 and 3 focus on the normal state of the CLK signal when the SPI bus master is in standby and no data is being transmitted to the serial Flash. For mode 0, the CLK signal is usually low during the falling and rising edges/ CS. For mode 3, the CLK signal is usually high at the falling and rising edges of /CS. Since the idle state of the serial synchronous clock is high, we choose the second transition edge, thus selecting SPI_CPHA_2Edge, meaning CPHA is 1, and we choose mode 3 (1,1).

Key Knowledge Points for STM32 Embedded Interviews

7. CAN

  • Question 1: Summarize CAN? The CAN controller determines the bus level based on the potential difference on CAN_L and CAN_H. The bus level is divided into dominant and recessive levels, one of which must be present. The sender sends messages to the receiver by changing the bus level.

  • Question 2: Steps for CAN initialization configuration? (1) Configure the multiplexing function of related pins, enable CAN clock (2) Set CAN operating mode and baud rate (CAN initialization loopback mode, baud rate 500Kbps) (3) Set filters.

  • Question 3: CAN data sending format? CanTxMsg TxMessage; TxMessage.StdId=0x12; // Standard identifier TxMessage.ExtId=0x12; // Set extended identifier TxMessage.IDE=CAN_Id_Standard; // Standard frame TxMessage.RTR=CAN_RTR_Data; // Data frame TxMessage.DLC=len; // Length of data to be sent 8 bytes for(i=0;i<len;i++)TxMessage.Data[i]=msg[i]; // data.

8. DMA

  • Question 1: What is DMA? Direct Memory Access (DMA) is used to provide high-speed data transfer between peripherals and memory or between memory and memory. Data can be moved quickly via DMA without CPU intervention, saving CPU resources for other operations.

  • Question 2: How many modes of DMA transfer are there? DMA_Mode_Circular circular mode, DMA_Mode_Normal normal buffer mode. Application scenarios: GPS, Bluetooth, both use circular sampling, DMA_Mode_Circular mode.

Answer:

A relatively important function, obtaining the current remaining data size, is to subtract the current remaining data size from the set receive buffer size to get the current received data size.

9. Interrupts

  • Question 1: Describe the interrupt handling process? (1) Initialize the interrupt, set the trigger method to rising edge/falling edge/both edges. (2) Trigger the interrupt, enter the interrupt service function.

  • Question 2: How many external interrupts does the STM32 interrupt controller support? The STM32 interrupt controller supports 19 external interrupt/event requests: As shown in the diagram, GPIO pins GPIOx.0~GPIOx.15 (x=A, B, C, D, E, F, G) correspond to interrupt lines 0 to 15. In addition, the connections for the other four EXTI lines are as follows: ● EXTI line 16 connects to PVD output ● EXTI line 17 connects to RTC alarm event ● EXTI line 18 connects to USB wake-up event ● EXTI line 19 connects to Ethernet wake-up event (only applicable to interconnected products) The interrupt service function list: IO external interrupts in the interrupt vector table are only allocated 7 interrupt vectors, meaning only 7 interrupt service functions can be used. EXTI0_IRQHandler, EXTI1_IRQHandler, EXTI2_IRQHandler, EXTI3_IRQHandler, EXTI4_IRQHandler, EXTI9_5_IRQHandler, EXTI15_10_IRQHandler.

10. How many clock sources does STM32 have?

STM32 has 5 clock sources: HSI, HSE, LSI, LSE, PLL.

① HSI is a high-speed internal clock, RC oscillator, with a frequency of 8MHz and low accuracy.

② HSE is a high-speed external clock that can connect to quartz/ceramic resonators or external clock sources, with a frequency range of 4MHz~16MHz.

③ LSI is a low-speed internal clock, RC oscillator, with a frequency of 40kHz, providing a low-power clock.

④ LSE is a low-speed external clock, connecting to a quartz crystal with a frequency of 32.768kHz.

⑤ PLL is a phase-locked loop frequency multiplier output, and its clock input source can be selected from HSI/2, HSE, or HSE/2. The multiplication factor can be selected from 2 to 16, but its output frequency must not exceed 72MHz.

11. How to write tasks in RTOS? How to switch tasks?

Answer:

A task, also known as a thread. UCOS has a task scheduling mechanism that schedules tasks based on their priority. One is hardware interrupts, where the system pushes the current task’s related variables onto the stack and executes the interrupt service program, then pops the stack and returns. The other is task switching, which uses task scheduling where each task has its own stack, also follows the same principle of pushing onto the stack, then executing another program, and then popping out and returning.

Tasks do not execute in strict priority order but rather high-priority tasks run exclusively unless they voluntarily yield execution; otherwise, low-priority tasks cannot preempt.

Meanwhile, high-priority tasks can reclaim CPU usage that they yielded to low-priority tasks.

Thus, in UCOS, tasks should include wait delays to allow UCOS to yield and let low-priority tasks execute.

12. What are the communication methods between tasks in UCOSII?

Answer:

In UCOSII, tasks communicate using semaphores, mailboxes (message mailboxes), and message queues, which are referred to as events, as well as global variables. Semaphores are used to: 1. Control the usage rights of shared resources (satisfy mutual exclusion conditions) 2. Indicate the occurrence of an event 3. Synchronize the behavior of two tasks.

Application example: A mutex semaphore serves as a mutual exclusion condition initialized to 1. The goal is to call a serial port to send a command, which must wait for the return of the “OK” character before sending the next command. Each task may use this send function, and conflicts must be avoided!

Mailbox (message mailbox):

Message queue: Concept: (1) A message queue is essentially an array of mailboxes. (2) Both tasks and interrupts can place a message into the queue, and tasks can retrieve messages from the message queue. (3) The first message to enter the queue is the first one to be sent to the task (FIFO). (4) Each message queue has a waiting list for tasks waiting for messages; if there are no messages in the queue, waiting tasks are suspended until a message arrives.

Application scenario: Receive buffer in serial port reception programs. Store external events.

13. The project uses a custom protocol; what is its structure?

Answer:

Familiar with the Modbus protocol. The structure is: Frame header (SDTC) + Frame length + Command + Serial number + Data + CRC check.

14. Differences between uCOSII and Linux?

Answer:

μC/OS-II is designed specifically for embedded applications in computers, featuring high execution efficiency, small footprint, excellent real-time performance, and strong scalability, with the minimum kernel compiled to 2KB. μC/OS-II has been ported to almost all well-known CPUs. Linux is free, secure, stable, and widely used in embedded systems, servers, and home computers. Both μC/OS-II and Linux are suitable for embedded applications. However, μC/OS-II is designed specifically for embedded systems, resulting in higher running efficiency and less resource usage. Linux can be used on servers, with high utilization. Although Linux was not specifically developed for servers, its open-source code can be modified, making the differences between the two not significant; the most widely used distribution, Red Hat Linux, is heavily utilized in server systems.

15. Git commit code process?

Question: Git commit code process?

Answer:

1. Display modified files in the working directory:

$ git status

2. Enter the modified file directory:

$cd -

3. Show differences from the last commit version:

$ git diff

4. Add all current modifications to the next commit:

$ git add .

5. Add relevant functionality description (use this for the first commit)

$ git commit -s

Note: Each folder must be submitted again.

6. View the submitted code

$ tig .

7. Do not modify published commit records! (Use this for future submissions)

$git commit --amend

In command mode: 😡 (write file and exit)

8. Push to the server

$ git push origin HEAD:refs/for/master

16. Comparison of uCOSII, uCOSIII, and FreeRTOS

  • Question 1: Comparison of the three?

Answer:

Comparison of uCOSII and FreeRTOS: (1) FreeRTOS only supports TCP/IP, while uCOSII has extensive support for extensions like FS, USB, GUI, CAN, etc. (We need to use CAN for Tbox, so we chose uCOSII) (2) FreeRTOS is free for commercial applications, while uCOSII requires payment for commercial use. (3) FreeRTOS supports inter-task communication only through queues, semaphores, and mutexes. In contrast, uCOSII supports events, including these and also event flag groups and mailboxes. (4) Theoretically, FreeRTOS can manage more than 64 tasks, while uCOSII can only manage 64.

Comparison of uCOSII and uCOSIII: What are the differences from μC/OS-II to μC/OS-III?

Many changes have been made.

One is that there were originally only 0~63 priorities, and priorities could not be duplicated. Now multiple tasks can use the same priority, and time-slice scheduling is supported within the same priority.

The second is that users are allowed to dynamically configure real-time operating system kernel resources during program execution, such as tasks, task stacks, semaphores, event flag groups, message queues, message counts, mutex semaphores, memory block divisions, and timers, which can be changed during program execution.

This allows users to avoid resource allocation issues during program compilation.

There have also been some improvements in resource reuse.

In μC/OS-II, the maximum number of tasks was 64, but after version 2.82, it increased to 256. In μC/OS-III, users can have any number of tasks, semaphores, mutex semaphores, event flags, message lists, timers, and any allocated memory block capacity, limited only by the RAM amount that the user’s CPU can use.

This is also a significant expansion.

(Question: Teacher Shao, is this number fixed at startup, or can it be defined freely after startup?)

It can be freely defined during configuration as long as your RAM is large enough.

The fourth point is that many functions have been added, and the functionality is continually increasing; you can take a look at that. These functions were not present in μC/OS-II.

17. Low Power Modes

  • Question 1: How many low power modes are there? What are the wake-up methods?

Answer:

Key Knowledge Points for STM32 Embedded Interviews

18. Architecture of the Internet of Things

  • Question 1: How many layers are there in the architecture of the Internet of Things? What functions does each layer perform?

Answer:

Divided into three layers, the architecture of the Internet of Things can be divided into sensing layer, network layer, and application layer. (1) Sensing Layer: Responsible for information collection and transmission between objects. The technologies for information collection include sensors, barcodes and QR codes, RFID technology, audio and video, and other multimedia information. Information transmission includes near and far data transmission technologies, self-organizing networking technologies, collaborative information processing technologies, and middleware technologies for information collection. The sensing layer is the core capability for achieving comprehensive perception in the Internet of Things, and it is a crucial part that requires breakthroughs in key technologies, standardization, and industrialization, focusing on having more accurate and comprehensive sensing capabilities while addressing issues of low power consumption, miniaturization, and low cost. (2) Network Layer: Utilizes wireless and wired networks to encode, authenticate, and transmit collected data. The widely covered mobile communication network is the infrastructure for achieving the Internet of Things, being the most standardized, industrially capable, and mature part of the three layers. The key is to optimize and improve the application characteristics of the Internet of Things, forming a collaborative sensing network. (3) Application Layer: Provides rich applications based on the Internet of Things, which is the fundamental goal of IoT development, combining IoT technology with industry information needs to realize extensive intelligent application solutions. The key lies in industry integration, the development and utilization of information resources, low-cost and high-quality solutions, ensuring information security, and developing effective business models.

19. Memory Management

  • Question 1: What methods are there for memory management in UCOS?

Answer:

The system manages memory partitions through memory control blocks associated with the memory partitions.

Dynamic memory management functions include: Create dynamic memory partition function OSMemCreate(); Request memory block function OSMemGet(); Release memory block function OSMemPut();

20. What are the task states in Ucos? What is the relationship diagram between task states?

Answer:

There are 5 states: Sleep state, Ready state, Running state, Waiting state (waiting for a certain event to occur), and Interrupt service state.

UCOSII task state transition relationships:

Key Knowledge Points for STM32 Embedded Interviews

21. ADC

  • Question 1: Briefly describe the functional characteristics of the STM32 ADC system? (1) 12-bit resolution (2) Automatic calibration (3) Programmable data alignment (conversion results support left or right alignment stored in a 16-bit data register) (4) Single and continuous conversion modes.

22. System Clock

  • Question 1: Briefly describe the basic process of setting the system clock? (1) Turn on HSE, wait for it to be ready, and set Flash wait operations. (2) Set AHB, APB1, APB2 prescaler coefficients, determining their relationships with the system clock. (3) Set CFGR register to determine PLL clock source and multiplication factor (HSE external 8M * 9 times = 72MHz). (4) Enable PLL and switch the system clock source to PLL.

23. HardFault_Handler processing

  • Question 1: What are the causes? (1) Array out-of-bounds operation; (2) Memory overflow, out-of-bounds access; (3) Stack overflow, program runaway; (4) Interrupt processing errors;

  • Question 2: What are the processing methods? (1) Find the address remapping of HardFault_Handler in startup_stm32f10x_cl.s and rewrite it to jump to the HardFaultHandle function. (2) Print and check registers R0, R1, R2, R3, R12, LR, PC, PSR. (3) Check the fault status register group (SCB->CFSR and SCB->HFSR).

24. TTS Speech Synthesis Method

  • Question 1: What method does sim7600 TTS speech use?

Answer:

(1) Use Unicode encoding to synthesize sound AT+CTTS=1,”6B228FCE4F7F75288BED97F3540862107CFB7EDF” content is “Welcome to the speech synthesis system”; the module sends and receives Chinese SMS using Unicode encoding, making it easy to read SMS aloud; (2) Directly input text, ordinary characters use ASCII code, Chinese characters use GBK encoding. AT+CTTS=2,”Welcome to the speech synthesis system”.

25. Timer

  • Question 1: Given that the STM32 system clock is 72MHz, how to set the relevant registers to achieve a 20ms timer?

By using SysTick_Config(SystemCoreClock / OS_TICKS_PER_SEC)) // 1ms timer

Where:

uint32_t SystemCoreClock         = SYSCLK_FREQ_72MHz;        /*!< System Clock Frequency (Core Clock) */#define SYSCLK_FREQ_72MHz  72000000#define OS_TICKS_PER_SEC       1000    /* Set the number of ticks in one second

If 20ms is needed, a global variable can be set initially to 20, so that with each systick interrupt, this global variable decreases by 1, and when it reaches 0, the systick interrupts 20 times, resulting in a time of: 1ms * 20 = 20ms. Thus, a 20ms timer can be achieved.

26. Priority

  • Question 1: How do two tasks with the same priority run?

Answer:

During the usage of shared resources, the priority of the task obtaining the semaphore is temporarily raised to one level higher than that of all tasks to ensure that this task is not interrupted by others, allowing it to quickly use and release the shared resource, and then restore the original priority after releasing the semaphore.

27. State Machine

  • Question 1: What state machine is used?

Answer:

Finite State Machine (FSM), also known as a finite state automaton.

Assuming the state transitions of the state machine are as shown in the table below:

Key Knowledge Points for STM32 Embedded Interviews

Implementation: (using switch statement)

// Write horizontally
void event0func(void){
    switch(cur_state)
    {
        case State0:
             action0;
             cur_state = State1;
        break;
         case State1:
             action1;
             cur_state = State2;
        break;
         case State2:
             action1;
             cur_state = State0;
        break;
        default:break;
    }
}
void event1func(void){
    switch(cur_state)
    {
        case State0:
             action4;
             cur_state = State1;
        break;
        default:break;
    }
}
void event2func(void){
    switch(cur_state)
    {
        case State0:
             action5;
             cur_state = State2;
        break;
         case State1:
             action6;
             cur_state = State0;
        break;
        default:break;
    }
}

28. Device Selection

  • Question 1: Comparison of STM32F407 vs STM32F103 main functions and resources?

Answer:

Key Knowledge Points for STM32 Embedded Interviews

Source: juyou.blog.csdn.net/article/details/116021595

-END-

Previous Recommendations: Click the image to jump to read
Key Knowledge Points for STM32 Embedded Interviews

How to Design Embedded C Language Logging Levels?

Key Knowledge Points for STM32 Embedded Interviews

How to Build Embedded Software Infrastructure?

Key Knowledge Points for STM32 Embedded Interviews

Code Reading Tool Based on ChatGPT

Leave a Comment