Hi. Im new to this arduino thing and originally my project was just using the esp8266(Esp12-e) as a controller and be done with it but unfortunately my esp8266 does not do what it is intended.
My project was supposed to be using an ultrasonic sensor to watch water levels and send the data to thingspeak (and/or Node red). However, the esp8266 just displays either constant 0 or random numbers. I knew that the HC-SRO4 needs 5v and because of that Im using the arduino uno as a power source while the information is sent to the nodemcu. Needless to say i changed the main controller to the arduino uno and the ultrasonic sensor data is being read correctly.
const int trigPin = 7;
const int echoPin = 7;
void setup() {
Serial.begin(9600);
}
void loop() {
long duration, inches, cm;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}
This is my code for the offline version (yes a modified version of the example pin) and i dont understand how to connect from arduino to thingspeak (and/or Node-red) using the esp8266.
The code for the esp8266 as the main controller and wifi is this
#include "ThingSpeak.h"
#include <ESP8266WiFi.h>
const int trigPin = D3;
const int echoPin = D4;
unsigned long ch_no = channel;
const char * write_api = "api";
const char * auth = "author";
const char * ssid = "wifi";
const char * pass = "Pass";
const char * server = "api.thingspeak.com";
unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 10000;
WiFiClient client;
long duration1;
int distance1;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
ThingSpeak.begin(client);
startMillis = millis(); //initial start time
}
void loop()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration1 = pulseIn(echoPin, HIGH);
distance1 = duration1 * 0.034 / 2;
Serial.println(distance1);
currentMillis = millis();
if (currentMillis - startMillis >= period)
{
ThingSpeak.setField(1, distance1);
ThingSpeak.writeFields(ch_no, write_api);
startMillis = currentMillis;
}
}
Any advice is highly appreciated