//**************************************************************************** //Initiates a read transfer. Loads global variables. Sends START. ISR handles //the rest. //**************************************************************************** void twi_start_rd(uint8_t twi_addr, uint8_t *twi_data, uint8_t byte_cnt){ while(twi_busy()); //wait till TWI rdy for next xfer twi_bus_addr = (twi_addr | TW_READ); //set twi bus address, mark as read twi_buf = twi_data; //load pointer to write buffer twi_msg_size = byte_cnt; //load size of xfer TWCR = TWCR_START; //initiate START }
void write_LSM6DS3(uint8_t address, uint8_t value){ uint8_t wr_buf[2]; // Save address to address buffer wr_buf[0] = address; wr_buf[1] = value; // Write value to register address twi_start_wr(LSM6DS3_WRITE, wr_buf, 2); // Wait until data is sent while(twi_busy()); }
void read_LSM6DS3(uint8_t address, uint8_t *rd_buf){ uint8_t addr_buf[1]; // Save address to address buffer addr_buf[0] = address; // Write register address of where to read data from twi_start_wr(LSM6DS3_WRITE, addr_buf, 1); // Recieve data from register address and store in rd_buf twi_start_rd(LSM6DS3_READ, rd_buf, 1); // Wait until data is recieved while(twi_busy()); }
void twi_start_rx(uint8_t adr, uint8_t *data, uint8_t bytes_to_receive) { // Wait for previous transaction to finish while(twi_busy()) { ; } // Copy address; set R/~W bit in SLA+R/W address field //twi_adr = adr | TW_READ; twi_adr = ( adr << 1 ) | TW_READ; // Save pointer to data and number of bytes to receive twi_data = data; twi_data_counter = bytes_to_receive; // Initiate a START condition; Interrupt enabled and flag cleared TWCR = (1<<TWINT)|(0<<TWEA)|(1<<TWSTA)|(0<<TWSTO)|(0<<TWWC)|(1<<TWEN)|(1<<TWIE); }
void twi_stop(void) { // Wait for transaction to finish while(twi_busy()) { ; } // Make sure transaction was succesful if(twi_status != TWI_STATUS_DONE) { return; } // Initiate a STOP condition TWCR = (1<<TWINT)|(0<<TWEA)|(0<<TWSTA)|(1<<TWSTO)|(0<<TWWC)|(1<<TWEN)|(0<<TWIE); // Wait until STOP has finished LOOP_UNTIL_BIT_IS_LO(TWCR, TWSTO); }
void ecmd_twi_periodic(void) { if (!twi_busy()) //wait until TWI interrupt is disabled { TWIDEBUG("ecmd_twi_periodic\n"); cmd_rx_len=twi_rx_len(); if (cmd_rx_len<=2) //assume its raw parse_rawdata_twi_slave(); else { parse_ecmd_twi_slave(); } TWCR = (1<<TWEN)| // TWI Interface enabled (1<<TWIE)|(1<<TWINT)| // Enable TWI Interupt and clear the flag to send byte (1<<TWEA)|(0<<TWSTA)|(0<<TWSTO)| // Send ACK after next reception (0<<TWWC); } }