1

I have the following code for Arduino mega to output 40 kHz square waves at the analog pins. I need to apply specific phase delays for the signals at each pin though and am struggling to find out how to do this. Any help would be appreciated. Thanks!

byte TP = 0b10101010; // Every other port receives the inverted signal

void setup() {

DDRF = 0b11111111; // Set all analog ports to be outputs
DDRK = 0b11111111; // Set all analog ports to be outputs
// Initialize Timer1

noInterrupts(); // Disable interrupts

TCCR1A = 0;

TCCR1B = 0;

TCNT1 = 0;

OCR1A = 200; // Set compare register (16MHz / 200 = 80kHz square wave -> 40kHz full wave)

TCCR1B |= (1 << WGM12); // CTC mode

TCCR1B |= (1 << CS10); // Set prescaler to 1 ==> no prescaling

TIMSK1 |= (1 << OCIE1A); // Enable compare timer interrupt

interrupts(); // Enable interrupts

}

ISR(TIMER1_COMPA_vect) {

PORTF = TP; // Send the value of TP to the outputs
PORTK = TP;
TP = ~TP; // Invert TP for the next run

}

void loop() {

// Nothing left to do here :)

}
6
  • Do you need multiple pins with linear growing phase delay?
    – chrisl
    Sep 26, 2019 at 12:51
  • Hi Chris :) I need multiple pins with different phase delays.
    – Marion
    Sep 26, 2019 at 13:35
  • I suspect that you can't do that. The square wave output on AVR-based Arduinos is pretty crude, and relies on interrupt-driven counters and dividers to generate the outputs. I doubt if the hardware has enough precision to manage outputs with different phases. You might need to use external signal generator hardware for this.
    – Duncan C
    Sep 26, 2019 at 17:51
  • hi Duncan :) thanks for the response. I am outputting the signals to the analog pins though not the PWM.
    – Marion
    Sep 26, 2019 at 18:11
  • What phase delays do you need? Are they constant or variable? Will the program eventually grow and have something in loop() Could you use different pins? Sep 26, 2019 at 19:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.