13. Networking and communications¶
Instruction¶
individual assignment:
- design, build, and connect wired or wireless node(s)with network or bus addresses → Here
group assignment:
- send a message between two projects → In this page
What I did in this week¶
- Test board by serial connection → in this page
-
Running servo motors from my smartphone (between 2 projects) → in this page¶
Preparation¶
additional boards manager URLs:
https://dl.espressif.com/dl/package_esp32_index.json
Install board manager
ESP32
The board I used¶
Note : When Programmingm, connect IO0 to GND in order to short circuit
Test board by serial connection¶
Wiring¶
Short-circuit to write for board
Code¶
void setup()
{
Serial.begin(9600); // The connection speed
}
void loop()
{
Serial.println("Hello, World"); // output "Hello, World"
delay(1000); // wait for 1 second
}
Arduino Setting¶
After writing is completed, remove the short-circuit between IO0 and GND to start serial communication
Note:
Select Bootloader ModeGPIO0
The ESP32 will enter the serial bootloader when GPIO0 is held low on reset. Otherwise it will run the program in flash.
GIO0 Input | mode |
---|---|
Low/GND | ROM serial bootloader for esptool |
High/VCC | Normal execution mode |
GIO0 Input | mode |
---|---|
Low/GND | ROM serial bootloader for esptool |
High/VCC | Normal execution mode |
GPIO0 has an internal pullup resistor, so if it is left unconnected then it will pull high.
CheckSerial monitor¶
Displayed “Hello, World” → success
Running servo motors from my smartphone¶
Inspired by : Switch bot
Wiring¶
connect the servo motor to the board
Conneciton
Code¶
//Put the & at the end of the URL parameter when you access it!
#include <WiFi.h>
// Rewrite it to the Wi-Fi you use and its password
const char* ssid = "fablabkannai";
const char* password = "XXXXXXXXXXX";
// using port 80
WiFiServer server(80);
// Variable to store HTTP requests
String header;
// Variables used to set values
String valueString = String(5);
String delay_valueString = String(500);
int pos1 = 0;
int pos2 = 0;
//pin
const int servo_pin = 16;
//Servo motor rotation angle
const int servo_left = 26;
const int servo_center = 75;
const int servo_right = 123;
void setup() {
pinMode(4, OUTPUT);
//ledc setting
ledcSetup(0, 50, 10); // 0ch 50 Hz 10bit resolution
ledcAttachPin(servo_pin, 0); // 15pin, 0ch
//Start of serial communication
Serial.begin(115200);
//Flashing flashlight at startup
for(int i=0; i<5; i=i+1) {
digitalWrite(4, HIGH);
delay(50);
digitalWrite(4, LOW);
delay(50);
}
// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Show local IP (access this IP from your phone, etc.)
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" http-equiv=\"content-type\" charset=\"utf-8\"><title>ESP32 servo controller</title>");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>.block{display: inline-block; vertical-align: middle; height: 50px; font-size: 0;}");
client.println(".btn-square-shadow {display: inline-block; width: 300px; height: 50px; text-decoration: none; background: #668ad8; color: #FFF; border-bottom: solid 4px #627295; border-radius: 3px; font-size: 30px;}");
client.println(".btn-square-shadow:active {-webkit-transform: translateY(4px); transform: translateY(4px); box-shadow: 0px 0px 1px rgba(0, 0, 0, 0.2); border-bottom: none;}");
client.println("</style>");
client.println("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");
// Web Page
client.println("</head><body style='text-align: center;'><h1>ESP32 サーボモーター コントロールパネル</h1>");
//servo slide bar <--------------------------------------------------------------------------------------------------------------------------------------------------------------------ESP32's IP address. To find open serial monitor with 115200bps
client.println("<div class='left block'> <a href='http://192.168.1.173/?angle=50&delay=500&'><button id='entrance_button' class='btn-square-shadow' type='button'>Turn on Fan</button></a></div>");
client.println("<div class='right block'><a href='http://192.168.1.173/?angle=100&delay=500&'><button id='room_button' class='btn-square-shadow' type='button'>Turn on Light</button></a></div>");
client.println("</body></html>");
//Processing part of HTTP request
delay_valueString = "500";
pos1 = header.indexOf('=',18);
pos2 = header.indexOf('&',18);
if(pos1!=-1 && pos2!=-1) {
delay_valueString = header.substring(pos1+1, pos2);
Serial.print("pos:");
Serial.println(pos1);
Serial.println(pos2);
} else {
Serial.print("default servo standby time:");
Serial.println(delay_valueString.toInt());
}
Serial.print("Servo standby time:");
Serial.println(delay_valueString.toInt());
pos1 = header.indexOf('=');
pos2 = header.indexOf('&');
valueString = header.substring(pos1+1, pos2);
Serial.print("URL parameter:");
Serial.println(valueString);
if(valueString.toInt()>=26 && valueString.toInt()<=123) {
//Rotate servo motor
digitalWrite(4, HIGH);
delay(50);
digitalWrite(4, LOW);
ledcWrite(0, servo_center);
delay(delay_valueString.toInt());
ledcWrite(0, valueString.toInt());
delay(delay_valueString.toInt());
ledcWrite(0, servo_center);
// バグ防止
delay(delay_valueString.toInt());
ledcWrite(0, 0);
digitalWrite(4, HIGH);
delay(50);
digitalWrite(4, LOW);
} else {
Serial.println("URLパラメーター エラー!");
}
// End of HTTP Response
client.println();
// Break out of the while loop
break;
} else {
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
}
}
// Clear the header variable
header = "";
// Disconnect
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Howrver Error is occured. Error messege is below
Arduino: 1.8.19 (Mac OS X), Board: "ESP32 Wrover Module, Huge APP (3MB No OTA/1MB SPIFFS), QIO, 80MHz, 921600, None"
Sketch uses 718866 bytes (22%) of program storage space. Maximum is 3145728 bytes.
Global variables use 38504 bytes (11%) of dynamic memory, leaving 289176 bytes for local variables. Maximum is 327680 bytes.
esptool.py v3.0-dev
Traceback (most recent call last):
File "esptool.py", line 3969, in <module>
File "esptool.py", line 3962, in _main
File "esptool.py", line 3551, in main
File "esptool.py", line 271, in __init__
Serial port /dev/cu.usbmodem101
File "serial/__init__.py", line 88, in serial_for_url
File "serial/serialposix.py", line 268, in open
serial.serialutil.SerialException: [Errno 2] could not open port /dev/cu.usbmodem101: [Errno 2] No such file or directory: '/dev/cu.usbmodem101'
Failed to execute script esptool
An error occurred while uploading the sketch
processing.app.SerialException: Error opening serial port '/dev/cu.usbmodem101'.
at processing.app.Serial.<init>(Serial.java:152)
at processing.app.Serial.<init>(Serial.java:82)
at processing.app.SerialMonitor$2.<init>(SerialMonitor.java:132)
at processing.app.SerialMonitor.open(SerialMonitor.java:132)
at processing.app.AbstractMonitor.resume(AbstractMonitor.java:132)
at processing.app.Editor.resumeOrCloseSerialMonitor(Editor.java:2126)
at processing.app.Editor.access$1300(Editor.java:116)
at processing.app.Editor$UploadHandler.run(Editor.java:2095)
at java.lang.Thread.run(Thread.java:748)
Caused by: jssc.SerialPortException: Port name - /dev/cu.usbmodem101; Method name - openPort(); Exception type - Port not found.
at jssc.SerialPort.openPort(SerialPort.java:167)
at processing.app.Serial.<init>(Serial.java:141)
... 8 more
Error opening serial port '/dev/cu.usbmodem101'.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Unplug and retry servo motors → success!
open the serial monitor
get the local adress
http://192.168.1.173/
Write the right local address in the sketch.
However, error occured
Arduino: 1.8.19 (Mac OS X), Board: "ESP32 Wrover Module, Huge APP (3MB No OTA/1MB SPIFFS), QIO, 80MHz, 921600, None"
Sketch uses 718866 bytes (22%) of program storage space. Maximum is 3145728 bytes.
Global variables use 38504 bytes (11%) of dynamic memory, leaving 289176 bytes for local variables. Maximum is 327680 bytes.
esptool.py v3.0-dev
Serial port /dev/cu.usbmodem1101
Connecting........_____....._____....._____....._____....._____....._____.....____An error occurred while uploading the sketch
_
A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Replace new connector connecting IO0 and GND and retry
→ success
Open in browser¶
http://192.168.1.173/?angle=50&delay=500&
informationtworking¶
Connect the servo motor to the fan in order to control switching of the fan¶
Attach to fan and switch on/off
Yey!