Skip to content

Instantly share code, notes, and snippets.

@luisfcorreia
Created April 16, 2016 22:37
Show Gist options
  • Save luisfcorreia/e3e06913794fbd68621086e3ec3f7f2a to your computer and use it in GitHub Desktop.
Save luisfcorreia/e3e06913794fbd68621086e3ec3f7f2a to your computer and use it in GitHub Desktop.
/*
Example code to get a MCP3*08 running with an ESP8266
for DiY energy monitoring solutions
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "MCP3208.h"
const char* ssid = "...";
const char* host = "...";
const char* password = "...";
const int httpPort = 80;
float adc0 = 0;
// bitbanging all the way
// reusing TX RX pins as GPIO
#define SELPIN 0 //CS
#define DATAOUT 1 //MOSI
#define DATAIN 3 //MISO
#define SPICLOCK 2 //SCLK
MCP3208 adc(SPICLOCK, DATAOUT, DATAIN, SELPIN);
// ADC read time "delays"
unsigned long adcTime;
unsigned long adcDelay = 1000;
// IOT send time "delays"
unsigned long iotTime;
unsigned long iotDelay = 2000;
// stub function for resetting ADC read time delay
void setAdcDelay() {
adcTime = millis() + adcDelay;
}
// stub function for resetting HTTP send delay
void setIoTDelay() {
iotTime = millis() + iotDelay;
}
void setup() {
//Serial.begin(115200);
//Serial.println('Setup complete.');
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
setAdcDelay();
setIoTDelay();
}
void loop() {
if (millis() >= adcTime) {
adc0 = adc.readADC(0);
//adc0 = 1.45;
setAdcDelay();
}
if (millis() >= iotTime) {
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
// this is something like "GET /iot?id=esp01&key=adc&value=2197.00"
String url = "/iot";
url += "?id=esp01";
url += "&key=adc";
url += "&value=";
url += adc0;
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
int timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) {
client.stop();
return;
}
}
setIoTDelay();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment