// topoctave2.ino
// guest - openmusiclabs - 4.24.16
// creates 13 squarewaves for the top opctave of an organ

#define FREQ1 239 // on 8b timer @ 2MHz
#define FREQ2 253 // on 8b timer @ 2MHz
#define FREQ3 2145 // using 16b timer @16MHz, so value is ~8x
#define FREQ4 3460 // the rest use the assembler loop
#define FREQ5 3266 // and are calculated as:
#define FREQ6 3083 // # = 2*loop_cycles*note_frequency*65536/16MHz
#define FREQ7 2910 // i cant get them to be recognized in the inline
#define FREQ8 2746 // so they are just typed in down there, sorry
#define FREQ9 2592 // there are 60 cycles in the loop
#define FREQ10 2447
#define FREQ11 2309
#define FREQ12 2180
#define FREQ13 2058

void setup() {
  // setup t0 for FREQ1
  TIMSK0 = 0;
  TCCR0A = 0x33;
  TCCR0B = 0x0a;
  OCR0A = (FREQ1-1);
  OCR0B = (FREQ1/2);
  // setup t2 for FREQ2
  TIMSK2 = 0;
  TCCR2A = 0x33;
  TCCR2B = 0x0a;
  OCR2A = (FREQ2-1);
  OCR2B = (FREQ2/2);
  // setup t1 for FREQ3
  TIMSK1 = 0;
  TCCR1A = 0x33;
  TCCR1B = 0x19;
  TCCR1C = 0;
  OCR1AH = ((FREQ3-1)>>8);
  OCR1AL = ((FREQ3-1)&0xff);
  OCR1BH = ((FREQ3/2)>>8);
  OCR1BL = ((FREQ3/2)&0xff);
  // turn on output ports
  DDRB = 0x1f;
  DDRD = 0xff;
}

void loop() {
asm volatile ( // software counter loops
  "1: \n"
  "ldi r16,0x01 \n"
  "subi r18,lo8(-(3460)) \n"
  "sbci r19,hi8(-(3460)) \n"
  "brcs 2f \n"
  "eor r0,r16 \n"
  
  "2: \n"
  "ldi r16,0x02 \n"
  "subi r20,lo8(-(3266)) \n"
  "sbci r21,hi8(-(3266)) \n"
  "brcs 3f \n"
  "eor r0,r16 \n"
  
  "3: \n"
  "ldi r16,0x04 \n"
  "subi r22,lo8(-(3083)) \n"
  "sbci r23,hi8(-(3083)) \n"
  "brcs 4f \n"
  "eor r0,r16 \n"
  
  "4: \n"
  "ldi r16,0x10 \n"
  "subi r24,lo8(-(2910)) \n"
  "sbci r25,hi8(-(2910)) \n"
  "brcs 5f \n"
  "eor r0,r16 \n"
  
  "5: \n"
  "ldi r16,0x40 \n"
  "subi r26,lo8(-(2746)) \n"
  "sbci r27,hi8(-(2746)) \n"
  "brcs 6f \n"
  "eor r0,r16 \n"
  
  "6: \n"
  "ldi r16,0x80 \n"
  "subi r28,lo8(-(2592)) \n"
  "sbci r29,hi8(-(2592)) \n"
  "brcs 7f \n"
  "eor r0,r16 \n"
  
  "7: \n"
  "ldi r16,0x01 \n"
  "subi r30,lo8(-(2447)) \n"
  "sbci r31,hi8(-(2447)) \n"
  "brcs 8f \n"
  "eor r1,r16 \n"
  
  "8: \n"
  "ldi r16,0x02 \n"
  "ldi r17,lo8((2309)) \n"
  "add r14,r17 \n"
  "ldi r17,hi8((2309)) \n"
  "adc r15,r17 \n"
  "brcc 9f \n"
  "eor r1,r16 \n"
  
  "9: \n"
  "ldi r16,0x08 \n"
  "ldi r17,lo8((2180)) \n"
  "add r12,r17 \n"
  "ldi r17,hi8((2180)) \n"
  "adc r13,r17 \n"
  "brcc 10f \n"
  "eor r1,r16 \n"
  
  "10: \n"
  "ldi r16,0x10 \n"
  "ldi r17,lo8((2058)) \n"
  "add r10,r17 \n"
  "ldi r17,hi8((2058)) \n"
  "adc r11,r17 \n"
  "brcc 11f \n"
  "eor r1,r16 \n"
  
  "11: \n"
  "out 0x0b,r0 \n"
  "out 0x05,r1 \n"
  "rjmp 1b \n"
); 
}
