mikroavr

kirim_adc_i2c_slave_mega328_lora_tani

Feb 15th, 2021 (edited)
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ArduinoJson.h>
  2. StaticJsonDocument<50> doc1;
  3. StaticJsonDocument<50> doc2;
  4. StaticJsonDocument<50> doc3;
  5.  
  6. #include <Wire.h>
  7. unsigned long cur_time,old_time;
  8.  
  9. int dt_adc0;
  10. int dt_adc1;
  11. int dt_adc2;
  12. int dt_adc3;
  13. int dt_adc6;
  14. int dt_adc7;
  15.  
  16. char char_payload1[50];
  17. char char_payload2[50];
  18. char char_payload3[50];
  19.  
  20. String str_payload;
  21.  
  22. byte count_request = 0;
  23.  
  24. void setup() {
  25.   Serial.begin(115200);
  26.   Wire.begin(1);                // join i2c bus with address #8
  27.   Wire.onRequest(requestEvent); // register event
  28. }
  29.  
  30. void loop() {
  31.   cur_time = millis();
  32.   if(cur_time -old_time >= 1000){
  33.     baca_adc();
  34.     //Serial.println("bismillaah");
  35.     old_time = cur_time;
  36.   }
  37.   //Serial.println("bismillaah");
  38. }
  39.  
  40. void requestEvent() {
  41.     switch(count_request){
  42.       case 0:
  43.         count_request = 1;
  44.         Wire.write(char_payload1);
  45.         //Serial.println(char_payload1);
  46.       break;
  47.       case 1:
  48.         count_request = 0;
  49.         Wire.write(char_payload2);
  50.         //Serial.println(char_payload2);
  51.       break;
  52.     }
  53. }
  54.  
  55.  
  56. void baca_adc(){
  57.   dt_adc0 = analogRead(A0);
  58.   dt_adc1 = analogRead(A1);
  59.   dt_adc2 = analogRead(A2);
  60.   dt_adc3 = analogRead(A3);
  61.   dt_adc6 = analogRead(A6);
  62.   dt_adc7 = analogRead(A7);
  63.   build_json();
  64. }
  65.  
  66. void build_json(){
  67.   String payload;
  68.   doc1["s"] = 0;
  69.   doc1["a"] = dt_adc0;
  70.   doc1["b"] = dt_adc1;
  71.   doc1["c"] = dt_adc2;
  72.   serializeJson(doc1, payload);
  73.   str_payload = payload;
  74.   str_payload.toCharArray(char_payload1, str_payload.length()+1);
  75.   str_payload = "";payload = "";
  76.  
  77.  
  78.   doc2["s"] = 1;
  79.   doc2["d"] = dt_adc3;
  80.   doc2["e"] = dt_adc6;
  81.   doc2["f"] = dt_adc7;
  82.  
  83.   serializeJson(doc2, payload);
  84.   str_payload = payload;
  85.   str_payload.toCharArray(char_payload2, str_payload.length()+1);
  86.   str_payload = "";payload = "";
  87.  
  88.   //Serial.println(char_payload1);
  89.   //Serial.println(char_payload2);
  90.   doc1.clear();
  91.   doc2.clear();
  92. }
  93.  
Add Comment
Please, Sign In to add comment