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.
- void ARDUINO_ISR_ATTR timer1_ISR() {
- digitalWrite(trigPin1, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin1, LOW);
- }
- void ARDUINO_ISR_ATTR timer1_ISR() {
- portENTER_CRITICAL_ISR(&timerMux);
- switch (trigTimerCnt) {
- case 0:
- digitalWrite(trigPin1, HIGH);
- trigTimerCnt++;
- break;
- case 1:
- digitalWrite(trigPin1, LOW);
- trigTimerCnt++;
- break;
- case 5999:
- trigTimerCnt = 0;
- break;
- default:
- trigTimerCnt++;
- break;
- }
- portEXIT_CRITICAL_ISR(&timerMux);
- }
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!