uchar twi_read(uchar W_ADDRESS) { uchar temp; START(); //TWI启动 WAIT(); if (SATUS()!=_START) return TRUE; TWI_WRITE(W_MPU6050_ADDR); //写 MPU6050地址和写方式 WAIT(); if (SATUS()!=MT_SLA_ACK) return TRUE; TWI_WRITE(W_ADDRESS); //写 MPU6050相应寄存器地址 WAIT(); if (SATUS()!=MT_DATA_ACK) return TRUE; START(); //TWI重新启动 WAIT(); if (SATUS()!=RE_START) return TRUE; TWI_WRITE(R_MPU6050_ADDR); //写 MPU6050地址和读方式 WAIT(); if(SATUS()!=MR_SLA_ACK) return TRUE; TWI_READ(); //启动主TWI读方式 WAIT(); if(SATUS()!=MR_DATA_NOACK)//读完一个数停止接收数据 ,主机接收到不再接收应答信号 ,如果继续接收到应答信号 return TRUE; //说明主机继续接收数据则为错误 temp=TWDR; //读取 TWI接收数据 STOP(); //TWI停止 return temp; }
bool _moduloTransfer( uint8_t address, uint8_t command, uint8_t *sendData, uint8_t sendLen, uint8_t *receiveData, uint8_t receiveLen, bool receiveString) { // Star the transmit CRC with the address in the upper 7 bits uint8_t crc = _crc8_ccitt_update(0, address); TWI_BEGIN_WRITE(address); // Send the command and length TWI_WRITE(command); TWI_WRITE(sendLen); crc = _crc8_ccitt_update(crc, command); crc = _crc8_ccitt_update(crc, sendLen); // Send the data for (int i=0; i < sendLen; i++) { TWI_WRITE(sendData[i]); crc = _crc8_ccitt_update(crc, sendData[i]); } // Send the CRC and end the transmission TWI_WRITE(crc); if (TWI_END_WRITE(receiveLen == 0) != 0) { return false; } if (receiveLen == 0) { return true; } while (TWI_AVAILABLE()) { TWI_READ(); } // Request receiveLen data bytes plus 1 CRC byte. if (TWI_REQUEST_FROM((int)address, (int)receiveLen+1) != receiveLen+1) { return false; } // Start the CRC with the I2C address byte (address in upper 7, 1 in lsb) crc = _crc8_ccitt_update(0, address); // Receive the data for (int i=0; i < receiveLen; i++) { receiveData[i] = TWI_READ(); // If we're receiving a string, then stop when we find a 0 byte. if (receiveString and i > 0 and receiveData[i-1] == 0) { return (receiveData[i] == crc); } crc = _crc8_ccitt_update(crc, receiveData[i]); } // Receive the CRC. uint8_t receivedCRC = TWI_READ(); // Check the CRC. return (crc == receivedCRC); }