Try not to focus on how the speaker works, but on sound.
Sound is a waveform, with different frequencies and some other stuff.
Our goal is to simulate a wave by output 1's and 0's since this will make the speaker move and create the wave.
But since we only got 1 and 0 we can not have a perfect smooth wave and won't have uber quality sound.
But you will have sound
What you need to focus on is creating the wave. You will need to know some details of the serial port in order to be able to create the frequencies you want.
The serial speed is 115200 baud, which is changes/sec. Its like bits/s, but not really.
So, how do we create our wave with 'x' Hz and playing 't' long?
First of all you need to know that Hz is cycles/second. To put this simple that means 500ms of 0's and 500ms of 1's.
Now lets first calculate how many bits we need to send to create one wave of 'x' Hz.
115200/x
That means we need 57600/x bits of 0 and 57600/x bits of 1.
Lets create some pseudo code for that
function wave(x){
am = 57600/x;
sendBits(0, am);
sendBits(1, am);
}
Imagine that
sendBits(bit, amount) sends 'bit' 'amount' times to the port.
Now, this is only one wave. To play it 't' long we need to repeat it x*t times
function wave(x, t){
am = 57600/x;
for (i=0; i<x*t;i++){
sendBits(0, am);
sendBits(1, am);
}
}
But, actually we only can send bytes to the serial port.
Now its important to know that 1 byte is actually
10 because of some extra flag bits in the protocol.
Lets change the code for bytes
function wave(x, t){
am = (57600/x)/10;
for (i=0; i<x*t;i++){
sendBytes(\x00, am);
sendBytes(\xFF, am);
}
}
I use \x00 as 0 and \xFF as 1.
Now, this should be enough to understand it (I hope)