Sending a very short duration pulse on a timer interrupt

mattfaigan
Posts: 1
Joined: Thu Nov 10, 2022 11:21 pm

Sending a very short duration pulse on a timer interrupt

Postby mattfaigan » Thu Nov 10, 2022 11:51 pm

Hello, this is my first post so please let me know if there is any forum etiquette, etc that I am missing.

I'm wanting to use an HC-SR04 ultrasonic rangefinder to measure distance periodically. The rangefinder is triggered with a 10 us pulse on the trigger pin. Because the main loop will also be handling other tasks (uploading readings to a server), I plan to send this pulse in an ISR called every 60 ms by a periodic timer. I'm unsure how best to go about this.

1. Setting the trigger pin high, calling delayMicroseconds(10), and setting the trigger pin low, inside the ISR. The timer would fire every 60 milliseconds.
  1. void ARDUINO_ISR_ATTR timer1_ISR() {
  2.   digitalWrite(trigPin1, HIGH);
  3.   delayMicroseconds(10);
  4.   digitalWrite(trigPin1, LOW);
  5. }
2. Using a 10 us timer period and tracking the number of times the ISR is called. When the count is 0, set the output high. When the count is 1, set the output low. Otherwise, do nothing and wrap back around once the ISR is called 6000 times (or 60 ms, given a 10 us period).
  1. void ARDUINO_ISR_ATTR timer1_ISR() {
  2.   portENTER_CRITICAL_ISR(&timerMux);
  3.   switch (trigTimerCnt) {
  4.     case 0:
  5.       digitalWrite(trigPin1, HIGH);
  6.       trigTimerCnt++;
  7.       break;
  8.     case 1:
  9.       digitalWrite(trigPin1, LOW);
  10.       trigTimerCnt++;
  11.       break;
  12.     case 5999:
  13.       trigTimerCnt = 0;
  14.       break;
  15.     default:
  16.       trigTimerCnt++;
  17.       break;
  18.   }
  19.   portEXIT_CRITICAL_ISR(&timerMux);
  20. }
3. Having the timer fire every 60 ms, and the ISR starts a second non-repeating timer to fire 10 us later which turns off the pulse. I don't have a code example for this one.

Regarding 1, I know that ISRs are supposed to be as fast as possible, and that delays inside ISRs are generally frowned upon. That's why I'm unsure about that option, but I'm including it for completeness.
Regarding 2, my worry is that 10 microseconds is too short of a period and the CPU will be overwhelmed.

I'm new to embedded (doing this for a university project, in fact) so any help is much appreciated!

ESP_Sprite
Posts: 9727
Joined: Thu Nov 26, 2015 4:08 am

Re: Sending a very short duration pulse on a timer interrupt

Postby ESP_Sprite » Fri Nov 11, 2022 3:52 am

If anything, I'd suggest you look into the RMT peripheral.

Who is online

Users browsing this forum: No registered users and 91 guests