Hi,
I have some trouble when dealing with time for periodic events at quite high frequencies.
I'm working on a remote control using a protocol of my own (not interested in using existing ones - I like doing things the hard way). It is really simple :
XXXX0XXXX01111
-4bit word of data
-void bit
-4bit word of data
-void bit
-sync word - 5 bits set to 1
It works fine at low speeds (0.4bit/s i.e. 0.6 sec for each bit times 15 bits), but when I get at higher speeds (4ms per bit) i'm having a very high error rate (i.e. doesn't find the sync word and doesn't work at all). However, it works ok at 8ms per bit ("ok" meaning error rate good enough to have the message get though).
I had another time problem with an arduino I was using to generate a square-shaped 0V to 5V voltage with cycles at 26us. Instead of having cycles of 26us of length, they were 35us long. Here's the source code :
#define OUToPIN 13
#define PERIOD 16//normalement devrait etre 26
#define HALFoPERIOD PERIOD/2
void setup() {
pinMode(OUToPIN,OUTPUT);
digitalWrite(OUToPIN,LOW);
}
void loop() {
delayMicroseconds(HALFoPERIOD);
digitalWrite(OUToPIN,HIGH);
delayMicroseconds(HALFoPERIOD);
digitalWrite(OUToPIN,LOW);
}
As this was a simple program I simply changed the 26us to 16us and obtained the correct output.
I'm using the right quartz (16MHz) so I believe the problem comes from the time needed to run each instruction. However, it would mean that in order to run two delays + two digitalWrite (should take the same time as bitWrite ?) + do...while (equivalent to goto ?), the arduino needs 10us. So in this example the arduino needs an average time of 2us per instruction. However it is also using a 16MHz quartz for it's internal clock ? Shouldn't it run at 1 instruction each 0.06us (or 0.12us) ? Should this mean that the compilated code gives an average of 33 sub-instructions for each "C-like" instruction ? Or is there something that I didn't understand ?
Should I program the ATmega u?sing asm ? Do you have any hints so that I could solve my problem?
Could it be that it's better to use micros(4000) than delay(4), since it's more precise ?
Thanks in advance