I viewed the signal on Pin 5 with an oscilloscope and found that the HIGH phase is 6.5us and the LOW phase is 7.1us, as shown in the picture below.
How can a simple instruction like digitalWrite() take several microseconds on a CPU with 16MHz? If I'm not mistaken, 16MHz means 16 machine instructions per microsecond and digitalWrite should take - just a guess - 1 up to 4 machine instructions?
Does anyone have an idea?
There is quite a lot of code in this function of you look at it. It does things like check to see if the pin is doing PWM and if so turns it off.
If you want it quicker then look up direct port manipulation I'm the referance section.
There are one to two cycles per machine code instruction.
M1cr0M4n:
I viewed the signal on Pin 5 with an oscilloscope and found that the HIGH phase is 6.5us and the LOW phase is 7.1us, as shown in the picture below.
M1cr0M4n:
If I'm not mistaken, 16MHz means 16 machine instructions per microsecond and digitalWrite should take - just a guess - 1 up to 4 machine instructions?
digitalWrite takes a variable as an argument. Translating that variable into a port number and a bit number takes a few machine instructions. Try the digitalWriteFast library.
@Grumpy_Mike:
Thanks, I tried direct port manipulation and now the HIGH phase is 68ns an the LOW phase is 937ns.
[quote author=Nick Gammon link=topic=179928.msg1333590#msg1333590 date=1375095026]
What useful thing does this program do?
it's part of the debugging for a program that drives an open drain output with a capacitor in order to simulate a sensor signal.
I'm sorry for the picture. I thought I could upload it from a location on my computer. It's just an image of a rectangular signal (with narrow overshoots) for those who are curious.
I'm sorry for the picture. I thought I could upload it from a location on my computer. It's just an image of a rectangular signal (with narrow overshoots) for those who are curious.
Ok I'm imagining that in my mind then ...
If you want fast port manipulation use PORTX register to manipulate it
Thanks, I tried direct port manipulation and now the HIGH phase is 68ns an the LOW phase is 937ns.
You could put the pair of instructions inside their own "while (1)" loop - that should even things up.
Better - put a block of HIGH/LOW pairs inside the while loop - then you can see how fast the port toggle is, and how much time is taken to loop back to the start.
Seriously though, for getting a high frequency out with a good wave-form, use the hardware timers. This sort of loop will always have glitches, when interrupts fire.