mikroavr

terima_i2c_oleh_esp32_lora_tani

Feb 15th, 2021
824
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ArduinoJson.h>
  2. #include <Wire.h>
  3.  
  4. String str_dt;
  5. char chr_i2c[33];
  6. int jml_i2c;
  7.  
  8. int adc0, adc1, adc2, adc3, adc6, adc7;
  9. int count_request = 0;
  10. int sts = 0;
  11.  
  12. void setup() {
  13.   Wire.begin();        // join i2c bus (address optional for master)
  14.   Serial.begin(115200);  // start serial for output
  15.   pinMode(4, OUTPUT);
  16.   pinMode(5, OUTPUT);
  17. }
  18.  
  19. void loop() {
  20.   request_i2c();
  21.   delay(250);
  22. }
  23.  
  24. void request_i2c() {
  25.   //Serial.println("request data");
  26.   Wire.requestFrom(1, 32);    // request 6 bytes from slave device #8
  27.   while (Wire.available()) { // slave may send less than requested
  28.     chr_i2c[jml_i2c] = Wire.read(); // receive a byte as character
  29.     if (chr_i2c[jml_i2c] == '}')break;
  30.     jml_i2c++;
  31.  
  32.   }
  33.  
  34.   for (int i = 0; i < 32; i++) {
  35.     str_dt += String(chr_i2c[i]);
  36.   }
  37.   DynamicJsonDocument doc(100);
  38.   deserializeJson(doc, str_dt);
  39.   //Serial.println(str_dt);
  40.   sts = doc["s"];
  41.   //Serial.println(sts);
  42.   switch (sts) {
  43.     case 0:
  44.       adc0 = doc["a"];
  45.       adc1 = doc["b"];
  46.       adc2 = doc["c"];
  47.       Serial.print("adc0: ");Serial.print(adc0); Serial.print(",");
  48.       Serial.print("adc1: ");Serial.print(adc1); Serial.print(",");
  49.       Serial.print("adc2: ");Serial.print(adc2); Serial.println();
  50.       break;
  51.     case 1:
  52.       adc3 = doc["d"];
  53.       adc6 = doc["e"];
  54.       adc7 = doc["f"];
  55.       Serial.print("adc3: ");Serial.print(adc3); Serial.print(",");
  56.       Serial.print("adc6: ");Serial.print(adc6); Serial.print(",");
  57.       Serial.print("adc7: ");Serial.print(adc7); Serial.println();
  58.       break;
  59.   }
  60.  
  61.   str_dt = ""; jml_i2c = 0; doc.clear();
  62.  
  63. }
  64.  
  65.  
  66.  
  67.  
RAW Paste Data