Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1.  
  2. #include <SoftwareSerial.h>
  3. #define RX 10
  4. #define TX 11
  5. SoftwareSerial esp(RX, TX);
  6.  
  7. //cmd
  8. int cTrCmd;
  9. int cTmCmd;
  10. boolean f = false;
  11.  
  12. //Wifi
  13. String W_SSID = "TP-LINK_F1D01E";
  14. String W_PASS = "4188370026563794";
  15.  
  16. //ThingSpeak
  17. String API_KEY = "XMISMZZSMUYC33E9";
  18. String THING_IP = "api.thingspeak.com";
  19. String PORT = "80";
  20.  
  21.  
  22.  
  23. void setup() {
  24.   Serial.begin(9600);
  25.   esp.begin(115200);
  26.  
  27.   debug();
  28.   connectWiFi();
  29. }
  30.  
  31. void loop() {
  32.  
  33.   delay(13000);
  34.   sendData();
  35.  
  36.  
  37.  
  38. }
  39.  
  40. void sendData() {
  41.   sendCmd("AT+CIPMUX=1","OK");
  42.   String cmd = "AT+CIPSTART=0,\"TCP\",\"" + THING_IP + "\"," + PORT;
  43.   sendCmd(cmd, "OK");
  44.   int i = random(100);
  45.   String getMethod = "GET /update?key=" + API_KEY + "&field1=" + i + " \r\n";
  46.   sendCmd("AT+CIPSEND=0," + String(getMethod.length() + 4), ">");
  47.   sendCmd(getMethod);  
  48.   delay(2000);
  49.   sendCmd("AT+CIPCLOSE=0", "OK");
  50. }
  51.  
  52. void connectWiFi() {
  53.   if (sendCmd("AT+CWMODE=1", "OK")) {
  54.     Serial.println("----> Module mod set to Station");
  55.   }
  56.   if (sendCmd("AT+CWJAP=\"" + W_SSID + "\",\"" + W_PASS + "\"", "OK")) {
  57.     Serial.println("----> Connected to WiFI: " + W_SSID);
  58.   } else {
  59.     Serial.println("----> Connection failed: " + W_SSID);
  60.   }
  61. }
  62.  
  63. void debug() {
  64.   if (sendCmd("AT", "OK")) {
  65.     Serial.println("----> Module connection DONE");
  66.   } else {
  67.     Serial.println("----> Module connection FAILED");
  68.   }
  69. }
  70.  
  71. boolean sendCmd(String cmd, char repl[]) {
  72.   Serial.print(cTrCmd);
  73.   Serial.print(". Command: " + cmd + " ");
  74.   while (cTmCmd < 20) {
  75.     esp.println(cmd);
  76.     if (esp.find(repl)) {
  77.       f = true;
  78.       break;
  79.     }
  80.     cTmCmd++;
  81.   }
  82.   if (f == true) {
  83.     Serial.println("DONE");
  84.     cTrCmd++;
  85.     cTmCmd = 0;
  86.   }
  87.   if (f == false) {
  88.     Serial.println("FAIL");
  89.     cTrCmd = 0;
  90.     cTmCmd = 0;
  91.   }
  92.   boolean f_l = f;
  93.   f = false;
  94.   return f_l;
  95. }
  96. boolean sendCmd(String cmd) {
  97.   Serial.print(cTrCmd);
  98.   Serial.println(". Command: " + cmd + " ");
  99.   esp.println(cmd);
  100.   cTrCmd++;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement