Replace delayMicroseconds() with micros()

Hello everyone!

I’m trying to make an AC control for lamps. There is a zero crossing detector that sends a pulse to Arduino everytime the sine wave passes thru 0. This pulse activate an ISR that generates another phased pulse to trigger the TRIAC. In near future, I will add other lamps that will be controlled separately with potentiometers. The delayMicroseconds() won’t let me control multiple lamps, so I want to replace it with micros() (code below). I need to get rid off delays cuz the readings can’t be late. I need simultaneously readings from multiple potentiometers.

  • The code is working perfectly with one lamp/pot. I haven’t tested with more lamps yet.

  • Graphs: [Attached images]
    blue line: zero-cross signal
    red line: dimmerized signal (phased signal)
    green line: load sine wave

Thx

#define dimmer 5

volatile long pot = 0.0; // potentiometer read

void zeroCross() {

    // Calculates t1
  long t1 = 8333L * (100L - pot) / 100L;
  delayMicroseconds(t1);
  digitalWrite(dimmer,HIGH);
  delayMicroseconds(10);
  digitalWrite(dimmer,LOW);
}

void setup() {
  pinMode(dimmer, OUTPUT);
  digitalWrite(dimmer, LOW);
  attachInterrupt(0, zeroCross, FALLING);
}

void loop() {
  pot = map(analogRead(A0), 0, 1023, 1, 90);
  delay(10);
}[\code]

ZeroCross.png

Just use this https://forum.arduino.cc/index.php?topic=223286.0 and replace millis() with micros().

Just keep in mind that the Arduino micros() resolution is 4 microseconds and overflows every 70 minutes.

The ESP32's equivalent of micros resolution is 1 microsecond and overflows in a bit more then 100 years. Then again you'd not need micros() with a ESP32. The OS, freeRTOS, built into the ESP32 is multitasking and multithreading.

Disparaging posts REMOVED.

@danicomartins

Could you use code tags please ( </> )

Could you also take a few moments to Learn How To Use The Forum.
It will help you get the best out of the forum in the future.
Other general help and troubleshooting advice can be found here.