Kaynağa Gözat

ds3231: Protect read and write operations with mutex

Helmut Pozimski 1 yıl önce
ebeveyn
işleme
e9d6c3ba56
1 değiştirilmiş dosya ile 8 ekleme ve 0 silme
  1. 8 0
      main/ds3231.c

+ 8 - 0
main/ds3231.c

@@ -25,8 +25,12 @@
 #define CONTROL_REGISTER 0x0E
 #define STATUS_REGISTER 0x0F
 
+static SemaphoreHandle_t mutex = NULL;
 
 esp_err_t ds3231_init(int sda_pin, int scl_pin) {
+	 if (mutex == NULL) {
+	 	mutex = xSemaphoreCreateMutex();
+	 }
     int i2c_master_port = I2C_NUM_0;
     i2c_config_t conf;
     conf.mode = I2C_MODE_MASTER;
@@ -43,6 +47,7 @@ esp_err_t ds3231_init(int sda_pin, int scl_pin) {
 
 static esp_err_t read_value(uint8_t register_addr, uint8_t *value_read) {
     esp_err_t ret;
+    xSemaphoreTake(mutex, portMAX_DELAY);
     i2c_cmd_handle_t cmd = i2c_cmd_link_create();
     i2c_master_start(cmd);
     i2c_master_write_byte(cmd, DS3231_ADDRESS << 1 | I2C_MASTER_WRITE, 0x01);
@@ -63,12 +68,14 @@ static esp_err_t read_value(uint8_t register_addr, uint8_t *value_read) {
     i2c_master_cmd_begin(I2C_NUM_0, cmd, 1000 / portTICK_PERIOD_MS);
     i2c_cmd_link_delete(cmd);
 
+	 xSemaphoreGive(mutex);
     return ret;
 
 }
 
 static esp_err_t write_value(uint8_t register_addr, uint8_t write_value) {
     esp_err_t ret;
+    xSemaphoreTake(mutex, portMAX_DELAY);
     i2c_cmd_handle_t cmd = i2c_cmd_link_create();
     i2c_master_start(cmd);
     i2c_master_write_byte(cmd, DS3231_ADDRESS << 1 | I2C_MASTER_WRITE, 0x01);
@@ -78,6 +85,7 @@ static esp_err_t write_value(uint8_t register_addr, uint8_t write_value) {
     ret = i2c_master_cmd_begin(I2C_NUM_0, cmd, 1000 / portTICK_PERIOD_MS);
     i2c_cmd_link_delete(cmd);
 
+	 xSemaphoreGive(mutex);
     return ret;
 
 }