Connect Wi-Fi

Dependencies:   mbed

Revision:
1:c0fbff97b740
Child:
2:6738db3eb2ed
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ESP8266.cpp	Sat Dec 09 20:43:11 2017 +0000
@@ -0,0 +1,90 @@
+#include "ESP8266.h"
+
+// Constructor
+ESP8266::ESP8266(PinName tx, PinName rx, int br) : comm(tx, rx) {
+    comm.baud(br);
+}
+
+// Destructor
+ESP8266::~ESP8266() { }
+
+void ESP8266::AddEOL(char * s) {
+    char k;
+    k = strlen(s); // Finds position of NULL character
+    s[k] = 0x0D; // switch NULL for <CR>
+    s[k + 1] = 0x0A; // Add <LF>
+    s[k + 2] = 0; // Add NULL at the end
+}
+
+void ESP8266::AddChar(char * s, char c) {
+    char k;
+    k = strlen(s);
+    s[k] = c;
+    s[k + 1] = 0;
+}
+
+void ESP8266::SendCMD(char * s) {
+    AddEOL(s);
+    comm.printf("%s", s);
+}
+
+void ESP8266::Reset(void) {
+    char rs[10];
+    strcpy(rs, "AT+RST");
+    SendCMD(rs);
+}
+
+void ESP8266::RcvReply(char * r, int to) {
+    Timer t;
+    bool ended = 0;
+    char c;
+    
+    strcpy(r, "");
+    t.start();
+    while(!ended) {
+        if(comm.readable()) {
+            c = comm.getc();
+            AddChar(r, c);
+            t.start();
+        }
+        if(t.read_ms() > to) {
+                ended = 1;
+        }
+    }
+    AddChar(r, 0x00);
+}
+
+void ESP8266::SetMode(char mode) {
+    char cmd[15];
+    strcpy(cmd, "AT+CWMODE=");
+    mode = mode + 0x30; // Converts number into corresponding ASCII character
+    AddChar(cmd, mode); // Completes command string
+    SendCMD(cmd);
+}
+
+void ESP8266::GetList(char * l) {
+    char rs[15];
+    strcpy(rs, "AT+CWLAP");
+    SendCMD(rs);
+    RcvReply(l, 5000); // Needs big timeout because it takes long to start replying
+}
+
+void ESP8266::Join(char * id, char * pwd) {
+    char cmd[255];
+    strcpy(cmd, "AT+CWJAP=");
+    AddChar(cmd, 0x22);
+    strcat(cmd, id);
+    AddChar(cmd, 0x22);
+    AddChar(cmd, 0x2C);
+    AddChar(cmd, 0x22);
+    strcat(cmd, pwd);
+    AddChar(cmd, 0x22);
+    SendCMD(cmd);
+}
+
+void ESP8266::GetIP(char * ip) {
+    char cmd[15];
+    strcpy(cmd, "AT+CIFSR");
+    SendCMD(cmd);
+    RcvReply(ip, 2000);
+}