Home DIY or DIY PIC16F1503. A car for a ride – 1. Sound

PIC16F1503. A car for a ride – 1. Sound

by admin

I think every parent has that moment when he or she finds a child at the cash register in a store with something , and the child claims that it is this something very important to the whole world on earth and to him in particular. That’s what happened to me once again. On the fly, having assessed the value of this nothings Parental greed waved its hand and decided that we live once and will not earn all the money anyway. The mind, on the other hand, appreciated the speed at which it was dying nothings And gave the go-ahead, too.
As a result, children’s auto park was enriched with such miracle of Chinese engineering. Jeep, with a "chandelier" and a winch!
PIC16F1503. A car for a ride - 1. Sound
The miracle was able to flash "chandelier" and "headlights" and loudly produce three recorded sounds. According to all canons, the car rather quickly "died" and was brought in for repair. I refused to take the car for repair, explaining my refusal by unwashed hands and a half-eaten dinner. In addition the Chinese somehow managed to squeeze out of this machine a few extra decibels at a frequency resonating with my skull (even my teeth ached), so I did not want to experience the same sensations again.
As a result of long negotiations it was decided that a simple change of batteries is no longer fashionable. After all, all the real drivers tune their cars in special studios, after which they drive cars that no one else has. So I took my car to the "All Mine" studio for tuning…
What’s the first thing to do? That’s right, assess the amount of work dumped on us. We disassemble the car.
PIC16F1503. A car for a ride - 1. Sound
Inside are three LEDs (blue, bright, cheap), a squeaker, and an unknown shell-less "Chinese snot" class microcontroller. All this is powered by 3 LR4 batteries (capacity about 20mAh), so no wonder that the machine died so quickly. All this splendor is started by a button, which in the best traditions of the Chinese car industry jams and bites.
Anyway, you have to change everything. Or almost everything. With what?
Of course, I wouldn’t mind sticking an STM32F4 inside the machine, but the evaluation board won’t fit inside, and the under this circuit board is frankly lazy. I searched through my drawers and found a PIC16F1503-based demo board. It has up to 16 MHz, 3kb Flash and 128 bytes of memory. Perfect for the machine!
If you want to repeat my exercises, you need to search for PIC-H1503 (the microcontroller itself) and PIC-KIT3 (the programmer) from Olimex. You will also need to download and install MPLAB X Ide and XC8 from microlab website. Unlike the OT, it supports Windows, Linux and OS X.
Where do we start with the tuning? That’s right, let’s start like everyone else, with the sound. We don’t need to make it louder, we need to make it "police-like" and not loud.
We take the "squeaker" out of the car and try to figure out what it is. If we don’t find any identifying marks, we connect it to an ohmmeter. The ohmmeter reads 15 ohms. So it is a microdynamic : if the ohmmeter showed "breakage", then it is a piezo squeaker.
It makes no sense to connect the speaker directly to the microprocessor pin (15 ohms on 3 volts will give 200mA current, which is obviously not good for the microcontroller, which is 20 enough), so we make a simple circuit on the first NPN transistor we see.
PIC16F1503. A car for a ride - 1. Sound
The ratings are practically irrelevant. The plus or minus from the circuit will make almost no difference. I will explain later why the capacitor in the circuit is needed (in principle you can also connect it parallel to the transistor). We connect the input to the 9th pin of the Microcontroller.
Now it remains to understand how we can extract sound. We know from high school physics that sound is vibrations of air. And the speaker translates vibrations of electricity into vibrations of air. So we have to shake the speaker. But the speaker is directly connected to the microcontroller, which can only output "1" (it’s on a pin) and "0" (nothing). Yes, even (even? that’s rare) this microcontroller has a 5 bit DAC (audiophiles are crazy about the single bit ones, if anything. smail), but it’s not sporty.
Physics saves us again: even if you apply a "1" to the speaker, the magnet will not pull up the cone instantly, nor will it release it instantly after a "0".
The easiest way is to write code like this


If the pauses are counted in milliseconds, then in the speaker we get a "squeak" of 500Hz. And by changing the duration of the pauses you can get quite a decent sound. What’s the problem? The problem is that we will need to be constantly distracted by the "leg twitching".
But in any decent microcontroller there is such a thing as PWM, aka PWM (what is it? easily searchable in the same wikipedia, with pictures and long explanations). It is also available in pikes. Open MPLAB, create a new project and with the Code Configurator (menu Tools-Embedded. You may need to put it in Plugins first) add a new PWM.
PIC16F1503. A car for a ride - 1. Sound
I got the PWM4 solely because of the convenience of the leg. Since the PWM can’t peak without a timer, let’s take a look at it as well.
PIC16F1503. A car for a ride - 1. Sound
Since nothing is clear yet, let’s just click "Generate Code" and try to run what we get. As usual, nothing should happen – there is no program. If you get an error about the VDD, you have to put a checkmark in Run-Project Configuration-PICkit3-Power against Power target Circuit. You can just program the boards "in operation", and the current from the programmer is not always enough to power the circuit.
Let’s type in the first code. Everything is done in main.c, I separated the blocks there with comments.

uint16_t count;for(count=0; count<1024; count++){PWM4_LoadDutyValue(count);__delay_ms(10);}

We pump and connect the oscilloscope with one input to the microcontroller output (blue line) and the other to the speaker (red).
PIC16F1503. A car for a ride - 1. Sound
So, what do we see? The blue line is the result of the PWM. Filling from 0 to 100% and then jumping back to zero. But the red line somewhere in the middle of the filling is remotely similar to a sine wave. To be honest, this remoteness was obtained by attaching a 0.47 μF capacitor in parallel to the transistor, for a nice gif. The real picture can be seen below.
Let’s remove the capacitor.
PIC16F1503. A car for a ride - 1. Sound
See the peaks in the red? That’s the speaker in "reverse" acting as an oscillator and easily kicking in a whole volt when powered by 3s. In principle, under certain conditions it is easy to burn the circuit. But these peaks don’t bother anyone here, so it’s up to you whether to put a capacitor or not. I did it for beauty.
Let’s put it up again. It was already there, but this picture is in static.
PIC16F1503. A car for a ride - 1. Sound
Change to 0.1mcf. Just to compare and show the effect of capacitance on sound 🙂
PIC16F1503. A car for a ride - 1. Sound
Basically we already got a 15 kilohertz squeak, but who needs it except mosquitoes? So we have to turn the frequency. The PWM frequency depends on the timer, and how often the timer will "tick" depends on the counter, which is set each time the timer starts.
So the timer algorithm looks like this
– Starting the timer.
– The timer ticked and decreased the counter.
– Is the counter at zero? If not, then tick again. If yes, generate interrupt.
Interrupt Handler :
– OUCH! The timer ticked!
– Reset the timer again

And now the PWM start is connected to the timer interrupt. And we can rotate both the frequency of the "ticking input" (prescaler in the settings) and the counter value.
Change the code (aka stage2)

uint8_t count;for(count=0;count<256;count++){PWM4_LoadDutyValue(count*2);TMR2_LoadPeriodRegister(count);__delay_ms(100);}

PIC16F1503. A car for a ride - 1. Sound
We look at the beautiful red line and see that we get something remotely like a sine wave, and varying in frequency. Yes, and the ear confirms it. Just what we need!
Why I change the filling of the PWM, I suggest you think for yourself. But in principle, if you mentally continue the graph and slow down the change of one parameter, everything becomes clear. Particularly advanced can see a similar picture in some emulator, for example proteus
Let’s now determine what frequency range we got
Nail count to 255
PIC16F1503. A car for a ride - 1. Sound
And now we put in 10
PIC16F1503. A car for a ride - 1. Sound
Pay attention to the upper right corner where the grid spacing is shown. I got a range of about 300-5000Hz "by eye". Quite. And it won’t "ride" on your skull. Perfectionists can use a frequency meter, or calculate the real value from the clock frequency and prescalers.
And this is where I ran into problems. Any understanding of how the it sound, I don’t have any. To put it crudely, in music, the Chukcha is the reader, but not the writer.
Barely found by half which frequencies correspond to which notes, found some notation of "there was a Christmas tree born in the forest"…
Counted the delays, wrote

#define do 243 //523Hz#define re 239 //587#define mi 236 //659#define fa 231 //739#define sol 229 //783#define la 224 //880#define si 218 //987// and again +523Hzconst uint8_t elka[29]={do, la, la, sol, la, fa, do, do, do, la, la, si, sol, do, do, re, re, si, si, si, la, sol, fa, do, la, la, sol, la, fa};void play(uint8_t p){// 255 - 3ms period - 300Hz// 10 - 0, 2ms - 5000HzPWM4_LoadDutyValue(p*2);TMR2_LoadPeriodRegister(p);}....uint8_t count;for (count = 0; count < 29; count++) {play(elka[count]);__delay_ms(300);PWM4_LoadDutyValue(0);TMR2_LoadPeriodRegister(0);__delay_ms(50);}

Compiled it, ran it. No, the tune is guessed without problems, but it’s not like that. By adjusting resistors and capacitors, I got an "almost sinusoidal sawtooth" output, but the ear hears the difference.
As a result, so far I have settled on the usual two-tone signal: "high-low". The classic police "wow-wow", known to everyone in Hollywood movies, I did not get. And google for "police sirene tones code program example" gives out anything but the right thing.
Help, please? In what sequence does the beeping go there?
Basically, we already came to the point where the next step would be to play a regular wav. That is, don’t bother with tones and stuff. Just record the sound, translate it into a digestible form, and play it back. Just like different ScreamTrackers used to do.
Only one problem: half a second of sound in PCM format, mono, sampled at 8KHz takes about a kilobyte. And I only have three and a half kilobytes. No good. But you can get acquainted with the principles and examples simply by googling "pic pcm sound". From the first link you will find both source code and programs.
So our consolation is that we will have a real, "warm tube sound from those times", which does not require the attention of a programmer: said what frequency to play and went to mind your own business, and there the hardware will do everything.
But sound is half the battle. Good light is also the hallmark of true tuning 🙂 But that’s a little later.
As usual, a ready-made project for MPLAB with all the stuff you can pick up here

You may also like