So this week you’ll be exploring digital to analog conversion, outputing an analog signal with your Arduino.

The guide for this lab is here.

In this lab you’ll have to do two things at the same time - control a square wave and measure the analog input - without blocking the main loop. How to do that?

First, to generate a square wave, you can use the digitalWrite function. Timing the turn HIGH/LOW, you can generate a square wave. Read more about this function here.

You can use the function millis() to keep track of time. Once a previously defined ammount of time has passed, you do something. Check the following example:

unsigned long previous_time = 0;
unsigned int dt = 100;
unsigned long current_time = 0;

void setup {
    // setup your code
}

void loop {
    current_time = millis();
    if (current_time - previous_time > dt) {
        // do something here
        previous_time = current_time;
    }
}

As you can see in the example above, this will do something every dt milliseconds without blocking the loop.

To do two things at the same time, with different intervals, without blocking the loop, you can use something similar to the following code:

unsigned long pt1 = 0;
unsigned long pt2 = 0;

unsigned int dt1 = 100;
unsigned int dt2 = 100;

unsigned long ct = 0;

void setup {
    // setup your code
}

void loop {
    ct = millis();
    
    if (ct - pt1 > dt1) {
        // do something here
        pt1 = ct;
    }

    if (ct - pt2 > dt2) {
        // do something else here
        pt2 = ct;
    }
}

Another thing that you have to do is generating a square wave with half the amplitude, Vcc/2. You can easily accomplish that using a voltage divider:

voltage divider

Where Vin is connected to the digital output pin and Vout to the analog input pin.