import part of teensy3 lib
[teensytas.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 attachInterrupt(uint8_t pin, void (*function)(void), int mode)
120 {
121         volatile uint32_t *config;
122         uint32_t cfg, mask;
123
124         if (pin >= CORE_NUM_DIGITAL) return;
125         switch (mode) {
126           case CHANGE:  mask = 0x0B; break;
127           case RISING:  mask = 0x09; break;
128           case FALLING: mask = 0x0A; break;
129           case LOW:     mask = 0x08; break;
130           case HIGH:    mask = 0x0C; break;
131           default: return;
132         }
133         mask = (mask << 16) | 0x01000000;
134         config = portConfigRegister(pin);
135
136         __disable_irq();
137         cfg = *config;
138         cfg &= ~0x000F0000;             // disable any previous interrupt
139         *config = cfg;
140         intFunc[pin] = function;        // set the function pointer
141         cfg |= mask;
142         *config = cfg;                  // enable the new interrupt
143         __enable_irq();
144 }
145
146 void detachInterrupt(uint8_t pin)
147 {
148         volatile uint32_t *config;
149
150         config = portConfigRegister(pin);
151         __disable_irq();
152         *config = ((*config & ~0x000F0000) | 0x01000000);
153         intFunc[pin] = NULL;
154         __enable_irq();
155 }
156
157
158 void porta_isr(void)
159 {
160         uint32_t isfr = PORTA_ISFR;
161         PORTA_ISFR = isfr;
162         if ((isfr & CORE_PIN3_BITMASK) && intFunc[3]) intFunc[3]();
163         if ((isfr & CORE_PIN4_BITMASK) && intFunc[4]) intFunc[4]();
164         if ((isfr & CORE_PIN24_BITMASK) && intFunc[24]) intFunc[24]();
165         if ((isfr & CORE_PIN33_BITMASK) && intFunc[33]) intFunc[33]();
166 }
167
168 void portb_isr(void)
169 {
170         uint32_t isfr = PORTB_ISFR;
171         PORTB_ISFR = isfr;
172         if ((isfr & CORE_PIN0_BITMASK) && intFunc[0]) intFunc[0]();
173         if ((isfr & CORE_PIN1_BITMASK) && intFunc[1]) intFunc[1]();
174         if ((isfr & CORE_PIN16_BITMASK) && intFunc[16]) intFunc[16]();
175         if ((isfr & CORE_PIN17_BITMASK) && intFunc[17]) intFunc[17]();
176         if ((isfr & CORE_PIN18_BITMASK) && intFunc[18]) intFunc[18]();
177         if ((isfr & CORE_PIN19_BITMASK) && intFunc[19]) intFunc[19]();
178         if ((isfr & CORE_PIN25_BITMASK) && intFunc[25]) intFunc[25]();
179         if ((isfr & CORE_PIN32_BITMASK) && intFunc[32]) intFunc[32]();
180 }
181
182 void portc_isr(void)
183 {
184         // TODO: these are inefficent.  Use CLZ somehow....
185         uint32_t isfr = PORTC_ISFR;
186         PORTC_ISFR = isfr;
187         if ((isfr & CORE_PIN9_BITMASK) && intFunc[9]) intFunc[9]();
188         if ((isfr & CORE_PIN10_BITMASK) && intFunc[10]) intFunc[10]();
189         if ((isfr & CORE_PIN11_BITMASK) && intFunc[11]) intFunc[11]();
190         if ((isfr & CORE_PIN12_BITMASK) && intFunc[12]) intFunc[12]();
191         if ((isfr & CORE_PIN13_BITMASK) && intFunc[13]) intFunc[13]();
192         if ((isfr & CORE_PIN15_BITMASK) && intFunc[15]) intFunc[15]();
193         if ((isfr & CORE_PIN22_BITMASK) && intFunc[22]) intFunc[22]();
194         if ((isfr & CORE_PIN23_BITMASK) && intFunc[23]) intFunc[23]();
195         if ((isfr & CORE_PIN27_BITMASK) && intFunc[27]) intFunc[27]();
196         if ((isfr & CORE_PIN28_BITMASK) && intFunc[28]) intFunc[28]();
197         if ((isfr & CORE_PIN29_BITMASK) && intFunc[29]) intFunc[29]();
198         if ((isfr & CORE_PIN30_BITMASK) && intFunc[30]) intFunc[30]();
199 }
200
201 void portd_isr(void)
202 {
203         uint32_t isfr = PORTD_ISFR;
204         PORTD_ISFR = isfr;
205         if ((isfr & CORE_PIN2_BITMASK) && intFunc[2]) intFunc[2]();
206         if ((isfr & CORE_PIN5_BITMASK) && intFunc[5]) intFunc[5]();
207         if ((isfr & CORE_PIN6_BITMASK) && intFunc[6]) intFunc[6]();
208         if ((isfr & CORE_PIN7_BITMASK) && intFunc[7]) intFunc[7]();
209         if ((isfr & CORE_PIN8_BITMASK) && intFunc[8]) intFunc[8]();
210         if ((isfr & CORE_PIN14_BITMASK) && intFunc[14]) intFunc[14]();
211         if ((isfr & CORE_PIN20_BITMASK) && intFunc[20]) intFunc[20]();
212         if ((isfr & CORE_PIN21_BITMASK) && intFunc[21]) intFunc[21]();
213 }
214
215 void porte_isr(void)
216 {
217         uint32_t isfr = PORTE_ISFR;
218         PORTE_ISFR = isfr;
219         if ((isfr & CORE_PIN26_BITMASK) && intFunc[26]) intFunc[26]();
220         if ((isfr & CORE_PIN31_BITMASK) && intFunc[31]) intFunc[31]();
221 }
222
223
224
225
226 unsigned long rtc_get(void)
227 {
228         return RTC_TSR;
229 }
230
231 void rtc_set(unsigned long t)
232 {
233         RTC_SR = 0;
234         RTC_TPR = 0;
235         RTC_TSR = t;
236         RTC_SR = RTC_SR_TCE;
237 }
238
239
240 // adjust is the amount of crystal error to compensate, 1 = 0.1192 ppm
241 // For example, adjust = -100 is slows the clock by 11.92 ppm
242 //
243 void rtc_compensate(int adjust)
244 {
245         uint32_t comp, interval, tcr;
246
247         // This simple approach tries to maximize the interval.
248         // Perhaps minimizing TCR would be better, so the
249         // compensation is distributed more evenly across
250         // many seconds, rather than saving it all up and then
251         // altering one second up to +/- 0.38%
252         if (adjust >= 0) {
253                 comp = adjust;
254                 interval = 256;
255                 while (1) {
256                         tcr = comp * interval;
257                         if (tcr < 128*256) break;
258                         if (--interval == 1) break;
259                 }
260                 tcr = tcr >> 8;
261         } else {
262                 comp = -adjust;
263                 interval = 256;
264                 while (1) {
265                         tcr = comp * interval;
266                         if (tcr < 129*256) break;
267                         if (--interval == 1) break;
268                 }
269                 tcr = tcr >> 8;
270                 tcr = 256 - tcr;
271         }
272         RTC_TCR = ((interval - 1) << 8) | tcr;
273 }
274
275 #if 0
276 // TODO: build system should define this
277 // so RTC is automatically initialized to approx correct time
278 // at least when the program begins running right after upload
279 #ifndef TIME_T
280 #define TIME_T 1350160272
281 #endif
282
283 void init_rtc(void)
284 {
285         serial_print("init_rtc\n");
286         //SIM_SCGC6 |= SIM_SCGC6_RTC;
287
288         // enable the RTC crystal oscillator, for approx 12pf crystal
289         if (!(RTC_CR & RTC_CR_OSCE)) {
290                 serial_print("start RTC oscillator\n");
291                 RTC_SR = 0;
292                 RTC_CR = RTC_CR_SC16P | RTC_CR_SC4P | RTC_CR_OSCE;
293         }
294         // should wait for crystal to stabilize.....
295
296         serial_print("SR=");
297         serial_phex32(RTC_SR);
298         serial_print("\n");
299         serial_print("CR=");
300         serial_phex32(RTC_CR);
301         serial_print("\n");
302         serial_print("TSR=");
303         serial_phex32(RTC_TSR);
304         serial_print("\n");
305         serial_print("TCR=");
306         serial_phex32(RTC_TCR);
307         serial_print("\n");
308
309         if (RTC_SR & RTC_SR_TIF) {
310                 // enable the RTC
311                 RTC_SR = 0;
312                 RTC_TPR = 0;
313                 RTC_TSR = TIME_T;
314                 RTC_SR = RTC_SR_TCE;
315         }
316 }
317 #endif
318
319 extern void usb_init(void);
320
321
322 // create a default PWM at the same 488.28 Hz as Arduino Uno
323 #if F_BUS == 48000000
324 #define DEFAULT_FTM_MOD (49152 - 1)
325 #define DEFAULT_FTM_PRESCALE 1
326 #else
327 #define DEFAULT_FTM_MOD (49152 - 1)
328 #define DEFAULT_FTM_PRESCALE 0
329 #endif
330
331 //void init_pins(void)
332 void _init_Teensyduino_internal_(void)
333 {
334         init_pin_interrupts();
335
336         //SIM_SCGC6 |= SIM_SCGC6_FTM0;  // TODO: use bitband for atomic read-mod-write
337         //SIM_SCGC6 |= SIM_SCGC6_FTM1;
338         FTM0_CNT = 0;
339         FTM0_MOD = DEFAULT_FTM_MOD;
340         FTM0_C0SC = 0x28; // MSnB:MSnA = 10, ELSnB:ELSnA = 10
341         FTM0_C1SC = 0x28;
342         FTM0_C2SC = 0x28;
343         FTM0_C3SC = 0x28;
344         FTM0_C4SC = 0x28;
345         FTM0_C5SC = 0x28;
346         FTM0_C6SC = 0x28;
347         FTM0_C7SC = 0x28;
348         FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
349         FTM1_CNT = 0;
350         FTM1_MOD = DEFAULT_FTM_MOD;
351         FTM1_C0SC = 0x28;
352         FTM1_C1SC = 0x28;
353         FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
354 #if defined(__MK20DX256__)
355         FTM2_CNT = 0;
356         FTM2_MOD = DEFAULT_FTM_MOD;
357         FTM2_C0SC = 0x28;
358         FTM2_C1SC = 0x28;
359         FTM2_SC = FTM_SC_CLKS(1) | FTM_SC_PS(DEFAULT_FTM_PRESCALE);
360 #endif
361
362         analog_init();
363         //delay(100); // TODO: this is not necessary, right?
364         delay(4);
365         usb_init();
366 }
367
368
369
370 static uint8_t analog_write_res = 8;
371
372 // SOPT4 is SIM select clocks?
373 // FTM is clocked by the bus clock, either 24 or 48 MHz
374 // input capture can be FTM1_CH0, CMP0 or CMP1 or USB start of frame
375 // 24 MHz with reload 49152 to match Arduino's speed = 488.28125 Hz
376
377 void analogWrite(uint8_t pin, int val)
378 {
379         uint32_t cval, max;
380
381 #if defined(__MK20DX256__)
382         if (pin == A14) {
383                 uint8_t res = analog_write_res;
384                 if (res < 12) {
385                         val <<= 12 - res;
386                 } else if (res > 12) {
387                         val >>= res - 12;
388                 }
389                 analogWriteDAC0(val);
390                 return;
391         }
392 #endif
393
394         max = 1 << analog_write_res;
395         if (val <= 0) {
396                 digitalWrite(pin, LOW);
397                 pinMode(pin, OUTPUT);   // TODO: implement OUTPUT_LOW
398                 return;
399         } else if (val >= max) {
400                 digitalWrite(pin, HIGH);
401                 pinMode(pin, OUTPUT);   // TODO: implement OUTPUT_HIGH
402                 return;
403         }
404
405         //serial_print("analogWrite\n");
406         //serial_print("val = ");
407         //serial_phex32(val);
408         //serial_print("\n");
409         //serial_print("analog_write_res = ");
410         //serial_phex(analog_write_res);
411         //serial_print("\n");
412         if (pin == 3 || pin == 4) {
413                 cval = ((uint32_t)val * (uint32_t)(FTM1_MOD + 1)) >> analog_write_res;
414 #if defined(__MK20DX256__)
415         } else if (pin == 25 || pin == 32) {
416                 cval = ((uint32_t)val * (uint32_t)(FTM2_MOD + 1)) >> analog_write_res;
417 #endif
418         } else {
419                 cval = ((uint32_t)val * (uint32_t)(FTM0_MOD + 1)) >> analog_write_res;
420         }
421         //serial_print("cval = ");
422         //serial_phex32(cval);
423         //serial_print("\n");
424         switch (pin) {
425           case 3: // PTA12, FTM1_CH0
426                 FTM1_C0V = cval;
427                 CORE_PIN3_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
428                 break;
429           case 4: // PTA13, FTM1_CH1
430                 FTM1_C1V = cval;
431                 CORE_PIN4_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
432                 break;
433           case 5: // PTD7, FTM0_CH7
434                 FTM0_C7V = cval;
435                 CORE_PIN5_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
436                 break;
437           case 6: // PTD4, FTM0_CH4
438                 FTM0_C4V = cval;
439                 CORE_PIN6_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
440                 break;
441           case 9: // PTC3, FTM0_CH2
442                 FTM0_C2V = cval;
443                 CORE_PIN9_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
444                 break;
445           case 10: // PTC4, FTM0_CH3
446                 FTM0_C3V = cval;
447                 CORE_PIN10_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
448                 break;
449           case 20: // PTD5, FTM0_CH5
450                 FTM0_C5V = cval;
451                 CORE_PIN20_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
452                 break;
453           case 21: // PTD6, FTM0_CH6
454                 FTM0_C6V = cval;
455                 CORE_PIN21_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
456                 break;
457           case 22: // PTC1, FTM0_CH0
458                 FTM0_C0V = cval;
459                 CORE_PIN22_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
460                 break;
461           case 23: // PTC2, FTM0_CH1
462                 FTM0_C1V = cval;
463                 CORE_PIN23_CONFIG = PORT_PCR_MUX(4) | PORT_PCR_DSE | PORT_PCR_SRE;
464                 break;
465 #if defined(__MK20DX256__)
466           case 32: // PTB18, FTM2_CH0
467                 FTM2_C0V = cval;
468                 CORE_PIN32_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
469                 break;
470           case 25: // PTB19, FTM1_CH1
471                 FTM2_C1V = cval;
472                 CORE_PIN25_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
473                 break;
474 #endif
475           default:
476                 digitalWrite(pin, (val > 127) ? HIGH : LOW);
477                 pinMode(pin, OUTPUT);
478         }
479 }
480
481 void analogWriteRes(uint32_t bits)
482 {
483         if (bits < 1) {
484                 bits = 1;
485         } else if (bits > 16) {
486                 bits = 16;
487         }
488         analog_write_res = bits;
489 }
490
491 void analogWriteFrequency(uint8_t pin, uint32_t frequency)
492 {
493         uint32_t minfreq, prescale, mod;
494
495         //serial_print("analogWriteFrequency: pin = ");
496         //serial_phex(pin);
497         //serial_print(", freq = ");
498         //serial_phex32(frequency);
499         //serial_print("\n");
500         for (prescale = 0; prescale < 7; prescale++) {
501                 minfreq = (F_BUS >> 16) >> prescale;
502                 if (frequency > minfreq) break;
503         }
504         //serial_print("F_BUS = ");
505         //serial_phex32(F_BUS >> prescale);
506         //serial_print("\n");
507         //serial_print("prescale = ");
508         //serial_phex(prescale);
509         //serial_print("\n");
510         //mod = ((F_BUS >> prescale) / frequency) - 1;
511         mod = (((F_BUS >> prescale) + (frequency >> 1)) / frequency) - 1;
512         if (mod > 65535) mod = 65535;
513         //serial_print("mod = ");
514         //serial_phex32(mod);
515         //serial_print("\n");
516         if (pin == 3 || pin == 4) {
517                 FTM1_SC = 0;
518                 FTM1_CNT = 0;
519                 FTM1_MOD = mod;
520                 FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(prescale);
521         } else if (pin == 5 || pin == 6 || pin == 9 || pin == 10 ||
522           (pin >= 20 && pin <= 23)) {
523                 FTM0_SC = 0;
524                 FTM0_CNT = 0;
525                 FTM0_MOD = mod;
526                 FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_PS(prescale);
527         }
528 }
529
530
531
532
533 // TODO: startup code needs to initialize all pins to GPIO mode, input by default
534
535 void digitalWrite(uint8_t pin, uint8_t val)
536 {
537         if (pin >= CORE_NUM_DIGITAL) return;
538         if (*portModeRegister(pin)) {
539                 if (val) {
540                         *portSetRegister(pin) = 1;
541                 } else {
542                         *portClearRegister(pin) = 1;
543                 }
544         } else {
545                 volatile uint32_t *config = portConfigRegister(pin);
546                 if (val) {
547                         // TODO use bitband for atomic read-mod-write
548                         *config |= (PORT_PCR_PE | PORT_PCR_PS);
549                         //*config = PORT_PCR_MUX(1) | PORT_PCR_PE | PORT_PCR_PS;
550                 } else {
551                         // TODO use bitband for atomic read-mod-write
552                         *config &= ~(PORT_PCR_PE);
553                         //*config = PORT_PCR_MUX(1);
554                 }
555         }
556
557 }
558
559 uint8_t digitalRead(uint8_t pin)
560 {
561         if (pin >= CORE_NUM_DIGITAL) return 0;
562         return *portInputRegister(pin);
563 }
564
565
566
567 void pinMode(uint8_t pin, uint8_t mode)
568 {
569         volatile uint32_t *config;
570
571         if (pin >= CORE_NUM_DIGITAL) return;
572         config = portConfigRegister(pin);
573
574         if (mode == OUTPUT) {
575                 *portModeRegister(pin) = 1;
576                 *config = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
577         } else {
578                 *portModeRegister(pin) = 0;
579                 if (mode == INPUT) {
580                         *config = PORT_PCR_MUX(1);
581                 } else {
582                         *config = PORT_PCR_MUX(1) | PORT_PCR_PE | PORT_PCR_PS; // pullup
583                 }
584         }
585 }
586
587
588 void _shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t value)
589 {
590         if (bitOrder == LSBFIRST) {
591                 shiftOut_lsbFirst(dataPin, clockPin, value);
592         } else {
593                 shiftOut_msbFirst(dataPin, clockPin, value);
594         }
595 }
596
597 void shiftOut_lsbFirst(uint8_t dataPin, uint8_t clockPin, uint8_t value)
598 {
599         uint8_t mask;
600         for (mask=0x01; mask; mask <<= 1) {
601                 digitalWrite(dataPin, value & mask);
602                 digitalWrite(clockPin, HIGH);
603                 digitalWrite(clockPin, LOW);
604         }
605 }
606
607 void shiftOut_msbFirst(uint8_t dataPin, uint8_t clockPin, uint8_t value)
608 {
609         uint8_t mask;
610         for (mask=0x80; mask; mask >>= 1) {
611                 digitalWrite(dataPin, value & mask);
612                 digitalWrite(clockPin, HIGH);
613                 digitalWrite(clockPin, LOW);
614         }
615 }
616
617 uint8_t _shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder)
618 {
619         if (bitOrder == LSBFIRST) {
620                 return shiftIn_lsbFirst(dataPin, clockPin);
621         } else {
622                 return shiftIn_msbFirst(dataPin, clockPin);
623         }
624 }
625
626 uint8_t shiftIn_lsbFirst(uint8_t dataPin, uint8_t clockPin)
627 {
628         uint8_t mask, value=0;
629         for (mask=0x01; mask; mask <<= 1) {
630                 digitalWrite(clockPin, HIGH);
631                 if (digitalRead(dataPin)) value |= mask;
632                 digitalWrite(clockPin, LOW);
633         }
634         return value;
635 }
636
637 uint8_t shiftIn_msbFirst(uint8_t dataPin, uint8_t clockPin)
638 {
639         uint8_t mask, value=0;
640         for (mask=0x80; mask; mask >>= 1) {
641                 digitalWrite(clockPin, HIGH);
642                 if (digitalRead(dataPin)) value |= mask;
643                 digitalWrite(clockPin, LOW);
644         }
645         return value;
646 }
647
648
649
650 // the systick interrupt is supposed to increment this at 1 kHz rate
651 volatile uint32_t systick_millis_count = 0;
652
653 //uint32_t systick_current, systick_count, systick_istatus;  // testing only
654
655 uint32_t micros(void)
656 {
657         uint32_t count, current, istatus;
658
659         __disable_irq();
660         current = SYST_CVR;
661         count = systick_millis_count;
662         istatus = SCB_ICSR;     // bit 26 indicates if systick exception pending
663         __enable_irq();
664          //systick_current = current;
665          //systick_count = count;
666          //systick_istatus = istatus & SCB_ICSR_PENDSTSET ? 1 : 0;
667         if ((istatus & SCB_ICSR_PENDSTSET) && current > 50) count++;
668         current = ((F_CPU / 1000) - 1) - current;
669         return count * 1000 + current / (F_CPU / 1000000);
670 }
671
672 void delay(uint32_t ms)
673 {
674         uint32_t start = micros();
675
676         if (ms > 0) {
677                 while (1) {
678                         if ((micros() - start) >= 1000) {
679                                 ms--;
680                                 if (ms == 0) return;
681                                 start += 1000;
682                         }
683                         yield();
684                 }
685         }
686 }
687
688 #if F_CPU == 96000000
689 #define PULSEIN_LOOPS_PER_USEC 14
690 #elif F_CPU == 48000000
691 #define PULSEIN_LOOPS_PER_USEC 7
692 #elif F_CPU == 24000000
693 #define PULSEIN_LOOPS_PER_USEC 4
694 #endif
695
696
697 uint32_t pulseIn_high(volatile uint8_t *reg, uint32_t timeout)
698 {
699         uint32_t timeout_count = timeout * PULSEIN_LOOPS_PER_USEC;
700         uint32_t usec_start, usec_stop;
701         
702         // wait for any previous pulse to end
703         while (*reg) {
704                 if (--timeout_count == 0) return 0;
705         }
706         // wait for the pulse to start
707         while (!*reg) {
708                 if (--timeout_count == 0) return 0;
709         }
710         usec_start = micros();
711         // wait for the pulse to stop
712         while (*reg) {
713                 if (--timeout_count == 0) return 0;
714         }
715         usec_stop = micros();
716         return usec_stop - usec_start;
717 }
718
719 uint32_t pulseIn_low(volatile uint8_t *reg, uint32_t timeout)
720 {
721         uint32_t timeout_count = timeout * PULSEIN_LOOPS_PER_USEC;
722         uint32_t usec_start, usec_stop;
723         
724         // wait for any previous pulse to end
725         while (!*reg) {
726                 if (--timeout_count == 0) return 0;
727         }
728         // wait for the pulse to start
729         while (*reg) {
730                 if (--timeout_count == 0) return 0;
731         }
732         usec_start = micros();
733         // wait for the pulse to stop
734         while (!*reg) {
735                 if (--timeout_count == 0) return 0;
736         }
737         usec_stop = micros();
738         return usec_stop - usec_start;
739 }
740
741 // TODO: an inline version should handle the common case where state is const
742 uint32_t pulseIn(uint8_t pin, uint8_t state, uint32_t timeout)
743 {
744         if (pin >= CORE_NUM_DIGITAL) return 0;
745         if (state) return pulseIn_high(portInputRegister(pin), timeout);
746         return pulseIn_low(portInputRegister(pin), timeout);;
747 }
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775