-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmicrosecond_clock.ino
57 lines (44 loc) · 1.5 KB
/
microsecond_clock.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
Create a simple 50ms/20Hz clock, blinking the onboard LED every second.
Copyright 2020-2021 by Murray Altheim. All rights reserved. This file is part
of the Robot Operating System project, released under the MIT License. Please
see the LICENSE file included as part of this package.
*/
const int ledPin = 13; // the LED pin
const int clockPin = 7; // the clock output pin to connect to Pi
// Variables will change:
int clockState = LOW; // clockState used for the timer loop
int ledState = LOW; // used to toggle the LED
// use "unsigned long" for variables that hold time
unsigned long previousMicros = 0; // stores last time clock was updated
unsigned long ticks = 0; // used to modulo the LED
// 50ms = 50000us; 1000ms = 1000000us
const long interval = 50000; // 20Hz clock interval (microseconds)
void setup() {
// set the digital pins as outputs:
pinMode(ledPin, OUTPUT);
pinMode(clockPin, OUTPUT);
}
void loop() {
unsigned long currentMicros = micros();
if ( currentMicros - previousMicros >= interval ) {
previousMicros = currentMicros;
// toggle clock state
if ( clockState == LOW ) {
clockState = HIGH;
} else {
clockState = LOW;
}
digitalWrite(clockPin, clockState);
ticks += 1;
if ( ticks % 20 == 0 ) { // blink every 20th tick
// toggle LED state
if ( ledState == LOW ) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
}
}