I'm having troubles connecting an ESP8266 NodeMCU (LoLin V3) to an I2C slave.
The characters recieved are nonsense.
I tried different setups with and without level-shifter, pullup on 5V or 3V3 side, different NodeMCU-Boards (NoName) - all with the same results. An Arduino Nano as master_reader works perfectly, so the slave_sender shouldn't be the problem.
Here's the Code:
#include <Wire.h>
void setup() {
Wire.begin(2, 0); // GPIO 2 & 0 correspond to D4 & D3 (On the Nano you just need: Wire.begin();)
Serial.begin(115200);
}
void loop() {
Wire.requestFrom(10, 14); //request 14 bytes from adress 10 (0x0A)
Serial.print("I2C: ");
while (Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}
Serial.println();
delay(1000);
}
NodeMCU ESP 8266 Level-Shifter Ardu.Nano
3V3 5V
D4 ---- o o -- 10k Pullup -- SDA_Slave (A4)
D3 ---- o o -- 10k Pullup -- SCL_Slave (A5)
G ---- o ------- o ---------------- GND
My NodeMCU (ESP8266) is receiving well a string from NANO-Slave!
ESP-Codes:
#include <Wire.h>
void setup()
{
Wire.begin(2, 0); // SDA, SCL GPIO 2 & 0 correspond to D4 & D3 (On the Nano you just need: Wire.begin();)
Serial.begin(115200);
Serial.print(" ");
}
void loop()
{
byte n = Wire.requestFrom(10, 14); //request 14 bytes from adress 10 (0x0A)
Serial.print("I2C: ");
for (int i =0; i<n-1; i++)
{ // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}
Serial.println();
delay(1000);
}
Google always helps, but you need to ask the related question.
After hours of investigating , taking my setup apart, changing resistors, switching the boards, googling (still working i2c with nano => nano, error with the same nano => esp8266) ....
The slave-nano seems to take to long to compute the reply (put together a char Array with sensor values), so the esp8266 was waiting too long.
The nano as master-reader seems to handle longer delays in its i2c library.
Maybe 4000 µs is overkill (?) but I'll stick to that as a have no oscilloscope to measure the delay time.
Working code:
#include <Wire.h>
void setup() {
Wire.begin(5, 4);
Serial.begin(115200);
Wire.setClockStretchLimit(4000L);
}
void loop() {
Wire.requestFrom(10, 14); //request 14 bytes from adress 10 (0x0A)
Serial.print("I2C: ");
// delay(5);
while (Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
// delay(5);
}
Serial.println();
delay(1000);
}
I am impressed about the help some unknowing hobby-programmer-dude gets in this forum. Even somebody somewhere loaded my sketch on his own esp, did the wiring, programmed a slave device, made screenshots, shared all this just to help finding the error. Big thank you to everybody helping beginners like me in this forum! I learned so much from reading all your replies on so many questions I came across!