diff --git a/Arduino/LIN_to_IR/LIN_to_IR.cpp b/Arduino/LIN_to_IR/LIN_to_IR.cpp index e3f05eb..0bd050c 100644 --- a/Arduino/LIN_to_IR/LIN_to_IR.cpp +++ b/Arduino/LIN_to_IR/LIN_to_IR.cpp @@ -10,15 +10,42 @@ #define FAULT_PIN PIN_PB1 // Digital pin 1 #define CS_PIN PIN_PB3 // Digital pin 11 -#define RTI_RX_PIN PIN_PA4 // Digital pin 6 (Unused/LED COM) #define RTI_TX_PIN PIN_PA5 // Digital pin 5 -#define MUX_LOGIC_SEL_PIN PIN_PA6 // Digital pin 4 #define SYN_FIELD 0x55 #define SWM_ID 0x20 SoftwareSerial LINBusSerial(RX_PIN, TX_PIN); -SoftwareSerial rtiSerial(RTI_RX_PIN, RTI_TX_PIN); + +#if defined(TIM1_COMPA_vect) && !defined(TIMER1_COMPA_vect) + #define TIMER1_COMPA_vect TIM1_COMPA_vect +#endif + +volatile uint16_t rti_tx_buffer = 0xFFFF; +volatile uint8_t rti_tx_bit_count = 0; + +ISR(TIMER1_COMPA_vect) { + if (rti_tx_bit_count > 0) { + uint8_t bit = rti_tx_buffer & 1; + if (bit) { + digitalWrite(RTI_TX_PIN, HIGH); + } else { + digitalWrite(RTI_TX_PIN, LOW); + } + rti_tx_buffer >>= 1; + rti_tx_bit_count--; + } +} + +void rti_write_byte(uint8_t data) { + while (rti_tx_bit_count > 0) { + // Wait for the previous byte to finish transmitting + } + noInterrupts(); + rti_tx_buffer = 0x200 | (data << 1); + rti_tx_bit_count = 10; + interrupts(); +} // RC-6 timing constants // 1 time unit (1t) = 444us @@ -237,9 +264,9 @@ void setup() { pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); // LED OFF - // Mux logic select pin - pinMode(MUX_LOGIC_SEL_PIN, OUTPUT); - digitalWrite(MUX_LOGIC_SEL_PIN, HIGH); + // Configure RTI TX pin + pinMode(RTI_TX_PIN, OUTPUT); + digitalWrite(RTI_TX_PIN, HIGH); // Serial idle is HIGH // Enable MCP2004 pinMode(CS_PIN, OUTPUT); @@ -249,7 +276,15 @@ void setup() { digitalWrite(FAULT_PIN, HIGH); LINBusSerial.begin(9600); - rtiSerial.begin(2400); + + // Initialize Timer 1 for 2400 Hz CTC interrupts + TCCR1A = 0; + TCCR1B = 0; + TCNT1 = 0; + OCR1A = 3332; // 8,000,000 / (1 * 2400) - 1 + TCCR1B |= (1 << WGM12); // CTC mode + TCCR1B |= (1 << CS10); // Prescaler 1 + TIMSK1 |= (1 << OCIE1A); // Enable interrupt frame = LinFrame(); last_frame_time = millis(); @@ -314,7 +349,7 @@ void loop() { else byte_to_send = 0x83; } - rtiSerial.write(byte_to_send); + rti_write_byte(byte_to_send); rti_byte_index = (rti_byte_index + 1) % 3; } }