Physcial Computing Blog

Week 3 - Analog Output

The most prominent thing for me in this week's material was to wrap my head around how pulse width modulation translates into analog output. I was familiar with PWM because I had worked with synthesizers before and the concept of turning it into analog output is interesting. My initial guess was that the length of a pulse would determine the value, but I couldn't figure out how we would get the length. The average of the on time to off time would determine the value of output. I had to review it multiple times to get a grasp of what was happening in the process.

It feels like I'm dealing with the building blocks of a synthesizer. It's so fascinating to see the bare minimum needed to convert an electric current into sound, I had no mental image of what was happening inside a synth or an electronic instrument, now it makes sense and I can see how it would happen without any magic going on. I imagined a sequencer in my head and tried to imitate that behaviour using code, the tone goes up in fifths (kind of) and when it gets too high it starts from 100Hz higher than the base 440Hz, and resets once the base frequency gets too high. One challenging bit for me is the period and how it relates to frequency. I think in simple words a period is the time it takes for the speaker to go back and forth and to rest position and frequency is how many times a second that period can happen.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
float i = 1.5;
int duration = 100;
float freq = 440.0;
float toneFreq = 440.0;

void setup() {
}

void loop() {
  toneFreq = toneFreq*i;

  if(toneFreq>10000) {
    freq = freq + 100.0;
    toneFreq = freq;
  }

  if(freq>2000){ 
    freq = 440.0;
    toneFreq = freq;
  }

  tone(8, toneFreq, duration);
  delay(duration);
}

Nima Niazi