support 2nd player streaming from separate raw file
[megadrive.git] / teensy3 / pins_teensy.c
1 /* Teensyduino Core Library
2  * http://www.pjrc.com/teensy/
3  * Copyright (c) 2013 PJRC.COM, LLC.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sublicense, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * 1. The above copyright notice and this permission notice shall be 
14  * included in all copies or substantial portions of the Software.
15  *
16  * 2. If the Software is incorporated into a build system that allows 
17  * selection among a list of target devices, then similar target
18  * devices manufactured by PJRC.COM must be included in the list of
19  * target devices and selectable in the same manner.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
25  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
26  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
27  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28  * SOFTWARE.
29  */
30
31 #include "core_pins.h"
32 #include "pins_arduino.h"
33 //#include "HardwareSerial.h"
34
35 #if 0
36 // moved to pins_arduino.h
37 struct digital_pin_bitband_and_config_table_struct {
38         volatile uint32_t *reg;
39         volatile uint32_t *config;
40 };
41 const struct digital_pin_bitband_and_config_table_struct digital_pin_to_info_PGM[];
42
43 // compatibility macros
44 #define digitalPinToPort(pin) (pin)
45 #define digitalPinToBitMask(pin) (1)
46 #define portOutputRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 0))
47 #define portSetRegister(pin)    ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 32))
48 #define portClearRegister(pin)  ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 64))
49 #define portToggleRegister(pin) ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 96))
50 #define portInputRegister(pin)  ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 128))
51 #define portModeRegister(pin)   ((volatile uint8_t *)(digital_pin_to_info_PGM[(pin)].reg + 160))
52 #define portConfigRegister(pin) ((volatile uint32_t *)(digital_pin_to_info_PGM[(pin)].config))
53 #endif
54
55 //#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
56 //#define analogInPinToBit(P) (P)
57
58 #define GPIO_BITBAND_ADDR(reg, bit) (((uint32_t)&(reg) - 0x40000000) * 32 + (bit) * 4 + 0x42000000)
59 #define GPIO_BITBAND_PTR(reg, bit) ((uint32_t *)GPIO_BITBAND_ADDR((reg), (bit)))
60 //#define GPIO_SET_BIT(reg, bit) (*GPIO_BITBAND_PTR((reg), (bit)) = 1)
61 //#define GPIO_CLR_BIT(reg, bit) (*GPIO_BITBAND_PTR((reg), (bit)) = 0)
62
63 const struct digital_pin_bitband_and_config_table_struct digital_pin_to_info_PGM[] = {
64         {GPIO_BITBAND_PTR(CORE_PIN0_PORTREG, CORE_PIN0_BIT), &CORE_PIN0_CONFIG},
65         {GPIO_BITBAND_PTR(CORE_PIN1_PORTREG, CORE_PIN1_BIT), &CORE_PIN1_CONFIG},
66         {GPIO_BITBAND_PTR(CORE_PIN2_PORTREG, CORE_PIN2_BIT), &CORE_PIN2_CONFIG},
67         {GPIO_BITBAND_PTR(CORE_PIN3_PORTREG, CORE_PIN3_BIT), &CORE_PIN3_CONFIG},
68         {GPIO_BITBAND_PTR(CORE_PIN4_PORTREG, CORE_PIN4_BIT), &CORE_PIN4_CONFIG},
69         {GPIO_BITBAND_PTR(CORE_PIN5_PORTREG, CORE_PIN5_BIT), &CORE_PIN5_CONFIG},
70         {GPIO_BITBAND_PTR(CORE_PIN6_PORTREG, CORE_PIN6_BIT), &CORE_PIN6_CONFIG},
71         {GPIO_BITBAND_PTR(CORE_PIN7_PORTREG, CORE_PIN7_BIT), &CORE_PIN7_CONFIG},
72         {GPIO_BITBAND_PTR(CORE_PIN8_PORTREG, CORE_PIN8_BIT), &CORE_PIN8_CONFIG},
73         {GPIO_BITBAND_PTR(CORE_PIN9_PORTREG, CORE_PIN9_BIT), &CORE_PIN9_CONFIG},
74         {GPIO_BITBAND_PTR(CORE_PIN10_PORTREG, CORE_PIN10_BIT), &CORE_PIN10_CONFIG},
75         {GPIO_BITBAND_PTR(CORE_PIN11_PORTREG, CORE_PIN11_BIT), &CORE_PIN11_CONFIG},
76         {GPIO_BITBAND_PTR(CORE_PIN12_PORTREG, CORE_PIN12_BIT), &CORE_PIN12_CONFIG},
77         {GPIO_BITBAND_PTR(CORE_PIN13_PORTREG, CORE_PIN13_BIT), &CORE_PIN13_CONFIG},
78         {GPIO_BITBAND_PTR(CORE_PIN14_PORTREG, CORE_PIN14_BIT), &CORE_PIN14_CONFIG},
79         {GPIO_BITBAND_PTR(CORE_PIN15_PORTREG, CORE_PIN15_BIT), &CORE_PIN15_CONFIG},
80         {GPIO_BITBAND_PTR(CORE_PIN16_PORTREG, CORE_PIN16_BIT), &CORE_PIN16_CONFIG},
81         {GPIO_BITBAND_PTR(CORE_PIN17_PORTREG, CORE_PIN17_BIT), &CORE_PIN17_CONFIG},
82         {GPIO_BITBAND_PTR(CORE_PIN18_PORTREG, CORE_PIN18_BIT), &CORE_PIN18_CONFIG},
83         {GPIO_BITBAND_PTR(CORE_PIN19_PORTREG, CORE_PIN19_BIT), &CORE_PIN19_CONFIG},
84         {GPIO_BITBAND_PTR(CORE_PIN20_PORTREG, CORE_PIN20_BIT), &CORE_PIN20_CONFIG},
85         {GPIO_BITBAND_PTR(CORE_PIN21_PORTREG, CORE_PIN21_BIT), &CORE_PIN21_CONFIG},
86         {GPIO_BITBAND_PTR(CORE_PIN22_PORTREG, CORE_PIN22_BIT), &CORE_PIN22_CONFIG},
87         {GPIO_BITBAND_PTR(CORE_PIN23_PORTREG, CORE_PIN23_BIT), &CORE_PIN23_CONFIG},
88         {GPIO_BITBAND_PTR(CORE_PIN24_PORTREG, CORE_PIN24_BIT), &CORE_PIN24_CONFIG},
89         {GPIO_BITBAND_PTR(CORE_PIN25_PORTREG, CORE_PIN25_BIT), &CORE_PIN25_CONFIG},
90         {GPIO_BITBAND_PTR(CORE_PIN26_PORTREG, CORE_PIN26_BIT), &CORE_PIN26_CONFIG},
91         {GPIO_BITBAND_PTR(CORE_PIN27_PORTREG, CORE_PIN27_BIT), &CORE_PIN27_CONFIG},
92         {GPIO_BITBAND_PTR(CORE_PIN28_PORTREG, CORE_PIN28_BIT), &CORE_PIN28_CONFIG},
93         {GPIO_BITBAND_PTR(CORE_PIN29_PORTREG, CORE_PIN29_BIT), &CORE_PIN29_CONFIG},
94         {GPIO_BITBAND_PTR(CORE_PIN30_PORTREG, CORE_PIN30_BIT), &CORE_PIN30_CONFIG},
95         {GPIO_BITBAND_PTR(CORE_PIN31_PORTREG, CORE_PIN31_BIT), &CORE_PIN31_CONFIG},
96         {GPIO_BITBAND_PTR(CORE_PIN32_PORTREG, CORE_PIN32_BIT), &CORE_PIN32_CONFIG},
97         {GPIO_BITBAND_PTR(CORE_PIN33_PORTREG, CORE_PIN33_BIT), &CORE_PIN33_CONFIG}
98 };
99
100
101
102
103 typedef void (*voidFuncPtr)(void);
104 volatile static voidFuncPtr intFunc[CORE_NUM_DIGITAL];
105
106 void init_pin_interrupts(void)
107 {
108         //SIM_SCGC5 = 0x00043F82;               // clocks active to all GPIO
109         NVIC_ENABLE_IRQ(IRQ_PORTA);
110         NVIC_ENABLE_IRQ(IRQ_PORTB);
111         NVIC_ENABLE_IRQ(IRQ_PORTC);
112         NVIC_ENABLE_IRQ(IRQ_PORTD);
113         NVIC_ENABLE_IRQ(IRQ_PORTE);
114         // TODO: maybe these should be set to a lower priority
115         // so if the user puts lots of slow code on attachInterrupt
116         // fast interrupts will still be serviced quickly?
117 }
118
119 void attachInterruptVector(enum IRQ_NUMBER_t irq, void (*function)(void))
120 {
121         _VectorsRam[irq + 16] = function;
122 }
123
124 void attachInterrupt(uint8_t pin, void (*function)(void), int mode)
125 {
126         volatile uint32_t *config;
127         uint32_t cfg, mask;
128
129         if (pin >= CORE_NUM_DIGITAL) return;
130         switch (mode) {
131           case CHANGE:  mask = 0x0B; break;
132           case RISING:  mask = 0x09; break;
133           case FALLING: mask = 0x0A; break;
134           case LOW:     mask = 0x08; break;
135           case HIGH:    mask = 0x0C; break;
136           default: return;
137         }
138         mask = (mask << 16) | 0x01000000;
139         config = portConfigRegister(pin);
140
141         __disable_irq();
142         cfg = *config;
143         cfg &= ~0x000F0000;             // disable any previous interrupt
144         *config = cfg;
145         intFunc[pin] = function;        // set the function pointer
146         cfg |= mask;
147         *config = cfg;                  // enable the new interrupt
148         __enable_irq();
149 }
150
151 void detachInterrupt(uint8_t pin)
152 {
153         volatile uint32_t *config;
154
155         config = portConfigRegister(pin);
156         __disable_irq();
157         *config = ((*config & ~0x000F0000) | 0x01000000);
158         intFunc[pin] = NULL;
159         __enable_irq();
160 }
161
162
163 void porta_isr(void)
164 {
165         uint32_t isfr = PORTA_ISFR;
166         PORTA_ISFR = isfr;
167         if ((isfr & CORE_PIN3_BITMASK) && intFunc[3]) intFunc[3]();
168         if ((isfr & CORE_PIN4_BITMASK) && intFunc[4]) intFunc[4]();
169         if ((isfr & CORE_PIN24_BITMASK) && intFunc[24]) intFunc[24]();
170         if ((isfr & CORE_PIN33_BITMASK) && intFunc[33]) intFunc[33]();
171 }
172
173 void portb_isr(void)
174 {
175         uint32_t isfr = PORTB_ISFR;
176         PORTB_ISFR = isfr;
177         if ((isfr & CORE_PIN0_BITMASK) && intFunc[0]) intFunc[0]();
178         if ((isfr & CORE_PIN1_BITMASK) && intFunc[1]) intFunc[1]();
179         if ((isfr & CORE_PIN16_BITMASK) && intFunc[16]) intFunc[16]();
180         if ((isfr & CORE_PIN17_BITMASK) && intFunc[17]) intFunc[17]();
181         if ((isfr & CORE_PIN18_BITMASK) && intFunc[18]) intFunc[18]();
182         if ((isfr & CORE_PIN19_BITMASK) && intFunc[19]) intFunc[19]();
183         if ((isfr & CORE_PIN25_BITMASK) && intFunc[25]) intFunc[25]();
184         if ((isfr & CORE_PIN32_BITMASK) && intFunc[32]) intFunc[32]();
185 }
186
187 void portc_isr(void)
188 {
189         // TODO: these are inefficent.  Use CLZ somehow....
190         uint32_t isfr = PORTC_ISFR;
191         PORTC_ISFR = isfr;
192         if ((isfr & CORE_PIN9_BITMASK) && intFunc[9]) intFunc[9]();
193         if ((isfr & CORE_PIN10_BITMASK) && intFunc[10]) intFunc[10]();
194         if ((isfr & CORE_PIN11_BITMASK) && intFunc[11]) intFunc[11]();
195         if ((isfr & CORE_PIN12_BITMASK) && intFunc[12]) intFunc[12]();
196         if ((isfr & CORE_PIN13_BITMASK) && intFunc[13]) intFunc[13]();
197         if ((isfr & CORE_PIN15_BITMASK) && intFunc[15]) intFunc[15]();
198         if ((isfr & CORE_PIN22_BITMASK) && intFunc[22]) intFunc[22]();
199         if ((isfr & CORE_PIN23_BITMASK) && intFunc[23]) intFunc[23]();
200         if ((isfr & CORE_PIN27_BITMASK) && intFunc[27]) intFunc[27]();
201         if ((isfr & CORE_PIN28_BITMASK) && intFunc[28]) intFunc[28]();
202         if ((isfr & CORE_PIN29_BITMASK) && intFunc[29]) intFunc[29]();
203         if ((isfr & CORE_PIN30_BITMASK) && intFunc[30]) intFunc[30]();
204 }
205
206 void portd_isr(void)
207 {
208         uint32_t isfr = PORTD_ISFR;
209         PORTD_ISFR = isfr;
210         if ((isfr & CORE_PIN2_BITMASK) && intFunc[2]) intFunc[2]();
211         if ((isfr & CORE_PIN5_BITMASK) && intFunc[5]) intFunc[5]();
212         if ((isfr & CORE_PIN6_BITMASK) && intFunc[6]) intFunc[6]();
213         if ((isfr & CORE_PIN7_BITMASK) && intFunc[7]) intFunc[7]();
214         if ((isfr & CORE_PIN8_BITMASK) && intFunc[8]) intFunc[8]();
215         if ((isfr & CORE_PIN14_BITMASK) && intFunc[14]) intFunc[14]();
216         if ((isfr & CORE_PIN20_BITMASK) && intFunc[20]) intFunc[20]();
217         if ((isfr & CORE_PIN21_BITMASK) && intFunc[21]) intFunc[21]();
218 }
219
220 void porte_isr(void)
221 {
222         uint32_t isfr = PORTE_ISFR;
223         PORTE_ISFR = isfr;
224         if ((isfr & CORE_PIN26_BITMASK) && intFunc[26]) intFunc[26]();
225         if ((isfr & CORE_PIN31_BITMASK) && intFunc[31]) intFunc[31]();
226 }
227
228
229
230
231 unsigned long rtc_get(void)
232 {
233         return RTC_TSR;
234 }
235
236 void rtc_set(unsigned long t)
237 {
238         RTC_SR = 0;
239         RTC_TPR = 0;
240         RTC_TSR = t;
241         RTC_SR = RTC_SR_TCE;
242 }
243
244
245 // adjust is the amount of crystal error to compensate, 1 = 0.1192 ppm
246 // For example, adjust = -100 is slows the clock by 11.92 ppm
247 //
248 void rtc_compensate(int adjust)
249 {
250         uint32_t comp, interval, tcr;
251
252         // This simple approach tries to maximize the interval.
253         // Perhaps minimizing TCR would be better, so the
254         // compensation is distributed more evenly across
255         // many seconds, rather than saving it all up and then
256         // altering one second up to +/- 0.38%
257         if (adjust >= 0) {
258                 comp = adjust;
259                 interval = 256;
260                 while (1) {
261                         tcr = comp * interval;
262                         if (tcr < 128*256) break;
263                         if (--interval == 1) break;
264                 }
265                 tcr = tcr >> 8;
266         } else {
267                 comp = -adjust;
268                 interval = 256;
269                 while (1) {
270                         tcr = comp * interval;
271                         if (tcr < 129*256) break;
272                         if (--interval == 1) break;
273                 }
274                 tcr = tcr >> 8;
275                 tcr = 256 - tcr;
276         }
277         RTC_TCR = ((interval - 1) << 8) | tcr;
278 }
279
280 #if 0
281 // TODO: build system should define this
282 // so RTC is automatically initialized to approx correct time
283 // at least when the program begins running right after upload
284 #ifndef TIME_T
285 #define TIME_T 1350160272
286 #endif
287
288 void init_rtc(void)
289 {
290         serial_print("init_rtc\n");
291         //SIM_SCGC6 |= SIM_SCGC6_RTC;
292
293         // enable the RTC crystal oscillator, for approx 12pf crystal
294         if (!(RTC_CR & RTC_CR_OSCE)) {
295                 serial_print("start RTC oscillator\n");
296                 RTC_SR = 0;
297                 RTC_CR = RTC_CR_SC16P | RTC_CR_SC4P | RTC_CR_OSCE;
298         }
299         // should wait for crystal to stabilize.....
300
301         serial_print("SR=");
302         serial_phex32(RTC_SR);
303         serial_print("\n");
304         serial_print("CR=");
305         serial_phex32(RTC_CR);
306         serial_print("\n");
307         serial_print("TSR=");
308         serial_phex32(RTC_TSR);
309         serial_print("\n");
310         serial_print("TCR=");
311         serial_phex32(RTC_TCR);
312         serial_print("\n");
313
314         if (RTC_SR & RTC_SR_TIF) {
315                 // enable the RTC
316                 RTC_SR = 0;
317                 RTC_TPR = 0;
318                 RTC_TSR = TIME_T;
319                 RTC_SR = RTC_SR_TCE;
320         }
321 }
322 #endif
323
324 extern void usb_init(void);
325
326
327 // create a default PWM at the same 488.28 Hz as Arduino Uno
328
329 #if F_BUS == 60000000
330 #define DEFAULT_FTM_MOD (61440 - 1)
331 #define DEFAULT_FTM_PRESCALE 1
332 #elif F_BUS == 56000000
333 #define DEFAULT_FTM_MOD (57344 - 1)
334 #define DEFAULT_FTM_PRESCALE 1
335 #elif F_BUS == 48000000
336 #define DEFAULT_FTM_MOD (49152 - 1)
337 #define DEFAULT_FTM_PRESCALE 1
338 #elif F_BUS == 40000000
339 #define DEFAULT_FTM_MOD (40960 - 1)
340 #define DEFAULT_FTM_PRESCALE 1
341 #elif F_BUS == 36000000
342 #define DEFAULT_FTM_MOD (36864 - 1)
343 #define DEFAULT_FTM_PRESCALE 1
344 #elif F_BUS == 24000000
345 #define DEFAULT_FTM_MOD (49152 - 1)
346 #define DEFAULT_FTM_PRESCALE 0
347 #elif F_BUS == 16000000
348 #define DEFAULT_FTM_MOD (32768 - 1)
349 #define DEFAULT_FTM_PRESCALE 0
350 #elif F_BUS == 8000000
351 #define DEFAULT_FTM_MOD (16384 - 1)
352 #define DEFAULT_FTM_PRESCALE 0
353 #elif F_BUS == 4000000
354 #define DEFAULT_FTM_MOD (8192 - 1)
355 #define DEFAULT_FTM_PRESCALE 0
356 #elif F_BUS == 2000000
357 #define DEFAULT_FTM_MOD (4096 - 1)
358 #define DEFAULT_FTM_PRESCALE 0
359 #endif
360
361 //void init_pins(void)
362 void _init_Teensyduino_internal_(void)
363 {
364         init_pin_interrupts();
365
366         //SIM_SCGC6 |= SIM_SCGC6_FTM0;  // TODO: use bitband for atomic read-mod-write
367         //SIM_SCGC6 |= SIM_SCGC6_FTM1;
368         FTM0_CNT = 0;
369         FTM0_MOD = DEFAULT_FTM_MOD;
370         FTM0_C0SC = 0x28; // MSnB:MSnA = 10, ELSnB:ELSnA = 10
371         FTM0_C1SC = 0x28;
372         FTM0_C2SC = 0x28;
373         FTM0_C3SC = 0x28;
374         FTM0_C4SC = 0x28;
375         FTM0_C5SC = 0x28;
376         FTM0_C6SC = 0x28;
377         FTM0_C7SC = 0x28;
378         FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
379         FTM1_CNT = 0;
380         FTM1_MOD = DEFAULT_FTM_MOD;
381         FTM1_C0SC = 0x28;
382         FTM1_C1SC = 0x28;
383         FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
384 #if defined(__MK20DX256__)
385         FTM2_CNT = 0;
386         FTM2_MOD = DEFAULT_FTM_MOD;
387         FTM2_C0SC = 0x28;
388         FTM2_C1SC = 0x28;
389         FTM2_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
390 #endif
391
392         //analog_init();
393         //delay(100); // TODO: this is not necessary, right?
394         delay(4);
395         usb_init();
396 }
397
398 #if 0
399
400 static uint8_t analog_write_res = 8;
401
402 // SOPT4 is SIM select clocks?
403 // FTM is clocked by the bus clock, either 24 or 48 MHz
404 // input capture can be FTM1_CH0, CMP0 or CMP1 or USB start of frame
405 // 24 MHz with reload 49152 to match Arduino's speed = 488.28125 Hz
406
407 void analogWrite(uint8_t pin, int val)
408 {
409         uint32_t cval, max;
410
411 #if defined(__MK20DX256__)
412         if (pin == A14) {
413                 uint8_t res = analog_write_res;
414                 if (res < 12) {
415                         val <<= 12 - res;
416                 } else if (res > 12) {
417                         val >>= res - 12;
418                 }
419                 analogWriteDAC0(val);
420                 return;
421         }
422 #endif
423
424         max = 1 << analog_write_res;
425         if (val <= 0) {
426                 digitalWrite(pin, LOW);
427                 pinMode(pin, OUTPUT);   // TODO: implement OUTPUT_LOW
428                 return;
429         } else if (val >= max) {
430                 digitalWrite(pin, HIGH);
431                 pinMode(pin, OUTPUT);   // TODO: implement OUTPUT_HIGH
432                 return;
433         }
434
435         //serial_print("analogWrite\n");
436         //serial_print("val = ");
437         //serial_phex32(val);
438         //serial_print("\n");
439         //serial_print("analog_write_res = ");
440         //serial_phex(analog_write_res);
441         //serial_print("\n");
442         if (pin == 3 || pin == 4) {
443                 cval = ((uint32_t)val * (uint32_t)(FTM1_MOD + 1)) >> analog_write_res;
444 #if defined(__MK20DX256__)
445         } else if (pin == 25 || pin == 32) {
446                 cval = ((uint32_t)val * (uint32_t)(FTM2_MOD + 1)) >> analog_write_res;
447 #endif
448         } else {
449                 cval = ((uint32_t)val * (uint32_t)(FTM0_MOD + 1)) >> analog_write_res;
450         }
451         //serial_print("cval = ");
452         //serial_phex32(cval);
453         //serial_print("\n");
454         switch (pin) {
455           case 3: // PTA12, FTM1_CH0
456                 FTM1_C0V = cval;
457                 CORE_PIN3_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
458                 break;
459           case 4: // PTA13, FTM1_CH1
460                 FTM1_C1V = cval;
461                 CORE_PIN4_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
462                 break;
463           case 5: // PTD7, FTM0_CH7
464                 FTM0_C7V = cval;
465                 CORE_PIN5_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
466                 break;
467           case 6: // PTD4, FTM0_CH4
468                 FTM0_C4V = cval;
469                 CORE_PIN6_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
470                 break;
471           case 9: // PTC3, FTM0_CH2
472                 FTM0_C2V = cval;
473                 CORE_PIN9_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
474                 break;
475           case 10: // PTC4, FTM0_CH3
476                 FTM0_C3V = cval;
477                 CORE_PIN10_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
478                 break;
479           case 20: // PTD5, FTM0_CH5
480                 FTM0_C5V = cval;
481                 CORE_PIN20_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
482                 break;
483           case 21: // PTD6, FTM0_CH6
484                 FTM0_C6V = cval;
485                 CORE_PIN21_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
486                 break;
487           case 22: // PTC1, FTM0_CH0
488                 FTM0_C0V = cval;
489                 CORE_PIN22_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
490                 break;
491           case 23: // PTC2, FTM0_CH1
492                 FTM0_C1V = cval;
493                 CORE_PIN23_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
494                 break;
495 #if defined(__MK20DX256__)
496           case 32: // PTB18, FTM2_CH0
497                 FTM2_C0V = cval;
498                 CORE_PIN32_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
499                 break;
500           case 25: // PTB19, FTM1_CH1
501                 FTM2_C1V = cval;
502                 CORE_PIN25_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
503                 break;
504 #endif
505           default:
506                 digitalWrite(pin, (val > 127) ? HIGH : LOW);
507                 pinMode(pin, OUTPUT);
508         }
509 }
510
511 void analogWriteRes(uint32_t bits)
512 {
513         if (bits < 1) {
514                 bits = 1;
515         } else if (bits > 16) {
516                 bits = 16;
517         }
518         analog_write_res = bits;
519 }
520
521 void analogWriteFrequency(uint8_t pin, uint32_t frequency)
522 {
523         uint32_t minfreq, prescale, mod;
524
525         //serial_print("analogWriteFrequency: pin = ");
526         //serial_phex(pin);
527         //serial_print(", freq = ");
528         //serial_phex32(frequency);
529         //serial_print("\n");
530         for (prescale = 0; prescale < 7; prescale++) {
531                 minfreq = (F_BUS >> 16) >> prescale;
532                 if (frequency > minfreq) break;
533         }
534         //serial_print("F_BUS = ");
535         //serial_phex32(F_BUS >> prescale);
536         //serial_print("\n");
537         //serial_print("prescale = ");
538         //serial_phex(prescale);
539         //serial_print("\n");
540         //mod = ((F_BUS >> prescale) / frequency) - 1;
541         mod = (((F_BUS >> prescale) + (frequency >> 1)) / frequency) - 1;
542         if (mod > 65535) mod = 65535;
543         //serial_print("mod = ");
544         //serial_phex32(mod);
545         //serial_print("\n");
546         if (pin == 3 || pin == 4) {
547                 FTM1_SC = 0;
548                 FTM1_CNT = 0;
549                 FTM1_MOD = mod;
550                 FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(prescale);
551         } else if (pin == 5 || pin == 6 || pin == 9 || pin == 10 ||
552           (pin >= 20 && pin <= 23)) {
553                 FTM0_SC = 0;
554                 FTM0_CNT = 0;
555                 FTM0_MOD = mod;
556                 FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(prescale);
557         }
558 #if defined(__MK20DX256__)
559           else if (pin == 25 || pin == 32) {
560                 FTM2_SC = 0;
561                 FTM2_CNT = 0;
562                 FTM2_MOD = mod;
563                 FTM2_SC = FTM_SC_CLKS(1) | FTM_SC_PS(prescale);
564         }
565 #endif
566 }
567
568 #endif
569
570
571 // TODO: startup code needs to initialize all pins to GPIO mode, input by default
572
573 void digitalWrite(uint8_t pin, uint8_t val)
574 {
575         if (pin >= CORE_NUM_DIGITAL) return;
576         if (*portModeRegister(pin)) {
577                 if (val) {
578                         *portSetRegister(pin) = 1;
579                 } else {
580                         *portClearRegister(pin) = 1;
581                 }
582         } else {
583                 volatile uint32_t *config = portConfigRegister(pin);
584                 if (val) {
585                         // TODO use bitband for atomic read-mod-write
586                         *config |= (PORT_PCR_PE | PORT_PCR_PS);
587                         //*config = PORT_PCR_MUX(1) | PORT_PCR_PE | PORT_PCR_PS;
588                 } else {
589                         // TODO use bitband for atomic read-mod-write
590                         *config &= ~(PORT_PCR_PE);
591                         //*config = PORT_PCR_MUX(1);
592                 }
593         }
594
595 }
596
597 uint8_t digitalRead(uint8_t pin)
598 {
599         if (pin >= CORE_NUM_DIGITAL) return 0;
600         return *portInputRegister(pin);
601 }
602
603
604
605 void pinMode(uint8_t pin, uint8_t mode)
606 {
607         volatile uint32_t *config;
608
609         if (pin >= CORE_NUM_DIGITAL) return;
610         config = portConfigRegister(pin);
611
612         if (mode == OUTPUT) {
613                 *portModeRegister(pin) = 1;
614                 *config = /*PORT_PCR_SRE |*/ PORT_PCR_DSE | PORT_PCR_MUX(1);
615         } else {
616                 *portModeRegister(pin) = 0;
617                 if (mode == INPUT) {
618                         *config = PORT_PCR_MUX(1);
619                 } else {
620                         *config = PORT_PCR_MUX(1) | PORT_PCR_PE | PORT_PCR_PS; // pullup
621                 }
622         }
623 }
624
625
626 void _shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t value)
627 {
628         if (bitOrder == LSBFIRST) {
629                 shiftOut_lsbFirst(dataPin, clockPin, value);
630         } else {
631                 shiftOut_msbFirst(dataPin, clockPin, value);
632         }
633 }
634
635 void shiftOut_lsbFirst(uint8_t dataPin, uint8_t clockPin, uint8_t value)
636 {
637         uint8_t mask;
638         for (mask=0x01; mask; mask <<= 1) {
639                 digitalWrite(dataPin, value & mask);
640                 digitalWrite(clockPin, HIGH);
641                 digitalWrite(clockPin, LOW);
642         }
643 }
644
645 void shiftOut_msbFirst(uint8_t dataPin, uint8_t clockPin, uint8_t value)
646 {
647         uint8_t mask;
648         for (mask=0x80; mask; mask >>= 1) {
649                 digitalWrite(dataPin, value & mask);
650                 digitalWrite(clockPin, HIGH);
651                 digitalWrite(clockPin, LOW);
652         }
653 }
654
655 uint8_t _shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder)
656 {
657         if (bitOrder == LSBFIRST) {
658                 return shiftIn_lsbFirst(dataPin, clockPin);
659         } else {
660                 return shiftIn_msbFirst(dataPin, clockPin);
661         }
662 }
663
664 uint8_t shiftIn_lsbFirst(uint8_t dataPin, uint8_t clockPin)
665 {
666         uint8_t mask, value=0;
667         for (mask=0x01; mask; mask <<= 1) {
668                 digitalWrite(clockPin, HIGH);
669                 if (digitalRead(dataPin)) value |= mask;
670                 digitalWrite(clockPin, LOW);
671         }
672         return value;
673 }
674
675 uint8_t shiftIn_msbFirst(uint8_t dataPin, uint8_t clockPin)
676 {
677         uint8_t mask, value=0;
678         for (mask=0x80; mask; mask >>= 1) {
679                 digitalWrite(clockPin, HIGH);
680                 if (digitalRead(dataPin)) value |= mask;
681                 digitalWrite(clockPin, LOW);
682         }
683         return value;
684 }
685
686
687
688 // the systick interrupt is supposed to increment this at 1 kHz rate
689 volatile uint32_t systick_millis_count = 0;
690
691 //uint32_t systick_current, systick_count, systick_istatus;  // testing only
692
693 static uint32_t micros_mask(void)
694 {
695         uint32_t count, current, istatus;
696
697         __disable_irq();
698         current = SYST_CVR;
699         count = systick_millis_count;
700         istatus = SCB_ICSR;     // bit 26 indicates if systick exception pending
701         __enable_irq();
702          //systick_current = current;
703          //systick_count = count;
704          //systick_istatus = istatus & SCB_ICSR_PENDSTSET ? 1 : 0;
705         if ((istatus & SCB_ICSR_PENDSTSET) && current > 50) count++;
706         current = ((F_CPU / 1000) - 1) - current;
707         return count * 1000 + current / (F_CPU / 1000000);
708 }
709
710 uint32_t micros(void)
711 {
712         uint32_t count, current, istatus;
713
714         if (nvic_execution_priority() <= (SCB_SHPR3 >> 24))
715                 return micros_mask();
716
717         do {
718                 current = SYST_CVR;
719                 count = systick_millis_count;
720                 istatus = SCB_ICSR;     // bit 26 indicates if systick exception pending
721         }
722         while (istatus & SCB_ICSR_PENDSTSET);
723
724         current = ((F_CPU / 1000) - 1) - current;
725         return count * 1000 + current / (F_CPU / 1000000);
726 }
727
728 void delay(uint32_t ms)
729 {
730         uint32_t start = micros();
731
732         if (ms > 0) {
733                 while (1) {
734                         if ((micros() - start) >= 1000) {
735                                 ms--;
736                                 if (ms == 0) return;
737                                 start += 1000;
738                         }
739                         yield();
740                 }
741         }
742 }
743
744 // TODO: verify these result in correct timeouts...
745 #if F_CPU == 168000000
746 #define PULSEIN_LOOPS_PER_USEC 25
747 #elif F_CPU == 144000000
748 #define PULSEIN_LOOPS_PER_USEC 21
749 #elif F_CPU == 120000000
750 #define PULSEIN_LOOPS_PER_USEC 18
751 #elif F_CPU == 96000000
752 #define PULSEIN_LOOPS_PER_USEC 14
753 #elif F_CPU == 72000000
754 #define PULSEIN_LOOPS_PER_USEC 10
755 #elif F_CPU == 48000000
756 #define PULSEIN_LOOPS_PER_USEC 7
757 #elif F_CPU == 24000000
758 #define PULSEIN_LOOPS_PER_USEC 4
759 #elif F_CPU == 16000000
760 #define PULSEIN_LOOPS_PER_USEC 1
761 #elif F_CPU == 8000000
762 #define PULSEIN_LOOPS_PER_USEC 1
763 #elif F_CPU == 4000000
764 #define PULSEIN_LOOPS_PER_USEC 1
765 #elif F_CPU == 2000000
766 #define PULSEIN_LOOPS_PER_USEC 1
767 #endif
768
769
770 uint32_t pulseIn_high(volatile uint8_t *reg, uint32_t timeout)
771 {
772         uint32_t timeout_count = timeout * PULSEIN_LOOPS_PER_USEC;
773         uint32_t usec_start, usec_stop;
774         
775         // wait for any previous pulse to end
776         while (*reg) {
777                 if (--timeout_count == 0) return 0;
778         }
779         // wait for the pulse to start
780         while (!*reg) {
781                 if (--timeout_count == 0) return 0;
782         }
783         usec_start = micros();
784         // wait for the pulse to stop
785         while (*reg) {
786                 if (--timeout_count == 0) return 0;
787         }
788         usec_stop = micros();
789         return usec_stop - usec_start;
790 }
791
792 uint32_t pulseIn_low(volatile uint8_t *reg, uint32_t timeout)
793 {
794         uint32_t timeout_count = timeout * PULSEIN_LOOPS_PER_USEC;
795         uint32_t usec_start, usec_stop;
796         
797         // wait for any previous pulse to end
798         while (!*reg) {
799                 if (--timeout_count == 0) return 0;
800         }
801         // wait for the pulse to start
802         while (*reg) {
803                 if (--timeout_count == 0) return 0;
804         }
805         usec_start = micros();
806         // wait for the pulse to stop
807         while (!*reg) {
808                 if (--timeout_count == 0) return 0;
809         }
810         usec_stop = micros();
811         return usec_stop - usec_start;
812 }
813
814 // TODO: an inline version should handle the common case where state is const
815 uint32_t pulseIn(uint8_t pin, uint8_t state, uint32_t timeout)
816 {
817         if (pin >= CORE_NUM_DIGITAL) return 0;
818         if (state) return pulseIn_high(portInputRegister(pin), timeout);
819         return pulseIn_low(portInputRegister(pin), timeout);;
820 }
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848