Selaa lähdekoodia

twi safe init

Alex Voinea 2 vuotta sitten
vanhempi
commit
abbf2a3927
2 muutettua tiedostoa jossa 19 lisäystä ja 2 poistoa
  1. 1 1
      Firmware/swi2c.c
  2. 18 1
      Firmware/twi.cpp

+ 1 - 1
Firmware/swi2c.c

@@ -30,7 +30,7 @@ void swi2c_init(void)
 	SET_INPUT(SWI2C_SDA);
 	SET_INPUT(SWI2C_SDA);
 	WRITE(SWI2C_SDA, 1); //SDA must be input with pullups while we are not sure if the slave is outputing or not
 	WRITE(SWI2C_SDA, 1); //SDA must be input with pullups while we are not sure if the slave is outputing or not
 
 
-	WRITE(SWI2C_SCL, 1);
+	WRITE(SWI2C_SCL, 0);
 	SET_OUTPUT(SWI2C_SCL); //SCL can be an output at all times. The bus is not in a multi-master configuration.
 	SET_OUTPUT(SWI2C_SCL); //SCL can be an output at all times. The bus is not in a multi-master configuration.
 
 
 	for (uint8_t i = 0; i < 100; i++) //wait. Not sure what for, but wait anyway.
 	for (uint8_t i = 0; i < 100; i++) //wait. Not sure what for, but wait anyway.

+ 18 - 1
Firmware/twi.cpp

@@ -21,6 +21,7 @@
 
 
 
 
 #include <math.h>
 #include <math.h>
+#include <util/delay.h>
 #include "config.h"
 #include "config.h"
 #include "fastio.h"
 #include "fastio.h"
 #include "twi.h"
 #include "twi.h"
@@ -29,8 +30,24 @@
 
 
 void twi_init(void)
 void twi_init(void)
 {
 {
-  // activate internal pullups for twi.
+  // activate internal pullups for SDA
+  SET_INPUT(SDA_PIN);
   WRITE(SDA_PIN, 1);
   WRITE(SDA_PIN, 1);
+  
+  // start with the SDA pulled low
+  WRITE(SCL_PIN, 0);
+  SET_OUTPUT(SCL_PIN);
+  
+  // clock 10 cycles to make sure that the sensor is not stuck in a register read.
+  for (uint8_t i = 0; i < 10; i++) {
+    WRITE(SCL_PIN, 1);
+    _delay_us((1000000 / TWI_FREQ) / 2);
+    WRITE(SCL_PIN, 0);
+    _delay_us((1000000 / TWI_FREQ) / 2);
+  }
+
+  // activate internal pullups for SCL
+  SET_INPUT(SCL_PIN);
   WRITE(SCL_PIN, 1);
   WRITE(SCL_PIN, 1);
 
 
   // initialize twi prescaler and bit rate
   // initialize twi prescaler and bit rate