Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const int trigPin = 2;
- const int echoPin = 4;
- const int relayPin = 6;
- #define SSID "MYSSID"
- #define PASS "MYPASSWORD"
- #define OPENMAXDIST 15
- #define CLOSEDMINDIST 40
- #define WIFI_Serial Serial
- //#define DEBUG
- #ifdef DEBUG
- #define Debug_Serial softSerial
- #include <SoftwareSerial.h>
- SoftwareSerial softSerial(10, 11); // RX, TX
- #endif
- const unsigned long sensorReadInterval = 2000;
- boolean commandReady = false;
- char *command;
- const unsigned long monitorBufferTimeout = 1000;
- const byte numMonitorChars = 64;
- char monitorBuffer[numMonitorChars];
- int connectionId = -1;
- int dataLength = 0;
- void setup()
- {
- WIFI_Serial.begin(9600);
- #ifdef DEBUG
- Debug_Serial.begin(4800);
- #endif
- pinMode(relayPin, OUTPUT);
- pinMode(13, OUTPUT);
- digitalWrite(relayPin, HIGH);
- // Wait 10 seconds to set up the debug console, output counter
- digitalWrite(13, HIGH);
- for (int i = 0; i < 3; i++)
- {
- delay(1000);
- #ifdef DEBUG
- Debug_Serial.println(i);
- #endif
- }
- // Start the ESP. Wait for OK while outputing input to Debug_Serial
- #ifdef DEBUG
- Debug_Serial.println("Starting up");
- #endif
- WIFI_Serial.println("AT+RST");
- if (checkForOK(10000))
- {
- #ifdef DEBUG
- Debug_Serial.println("Module is ready");
- #endif
- }
- else
- {
- #ifdef DEBUG
- Debug_Serial.println("Module has no response.");
- #endif
- while (1);
- }
- // Start the ESP. Wait for OK while outputing input to Debug_Serial
- WIFI_Serial.println("AT+CWMODE=1");
- if (checkForOK(10000))
- {
- #ifdef DEBUG
- Debug_Serial.println("Module is ready");
- #endif
- }
- else
- {
- #ifdef DEBUG
- Debug_Serial.println("Module has no response.");
- #endif
- while (1);
- }
- //connect to the wifi
- boolean connected = false;
- for (int i = 0; i < 10; i++)
- {
- if (connectWiFi())
- {
- connected = true;
- break;
- }
- }
- if (!connected) {
- while (1);
- }
- // Do a bunch of config stuff, discard the output
- //print the ip addr
- WIFI_Serial.println("AT+CIFSR");
- checkForOK(1000);
- //set multiple connection mode
- WIFI_Serial.println("AT+CIPMUX=1");
- checkForOK(1000);
- //set server mode
- WIFI_Serial.println("AT+CIPSERVER=1,23");
- checkForOK(1000);
- // Flush buffer if not already done by debug mode
- delay(1000);
- while (WIFI_Serial.available())
- WIFI_Serial.read();
- digitalWrite(13, LOW);
- }
- void loop()
- {
- // Refresh gate distance if necessary
- getGateDistance();
- // Monitor the serial port input
- monitorSerial();
- //Check if relay should be turned off again. Since the duration of the
- switch press doesn't really matter, I don't take the overhead of timed
- interrupts.
- controlRelay(0);
- }
- void executeCommand()
- {
- String message;
- boolean sendmessage = true;
- if (!strcmp(command, "status")) // print distance from sensor
- {
- message = String(getGateDistance());
- if (getGateDistance() < OPENMAXDIST)
- message += " (OPEN)";
- else if (getGateDistance() > CLOSEDMINDIST)
- message += " (CLOSED)";
- else
- message += " (UNCLEAR)";
- }
- else if (!strcmp(command, "close")) // close ...
- {
- if (getGateDistance() < OPENMAXDIST) // ... if gate open
- {
- controlRelay(500);
- message = "OK";
- }
- else
- {
- message = "ISCLOSED";
- }
- }
- else if (!strcmp(command, "open")) // open ...
- {
- if (getGateDistance() > CLOSEDMINDIST) // ... if gate closed
- {
- controlRelay(500);
- message = "OK";
- }
- else
- {
- message = "ISOPEN";
- }
- }
- else
- {
- #ifdef DEBUG
- Debug_Serial.println("Unknown command");
- #endif
- sendmessage = false;
- }
- if (sendmessage)
- {
- sendIPMessage(connectionId, message);
- closeConnection(connectionId);
- }
- }
- void controlRelay(unsigned long duration)
- {
- static unsigned long offTime = 0;
- if (offTime < millis())
- digitalWrite(relayPin, HIGH);
- if (duration > 0)
- {
- offTime = millis() + duration;
- digitalWrite(relayPin, LOW);
- }
- }
- void monitorSerial()
- {
- static byte monitorBufferingIdx = 0;
- static unsigned long monitorBufferStart = 0;
- static boolean monitorBuffering = false;
- char inChar;
- // We are not going to wait forever for you to finish ...
- if (monitorBuffering && (millis() - monitorBufferStart) >
- monitorBufferTimeout)
- {
- #ifdef DEBUG
- Debug_Serial.println("Input timeout");
- #endif
- monitorBuffering = false;
- monitorBufferingIdx = 0;
- }
- while (WIFI_Serial.available())
- {
- inChar = WIFI_Serial.read();
- #ifdef DEBUG
- Debug_Serial.print(inChar);
- #endif
- if (inChar == '\n' || inChar == '\r')
- {
- if (monitorBufferingIdx > 0)
- {
- monitorBuffer[monitorBufferingIdx] = '\0';
- #ifdef DEBUG
- Debug_Serial.print("Parsing Data: ");
- Debug_Serial.println(monitorBuffer);
- #endif
- parseData();
- }
- monitorBuffering = false;
- monitorBufferingIdx = 0;
- }
- else
- {
- monitorBuffer[monitorBufferingIdx] = inChar;
- monitorBuffering = true;
- monitorBufferStart = millis();
- monitorBufferingIdx++;
- if (monitorBufferingIdx >= numMonitorChars)
- {
- monitorBufferingIdx = numMonitorChars - 1;
- #ifdef DEBUG
- Debug_Serial.println("Input buffer overfill!");
- #endif
- }
- }
- }
- }
- void parseData()
- {
- //I expect data of the form "+IPD,<id>,<len>:<data>"
- char delimiter[] = ",:";
- char *ptr;
- int tmpConnectionId;
- int dataLength;
- // initialisieren und ersten Abschnitt erstellen
- ptr = strtok(monitorBuffer, delimiter);
- if (0 != strcmp(ptr, "+IPD"))
- {
- #ifdef DEBUG
- Debug_Serial.println("No use for input.");
- #endif
- return;
- }
- #ifdef DEBUG
- Debug_Serial.print("Got IP connection ");
- #endif
- //read connectionId
- ptr = strtok(NULL, delimiter);
- tmpConnectionId = atoi(ptr);
- #ifdef DEBUG
- Debug_Serial.print("with connection id ");
- Debug_Serial.println(tmpConnectionId);
- #endif
- if (connectionId >= 0 && connectionId != tmpConnectionId) //We are
- currently busy, please leave
- {
- sendIPMessage(tmpConnectionId, "BUSY");
- closeConnection(tmpConnectionId);
- #ifdef DEBUG
- Debug_Serial.print("Discarded connection ");
- Debug_Serial.print(tmpConnectionId);
- Debug_Serial.println(" since active connection present.");
- #endif
- return;
- }
- else
- {
- connectionId = tmpConnectionId;
- #ifdef DEBUG
- Debug_Serial.print("Accepted connection ");
- Debug_Serial.println(connectionId);
- #endif
- }
- //read data length
- ptr = strtok(NULL, delimiter);
- dataLength = atoi(ptr);
- if (dataLength == 0) //Then what do you want?
- {
- #ifdef DEBUG
- Debug_Serial.println("Empty data");
- #endif
- return;
- }
- //read data
- command = strtok(NULL, delimiter);
- dataLength = atoi(ptr);
- if (dataLength != strlen(command)) //Length doesn't seem reliable, so
- just a notice
- {
- //closeConnection(connectionId);
- #ifdef DEBUG
- Debug_Serial.print("Something is wrong. Expected ");
- Debug_Serial.print(dataLength);
- Debug_Serial.print(" characters, but got '");
- Debug_Serial.print(command);
- Debug_Serial.println("'");
- #endif
- //return;
- }
- #ifdef DEBUG
- Debug_Serial.print("Found command: '");
- Debug_Serial.print(command);
- Debug_Serial.println("'");
- #endif
- if (strlen(command) > 0)
- {
- #ifdef DEBUG
- Debug_Serial.println("Signalling ready command");
- #endif
- executeCommand();
- }
- #ifdef DEBUG
- else
- {
- Debug_Serial.println("Ignoring empty command");
- }
- #endif
- }
- void closeConnection(int connectionId)
- {
- String closeCommand = "AT+CIPCLOSE=";
- closeCommand += connectionId; // append connection id
- closeCommand += "\r\n";
- boolean closed = false;
- for(int i = 0; i<10 && !closed; i++)
- {
- #ifdef DEBUG
- Debug_Serial.print("Closing connection: ");
- Debug_Serial.println(connectionId);
- #endif
- WIFI_Serial.println(closeCommand);
- closed = WIFI_Serial.find("CLOSED"); //Blocking!
- }
- connectionId = -1;
- }
- void sendIPMessage(int connectionId, String message)
- {
- String cipSend = "AT+CIPSEND=";
- cipSend += connectionId;
- cipSend += ",";
- cipSend += message.length();
- cipSend += "\r\n";
- WIFI_Serial.println(cipSend);
- #ifdef DEBUG
- Debug_Serial.println(cipSend);
- #endif
- if (WIFI_Serial.find(">"))
- {
- WIFI_Serial.println(message);
- if (checkForOK(10000))
- {
- #ifdef DEBUG
- Debug_Serial.print("Send '");
- Debug_Serial.print(message);
- Debug_Serial.println("'");
- #endif
- }
- #ifdef DEBUG
- else
- {
- Debug_Serial.print("Could not send '");
- Debug_Serial.print(message);
- Debug_Serial.println("'");
- }
- #endif
- }
- #ifdef DEBUG
- else
- {
- Debug_Serial.print("Timeout waiting for '>'. Message: ");
- Debug_Serial.println(message);
- }
- #endif
- }
- boolean connectWiFi()
- {
- String cmd = "AT+CWJAP=\"";
- cmd += SSID;
- cmd += "\",\"";
- cmd += PASS;
- cmd += "\"";
- #ifdef DEBUG
- Debug_Serial.println(cmd);
- #endif
- WIFI_Serial.println(cmd);
- if (checkForOK(10000))
- {
- #ifdef DEBUG
- Debug_Serial.println("OK, Connected to WiFi.");
- #endif
- return true;
- }
- else
- {
- #ifdef DEBUG
- Debug_Serial.println("Can not connect to the WiFi.");
- #endif
- return false;
- }
- }
- boolean checkForOK(unsigned long timeout)
- {
- // Blocking check for the string OK with debug output
- char inChar;
- boolean oLast = false;
- boolean returnV = false;
- unsigned long time = millis();
- while (!returnV && (millis() - time) < timeout)
- {
- while (WIFI_Serial.available() && !returnV)
- {
- inChar = WIFI_Serial.read();
- #ifdef DEBUG
- Debug_Serial.print(inChar);
- #endif
- if (oLast && inChar == 'K')
- returnV = true;
- else if (inChar == 'O')
- oLast = true;
- else
- oLast = false;
- }
- }
- #ifdef DEBUG
- Debug_Serial.println();
- #endif
- return returnV;
- }
- unsigned int getGateDistance()
- {
- static unsigned long sensorReadTime = 0;
- static unsigned int gateDistance = 0;
- if ((millis() - sensorReadTime) > sensorReadInterval || sensorReadTime
- == 0)
- {
- unsigned long duration;
- pinMode(echoPin, INPUT);
- // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
- // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
- pinMode(trigPin, OUTPUT);
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Read the signal from the sensor: a HIGH pulse whose
- // duration is the time (in microseconds) from the sending
- // of the ping to the reception of its echo off of an object.
- duration = pulseIn(echoPin, HIGH);
- gateDistance = (double)duration / 58.2;
- sensorReadTime = millis();
- //#ifdef DEBUG
- // Debug_Serial.print("Distance: ");
- // Debug_Serial.println(gateDistance);
- //#endif
- }
- return gateDistance;
- }
- -- Dr. Michaela Lemmer Heuftgraben 1 49134 Wallenhorst
Advertisement
Add Comment
Please, Sign In to add comment