John Bradnam
Published © GPL3+

Tube Alarm Clock

A tubular alarm clock that incorporates a rotary encoder at one end to set the time and alarm. Supports both left and right handed users.

IntermediateFull instructions provided12 hours1,416
Tube Alarm Clock

Things used in this project

Hardware components

Microchip ATtiny1614 Microprocessor
×1
TM1650 4-Digit Display Drive
SOIC 16
×1
Real Time Clock (RTC)
Real Time Clock (RTC)
DS1307 SOIC 8 variant
×1
0.8in 4-Digit 7-Segment CC Display
×1
32.768 kHz Crystal
32.768 kHz Crystal
×1
Battery Holder, Coin Cell
Battery Holder, Coin Cell
CR1220 Battery Holder
×1
Rotary Encoder with Push-Button
Rotary Encoder with Push-Button
20mm D-Shaft
×1
Buzzer
Buzzer
×1
LM1117-5V
SOT-223 5V regulator
×1
Passive Components
Resistors: 2 x 10K 0805, Capacitors: 2 x 22nF 0805, 2 x 0.1uF 0805, 1 x 10uF 1206, 1 x 47uF/16V 3528 Tantalum
×1

Software apps and online services

Arduino IDE
Arduino IDE

Hand tools and fabrication machines

3D Printer (generic)
3D Printer (generic)
Soldering iron (generic)
Soldering iron (generic)

Story

Read more

Custom parts and enclosures

STL Files

STL files for 3D printing

Schematics

Schematic

PCB

Eagle Files

Schematic and PCB in Eagle format

Code

TubeClockV1.ino

C/C++
/**
 * ATtiny1614 Tube Clock
 * John Bradnam (jbrad2089@gmail.com)
 * 
 * 2021-10-10 - Initial Code Base
 *
 * ---------------------------------------
 * ATtiny1614 Pins mapped to Ardunio Pins
 *
 *             +--------+
 *         VCC + 1   14 + GND
 * (SS)  0 PA4 + 2   13 + PA3 10 (SCK)
 *       1 PA5 + 3   12 + PA2 9  (MISO)
 * (DAC) 2 PA6 + 4   11 + PA1 8  (MOSI)
 *       3 PA7 + 5   10 + PA0 11 (UPDI)
 * (RXD) 4 PB3 + 6    9 + PB0 7  (SCL)
 * (TXD) 5 PB2 + 7    8 + PB1 6  (SDA)
 *             +--------+
 *             
 *             
 * BOARD: ATtiny1614/1604/814/804/414/404/214/204
 * Chip: ATtiny1614
 * Clock Speed: 20MHz
 * millis()/micros(): "TCD0 (1 series only, default there)"
 * Programmer: jtag2updi (megaTinyCore)
 * ----------------------------------------
 */

#include <Wire.h>
#include <RTClib.h>

//DS1307
#define _SCL 9         //PA2
#define _SDA 8         //PA1

#define DATA      0   //PA4
#define CLK       1   //PA5
#define MERCURY   2   //PA6
#define SPEAKER   3   //PA7
#define ENC_S     8   //PA1
#define ENC_A     9   //PA2
#define ENC_B     10  //PA3

#include "Display.h"
#include "Rotary.h"
#include "Memory.h"
#include "Music.h"

enum SETUP { SHOW_TIME, ALARM_ONOFF, ALARM_HOUR, ALARM_MIN, TIME_HOUR, TIME_MIN };
SETUP setupMode = SHOW_TIME;

#define FLASH_TIME 200          //Time in mS to flash digit being set
#define STEP_TIME 350           //Time in mS for auto increment or decrement of time

bool flashOn = false;           //Used to flash display when setting clock or alarm
long flashTimeout = 0;          //Flash timeout when setting clock or alarm

int8_t setTH = 0;               //Time Hour being set
int8_t setTM = 0;               //Time Minute being set
int8_t setAH = 0;               //Alarm Hour being set
int8_t setAM = 0;               //Alarm Minute being set
bool setAO = false;             //Alarm on/off being set
int setAF = 0;             //Alarm on/off being set

int lastHours = -1;             //Used to test if hour changed
int lastMinutes = -1;           //Used to test if minute changed
int lastSecs = -1;              //Used to test if second changed

bool repaint = false;           //Set true to refresh display
bool alarmCancelled = false;    //Set true if user cancelled alarm


//----------------------------------------------------------------------
// Hardware Setup

RTC_DS1307 rtc;

void setup() 
{
  readEepromData();
  setupDisplay();
  setupRotary();
  
  Wire.usePullups();                // Use pullup resistors on SDA and SCL pins
  if (!rtc.begin())
  {
    //Cannot find RTC
    displayTextRTC();
    delay(1000);
  }
  else if (!rtc.isrunning()) 
  {
    //RTC lost power - RTC reset;
    rtc.adjust(DateTime(2021, 10, 10, 8, 51, 0));
    displayTextLOST();
    delay(1000);
  }
}

//----------------------------------------------------------------------
// Main program loop
void loop()
{
  bool first = testSetupButton();
  switch (setupMode)
  {
    case SHOW_TIME: showTimeMode(first); break;
    case ALARM_ONOFF: setAlarmOnOff(first); break;
    case ALARM_HOUR: setAlarmHour(first); break;
    case ALARM_MIN: setAlarmMinute(first); break;
    case TIME_HOUR: setTimeHour(first); break;
    case TIME_MIN: setTimeMinute(first); break;
  }
} 

//----------------------------------------------------------------------
// Test for Rotary button press and advance menu if pressed
//  Returns true if button is pressed
bool testSetupButton()
{
  bool changeInSetup = false;
  if (isRotarySwitchPressed())
  {
    setupMode = (setupMode == TIME_MIN) ? SHOW_TIME : (SETUP)((int)setupMode + 1);
    flashTimeout = millis() + FLASH_TIME;
    flashOn = false;
    changeInSetup = true;
  }
  return changeInSetup;
}
  
//----------------------------------------------------------------------
// Clock is in SHOW_TIME mode
//  first - true to this is the first time this mode was entered into after setup
void showTimeMode(bool first)
{
  DateTime newTime = rtc.now();
  int hours = newTime.hour();
  int minutes = newTime.minute();
  int secs = newTime.second();

  if (first)
  {
    //Just come out of setup so test if time has changed
    if (hours != setTH || minutes != setTM)
    {
      //Update RTC with changes
      rtc.adjust(DateTime(newTime.year(), newTime.month(), newTime.day(), setTH, setTM, 0));
      hours = setTH;
      minutes = setTM;
      secs = 0;
    }
  }

  if (first || hours != lastHours || minutes != lastMinutes || secs != lastSecs)
  {
    lastHours = hours;
    lastMinutes = minutes;
    lastSecs = secs;

    bool colon = secs & 0x01;

    displayTime(HOURS,hours,false,true,colon);
    displayTime(MINUTES,minutes,true,true,colon);
  }

  //Test if alarm gone off
  if (alarmCancelled && (hours != EepromData.alarmHour || minutes != EepromData.alarmMinute))
  {
    alarmCancelled = false;
  }
  else if (EepromData.alarmOn && !alarmCancelled && hours == EepromData.alarmHour && minutes == EepromData.alarmMinute)
  {
    turnOnAlarm();
    alarmCancelled = true;
  }
}

//----------------------------------------------------------------------
// Clock is in ALARM_HOUR mode
//  first - true to this is the first time this mode was entered into
void setAlarmOnOff(bool first)
{
  displayChar(3,CHAR_A);

  if (first)
  {
    //Store alarm settings so we can detect if they changed
    setAO = EepromData.alarmOn;
    setAH = EepromData.alarmHour;
    setAM = EepromData.alarmMinute;
  }
  
  repaint = true;

  //Handle rotary encoder
  if (rotaryMovement == 1)
  {
    setAO = true;
  }
  else if (rotaryMovement == -1)
  {
    setAO = false;
  }
  else if (!flashTimedOut())
  {
    repaint = false;
  }
  
  if (repaint)
  {
    displayAlarmState(setAO, flashOn);
  }

  //Clear ready to detect next rotational change
  rotaryMovement = 0;
}

//----------------------------------------------------------------------
// Clock is in ALARM_HOUR mode
//  first - true to this is the first time this mode was entered into
void setAlarmHour(bool first)
{
  displayTextAH();

  repaint = true;

  //Handle rotary encoder
  if (rotaryMovement == 1)
  {
    setAH = (setAH + 1) % 24;
  }
  else if (rotaryMovement == -1)
  {
    setAH = (setAH + 23) % 24;
  }
  else if (!flashTimedOut())
  {
    repaint = false;
  }
  
  if (repaint)
  {
    displayTime(MINUTES,setAH,true,flashOn,false);
  }

  //Clear ready to detect next rotational change
  rotaryMovement = 0;
}

//----------------------------------------------------------------------
// Clock is in ALARM_MIN mode
//  first - true to this is the first time this mode was entered into
void setAlarmMinute(bool first)
{
  displayTextAM();
  
  repaint = true;

  //Handle rotary encoder
  if (rotaryMovement == 1)
  {
    setAM = (setAM + 1) % 60;
  }
  else if (rotaryMovement == -1)
  {
    setAM = (setAM + 59) % 60;
  }
  else if (!flashTimedOut())
  {
    repaint = false;
  }

  if (repaint)
  {
    displayTime(MINUTES,setAM,true,flashOn,false);
  }

  //Clear ready to detect next rotational change
  rotaryMovement = 0;
}

//----------------------------------------------------------------------
// Clock is in TIME_HOUR mode
//  first - true to this is the first time this mode was entered into
void setTimeHour(bool first)
{
  if (first)
  {
    //Test if alarm status has changed
    if (setAO != EepromData.alarmOn || setAH != EepromData.alarmHour || setAM != EepromData.alarmMinute)
    {
      //Write changes back to EEPROM
      EepromData.alarmOn = setAO;
      EepromData.alarmHour = setAH;
      EepromData.alarmMinute = setAM;
      writeEepromData();
    }
    
    //Default to time as of now    
    DateTime currentTime = rtc.now();
    setTH = currentTime.hour();
    setTM = currentTime.minute();
  }

  displayTextTH();

  repaint = true;

  //Handle rotary encoder
  if (rotaryMovement == 1)
  {
    setTH = (setTH + 1) % 24;
  }
  else if (rotaryMovement == -1)
  {
    setTH = (setTH + 23) % 24;
  }
  else if (!flashTimedOut())
  {
    repaint = false;
  }

  if (repaint)
  {
    displayTime(MINUTES,setTH,true,flashOn,false);
  }

  //Clear ready to detect next rotational change
  rotaryMovement = 0;
}

//----------------------------------------------------------------------
// Clock is in TIME_MIN mode
//  first - true to this is the first time this mode was entered into
void setTimeMinute(bool first)
{
  displayTextTM();

  repaint = true;

  //Handle rotary encoder
  if (rotaryMovement == 1)
  {
    setTM = (setTM + 1) % 60;
  }
  else if (rotaryMovement == -1)
  {
    setTM = (setTM + 59) % 60;
  }
  else if (!flashTimedOut())
  {
    repaint = false;
  }

  if (repaint)
  {
    displayTime(MINUTES,setTM,true,flashOn,false);
  }

  //Clear ready to detect next rotational change
  rotaryMovement = 0;
}

//----------------------------------------------------------------------
// Test if the flash timeout has expired
//  returns true if flash timeout has expired
bool flashTimedOut()
{
  bool timedOut = false;
  if (millis() > flashTimeout)
  {
    flashTimeout = millis() + FLASH_TIME;
    flashOn = !flashOn;
    timedOut = true;
  }
}

//---------------------------------------------------------------
//Sound the alarm
// This will play for one minute or until the rotary switch is pressed
void turnOnAlarm()
{
  attachSwitchInterrupt();
  DateTime newTime = rtc.now();
  int hours = newTime.hour();
  int minutes = newTime.minute();
  while (!rotarySwitchPressed && hours == newTime.hour() && minutes == newTime.minute())
  {
    playSong(melody_elise);
    delay(200);
    newTime = rtc.now();
  }
  detachSwitchInterrupt();
}

Display.h

C/C++
/**
 * ATtiny1614 Tube Clock
 * John Bradnam (jbrad2089@gmail.com)
 * 
 * 2021-10-08 - Create display functions for clock
 *
*/

#pragma once

#include <TM1650.h>

#define DATA      0   //PA4
#define CLK       1   //PA5
#define MERCURY   2   //PA6

#define BRIGHTNESS 2
enum SHOW {HOURS,MINUTES};

#define SPACE 10
#define CHAR_R 11
#define CHAR_T 12
#define CHAR_C 13
#define CHAR_L 14
#define CHAR_O 15
#define CHAR_A 16
#define CHAR_P 17
#define CHAR_N 18
#define CHAR_F 19
#define CHAR_H 20
#define DP_SEGMENT 0b00000010
const PROGMEM byte NUMBER_FONT[] = {
//  edcgfbpa
  0b11101101, // 0
  0b00100100, // 1
  0b11010101, // 2
  0b01110101, // 3
  0b00111100, // 4
  0b01111001, // 5
  0b11111001, // 6
  0b00100101, // 7
  0b11111101, // 8
  0b01111101, // 9
  0b00000000,  // SPACE
  0b10010000, // r
  0b11011000, // t
  0b11010000, // c
  0b11001000, // L
  0b11110000, // o
  0b10111101, // A
  0b10011101, // P
  0b10110000, // n
  0b10011001, // f
  0b10111000  // h
};

//a<->d, f<->c, b<->e
const PROGMEM byte REVERSE_FONT[] = {
//  edcgfbpa
  0b11101101, // 0
  0b10001000, // 1
  0b11010101, // 2
  0b11011001, // 3
  0b10111000, // 4
  0b01111001, // 5
  0b01111101, // 6
  0b11001000, // 7
  0b11111101, // 8
  0b11111001, // 9
  0b00000000,  // SPACE
  0b00010100, // r
  0b00110101, // t
  0b00010101, // c
  0b00100101, // L
  0b00011101, // o
  0b11111100, // A
  0b11110100, // P
  0b00011100, // n
  0b01110100, // f
  0b00111100  // h
};

//----------------------------------------------------------------------
// TM1650 definitions

TM1650 display1(DATA,   //byte dataPin
                CLK,    //byte clockPin
                4,      //byte number of digits
                true,   //boolean activeDisplay = true
                BRIGHTNESS       //byte intensity
);

//-----------------------------------------------------------------------------------
// Forward references

void setupDisplay();
void displayTextRTC();
void displayTextLOST();
void displayTextTH();
void displayTextTM();
void displayTextAH();
void displayTextAM();
void displayAlarmState(bool alarmOn, bool on);
void displayNumber(long num, bool leadingZeros, bool on);
void displayTime(SHOW s, int num, bool leadingZeros, bool on, bool c);
void displayChar(int digit, int chr);
void displayCharWithColon(int digit, int chr, bool c);

//---------------------------------------------------------------
// Setup pin connected to mercury switch
void setupDisplay()
{
  pinMode(MERCURY,INPUT_PULLUP);
}

//---------------------------------------------------------------
// Write RTC_ on the display
void displayTextRTC()
{
  displayChar(3,CHAR_R);
  displayChar(2,CHAR_T);
  displayChar(1,CHAR_C);
  displayChar(0,SPACE);
}

//---------------------------------------------------------------
// Write LOST on the display
void displayTextLOST()
{
  displayChar(3,CHAR_L);
  displayChar(2,CHAR_O);
  displayChar(1,5);
  displayChar(0,CHAR_T);
}

//---------------------------------------------------------------
// Write TH on the display
void displayTextTH()
{
  displayChar(3,CHAR_T);
  displayChar(2,CHAR_H);
}

//---------------------------------------------------------------
// Write TM on the display
void displayTextTM()
{
  displayChar(3,CHAR_T);
  displayChar(2,CHAR_N);
}

//---------------------------------------------------------------
// Write AH on the display
void displayTextAH()
{
  displayChar(3,CHAR_A);
  displayChar(2,CHAR_H);
}

//---------------------------------------------------------------
// Write AM on the display
void displayTextAM()
{
  displayChar(3,CHAR_A);
  displayChar(2,CHAR_N);
}

//---------------------------------------------------------------------
//Write alarm state to the display
//  alarmOn - State of alarm either on or off
//  on - true to show state, false to show blank
void displayAlarmState(bool alarmOn, bool on)
{
  if (!on)
  {
    displayChar(2,SPACE);
    displayChar(1,SPACE);
    displayChar(0,SPACE);
  }
  else if (alarmOn)
  {
    displayChar(2,SPACE);
    displayChar(1,CHAR_O);
    displayChar(0,CHAR_N);
  }
  else
  {
    displayChar(2,CHAR_O);
    displayChar(1,CHAR_F);
    displayChar(0,CHAR_F);
  }  
}

//---------------------------------------------------------------------
//Write number to display
//  num - (0 to 9999) 
//  leadingZeros - true to have leading zeros
//  on - true to show digit, false to show blank
void displayNumber(long num, bool leadingZeros, bool on)
{
  num = max(min(num, 99999999), 0);
  for (int i = 0; i < 8; i++)
  {
    if (on && (num > 0 || i == 0 || leadingZeros))
    {
      displayChar(i, num % 10);
    }
    else
    {
      displayChar(i, SPACE);
    }
    num = num / 10;
  }
}

//---------------------------------------------------------------------
//Write time to display
//  s - SHOW constant
//  num - (0 to 99) 
//  leadingZeros - true to have leading zeros
//  on - true to show digit, false to show blank
//  c - true to show colon
void displayTime(SHOW s, int num, bool leadingZeros, bool on, bool c)
{
  num = max(min(num, 99), 0);
  int b = (s == HOURS) ? 2 : 0;
  for (int i = 0; i < 2; i++)
  {
    if (on && (num > 0 || i == 0 || leadingZeros))
    {
      displayCharWithColon(b + i, num % 10, c);
    }
    else
    {
      displayChar(b + i, SPACE);
    }
    num = num / 10;
  }
}

//---------------------------------------------------------------------
//Write digit to display
//  digit - digit to write to (0 - left most to 7 - right most)
//  char - character to display
void displayChar(int digit, int chr)
{
  displayCharWithColon(digit, chr, false);
}

//---------------------------------------------------------------------
//Write digit to display
//  digit - digit to write to (0 - left most to 7 - right most)
//  char - character to display
//  c - true to show colon
void displayCharWithColon(int digit, int chr, bool c)
{
  bool normal = (digitalRead(MERCURY) == HIGH);

  int8_t physical = (normal) ? 3 - digit : digit;  
  int8_t cDigit = (normal) ? 0 : 3;  
  byte segments = (normal) ? pgm_read_byte(&NUMBER_FONT[chr]) : pgm_read_byte(&REVERSE_FONT[chr]);
  if (c && digit == cDigit)
  {
    segments = segments | DP_SEGMENT;
  }
  display1.setSegments(segments, physical);
}

Memory.h

C/C++
/**
 * ATtiny1614 Tube Clock
 * John Bradnam (jbrad2089@gmail.com)
 * 
 * 2021-10-10 - Create EEPROM functions for clock
 *
*/

#pragma once

//Uncomment to reset EEPROM data
//#define RESET_EEPROM

#ifdef __AVR_ATtiny1614__
#include <avr/eeprom.h>
#else
#include <EEPROM.h>
#endif

//EEPROM handling
#define EEPROM_ADDRESS 0
#define EEPROM_MAGIC 0x0DAD0BAD
typedef struct {
  uint32_t magic;
  bool alarmOn;
  int8_t alarmHour;
  int8_t alarmMinute;
} EEPROM_DATA;

volatile EEPROM_DATA EepromData;       //Current EEPROM settings

//-----------------------------------------------------------------------------------
// Forward references

void writeEepromData();
void readEepromData();

//---------------------------------------------------------------
//Write the EepromData structure to EEPROM
void writeEepromData()
{
  //This function uses EEPROM.update() to perform the write, so does not rewrites the value if it didn't change.
  #ifdef __AVR_ATtiny1614__
    eeprom_update_block (( void *) &EepromData , ( const void *) EEPROM_ADDRESS, sizeof(EepromData));  
  #else
    EEPROM.put(EEPROM_ADDRESS,EepromData);
  #endif
}

//---------------------------------------------------------------
//Read the EepromData structure from EEPROM, initialise if necessary
void readEepromData()
{
  //Eprom
  #ifdef __AVR_ATtiny1614__
    eeprom_read_block (( void *) &EepromData , ( const void *) EEPROM_ADDRESS, sizeof(EepromData));  
  #else
    EEPROM.get(EEPROM_ADDRESS,EepromData);
  #endif
  #ifndef RESET_EEPROM
  if (EepromData.magic != EEPROM_MAGIC)
  #endif
  {
    EepromData.magic = EEPROM_MAGIC;
    EepromData.alarmOn = false;
    EepromData.alarmHour = 6;
    EepromData.alarmMinute = 0;
    writeEepromData();
  }
}

Music.h

C/C++
/**
 * ATtiny1614 Tube Clock
 * John Bradnam (jbrad2089@gmail.com)
 * 
 * 2021-10-08 - Create tunes for clock
 *
*/

#pragma once

#include "Rotary.h"

#define SPEAKER   3   //PA7

// Constants for notes
#define REST   0
#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978
#define END_OF_TUNE 0xFFFF

#define DUR_8 0xE000
#define DUR_6 0xC000
#define DUR_4 0x8000
#define DUR_3 0x6000
#define DUR_2 0x4000
#define DUR_1 0x2000

// FR ELISE
const uint16_t melody_elise[] PROGMEM = {
  DUR_4|NOTE_E5, DUR_4|NOTE_DS5, DUR_4|NOTE_E5, DUR_4|NOTE_DS5, DUR_4|NOTE_E5, DUR_4|NOTE_B4, DUR_4|NOTE_D5, DUR_4|NOTE_C5, DUR_2|NOTE_A4, 
  DUR_8|NOTE_C4, DUR_4|NOTE_E3, DUR_4|NOTE_A4, DUR_2|NOTE_B4, DUR_8|NOTE_E3, DUR_4|NOTE_GS3, DUR_4|NOTE_B4, DUR_2|NOTE_C5,
  DUR_8|NOTE_E3,
  DUR_4|NOTE_E5, DUR_4|NOTE_DS5, DUR_4|NOTE_E5, DUR_4|NOTE_DS5, DUR_4|NOTE_E5, DUR_4|NOTE_B4, DUR_4|NOTE_D5, DUR_4|NOTE_C5, DUR_1|NOTE_A4, 
  DUR_4|REST, END_OF_TUNE 
};

// YOU ARE MY SUNSHINE
const uint16_t melody_sunshine[] PROGMEM = {
  DUR_8|NOTE_G3, DUR_8|NOTE_C4, DUR_8|NOTE_D4, DUR_4|NOTE_E4, DUR_4|NOTE_E4, DUR_8|REST, DUR_8|NOTE_E4, DUR_8|NOTE_DS4, DUR_8|NOTE_E4, DUR_4|NOTE_C4, DUR_4|NOTE_C4,
  DUR_8|REST, DUR_8|NOTE_C4, DUR_8|NOTE_D4, DUR_8|NOTE_E4, DUR_4|NOTE_F4, DUR_4|NOTE_A4, DUR_8|REST, DUR_8|NOTE_A4, DUR_8|NOTE_G4, DUR_8|NOTE_F4, DUR_2|NOTE_E4,
  DUR_8|REST, DUR_8|NOTE_C4, DUR_8|NOTE_D4, DUR_8|NOTE_E4, DUR_4|NOTE_F4, DUR_4|NOTE_A4, DUR_8|REST, DUR_8|NOTE_A4, DUR_8|NOTE_G4, DUR_8|NOTE_F4, DUR_4|NOTE_E4, DUR_4|NOTE_C4,
  DUR_4|REST, DUR_4|NOTE_C4, DUR_8|NOTE_D4, DUR_3|NOTE_E4, DUR_8|NOTE_F4, DUR_4|NOTE_D4, DUR_8|NOTE_D4, DUR_8|NOTE_E4, DUR_2|NOTE_C4, 
  DUR_4|REST, END_OF_TUNE 
};

// HOME ON THE RANGE
const uint16_t melody_range[] PROGMEM = {
  DUR_8|NOTE_G3, DUR_8|NOTE_G3, DUR_8|NOTE_C4, DUR_8|NOTE_D4, DUR_4|NOTE_E4, DUR_8|NOTE_C4, DUR_8|NOTE_B3, DUR_8|NOTE_A3, DUR_8|NOTE_F4, DUR_8|NOTE_F4, DUR_4|NOTE_F4,
  DUR_8|NOTE_E4, DUR_8|NOTE_F4, DUR_4|NOTE_G4, DUR_8|NOTE_C4, DUR_8|NOTE_C4, DUR_8|NOTE_C4, DUR_8|NOTE_B3, DUR_8|NOTE_C4, DUR_1|NOTE_D4,
  DUR_8|NOTE_G3, DUR_8|NOTE_G3, DUR_8|NOTE_C4, DUR_8|NOTE_D4, DUR_4|NOTE_E4, DUR_8|NOTE_C4, DUR_8|NOTE_B3, DUR_8|NOTE_A3, DUR_8|NOTE_F4, DUR_8|NOTE_F4, DUR_4|NOTE_F4,
  DUR_8|NOTE_F4, DUR_8|NOTE_F4, DUR_6|NOTE_E4, DUR_8|NOTE_D4, DUR_8|NOTE_C4, DUR_8|NOTE_B3, DUR_8|NOTE_C4, DUR_8|NOTE_D4, DUR_2|NOTE_C4, DUR_2|REST,
  DUR_2|NOTE_G4, DUR_8|NOTE_F4, DUR_6|NOTE_E4, DUR_8|NOTE_D4, DUR_1|NOTE_E4, 
  DUR_8|NOTE_G3, DUR_8|NOTE_G3, DUR_4|NOTE_C4, DUR_8|NOTE_C4, DUR_8|NOTE_C4, DUR_8|NOTE_C4, DUR_8|NOTE_C4, DUR_8|NOTE_B3, DUR_8|NOTE_C4, DUR_2|NOTE_D4,
  DUR_8|NOTE_G3, DUR_8|NOTE_G3, DUR_8|NOTE_C4, DUR_8|NOTE_D4, DUR_4|NOTE_E4, DUR_8|NOTE_C4, DUR_8|NOTE_B3, DUR_8|NOTE_A3, DUR_8|NOTE_F4, DUR_8|NOTE_F4, DUR_4|NOTE_F4,
  DUR_8|NOTE_F4, DUR_8|NOTE_F4, DUR_4|NOTE_E4, DUR_8|NOTE_D4, DUR_8|NOTE_C4, DUR_8|NOTE_B3, DUR_8|NOTE_C4, DUR_8|NOTE_D4, DUR_1|NOTE_C4,
  DUR_4|REST, END_OF_TUNE 
};

//-----------------------------------------------------------------------------------
// Forward references

void playSong(const uint16_t* melody);
void playNote(uint16_t noteRaw);

//---------------------------------------------------------------
// Play a melody
//  melody - one of the above melodies to play
void playSong(const uint16_t* melody)
{
  //Play each note in the melody until the END_OF_TUNE note is encountered
  int thisNote = 0;
  uint16_t noteRaw = pgm_read_word(&melody[thisNote++]);
  while (!rotarySwitchPressed && noteRaw != END_OF_TUNE)
  {
    playNote(noteRaw);
    noteRaw = pgm_read_word(&melody[thisNote++]);
  } //while
}

//---------------------------------------------------------------
// Play a note
//  noteRaw - Note made up of frequency and duration (to 3 bits are duration)
void playNote(uint16_t noteRaw)
{
  // to calculate the note duration, take one second divided by the note type.
  // e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
  uint16_t frequency = noteRaw & 0x1FFF;
  uint8_t duration = (noteRaw & 0xE000) >> 13;
  if (duration == 7)
    duration = 8;
  uint16_t noteDuration = 1800 / duration;

  int led = 0;
  if (frequency != REST)
  {
    tone(SPEAKER, frequency, noteDuration);
  }
    
  // to distinguish the notes, set a minimum time between them.
  // the note's duration + 30% seems to work well:
  uint16_t pauseBetweenNotes = (noteDuration * 13) / 10;
  delay(pauseBetweenNotes);

  if (frequency != REST)
  {
    // stop the tone playing:
    noTone(SPEAKER);
  }
}

Rotary.h

C/C++
/**
 * ATtiny1614 Tube Clock
 * John Bradnam (jbrad2089@gmail.com)
 * 
 * 2021-10-08 - Create rotary encoder functions for clock
 *
*/

#pragma once

#define ENC_S     8   //PA1
#define ENC_B     9   //PA2
#define ENC_A     10  //PA3

volatile int8_t rotaryMovement = 0;
volatile bool rotarySwitchPressed = false;

//-----------------------------------------------------------------------------------
// Forward references

void setupRotary();
void rotaryInterrupt();
void attachSwitchInterrupt();
void detachSwitchInterrupt();
void switchInterrupt();
bool isRotarySwitchPressed();

//---------------------------------------------------------------------
// Setup Hardware
void setupRotary() 
{
  pinMode(ENC_A,INPUT);
  pinMode(ENC_B,INPUT);
  pinMode(ENC_S,INPUT_PULLUP);

  attachInterrupt(ENC_A, rotaryInterrupt, FALLING);
}

//---------------------------------------------------------------------
// Rotary encoder has moved
void rotaryInterrupt()
{
  if (!digitalRead(ENC_A))
  {
    rotaryMovement = (digitalRead(ENC_B)) ? -1 : 1;
  }
}

//---------------------------------------------------------------------
// Attach interrupt on switch
void attachSwitchInterrupt()
{
  rotarySwitchPressed = false;
  attachInterrupt(ENC_S, switchInterrupt, CHANGE);
}

//---------------------------------------------------------------------
// Detach interrupt on switch
void detachSwitchInterrupt()
{
  detachInterrupt(ENC_S);
  //Wait until button is released      
  while (digitalRead(ENC_S) == LOW)
  {
    yield();
  }
  rotarySwitchPressed = false;
}

//---------------------------------------------------------------------
// Rotary encoder was pressed
void switchInterrupt()
{
  rotarySwitchPressed = rotarySwitchPressed | (digitalRead(ENC_S) == LOW);
}

//---------------------------------------------------------------------
// Rotary encoder was pressed
bool isRotarySwitchPressed()
{
  bool pressed = false;
  if (digitalRead(ENC_S) == LOW)
  {
    delay(10);  //10mS debounce switch
    if (digitalRead(ENC_S) == LOW)
    {
      //Wait until button is released      
      while (digitalRead(ENC_S) == LOW)
      {
        yield();
      }
      pressed = true;
    }
  }
  return pressed;
}

Credits

John Bradnam

John Bradnam

145 projects • 178 followers
Thanks to overlok.

Comments