Teensy Serial Clock

Status
Not open for further replies.

mtiger

Well-known member
Hi Guys,

Wrote a little sketch to print a timer to the serial monitor and wondering if or how I could improve it?

I added a led flash every second however watching carefully, its slightly out of time. Wondering how I could make it exact?

Let me know what you think. Any help, always appreciated.

Code:
const int ledPin = 13;

unsigned long currentMillis;
unsigned long previousMillis;

int microSeconds = 0;
int seconds = 0;
int minutes = 0;
int hours = 0;

void setup()  {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  currentMillis = millis();

  if (currentMillis - previousMillis > 10)  {
    previousMillis = currentMillis;
    microSeconds++;
    if (microSeconds == 100)  {
      digitalWrite(ledPin, HIGH);
      microSeconds = 0;
      seconds++;
    } else  {
      digitalWrite(ledPin, LOW);
      if (seconds == 60)  {
        seconds = 0;
        minutes++;
        if (minutes == 60) {
          seconds = 0;
          minutes = 0;
          hours++;
        }
      }
    }
    if (seconds < 10) {
      Serial.printf("0%d:0%d:0%d:%d", hours, minutes, seconds, microSeconds);
      Serial.println();
    } else if (minutes < 10)  {
      Serial.printf("0%d:0%d:%d:%d", hours, minutes, seconds, microSeconds);
      Serial.println();
    } else if (hours < 10) {
      Serial.printf("0%d:%d:%d:%d", hours, minutes, seconds, microSeconds);
      Serial.println();
    }
  }
}

The sketch uses 36,384 bytes, wondering how i might be able to reduce / optimize this significantly?
 
Last edited:
What Teensy # is in use? What compile option: Smallest, FASTEST - with or without LTO?

Using printf() brings in extra code - manually printing in parts with Serial.print( ... ) will reduce code size.

Adding Serial itself adds a fair amount of code when compiling with Serial Type : USB. You can compile once without that to see how much it uses - but unless you are printing to another device it has to stay.

It checks 100 times per second or each 10 microSeconds [ thousandths ] of a second [ millis() ]
Then does : microSeconds++;

There are 1000 microseconds [ micros() ] per millisecond - are the units or the labels off - i.e. backwards?

100 sets of 10 microseconds is one millisecond

100 sets of 10 milliseconds is one second

There is an elapsedMillis and elapsedMicros that incorporate some of the math into a PJRC creation that could be used to keep time from slipping away with repeated rounding errors when used something like:

Code:
elapsedMillis foo;

setup() {
// ...
foo=0;
}

loop() {
  if ( foo >= 10 ) {
   foo -= 10; // taking off just 10 will keep it from slipping 
   // 10 milliseconds have elapsed
  }
}
 
Status
Not open for further replies.
Back
Top