You are on page 1of 64

ĐỀ CƯƠNG

Số giờ (1 tiết = 50 phút)

Thứ tự Nội dung Lý Thảo Bài Thí Thực Tự


chương mục thuyết luận tập nghiệm hành học

Chương 1 Ôn tập kiến thức cơ bản 2 0

1.1 Lập trình C cơ bản 0.5

1.2 Hệ thống số 0.5

Chương 2 Giới thiệu Arduino WeMos D1 1 0

2.1 Tổng quan về Arduino WeMos D1

2.2 Cấu trúc và hoạt động của Arduino


WeMos D1

2.3 Đặc tính kỹ thuật của Arduino WeMos


D1

Chương 3 Lập trình cho Arduino WeMos D1 2 4

3.1. Một số phần mềm thông dụng

3.2. Tổ chức chương trình phần mềm

3.3. Tập lệnh Arduino WeMos D1

Chương 4 Giao tiếp và điều khiển thiết bị qua 7 22


Internet với Arduino WeMos D1

4.1. Giao tiếp LED đơn 1 2

4.2. Giao tiếp cảm biến hồng ngoại. 1 4

4.3. Giao tiếp cảm biến nhiệt độ. 2 4

4.4. Giao tiếp động cơ 2 4

Chương 5 Xây dựng hệ thống IoT 1 6

Cộng 12 0 0 0 24 60

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 1


Chương 1: ÔN TẬP KIẾN THỨC CƠ BẢN
1.1. Lập trình C cơ bản.
Giáo viên hướng dẫn
1.1.1. BIẾN, HẰNG, MẢNG TRONG C
Các kiểu biến dữ liệu :

Khai báo biến: Kiểu biến Tên biến;


VÍ DỤ: unsigned char x;
Ta cũng có thể gán luôn giá trị ban đầu cho biến: unsigned char x=0;
Hoặc ta cũng có thể khai báo nhiêu biến một lúc: unsigned char x,y,z;
Ngoài ra dùng cho vi điều khiển trình biên dich chuyên dụng còn hỗ trợ các biến sau:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 2


Biến có 2 loại: cục bộ và toàn cục
1. Hằng
const type NAME=giá trị;

#define tênhằngsố giá trị;


Ví dụ:
const float Pi=3.14;
#define Pi 3.14;
2. Mảng
Kiểudữliệu Tênmảng[số phần tử mảng];
Ví dụ:
unsigned char ma_bcd[10] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
// ma led 7seg 0 1 2 3 4 5 6 7 8 9
3. Con trỏ
Kiểudữliệu *têncontro;
Ví dụ: int *pt,*x;
4. Chuỗi
char tenchuoi [chiều dài thực +1];
char tenchuoi [ ];

I. CÁC TOÁN TỬ
STT TOÁN TỬ Ý NGHĨA
1 = Toán tử gán
2 + cộ ng
3 - trừ
4 * nhân
5 / chia
6 % lấy phần dư (trong phép chia)
7 & AND Logical AND
8 | OR Logical OR

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 3


9 ^ XOR Logical exclusive OR
10 ~ NOT Đảo ng ược bit
11 << SHL Dịch bit sang trái
12 >> SHR Dịch bit sang phải
13 ++ -- Tăng và giảm
14 ( ==, !=, >, <, >=, <= ) Các toán tử quan hệ
- Các toán tử gán phức hợ p (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

- Các toán tử logic ( !, &&, || ).

! NOT
&& AND
|| OR

Ví dụ:

!(5 == 5) trả về false vì bi ể u th ứ c bên phả i (5 == 5) có giá tr ị true.

!(6 <= 4) trả về true vì (6 <= 4)có giá tr ị false.

!true trả về false.

!false trả về true.

1.1.2. CẤU TRÚC TRONG C

1.Các ký hiệu trong chương trình C

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 4


2. Các ký hiệu lưu đồ

3. Cấu trúc tuần tự

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 5


4. Cấu trúc rẽ nhánh
a. If

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 6


b. If...else

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 7


c. Switch ... case

5. Cấu trúc lặp

a. for

b. while

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 8


1.1.3. HÀM

1. Hàm có giá trị trả về, có biến truyền vào


Cấu trúc: <Kiểu giá trị trả về> <Tên hàm (Biến truyền vào hàm)>
{ // Khai báo các biến cục bộ
// Các lệnh xử lý
return kq;
}

VD : unsigned char Cong(unsigned char x, unsigned char y)


{ // Khai báo các biến cục bộ
// Các lệnh xử lý
return kq;
}
2. Hàm không có giá trị trả về, có biến truyền vào
Cấu trúc: void <Tên hàm (Biến truyền vào hàm)>
{ // Khai báo các biến cục bộ
// Các lệnh xử lý
}

VD: void Cong(unsigned char x, unsigned char y)


{ // Khai báo các biến cục bộ
// Các lệnh xử lý
}

3. Hàm có giá trị trả về, không có biến truyền vào


VD:
unsigned char Tênhàm(void)
{ // Khai báo các biến cục bộ
// Các lệnh xử lý
return kq;
}

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 9


4. Hàm không có giá trị trả về, không có biến truyền vào
void main(void)
{// Khai báo các biến cục bộ
// Các lệnh xử lý
}
hoặc void main()

1.2. Hệ thống số.


Giáo viên hướng dẫn

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 10


Chương 2: GIỚI THIỆU ARDUINO WEMOS D1

2.1. Tổng quan về Arduino WeMos D1

– Kit Arduino Wifi ESP8266 WeMos D1 R2 là phiên bản mới nhất từ WeMos, kit được
thiết kế với hình dáng tương tự Arduino Uno nhưng trung tâm lại là module wifi Soc
ESP8266 được build lại firmware để có thể chạy với chương trình Arduino.

– Kit Arduino Wifi ESP8266 WeMos D1 R2 thích hợp và dễ dàng thực hiện các ứng
dụng thu thập dữ liệu và điều khiển qua Wifi.

2.2. Cấu trúc và hoạt động của Arduino WeMos D1

Có 2 loại board trên thị trường tương ứng với thứ tự chân theo bảng dưới:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 11


This is what an actual WeMos D1 board looks like:

This is what my Knockoff WeMos D1 board looks like:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 12


Arduino
Official WeMos Knockoff WeMos 11- Digital
Software
D1 Board Label D1 Board Label Pin
ESP8266 (GPIO)

RX RX<-D0 D0 3

TX TX->D1 D1 1

D0 D2 D2 16

SCL/D1 D15/SCL/D3 D3 5

SDA/D2 D14/SDA/D4 D4 4

D3 D8 D5 0=GPIO0

D4 TX1/D9 D6 2

D5 D13/SCK/D5 D7 14

D6 D12/MISO/D6 D8 12

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 13


Arduino
Official WeMos Knockoff WeMos 11- Digital
Software
D1 Board Label D1 Board Label Pin
ESP8266 (GPIO)

D7 D11/MOSI/D7 D9 13

SS/D8 D10/SS D10 15

A0 A0 A0 A0

Official WeMos D1 Board Label :

Chân của ESP8266 cũng là chân của phần mềm lập trình

ĐỂ CHÍNH XÁC TA CÓ THỂ XEM KÝ HIỆU CHÂN Ở MẶT DƯỚI VÀ MẶT


TRÊN CỦA KÍT ĐỂ ĐỐI CHIẾU.

Khi viết code nếu muốn xuất tín hiệu HIGH cho pin số D8 trên kit thì không thể
viết "digiatlWrite(8,HIGH);" mà phải viết là "digitalWrite(0,HIGH);" (Theo trên bảng
thì chân D8 trên kit là chân 0 của ESP). Hay nói cách khác là ta điều khiển chân trên
ESP8266. Và khi ta code xuất chân D3 mức HIGH thì chân D15 cũng được xuất HIGH,
lí do là vì: các chân từ D11=>D15 là các chân "giả" để kit trông giống arduino hơn (ESP
chỉ có 11 pin digital), vì vậy các pin D11=>D15 được nối lần lượt với D7=>D3.

Ví dụ: Led nhấp nháy


/* HCDVBD0027 Blink example - HobbyComponents.com */
#include <ESP8266WiFi.h>
#define PIN 16 // Flash the LED connected to GPIO16=D2
GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 14
void setup()
{
pinMode(PIN, OUTPUT); // Set the pin to an output
}
void loop()
{
digitalWrite(PIN, LOW); // Turn the LED on
delay(1000); // Wait for a second
digitalWrite(PIN, HIGH); // Turn the LED off
delay(1000); // Wait for another second
}
2.3. Đặc tính kỹ thuật của Arduino WeMos D1

Thông số kỹ thuật

 IC wifi ESP-8266EX
 Điện áp hoạt động: 3.3V
 Số chân I/O Digital: 11
 Số chân Analog: 1 chân (Max input: 3.2V)
 Xung clock: 80MHz/160MHz
 Bộ nhớ Flash: 4 MB
Warnings: All IO is work at 3.3V.

*All IO have interrupt/pwm/I2C/one-wire supported(except D0)

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 15


CHƯƠNG 3: LẬP TRÌNH CHO ARDUINO WEMOS D1
3.1. Một số phần mềm thông dụng

Các thiết bị dựa trên nền tảng Arduino được lập trình bằng ngôn riêng. Ngôn ngữ này
dựa trên ngôn ngữ Wiring được viết cho phần cứng nói chung. Và Wiring lại là một biến
thể của C/C++. Môi trường lập trình Arduino được gọi là Arduino IDE
(Intergrated Development Environment).

Hoặc phần mềm mBlock

Programming: Arduino IDE

WeMos D1 R2 WiFi ESP8266 Development Board Compatible Arduino UNO


Program By Arduino IDE:

Installing the WeMos-D1R2 Board Via the Board Manager:

The D1 R2 has a micro USB for auto programming:


Cài thêm “CH340 USB”

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 16


Vào File→ Preferences, vào textbox Additional Board Manager URLs thêm đường
link sau vào

http://arduino.esp8266.com/stable/package_esp8266com_index.json

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 17


Click OK để chấp nhận.

Tiếp theo vào Tool→Board→Boards Manager

Đợi một lát để chương trình tìm kiếm. Ta kéo xuống và click vào ESP8266 by ESP8266
Community, click vào Install. Chờ phần mềm tự động download và cài đặt.

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 18


Chọn Board để lập trình cho ESP8266:

Selecting the WeMos-D1R2 Board:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 19


Tools -> Upload Speed: 115200

3.2. Tổ chức chương trình phần mềm

//Gọi thư viện cần sử dụng


#include <ESP8266WiFi.h>
// Các định nghĩa, khai báo hằng, biến toàn cục,...
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
int buttonState = 0; // variable for reading the pushbutton status
//Các khai báo cài đặt, hàm này chỉ chạy một lần khi mới khởi động
void setup() {
// put your setup code here, to run once:
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
// Chương trình chính
void loop() {
// put your main code here, to run repeatedly:
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 20


// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
3.3. Tập lệnh Arduino WeMos D1

Giống tập lệnh của Arduino UNO.(Xem trang arduino.cc hoặc arduino.vn)

Cấu trúc Giá trị Hàm và thủ tục

 setup() Hằng số Nhập xuất Digital (Digital I/O)


 loop()  HIGH | LOW  pinMode()
Cấu trúc điều khiển   digitalWrite()
INPUT | INPUT_PULLUP | OUTPUT
 if  LED_BUILTIN  digitalRead()
 if...else  true | false Nhập xuất Analog (Analog I/O)
 switch / case  Hằng số nguyên (integer constants)  analogReference()
 for   analogRead()
Hằng số thực (floating point constants)
 while Kiểu dữ liệu  analogWrite() - PWM - PPM
 break  void Hàm thời gian
 continue  boolean  millis()
 return  char  micros()
 goto  unsigned char  delay()
Cú pháp mở rộng  byte  delayMicroseconds()
 ; (dấu chấm phẩy)  int Hàm toán học
 {} (dấu ngoặc nhọn)  unsigned int  min()
 // (single line comment)  word  max()
 /* */ (multi-line comment)  long  abs()
 #define  unsigned long  map()
 #include  short  pow()
Toán tử số học  float  sqrt()
 = (phép gán)  double  sq()
 + (phép cộng)  array  isnan()
 - (phép trừ)  string (chuỗi kí tự biểu diễn  constrain()

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 21


 * (phép nhân) bằng array) Hàm lượng giác
 / (phép chia)  String (object)  cos()
 % (phép chia lấy dư) Chuyển đổi kiểu dữ liệu  sin()
Toán tử so sánh  char()  tan()
 == (so sánh bằng)  byte() Sinh số ngẫu nhiên
 != (khác bằng)  int()  randomSeed()
 > (lớn hơn)  word()  random()
 < (bé hơn)  long() Nhập xuất nâng cao (Advanced I/O)
 >= (lớn hơn hoặc bằng)  float()  tone()
 <= (bé hơn hoặc bằng) Phạm vi của biến và phân loại noTone()
Toán tử logic  Phạm vi hiệu lực của biến  shiftOut()
 && (và)  static - biến tĩnh  shiftIn()
 || (hoặc)  const - biến hằng  pulseIn()
 ! (phủ định)  volatile Bits và Bytes
 ^ (loại trừ) Hàm hỗ trợ  lowByte()
Phép toán hợp nhất  sizeof()  highByte()
 ++ (cộng thêm 1 đơn vị) Giao tiếp  bitRead()
 -- (trừ đi 1 đơn vị)  Serial  bitWrite()
 += (phép rút gọn của phép  bitSet()
cộng)  bitClear()
 -= (phép rút gọn của phép trừ)  bit()
 *= (phép rút gọn của phép Ngắt (interrupt)
nhân)  attachInterrupt()
 /= (phép rút gọn của phép  detachInterrupt()
chia)  interrupts()
 noInterrupts()

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 22


Chương 4: GIAO TIẾP VÀ ĐIỀU KHIỂN THIẾT BỊ
QUA INTERNET VỚI ARDUINO WEMOS D1
4.1. Giao tiếp LED đơn

Mô hình hệ thống IoT đơn giản

Theo như mô hình trên:

 Socket Server nằm ở tầng cao nhất gọi là tầng Server.(nội bộ có thể là
modem=192.168.1.1)
 ESP8266 và Trình duyệt Web nằm ở tầng thứ 2 gọi là tầng Client
 Arduino ở tầng thứ 3 gọi là Application.
 Mỗi tầng chỉ có thể liên lạc với tầng kế tiếp hoặc bên dưới nó.

Như vậy, chỉ cần xây dựng các phần mô hình giao tiếp ổn định giữa các tầng là chúng ta
đã có ngay mô hình IoT đơn giản.

Để giao tiếp giữa tầng 1 và tầng 2, chúng ta sử dụng kết nối Internet thông qua các gói
dữ liệu được đóng gói theo chuẩn JSON.

JSON là một kiểu dữ liệu đặc biệt, nó sẽ giúp ta đóng gói tập hợp các dữ liệu thành một
chuỗi đơn giản theo quy chuẩn nhất định. Chuỗi này sẽ dễ dàng được vận chuyển thông
qua môi trường Internet.

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 23


Chúng ta không cần lo lắng đến cách làm thế nào để truyền các tham số vào một chuỗi
JSON vì đã có thư viện ArduinoJSON chúng ta làm việc đó (ở ESP8266) và thư viện
JSON (ở Socket Server là trình duyệt Web).

JSON là kiểu dữ liệu chuẩn, dễ encode và decode nhất, hầu hết các thiết bị và nền tảng
lập trình đều hỗ trợ kiểu dữ liệu này.

Để giao tiếp giữa tầng 2 và tầng 3, chúng ta sử dụng cổng Serial truyền thống mà các
bạn đã có thể làm quen thông qua việc làm xe điều khiển từ xa thông qua bluetooth. Nói
chung Serial cũng đã là một giao tiếp chuẩn và tất cả các mạch ESP8266 và Arduino đều
hỗ trợ ít nhất một cổng Serial trong hệ thống IO của mình.

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 24


A. Chạy ví dụ SimpleWebServer Sketch:

#include <ESP8266WiFi.h>
const char* ssid = "Thien Linh";
const char* password = "987654321";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
void setup() {
//Bật baudrate ở mức 115200 để giao tiếp với máy tính qua Serial
Serial.begin(115200);
delay(10);
Serial.println();

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 25


Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
//Việc đầu tiên cần làm là kết nối vào mạng Wifi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
//Kiểm tra xem trạng thái đã kết nối chưa nếu chưa thì in ra dấu ...
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//Thông báo trạng thái đã kết nối
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
void loop() {
}

Giải thích chương trình:

- Includes the ESP8266 library ESP8266WiFi.h.


- Creates the instance "server" of the class "WiFiServer" listening on port 80. Notice
"server" is a global instance.
- Set the mode of our ESP8266 to be an Access Point (AP).
- Provide the SSID and password. The password / passphrase has to be at least 8
characters long.
- Fire-up our server by calling the begin() method.
- Start communication between the ESP8266-12E and the monitor window
- Obtain the IP of the Server
- Print the IP to the monitor window
Kiểm tra kết nối wifi:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 26


Xem WeMos D1 đã gửi tín hiệu tới server chưa, nếu có thì nó sẽ nhận được một IP phản
hồi: >>Serial Monitor Tools | Serial Monitor

Tools -> Upload Speed: 115200

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 27


Chép code sau vào loop(): WeMos D1 = server , máy tính = client
WiFiClient client = server.available();
if (!client) { //Ket noi den server chưa
return; //nếu chưa Ket noi thì quay lại
}
//nếu Ket noi thì gửi thông điệp lên server
client.print(“Hello IoT Class”);
Serial.println("Somebody has connected :)");

Giải thích chương trình:

- Nếu WeMos D1 được kết nối với server thì gửi từ WeMos D1 lên server một tin nhắn
:" Hello IoT Class"

- Open a browser window and enter http://192.168.1.49 and hit enter

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 28


- Observe your Monitor window to check for a connection.

Chúng ta sẽ bật/tắt một Led trên chân GPIO16 thông qua một trình duyệt web.

1. Firstly initialize the digital port GPIO16 as an output port and keep the initial state of
the LED ON.
2. At the bottom of setup() function add the following lines of code:

// prepare GPIO2
pinMode(2, OUTPUT);
digitalWrite(2, 0);
At the bottom of loop() function add the following lines of code:

//Read what the browser has sent into a String class and print the request to the monitor
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush(); //xóa các giá trị của biến client class

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 29


// Match the request: so khớp giá trị nhận được để thực thi nhiệm vụ
int val;
if (req.indexOf("/gpio/0") != -1)
val = 0;
else if (req.indexOf("/gpio/1") != -1)
val = 1;
else {
Serial.println("invalid request");
client.stop();//dừng biến client
return;
}
// Set GPIO2 according to the request
digitalWrite(2, val);
client.flush();
// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE
HTML>\r\n<html>\r\nGPIO is now ";
s += (val)?"high":"low"; // val=1 thì chuỗi s+=high ngược lại =low
s += "</html>\n";
// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");
// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
In the address bar of your browse type the following URL:
http://192.168.4.1/ gpio/1
The LED on the Wemos D1 will turn ON.

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 30


Then type the following URL:
http://192.168.4.1/ gpio/0
The LED on the Wemos D1 will turn OFF.

hoặc điều khiển nhiều LED:

// Match the request


int val;
if (req.indexOf("/gpio/0") != -1)
{val = 0; digitalWrite(2, 0);} //Led 1 sáng
if (req.indexOf("/gpio/1") != -1)
{ val = 1;digitalWrite(2, 1);} //Led 1 tắt
if (req.indexOf("/gpio/2") != -1)
{val = 2; digitalWrite(4, 0);} //Led 2 sáng
if (req.indexOf("/gpio/3") != -1)
{val = 3;digitalWrite(4, 1);} //Led 2 tắt
if (req.indexOf("/gpio/4") != -1)
{val = 4; digitalWrite(2, 0);} //Led 1 sáng

Copy this code and add it at the bottom of the Loop() function:

String s = "HTTP/1.1 200 OK\r\n";


s += "Content-Type: text/html\r\n\r\n";
s += "<!DOCTYPE HTML>\r\n<html>\r\n";

s += "<br>GPIO is now ";


s += (val)?"high":"low";
s += "</html>\n";

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 31


s += "<br><br><br><input type=\"button\" name=\"b1\" value=\"Turn LED ON\"
onclick=\"location.href='/ON'\">"; //bật
s += "<br><br><br>";
s += "<input type=\"button\" name=\"bi\" value=\"Turn LED OFF\"
onclick=\"location.href='/OFF'\">";//tắt
s += "</html>\n";

// Send the response to the client


client.flush(); //clear previous info in the stream
client.print(s);
delay(1);
Serial.println("Client disonnected");

// The client will actually be disconnected


// when the function returns and 'client' object is detroyed

Giải thích chương trình:

- Tạo đoạn code .html trên WeMos D1 và gửi đoạn code này đến Web server.
- Mục đích là tạo ra 2 nút Button trên web để điều khiển Led, 2 Button này có chức
năng kích hoạt (onclick) và gửi phản hồi về WeMos D1 dưới dạng chuỗi ký tự: “ON” ,
“OFF”.
- WeMos D1 nhận được chuỗi ký tự phản hồi sẽ thực hiện công việc tương ứng như
đoạn code đã nêu ở trên phần B là:

// Read the first line of the request


String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();

// Match the request


int val;
if (req.indexOf("/ON") != -1)
val = 0;
else if (req.indexOf("/OFF") != -1)
val = 1;
else {
Serial.println("invalid request");
client.stop();
return;
}

// Set GPIO2 according to the request


GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 32
digitalWrite(2, val);

Code đầy đủ:

Ví dụ 1:

/*
* This sketch demonstrates how to set up a simple HTTP-like server.
* The server will set a GPIO pin depending on the request
* http://server_ip/0 will set the GPIO2 low,
* http://server_ip/1 will set the GPIO2 high
* server_ip is the IP address of the ESP8266 module, will be
* printed to Serial when the module is connected.
*/

#include <ESP8266WiFi.h>

const char* ssid = "Thien Linh";


const char* password = "987654321";

// Create an instance of the server


// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);

// prepare GPIO2
pinMode(2, OUTPUT);
digitalWrite(2, 0);

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 33


// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server


server.begin();
Serial.println("Server started");

// Print the IP address


Serial.println(WiFi.localIP());
}

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data


Serial.println("new client");
while(!client.available()){
delay(1);
}

// Read the first line of the request


String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 34


// Match the request
int val;
if (req.indexOf("/OFF") != -1)
val = 0;
else if (req.indexOf("/ON") != -1)
val = 1;
else {
Serial.println("invalid request");
client.stop();
return;
}

// Set GPIO2 according to the request


digitalWrite(2, val);

client.flush();//clear previous info in the stream

// Prepare the response

String s = "HTTP/1.1 200 OK\r\n";


s += "Content-Type: text/html\r\n\r\n";
s += "<!DOCTYPE HTML>\r\n<html>\r\n";

s += "<br>GPIO is now ";


s += (val)?"high":"low";
s += "</html>\n";

s += "<br><br><br><input type=\"button\" name=\"b1\" value=\"Turn LED ON\"


onclick=\"location.href='/ON'\">"; //bật
s += "<br><br><br>";
s += "<input type=\"button\" name=\"bi\" value=\"Turn LED OFF\"
onclick=\"location.href='/OFF'\">";// tắt
s += "</html>\n";

// Send the response to the client


client.flush(); //clear previous info in the stream
client.print(s);
delay(1);
Serial.println("Client disonnected");

// The client will actually be disconnected


// when the function returns and 'client' object is detroyed

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 35


}

>>Compile and load.

Ví dụ 2: nhiệm vụ như ví dụ trên

/* WiFi Web Server LED Blink

A simple web server that lets you blink an LED via the web.

This sketch will print the IP address of your WiFi Shield (once connected)

to the Serial monitor. From there, you can open that address in a web browser

to turn on and off the LED on pin 9.

If the IP address of your shield is yourAddress:

http://yourAddress/H turns the LED on

http://yourAddress/L turns it off


GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 36
This example is written for a network using WPA encryption. For

WEP or WPA, change the Wifi.begin() call accordingly.

Circuit:

* WiFi shield attached

* LED attached to pin 9

created 25 Nov 2012

by Tom Igoe

*/

#include <SPI.h>

#include <WiFi.h>

char ssid[] = "yourNetwork"; // your network SSID (name)

char pass[] = "secretPassword"; // your network password

int keyIndex = 0; // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;

WiFiServer server(80);

void setup() {

Serial.begin(9600); // initialize serial communication

pinMode(9, OUTPUT); // set the LED pin mode

// check for the presence of the shield:

if (WiFi.status() == WL_NO_SHIELD) {

Serial.println("WiFi shield not present");

while (true); // don't continue

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 37


String fv = WiFi.firmwareVersion();

if (fv != "1.1.0") {

Serial.println("Please upgrade the firmware");

// attempt to connect to Wifi network:

while (status != WL_CONNECTED) {

Serial.print("Attempting to connect to Network named: ");

Serial.println(ssid); // print the network name (SSID);

// Connect to WPA/WPA2 network. Change this line if using open or WEP network:

status = WiFi.begin(ssid, pass);

// wait 10 seconds for connection:

delay(10000);

server.begin(); // start the web server on port 80

printWifiStatus(); // you're connected now, so print out the status

void loop() {

WiFiClient client = server.available(); // listen for incoming clients

if (client) { // if you get a client,

Serial.println("new client"); // print a message out the serial port

String currentLine = ""; // make a String to hold incoming data from the
client

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 38


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

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();

// the content of the HTTP response follows the header:

client.print("Click <a href=\"/H\">here</a> turn the LED on pin 9 on<br>");

client.print("Click <a href=\"/L\">here</a> turn the LED on pin 9 off<br>");

// The HTTP response ends with another blank line:

client.println();

// break out of the while loop:

break;

} else { // if you got a newline, then clear currentLine:

currentLine = "";

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 39


}

} else if (c != '\r') { // if you got anything else but a carriage return character,

currentLine += c; // add it to the end of the currentLine

// Check to see if the client request was "GET /H" or "GET /L":

if (currentLine.endsWith("GET /H")) {

digitalWrite(9, HIGH); // GET /H turns the LED on

if (currentLine.endsWith("GET /L")) {

digitalWrite(9, LOW); // GET /L turns the LED off

// close the connection:

client.stop();

Serial.println("client disonnected");

void printWifiStatus() {

// print the SSID of the network you're attached to:

Serial.print("SSID: ");

Serial.println(WiFi.SSID());

// print your WiFi shield's IP address:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 40


IPAddress ip = WiFi.localIP();

Serial.print("IP Address: ");

Serial.println(ip);

// print the received signal strength:

long rssi = WiFi.RSSI();

Serial.print("signal strength (RSSI):");

Serial.print(rssi);

Serial.println(" dBm");

// print where to go in a browser:

Serial.print("To see this page in action, open a browser to http://");

Serial.println(ip);

https://www.blynk.cc/getting-started/

https://www.instructables.com/id/Blink-a-LED-With-Blynk-App-Wemos-D1-Mini-Pro/

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 41


Bước 1: Cài app Blynk cho điện thoại.

- Create a Blynk Account.


- Using a real email address because it will simplify things later.

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 42


Bước 2: cài đặt Blynk library cho phần mềm Arduino IDE.
https://github.com/blynkkk/blynk-library/releases/tag/v0.5.3

 Blynk_Release_v0.5.3.zip

☝Blynk library should be installed manually. Follow the instructions:


1. Unzip the Blynk_Release_vXX.zip archive. You will notice that archive
contains several folders and several libraries.
2. Copy all of these libraries to your sketchbook folder of Arduino IDE.
To find the location of your sketchbook folder, go to top menu in Arduino IDE:
Windows: File → Preferences
Mac OS: Arduino → Preferences
☝Note that
 libraries should go to libraries
 tools should go to tools
Bước 3: Create a New Project

Create a New Project Choose Your Hardware

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 43


Tạo Auth Token Xem Auth Token đã gửi qua mail

NOTE: Don’t share your Auth Token with anyone, unless you want someone to have
access to your hardware

Bước 4: Add a Widget

Chọn các công cụ cần tương tác.


GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 44
Widget Settings - Each Widget has it’s own settings. Tap on the widget to get to them.
Chọn một Button, thiết lập liên kết điều khiển với led tại chân Digital Pin 8=D8

Bước 4: Kết nối phần cứng với Arduino Wemos D1

Kết nối Led đơn với chân D8

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 45


Mô tả chương trình:
- Khi nhấn Button trên app Blynk thì Led1 trên chân D8 sẽ sáng/tắt.
- Đồng thời một Led ảo V1 trên app Blynk nhấp nháy.
/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";
char d8;
WidgetLED led1(V1);//tạo led ảo trên app Blynk

BlynkTimer timer;
// V1 LED Widget is blinking
void blinkLedWidget()
{ d8=digitalRead(0);// D8 = led đơn

if (d8==0) {
led1.off();
Serial.println("LED on V1: off");
} else {
led1.on();
Serial.println("LED on V1: on");
}
}
void setup()
{
// Debug console

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 46


Serial.begin(9600);
pinMode(0,INPUT);
Blynk.begin(auth, ssid, pass);
// You can also specify server:
//Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
//Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
timer.setInterval(1000L, blinkLedWidget);
}
void loop()
{
Blynk.run();
timer.run();

}
Bước 5: Run The Project

Ví dụ 2: PWM với Led chân D8: sử dụng Widget = Slider tạo PWM điều khiển trực tiếp
trên D8, hoặc Gauge.

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 47


4.2. Giao tiếp cảm biến hồng ngoại. (Giáo viên hướng dẫn)
VD: Nút nhấn
#define LED 13 //D7
#define BUTTON 12//D6
void setup() {
pinMode(LED, OUTPUT); /* Cấu hình chân 13 ở chế độ OUTPUT */
pinMode(BUTTON, INPUT); /* Cấu hình chân 12 ở chế độ INPUT */
digitalWrite(LED, LOW);
}
void loop() {
if(digitalRead(BUTTON) == LOW)/* Nhấn nút, chân 12 ở mức cao, ngược lại ở
mức thấp */
{
delay(20); /* Trễ khoảng 20ms để trạng thái điện áp của nút nhấn ổn định */
while(digitalRead(BUTTON) == LOW) /* Nếu vẫn còn nhấn nút*/
{
digitalWrite(LED, HIGH);//sáng LED

}
}
else
{
digitalWrite(LED, LOW);
}
}
Code Button-Blynk:
/* Comment this out to disable prints and save space */
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
//#include <SPI.h>
#define BLYNK_PRINT Serial
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = " f8781ee65b46434b99e4f4bbe87a3d55";
char ssid[] = "Thien Linh";
char pass[] = "987654321";
int nutnhan;
BlynkTimer timer;
WidgetLED led1(V1);
void myTimerEvent()
{
GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 48
nutnhan = digitalRead(13); // D7
if (nutnhan==0)
{//Blynk.virtualWrite(V1,0);
led1.on();
}
else
{//Blynk.virtualWrite(V1,255);
led1.off();
}
}
void setup()
{
// Debug console
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
timer.setInterval(1000L, myTimerEvent);
}
void loop()
{
Blynk.run();
timer.run();
}

4.3. Giao tiếp cảm biến nhiệt độ. (Giáo viên hướng dẫn)

Phần mềm: hiển thị nhiệt độ và độ ẩm

Blynk: chọn công cụ trong Widget Box: 2- Value Display và 2 -Gauge

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 49


Chọn chân ảo Virtual pins= V0 cho nhiệt độ và V1 cho độ ẩm.

Có thể thêm công cụ History graph:

https://www.hackster.io/Matei_Tudose/how-to-read-temperature-and-humidity-on-
blynk-with-dht11-f5fbae

Google Sheet : (tham khảo)

Arduino IDE -WeMos D1:


#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include "DHTesp.h"// DHT sensor library for ESPx =online
//#include <SimpleTimer.h> //including the library of SimpleTimer
DHTesp dht;
#define dht_dpin 14 // ngõ vào cảm biến DHT là chân D5
BlynkTimer timer;
char auth[] = "Your Auth. Key"; // Get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).

char ssid[] = "Your Wifi Network name"; // Your WiFi credentials.


char pass[] = "Password of your network"; // Set password to "" for open networks.
float t; // Declare the variables
float h;

void setup()
{

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 50


Serial.begin(9600);// Debug console
Blynk.begin(auth, ssid, pass);
dht.setup(14, DHTesp::DHT11); // Connect DHT sensor=GPIO17
timer.setInterval(2000, sendUptime);
}

void sendUptime()
{ float h = dht.getHumidity(); //đọc giá trị nhiệt độ
float t = dht.getTemperature();//đọc giá trị độ ẩm

Serial.println("Humidity and temperature\n\n");


Serial.print("Current humidity = ");
Serial.print(h);
Serial.print("% ");
Serial.print("temperature = ");
Serial.print(t);
Blynk.virtualWrite(V0, t); //gửi giá trị nhiệt độ đến biến ảo V0
Blynk.virtualWrite(V1, h); //gửi giá trị độ ẩm đến biến ảo V1

void loop()
{
Blynk.run();
timer.run();
}

Phần cứng:

WeMos D1:

TT Chân của DHT11 Kết nối với WeMos D1

1 VCC +3.3V

2 DATA D5

3 GND GND

4.4. Giao tiếp động cơ. (Giáo viên hướng dẫn)

-Servo SG90:

Phần cứng:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 51


Kết nối dây màu đỏ với 5V, dây màu nâu với mass, dây màu cam với chân phát xung D4
của Wemos D1. Ở chân xung cấp một xung từ 1ms-2ms để điều khiển góc quay theo ý
muốn.

Phần mềm:

- Chọn Slider trong Widget Box, khai báo ngõ ra là biến ảo V3.

- Chọn thang đo (0:180) tương ứng với góc quay của Servo.

Code WeMos D1:


GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 52
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SPI.h>
#include <Servo.h> // Thư viện điều khiển servo
#define BLYNK_PRINT Serial
char auth[] = " f8781ee65b46434b99e4f4bbe87a3d55";

char ssid[] = "sonymouse";


char pass[] = "12345678";
int dcservo;
Servo myservo1; // Khai báo biến servo thứ 1
BlynkTimer timer;
BLYNK_WRITE(V3){
dcservo=param.asInt();
myservo1.write(dcservo);//lấy giá trị từ biến ảo V3 trên App để dk servo
}

void setup()
{
myservo1.attach(4);// ngo ra dieu khien servo 1
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
}
void loop()
{
Blynk.run();
timer.run();
}
-Giao tiếp động cơ bước 28BYJ-48:

L298N:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 53


Kết nối WeMos D1 và L298N:
WeMos D1 Board L298N Motor Controller
D2 ENA
D15/SCL/D3 IN1
D14/SDA/D4 IN2
D13/SCK/D5 IN3
D12/MISO/D6 IN4
D11/MOSI/D7 ENB
Kết nối L298N và động cơ bước 28BYJ-48:
L298N Motor 28BYJ-48 Stepper
Controller Motor
OUT1 1. Blue
OUT2 3. Yellow
OUT3 4. Pink
OUT4 5. Orange
Lưu ý: cần cấp nguồn riêng 6-12V cho động cơ, nối mass chung với WeMos D1
Code tham khảo chưa có wifi:

/* Driving a 5V stepper motor using Keyes L298N Dual Motor Driver;*/

const int ENA = 7;

const int IN1 = 6;

const int IN2 = 5;

const int ENB = 8;

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 54


const int IN4 = 9;

const int IN3 = 10;

const int ledPin = 13;

void setup()

pinMode(ENA,OUTPUT);

pinMode(IN1,OUTPUT);

pinMode(IN2,OUTPUT);

pinMode(ENB,OUTPUT);

pinMode(IN3,OUTPUT);

pinMode(IN4,OUTPUT);

pinMode(ledPin,OUTPUT);

digitalWrite(ledPin, LOW);

//delay is used to control the speed, the lower the faster.

//reverse(step,delay);

reverse(80,20);

//forward(step,delay);

forward(80,20);

void loop()

{// code tự viết

void reverse(int i, int j) {

// set both motors ON

digitalWrite(ENA, HIGH);

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 55


digitalWrite(ENB, HIGH);

while (1) {

digitalWrite(IN1, 0);

digitalWrite(IN2, 1);

digitalWrite(IN3, 0);

digitalWrite(IN4, 1);

delay(j);

i--;

if (i < 1) break;

digitalWrite(IN1, 0);

digitalWrite(IN2, 1);

digitalWrite(IN3, 1);

digitalWrite(IN4, 0);

delay(j);

i--;

if (i < 1) break;

digitalWrite(IN1, 1);

digitalWrite(IN2, 0);

digitalWrite(IN3, 1);

digitalWrite(IN4, 0);

delay(j);

i--;

if (i < 1) break;

digitalWrite(IN1, 1);

digitalWrite(IN2, 0);

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 56


digitalWrite(IN3, 0);

digitalWrite(IN4, 1);

delay(j);

i--;

if (i < 1) break;

// set both motors OFF

digitalWrite(ENA, LOW);

digitalWrite(ENB, LOW);

} // end reverse()

void forward(int i, int j) {

// Set both motors ON

digitalWrite(ENA, HIGH);

digitalWrite(ENB, HIGH);

while (1) {

digitalWrite(IN1, 0);

digitalWrite(IN2, 1);

digitalWrite(IN3, 0);

digitalWrite(IN4, 1);

delay(j);

i--;

if (i < 1) break;

digitalWrite(IN1, 1);

digitalWrite(IN2, 0);

digitalWrite(IN3, 0);

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 57


digitalWrite(IN4, 1);

delay(j);

i--;

if (i < 1) break;

digitalWrite(IN1, 1);

digitalWrite(IN2, 0);

digitalWrite(IN3, 1);

digitalWrite(IN4, 0);

delay(j);

i--;

if (i < 1) break;

digitalWrite(IN1, 0);

digitalWrite(IN2, 1);

digitalWrite(IN3, 1);

digitalWrite(IN4, 0);

delay(j);

i--;

if (i < 1) break;

// set both motors OFF

digitalWrite(ENA, LOW);

digitalWrite(ENB, LOW);
} // end forward()

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 58


Chương 5: XÂY DỰNG HỆ THỐNG IOT
MÔ TẢ HỆ THỐNG:

A. Phần cứng:

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 59


B. Phần mềm:
CODE:
/* Comment this out to disable prints and save space */

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SPI.h>
#define BLYNK_PRINT Serial
char auth[] = " f8781ee65b46434b99e4f4bbe87a3d55";
char ssid[] = "Thien Linh";
char pass[] = "987654321";
int nutnhan=1;
int val;
int sensorPin = A0;
BlynkTimer timer;

WidgetLED led1(V1);
WidgetLED led2(V2);

void myTimerEvent()
{ blinkLedWidget();
val = analogRead(sensorPin)*100/1024;// max=1024, chuyen sang thang do 100
Blynk.virtualWrite(V0,val);//bien ao V0 là giá trị chuyen doi từ cam bien
nutnhan = digitalRead(13); //D7=GPIO13
if (nutnhan==0)
{//Blynk.virtualWrite(V1,0);
GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 60
led2.on();
Blynk.notify("CAM BIEN 1");
}
else
{//Blynk.virtualWrite(V1,255);
led2.off();
}
}
void blinkLedWidget()
{
if (led1.getValue()) {
led1.off();
Serial.println("LED on V1: off");
} else {
led1.on();
Serial.println("LED on V1: on");
}
}

/*void emailOnButtonPress()
{
// *** WARNING: You are limited to send ONLY ONE E-MAIL PER 5 SECONDS!
***
// Let's send an e-mail when you press the button
// connected to digital pin 2 on your Arduino
int isButtonPressed = !digitalRead(2); // Invert state, since button is "Active LOW"
if (isButtonPressed) // You can write any condition to trigger e-mail sending
{
Blynk.email("vothien22@gmail.com", "Subject: Canh bao tu Blynk ", "hello");

// Or, if you want to use the email specified in the App (like for App Export):
//Blynk.email("Subject: Button Logger", "You just pushed the button...");
}
}*/
void setup()
{
Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
timer.setInterval(1000L, myTimerEvent);
//Blynk.email("vothien22@gmail.com", "Subject", "My Blynk project is online.");
pinMode(13,INPUT);//D7
// Attach pin 2 interrupt to our handler

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 61


//attachInterrupt(digitalPinToInterrupt(2), emailOnButtonPress, CHANGE);

void loop()
{
Blynk.run();
timer.run();
}

Tài liệu tham khảo:

 http://www.wemos.cc/tutorial/getstartedin_arduino.html
 http://forum.wemos.cc/topic/102/wemos-d1-r2-not-see-usb-ports-on-mac/2
 http://www.instructables.com/id/Programming-the-WeMos-Using-Arduino-SoftwareIDE/?ALLSTEPS
 http://forum.wemos.cc/topic/102/wemos-d1-r2-not-see-usb-ports-on-mac/2
 https://www.instructables.com/id/Programming-a-HTTP-Server-on-ESP-8266-12E/
 https://www.hackster.io/blynk/products/blynk

Xử lý lỗi Uploading:
Initial Checks
In order to troubleshoot “espcomm_sync failed” error, please proceed step by step through
the checklist below. This list is organized starting with most common and simple to more
complex issues.

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 62


1. Start with reading exact message displayed in debug window of Arduino IDE. In many cases it
provides direct information where the issue is.

“espcomm_open failed” error


For instance message above suggests that Arduino IDE is unable to open a serial port COM3.
Check if you have selected port where your module is connected to.

Serial port selection

2. If a module is connected to the serial port but not responding as a valid ESP8266 device, the
message will read slightly different (see below). If you have other modules connected to your PC,
make sure that you are uploading code to ESP8266 and not to e.g. Arduino UNO.

Serial port selection

3. To have your PC talking to ESP, select exact ESP type in upload menu. If selection is incorrect
then the upload may fail.

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 63


Board selection
Basing on selected board type, Arduino IDE will apply specific “reset method” to enter the
board into boot loading mode. Reset methods are board specific. Some boards do not have
the h/w in place to support reset by Arduino IDE. If this is the case, you need to enter such
board into boot loading mode manually.

4. Upload may be also failing due to too high speed. If you have long or poor quality USB cable,
try reducing selection under Upload Speed.

Tools -> Upload Speed: 115200

Serial speed selection

GVHD: ThS Võ Thiện Lĩnh – BM ĐIỆN –ĐIỆN TỬ UTC2 Page 64

You might also like