Advertisement
mikroavr

saklar sms arduino

Feb 23rd, 2022
1,177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <gprs.h>
  2. #include <softwareserial.h>
  3.  
  4. /*koneksi sim800 dengan Arduino
  5. SIM800 TX is connected to Arduino D8
  6. SIM800 RX is connected to Arduino D7
  7. */
  8.  
  9. #define TIMEOUT    5000
  10. #define RELAY_PIN    0 // relay pin di hubungkan ke D0
  11.  
  12. bool relayStatus;
  13. GPRS gprs;
  14.  
  15. void setup() {
  16.   Serial.begin(9600);
  17.   while (!Serial);
  18.  
  19.   Serial.println("Starting SIM800 SMS Command Processor");
  20.   gprs.preInit();
  21.   delay(1000);
  22.  
  23.   while (0 != gprs.init()) {
  24.     delay(1000);
  25.     Serial.print("init error\r\n");
  26.   }
  27.  
  28.   //Set SMS mode ke mode ASCII
  29.   if (0 != gprs.sendCmdAndWaitForResp("AT+CMGF=1\r\n", "OK", TIMEOUT)) {
  30.     ERROR("ERROR:CNMI");
  31.     return;
  32.   }
  33.  
  34.   //mulai baca ada indikasi sms baru
  35.   if (0 != gprs.sendCmdAndWaitForResp("AT+CNMI=1,2,0,0,0\r\n", "OK", TIMEOUT)) {
  36.     ERROR("ERROR:CNMI");
  37.     return;
  38.   }
  39.  
  40.   Serial.println("Init success");
  41. }
  42.  
  43. //Variable penyimpanan sms
  44. char currentLine[500] = "";
  45. int currentLineIndex = 0;
  46.  
  47. bool nextLineIsMessage = false;
  48.  
  49. void loop() {
  50.   //kontrol status relay di sini
  51.   digitalWrite(RELAY_PIN, relayStatus);
  52.  
  53.   //jika ada data serial terbaca
  54.   if (gprs.serialSIM800.available()) {
  55.     char lastCharRead = gprs.serialSIM800.read();
  56.     //baca karakter dari serial
  57.     if (lastCharRead == '\r' || lastCharRead == '\n') {
  58.       String lastLine = String(currentLine);
  59.  
  60.       //jika baris terakhir adalah +CMT, ada indikasi sms baru masuk.
  61.       if (lastLine.startsWith("+CMT:")) {
  62.  
  63.         Serial.println(lastLine);
  64.         nextLineIsMessage = true;
  65.  
  66.       } else if (lastLine.length() > 0) {
  67.  
  68.         if (nextLineIsMessage) {
  69.           Serial.println(lastLine);
  70.  
  71.           //disini tempat pembacaan sms oleh sim800, kontrol sms ada disini
  72.           if (lastLine.indexOf("RELAY ON") >= 0) {
  73.             relayStatus = 1;
  74.           } else if (lastLine.indexOf("RELAY OFF") >= 0) {
  75.             relayStatus = 0;
  76.           }
  77.  
  78.           nextLineIsMessage = false;
  79.         }
  80.  
  81.       }
  82.  
  83.       //Clear char array for next line of read
  84.       for ( int i = 0; i < sizeof(currentLine);  ++i ) {
  85.         currentLine[i] = (char)0;
  86.       }
  87.       currentLineIndex = 0;
  88.     } else {
  89.       currentLine[currentLineIndex++] = lastCharRead;
  90.     }
  91.   }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement