Arduino R2R DAC: Circuit Tuning

I’ve spent my last two posts making some important improvements to the code for my Digital to Analog converter. I’ve converter the code to write directly to the PORT register to speed up my updates and implemented timer interrupts to improve my timing. These are both vast improvements but there’s still one more area that desperately needs my attention before I start building out the features of my new oscillator. That area is the circuit.

Today I’ll be working to hammer out two big issues I’ve been having with the circuit. The first I identified back when I first introduced this project, that is the lack of consistency in the values of the various voltage steps. Once that’s squared away I’d like to have a look at buffering the output so I can start driving a speaker (or other analog load) with the DAC.

The Resistance

Original DAC Output

Ideally when stepping through the voltages of my DAC (as I do with my saw wave function) I should be seeing a smooth staircase on my oscilloscope. Unfortunately looking at the output above we see this is not exactly the case. The issue here has to do with the tolerance of the resistors. Had this original design been more than a proof of concept I would have ordered low tolerance resistors special for the task. Instead in my rush I used what was available in my parts drawer. Unfortunately this meant the values of my resistors varied quite widely from the 100 and 200 ohms I had planned.

My approach here is pretty low-tech. I drew a quick schematic of the circuit and using my multimeter marked down the actual resistance of each resistor. Diagram in hand I started measuring the other 100 ohm resistors I had on hand. When I found one closer to the target resistance than what was on my diagram I switched them out and updated the diagram. Since I had limited resistors available I wasn’t able to get the values exactly but it still made a substantial difference.

New DAC output

Looking at the new output above the steps still aren’t perfect but they are substantially closer to the idealized staircase we are looking for. Each of the 16 steps is now clearly visible and differentiated.

Another approach you can take to bypass these issues is trimmer pots. If you replace each resistor with a trimmer potentiometer you can dial in the exact resistance you want up to the resolution of the trimmer.

Buffering

If you know anything about me it’s that I like to make noise. It’s sort of my jam. Sadly though if you’ve tried to connect this circuit as it stands to a speaker you may have been sorely disappointed to find nothing coming out. This simply won’t do!

The issue here is with the current in my circuit. Digital pins (both on the Arduino and otherwise) put out a tiny amount of current. The absolute maximum available from any digital pin on the Arduino is 40.0 mA.

If we consider the case of a 1W 8ohm speaker (similar to a cheap computer speaker) being driven at 5V we’ll find that it needs about 200mA to run (1W/5V = 0.2A = 200mA). Clearly we need to step things up a notch.

4-bit DAC Circuit

My solution here was to add an LM358 op-amp to buffer the signal. Since the output of the Arduino is already 5V I didn’t need any gain so I set this up as a “Unity Gain Amplifier”. One issue I did encounter is that the output range of the LM358 does not cover the full 5V range I’m supplying it with. I found the signal became saturated at about 4.1-4.2V. To combat this I added the potentiometer to work as a voltage divider and attenuate the signal slightly before it enters the amplifier.

Arduino R2R DAC: Timer Interrupts

Up to this point I’ve been handling all of the timing in my Arduino projects using the delay (or delayMicroseconds) function. This has worked pretty well but isn’t without it’s issues. Primarily there are two problems that need to be addressed. First, when using the delay function my timing doesn’t take into account the time it takes to process the rest of the code. And second when using delay my Arduino isn’t able to do anything else. If I wanted to, for instance, run two oscillators simultaneously at different speeds everything would break down.

The solution to these problems is to leverage timer interrupts. This essentially sets up a clock that calls a function at regular intervals. This means my timing will have much higher accuracy and I can have the Arduino do whatever I want in between updates.

Arduino Timers

The Arduino Uno has three timers appropriately named Timer0, Timer1 and Timer2. each of these runs off the 16MHz clock oscillator within the Arduino.

Each timer has a couple important parameters we can control. The first is something known as a prescaler. The prescaler allows us to slow down the clock speed from 16MHz to a more manageable speed. The prescaler values available are 1 (no change), 8 (sets timer to 16MHZ/8 = 2MHz), 64 (slows the timer to 250kHz), 256 (62.5kHz) and 1024 (15.625kHz). These prescaler are set by writing ones different combinations of three registers (CSx0, CSx1 and CSx2) as seen in the following grid.

Clock Selector Bits

Note: the x in these register names should be replaced with the timer number.

The second parameter that will impact our timing is the value in the output compare register (OCR). The timer will count up based on the clock frequency and prescaler. Each time it reaches the value in the OCR register it will reset and send an interrupt. On the Arduino Uno Timers 0 and 2 have an 8 bit counter meaning the OCR can be any value between 1 and 256. Timer 1 is a 16 bit timer meaning it can count as high as 65536.

Math Time

So how do we put this all together? Lets say we want our saw wave to run at 1kHz. The first thing we have to correct for is the steps in the saw itself. Right now we’ve got the saw wave set up to cycle through 16 voltage levels, so right away our 1kHz signal will require the timer to fire at 16Hz. No problem!

So to get the 16MHz clock input down to 16Hz we first need to apply a prescaler. Lets divide the 16MHz by a prescaler of 8 (16MHz/8 = 2MHz). Now to get that 2MHz down to 16kHz we need to set our OCR. if we divide the timer speed by the desired speed we’ll find the value we need (2MHz/16kHz = 125).

Lets Write It

Enough theory, let’s write some code! First things first, I define a function to initiate the timer and call it in the setup function.

void timer1_init();

void setup() {
  DDRB = B1111;      //Set Pins 8-11 as Inputs

  timer1_init();    //Initiate timer
}

For the timer function we want to start by disabling all interrupts and setting the following three registers to zero. This initiates the timer.

  noInterrupts();        

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;

Next we set the OCR value.

  OCR1A = 125;                //Compare Value

We set the timer into CTC mode using the following command. CTC mode allows us to trigger our interrupts each time the counter hits the OCR value. This is immediately followed by a command setting the prescaler and a final command enabling the interrupt itself. Last we reenable the interrupts.

  TCCR1B |= (1 << WGM12);       // CTC mode
  TCCR1B |= (1<<CS11);         // 8 prescaler 
  TIMSK1 |= (1 << OCIE1A);    // enable timer compare interrupt

  interrupts();     

So that sets up the interrupt but how does it get called? Essentially what happens is each time the interrupt triggers it calls a specific function known as ISR. We can set up the ISR function as follows.

ISR(TIMER1_COMPA_vect){
  PORTB = v_level;         
  v_level = (v_level + 1) % 16;
}

And there we have it. We’ve done away with the evil delay function and replaced it with a timer interrupt. I’ll finish off with the complete code and I’ll see you all soon.

#define PIN_8 8
#define PIN_9 9
#define PIN_10 10
#define PIN_11 11

#define N 15

int DAC_bus[] = {PIN_8, PIN_9, PIN_10, PIN_11};

int v_level = 0;

void timer1_init();

void draw_saw();

void setup() {
  DDRB = B1111;      //Set Pins 8-11 as Inputs

  timer1_init();    //Initiate timer
}

void loop(){
  }

void timer1_init(){
  noInterrupts();        
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;

  OCR1A = 125;                //Compare Value
  TCCR1B |= (1 << WGM12);      // CTC mode
  TCCR1B |= (1<<CS11);    // 8 prescaler 
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt

  interrupts();     
}

ISR(TIMER1_COMPA_vect){
  PORTB = v_level;         
  v_level = (v_level + 1) % 16;
}

Arduino R2R DAC: Writing to Ports

A few days ago I wrote a post outlining the R2R Digital to Analog Converter. This project is in it’s early stages, but there were a few refinements I wanted to make prior to expanding it’s functionality. The first thing I want to modify is the way that the code handles writing values to the digital pins.

The digitalWrite function on Arduino is only capable of changing the state of one pin at a time. This means we are currently writing to PIN_8, then PIN_9, then 10 and so on. This becomes an issue at high speeds since I am setting my voltage levels based on the sum of these pin’s outputs. The time in between the first and final pin switching will not match the desired voltage and can cause the wave to break down.

The solution to this problem involves pulling back a layer of abstraction from the Arduino. By bypassing the digitalWrite function and writing directly to the ports of the Arduino we can manipulate these pins at the same time. This will provide us faster and more efficient code.

What’s a Port

In the architecture of ATMEGA chips (The chips that run Arduinos) as well as most microprocessors the pins are organized into a set of Ports. These ports are a way of organizing the i/o pins and simplify the chips internal logic.

In the case of the Arduino we have 3 ports. They are as follows:

  • Port B: Digital Pins 8 – 13
  • Port C: Analog Input Pins
  • Port D: Digital Pins 0-7

This project uses pins 8-11 so I am interested in Port B. But how do I access this port?

Port Registers

Each port functions with the aid of three registers. A register is a special section of volatile (non-permanent) memory. Registers hold parameters or values for the system. Each of these three registers has a different task relating to the port. Further each of these registers is made up of 8 bits with each bit corresponding to a pin in the port.

DDR – Port Data Direction Register – As it’s name suggests the DDR port controls the direction of data flow for each pin in the port. If a bit in this register is set to 1 the corresponding pin is an output. Meanwhile the pin is an input when the corresponding bit is set to zero.

PORT – Port Data Register – This port governs the data being written to the pins in the port. When working with output pins we can write zeros or ones to this register to output high or low on the corresponding pins.

PIN – Port Input Register – This register is less relevant to this project but is still good to be aware of. The input register is where you can read the values being received by any of the input pins.

Each of these registers is set up as a variable within the Arduino IDE making them very easy to access. To access one of these registers we just need to append the port name to the register name. For this project I will be using DDRB and PORTB.

Setting Pin States

void setup() {
  for (int k = 0; k < 4; k++){
    pinMode(DAC_bus[k], OUTPUT);
  }

In my original code I used the loop above to set pins 8-11 to Output. This is not very efficient. Instead we can use the register DDRB to set these pins. One important note is that the lowest pin in the port is tied to the last bit in the register. That means to set pins 8-11 to Output I need to write B00001111 into the register. The “B” here tells the compiler this is a binary number. Since the most significant bits here are all zeros we can even shorten this slightly to give us B1111. This gives us the following setup function.

void setup() {
  DDRB = B1111;      //Set Pins 8-11 as Inputs
}

This shortens our code and minimizes the amount of memory required on the Arduino. Additionally this new setup function will run much faster. As a housekeeping item, I also added a comment to clarify what is happening since it is no longer clear in the code.

Writing To A Port

void test_run2(){
  for (int i = 0; i < 15; i++){
    int value = i;
    for (int k = 0; k < 4; k++){
      digitalWrite(DAC_bus[k], value%2);
      value = value/2;
    }
    delay(1);
  }
}

Above I’ve included my original function to draw a sawtooth pattern. In addition to being inefficient this function is just plain ugly. Using the PORTB register we should be able to get rid of the nested loop and write the value directly to the register. Conveniently the variable i is stored in the Arduino in binary. This means we don’t have to do any kind of conversion, we can write the value directly into the port.

void draw_saw(){
  for (int v_level = 0; v_level < 15; v_level++){
    PORTB = v_level;         
    delayMicroseconds(500);
  }
}

That looks a lot cleaner! By making this change I’ve now assured all of the digital pins update simultaneously. This will allow the oscillator to run much more accurately at high speeds. Additionally I’ve reduced the size of the program freeing more memory in the Arduino.

Notice I also made a few other changes to the function. I have changed the function and variable names to be more descriptive. This makes it much clearer what is happening. Additionally I have swapped the Arduino delay function for delayMicroseconds. This allows me to use much smaller delay times and achieve significantly higher frequencies.

With these changes I can now create saw waves throughout the audio frequency range (20 – 20,000Hz) and well beyond it. I’ve been able to shrink the code while improving performance. Further I’ve honed what will be a valuable skill moving forward. That’s all for today but I hope you are all staying healthy. I’ll see you again soon!

Binary Representation

Since I’ve been working so much lately in the digital space I thought it would be pertinent to do a quick review today. I want to spend some time on one of the most fundamental ideas in digital logic, Binary Representation. I know it’s not the most exciting topic but understanding binary numbers intuitively is critical to understanding the inner workings of digital devices.

Why Do We Care?

You’ve undoubtedly run into binary numbers in pop culture. They seem to appear any time a screenwriter wants to convey that a character “speaks computer.” But what do these zeros and ones mean? And more importantly, why do we care?

At the core the answer is that a computer has no idea what a 7 is. Computers are made up of millions (or billions) of transistors. These transistors only have two states, High and Low, or if you prefer zero and one. This means every thing you store in memory and any instructions you send into your processor need to be written as a series of these zeroes and ones. That goes for all your video files, pictures, video games and even your operating system itself. As far as your computer is concerned it’s all binary.

We can make it a long way working in high level languages like C or Python but inevitably there will come a time when you have to write directly to a register or transmit raw data. This is when binary will serve you. These situations are doubly likely to occur if you are working with microprocessors as both memory and power are limited. Further in time sensitive situations (like audio processing) writing straight to a register is typically faster and more efficient than using high level code.

How Does It Work?

The numbers we are familiar with are known as base 10 (or decimal numbers). This means each digit can be one of 10 possible values (0-9). If I add one to 9 the ones digit resets to zero and the tens digit is incremented to 1 (Giving you 10). When you were first learning to add numbers together you may have been taught to write the two numbers one atop the other and add each digit individually carrying to the next digit when your answer was more than 9. This gets at the core of the base 10 system.

The binary system is no great magic trick. We simply change the base to 2. This means each digit can only hold one of two values (0 or 1). As you count upwards you start with 0. Adding one gives you 1. When you try to add another one you have to carry over to the next digit (just like adding one to 9) giving you 10. To help clarify this process I’ve written out the binary representations of the numbers 0 to 15.

Binary Representation of 0-15

It’s good to note that there are other bases commonly used as well. In computation hexadecimal (base 16) is frequently used to make very large numbers manageable. In Hexadecimal we use the letters A-F to represent 10-15.

How Many Bits?

Notice in the previous table I used 4 digits and was able to represent numbers from 0 to 15 before I ran out of space. These digits are usually referred to as bits and they govern how large a number you can represent. This shouldn’t be too surprising as this is exactly how binary works (2 digits can represent numbers up to 99, 4 digits can represent up to 9999).

So how do we know how many bits we need? In decimal each new digit has a ten times higher value than the previous digit (1. In binary we can use a similar rule except since it’s base 2 each new digit is double the previous one. Here I have shown the value of a one in each of the first 8 digits to illustrate this rule.

Values of Binary Digits

Additionally in decimal you can find the number maximum value you can obtain with a number of digits using the following formula:

Where n is the number of digits and N is the highest value possible. We can do the same in binary by swapping the 10 for a 2:

Using this formula we can calculate the range of numbers available given any number of bits:

Maximum Value Based on Quantity Of Bits

Conversions

There are various methods to convert between decimal and binary. The route I have always found easiest though involves repeatedly dividing a number by two. Each time you divide by two you check if there is a remainder and note that remainder (it will always be 1 if it exists). If there is no remainder (ie. the number is even) note a zero. When you finish you can reverse the order of the numbers you have noted to see the binary representation.

Lets try applying this algorithm for 42:

Binary Conversion of 42

We can see that the binary conversion of 42 is 101010 by reading the remainders from the bottom up. Additionally you can verify your answer by multiplying each digit by the values determined earlier in this article (1*32 + 1*8 + 1*4). Doing this you should get back your original number.

Closing

Before I finish up for the day I have one final question. How high can you count on your fingers? If you answered 10 you’re not thinking with portals yet. We have 10 fingers, each of which can be either extended or folded. If we use binary counting we can reach 2^10 – 1. That’s 1023! You’ll never need a calculator again!

That’s all for me today. I hope you’ve found this refresher helpful, I’ll be back soon with further updates to my Arduino R2R DAC project.

Building A Better DAC

I’ve had a lot of fun playing with my PWM Oscillator but at the end of the day it’s a bit limited. 10Hz is barely going to get us very far and the waveforms aren’t exactly smooth. Surely we can do better!

Today I’d like to start exploring something a bit more interesting. An R2R Digital to Analog Converter. Here I will use multiple digital pins and a resistor ladder to create a much more versatile analog oscillator. For now I am going start with a very basic version of the converter to hammer out the logic. Once this is done I can start building the circuit and code up to see what it can do.

The Circuit

4-Bit R2R DAC

Looking at the circuit diagram gives some indication of where this converter gets it’s name. The circuit is made up of a ladder of resistors composed of 2R from each digital pin and R connecting them together (Where R is any resistor value). For mine I’ve used 200 and 100 ohms respectively.

These resistors function as a chain of Voltage Dividers. The math here gets a bit complicated but how it all pans out is this; The signal from the pin closest to the output (Pin 11 above) will give a voltage of approximately half your range at the output, each subsequent pin will reach the output with half of the voltage of the previous pin. This means if you had an output range of 5V, pin 11 would output 2.5V, pin 10 would output 1.25V, 9 would output 0.625V and 8 would output 0.3125V. When multiple pins are set high at once these voltages are added together. This gives us a wide range of voltages to play with.

It’s important to note that these are idealized values. Dependent on the tolerance of the resistors you use there will be variances between the resistor values. These variances will skew these numbers and distort your output. For the time being I will let this slide and use what I have on hand as a proof of concept. As I refine this circuit however, I will have to make allowances for this. This can be done by either testing a large number of resistors to find ones which most closely match your target resistance or adding trimmer pots to fine tune the resistances in the ladder.

Test Code

I feel like the functionality of this converter becomes clear when you see it in action. To that end I want to set up some code to test it out.

#define PIN_8 8
#define PIN_9 9
#define PIN_10 10
#define PIN_11 11

int DAC_bus[] = {PIN_8, PIN_9, PIN_10, PIN_11};

void test_run();

First up are some definitions and declarations. The first set of definitions set up my digital pins. Once they are defined I place the pins in an array to keep things organized. Finally I define a test_run function which I will use to run a simple test on the converter.

void setup() {
  for (int k = 0; k < 4; k++){
    pinMode(DAC_bus[k], OUTPUT);
  }

In the setup function I iterate through the DAC_bus and set each pin to output.

void loop() {
  test_run();
}

void test_run(){
  for (int i = 0; i < 4; i++){
    digitalWrite(DAC_bus[i], HIGH);
    delay(5);
    }
  for (int i = 0; i < 4; i++){
    digitalWrite(DAC_bus[4-i], LOW);
    delay(5);
    }
  }

Finally we create the test_run function and call it in the main loop. The test run function sets each of the pins to high 5ms apart then sets each pin back to low.

Test 1 Output

Looking at the output of this simple test you can distinctly see the pins being turned on and off and the corresponding changes in voltage.

Saw Tooth

These voltage levels only begin to tell the story. By turning different combinations of pins on and off we can actually achieve 16 distinct voltage levels (including 0V). To show this I wrote a second test function which draws a saw tooth wave.

void test_run2(){
  for (int i = 0; i < 15; i++){
    int value = i;
    for (int k = 0; k < 4; k++){
      digitalWrite(DAC_bus[k], value%2);
      value = value/2;
    }
    delay(1);
  }
}

This one may look a bit strange if you haven’t worked extensively with binary numbers. This is something I’ll explore further when we start drawing wave forms. Essentially what’s happening though is we are counting from zero to 15, converting each number to binary and writing those binary numbers to the digital pins. The output I received running this second test were as follows:

Test 2 Output

Here we can see the wide variety of voltages we can obtain with only 4 digital channels. With a little filtering we could turn this into a fairly workable saw wave.

This output also illustrates the issue with high tolerance resistors. In an idealized version of this converter this saw wave would look like a perfect staircase. Each step up would be of equal voltage. In our output we can see this is not the case. This is likely due to variations in the resistor values I used build the converter. In future posts I will look at refining my circuit to improve this performance.

The Code

I’m going to finish things off today by providing the full code to get this up and running. There are a lot of places I can go from here but I hope this introduction gives a brief illustration of how R2R DACs work and provides some idea of what we can accomplish with them.

#define PIN_8 8
#define PIN_9 9
#define PIN_10 10
#define PIN_11 11

int DAC_bus[] = {PIN_8, PIN_9, PIN_10, PIN_11};

void test_run();

void test_run2();

void setup() {
  for (int k = 0; k < 4; k++){
    pinMode(DAC_bus[k], OUTPUT);
  }

}

void loop() {
  test_run2();  
}


void test_run(){
  for (int i = 0; i < 4; i++){
    digitalWrite(DAC_bus[i], HIGH);
    delay(5);
    }
  for (int i = 0; i < 4; i++){
    digitalWrite(DAC_bus[4-i], LOW);
    delay(5);
    }
  }

//saw tooth test function
void test_run2(){
  for (int i = 0; i < 15; i++){
    int value = i;
    for (int k = 0; k < 4; k++){
      digitalWrite(DAC_bus[k], value%2);
      value = value/2;
    }
    delay(1);
  }
}

Arduino Function Generator

Alright… We’ve put the work in, lets bring this one home. We’ve got a fairly reliable (if a little bit low res) sine wave generator, but we can make our Arduino do a lot more. Today I’d like to modify my Arduino based sine wave generator to output a variety of predefined waveforms.

To accomplish this I need two things. First I need to program a button to let me select a waveform. Then I’ll need to create tables for these additional waveforms and implement logic to pull values from the correct table.

The Circuit

Arduino Function Generator Circuit

The circuit for this one is essentially the same as the circuit from my last post. The only change I’ve made is the addition of a push button connected between pin 2 on the Arduino and ground. In the code I will set this pin to “pull up” meaning the pin is kept high until the button is pressed. When the button is pressed the pin is connected to ground which will force it low.

Polling Vs Interrupts

When setting up the button press I have two choices. We can either use polling to check for a button press or set up an interrupt. In polling we would add a check in the main loop so that each time the Arduino cycles through the loop it will check the status of the button. This option is very easy to implement but is not terribly efficient.

The analogy I often hear is to imagine you are waiting for a phone call. Polling would be the equivalent of disabling your ringer and checking the phone every 30 seconds to see if the call is coming in. There are a few obvious issues with this approach. What if the call comes in in between the times when you check? you would miss it. Further what if you have a homework assignment your trying to get done at the same time? You wouldn’t make much progress if you stopped every 30 seconds to check your phone.

A better option would be to turn your ringer on and set your phone to the side while you work on other things. This is what happens when we set an interrupt. We tell the Arduino to let us know when an event happens. When something does happen the Arduino takes note of what it’s working on, stops, and proceeds to take care of the instructions we left it for the event.

Setting up an Interrupt

There are a few steps to set up an interrupt for the button press. First I define the pin and create a variable for the pins state. Notice I use the keyword volatile to communicate to the Arduino that this value may change at any time.

#define SWITCH_PIN 2         //Push button to switch waveform
volatile int switch_state = HIGH;

Next comes the setup function for the Arduino. Here I need to set the pinMode. I set this pin as an INPUT_PULLUP so that the pin is held high until the button is pressed.

Also in the setup we will call the attachInterrupt function. This tells the Arduino how to handle this pin. This function takes three arguments. The first of these sets the pin we are attaching the interrupt to. The second gives the name of the function to be called when the interrupt happens. The third identifies the event at the pin which will trigger the interrupt, I have used FALLING here meaning the Arduino will trigger the event when the pin goes from high to low.

void setup() {
  pinMode(SWITCH_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(SWITCH_PIN), switch_pin_ISR, FALLING);
  
  get_sine_table();
}

Finally I need to implement the function mentioned in the setup (switch_pin_ISR). My goal here is to use a new variable (table) to track what table is being used. When the button is pressed I want this variable to increment by one which will tell the main loop to start pulling from the next waveform’s table (more on this later). Additionally I don’t want this variable to ever go beyond the number of tables I have so I will use the modulo operator. This ensures that if the variable reaches beyond the number of tables I have defined it will reset to zero.

int table = 0;
/* Identifies current waveform table
 * 0 - Sine
 * 1 - Right Saw
 * 2 - Left Saw
 * 3 - Triangle
 */


void switch_pin_ISR(){
  table = (table + 1) % 4;
  }

Tables Tables Tables

Now that I’ve built up the logic to handle the button control I’d better set up some tables to create the different waveforms. At the time of writing I have 4 waveforms I’m using. These are the sine we originally created, right and left biased saw waves and a triangle. I generate each of these during the set-up function.

int sine_table[100];
int rsaw_table[100];
int lsaw_table[100];
int triangle_table[100];


void setup() {
  pinMode(SWITCH_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(SWITCH_PIN), switch_pin_ISR, FALLING);
  
  get_sine_table();
  get_rsaw_table();
  get_lsaw_table();
  get_triangle_table();
}

For each wave I have created a function to create the table. The logic behind these waveforms is fairly straightforward. For the right sine wave I created loop from 0 to N setting each value to i*(255/N). The left sine is identical except that I subtract the result of that equation from 255 to invert the result. The triangle is slightly more interesting, I used an if statement to separate the values before N/2 from those after. Those before I set equal to i*(255/(N/2)). Those after I set equal to 255- i*(255/(N/2)).

void get_sine_table(){
  for (int i = 0; i < N; i++){
    sine_table[i] = 127+127*sin(i*(2*3.14)/N);
  }
}

void get_rsaw_table(){
  for (int i = 0; i < N; i++){
    rsaw_table[i] = i*(255/N);
  }
}

void get_lsaw_table(){
  for (int i = 0; i < N; i++){
    lsaw_table[i] = 255 - i*(255/N);
  }
}

void get_triangle_table(){
  for (int i = 0; i < N; i++){
    if (i<(N/2)){
      triangle_table[i] = i*(255/(N/2));
      }
    else{
      triangle_table[i] = 255 - (i-N/2)*(255/(N/2));
      }
  }
}

If the logic of these functions seems unclear don’t worry. These kind of algorithms are not necessarily intuitive at first. My best advice is to work through them, take an N value of 5 and calculate the result for each i less than N. Remember that a value of 0 equates to 0V output and 255 equates to 5V output. Your results should mimic the desired waveform.

The Switch

The final piece of this puzzle comes in the main loop. We have tables for each waveform, a variable to track which table we’re using and an interrupt to modify that variable. Now we just have to read that variable and pull our PWM values from the correct table. Here I’ve used a switch statement. If you’ve programmed mostly in Python or Java you may not have encountered switches before. A switch is essentially a clean way to write a very ugly if else statement. We define a variable to evaluate and then give a list of “cases” for different values of that variable. Each case describes the actions to take if the variable equals that value. If you’d like to learn more about switch statements Geeks for Geeks have a great article about them.

void loop() {
  for (int i = 0; i < N; i++){
    sample_time = analogRead(ANALOG_0);
    sample_time = (sample_time/16)+2;

    switch (table) {
      case 0:
        analogWrite(PWM_PIN, sine_table[i]);
        break;

      case 1:
        analogWrite(PWM_PIN, rsaw_table[i]);
        break;

      case 2:
        analogWrite(PWM_PIN, lsaw_table[i]);
        break;

      case 3:
        analogWrite(PWM_PIN, triangle_table[i]);
        break;


      
      }
      
    delay(sample_time);
  }
}

All The Code

With that we’ve done it! We’ve turned our Sine Wave Generator into a proper function generator. There’s no reason to stop here though, I’ve only scratched the surface of the available waveforms. Additionally there are better filters and better algorithms begging to be explored. Now that I have this up and running I’d also like to spend some time in a future post exploring how to interface it with other oscillators to use it as an LFO. For today I’ll finish up by providing my code in full, Take care. I’ll see you all soon.


/*
 * www.SamVsSound.com
 * Arduino PWM Function Generator
 * 11/14/2020
 */

#define PWM_PIN 5            //PWM output at pin5
#define ANALOG_0 A0          //Input for sample_time
#define SWITCH_PIN 2         //Push button to switch waveform

#define PWM_FREQ  980        //Hz
#define N 100

int sine_table[100];
int rsaw_table[100];
int lsaw_table[100];
int triangle_table[100];

volatile int switch_state = HIGH;

int table = 0;
/*
 * 0 - Sine
 * 1 - Right Saw
 * 2 - Left Saw
 * 3 - Triangle
 */


int sample_time;

void get_sine_table();
void get_rsaw_table();
void get_lsaw_table();
void get_triangle_table();

void setup() {
  pinMode(SWITCH_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(SWITCH_PIN), switch_pin_ISR, FALLING);
  
  get_sine_table();
  get_rsaw_table();
  get_lsaw_table();
  get_triangle_table();
}

void loop() {
  for (int i = 0; i < N; i++){
    sample_time = analogRead(ANALOG_0);
    sample_time = (sample_time/16)+2;

    switch (table) {
      case 0:
        analogWrite(PWM_PIN, sine_table[i]);
        break;

      case 1:
        analogWrite(PWM_PIN, rsaw_table[i]);
        break;

      case 2:
        analogWrite(PWM_PIN, lsaw_table[i]);
        break;

      case 3:
        analogWrite(PWM_PIN, triangle_table[i]);
        break;


      
      }
      
    delay(sample_time);
  }
}

void switch_pin_ISR(){
  table = (table + 1)%4;
  }

void get_sine_table(){
  for (int i = 0; i < N; i++){
    sine_table[i] = 127+127*sin(i*(2*3.14)/N);
  }
}

void get_rsaw_table(){
  for (int i = 0; i < N; i++){
    rsaw_table[i] = i*(255/N);
  }
}

void get_lsaw_table(){
  for (int i = 0; i < N; i++){
    lsaw_table[i] = 255 - i*(255/N);
  }
}

void get_triangle_table(){
  for (int i = 0; i < N; i++){
    if (i<(N/2)){
      triangle_table[i] = i*(255/(N/2));
      }
    else{
      triangle_table[i] = 255 - (i-N/2)*(255/(N/2));
      }
  }
}

Sine Waves on Arduino: Variation

Today Ill be building on my Arduino Sine Wave Generator project. My goal is simple, to add the ability to dynamically change the frequency of the wave being generated. I should be able to read the value from a potentiometer similar to what was used in my original Arduino PWM post and write that value into the delay variable to modify the timing.

Wiring it Up

Arduino Function Generator Wiring

The wiring for this one is pretty straight forward and nothing we haven’t seen before. On the left is a potentiometer connected between 5V and ground. The wiper of this potentiometer is connected to analog pin A0 on the Arduino. This pin will provide an input value between 0 and 1023 depending on the position of the pot.

On the right we have the digital pin 5 connected through the same low pass filter I’ve used in previous projects. This will take our PWM output and smooth it into the final waveform.

The Code

The code only needs some slight modification from my last post. We need to first define the analog pin and read its value using analogRead. This is where some choices need to be made though. I mentioned that the analogRead for the potentiometer gives us a value from 0 to 1023. If we were to write this directly to the sample_time variable we would be producing some extremely long sine waves. Since our sine table has 50 entries this would mean at the highest setting each wave would take 51.15 seconds (1023*50/1000) to complete. That might be a bit much. So we need to decide how large a range we want to use and process the input accordingly.

I chose to divide the input by 16, this gives me a frequency range from about 10Hz to 0.313Hz. In the code you’ll notice I added a hard limit at 10Hz by adding 2 to the input value. This ensures the delay time never drops below a range that the Arduino and our filter can handle.


#define PWM_PIN 5            //PWM output at pin5
#define ANALOG_0 A0          //Input for sample_time
#define PWM_FREQ  980        //Hz
#define N 50

int sine_table[50];
int sample_time;
void get_sine_table();

void setup() {
  get_sine_table();
}

void loop() {
  for (int i = 0; i < N; i++){
    sample_time = analogRead(ANALOG_0);
    sample_time = (sample_time/16)+2;
    analogWrite(PWM_PIN, sine_table[i]);
    delay(sample_time);
  }
}

void get_sine_table(){
  for (int i = 0; i < N; i++){
    sine_table[i] = 127+127*sin(i*(2*3.14)/N);
  }
}

And there you have it! We can now adjust our frequency on the fly. Sorry it’s a bit of a shorter post today life’s been pretty full of late. Still I think this marks a pretty substantial step forward in this project. In my next post I’ll be looking at implementing the ability to produce more waveforms beyond just the sine.

Sine Waves On Arduino: Cleanup

In my last post I used a simple low pass filter to start generating sine waves on my Arduino Uno. The code I wrote for this project probably seems pretty clear since the program is so basic. However in my haste I took a number of shortcuts which will lead to the code becoming confusing and inefficient as I start adding complexity. Today I’m going to work on cleaning up this code by discussing some best practices. I know this isn’t as exciting as moving forward with the project but it is important. This cleanup will save me a lot of time in future by making sure I am starting with, and continuing to write, simple, efficient and readable code.

I’ll be going through these changes one by one in the body of this post. At the end of the post I’ll provide the new code in it’s entirety for your review.

Table Lookups

void loop() {
  for (i = 0; i < N; i++){
    duty_cycle = 127+127*sin(i*(2*3.14)/N);
    analogWrite(PWM_out, duty_cycle);
    delay(sample_time);
  }
}

Above I’ve shown the original loop I wrote for this program. For each step of the sine wave this loop calculates the value of sine, writes that value to the PWM and delays for a given time. The issue here is that any calculations we are doing at runtime take time. That means every time we calculate our duty cycle there is a small delay. This extra delay will cause our frequency to become less accurate.

A better solution is to use a look-up table. By conducting all of our calculations before hand and storing the results we can remove the equation from the main loop. To do this I’ll first initialize a table and then calculate it’s values in our setup function:

int sine_table[50];

void setup() {
  for (i = 0; i < N; i++){
    sine_table[i] = 127+127*sin(i*(2*3.14)/N);
  }
}

Once I’ve set up a table in this way I can simply set the PWM value based on the index of this table in our main loop:

void loop() {
  for (i = 0; i < N; i++){
    analogWrite(PWM_out, sine_table[i]);
    delay(sample_time);
  }
}

Function Extraction

void setup() {
   for (i = 0; i < N; i++){
     sine_table[i] = 127+127sin(i(2*3.14)/N);
   }
 }

Looking back at our setup function you may not see any issues. Currently it looks pretty clean. What happens though when I start doing more than just this one thing during startup? Imagine if we were initializing several wave tables, this would start to get pretty ugly pretty fast.

The technique we use here is called function extraction. Basically the idea is to create functions within your program to handle each specific task your program does. This allows you to move code specific to those tasks out of your main code. Doing this will not change the functionality of the code but makes the code significantly more clear and readable, especially as your program grows more complex.

void get_sine_table();  

First we declare our new function at the top of the code (with the global variable definitions).

void get_sine_table(){
  for (i = 0; i < N; i++){
    sine_table[i] = 127+127*sin(i*(2*3.14)/N);
  }
}

Next we can implement the function at the end of our code. Notice the contents of this function are the same as what we originally had in our setup.

void setup() {
  get_sine_table();
}

Finally we update our setup to call this function. Notice how much clearer this is. By giving the function a descriptive name we can now tell exactly what is being done in the setup.

Variables vs Definitions

int PWM_out = 5;           //PWM output at pin5

int sample_time = 2;       //ms
int PWM_frequency = 980;   //Hz
int N = 50;
int duty_cycle;            //unitless
int sine_table[50];

Next I’d like to have a look at the variable definitions of this program. These variables can be roughly separated into two categories, those which change during runtime and those that do not. Those which change are best stored as global variables however those which don’t we can handle in a better way.

When a variable is defined a location in memory is set aside for it and every time it is accessed that memory location is read (when the variable is called) or written to (when the variable is changed). This means each variable we have in the code is taking up a small amount of our system memory and each time we access them it takes time (though an infinitesimally small amount).

Using the keyword #define we can bypass this process for static variables. Define is what is known as a preprocessor directive. That’s a fancy way of saying that it is not an instruction for your Arduino, it is an instruction for the compiler which builds your program and sends it to the Arduino. When you build your program the compiler will search the code for any instances of the name you defined and replace it with the value given. this means rather than having to store and access a variable in the program the value is directly written into the code. All the while maintaining the ease of use and readability that having the value named provides.

#define PWM_PIN 5            //PWM output at pin5
#define SAMPLE_TIME 2        //ms
#define PWM_FREQ  980        //Hz
#define N 50

int sine_table[50];

Above I have changed all variables that do not need to be modified at runtime to definitions. Notice I also removed the duty cycle variable. Since I’m setting the value of the PWM directly from the table it is not needed.

Putting it Together

//www.SamVsSound.com 11/08/2020

#define PWM_PIN 5            //PWM output at pin5
#define SAMPLE_TIME 2        //ms
#define PWM_FREQ  980        //Hz
#define N 50

int sine_table[50];

void get_sine_table();

void setup() {
  get_sine_table();
}

void loop() {
  for (int i = 0; i < N; i++){
    analogWrite(PWM_PIN, sine_table[i]);
    delay(SAMPLE_TIME);
  }
}

void get_sine_table(){
  for (int i = 0; i < N; i++){
    sine_table[i] = 127+127*sin(i*(2*3.14)/N);
  }
}

Here we have our new cleaner code. I know with a program this small these changes are not striking. Still, you can imagine the difference these will make as we add complexity going forward. I’m sorry this turned into more of a coding tutorial than an audio project but I’ll be back soon to start building this project up into something cool.

Sine Waves on Arduino

I’ve spent the last few weeks going over the fundamentals of PWM and implementing them on my Arduino Uno. Today it’s time to apply those basics to something a little more interesting. I want to get my Arduino outputting sine waves. I’m going to focus on creating a workable 10Hz sine wave and then in forthcoming posts I’ll look at manipulating the frequency and modelling more interesting wave-forms.

Know Thy Limits

Before I go to far into this project I want to talk a little bit about the limitations of the Arduino. The Arduino has a maximum PWM frequency of 980Hz which is quite low, especially when working in the audio space. As an example if I wanted a sin wave with a frequency of 100Hz I would only be able to use approximately 10 PWM cycles per sine wave. The fewer cycles you have per wave the more misshapen your output wave will be. I’ve had some success creating “relatively” clean 100Hz waves but going much higher than this results in the wave breaking down entirely.

One nice thing about the sine wave is that the changes in voltage through the wave are continuous. This means we can push our samples much closer than the normal settling time discussed in my last post. However, the idea of creating an full audio oscillator with this method is an impossibility. An LFO or envelope generator though are still realistic goals.

If you are interested in creating an audio oscillator using your Arduino I would recommend looking into off-board DACs (Digital to Analog Converters) which use serial communication with the board to provide much higher output speeds and resolutions.

The Filter

Low Pass Filter With RC=0.0047

To get started I set up an RC Low Pass Filter. After the experiments in my last post I settled on an RC value of 0.005 (or 0.0047 more accurately). This should give me a good balance between stability and low settling time. I used a 47K ohm resistor and a 0.1uF capacitor to accomplish this.

The Sine Wave

Sine Wave Equation with DC Offset

I want to have a quick look at the sine wave equation before I start coding. There are a number of variables which we can use to adjust the waves properties. The first thing to note is the variable n. If you’ve worked with continuous sine waves you may have seen this formula as a function of t. Where t represents time (a continuous variable), n represents discreet samples. This means n will always be a whole number (0, 1, 2, …) which lends itself to working in a digital environment.

The next variable we have to look at is w which represents the angular velocity (also called normalized frequency depending on your background). This represents how quickly your sine wave will move through a full cycle. We can determine the value for w with the following formula:

In the above formula N represents the total number of samples it will take to traverse a full cycle of the sine wave.

Next up is A which is known as the amplitude or scaling factor of the wave and C which represents the offset. A typical sine wave varies between 1 and -1 centered at 0. However, on the Arduino the duty cycle of a PWM signal is set by an integer between 0 and 255. To get our sine wave to fill this range we first multiply the sine wave by 127 (A). This creates a wave which varies between -127 and 127. Next we add the offset of 127 (C) to the output which gives us our final sine values between 0 and 254.

Choosing Your Frequency

Two factors affect the frequency of the sine wave. N (Discussed above) is the first. If you are moving through your samples at a constant rate the more samples you have the longer it will take. The trade off here is as you might imagine, the more samples you have the cleaner your sine wave will look.

Sample time (given in ms) is the other. This is the time the Arduino will wait between each step of the sine wave. This again is something of a balancing act as you must allow enough time for your signal to stabilize at each new voltage level.

Taken together we can create the following formula to determine our final frequency:

Discreet Frequency Calculation

You may recognize that this is essentially the calculation to find frequency from the period (f = 1/p). In this equation N*(sample time) represents the period (the number of samples * the time it takes for each sample). Since sample time is in ms we use 1000 as a conversion factor.

The Code

Now that we’ve got everything set up it’s time to write the code. I’ll start out by declaring the necessary variables:

int PWM_out = 5;           //PWM output at pin5

int sample_time = 5;       //ms
int N = 20;                //int
int duty_cycle;            //unitless

int i;                     //Counter variable

Here you can see I’ve set the sample_time to 5 and N to 20. Using the formula I showed earlier this should give me a frequency of 10Hz (1000/(5*20) = 1000/100 = 10Hz).

For this program I don’t need to run any kind of set-up. That means I can leave the set-up block blank:

void setup() {
}

Next comes our main loop where all the magic happens:

void loop() {
  for (i = 0; i < N; i++){
    duty_cycle = 127+127*sin(i*(2*3.14)/N);
    analogWrite(PWM_out, duty_cycle);
    delay(sample_time);
  }
}

Lets go through this one in a bit more detail. First I set up a for loop which will iterate through the code N times incrementing i each time.

Next I calculate the duty_cycle value using the sine wave equation. Notice I have placed the angular velocity equation directly inside the sine equation (2*pi/N) to simplify the line. From there we write that duty cycle value to the PWM_out pin (pin5) using analogWrite.

Finally there is a delay command. The delay waits for the amount of time defined by sample_time before beginning the next iteration of the loop.

10 Hz Sine Wave From Arduino

And there we have it. As you can see from my oscilloscope output the wave is far from perfect, nonetheless we’ve created an analog sine wave using a digital microcontroller! This is no small accomplishment and I can’t wait to build on it further. I encourage you all to set up this code and play around. Try changing the variables and values to see how each impacts the design. I’ll be back soon with more!

Filtering PWM: Continued

In an earlier post I spoke in a fairly abstract way about filtering Pulse Width Modulated signals. I explained how when using a basic RC filter we have to compromise between the stability of the DC output and the time needed for the filtered signal to reach the average voltage of the source. Today I’d like to return to this problem with a slightly more analytical approach. My goal in doing this is to show you the process I will use to select the filter values for my Arduino PWM project.

Since this is ultimately for my Arduino based project I will be using a frequency of 980Hz for my calculations. This gives me a period of 0.00102s per cycle.

The Method

Step Response Equation for RC Circuits

My approach to this problem is fairly straightforward, if a bit computationally expensive. By using the step equation for voltage I introduced in my post regarding the step response of RC circuits, I should be able to move through each step of the PWM signal for a given RC value until the high and low voltages stabilize. Each step I will set V0 as the output of the last step and Vs to 0 or 5 Volts (Based on whether the step is up or down). At that point I can note how many steps it’s taken and what the remaining peak to peak voltage is. For my initial calculations I will use a duty cycle of 50% meaning a step occurs every 0.00051s.

Crunching Some Numbers

I started out attempting to do this project in Excel. I set up a cell formula and began populating results but before I knew it my table had grown well beyond a workable size and I decided to step back and regroup.

My solution was to write a python script that given a frequency, duty cycle, array of RC values and high/low voltage values would run the calculations for me and output a plot of the resulting ripple voltages and stabilization (settling) times. I will add my code at the end of this post so you can play with it yourself.

I started out with a fairly wide range of RC values from 0.0001 to 0.1 and stopped the calculations when the high voltage was within 0.01mV of the previous high voltage. This gave me the following two plots:

RC Values vs Ripple Voltage and Settling Time

Here we can get an idea of the nature of these two values. We can identify that (as expected) the ripple exponentially decreases as the RC value increases. Meanwhile the settling time appears to be a fairly linear function increasing as the RC values increase. It is also clear looking at these graphs that my initial range was much too large. I am going to eliminate all RC values where the peak to peak voltage is far greater than 1V by starting the scale at RC = 0.001. Meanwhile I will eliminate all values with a settling time greater than 0.1s (approximately RC = 0.01). Additionally I modified the voltage resolution to be 10mV.

RC Values vs Ripple Voltage and Settling Time (Modified Range)

This has made the picture significantly clearer. Particularly with the voltage ripple we can now see the slope of the exponential decay.

Sanity Check

Low Pass Filter Simulation Circuit

Before finishing up for today I wanted to make sure my math made sense. To do so I built a simple RC filter in NI Multisim and fed it a steady square wave signal at 980Hz. I chose an RC of 0.006 which should give me a peak to peak voltage after filtering of 0.2V and a settling time of approximately 0.024s (24ms). The output I received from the oscilloscope was as follows:

Ripple Voltage Test

The peak to peak voltage of the ripple appears to be just over 200mV (0.2V) which is exactly what we predicted!

Settling Time Test

The settling time is a little bit more up to interpretation. I found based on how I set the v_resolution in my program (value that v_high – v_high_last must be under to be seen as stable) I got profoundly different values for this reading. Basically what’s happening is that the output voltage is exponentially increasing towards the average voltage. This means even though the increases stop being visible on the oscilloscope output they are still proceeding each step in exponentially smaller and smaller amounts. That being said we can see that within the 25ms timeframe the output has absolutely stabilized. In practice we can likely get by with a much smaller timeframe based on the oscilloscope output above.

That’s probably enough science for today. I’ll be building further on these concepts in my next post where I will be filtering the PWM signal from my Arduino to see what I can create with it.

Code

Finally as promised here is the code I used for these calculations. Full disclosure I am not a software designer by any stretch so this may not be the prettiest program in the world but I hope it is helpful.

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import math
import pandas as pd


#Generate an array of rc values between rc_start and rc_stop with a step size of rc resolution
def create_rc_array(rc_start, rc_stop, rc_resolution):
    array = np.arange(rc_start, rc_stop, rc_resolution, dtype=float)
    return array


#Calculates period, time high and time low based on frequency and duty cycle
def get_period(frequency, duty_cycle):
    period = 1/frequency
    time_high = period*duty_cycle
    time_low = period*(1-duty_cycle)

    return period, time_high, time_low


#Given starting voltage, final voltage, rc and time solves step responce equation
def v_calc(v0, vf, rc, time):
    exponent = -(time/rc)
    v1 = vf
    v2 = v0 - vf

    return v1 + v2*math.exp(exponent)


#Iterates through list of rc values
#For each rc value will calculate v_high and_v_low for each step until v_high-v_high_last < v_resolution
def generate_values(rc_values, period, time_high, time_low, v_resolution, v_low, v_high):
    delta_v_list = []
    settling_times = []

    for rc in rc_values:
        time = 0
        v_start = v_low
        v_up_old = 5
        v_up = 0
        v_down = 0
        delta_v = 5
        while abs(v_up_old - v_up) > v_resolution:
            time = time + period
            v_up_old = v_up
            v_up = v_calc(v_down, v_high, rc, time_high)
            v_down = v_calc(v_up, v_low, rc, time_low)
            delta_v = abs(v_up-v_down)

        delta_v_list.append(delta_v)
        settling_times.append(time)

    return delta_v_list, settling_times


def main():
    #Declare parameters
    frequency = 980
    duty_cycle = 0.5

    rc_start = 0.001
    rc_stop = 0.01
    rc_resolution = 0.00001

    v_low = 0
    v_high = 5
    v_resolution = 0.01

    #create derived values
    rc_values = create_rc_array(rc_start, rc_stop, rc_resolution)
    period, time_high, time_low = get_period(frequency, duty_cycle)
    
    #Run calculations
    delta_v_list, settling_times = generate_values(rc_values, period, time_high, time_low, v_resolution, v_low, v_high)


    #Plotting
    sns.set_theme()

    ripple_frame = pd.DataFrame({'RC Values (1/s)': rc_values, 'Peak to Peak Voltage Ripple (V)': delta_v_list})
    settle_frame = pd.DataFrame({'RC Values (1/s)': rc_values, 'Settling Time (s)': settling_times})

    fig, ax = plt.subplots(1,2)

    sns.lineplot(x='RC Values (1/s)', y='Peak to Peak Voltage Ripple (V)', data=ripple_frame, ax=ax[0])

    sns.lineplot(x='RC Values (1/s)', y='Settling Time (s)', data=settle_frame, ax=ax[1])


    plt.show()



main()