Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool i2c_master_open(void) {
- return i2c1_driver_open();
- }
- bool i2c_master_write(uint8_t* data, uint8_t length, uint8_t address) {
- uint8_t n;
- I2C_INTERRUPT_FLAG = 0;
- I2C_COLLISION_FLAG = 0;
- // Start condition
- i2c1_driver_start();
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- // If no collision occurred
- if(I2C_INTERRUPT_FLAG) {
- // Send write address
- I2C_INTERRUPT_FLAG = 0;
- i2c1_driver_TXData(address & 0b11111110);
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- // No collision occurred?
- if(I2C_INTERRUPT_FLAG) {
- I2C_INTERRUPT_FLAG = 0;
- // Check the ACK status from the slave. If ACK was received, continue
- if(!i2c1_driver_isNACK()) {
- // Send all the bytes
- for(n = 0; n < length; ++n) {
- i2c1_driver_TXData(data[n]);
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- I2C_INTERRUPT_FLAG = 0;
- // Collision? Return
- if(I2C_COLLISION_FLAG) {
- i2c1_driver_stop();
- return false;
- }
- // NACK received from the slave device? Break!
- if(i2c1_driver_isNACK()) {
- break;
- }
- }
- // Generate the stop condition
- i2c1_driver_stop();
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- if(I2C_INTERRUPT_FLAG) {
- return true;
- }
- }
- }
- }
- return false;
- }
- bool i2c_master_read(uint8_t* data, uint8_t length, uint8_t address) {
- uint8_t n;
- I2C_INTERRUPT_FLAG = 0;
- I2C_COLLISION_FLAG = 0;
- // Start condition
- i2c1_driver_start();
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- // If no collision occurred
- if(I2C_INTERRUPT_FLAG) {
- // Send read address
- I2C_INTERRUPT_FLAG = 0;
- i2c1_driver_TXData(address | 0x01);
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- // No collision occurred?
- if(I2C_INTERRUPT_FLAG) {
- I2C_INTERRUPT_FLAG = 0;
- // Check the ACK status from the slave. If ACK was received, continue
- if(!i2c1_driver_isNACK()) {
- // Read all the bytes
- for(n = 0; n < length; ++n) {
- i2c1_driver_startRX();
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- I2C_INTERRUPT_FLAG = 0;
- data[n] = i2c1_driver_getRXData();
- // Collision? Return
- if(I2C_COLLISION_FLAG) {
- i2c1_driver_stop();
- return false;
- }
- // If this is the last byte we should read, send a NACK to the
- // slave device now
- if(n == length - 1) {
- i2c1_driver_sendNACK();
- }
- else {
- // Send ACK to keep receiving data
- i2c1_driver_sendACK();
- }
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- // Collision? Return
- if(I2C_COLLISION_FLAG) {
- i2c1_driver_stop();
- return false;
- }
- I2C_INTERRUPT_FLAG = 0;
- }
- // Generate the stop condition
- i2c1_driver_stop();
- while(!I2C_INTERRUPT_FLAG && !I2C_COLLISION_FLAG);
- if(I2C_INTERRUPT_FLAG) {
- return true;
- }
- }
- }
- }
- return false;
- }
Add Comment
Please, Sign In to add comment