Good evening everybody.
I am new to the forum so please, if I am in the wrong section of the forum, let me know.
I am using Arduino ( Arduino Nano with Atmega328P ) and I am observing a strange behavior:
I need to switch on and off one of the digital pin of my board in a very fast way, so I implemented the following code:
int l=512;
int myArray[512] = {0};
void setup()
{
pinMode(4, OUTPUT);
}
void loop() {
for (int j = 0; j < l; j++) {
if ((j % 2)==0) {myArray[j]=1;}
else {myArray[j]=0;}
}
while(true) {for (int i = 0; i < l; i++) {
bitWrite(PORTD, 4, myArray[i]);
}}
}
By this my Arduino produces a square waves with a frequency of 0.5 MHz. But now things start to be strange: in the oscilloscope I observe an off time of 6-7 microseconds after some repetition...
Someone could give me an explanation about it and if it is possible to fix it?
Please read the forum guide in the sticky post, then modify your post above and put in the code tags. As you can see, the forum has corrupted your code because you did not use code tags.
PaulRB:
Could the off time be caused by the code reaching the end of the array and re-starting at the beginning of the array?
In my opinion, no, because it is just the while loop that is repeated... why he has to wait that time?... in order to verify it, if I remember correctly (I don't have the oscilloscope here ), I have repeated the entire code considering a shorter sequence of bit, 8 indeed (10101010), and that effect is equal to the previous case...
I have also tried to use a 5V power supply instead of my pc to power the Arduino, in order to exclude any possible interference due to communication between the two device.
How many iterations are there here?
for (int j = 0; j < l; j++)
and
for (int i = 0; i < l; i++)
The achieved square waves ( 0.5 MHz ) is enough.
The number of iterations is fixed by l that in my case is 512, but is ok also for "l=whatever even number".
The first for is used to create the array that is scanned by the second for.
The off time is likely the micros() and millis() processing, along with the loop() code processing.
You can use the noInterrupts() that LarryD posted to stop the interrupts.
Thank to all the kind replies. I will surely try the noInterrupts(); that seems the correct to idea to solve my problem. Thank also larryd for posting a faster solution respect to mine! I will surely give a try to it!
Since I am new to Arduino I am quite interested in the differences that the code posted by David_2018 has respect to the other one. Why it results slower?