I am trying to make I2C Communication between NodeMCU and arduino Uno boards. However it is not working properly. It makes communication for once time when i uploaded code.
Master Device Code(NodeMCU 1.0)
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>
HTTPClient client;
StaticJsonDocument <200> doc;
const char* ssid = "MY_SSID";
const char* pass = "MY_PASSWORD";
void setup() {
Serial.begin(9600);
Wire.begin(D1,D2);
WiFi.begin(ssid,pass);
while(WiFi.status() != WL_CONNECTED) {;}
}
void loop() {
const char* cd = getCode();
if(cd==nullptr) {
Serial.println("Problem Occurred.");
delay(10000);
return;
}
//Bad code is starting...
//Basically, sending 24 bytes of data for a Wire Transmission
int n = strlen(cd);
int rem = n%24; //remainder
int quo = (n-rem)/24; //quotient
while(quo!=0) {
char sel[24];
for(int i =0;i<24;i++) {
sel[i] = cd[((((n-rem)/24)-quo)*24)+i];
}
Wire.beginTransmission(8);
Wire.write(sel);
Wire.endTransmission();
quo-=1;
}
char sel[rem];
for(int i =0;i<rem;i++) {
sel[i] = cd[n-rem+i];
}
if(rem>0) {
Wire.beginTransmission(8);
Wire.write(sel);
Wire.endTransmission();
}
//Bad code finished!
//this is also not working.
Wire.requestFrom(8,3);
while(Wire.available()) {
char c = Wire.read();
Serial.print(c);
}
delay(15000);
}
//get code from server.
const char* getCode() {
client.begin("http://...");
int res = client.GET();
if(res<0) {
return 0;
}
String root = client.getString();
deserializeJson(doc,root);
const char* code = doc["Liste"][0]["code"];
return code;
}
Slave Device Code(Arduino Uno)
#include <Wire.h>
void setup() {
Serial.begin(9600);
Wire.begin(8);
Wire.onReceive(received);
Wire.onRequest(requested);
}
void loop() {delay(200);}
void received(int bytes) {
while (Wire.available()) {
char c = Wire.read();
Serial.print(c);
}
}
void requested() {
Wire.write("abc");
}
Circuit:
D1-SDA
D2-SCL
GND-GND