i2c_slave.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* Library made by: g4lvanix
  2. * Github repository: https://github.com/g4lvanix/I2C-slave-lib
  3. */
  4. #include <avr/io.h>
  5. #include <util/twi.h>
  6. #include <avr/interrupt.h>
  7. #include <stdbool.h>
  8. #include "i2c_slave.h"
  9. void i2c_init(uint8_t address){
  10. // load address into TWI address register
  11. TWAR = (address << 1);
  12. // set the TWCR to enable address matching and enable TWI, clear TWINT, enable TWI interrupt
  13. TWCR = (1 << TWIE) | (1 << TWEA) | (1 << TWINT) | (1 << TWEN);
  14. }
  15. void i2c_stop(void){
  16. // clear acknowledge and enable bits
  17. TWCR &= ~((1 << TWEA) | (1 << TWEN));
  18. }
  19. ISR(TWI_vect){
  20. uint8_t ack = 1;
  21. // temporary stores the received data
  22. //uint8_t data;
  23. switch(TW_STATUS){
  24. case TW_SR_SLA_ACK:
  25. // The device is now a slave receiver
  26. slave_has_register_set = false;
  27. break;
  28. case TW_SR_DATA_ACK:
  29. // This device is a slave receiver and has received data
  30. // First byte is the location then the bytes will be writen in buffer with auto-incriment
  31. if(!slave_has_register_set){
  32. buffer_address = TWDR;
  33. if (buffer_address >= RX_BUFFER_SIZE){ // address out of bounds dont ack
  34. ack = 0;
  35. buffer_address = 0;
  36. }
  37. slave_has_register_set = true; // address has been receaved now fill in buffer
  38. } else {
  39. rxbuffer[buffer_address] = TWDR;
  40. buffer_address++;
  41. }
  42. break;
  43. case TW_ST_SLA_ACK:
  44. case TW_ST_DATA_ACK:
  45. // This device is a slave transmitter and master has requested data
  46. TWDR = txbuffer[buffer_address];
  47. buffer_address++;
  48. break;
  49. case TW_BUS_ERROR:
  50. // We got an error, reset i2c
  51. TWCR = 0;
  52. default:
  53. break;
  54. }
  55. // Reset i2c state mahcine to be ready for next interrupt
  56. TWCR |= (1 << TWIE) | (1 << TWINT) | (ack << TWEA) | (1 << TWEN);
  57. }