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
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
/*
 * File:        finalproject.c
 * Adapted from: 
 *
 *              TFT_keypad_BRL4.c
 * Author:      Bruce Land
 *              main.c by
 * Author:      Syed Tahmid Mahbub
 * Target PIC:  PIC32MX250F128B
 */

// graphics libraries
#include "config.h"
#include "tft_master.h"
#include "tft_gfx.h"
// need for rand function
#include <stdlib.h>
#include <math.h>

// threading library
#include <plib.h>
// config.h sets 40 MHz
#define SYS_FREQ 40000000
#include "pt_cornell_1_2.h"

// string buffer
char buffer[60];
char text[60];
char loopnote[60];
unsigned int loopdur[60];

signed int sine_table[256];
float ramp_table[320];
signed int music;
signed int ramp_index, ramp_index2;
//initialize increments for frequencies 0=261.626 C, 1=277.183 C#, 2=293.665 D, 3=311.127 D#, 
//4=329.628 E, 5=349.228 F, 6=369.994 F#, 7=391.995 G, 8=415.305 G#, 9=440.000 A, 10=466.164 A#, 11=493.883 B, Hz
//incr = Fout*(2^32)/64000

int incr_table[] = {8778846, 9300618, 9853595, 10439790, 11060548, 11718214, 12414804, 13153338, 13935156,
    14763950, 15641734, 16571863, 17557692, 18601235, 19707189, 20879581, 22121095, 23436429, 24829609, 26306675, 27870311,
    29527900, 31283468, 33143726, 35115384, 37202470, 39414378, 41759162, 44242190, 46872858, 49659218, 52613350, 55740622,
    59058800, 62566936, 66287452, 70230768, 74404940, 78828756, 83518324, 88484380, 93745716, 99318436, 105226700, 111481244,
    118117600, 125133872, 132574904};
volatile unsigned int accu1, accu2, replay_counter = 0, replay_index = 0, metro = 60, metrocount = 0, loopcount = 0;
volatile char sig1, sig2, play = 0, play2 = 0, loop = 0, loopindex = 0, octave = 1, octavetoggle = 0, replay = 0, help = 0;

// === thread structures ============================================
// thread control structs
static struct pt pt_key, pt_metro;

/* ====== MCP4822 control word ==============
bit 15 A/B: DACA or DACB Selection bit
1 = Write to DACB
0 = Write to DACA
bit 14 ? Don?t Care
bit 13 GA: Output Gain Selection bit
1 = 1x (VOUT = VREF * D/4096)
0 = 2x (VOUT = 2 * VREF * D/4096), where internal VREF = 2.048V.
bit 12 SHDN: Output Shutdown Control bit
1 = Active mode operation. VOUT is available. ?
0 = Shutdown the selected DAC channel. Analog output is not available at the channel that was shut down.
VOUT pin is connected to 500 k???typical)?
bit 11-0 D11:D0: DAC Input Data bits. Bit x is ignored.
 */
// A-channel, 1x, active
#define DAC_config_chan_A 0b0011000000000000

//== Timer 3 interrupt handler ===========================================
volatile unsigned int DAC_data; // output value
volatile SpiChannel spiChn = SPI_CHANNEL2; // the SPI channel to use
volatile int spiClkDiv = 2; // 20 MHz max speed for this DAC

// == Timer 3 ISR =====================================================
// DDS

void __ISR(_TIMER_3_VECTOR, ipl2) Timer3Handler(void) {

    // generate a trigger strobe for timing other events
    mPORTBClearBits(BIT_4); // start transaction CS low
    // add accumulator to increment table
    metrocount++;
    // loop mode
    if (loop) {
        loopcount++;
    }  // signal tone dds
    else if (loopnote[0]) {
        replay_counter--;
    }

    accu1 = accu1 + incr_table[sig1];

    if (sig2 != 49) { // not silence
        accu2 = accu2 + incr_table[sig2];
    } else {
        accu2 = 0;
    } // silence

    music = 0; //reset music since music += below line 115 (explode dac)

    // single tone signal generator
    int sine_index1 = (accu1) >> 24;
    if (play == 1) {
        music = (ramp_table[ramp_index])*(sine_table[sine_index1]);
        ramp_index++;
        if (ramp_index == 320) play = 2;
    } else if (play == 2) {
        music = (sine_table[sine_index1]);
        //if (replay_counter == 1) play = 3;
    } else if (play == 3) {
        music = (ramp_table[ramp_index])*(sine_table[sine_index1]);
        ramp_index--;
        if (ramp_index == -1) {
            play = 0;
        }
    }
    
    //signal generator for two notes at same time
    int sine_index2 = (accu2) >> 24;
    if (play2 == 1) { // ramp up
        music += (ramp_table[ramp_index2])*(sine_table[sine_index2]); // convolve ramp with sine
        ramp_index2++;
        if (ramp_index2 == 320) play2 = 2;
    } else if (play2 == 2) { // constant signal
        music += (sine_table[sine_index2]);
        if (replay_counter == 1) {
            play2 = 3; // ramp down
            ramp_index2 = 319;
        }
    } else if (play2 == 3) {
        music += (ramp_table[ramp_index2])*(sine_table[sine_index2]);
        ramp_index2--;
        if (ramp_index2 == -1) {
            replay_index++; //go to the next note or silence
            if (!loopnote[replay_index]) replay_index = 0;
            replay_counter = loopdur[replay_index] - 320; //dur of next note - ramp down
            sig2 = loopnote[replay_index];
            play2 = 1;
        }
    }

    // test for ready
    while (TxBufFullSPI2());
    // write to added sine waves
    WriteSPI2(DAC_config_chan_A | music + 2047);
    // test for done
    while (SPI2STATbits.SPIBUSY); // wait for end of transaction
    // clear the timer interrupt flag
    mT3ClearIntFlag();
    mPORTBSetBits(BIT_4); // end transaction CS high

}

// === Key Thread ==========================
static int keypad, ia = 0, ib = 0, b3 = 0, b2 = 0, i = 0, pattern, PushState = 10, previ, n;
volatile int k = 0;
volatile int test_counter = 0;

#define NoPush 10 
#define Pushed 20
#define MaybePush 30 
#define MaybeNoPush 40

static PT_THREAD(protothread_key(struct pt *pt)) {
    PT_BEGIN(pt);
    static char blackkey = 0;
    mPORTBSetPinsDigitalIn(BIT_3 | BIT_6 | BIT_7 | BIT_8 | BIT_9 | BIT_10 | BIT_11 | BIT_13);
    mPORTASetPinsDigitalIn(BIT_0 | BIT_2 | BIT_3 | BIT_4);
    //initialize display on startup
    tft_setTextColor(ILI9340_RED);
    tft_setTextSize(2);
    tft_setCursor(160, 140);
    tft_writeString("Octave");
    tft_setCursor(202, 160);
    sprintf(text, "%d", octave+3);
    tft_writeString(text);
    tft_setCursor(10, 140);
    tft_writeString("BPM");
    tft_setTextColor(ILI9340_WHITE);
    tft_setCursor(172, 160);
    sprintf(text, "%d", octave+2);
    tft_writeString(text);
    tft_setCursor(10, 160);
    sprintf(text, "%d", metro);
    tft_writeString(text);
    tft_fillCircle(32, 300, 4, ILI9340_RED);
    tft_fillCircle(48, 300, 4, ILI9340_BLUE);
    tft_fillCircle(64, 300, 4, ILI9340_WHITE);
    tft_fillCircle(80, 300, 4, ILI9340_BLUE);
    tft_fillCircle(96, 300, 4, ILI9340_WHITE);
    tft_fillCircle(112, 300, 4, ILI9340_WHITE);
    tft_fillCircle(128, 300, 4, ILI9340_BLUE);
    tft_fillCircle(144, 300, 4, ILI9340_WHITE);
    tft_fillCircle(160, 300, 4, ILI9340_BLUE);
    tft_fillCircle(176, 300, 4, ILI9340_WHITE);
    tft_fillCircle(192, 300, 4, ILI9340_BLUE);
    tft_fillCircle(208, 300, 4, ILI9340_RED);
    while (1) {
        PT_YIELD_TIME_msec(10);
        
        // reading input bits from keys
        b3 = mPORTBReadBits(BIT_3);
        b3 = b3 >> 2; // make bit_1
        b2 = mPORTBReadBits(BIT_2);
        b2 = b2 << 4; // make bit_6
        ia = mPORTAReadBits(BIT_0 | BIT_2 | BIT_3 | BIT_4);
        ib = mPORTBReadBits(BIT_7 | BIT_8 | BIT_9 | BIT_10 | BIT_11 | BIT_13);
        i = (ia | ib | b3 | b2);
        i = i | 0b01000000000000; // turn on bit_12 to make our math work otherwise subtract 2^12
        switch (PushState) { // key debounce FSM

            case NoPush:
                if (i == 16351) PushState = NoPush;
                else {
                    previ = i;
                    PushState = MaybePush;
                }
                break;

            case MaybePush: // process of being pushed
                if (previ == i) {
                    if (!help) { // do not play sounds when in help mode
                        if (i == 16350) {
                            sig1 = 0 + 12 * (octave+octavetoggle);
                            sprintf(text, "C");
                            blackkey = 0;
                        } else if (i == 16349) {
                            sig1 = 1 + 12 * (octave+octavetoggle);
                            sprintf(text, "C#/Db");
                            blackkey = 1;
                        } else if (i == 16347) {
                            sig1 = 2 + 12 * (octave+octavetoggle);
                            sprintf(text, "D");
                            blackkey = 0;
                        } else if (i == 16343) {
                            sig1 = 3 + 12 * (octave+octavetoggle);
                            sprintf(text, "D#/Eb");
                            blackkey = 1;
                        } else if (i == 16335) {
                            sig1 = 4 + 12 * (octave+octavetoggle);
                            sprintf(text, "E");
                            blackkey = 0;
                        } else if (i == 16287) {
                            sig1 = 5 + 12 * (octave+octavetoggle);
                            sprintf(text, "F");
                            blackkey = 0;
                        } else if (i == 16223) {
                            sig1 = 6 + 12 * (octave+octavetoggle);
                            sprintf(text, "F#/Gb");
                            blackkey = 1;
                        } else if (i == 16095) {
                            sig1 = 7 + 12 * (octave+octavetoggle);
                            sprintf(text, "G");
                            blackkey = 0;
                        } else if (i == 15839) {
                            sig1 = 8 + 12 * (octave+octavetoggle);
                            sprintf(text, "G#/Ab");
                            blackkey = 1;
                        } else if (i == 15327) {
                            sig1 = 9 + 12 * (octave+octavetoggle);
                            sprintf(text, "A");
                            blackkey = 0;
                        } else if (i == 14303) {
                            sig1 = 10 + 12 * (octave+octavetoggle);
                            sprintf(text, "A#/Bb");
                            blackkey = 1;
                        } else if (i == 8159) {
                            sig1 = 11 + 12 * (octave+octavetoggle);
                            sprintf(text, "B");
                            blackkey = 0;
                        }
                        if (blackkey != 2) {
                            if (blackkey == 1) {
                                tft_setCursor(60, 200); // so that key is centered
                                tft_fillCircle(32 + 16*(sig1%12), 294, 10, ILI9340_BLUE); // blow up key dot
                            }
                            else {
                                tft_setCursor(110, 200);
                                if (i == 8159 || i == 16350)
                                    tft_fillCircle(32 + 16*(sig1%12), 294, 10, ILI9340_RED);
                                else
                                    tft_fillCircle(32 + 16*(sig1%12), 294, 10, ILI9340_WHITE);
                            }
                            tft_setTextColor(ILI9340_WHITE);
                            tft_setTextSize(4);
                            tft_writeString(text); // display pressed key
                        }
                        tft_setTextSize(2); // text size for rewriting octave/bpm
                        if (i == 16271) {// octave select - middle green option buttons
                            octave = (octave+1)%3;
                            tft_fillRoundRect(172, 160, 10, 14, 0, ILI9340_BLACK);
                            tft_fillRoundRect(202, 160, 10, 14, 0, ILI9340_BLACK);
                            tft_setCursor(172+30*octavetoggle, 160);
                            tft_setTextColor(ILI9340_WHITE);
                            sprintf(text, "%d", octave + 2 + octavetoggle);
                            tft_writeString(text);
                            tft_setCursor(202-30*octavetoggle, 160);
                            tft_setTextColor(ILI9340_RED);
                            sprintf(text, "%d", octave + 3 - octavetoggle);
                            tft_writeString(text);
                            blackkey = 2;
                        }
                        else if (i == 14815) {// octave toggle - bottom option buttons
                            octavetoggle = !octavetoggle;
                            tft_setCursor(172+30*octavetoggle, 160);
                            tft_setTextColor(ILI9340_WHITE);
                            sprintf(text, "%d", octave + 2 + octavetoggle);
                            tft_writeString(text);
                            tft_setCursor(202-30*octavetoggle, 160);
                            tft_setTextColor(ILI9340_RED);
                            sprintf(text, "%d", octave + 3 - octavetoggle);
                            tft_writeString(text);
                            blackkey = 2;
                        }
                        else if (i == 16348) {// bpm increase - top option buttons
                            if (metro < 200) { // max bpm
                                metro += 5;
                                tft_fillRoundRect(10, 160, 40, 14, 0, ILI9340_BLACK);
                                tft_setCursor(10, 160);
                                tft_setTextColor(ILI9340_WHITE);
                                sprintf(text, "%d", metro);
                                tft_writeString(text);
                            }
                            blackkey = 2;
                        }
                        else if (i == 16339) {// bpm decrease - yellow option buttons
                            if (metro > 20) { // min bpm
                                metro -= 5;
                                tft_fillRoundRect(10, 160, 40, 14, 0, ILI9340_BLACK);
                                tft_setCursor(10, 160);
                                tft_setTextColor(ILI9340_WHITE);
                                sprintf(text, "%d", metro);
                                tft_writeString(text);
                            }
                            blackkey = 2;
                        }
                    }
                    
                    if (i == 8158 && !loop) { // help mode C and B
                        help = !help;
                        tft_fillScreen(ILI9340_BLACK);
                        if (help) { // enter help screen
                            tft_setTextColor(ILI9340_RED);
                            tft_setTextSize(4);
                            tft_setCursor(80, 10);
                            tft_writeString("HELP");
                            tft_fillCircle(20, 95, 4, ILI9340_GREEN);
                            tft_fillCircle(20, 105, 4, ILI9340_GREEN);
                            tft_fillCircle(20, 135, 4, ILI9340_YELLOW);
                            tft_fillCircle(20, 145, 4, ILI9340_YELLOW);
                            tft_fillCircle(20, 175, 4, ILI9340_GREEN);
                            tft_fillCircle(20, 185, 4, ILI9340_GREEN);
                            tft_fillCircle(20, 215, 4, ILI9340_RED);
                            tft_fillCircle(20, 225, 4, ILI9340_RED);
                            tft_fillCircle(20, 255, 4, ILI9340_BLUE);
                            tft_fillCircle(20, 265, 4, ILI9340_WHITE);
                            tft_setTextSize(1);
                            tft_setTextColor(ILI9340_WHITE);
                            tft_setCursor(37, 56);
                            tft_writeString("Press pair to select option");
                            tft_setCursor(40, 96);
                            tft_writeString("Increase metronome speed");
                            tft_setCursor(40, 136);
                            tft_writeString("Decrease metronome speed");
                            tft_setCursor(40, 176);
                            tft_writeString("Rotate through octave pairs");
                            tft_setCursor(40, 216);
                            tft_writeString("Start/stop recording");
                            tft_setCursor(40, 256);
                            tft_writeString("Toggle between octave pair");
                            tft_setCursor(20, 296);
                            tft_setTextColor(ILI9340_RED);
                            tft_writeString("Press the red end buttons to exit");
                        }
                        else { // exit help screen
                            tft_setTextColor(ILI9340_RED);
                            tft_setTextSize(2);
                            tft_setCursor(160, 140);
                            tft_writeString("Octave");
                            tft_setCursor(202-30*octavetoggle, 160);
                            sprintf(text, "%d", octave + 3 - octavetoggle);
                            tft_writeString(text);
                            tft_setCursor(10, 140);
                            tft_writeString("BPM");
                            tft_setTextColor(ILI9340_WHITE);
                            tft_setCursor(172+30*octavetoggle, 160);
                            sprintf(text, "%d", octave + 2 + octavetoggle);
                            tft_writeString(text);
                            tft_setCursor(10, 160);
                            sprintf(text, "%d", metro);
                            tft_writeString(text);
                            tft_fillCircle(32, 300, 4, ILI9340_RED);
                            tft_fillCircle(48, 300, 4, ILI9340_BLUE);
                            tft_fillCircle(64, 300, 4, ILI9340_WHITE);
                            tft_fillCircle(80, 300, 4, ILI9340_BLUE);
                            tft_fillCircle(96, 300, 4, ILI9340_WHITE);
                            tft_fillCircle(112, 300, 4, ILI9340_WHITE);
                            tft_fillCircle(128, 300, 4, ILI9340_BLUE);
                            tft_fillCircle(144, 300, 4, ILI9340_WHITE);
                            tft_fillCircle(160, 300, 4, ILI9340_BLUE);
                            tft_fillCircle(176, 300, 4, ILI9340_WHITE);
                            tft_fillCircle(192, 300, 4, ILI9340_BLUE);
                            tft_fillCircle(208, 300, 4, ILI9340_RED);
                        }
                    }
                    
                    if (loop) {
                        loopdur[loopindex] = loopcount; //saving duration of silence
                        loopindex++;
                        if (i != 15967) { // record - red option buttons
                            loopnote[loopindex] = sig1; //saving new note if not ending recording
                        }
                        loopcount = 0;
                    }
                    if (i == 15967 && !help) {// record - red option buttons
                        loop = !loop; //entering or exiting loop mode
                        if (!loop) { // recording ends
                            int q;
                            for (q = 0; q <= loopindex; q++) { // erase short sounds from double clicks
                                if (loopdur[q] < 6400 && loopdur[q] > 0) {
                                    loopnote[q] = 49; // set short sounds to silence
                                }
                            }
                            replay_index = 0;
                            accu2 = 0;
                            replay_counter = loopdur[0] - 320;
                            sig2 = loopnote[replay_index];
                            tft_fillRoundRect(40, 250, 160, 25, 0, ILI9340_BLACK);
                            ramp_index2 = 0;
                            play2 = 1;
                            replay = 1;
                        }
                        else { // recording starts
                            replay = 0;
                            sprintf(text, "%s", "RECORDING");
                            tft_setCursor(40, 250);
                            tft_setTextColor(ILI9340_RED);
                            tft_setTextSize(3);
                            tft_writeString(text);
                            sprintf(text, ""); // because sometimes "RECORDING" was being displayed as the key
                        }
                    }
                    accu1 = 0;
                    if (!help) play = 1;
                    ramp_index = 0;
                    PushState = Pushed;

                } else PushState = NoPush;

                break;

            case Pushed:
                if (previ == i) PushState = Pushed;
                else PushState = MaybeNoPush;
                break;

            case MaybeNoPush:
                if (!help) { // clear key push and reset key dots
                    tft_fillRoundRect(60, 200, 120, 30, 0, ILI9340_BLACK);
                    tft_fillCircle(32 + 16 * (sig1 % 12), 294, 10, ILI9340_BLACK);
                    tft_fillCircle(32, 300, 4, ILI9340_RED);
                    tft_fillCircle(48, 300, 4, ILI9340_BLUE);
                    tft_fillCircle(64, 300, 4, ILI9340_WHITE);
                    tft_fillCircle(80, 300, 4, ILI9340_BLUE);
                    tft_fillCircle(96, 300, 4, ILI9340_WHITE);
                    tft_fillCircle(112, 300, 4, ILI9340_WHITE);
                    tft_fillCircle(128, 300, 4, ILI9340_BLUE);
                    tft_fillCircle(144, 300, 4, ILI9340_WHITE);
                    tft_fillCircle(160, 300, 4, ILI9340_BLUE);
                    tft_fillCircle(176, 300, 4, ILI9340_WHITE);
                    tft_fillCircle(192, 300, 4, ILI9340_BLUE);
                    tft_fillCircle(208, 300, 4, ILI9340_RED);
                }
                if (previ == i) PushState = Pushed;
                else {
                    if (loop) {
                        if (previ == 15967) { // start recording - red option buttons
                            for (k=0; k<60; k++) {
                                loopnote[k] = 0;
                                loopdur[k] = 0;
                            }
                            loopindex = 0;
                        } else { // silence start
                            loopdur[loopindex] = loopcount;
                            loopindex++;
                        }
                        loopcount = 0;
                        loopnote[loopindex] = 49; //49 means silence
                    }
                    if (!help) play = 3;
                    ramp_index = 319;
                    PushState = NoPush;
                }
                break;
        } // end case
    } //END WHILE
    PT_END(pt);
}

// === Metronome Thread =============================================
static PT_THREAD(protothread_metro(struct pt *pt)) {
    static double theta = 3*M_PI_4;
    static int md = -1; // direction of metronome
    PT_BEGIN(pt);
    while (1) {
        // update ~33 times per sec
        PT_YIELD_TIME_msec(30);
        if (!help) {
            tft_fillCircle((int) 164*cos(theta)+120, (int) (180-164*sin(theta)), 2, ILI9340_BLACK);
            tft_fillCircle((int) 144*cos(theta)+120, (int) (180-144*sin(theta)), 2, ILI9340_BLACK);
            tft_fillCircle((int) 124*cos(theta)+120, (int) (180 - 124 * sin(theta)), 2, ILI9340_BLACK);
            tft_fillCircle((int) 104 * cos(theta) + 120, (int) (180 - 104 * sin(theta)), 2, ILI9340_BLACK);
            tft_fillCircle((int) 84 * cos(theta) + 120, (int) (180 - 84 * sin(theta)), 2, ILI9340_BLACK);
            //direction*(bpm/60)*(fraction of 1sec)*(pi/2)
            theta += md * ((double) metro / 60)*((double) metrocount / 64000) * M_PI_2;
            metrocount = 0; // reset metrocount immediately for precise timing
            if (theta > 3 * M_PI_4 || theta < M_PI_4) {
                md *= -1; //flip direction
                theta = (theta > 3 * M_PI_4 ? 3 * M_PI_4 : (theta < M_PI_4 ? M_PI_4 : theta)); // set to pi/4 or 3pi/4 if overflow
                tft_fillCircle((int) 164 * cos(theta) + 120, (int) (180 - 164 * sin(theta)), 2, ILI9340_WHITE);
                tft_fillCircle((int) 144 * cos(theta) + 120, (int) (180 - 144 * sin(theta)), 2, ILI9340_WHITE);
                tft_fillCircle((int) 124 * cos(theta) + 120, (int) (180 - 124 * sin(theta)), 2, ILI9340_WHITE);
                tft_fillCircle((int) 104 * cos(theta) + 120, (int) (180 - 104 * sin(theta)), 2, ILI9340_WHITE);
                tft_fillCircle((int) 84 * cos(theta) + 120, (int) (180 - 84 * sin(theta)), 2, ILI9340_WHITE);
            } else {
                tft_fillCircle((int) 164 * cos(theta) + 120, (int) (180 - 164 * sin(theta)), 2, ILI9340_BLUE);
                tft_fillCircle((int) 144 * cos(theta) + 120, (int) (180 - 144 * sin(theta)), 2, ILI9340_BLUE);
                tft_fillCircle((int) 124 * cos(theta) + 120, (int) (180 - 124 * sin(theta)), 2, ILI9340_BLUE);
                tft_fillCircle((int) 104 * cos(theta) + 120, (int) (180 - 104 * sin(theta)), 2, ILI9340_BLUE);
                tft_fillCircle((int) 84 * cos(theta) + 120, (int) (180 - 84 * sin(theta)), 2, ILI9340_BLUE);
            }
        }
        // NEVER exit while
    } // END WHILE(1)
    PT_END(pt);
} //metro thread


// === Main  ======================================================

void main(void) {
    SYSTEMConfigPerformance(PBCLK);

    ANSELA = 0;
    ANSELB = 0;
    CM1CON = 0;
    CM2CON = 0;

    // === config threads ==========
    // turns OFF UART support and debugger pin
    PT_setup();

    // timer interrupt //////////////////////////
    // Set up timer2 on,  interrupts, internal clock, prescalar 1, toggle rate
    OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_1, 625); // sampling at 64 kHz

    // set up the timer interrupt with a priority of 2
    ConfigIntTimer3(T3_INT_ON | T3_INT_PRIOR_2);
    mT3ClearIntFlag(); // and clear the interrupt flag

    // SCK2 is pin 26 
    // SDO2 (MOSI) is in PPS output group 2, could be connected to RB5 which is pin 14
    PPSOutput(2, RPB5, SDO2);

    // control CS for DAC pin 11
    mPORTBSetPinsDigitalOut(BIT_4);
    mPORTBSetBits(BIT_4);

    // divide Fpb by 2, configure the I/O ports. Not using SS in this example
    // 16 bit transfer CKP=1 CKE=1
    // possibles SPI_OPEN_CKP_HIGH;   SPI_OPEN_SMP_END;  SPI_OPEN_CKE_REV
    // For any given peripherial, you will need to match these
    SpiChnOpen(spiChn, SPI_OPEN_ON | SPI_OPEN_MODE16 | SPI_OPEN_MSTEN | SPI_OPEN_CKE_REV, spiClkDiv);


    // === setup system wide interrupts  ========
    INTEnableSystemMultiVectoredInt();

    //initialize sine table and ramp table
    int k;
    for (k = 0; k < 256; k++) {
        sine_table[k] = (int) (1023.0 * sin((float) k * 6.283 / (float) 256)); //8 bit amp, 256 samples
    }

    // initialize ramp table
    for (k = 0; k < 320; k++) {
        ramp_table[k] = (float) ((float) k / 320); // 5 msec ramp 6400kHz 
    }

    // init the threads
    PT_INIT(&pt_key);
    PT_INIT(&pt_metro);


    // init the display
    tft_init_hw();
    tft_begin();
    tft_fillScreen(ILI9340_BLACK);
    //240x320 vertical display
    tft_setRotation(0); // Use tft_setRotation(1) for 320x240

    // seed random color
    srand(1);

    // round-robin scheduler for threads
    while (1) {
        PT_SCHEDULE(protothread_key(&pt_key));
        PT_SCHEDULE(protothread_metro(&pt_metro));
    }
} // main

// === end  ====================================================== zx