Skip to content

Instantly share code, notes, and snippets.

@mlwmlw

mlwmlw/serial.ino

Last active Aug 11, 2016
Embed
What would you like to do?
Ardunio + ESP8266 + thingspeak
void setup() {
Serial1.begin(9600); //RX1 TX1,即 Pin18 及 Pin19
Serial.begin(9600);
}
void loop() {
if (Serial1.available()) {
Serial.write(Serial1.read());
}
if (Serial.available()) {
char chars = Serial.read();
Serial1.write(chars);
}
}
#include <JeeLib.h>
#include "ESP8266.h"
ESP8266 wifi(Serial1);
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "api key from thingspeak";
// Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
const int updateThingSpeakInterval = 16 * 1000;
// Variable Setup
long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;
ISR(WDT_vect) { Sleepy::watchdogEvent(); }
void setup()
{
// Start Serial for debugging on the Serial Monitor
Serial.begin(9600);
Serial.print("IP:");
Serial.println( wifi.getLocalIP().c_str());
}
void loop()
{
if(millis() - lastConnectionTime < updateThingSpeakInterval)
{
Sleepy::loseSomeTime(1000);
return;
}
uint8_t buffer[1024] = {0};
// Read value from Analog Input Pin 0
String analogValue0 = String(analogRead(A0), DEC);
if (wifi.createTCP(thingSpeakAddress, 80)) {
Serial.println("create tcp ok\r\n");
} else {
Serial.println("create tcp err\r\n");
return;
}
String post = "POST /update HTTP/1.1 \r\nHost: api.thingspeak.com\r\nConnection: close\r\nX-THINGSPEAKAPIKEY: " +
writeAPIKey + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length:" + (analogValue0.length() + 7) + "\r\n\r\n" +
"field1=" + analogValue0;
Serial.println(post);
wifi.send((const uint8_t*)post.c_str(), post.length());
lastConnectionTime = millis();
uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
if (len > 0) {
Serial.println("Received:[");
for(uint32_t i = 0; i < 15; i++) {
Serial.print((char)buffer[i]);
}
Serial.println("]\r\n");
}
else {
failedCounter++;
Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");
}
if (wifi.releaseTCP()) {
Serial.print("release tcp ok\r\n");
} else {
Serial.print("release tcp err\r\n");
}
# low energy mode
wifi.deepSleep(updateThingSpeakInterval - 1000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment