Guest User

Untitled

a guest
Jun 23rd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. void TWIinit()
  2. {
  3. //set SCL to 400kHz
  4. TWSR = 0x00;
  5. TWBR = 0x0C;
  6. TWCR = (1<<TWEN);
  7. }
  8.  
  9. uint8_t TWIstart()
  10. {
  11. TWCR= (1 << TWINT) | (1 << TWSTA) | (1 << TWEN) ;
  12. while ((TWCR & (1 << TWINT)) == 0);
  13. return (TWSR & 0xF8) != TW_START;
  14. }
  15.  
  16. void TWIstop()
  17. {
  18. TWCR= (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
  19. }
  20.  
  21. void TWIwrite(uint8_t data)
  22. {
  23. TWDR=data;
  24. TWCR = (1 << TWINT) | (1 << TWEN);
  25. while (!(TWCR & (1 << TWINT)));
  26. }
  27.  
  28. uint8_t TWIreadACK()
  29. {
  30. TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
  31. while (!(TWCR & (1 << TWINT)));
  32. return TWDR;
  33. }
  34.  
  35. uint8_t TWIreadNACK()
  36. {
  37. TWCR = (1 << TWINT) | (1 << TWEN);
  38. while (!(TWCR & (1 << TWINT)));
  39. return TWDR;
  40. }
  41.  
  42. uint8_t TWIGetStatus()
  43. {
  44. uint8_t status;
  45. status = TWSR & 0xF8;
  46. return status;
  47. }
  48.  
  49. void writeReg(uint8_t addr, uint8_t reg, uint8_t data)
  50. {
  51. TWIstart();
  52. TWIwrite(addr);
  53. TWIwrite(reg);
  54. TWIwrite(data);
  55. TWIstop();
  56. }
  57.  
  58. void readReg(uint8_t addr, uint8_t reg, uint8_t *data)
  59. {
  60. TWIstart();
  61. TWIwrite(addr);
  62. TWIwrite(reg);
  63. TWIstart();
  64. TWIwrite(addr | 1);
  65. *data = TWIreadNACK();
  66. TWIstop();
  67. }
  68.  
  69. void readRegstart(uint8_t addr, uint8_t reg)
  70. {
  71. TWIstart();
  72. TWIwrite(addr);
  73. TWIwrite(reg);
  74. TWIstart();
  75. TWIwrite(addr | 1);
  76. }
Add Comment
Please, Sign In to add comment