Let's Make Robots!

How I can get a same frequency sound with do_loop function

<!-- @page { margin: 0.79in } P { margin-bottom: 0.08in } -->

Hi,

I am a picaxe beginner, but I have a general idea how to make a program and electric circuit.



I want to control a speaker (on/off) using picaxe18m2.

In order to control it, B.0 and B.1 are assigned to receive signals from a PC.



The following is my code.

main:

if pinB.1 = 1 then start0

goto main

 

start0:
do
sound B.7,(100,100)
if pinB.0 = 1 then exit
loop
goto main



My problem is I got different frequency sound every 100 ms.

Because there is a time lag after sound.



Do you have any idea to avoid this problem?





Best regards,



Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

18m2? new stuff!

The duration of a note using the sound system is varied based on the processor speed. The default at 4 MHz is that a duration of 1 is about 10 ms. You're code has a duration of 100, which would be a base of 1000 ms.

However, you are running a Picaxe-18m2, which runs at 32 MHz (8 times faster), so the duration will be approximately, 125 ms. I'm not sure how you are measuring the change in frequency every 100 ms, but this seems pretty close to that time period.

So I suspect that there is a slight delay every time your code loops. Either to check pinB.0 within the start0 loop or when you check pinB.0 in the main loop. Maybe for both. While this portion of the code executes, the sound is off. Howevever, it is off so briefly that you may interpret it as a change in the frequency of the note.

Try using a polled interrupt instead of checking the pins for their state, which is faster. This will happen in the background, and the code will get interrupted if the pin you are watching is changed. Interrupts are checked between every statement, between each note in a sound command, and continuously during pause commands.

So you could replicate your code using interrupts as shown below. Note that it is not necessary to use two pins for the interrupt. You use a single pin instead of both pin B.0 and B.1.

setint %00000010,%00000010,B   'activate interrupt on pin1 high on port B

main:

sound B.7,(0,100)                     'Sound 0 is no sound

'Do whatever else you want to do in your program.

goto main

interrupt:

sound B.7,(100,100)

setint %00000010,%00000010   'you need to reset the interrupt each time

return

See how that works for you.