+/*********************
+ * Signal generation *
+ *********************/
+
+#define EMIT_CLOCKS(nsec) ((uint16_t)((nsec) * 24 / 1000))
+#define EMIT_NSEC(clocks) ((uint16_t)((clocks) * 1000 / 24))
+
+static uint32_t *emit_pcr = 0; // transmit pin name
+
+static uint64_t emit_start = 0; // transmit start time (world time)
+static uint64_t emit_period = 0; // transmit period
+static uint64_t emit_due = 0; // next transmit (world time)
+
+static uint32_t emit_slack = 0; // how far ahead we need to schedule, in us
+static uint32_t emit_worst = 0; // worst-case latency in task table
+
+void emit_init(int alt, PinName pin, PinMode mode)
+{
+ // Find pin
+ emit_pcr = (uint32_t*)(PORTA_BASE + pin);
+
+ // Enable clocks
+ SIM->SCGC6 |= SIM_SCGC6_TPM1_MASK;
+ SIM->SOPT2 |= SIM_SOPT2_TPMSRC(1);
+
+ // Set pin mode
+ emit_pcr[0] = PORT_PCR_ISF_MASK
+ | PORT_PCR_MUX(alt)
+ | mode;
+
+ // Setup Timer/PWM Module
+ TPM1->SC = TPM_SC_TOF_MASK;
+ TPM1->CNT = TPM_CNT_COUNT(0);
+ TPM1->MOD = TPM_MOD_MOD(0xFFFF);
+
+ TPM1->CONTROLS[0].CnSC = TPM_CnSC_CHF_MASK // clear flag
+ | TPM_CnSC_MSB_MASK // set output highon match,
+ | TPM_CnSC_ELSB_MASK // cleared on overflow
+ | TPM_CnSC_ELSA_MASK; // ..
+
+ TPM1->STATUS = TPM_STATUS_CH0F_MASK
+ | TPM_STATUS_TOF_MASK;
+
+ TPM1->CONF = TPM_CONF_CSOO_MASK;
+}
+
+void emit_enable(uint64_t start, uint64_t period)
+{
+ const int slack_clocks = 0x8000; // tune based on emit_worst
+
+ emit_start = start;
+ emit_period = period;
+ emit_due = start + period;
+
+ // TODO - tune slack time
+ // TODO - check clock power
+ // TODO - TPM clock source
+ emit_slack = EMIT_NSEC(slack_clocks);
+
+ time_printf("emit scheduled", emit_due);
+}
+
+void emit_schedule(uint64_t when)
+{
+ uint64_t now = time_to_world(tdma_time());
+ uint64_t start = when - now; // transmit time
+ uint64_t stop = start + 100000; // 100 us pulse
+
+ // Disable timer
+ TPM1->SC = TPM_SC_TOF_MASK;
+
+ // Set transmit time
+ TPM1->CONTROLS[0].CnV = EMIT_CLOCKS(start);
+ TPM1->MOD = TPM_MOD_MOD(EMIT_CLOCKS(stop));
+
+ // Start the timer
+ TPM1->SC = TPM_SC_TOF_MASK
+ | TPM_SC_PS(1)
+ | TPM_SC_CMOD(1);
+
+ // Debug output
+ //sirq_printf("emitting event\r\n");
+}
+
+void emit_transmit(uint64_t local, uint64_t world)
+{
+ static uint64_t prev = 0;
+
+ // Record how how much time we have to reschedule
+ if (prev && (local-prev) > emit_worst)
+ emit_worst = (local-prev);
+ prev = local;
+
+ // Schedule task if needed
+ if (emit_due && emit_period &&
+ world+emit_slack > emit_due) {
+ emit_schedule(emit_due);
+ emit_due += emit_period;
+ }
+}
+