NGUYỄN VĂN SUM

Wednesday, November 15, 2017

DS3231 Real Time

// Crated by Nguyen Sum,
// https://nguyensumiot.wordpress.com/
// http://nguyensum.simplesite.com/
//
// A quick demo of how to use my DS3231-library to
// quickly send time and date information over a serial link
//
// To use the hardware I2C (TWI) interface of the Arduino you must connect
// the pins as follows:
//
// Arduino Uno/2009:
// ----------------------
// DS3231: SDA pin -> Arduino Analog 4 or the dedicated SDA pin
// SCL pin -> Arduino Analog 5 or the dedicated SCL pin
//
// Arduino Leonardo:
// ----------------------
// DS3231: SDA pin -> Arduino Digital 2 or the dedicated SDA pin
// SCL pin -> Arduino Digital 3 or the dedicated SCL pin
//
// Arduino Mega:
// ----------------------
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA pin
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL pin
//
// Arduino Due:
// ----------------------
// DS3231: SDA pin -> Arduino Digital 20 (SDA) or the dedicated SDA1 (Digital 70) pin
// SCL pin -> Arduino Digital 21 (SCL) or the dedicated SCL1 (Digital 71) pin
//
// The internal pull-up resistors will be activated when using the
// hardware I2C interfaces.
//
// You can connect the DS3231 to any available pin but if you use any
// other than what is described above the library will fall back to
// a software-based, TWI-like protocol which will require exclusive access
// to the pins used, and you will also have to use appropriate, external
// pull-up resistors on the data and clock signals.
//

#include

// Init the DS3231 using the hardware interface
DS3231 rtc(SDA, SCL);

void setup()
{
// Setup Serial connection
Serial.begin(115200);
// Uncomment the next line if you are using an Arduino Leonardo
//while (!Serial) {}

// Initialize the rtc object
rtc.begin();

// The following lines can be uncommented to set the date and time
rtc.setDOW(WEDNESDAY); // Set Day-of-Week to SUNDAY
rtc.setTime(15, 14, 00); // Set the time to 12:00:00 (24hr format)
rtc.setDate(15, 11, 2017); // Set the date to January 1st, 2014
}

void loop()
{
// Send Day-of-Week
Serial.print(rtc.getDOWStr());
Serial.print(" ");

// Send date
Serial.print(rtc.getDateStr());
Serial.print(" -- ");

// Send time
Serial.println(rtc.getTimeStr());

// Wait one second before repeating :)
delay (1000);
}

Wednesday, November 1, 2017

Giám sát nhiệt độ, độ ẩm qua smartphone sử dụng iots


// Crated by Nguyen Sum,
// https://nguyensumiot.wordpress.com/
// http://nguyensum.simplesite.com/
#include
#include

//DHT config
#define DHTPIN 4 // what digital pin we're connected to
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);

// Wi-Fi Settings
const char* ssid = "YOUR-WIFI-SSID"; // your wireless network name (SSID)
const char* password = "YOUR-WIFI-PASS"; // your Wi-Fi network password

WiFiClient client;

// ThingSpeak Settings
const int channelID = YOUR-CHANNEL-ID; //
String writeAPIKey = "YOUR-API-KEY"; // write API key for your ThingSpeak Channel
const char* server = "api.thingspeak.com";
const int postingInterval = 2 * 1000; // post data every 2 seconds

void setup() {
Serial.begin(115200);
dht.begin();
Serial.print("Connecting");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println("\r\nWiFi connected");
}

void loop() {
// wait and then post again
delay(postingInterval);

float temp = dht.readTemperature();
float humi = dht.readHumidity();
if (isnan(temp) || isnan(humi)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
if (client.connect(server, 80)) {
// Construct API request body
String body = "field1=" + String(temp, 1) + "&field2=" + String(humi, 1);

client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + writeAPIKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(body.length());
client.print("\n\n");
client.print(body);
client.print("\n\n");
Serial.printf("Nhiet do %s - Do am %s\r\n", String(temp, 1).c_str(), String(humi, 1).c_str());
}
client.stop();
}

Link tham khảo
http://nguyensum.simplesite.com/431208435

ESP8266 Source Code

// Crated by Nguyen Sum,
// https://nguyensumiot.wordpress.com/
// http://nguyensum.simplesite.com/

#include
#include
#include
#include
#include
#include

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);



#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

const char* ssid = "Connectify-pc";
const char* password = "0816452400";

ESP8266WebServer server(80);

const int output1 = 14;
const int output2 = 12;
const int output3 = 13;
const int output4 = 15;

boolean device1 = false;
boolean device2 = false;
boolean device3 = false;
boolean device4 = false;

void handleRoot() {
//digitalWrite(led, 1);
//server.send(200, "text/plain", "hello from esp8266!");
//digitalWrite(led, 0);

String cmd;
cmd += "\r\n";
cmd += "\r\n";
//cmd += "
ESP8266 Webserver

\"ESP8266 Web Server Control\"

";
cmd += "";
cmd += "";
cmd += "";

if(device1){
cmd +=("
Device1 : ON");
}
else{
cmd +=("
Device1 : OFF");
}

if(device2){
cmd +=("
Device2 : ON");
}
else{
cmd +=("
Device2 : OFF");
}

if(device3){
cmd +=("
Device3 : ON");
}
else{
cmd +=("
Device3 : OFF");
}

if(device4){
cmd +=("
Device4 : ON");
}
else{
cmd +=("
Device4 : OFF");
}

cmd += "\r\n";
server.send(200, "text/html", cmd);
}

void handleNotFound(){
//digitalWrite(led, 1);
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i>1); // init done

display.clearDisplay(); // Clear the buffer.

display.setTextSize(2);
display.setTextColor(WHITE);
//display.setTextColor(BLACK, WHITE); // 'inverted' text
display.setCursor(0,0);
display.println(" ESP8266");

display.setTextSize(3); //Size4 = 5 digit , size3 = 7 digits
//display.setTextColor(BLACK, WHITE); // 'inverted' text
display.setTextColor(WHITE);
display.setCursor(0,18);
display.println("Control");

display.setTextSize(1);
display.setTextColor(WHITE);
//display.setTextColor(BLACK, WHITE); // 'inverted' text
display.setCursor(0,52);
display.println("Version 0.1");

display.display();
delay(2000);

display.clearDisplay();

display.setTextSize(2);
display.setTextColor(WHITE);
//display.setTextColor(BLACK, WHITE); // 'inverted' text
display.setCursor(0,0);
display.println("Connecting");


// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");

display.print(".");
display.display();
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

display.clearDisplay();
display.setTextSize(1); display.setTextColor(WHITE);
display.setCursor(0,0); display.println(ssid);
display.setTextSize(2); display.setTextColor(WHITE);
display.setCursor(0,18); display.println(WiFi.localIP());
//display.setCursor(0,36); display.println(WiFi.localIP());

display.display();



if (MDNS.begin("esp8266")) {
Serial.println("MDNS responder started");
}

server.on("/", handleRoot);

server.on("/status1=1", [](){
server.send(200, "text/plain", "device1 = ON");
digitalWrite(output1, HIGH);
device1 = true;
});

server.on("/status1=0", [](){
server.send(200, "text/plain", "device1 = OFF");
digitalWrite(output1, LOW);
device1 = false;
});

server.on("/status2=1", [](){
server.send(200, "text/plain", "device2 = ON");
digitalWrite(output2, HIGH);
device2 = true;
});

server.on("/status2=0", [](){
server.send(200, "text/plain", "device2 = OFF");
digitalWrite(output2, LOW);
device2 = false;
});

server.on("/status3=1", [](){
server.send(200, "text/plain", "device3 = ON");
digitalWrite(output3, HIGH);
device3 = true;
});

server.on("/status3=0", [](){
server.send(200, "text/plain", "device3 = OFF");
digitalWrite(output3, LOW);
device3 = false;
});

server.on("/status4=1", [](){
server.send(200, "text/plain", "device4 = ON");
digitalWrite(output4, HIGH);
device4 = true;
});

server.on("/status4=0", [](){
server.send(200, "text/plain", "device4 = OFF");
digitalWrite(output4, LOW);
device4 = false;
});

server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}

void loop(void){
server.handleClient();
}

Link tham khảo
http://nguyensum.simplesite.com/431208435



Đo nhịp tim và hiển thị trên OLED

// Crated by Nguyen Sum,
// https://nguyensumiot.wordpress.com/
// http://nguyensum.simplesite.com/

#include "MAX30100_PulseOximeter.h"
#include "SH1106.h"

#define REPORTING_PERIOD_MS 1000

// PulseOximeter is the higher level interface to the sensor
// it offers:
// * beat detection reporting
// * heart rate calculation
// * SpO2 (oxidation level) calculation
PulseOximeter pox;



SH1106 display(0x3c, 4, 5);

uint32_t tsLastReport = 0;

// Callback (registered below) fired when a pulse is detected
void onBeatDetected()
{
Serial.println("Beat!");
}

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

// Initialize the PulseOximeter instance and register a beat-detected callback
pox.begin();
pox.setOnBeatDetectedCallback(onBeatDetected);
display.init();

display.setFont(ArialMT_Plain_16);
}

void loop()
{
// Make sure to call update as fast as possible
pox.update();

// Asynchronously dump heart rate and oxidation levels to the serial
// For both, a value of 0 means "invalid"
if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
display.clear();
display.drawString(0, 0, "HR: " + String(pox.getHeartRate()) + " bpm");
display.drawString(0, 32, "SpO2: " + String(pox.getSpO2()) +" %");
display.display();
Serial.print("Heart rate:");
Serial.print(pox.getHeartRate());
Serial.print("bpm / SpO2:");
Serial.print(pox.getSpO2());
Serial.println("%");

tsLastReport = millis();
}
}

Digital IO

Tên chân trong Arduino (Pin number) giống với thứ tự chân của ESP8266. pinMode, digitalRead, và digitalWrite đều sử dụng Pin Number như nhau, ví dụ như đọc GPIO2, gọi hàm digitalRead(2).

Chân GPIO0..15 có thể là INPUT, OUTPUT, hay INPUT_PULLUP. Chân GPIO16 có thể là INPUT, OUTPUT hay INPUT_PULLDOWN_16. Khi khởi động, tất cả các chân sẽ được cấu hình là INPUT.

Mỗi chân có thể phục vụ cho một tính năng nào đó, ví dụ Serial, I2C, SPI. Và tính năng đó sẽ được cấu hình đúng khi sử dụng thư viện. Hình bên dưới thẻ hiện sơ đồ chân đối với module ESP-12 phổ biến.

GPIO6 và GPIO11 không được thể hiện bởi vì nó được sử dụng cho việc kết nối với Flash. Việc sử dụng 2 chân này có thể gây lỗi chương trình.

Ghi chú


Một số board và module khác (ví dụ ESP-12ED, NodeMCU 1.0) không có GPIO9 và GPIO11, họ sử dụng với chế độ DIO cho Flash, trong khi ESP12 chúng ta nói bên trên sử dụng chế độ QIO

Ngắt GPIO hỗ trợ thông qua các hàm attachInterrupt, detachInterrupt Ngắt GPIO có thể gán cho bất kỳ GPIO nào, ngoại trừ GPIO16. Đều hỗ trợ các ngắt tiêu chuẩn của Arduino như: CHANGE, RISING, FALLING.

Code:

/*
// Crated by Nguyen Sum,
// https://nguyensumiot.wordpress.com/
// http://nguyensum.simplesite.com/
ESP8266 Blink by Simon Peter
Blink the blue LED on the ESP-01 module
This example code is in the public domain

The blue LED on the ESP-01 module is connected to GPIO1
(which is also the TXD pin; so we cannot use Serial.print() at the same time)

Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is acive low on the ESP-01)
delay(1000); // Wait for a second
digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH
delay(2000); // Wait for two seconds (to demonstrate the active low LED)
}

Chớp tắt dùng định thời

Code:

// Crated by Nguyen Sum,
// https://nguyensumiot.wordpress.com/
// http://nguyensum.simplesite.com/
int ledPin = 16; // LED connected to digital pin 16
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop()
{
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (ledState == LOW)
ledState = HIGH; // Note that this switches the LED *off*
else
ledState = LOW; // Note that this switches the LED *on*
digitalWrite(ledPin, ledState);
}
}

Chớp tắt dùng Delay

Với cách chớp tắt này sẽ làm CPU bị dừng tại thời điểm delay và không thực thi được code nào khác

Code:

int ledPin = 16; // LED connected to digital pin 16
void setup()
{
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop()
{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}