I think every parent has such a moment when he discovers a child with
something in the store at the checkout counter, and the child claims that this is
something very important for the whole world on earth and for him in particular. So I have this happened again. On the move, having estimated the cost of this
neht , the parental toad gave up and decided that we once lived and still could not make all the money. Reason also appreciated the speed of dying of this
dumb and also gave the go-ahead.
As a result, the children's car park has been replenished with such a miracle of Chinese engineering. Jeep, with a "chandelier" and a winch!

')
Miracle skillfully blink "chandelier" and "headlights" and loudly produce three recorded sounds. According to all canons, the machine “died” pretty quickly and was brought in for repair. I refused to take the car for repairs, citing the refusal with unwashed hands and half-eaten dinner. Plus, the Chinese somehow managed to squeeze a couple of extra decibels out of this machine at a frequency resonating with my skull (my teeth ached), so I didn’t smile at all to re-experience the same sensations.
As a result of long negotiations, it was decided that a simple battery change is no longer fashionable. After all, all real drivers tyunyut their cars in special studios, after which they drive cars that no one else has. So I took the car to the studio "All Mine" for tuning ...
What is the first thing to do? That's right, estimate how much work has fallen on us. We disassemble the car.

Inside there are three LEDs (blue, bright, cheap), a squeaker and an unknown boxless microcontroller of the “Chinese snot” class. All this is powered by 3 LR4 batteries (capacity in the region of 20 mAh), so it is not surprising that the car died so quickly. All this splendor is triggered by a button, which, in the best traditions of the Chinese automotive industry, seizes and bites.
In general, here it is necessary to change everything. Or almost everything. For what?
Of course, I would not mind sticking the STM32F4 inside, but the estimated board wouldn’t get inside, but it’s really lazy to plant
a printed circuit board
under it . Rummaging in the boxes, I found a demo card on the PIC16F1503. Up to 16 megahertz, 3 kilobytes of flash and already 128 bytes of memory. The most it for cars!
If you wish to repeat my exercises, then you need to look for according to PIC-H1503 (this is the microcontroller itself) and PIC-KIT3 (this is a programmer) from Olimex. It will also be necessary to download and install MPLAB X Ide and XC8 from microlab. Unlike OT, Windows, Linux and OS X are supported.How to start tuning? That's right, let's start with the sound. Louder we do not need, we need to be screaming "in a police manner" and not loudly.
We get out of the machine "pishchalku" and try to understand what it is. Not finding any identification marks, we cling to the ohmmeter. Ohmmeter shows 15 Ohms. So, microdynamic: if an ohmmeter showed a "break", then this is a piezo squeaker.
Connecting the speaker directly to the microprocessor's foot is meaningless (15 ohm at 3 volts will give a current of 200mA, which the microcontroller, which is 20 over the eyes), obviously, so we make a simple circuit on the first NPN transistor.

Ratings are almost not important. Plus or minus from the scheme will bring almost no changes. Why the capacitor on the circuit, I will explain later (in principle, you can stick and parallel to the transistor). The input is connected to the 9th leg of the microcontroller.
Now it remains to understand how we extract the sound. From a school course in physics, we know that sound is the vibration of air. And the speaker translates the fluctuations of electricity into vibrations of air. So we need to shake the speaker. But the speaker is connected directly to the microcontroller, and he can only give out “1” (on the leg) and “0” (there is nothing). Yes, even (even? Yes, this is rare) this microcontroller has a 5-bit DAC (audiophiles trudge from one-bit, if that. Smail), but this is not sports.
Physics saves us again: even if applying “1” to the speaker, the magnet will not instantly pull up the diffuser, as after “0” it will not let go of it instantly.
The simplest thing is to write code like this.
while(1) { dinamikON(); pause(1); dinamikOFF(); pause(1); }
If pauses are counted in milliseconds, then in dynamics we will get a “squeak” of 500 Hz. And changing the duration of the pauses, you can get quite a decent sound. What is the problem? The problem is that we will need to be constantly distracted by the "hooting".
But in any decent microcontroller there is such a thing as PWM, it is PWM (what is it? Easily searched in the same wikipedia, with pictures and long explanations). There is it in peak. Open MPLAB, create a new project and use the Code Configurator (Tools-Embedded menu. It may be necessary to first put in the Plugins) add a new PWM.

I took the PWM4 solely because of the convenience of the legs. Since PWM in peak cannot do without a timer, let's look at it.

Since nothing is clear yet, just click on “Generate Code” and try to run the result. As usual, nothing should happen - there is no program.
If you got an error about VDD, then in the Run-Project Configuration-PICKit3-Power check the box next to Power target Circuit. It is just possible to program the boards “in operation”, and the current from the programmer is not always enough to power the circuit.We collect the first code. Everything is done in main.c, where I divided the blocks with comments.
uint16_t count; for(count=0; count<1024; count++) { PWM4_LoadDutyValue(count); __delay_ms(10); }
We download and connect the oscilloscope with one input to the output of the microcontroller (blue line) and the other to the dynamics (red).

So, what do we see? The blue line is the result of the work of SHIM. Fill from 0 to 100% and jump back to zero. But the red line somewhere in the middle of the filling is remotely similar to a sine wave. Frankly, this distance is obtained by hooking a 0.47 microfarad capacitor parallel to the transistor, for a beautiful gif. The real picture can be seen below.
Remove the capacitor.

See the spikes on red? This speaker on the "reverse" works as a generator and easily throws a whole volt when powered from 3x. In principle, under certain conditions, it is easy to burn the scheme. But these peaks do not bother anyone, so it’s up to you to put a conder or not. I set for the sake of beauty.
Put again. It already was, but this picture is static.

Let's replace by 0.1 ÎĽF. Just to compare and display the effect of capacitance on the sound :)

In principle, we have already received a squeak of 15 kilohertz, but who needs it, except for mosquitoes? So you need to turn the frequency. The frequency of the PWM depends on the timer, and how often the timer will “tick” depends on the counter that is set each time the timer starts.
That is, the timer operation algorithm looks like this
- We start the timer.
- The timer ticked and reduced the counter.
- Counter at zero? If not, then tick again. If so, generate an interrupt.
Interrupt Handler:
- Oh! The timer has ticked!
- Reset timer again
And here is the launch of PWM just as we hooked up to interrupt the timer. And we can turn both the frequency of the “tick entry” (prescaler in the settings) and the counter value.
Change the code (it is stage2)
uint8_t count; for(count=0;count<256;count++) { PWM4_LoadDutyValue(count*2); TMR2_LoadPeriodRegister(count); __delay_ms(100); }

We look at the beautiful red line and see that it turns out something distant to a sinusoid, and that varies in frequency. Yes, and confirms the ear. What we need!
Why do I change the filling of SHIM, I propose to think independently. But in principle, if you mentally continue the schedule and slow down the change in one parameter, then everything becomes clear. Those who are especially advanced can see a similar picture in some emulator, for example proteusLet's now determine which frequency range we got
Nailing the count at 255

And now we put in 10

Pay attention to the upper right corner where the grid step is indicated. I have "by eye" turned out the range of about 300-5000Hz. Full And on the skull "ride" will not.
Perfectionists can use a frequency meter, or calculate the real value from the clock frequency and prescalers.But then I have problems. I don't have any understanding how
it should sound. Roughly speaking, in the music of the Chukchi reader, but not a writer.
With difficulty I found what frequencies correspond to which notes, I found some musical notation “a Christmas tree was born” ...
I calculated the delay, wrote
#define do 243
Compiled, launched. No, the melody is guessed without problems, but it's not like that. By selecting resistors and capacitors, he achieved an “almost sinusoid-saw” at the exit, but the ear can hear the difference.
As a result, I stopped at the usual two-tone signal: “high-low”. The classic “wow wow” policeman, known to everyone from Hollywood films, didn’t work out for me. And Google in response to the “police sirene tones code program example” gives out anything, just not what is needed.
Help, pliz? In what sequence does the chuck go there?In principle, we have already come to the fact that the next step is to take and reproduce the usual wav. That is not to suffer with tones and other things. Just record the sound, translate it into a digestible form and lose. As did various ScreamTrackers in due time.
There is only one problem: half a second of PCM audio, mono, with 8 kHz sampling takes about kilobytes. And I have only three and a half kilobytes. Will not go. But you can familiarize yourself with the principles and examples by simply typing google “pic pcm sound”. And right from the first link there will be both the source code and the programs themselves.
Therefore, we are comforted by the fact that we will have a real, “warm tube sound from those times” for which the programmer’s attention is not needed: he said what frequency to scribble and went to do his own business, and there the hardware will do everything themselves.
But sound is half the battle.
Good light is also the hallmark of real tuning :) But this is a bit later.
As usual, ready projects for MPLAB with all the pieces can be
collected here.