Non integer pulse and sound

eddydde

Member
As a newcomer to the PICAXE (16F88) I would be grateful for some assistance with two programming questions:

1. Is it possible to generate a pulse as accurate as possible every 2.23 milliseconds?
2. Is it possible to generate a sound(tone) as close as possible to 4 kHz?

I have observed the Sound command 125 produces a tone of 4.22kHz but I would like to get closer to 4.0 kHz if possible.

Thanks.
 

womai

Senior Member
Can you tell us a bit more about your application?

Assuming you run your Picaxe at 4 MHz you can easily generate a precise 4 kHz square wave using the pwmout command:

pwmout 3 , 249, 500

Note that this uses a particular pin on your 18X. The beauty is that PWM runs in the background, i.e. the Picaxe is free to do other things (e.g. generate the 2.33ms period pulses) even while the 4 kHz output is active.

If you run the Picaxe at faster clock rates the minimum achievable PWM frequency is higher, but you can use the internal prescaler to reduce that (more to that if you really need it - needs a single poke to a specific memory location).

For the 2.23msec pulse, generating that "by hand" could be done as follows:

myloop:
'pause 1 ' optional of loop is too fast
pulsout mypin, duration
goto myloop

Assuming roughly 2000 commands/sec execution speed at 4 MHz clock, the loop will take about 1msec (2 commands - pulsout, goto) plus the duration of the output pulse. Now you will need to tweak duration so that the total loop takes exactly 2.23msec per repeat. Since the pulsout at 4 MHz clock has 10us of resolution, you should be able to get to within +/-0.005msec of your goal.

Note that any changes to the program can result in somewhat different execution times due to the interpreted nature of the Picaxe code and the fact that it is highly compressed.

If you used a Picaxe 28X1 ot 28X2 instead you could still do the PWM for the 4 kHz, but then put the 2.23msec period pulse generation in a timer interrupt routine. That way your program coulds do yet another (third!) thing in parallel, e.g. react to user input.
 
Last edited:
Top