Skip to content

Instantly share code, notes, and snippets.

@lopes
Last active August 7, 2024 13:34
Show Gist options
  • Save lopes/c4db8c4f46ff79847deb to your computer and use it in GitHub Desktop.
Save lopes/c4db8c4f46ff79847deb to your computer and use it in GitHub Desktop.
A stopwatch in Arduino Uno with DFRobot v1.1 board. #clang #arduino #prototype
/**
* cronometr.ino
* Implements a stopwatch in Arduino Uno with DFRobot v1.1 board.
* Author: José Lopes de Oliveira Jr. <jilo.cc>
* License: GPLv3+
*/
#include <LiquidCrystal.h>
/**
* GLOBAL VARIABLES
*/
#define RIGHT 0 // 0
#define UP 1 // 144
#define DOWN 2 // 329
#define LEFT 3 // 504
#define SELECT 4 // 741
#define NONE 5
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int key = 0;
int key_pressed = 0;
boolean running = false;
long elapsed_time = 0;
/**
* FUNCTIONS
*/
void time_format(long n){
/* Format n as a time string, like 000'00"0. */
int m = 0; // Minutes
int s = 0; // Seconds
int t = 0; // Tens of seconds
t = n % 10;
n -= t;
s = (n % 600) / 10;
m = (n / 600) % 1000; // Max.time: 999'59"9; then returns to 0
// The following is a workaround to display clock,
// since sprintf(ret, "%00d'%0d\"%d", m, s, t);
// doesn't work.
lcd.setCursor(4, 1);
lcd.print(m);
lcd.setCursor(7, 1);
lcd.print("'");
lcd.setCursor(8, 1);
lcd.print(s);
lcd.setCursor(10, 1);
lcd.print('"');
lcd.setCursor(11, 1);
lcd.print(t);
}
int read_buttons(){
/**
* Read key pressed from DFRobot v1.1 board.
*
* Credits:
* http://www.dfrobot.com/wiki/index.php?title=Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)
*/
key_pressed = analogRead(0);
// Add ~ 50 to those values and check
// to see if we are close
if (key_pressed > 1000) return NONE;
else if (key_pressed < 50) return RIGHT;
else if (key_pressed < 250) return UP;
else if (key_pressed < 450) return DOWN;
else if (key_pressed < 650) return LEFT;
else if (key_pressed < 850) return SELECT;
else return NONE;
}
/**
* MAIN
*/
void setup(){
lcd.begin(16, 2);
lcd.clear();
running = false;
elapsed_time = 0;
lcd.setCursor(2, 0);
lcd.print("CRONOMETRINO");
lcd.setCursor(4, 1);
time_format(elapsed_time);
}
void loop(){
key = read_buttons();
if (key == SELECT) running = !running;
if (running) {
elapsed_time++;
lcd.setCursor(4, 1);
time_format(elapsed_time);
delay(100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment