Share

Musical Lighter

Musical Lighter

This project started when the original chip in my musical lighter died. After much research trying to find the original lighter again online without any success, I thought I'd try to replace the chip. The PCBA didn't have any markings, and the chip on it was black-epoxied over.

I first decided to try replacing it with an ATtiny85, but after lots and lots of hours sending code to a Digispark board I'd bought online, I ended up corrupting all of them, because they all rely on very unreliable flashing. After much more research, I landed on the PIC16F18313 in the UDFN package. This chip is an absolute pleasure to work with — it's pretty sturdy and doesn't need much to get it running. I installed a 10k pull-up on MCLRE and a decoupling capacitor. Looking back, I could've bought a programmer for the tinyAVR family, but I wanted to dip my toes into something new. Staying in the AVR family would've probably simplified the code side of this project.

I ended up running a jumper from one GND pad to another GND pad because of DRC constraints.


The code was written by Claude after many iterations. For some reason, the C compiler doesn't allow variable delays and needs delays calculated at compile time, so this code took a lot of tries. The song was pulled from robsoncouto's repo, arduino-songs. Code is at the end of the page.

// Cantina Band - PIC16F18313
// Buzzer on RA2, XC8 compiler
// Configuration: MCLRE=OFF, internal oscillator 32MHz

// PIC16F18313 Configuration Bit Settings

// 'C' source line config statements

// CONFIG1
#pragma config FEXTOSC = ECH    // FEXTOSC External Oscillator mode Selection bits (EC (external clock) above 8 MHz)
#pragma config RSTOSC = HFINT32 // Power-up default value for COSC bits (HFINTOSC with 2x PLL (32MHz))
#pragma config CLKOUTEN = OFF   // Clock Out Enable bit (CLKOUT function is disabled; I/O or oscillator function on OSC2)
#pragma config CSWEN = ON       // Clock Switch Enable bit (Writing to NOSC and NDIV is allowed)
#pragma config FCMEN = ON       // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is enabled)

// CONFIG2
#pragma config MCLRE = OFF      // Master Clear Enable bit (MCLR/VPP pin function is digital input; MCLR internally disabled; Weak pull-up under control of port pin's WPU control bit.)
#pragma config PWRTE = ON       // Power-up Timer Enable bit (PWRT enabled)
#pragma config WDTE = OFF       // Watchdog Timer Enable bits (WDT disabled; SWDTEN is ignored)
#pragma config LPBOREN = OFF    // Low-power BOR enable bit (ULPBOR disabled)
#pragma config BOREN = ON       // Brown-out Reset Enable bits (Brown-out Reset enabled, SBOREN bit ignored)
#pragma config BORV = LOW       // Brown-out Reset Voltage selection bit (Brown-out voltage (Vbor) set to 2.45V)
#pragma config PPS1WAY = ON     // PPSLOCK bit One-Way Set Enable bit (The PPSLOCK bit can be cleared and set only once; PPS registers remain locked after one clear/set cycle)
#pragma config STVREN = ON      // Stack Overflow/Underflow Reset Enable bit (Stack Overflow or Underflow will cause a Reset)
#pragma config DEBUG = OFF      // Debugger enable bit (Background debugger disabled)

// CONFIG3
#pragma config WRT = OFF        // User NVM self-write protection bits (Write protection off)
#pragma config LVP = OFF        // Low Voltage Programming Enable bit (HV on MCLR/VPP must be used for programming.)

// CONFIG4
#pragma config CP = OFF         // User NVM Program Memory Code Protection bit (User NVM code protection disabled)
#pragma config CPD = OFF        // Data NVM Memory Code Protection bit (Data NVM code protection disabled)


#include <xc.h>
#include <stdint.h>
#include <stdlib.h>  // for abs()

#define _XTAL_FREQ   32000000UL
#define BUZZER_PIN LATAbits.LATA2
#define BUZZER_TRIS TRISAbits.TRISA2

// ---- Note definitions ----
#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

// ---- Melody ----
int tempo = 200;

const int melody[] = {
    NOTE_B4,-4, NOTE_E5,-4, NOTE_B4,-4, NOTE_E5,-4,
    NOTE_B4,8,  NOTE_E5,-4, NOTE_B4,8, REST,8,  NOTE_AS4,8, NOTE_B4,8,
    NOTE_B4,8,  NOTE_AS4,8, NOTE_B4,8, NOTE_A4,8, REST,8, NOTE_GS4,8, NOTE_A4,8, NOTE_G4,8,
    NOTE_G4,4,  NOTE_E4,-2,
    NOTE_B4,-4, NOTE_E5,-4, NOTE_B4,-4, NOTE_E5,-4,
    NOTE_B4,8,  NOTE_E5,-4, NOTE_B4,8, REST,8,  NOTE_AS4,8, NOTE_B4,8,
    NOTE_A4,-4, NOTE_A4,-4, NOTE_GS4,8, NOTE_A4,-4,
    NOTE_D5,8,  NOTE_C5,-4, NOTE_B4,-4, NOTE_A4,-4,
    NOTE_B4,-4, NOTE_E5,-4, NOTE_B4,-4, NOTE_E5,-4,
    NOTE_B4,8,  NOTE_E5,-4, NOTE_B4,8, REST,8,  NOTE_AS4,8, NOTE_B4,8,
    NOTE_D5,4, NOTE_D5,-4, NOTE_B4,8, NOTE_A4,-4,
    NOTE_G4,-4, NOTE_E4,-2,
    NOTE_E4,2, NOTE_G4,2,
    NOTE_B4,2, NOTE_D5,2,
    NOTE_F5,-4, NOTE_E5,-4, NOTE_AS4,8, NOTE_AS4,8, NOTE_B4,4, NOTE_G4,4,
};
 
// ---- Tone generation ----
// Bit-bang a square wave on RA2 for the given frequency and duration (ms)

 
// ?? Microsecond delay (software-calibrated, no hardware timer) ????????????????
//
// Inner loop timing at 32 MHz (8 MIPS, 1 instruction cycle = 0.125 µs):
//
//   _delay(5)           ? 5 instruction cycles  (guaranteed by XC8)
//   while(uint8_t--)    ? DECFSZ + BRA/GOTO = 3 instruction cycles overhead
//   ?????????????????????????????????????????????????????????????????????
//   Per iteration total =  8 instruction cycles = 1 µs  ?
//
// We use a uint8_t inner counter (not uint16_t) because the uint16_t decrement
// in XC8 costs ~7 cycles of overhead, which would break the calibration.
// Delays > 255 µs are handled by iterating the outer uint16_t counter.
//
static void delay_us(uint16_t us) {
    while (us > 0) {
        uint8_t chunk = (us > 255) ? 255 : (uint8_t)us;
        us -= chunk;
        while (chunk--) {
            _delay(5);   /* 5 cycles + DECFSZ/BRA 3 cycles = 8 cycles = 1 µs */
        }
    }
}
 
// ?? Millisecond delay (XC8 instruction-cycle delay, accurate) ?????????????????
static void delay_ms(uint16_t ms) {
    for (uint16_t i = 0; i < ms; i++) __delay_ms(1);
}
 
// ?? Tone generation ???????????????????????????????????????????????????????????
void tone(uint16_t freq, uint16_t duration_ms) {
    if (freq == 0) {
        delay_ms(duration_ms);
        return;
    }
 
    // half-period in µs: 500 000 / freq
    // e.g. B4 (494 Hz) ? 1012 µs,  E5 (659 Hz) ? 758 µs
    uint16_t half = (uint16_t)(500000UL / freq);
 
    // number of complete square-wave cycles to produce
    uint32_t cycles = (uint32_t)freq * duration_ms / 1000;
 
    for (uint32_t i = 0; i < cycles; i++) {
        BUZZER_PIN = 1;
        delay_us(half);
        BUZZER_PIN = 0;
        delay_us(half);
    }
}


// ---- Sleep ----
void goToSleep(void) {
    BUZZER_PIN = 0;
    SLEEP();
}
 
// ---- Main ----
void main(void) {
    BUZZER_TRIS = 0;
    BUZZER_PIN  = 0;
    ANSELA      = 0x00;   // all pins digital
 

 
    int notes     = sizeof(melody) / sizeof(melody[0]) / 2;
    int wholenote = (60000 * 2) / tempo;   // ms for a whole note
 
    for (int i = 0; i < notes * 2; i += 2) {
 
        int divider = melody[i + 1];
        int noteDuration;
 
        if (divider > 0) {
            noteDuration = wholenote / divider;
        } else {
            // dotted note = 1.5× the straight value
            noteDuration = wholenote / abs(divider);
            noteDuration = (noteDuration * 3) / 2;
        }
 
        // Play tone for 90 % of the note duration, then a 10 % silence gap.
        // This mirrors the Arduino behaviour:
        //   tone(pin, freq, noteDuration*0.9);  ? non-blocking on AVR
        //   delay(noteDuration);                ? full note timing
        //   noTone(pin);
        tone((uint16_t)melody[i],
             (uint16_t)(noteDuration * 9 / 10));   // 90 % tone
 
        delay_ms((uint16_t)(noteDuration / 10));    // 10 % gap
    }
 
    goToSleep();
}