Advertisement
phillip_bourdon234

EEPROM_Driver.c

Feb 28th, 2021
994
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.89 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "stm32f10x.h"
  4. #include "system_stm32f10x.h"
  5. #include "EEPROM_Driver.h"
  6. #include "I2C_Driver.h"
  7. #include "delay.h"
  8.  
  9.  
  10. //The reason I have to do extra stuff with the I2C library is because of the fact that
  11. //the I2C on the STM32 requires different code for different loads of data; For example,
  12. //sending one byte over the I2C line requires different code for sending 2 bytes of data,
  13. //and the same goes for 3 bytes of data. I wonder why there is not a repeat start
  14. //condition after one byte of data has been sent. If there was, then I could just keep calling
  15. //repeat start conditions until I was satisfied with the data that has been sent, and then
  16. //I could just send a nack or a stop condition.
  17. uint8_t eeprom_read(uint8_t device_address, uint8_t addr_hi, uint8_t addr_lo)
  18. {
  19.     i2c_write(device_address, addr_hi, addr_lo);
  20.    
  21.     uint8_t data;
  22.     uint16_t temp;
  23.    
  24.     I2C2->CR1 |= I2C_CR1_START; //generate start condition
  25.     while(!(I2C2->SR1 & I2C_SR1_SB)) //wait for the i2c to send the start condition
  26.     {
  27.     }
  28.     temp = I2C2->SR1;
  29.     I2C2->DR = device_address | 0x01; //send the adress plus a read opperation (0x01)
  30.  
  31.     while(!(I2C2->SR1 & I2C_SR1_ADDR)) //wait for the i2c to get a match for the address
  32.     {
  33.     }
  34.     I2C2->CR1 &= ~(I2C_CR1_ACK); //This sends a NACK to the slave, which tells it that this is the last read
  35.     temp = I2C2->SR1;
  36.     temp = I2C2->SR2;
  37.     I2C2->CR1 |= I2C_CR1_STOP; //generates a stop condition
  38.    
  39.     while(!(I2C2->SR1 & I2C_SR1_RXNE)) //wait for the i2c to get the data from the EEPROM
  40.     {
  41.     }
  42.  
  43.     data = (uint8_t)I2C2->DR;
  44.    
  45.     return data;
  46.  
  47. }
  48.  
  49. void eeprom_write(uint8_t device_address, uint8_t addr_hi, uint8_t addr_lo, uint8_t data)
  50. {
  51.     i2c_write_2(device_address, addr_hi, addr_lo, data);
  52.     delayMs(6); //data sheet says that eeprom write operation takes 5 ms. I put 6 just to be safe
  53. }
  54.  
  55. void eeprom_init()
  56. {
  57.     i2c_init();
  58. }
  59.    
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement