FYI Code timing

FYI
I thought some might be interested in a method to time code and check pin levels at points in your sketches.
Requires a storage oscilloscope or logic analyzer.

//Demonstration on Timing Code Execution
//Use D13 as a trigger output to time or capture events in your sketch
//You will need a storage scope or a logic analyzer to view logic levels
//and measure times.
//
//UNO rev 3
//
//PINB = 0x20;    // Toggles pin D13, this takes 65ns
//PINB = 0x20;    // Toggles pin D13, a second time creates one positive pulse
//                   on pin 13 @ 65ns wide.
//Four such lines can be used to time events
//example 1:  pinMode(13,OUTPUT); is placed in setup()
//          
//          PINB = 0x20;      //create a + 5V pulse on pin D13
//          PINB = 0x20;      //
//          millis();    //instruction(s) being timed go here        
//          PINB = 0x20;      //create a + 5V pulse on pin D13
//          PINB = 0x20;      //
//The time between the two 65ns pulses on pin D13 gives the time for the millis() function
//    - In this example it was measured millis() took 1.37us
//    - Changing this to: unsigned long millisNow = millis(); gives 1.87us i.e. 500ns more
//
//You will have to subtract 65ns from your measured results, for the third PINB = 0x20;
//
//Note: Interrupts may interfere with timing.
//
//example 2:
//You want to measure a logic level on a pin at a specific point in your sketch.
//Trigger on pin D13 "channel one".
//Put "channel two" on the pin you want to monitor. 
//Add two PINB = 0x20; lines just before the point in your sketch where you want to synch.

unsigned long millisNow;

void setup()
{
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  
} //END of setup()

void loop()
{
  PINB = 0x20;
  PINB = 0x20;
  millis();
  PINB = 0x20;
  PINB = 0x20;

  delay(1);

} //END of loop()

2016-03-06_0-11-24.png

2016-03-06_0-01-21.png