Trouble Generating a 10 µs Trigger Pulse for HC-SR04 Using STM32 Timer Block in Simulink

60 views (last 30 days)
Hi, I am trying to generate a 10 µs trigger pulse for the HC-SR04 ultrasonic sensor using a Timer block in Simulink on an STMF411RE. However, the trigger signal is not working as expected
Below is my current model setup:
  • I read the TIM3 CNT value using the STM32 Timer block.
  • I compare CNT > 10 using a Switch block to create the 10 µs HIGH pulse.
  • The output is connected to GPIOB Pin 4 configured as the Trigger pin.
However, when I run the model on hardware, the Trigger output stays HIGH continuously instead of generating a 10 µs pulse.
In the Simulation Data Inspector, the timer counter appears to be working, but the Switch output remains at 1 all the time
Block Diagram :
Data Inspector :
Scope :
Although the Timer Counter block and Switch block behave exactly as expected in the Simulink simulation, the output on the hardware does not generate the correct trigger pulse.
What could be causing this, and how can I fix it? Tnank you

Accepted Answer

Shivam
Shivam on 24 Nov 2025 at 16:28
Edited: Shivam on 24 Nov 2025 at 16:29
Hello @jinest,
As per my understanding, you want to generate a periodic pulse of 10 micro-second width for the ultrasonic sensor.
Your understanding behind the concept of using counters is correct, but let me clear the confusion.
The counter block placed from the simulink library is not the same as the timer block placed from STM32 peripheral library. The counter block will increment the count after each step size of simulation. For example if your simulation step size is 0.1s, your counter gets incremented by 1 in every 0.1 seconds simulation time.
Whereas, the timer peripheral block works on the clock of micro-controller (target hardware). It enables the counter of timer module of the target hardware and it increments counter value at every clock pulse. As an example, suppose that timer frequency of the target hardware is 100MHz and you program the period counts to be 5000. So, the time period of the counter will be 5000/100e6 = 50us. This means that your timer counts will increment from 0 to 5000 counts in just 50us. From the waveform attached by you, its evident that the simulink sample time is much greater than the time-period of the counter. Therefore, at each sample, you get almost the same value of timer counts.
SOLUTION:
The best way is to use timer "TIM3" in PWM mode. For this, configure the TIM3 in "PWM generation mode" in the CubeMX file. Configure the "Counter period" field as per your desired time period. Use the "PWM Output" block instead of "TIM" block.
The "CH1" input to the block will decide the pulse width for the ultrasonic sensor. Its value can be calculated as:
100*(10us/time_period(seconds))
Try out this approach!
I hope it helps!

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!