aboutsummaryrefslogtreecommitdiffstats
path: root/keyboards/comet46/i2c.c
blob: 4bee5c63982960b0793df01a975633d16e1ce19e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#include <util/twi.h>
#include <avr/io.h>
#include <stdlib.h>
#include <avr/interrupt.h>
#include <util/twi.h>
#include <stdbool.h>
#include "i2c.h"

#ifdef USE_I2C

// Limits the amount of we wait for any one i2c transaction.
// Since were running SCL line 100kHz (=> 10μs/bit), and each transactions is
// 9 bits, a single transaction will take around 90μs to complete.
//
// (F_CPU/SCL_CLOCK)  =>  # of μC cycles to transfer a bit
// poll loop takes at least 8 clock cycles to execute
#define I2C_LOOP_TIMEOUT (9+1)*(F_CPU/SCL_CLOCK)/8

#define BUFFER_POS_INC() (slave_buffer_pos = (slave_buffer_pos+1)%SLAVE_BUFFER_SIZE)

volatile uint8_t i2c_slave_buffer[SLAVE_BUFFER_SIZE];

static volatile uint8_t slave_buffer_pos;
static volatile bool slave_has_register_set = false;

// Wait for an i2c operation to finish
inline static
void i2c_delay(void) {
  uint16_t lim = 0;
  while(!(TWCR & (1<<TWINT)) && lim < I2C_LOOP_TIMEOUT)
    lim++;

  // easier way, but will wait slightly longer
  // _delay_us(100);
}

// Setup twi to run at 100kHz or 400kHz (see ./i2c.h SCL_CLOCK)
void i2c_master_init(void) {
  // no prescaler
  TWSR = 0;
  // Set TWI clock frequency to SCL_CLOCK. Need TWBR>10.
  // Check datasheets for more info.
  TWBR = ((F_CPU/SCL_CLOCK)-16)/2;
}

// Start a transaction with the given i2c slave address. The direction of the
// transfer is set with I2C_READ and I2C_WRITE.
// returns: 0 => success
//          1 => error
uint8_t i2c_master_start(uint8_t address) {
  TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTA);

  i2c_delay();

  // check that we started successfully
  if ( (TW_STATUS != TW_START) && (TW_STATUS != TW_REP_START))
    return 1;

  TWDR = address;
  TWCR = (1<<TWINT) | (1<<TWEN);

  i2c_delay();

  if ( (TW_STATUS != TW_MT_SLA_ACK) && (TW_STATUS != TW_MR_SLA_ACK) )
    return 1; // slave did not acknowledge
  else
    return 0; // success
}


// Finish the i2c transaction.
void i2c_master_stop(void) {
  TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);

  uint16_t lim = 0;
  while(!(TWCR & (1<<TWSTO)) && lim < I2C_LOOP_TIMEOUT)
    lim++;
}

// Write one byte to the i2c slave.
// returns 0 => slave ACK
//         1 => slave NACK
uint8_t i2c_master_write(uint8_t data) {
  TWDR = data;
  TWCR = (1<<TWINT) | (1<<TWEN);

  i2c_delay();

  // check if the slave acknowledged us
  return (TW_STATUS == TW_MT_DATA_ACK) ? 0 : 1;
}

// Read one byte from the i2c slave. If ack=1 the slave is acknowledged,
// if ack=0 the acknowledge bit is not set.
// returns: byte read from i2c device
uint8_t i2c_master_read(int ack) {
  TWCR = (1<<TWINT) | (1<<TWEN) | (ack<<TWEA);

  i2c_delay();
  return TWDR;
}

void i2c_reset_state(void) {
  TWCR = 0;
}

void i2c_slave_init(uint8_t address) {
  TWAR = address << 0; // slave i2c address
  // TWEN  - twi enable
  // TWEA  - enable address acknowledgement
  // TWINT - twi interrupt flag
  // TWIE  - enable the twi interrupt
  TWCR = (1<<TWIE) | (1<<TWEA) | (1<<TWINT) | (1<<TWEN);
}

ISR(TWI_vect);

ISR(TWI_vect) {
  uint8_t ack = 1;
  switch(TW_STATUS) {
    case TW_SR_SLA_ACK:
      // this device has been addressed as a slave receiver
      slave_has_register_set = false;
      break;

    case TW_SR_DATA_ACK:
      // this device has received data as a slave receiver
      // The first byte that we receive in this transaction sets the location
      // of the read/write location of the slaves memory that it exposes over
      // i2c.  After that, bytes will be written at slave_buffer_pos, incrementing
      // slave_buffer_pos after each write.
      if(!slave_has_register_set) {
        slave_buffer_pos = TWDR;
        // don't acknowledge the master if this memory loctaion is out of bounds
        if ( slave_buffer_pos >= SLAVE_BUFFER_SIZE ) {
          ack = 0;
          slave_buffer_pos = 0;
        }
        slave_has_register_set = true;
      } else {
        i2c_slave_buffer[slave_buffer_pos] = TWDR;
        BUFFER_POS_INC();
      }
      break;

    case TW_ST_SLA_ACK:
    case TW_ST_DATA_ACK:
      // master has addressed this device as a slave transmitter and is
      // requesting data.
      TWDR = i2c_slave_buffer[slave_buffer_pos];
      BUFFER_POS_INC();
      break;

    case TW_BUS_ERROR: // something went wrong, reset twi state
      TWCR = 0;
    default:
      break;
  }
  // Reset everything, so we are ready for the next TWI interrupt
  TWCR |= (1<<TWIE) | (1<<TWINT) | (ack<<TWEA) | (1<<TWEN);
}
#endif
page_erase(currentAddress); boot_spm_busy_wait(); } fillFlashWithVectors(); sei(); } static void writeFlashPage(void) { didWriteSomething = 1; cli(); boot_page_write(currentAddress - 2); boot_spm_busy_wait(); // Wait until the memory is written. sei(); } #define __boot_page_fill_clear() \ (__extension__({ \ __asm__ __volatile__ \ ( \ "sts %0, %1\n\t" \ "spm\n\t" \ : \ : "i" (_SFR_MEM_ADDR(__SPM_REG)), \ "r" ((uint8_t)(__BOOT_PAGE_FILL | (1 << CTPB))) \ ); \ })) static void writeWordToPageBuffer(uint16_t data) { // first two interrupt vectors get replaced with a jump to the bootloader vector table if (currentAddress == (RESET_VECTOR_OFFSET * 2) || currentAddress == (USBPLUS_VECTOR_OFFSET * 2)) { data = 0xC000 + (BOOTLOADER_ADDRESS/2) - 1; } if (currentAddress == BOOTLOADER_ADDRESS - TINYVECTOR_RESET_OFFSET) { data = vectorTemp[0] + ((FLASHEND + 1) - BOOTLOADER_ADDRESS)/2 + 2 + RESET_VECTOR_OFFSET; } if (currentAddress == BOOTLOADER_ADDRESS - TINYVECTOR_USBPLUS_OFFSET) { data = vectorTemp[1] + ((FLASHEND + 1) - BOOTLOADER_ADDRESS)/2 + 1 + USBPLUS_VECTOR_OFFSET; } // clear page buffer as a precaution before filling the buffer on the first page // TODO: maybe clear on the first byte of every page? if (currentAddress == 0x0000) __boot_page_fill_clear(); cli(); boot_page_fill(currentAddress, data); sei(); // only need to erase if there is data already in the page that doesn't match what we're programming // TODO: what about this: if (pgm_read_word(currentAddress) & data != data) { ??? should work right? //if (pgm_read_word(currentAddress) != data && pgm_read_word(currentAddress) != 0xFFFF) { //if ((pgm_read_word(currentAddress) & data) != data) { // fireEvent(EVENT_PAGE_NEEDS_ERASE); //} currentAddress += 2; } static void fillFlashWithVectors(void) { int16_t i; // fill all or remainder of page with 0xFFFF for (i = currentAddress % SPM_PAGESIZE; i < SPM_PAGESIZE; i += 2) { writeWordToPageBuffer(0xFFFF); } writeFlashPage(); } /* ------------------------------------------------------------------------ */ static uchar usbFunctionSetup(uchar data[8]) { usbRequest_t *rq = (void *)data; static uchar replyBuffer[4] = { (((uint)PROGMEM_SIZE) >> 8) & 0xff, ((uint)PROGMEM_SIZE) & 0xff, SPM_PAGESIZE, UBOOT_WRITE_SLEEP }; if (rq->bRequest == 0) { // get device info usbMsgPtr = replyBuffer; return 4; } else if (rq->bRequest == 1) { // write page writeLength = rq->wValue.word; currentAddress = rq->wIndex.word; return USB_NO_MSG; // hands off work to usbFunctionWrite } else if (rq->bRequest == 2) { // erase application fireEvent(EVENT_ERASE_APPLICATION); } else { // exit bootloader # if BOOTLOADER_CAN_EXIT fireEvent(EVENT_FINISH); # endif } return 0; } // read in a page over usb, and write it in to the flash write buffer static uchar usbFunctionWrite(uchar *data, uchar length) { writeLength -= length; do { // remember vectors or the tinyvector table if (currentAddress == RESET_VECTOR_OFFSET * 2) { vectorTemp[0] = *(short *)data; } if (currentAddress == USBPLUS_VECTOR_OFFSET * 2) { vectorTemp[1] = *(short *)data; } // make sure we don't write over the bootloader! if (currentAddress >= PROGMEM_SIZE) { __boot_page_fill_clear(); break; } writeWordToPageBuffer(*(uint16_t *) data); data += 2; // advance data pointer length -= 2; } while(length); // TODO: Isn't this always last? // if we have now reached another page boundary, we're done uchar isLast = (writeLength == 0); if (isLast) fireEvent(EVENT_WRITE_PAGE); // ask runloop to write our page return isLast; // let vusb know we're done with this request } /* ------------------------------------------------------------------------ */ void PushMagicWord (void) __attribute__ ((naked)) __attribute__ ((section (".init3"))); // put the word "B007" at the bottom of the stack (RAMEND - RAMEND-1) void PushMagicWord (void) { asm volatile("ldi r16, 0xB0"::); asm volatile("push r16"::); asm volatile("ldi r16, 0x07"::); asm volatile("push r16"::); } /* ------------------------------------------------------------------------ */ static inline void initForUsbConnectivity(void) { usbInit(); /* enforce USB re-enumerate: */ usbDeviceDisconnect(); /* do this while interrupts are disabled */ _delay_ms(500); usbDeviceConnect(); sei(); } static inline void tiny85FlashInit(void) { // check for erased first page (no bootloader interrupt vectors), add vectors if missing // this needs to happen for usb communication to work later - essential to first run after bootloader // being installed if(pgm_read_word(RESET_VECTOR_OFFSET * 2) != 0xC000 + (BOOTLOADER_ADDRESS/2) - 1 || pgm_read_word(USBPLUS_VECTOR_OFFSET * 2) != 0xC000 + (BOOTLOADER_ADDRESS/2) - 1) { fillFlashWithVectors(); } // TODO: necessary to reset currentAddress? currentAddress = 0; } static inline void tiny85FlashWrites(void) { _delay_us(2000); // TODO: why is this here? - it just adds pointless two level deep loops seems like? // write page to flash, interrupts will be disabled for > 4.5ms including erase if (currentAddress % SPM_PAGESIZE) { fillFlashWithVectors(); } else { writeFlashPage(); } } static inline void tiny85FinishWriting(void) { // make sure remainder of flash is erased and write checksum and application reset vectors if (didWriteSomething) { while (currentAddress < BOOTLOADER_ADDRESS) { fillFlashWithVectors(); } } } static inline __attribute__((noreturn)) void leaveBootloader(void) { //DBG1(0x01, 0, 0); bootLoaderExit(); cli(); USB_INTR_ENABLE = 0; USB_INTR_CFG = 0; /* also reset config bits */ // clear magic word from bottom of stack before jumping to the app *(uint8_t*)(RAMEND) = 0x00; *(uint8_t*)(RAMEND-1) = 0x00; // jump to application reset vector at end of flash asm volatile ("rjmp __vectors - 4"); } int __attribute__((noreturn)) main(void) { uint16_t idlePolls = 0; /* initialize */ wdt_disable(); /* main app may have enabled watchdog */ tiny85FlashInit(); bootLoaderInit(); if (bootLoaderCondition()){ initForUsbConnectivity(); do { usbPoll(); _delay_us(100); idlePolls++; if (events) idlePolls = 0; // these next two freeze the chip for ~ 4.5ms, breaking usb protocol // and usually both of these will activate in the same loop, so host // needs to wait > 9ms before next usb request if (isEvent(EVENT_ERASE_APPLICATION)) eraseApplication(); if (isEvent(EVENT_WRITE_PAGE)) tiny85FlashWrites(); if (isEvent(EVENT_FINISH)) { // || AUTO_EXIT_CONDITION()) { tiny85FinishWriting(); # if BOOTLOADER_CAN_EXIT _delay_ms(10); // removing delay causes USB errors break; # endif } // # if BOOTLOADER_CAN_EXIT // // exit if requested by the programming app, or if we timeout waiting for the pc with a valid app // if (isEvent(EVENT_EXIT_BOOTLOADER) || AUTO_EXIT_CONDITION()) { // //_delay_ms(10); // break; // } // # endif clearEvents(); } while(bootLoaderCondition()); /* main event loop */ } leaveBootloader(); } /* ------------------------------------------------------------------------ */