Adding Buttons to Webserver

Start 

Working LED Button

Parts

All Parts
All Parts
LED Module
Cable
PartQuantity
LED Module 1
Cable 1

Setup 

Take any color LED and insert it into the LED module. The longer leg is positive and should therefore be inserted into the hole labeled "+" on the module. Next, take the cable and plug one side into the LED module and the other into any Digital socket.

Parts needed
Parts needed
Take a wrapper screw
Place in wrapper
Tighten to chassis
Take led module
Place into wrapper
Place into wrapper
Take a cable
Unwrap
Place one end into LED socket
Place into D7 even though D6 is shown here

Upload 

Upload the following code. The example below uses D7 for the LED module.

Download file Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#include "WiFiEsp.h"
#include "SoftwareSerial.h"
#include "Grove_I2C_Motor_Driver.h"

// default I2C address is 0x0f
#define I2C_ADDRESS 0x0f

//Create Serial communication Object
SoftwareSerial Serial1(8, 9); // RX, TX
//Wifi server object
WiFiEspServer server(80);

// use a ring buffer to increase speed and reduce memory allocation
RingBuffer buf(8);

//Wifi settings
char ssid[] = "My WiFi Robot";    // the name of your access point
char pass[] = "password";        // the password for your access point
int status = WL_IDLE_STATUS;     // the Wifi radio's status

// CHANGE THIS TO YOUR OFFSET VALUE
int offset = 3;

// variable for power -> from -100 to 100 (negative numbers are backwards)
int power = 70;

//Increase for larger turns. Decrease for smaller turns
int turnAmount = 180;

// Variable for running the moving code
bool moving = false;

// Variables to time and stop moving
int interval;
unsigned long startTime;

// change these values to match your motor orientation
unsigned char left = MOTOR2;
unsigned char right = MOTOR1;

// Pin for LED module
int ledPin = 7;

void setup()
{
  // Start Serial Communication with computer and WiFi module
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // Initialize LED module as output and turn LED OFF
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  // start motor driver
  Motor.begin(I2C_ADDRESS);
  // correct pwm cycles
  Motor.frequence(F_490Hz);

  // Print out debugging messages
  Serial.print("Attempting to start AP ");
  Serial.println(ssid);

  // start access point
  status = WiFi.beginAP(ssid);

  // start the web server on port 80
  server.begin();
  IPAddress ip = WiFi.localIP();
  Serial.println("Server started");
  Serial.print("To see this page in action, connect to ");
  Serial.print(ssid);
  Serial.print(" and open a browser to http://");
  Serial.println(ip);
  Serial.println();
}

void loop()
{

  // Wait for a device to connect to the WiFi
  WiFiEspClient client = server.available();  // listen for incoming clients

  // if you get a client,
  if (client) {
    // print a message out the serial port
    Serial.println("New client");
    // initialize the circular buffer
    buf.init();

    // loop while the client's connected
    while (client.connected()) {
      // if there's bytes to read from the client,
      if (client.available()) {
        // read a byte, then
        char c = client.read();
        // push it to the ring buffer
        buf.push(c);

        String request = client.readStringUntil('\r');
        client.flush();

        // Match the request
        // if the string "/fwd" is found,
        //then call the moveDistance() function
        if (request.indexOf("/fwd") != -1) {
          //moveDistance(35, power);
          moveTime(2, power);
        }
        // if the string "/bwd" is found,
        //then call the moveDistance function
        if (request.indexOf("/bwd") != -1) {
          //moveDistance(35, -power);
          moveTime(2, -power);
        }
        // if the string "/left" is found,
        //then call the turn() function
        if (request.indexOf("/left") != -1) {
          turn('l');
        }
        // if the string "/right" is found,
        // then call the turn() function
        if (request.indexOf("/right") != -1) {
          turn('r');
        }

        // Set LED value as LOW and check to see if LED is currently ON or OFF
        int value = LOW;
        if (request.indexOf("/LED=ON") != -1) {
          digitalWrite(ledPin, HIGH);
          value = HIGH;
        }
        if (request.indexOf("/LED=OFF") != -1) {
          digitalWrite(ledPin, LOW);
          value = LOW;
        }

        // Return the response
        client.print(
          "HTTP/1.1 200 OK\r\n"
          "Content-Type: text/html\r\n");
        client.println();

         // CSS to style the on/off buttons

          client.print(F(
            "<!DOCTYPE HTML>\r\n"
            "<html>\r\n"
            "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n"
            "<link rel=\"icon\" href=\"data:,\">\r\n"

            // change the font and size of each button here

            "<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\r\n"
            ".button { background-color: #ff6666; border: black; color: black; padding: 16px 40px;\r\n"
            "text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}\r\n"
            ".button:hover {background: #eee;}\r\n"

            // change the background color of each button here

            ".led {background-color: #0077b3;}\r\n"
            ".forward {background-color: #ff6666;}\r\n"
            ".backward {background-color: #aaff80;}\r\n"
            ".left {background-color: #ff9900;}\r\n"
            ".right {background-color: #ffff66;}</style></head>\r\n"

            // change the heading of the web server here

            "<h2>My WiFi Robot Controls</h2>\r\n"));

            // change the function and label of the buttons here

          client.print(F(
            "<button class=\"button forward\" onClick=location.href='/fwd'>forward</button>\r\n"
            "<p><button class=\"button left\" onClick=location.href='/left'>left</button>\r\n"
            "<button class=\"button right\" onClick=location.href='/right'>right</button></p>\r\n"
            "<button class=\"button backward\" onClick=location.href='/bwd'>backward</button>\r\n"));

            // If the LED is already off, display ON button.
            if (value == LOW) {
              client.print(F("<p><button class=\"button led\" onClick=location.href='/LED=ON'>Turn LED ON</button><p>\r\n"));
            }
            // else, display OFF button
            else {
              client.print(F("<p><button class=\"button led\" onClick=location.href='/LED=OFF'>Turn LED OFF</button><p>\r\n"));
            }

          client.println("</body></html>");
          break;
      }

      //Run if moving
      if (moving) {
        //Checks the interval timing
        if (millis() - startTime > interval) {
          //Stop the motors
          Motor.stop(left);
          Motor.stop(right);
          //Change moving variable
          moving = false;
        }
      }
    }

    // close the connection
    client.stop();
    Serial.println("Client disconnected");
  }

  //Run if moving
  if (moving) {
    //Checks the interval timing
    if (millis() - startTime > interval) {
      //Stop the motors
      Motor.stop(left);
      Motor.stop(right);
      //Change moving variable
      moving = false;
    }
  }
}


// function to move robot forward or backward
void moveTime(int seconds, int motorPower) {
  //Set the starting time
  startTime = millis();
  //Set this true to run the move code
  moving = true;
  //Set the time to run
  interval = seconds * 1000;

  //Set correct motor polarity
  int leftPower = motorPower;
  int rightPower = - motorPower;

  //Set motor speed
  Motor.speed(left, leftPower - offset);
  Motor.speed(right, rightPower - offset);
}


// function to turn robot left or right
void turn(char Dir) {
  //Set this true to run the move code
  moving = true;
  //Set the time to run
  interval = turnAmount;

  //Switch case for the two directions
  switch (Dir) {
    // if the direction (Dir) is left, turn on the right motor
    case 'l':
      Motor.speed(right, - power - offset);
      break;

    // if the direction is right, turn on the left motor
    case 'r':
      Motor.speed(left, power - offset);
      break;
  }
}

Observe

Connect to the web server. You should now see a blue button. Your LED should turn ON and OFF when you click the button. If it doesn't, try a different LED. Also make sure your code matches the Digital pin your LED module is connected to. If your LED is dim you can use a screw driver to adjust the potentiometer on the module to adjust its resistance and dim or brighten the LED.

Experiment

Add more buttons! Now that you know how to add new buttons as well as change their font, color, and function the possibilities are endless!

Some additional projects to try:

  • Add the LCD to your robot to display different messages with various buttons.
  • Add the sound module to have your robot sing a song at the click of a button.
  • Use the LCD and weather station sensors to display real time updates of room temperatures, pressures, and humidities.