jerdon
July 26, 2024, 6:23pm
1
Arduino forum,
Using my nano I wrote this simple program to toggle one output port.
void setup()
{
pinMode(5, OUTPUT);
} // end void setup()
void loop()
{
do
{
digitalWrite(5, HIGH);
digitalWrite(5, LOW);
}while(1);
} // end void loop()
When I measure the rise to fall time of port 5 I get 4us or 250Khz. Can I use this to calculate the oscillator speed?
jerdon
Yes, you need to figure out how many instructions were executed and from that you can get the clock speed.
kolaha
July 26, 2024, 8:30pm
3
you can, but it will be useless.
you must measure time between raises or both raise/fall and fall/raise time.
and the oscillator speed
is incorrect
jerdon
July 26, 2024, 8:33pm
4
Arduno forum,
Rise to rise time is ~8us so looking at how simple the code is exactly how do I calculate the clock speed?
jerdon
kolaha
July 26, 2024, 8:35pm
5
1 second divide by measured unit, in you example 8µs
1000000000 / 8
in sketch:
unsigned long x = 1000000000UL / 8;
You can only calculate the clock speed if you know how many clock cycles each instruction takes.
digitalWrite() takes quite a few clock cycles, I don't know exactly how many but it's more than 50.
You can get a better idea if you use digitalWriteFast():
#include <digitalWriteFast.h>
void setup()
{
pinMode(5, OUTPUT);
} // end void setup()
void loop()
{
do
{
digitalWriteFast(5, HIGH);
digitalWriteFast(5, LOW);
} while (1);
} // end void loop()
Here the waveform is high for 2 clock cycles, and low for 4 clock cycles.
Or you can go even faster using direct port manipulation:
(I don't know whether this will work on a nano, but tried on a Uno R3)
void setup()
{
pinMode(5, OUTPUT);
} // end void setup()
void loop()
{
do
{
PORTD = B00100000;
PORTD = B00000000;
} while (1);
} // end void loop()
High for 1 clock cycle, low for 3 clock cycles.
It's the do..while that makes the waveform assymetrical.
jerdon
July 27, 2024, 4:05am
7
JohnLincoln,
Thanks for the reply. All good stuff for someone new to Arduino.
I have been reading an Arduino Language Reference web site but it doesn't mention about addressing the ports directly with binary.
In many instances I would rather use binary to get that extra bit of speed.
jerdon
It's very unlikely that it will be mentioned as it's different for every processor family so not portable. E.g. PORTD only exists on AVR based micros and not in SAM/SAMD based boards.
For your Nano, you can look at https://docs.arduino.cc/retired/hacking/software/PortManipulation/ .
westfw
July 28, 2024, 8:19am
9
See also this previous discussion: Maximum pin toggle speed
Hi, @jerdon
What is your ultimate project?
Tom...