Guest User

Untitled

a guest
May 12th, 2015
456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 11.02 KB | None | 0 0
  1.  
  2.  
  3. const int trigPin = 2;
  4. const int echoPin = 4;
  5. const int relayPin = 6;
  6.  
  7. #define SSID "MYSSID"
  8. #define PASS "MYPASSWORD"
  9. #define OPENMAXDIST 15
  10. #define CLOSEDMINDIST 40
  11.  
  12. #define WIFI_Serial Serial
  13.  
  14. //#define DEBUG
  15.  
  16. #ifdef DEBUG
  17. #define Debug_Serial softSerial
  18. #include <SoftwareSerial.h>
  19. SoftwareSerial softSerial(10, 11); // RX, TX
  20. #endif
  21.  
  22. const unsigned long sensorReadInterval = 2000;
  23.  
  24. boolean commandReady = false;
  25. char *command;
  26.  
  27. const unsigned long monitorBufferTimeout = 1000;
  28. const byte numMonitorChars = 64;
  29. char monitorBuffer[numMonitorChars];
  30.  
  31. int connectionId = -1;
  32. int dataLength = 0;
  33.  
  34. void setup()
  35. {
  36.   WIFI_Serial.begin(9600);
  37.  
  38. #ifdef DEBUG
  39.   Debug_Serial.begin(4800);
  40. #endif
  41.  
  42.   pinMode(relayPin, OUTPUT);
  43.   pinMode(13, OUTPUT);
  44.   digitalWrite(relayPin, HIGH);
  45.  
  46.   // Wait 10 seconds to set up the debug console, output counter
  47.   digitalWrite(13, HIGH);
  48.   for (int i = 0; i < 3; i++)
  49.   {
  50.     delay(1000);
  51. #ifdef DEBUG
  52.     Debug_Serial.println(i);
  53. #endif
  54.   }
  55.  
  56.   // Start the ESP. Wait for OK while outputing input to Debug_Serial
  57. #ifdef DEBUG
  58.   Debug_Serial.println("Starting up");
  59. #endif
  60.   WIFI_Serial.println("AT+RST");
  61.   if (checkForOK(10000))
  62.   {
  63. #ifdef DEBUG
  64.     Debug_Serial.println("Module is ready");
  65. #endif
  66.   }
  67.   else
  68.   {
  69. #ifdef DEBUG
  70.     Debug_Serial.println("Module has no response.");
  71. #endif
  72.     while (1);
  73.   }
  74.  
  75.   // Start the ESP. Wait for OK while outputing input to Debug_Serial
  76.   WIFI_Serial.println("AT+CWMODE=1");
  77.   if (checkForOK(10000))
  78.   {
  79. #ifdef DEBUG
  80.     Debug_Serial.println("Module is ready");
  81. #endif
  82.   }
  83.   else
  84.   {
  85. #ifdef DEBUG
  86.     Debug_Serial.println("Module has no response.");
  87. #endif
  88.     while (1);
  89.   }
  90.  
  91.   //connect to the wifi
  92.   boolean connected = false;
  93.   for (int i = 0; i < 10; i++)
  94.   {
  95.     if (connectWiFi())
  96.     {
  97.       connected = true;
  98.       break;
  99.     }
  100.   }
  101.   if (!connected) {
  102.     while (1);
  103.   }
  104.  
  105.   // Do a bunch of config stuff, discard the output
  106.   //print the ip addr
  107.   WIFI_Serial.println("AT+CIFSR");
  108.   checkForOK(1000);
  109.  
  110.   //set multiple connection mode
  111.   WIFI_Serial.println("AT+CIPMUX=1");
  112.   checkForOK(1000);
  113.  
  114.   //set server mode
  115.   WIFI_Serial.println("AT+CIPSERVER=1,23");
  116.   checkForOK(1000);
  117.  
  118.   // Flush buffer if not already done by debug mode
  119.   delay(1000);
  120.   while (WIFI_Serial.available())
  121.     WIFI_Serial.read();
  122.   digitalWrite(13, LOW);
  123. }
  124.  
  125. void loop()
  126. {
  127.   // Refresh gate distance if necessary
  128.   getGateDistance();
  129.  
  130.   // Monitor the serial port input
  131.   monitorSerial();
  132.  
  133.   //Check if relay should be turned off again. Since the duration of the
  134. switch press doesn't really matter, I don't take the overhead of timed
  135. interrupts.
  136.   controlRelay(0);
  137. }
  138.  
  139. void executeCommand()
  140. {
  141.   String message;
  142.   boolean sendmessage = true;
  143.   if (!strcmp(command, "status")) // print distance from sensor
  144.   {
  145.     message = String(getGateDistance());
  146.     if (getGateDistance() < OPENMAXDIST)
  147.       message += " (OPEN)";
  148.     else if (getGateDistance() > CLOSEDMINDIST)
  149.       message += " (CLOSED)";
  150.     else
  151.       message += " (UNCLEAR)";
  152.   }
  153.   else if (!strcmp(command, "close")) // close ...
  154.   {
  155.     if (getGateDistance() < OPENMAXDIST) // ... if gate open
  156.     {
  157.       controlRelay(500);
  158.       message = "OK";
  159.     }
  160.     else
  161.     {
  162.       message = "ISCLOSED";
  163.     }
  164.   }
  165.   else if (!strcmp(command, "open")) // open ...
  166.   {
  167.     if (getGateDistance() > CLOSEDMINDIST) // ... if gate closed
  168.     {
  169.       controlRelay(500);
  170.       message = "OK";
  171.     }
  172.     else
  173.     {
  174.       message = "ISOPEN";
  175.     }
  176.   }
  177.   else
  178.   {
  179. #ifdef DEBUG
  180.     Debug_Serial.println("Unknown command");
  181. #endif
  182.     sendmessage = false;
  183.   }
  184.  
  185.   if (sendmessage)
  186.   {
  187.     sendIPMessage(connectionId, message);
  188.     closeConnection(connectionId);
  189.   }
  190. }
  191.  
  192. void controlRelay(unsigned long duration)
  193. {
  194.   static unsigned long offTime = 0;
  195.   if (offTime < millis())
  196.     digitalWrite(relayPin, HIGH);
  197.  
  198.   if (duration > 0)
  199.   {
  200.     offTime = millis() + duration;
  201.     digitalWrite(relayPin, LOW);
  202.   }
  203. }
  204.  
  205. void monitorSerial()
  206. {
  207.   static byte monitorBufferingIdx = 0;
  208.   static unsigned long monitorBufferStart = 0;
  209.   static boolean monitorBuffering = false;
  210.   char inChar;
  211.  
  212.   // We are not going to wait forever for you to finish ...
  213.   if (monitorBuffering && (millis() - monitorBufferStart) >
  214. monitorBufferTimeout)
  215.   {
  216. #ifdef DEBUG
  217.     Debug_Serial.println("Input timeout");
  218. #endif
  219.     monitorBuffering = false;
  220.     monitorBufferingIdx = 0;
  221.   }
  222.  
  223.   while (WIFI_Serial.available())
  224.   {
  225.     inChar = WIFI_Serial.read();
  226. #ifdef DEBUG
  227.     Debug_Serial.print(inChar);
  228. #endif
  229.  
  230.     if (inChar == '\n' || inChar == '\r')
  231.     {
  232.       if (monitorBufferingIdx > 0)
  233.       {
  234.         monitorBuffer[monitorBufferingIdx] = '\0';
  235.  
  236. #ifdef DEBUG
  237.         Debug_Serial.print("Parsing Data: ");
  238.         Debug_Serial.println(monitorBuffer);
  239. #endif
  240.  
  241.         parseData();
  242.       }
  243.       monitorBuffering = false;
  244.       monitorBufferingIdx = 0;
  245.     }
  246.     else
  247.     {
  248.       monitorBuffer[monitorBufferingIdx] = inChar;
  249.       monitorBuffering = true;
  250.       monitorBufferStart = millis();
  251.  
  252.       monitorBufferingIdx++;
  253.       if (monitorBufferingIdx >= numMonitorChars)
  254.       {
  255.         monitorBufferingIdx = numMonitorChars - 1;
  256. #ifdef DEBUG
  257.         Debug_Serial.println("Input buffer overfill!");
  258. #endif
  259.       }
  260.     }
  261.   }
  262. }
  263.  
  264. void parseData()
  265. {
  266.   //I expect data of the form "+IPD,<id>,<len>:<data>"
  267.   char delimiter[] = ",:";
  268.   char *ptr;
  269.   int tmpConnectionId;
  270.   int dataLength;
  271.  
  272.   // initialisieren und ersten Abschnitt erstellen
  273.   ptr = strtok(monitorBuffer, delimiter);
  274.  
  275.   if (0 != strcmp(ptr, "+IPD"))
  276.   {
  277. #ifdef DEBUG
  278.     Debug_Serial.println("No use for input.");
  279. #endif
  280.     return;
  281.   }
  282. #ifdef DEBUG
  283.   Debug_Serial.print("Got IP connection ");
  284. #endif
  285.  
  286.   //read connectionId
  287.   ptr = strtok(NULL, delimiter);
  288.   tmpConnectionId = atoi(ptr);
  289. #ifdef DEBUG
  290.   Debug_Serial.print("with connection id ");
  291.   Debug_Serial.println(tmpConnectionId);
  292. #endif
  293.   if (connectionId >= 0 && connectionId != tmpConnectionId) //We are
  294. currently busy, please leave
  295.   {
  296.     sendIPMessage(tmpConnectionId, "BUSY");
  297.     closeConnection(tmpConnectionId);
  298. #ifdef DEBUG
  299.     Debug_Serial.print("Discarded connection ");
  300.     Debug_Serial.print(tmpConnectionId);
  301.     Debug_Serial.println(" since active connection present.");
  302. #endif
  303.     return;
  304.   }
  305.   else
  306.   {
  307.     connectionId = tmpConnectionId;
  308. #ifdef DEBUG
  309.     Debug_Serial.print("Accepted connection ");
  310.     Debug_Serial.println(connectionId);
  311. #endif
  312.   }
  313.  
  314.   //read data length
  315.   ptr = strtok(NULL, delimiter);
  316.   dataLength = atoi(ptr);
  317.   if (dataLength == 0) //Then what do you want?
  318.   {
  319. #ifdef DEBUG
  320.     Debug_Serial.println("Empty data");
  321. #endif
  322.     return;
  323.   }
  324.  
  325.   //read data
  326.   command = strtok(NULL, delimiter);
  327.   dataLength = atoi(ptr);
  328.   if (dataLength != strlen(command)) //Length doesn't seem reliable, so
  329. just a notice
  330.   {
  331.     //closeConnection(connectionId);
  332. #ifdef DEBUG
  333.     Debug_Serial.print("Something is wrong. Expected ");
  334.     Debug_Serial.print(dataLength);
  335.     Debug_Serial.print(" characters, but got '");
  336.     Debug_Serial.print(command);
  337.     Debug_Serial.println("'");
  338. #endif
  339.     //return;
  340.   }
  341. #ifdef DEBUG
  342.   Debug_Serial.print("Found command: '");
  343.   Debug_Serial.print(command);
  344.   Debug_Serial.println("'");
  345. #endif
  346.   if (strlen(command) > 0)
  347.   {
  348. #ifdef DEBUG
  349.     Debug_Serial.println("Signalling ready command");
  350. #endif
  351.     executeCommand();
  352.   }
  353. #ifdef DEBUG
  354.   else
  355.   {
  356.     Debug_Serial.println("Ignoring empty command");
  357.   }
  358. #endif
  359. }
  360.  
  361. void closeConnection(int connectionId)
  362. {
  363.   String closeCommand = "AT+CIPCLOSE=";
  364.   closeCommand += connectionId; // append connection id
  365.   closeCommand += "\r\n";
  366.  
  367.   boolean closed = false;
  368.   for(int i = 0; i<10 && !closed; i++)
  369.   {
  370.     #ifdef DEBUG
  371.       Debug_Serial.print("Closing connection: ");
  372.       Debug_Serial.println(connectionId);
  373.     #endif
  374.     WIFI_Serial.println(closeCommand);
  375.     closed = WIFI_Serial.find("CLOSED"); //Blocking!
  376.   }
  377.   connectionId = -1;
  378. }
  379.  
  380. void sendIPMessage(int connectionId, String message)
  381. {
  382.   String cipSend = "AT+CIPSEND=";
  383.   cipSend += connectionId;
  384.   cipSend += ",";
  385.   cipSend += message.length();
  386.   cipSend += "\r\n";
  387.  
  388.   WIFI_Serial.println(cipSend);
  389. #ifdef DEBUG
  390.   Debug_Serial.println(cipSend);
  391. #endif
  392.  
  393.   if (WIFI_Serial.find(">"))
  394.   {
  395.     WIFI_Serial.println(message);
  396.     if (checkForOK(10000))
  397.     {
  398. #ifdef DEBUG
  399.       Debug_Serial.print("Send '");
  400.       Debug_Serial.print(message);
  401.       Debug_Serial.println("'");
  402. #endif
  403.     }
  404. #ifdef DEBUG
  405.     else
  406.     {
  407.       Debug_Serial.print("Could not send '");
  408.       Debug_Serial.print(message);
  409.       Debug_Serial.println("'");
  410.     }
  411. #endif
  412.   }
  413. #ifdef DEBUG
  414.   else
  415.   {
  416.     Debug_Serial.print("Timeout waiting for '>'. Message: ");
  417.     Debug_Serial.println(message);
  418.   }
  419. #endif
  420. }
  421.  
  422. boolean connectWiFi()
  423. {
  424.   String cmd = "AT+CWJAP=\"";
  425.   cmd += SSID;
  426.   cmd += "\",\"";
  427.   cmd += PASS;
  428.   cmd += "\"";
  429. #ifdef DEBUG
  430.   Debug_Serial.println(cmd);
  431. #endif
  432.   WIFI_Serial.println(cmd);
  433.  
  434.   if (checkForOK(10000))
  435.   {
  436. #ifdef DEBUG
  437.     Debug_Serial.println("OK, Connected to WiFi.");
  438. #endif
  439.     return true;
  440.   }
  441.   else
  442.   {
  443. #ifdef DEBUG
  444.     Debug_Serial.println("Can not connect to the WiFi.");
  445. #endif
  446.     return false;
  447.   }
  448. }
  449.  
  450. boolean checkForOK(unsigned long timeout)
  451. {
  452.   // Blocking check for the string OK with debug output
  453.   char inChar;
  454.   boolean oLast = false;
  455.   boolean returnV = false;
  456.   unsigned long time = millis();
  457.  
  458.   while (!returnV && (millis() - time) < timeout)
  459.   {
  460.     while (WIFI_Serial.available() && !returnV)
  461.     {
  462.       inChar = WIFI_Serial.read();
  463. #ifdef DEBUG
  464.       Debug_Serial.print(inChar);
  465. #endif
  466.       if (oLast && inChar == 'K')
  467.         returnV = true;
  468.       else if (inChar == 'O')
  469.         oLast = true;
  470.       else
  471.         oLast = false;
  472.     }
  473.   }
  474. #ifdef DEBUG
  475.   Debug_Serial.println();
  476. #endif
  477.   return returnV;
  478. }
  479.  
  480. unsigned int getGateDistance()
  481. {
  482.   static unsigned long sensorReadTime = 0;
  483.   static unsigned int gateDistance = 0;
  484.  
  485.   if ((millis() - sensorReadTime) > sensorReadInterval || sensorReadTime
  486. == 0)
  487.   {
  488.     unsigned long duration;
  489.     pinMode(echoPin, INPUT);
  490.  
  491.     // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  492.     // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  493.     pinMode(trigPin, OUTPUT);
  494.     digitalWrite(trigPin, LOW);
  495.     delayMicroseconds(2);
  496.     digitalWrite(trigPin, HIGH);
  497.     delayMicroseconds(10);
  498.     digitalWrite(trigPin, LOW);
  499.  
  500.     // Read the signal from the sensor: a HIGH pulse whose
  501.     // duration is the time (in microseconds) from the sending
  502.     // of the ping to the reception of its echo off of an object.
  503.     duration = pulseIn(echoPin, HIGH);
  504.  
  505.     gateDistance = (double)duration / 58.2;
  506.     sensorReadTime = millis();
  507.  
  508.     //#ifdef DEBUG
  509.     //    Debug_Serial.print("Distance: ");
  510.     //    Debug_Serial.println(gateDistance);
  511.     //#endif
  512.   }
  513.  
  514.   return gateDistance;
  515. }
  516. -- Dr. Michaela Lemmer Heuftgraben 1 49134 Wallenhorst
Advertisement
Add Comment
Please, Sign In to add comment