daily pastebin goal
27%
SHARE
TWEET

Untitled

a guest Dec 9th, 2018 42 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. void initChip(){
  2. CLKDIVbits.RCDIV = 0;
  3. AD1PCFG = 0x9FFE;
  4. I2C2CON = 0;
  5. TRISBbits.TRISB3 = 0;
  6. TRISBbits.TRISB2 = 0;
  7. I2C2BRG = 157;
  8. I2C2CONbits.I2CEN = 1;
  9. _MI2C2IF = 0;
  10. }
  11.  
  12. void chipWrite(char reg, char data){
  13. //Start bit
  14. I2C2CONbits.SEN = 1;
  15. while(I2C2CONbits.SEN);
  16. IFS3bits.MI2C2IF = 0;
  17.  
  18. //Slave address bit
  19. I2C2TRN = 0b01010000;
  20. while(!IFS3bits.MI2C2IF);
  21. IFS3bits.MI2C2IF = 0;
  22.  
  23. //Register address
  24. I2C2TRN = reg;
  25. while(!IFS3bits.MI2C2IF);
  26. IFS3bits.MI2C2IF = 0;
  27.  
  28. //Data
  29. I2C2TRN = data;
  30. while(!IFS3bits.MI2C2IF);
  31. IFS3bits.MI2C2IF = 0;
  32.  
  33. //Stop bit
  34. I2C2CONbits.PEN = 1;
  35. IFS3bits.MI2C2IF = 0;
  36. while(I2C2CONbits.PEN);
  37. }
  38.  
  39. unsigned char chipRead(char reg){  
  40. unsigned char msb = 0;
  41.  
  42. /*configure i2c to send ACK*/  
  43. I2C2CONbits.ACKDT = 0;  
  44.  
  45.   /*start*/  
  46. I2C2CONbits.SEN = 1;  
  47. while(I2C2CONbits.SEN);
  48.  
  49. /*sensor address*/  
  50. I2C2TRN = 0b01010000;  
  51. while(I2C2STATbits.TBF);  
  52. while(I2C2STATbits.TRSTAT);
  53. while(I2C2STATbits.ACKSTAT);
  54.  
  55.  /*sensor command*/  
  56. I2C2TRN = 0b11111101;  
  57. while(I2C2STATbits.TBF);  
  58. while(I2C2STATbits.TRSTAT);
  59. while(I2C2STATbits.ACKSTAT);
  60.  
  61.  /*repeated start*/  
  62. I2C2CONbits.RSEN = 1;  
  63. while(I2C2CONbits.RSEN);
  64.  
  65. /*address for reading*/  
  66. I2C2TRN = reg;  
  67. while(I2C2STATbits.TBF);
  68. while(I2C2STATbits.TRSTAT);
  69. while(I2C2STATbits.ACKSTAT);
  70.  
  71.  /*receiver enabled*/  
  72. I2C2CONbits.RCEN = 1;
  73.  
  74. /*read first byte data*/  
  75. while(!I2C2STATbits.RBF);  
  76. msb = I2C2RCV;  
  77.  
  78. /*configure i2c to send nack*/    
  79. I2C2CONbits.ACKDT = 1;  
  80. /*send nack*/  
  81. I2C2CONbits.ACKEN = 1;
  82. while(I2C1CONbits.ACKEN);
  83.  
  84. /*send stop*/  
  85. I2C2CONbits.PEN = 1;  
  86. while(I2C2CONbits.PEN);
  87. I2C2CONbits.I2CEN = 0;
  88.  
  89. return msb;
  90. }
  91.  
  92. int main(void) {
  93. initChip();
  94. char key = 0b00000000;
  95. chipWrite(0x72,0x00);
  96. chipWrite(0x74, 0xFF);
  97.  
  98. while(1){
  99.     key = chipRead(0xFD);
  100.     asm("nop");
  101.     if(key == 0b01010000){
  102.         asm("nop");
  103.     }
  104. }
  105.  
  106. return 0;
  107. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top