I2C 2 Boards -> Hängt ständig

Hallo Zusammen.

Ich habe mir mal was zusammen kopiert um zwischen nem DUE und nem ESP befehle per i2c hinunher zu schaufeln.

Aber leider hängt sich entweder der DUE oder der ESP ab und an bei einer i2c anfrage auf.

Könnt ihr mir da mal weiterhelfen?

ESP(Master)

#include <ESP8266WiFi.h>
#include <Wire.h>    //declare I2C library function
#define I2CAddressESPWifi 6

const char* ssid = "blub";
const char* password = "blub";
String answer = "";                                 // initialize answer;
String Humidity = "";
String Temp1 = "";
String Temp2 = "";
String LDR = "";
String Uhrzeit = "";

int ledPin = 12; // GPIO12 of ESP8266
WiFiServer server(80);

String sendMessage(String msg)
{
  answer = "";
  //Serial.println(msg);
  if (msg.length() > 32)
  {
    msg = msg.substring(0, 32);
  }
  char buf[33];                                       // actually we should not send more than 32-characters
  unsigned int len = msg.length() + 1;                // one extra for null-terminator
  msg.toCharArray(buf, len);                          // convert string to buf
  Wire.beginTransmission(I2CAddressESPWifi);          // begin a transmission to slave device 6
  //Serial.println(buf);
  //Serial.println(len);
  Wire.write(buf, len);                               // send character string
  Wire.endTransmission();                             // end a transmission to slave
  char c;
  delay(800);                                         // delay 1000 Milliseconds = 1 Second
  Wire.requestFrom(I2CAddressESPWifi, 15);             // request 15 bytes from slave 6
  while (Wire.available())                             // when data is received from slave to master
  {
    c = Wire.read();                                   // receive one byte from slave and assign to variable c
    delayMicroseconds(500);                            // delay, otherwise won't work
    // Serial.println(c);
    answer += c;
  }

  if (answer == "012345678901234") return "ERR";

  return answer;
}

void setup() {
  Serial.begin(115200);
  delay(10);


  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  Wire.begin(0, 2);
  Wire.setClockStretchLimit(1500);    // in µs

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while (!client.available()) {
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request

  int value = LOW;
  int sensoren = LOW;

  if (request.indexOf("/LED=ON") != -1) {
    digitalWrite(ledPin, HIGH);
    answer = sendMessage("/w<1>");
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1) {
    digitalWrite(ledPin, LOW);
    answer = sendMessage("/w<0>");
    value = LOW;
  }
  if (request.indexOf("/Sensoren") != -1) {
    Humidity = "";
    Temp1 = "";
    Temp2 = "";
    LDR = "";
    Uhrzeit = "";
    Humidity = sendMessage("/r<1>");
    Temp1 = sendMessage("/r<2>");
    Temp2 = sendMessage("/r<3>");
    LDR = sendMessage("/r<4>");
    Uhrzeit = sendMessage("/r<5>");
    sensoren = HIGH;
  }

  // Set ledPin according to the request
  //digitalWrite(ledPin, value);


  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.print("Led pin is now: ");

  if (value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }

  if (sensoren == HIGH) {
    client.println("

");
    client.println("Humidity: ");
    client.println(Humidity);
    client.println("
");
    client.println("Temp1: ");
    client.println(Temp1);
    client.println("
");
    client.println("Temp2: ");
    client.println(Temp2);
    client.println("
");
    client.println("LDR: ");
    client.println(LDR);
    client.println("
");
    client.println("Uhrzeit: ");
    client.println(Uhrzeit);
  }
  client.println("

");
  client.println("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 2 ON
");
  client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 2 OFF
");
  client.println("Click <a href=\"/Sensoren\">Sensoren</a> turn the LED on pin 2 OFF
");
  client.println("</html>");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

DUE(SLAVE)

#include <Wire.h>
#define I2CAddressESPWifi 6
#define numberOfBytes 15
char charBuffer[] = "012345678901234";
unsigned long counter = 0;
float DHTTemp = 25.20;
float DHTHum = 55;
float DSTemp0 = 30.10;
char buftime[10] = "15:25:59";

void setup() {
  Serial.begin(9600);
  Wire1.begin(I2CAddressESPWifi);    // join I2Cbus as slave with identified address
  Wire1.onReceive(receiveEvent);     // register a function to be called when slave receive a transmission from master//
  Wire1.onRequest(requestEvent);     // register a function when master request data from this slave device//
}

void loop() {
  counter++;
  if (counter > 4294967294)
  {
    counter = 0;
  }
}


// when slave receives string from master, trigger this event.
void receiveEvent(int howMany)
{
  Serial.println("start auslesen");
  String message = "";
  while ( Wire1.available() ) // execute repeatedly and read all bytes in the data packet from master//
  {
    char c = Wire1.read();    // receive data from master and assign it to char c
    Serial.println(c);
    message += c;
  }
  Serial.println("ende auslesen");


  String answer = "";

  answer = getStrParamValue(message);
  pushMessageToCharBuffer("OK" + getStringFixLengthFromUnsignedLong(numberOfBytes - 2, answer), charBuffer);

}

// trigger this event when master requests data from slave,
void requestEvent()
{
  // IMPORTANT! this code needs to be executed quickly, so do not write any other code in here!
  // buffer containing message (answer) must have a fixed length of 15 because ESP expects so...
  Wire1.write(charBuffer);
}



// function to read the value of a parameter
String getStrParamValue(String s)
{
  Serial.println(s);
  if (s.startsWith("/r", 0))
  {
    int indexStart = s.indexOf('<');
    int indexEnd = s.indexOf('>');
    if (indexStart > 0 and indexEnd > indexStart)
    {
      int i = s.substring(indexStart + 1 , indexEnd).toInt();
      if (i == 2) return (String)DHTTemp;
      if (i == 1) return (String)DHTHum;
      if (i == 3) return (String)DSTemp0;
      if (i == 4) return (String)analogRead(A2);
      if (i == 5) return (String)buftime;


    } else {
      Serial.println("i2c Daten fehlerhaft");
    }

  } else if (s.startsWith("/w", 0)) {
    int indexStart = s.indexOf('<');
    int indexEnd = s.indexOf('>');
    if (indexStart > 0 and indexEnd > indexStart)
    {
      int i = s.substring(indexStart + 1 , indexEnd).toInt();
      if (i == 1) Serial.println("set 1");
      if (i == 0) Serial.println("set 0");

    } else {
      Serial.println("i2c Daten fehlerhaft");
    }


  } else {
    Serial.println("i2c Daten fehlerhaft");

  }
}

// convert message to char-buffer
void pushMessageToCharBuffer(String s, char *charArray)
{
  unsigned int len = s.length() + 1; // one extra for null-terminator
  s.toCharArray(charArray, len);
}

// fill up string with hashes in front of value
String getStringFixLengthFromUnsignedLong(int stringSize, String value)
{
  String s = String(value);
  String f = "";
  int spacers = stringSize - s.length();
  for (int i = 0; i < spacers; i++)
  {
    f += "#";
  }
  return (f + s).substring(0, stringSize);
}

Könnt ihr mir sagen was ich falsch mache?

Ich würde das mal ohne Strings probieren, vielleicht müllen die den Speicher voll bis nichts mehr geht.

Ansonsten jeden I2C Aufruf auf Fehler prüfen.

DrDiettrich:
Ansonsten jeden I2C Aufruf auf Fehler prüfen.

wie :slight_smile:

Schau nach, welche Ergebnisse die Funktionen zurückgeben.

Leider nicht die erhoffte Hilfe :frowning:

Auch wenn es Dir nicht gefällt: Der Hinweis mit den Strings war eine konkrete Hilfe.

Gruß Tommy