I am using Nodenmcu with arduino IDE . I have used DHT11 IC to read temperature and humidity. Now i would like to add parameter in web page called set_temp . When Set_temp value being set to value the value should get updated when change icon has been pressed. Here is my code. My code is working till to enter the text from web but it wont update set_temp value
#include <ESP8266WiFi.h>
#include "DHT.h"
static float Set_Temp;
DHT dht;
int value = LOW;
const char* ssid = "esp8266";
const char* password = "Test123456";
int ledPin = 13; // GPIO13
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
dht.setup(D3); /* D1 is used for data communication */
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
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.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
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);
}
// New code has been added
delay(dht.getMinimumSamplingPeriod()); /* Delay of amount equal to sampling period */
float humidity = dht.getHumidity(); /* Get humidity value */
float temperature = dht.getTemperature(); /* Get temperature value */
// Serial.print(dht.getStatusString()); /* Print status of communication */
if(temperature>=Set_Temp)
{
digitalWrite(ledPin, HIGH);
value = HIGH;
}else
{
digitalWrite(ledPin, LOW);
value = LOW;
}
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
/* if (request.indexOf("/LED=ON") != -1) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
value = LOW;
}*/
// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("Relay_Turn_On_Status: ");
if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
// client.println("<br><br>");
// client.println("<button>Turn On </button>");
// client.println("<button>Turn Off </button><br />");
// client.println("</html>");
client.print("</html>");
client.print("<head>");
client.print("<title>My Page</title>");
client.print("</head>");
client.print("<body>");
client.print("<br><br>");
client.print("Set_Temp: ");
client.println("<input type=text name=textbox size=5 value=Enter_Temp_Here");
client.println("<br><input type=submit value=Change ><br>");
client.println("</div>");
client.println("</body>");
client.println("</html>");
Set_Temp:"<br><input type=submit value=Change ><br>";
//Set_Temp:"<input type=text name=textbox size=5 value=Enter_Temp_Here>";
Serial.println(Set_Temp);
client.println("<br><br>");
client.println("DHT11_HumidityReading: ");
client.println(humidity,1);
client.println("<br><br>");
client.println("DHT11_Temprature Reading: ");
client.println(temperature,1);
client.println("<br><br>");
client.println("Set_Temp: ");
client.println(Set_Temp);
client.println("<br><br>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
My main doubt in this part of code where once i read it wont update.
Set_Temp:"<br><input type=submit value=Change ><br>";
//Set_Temp:"<input type=text name=textbox size=5 value=Enter_Temp_Here>";
Serial.println(Set_Temp);
If i use like this. it will display -1
Set_Temp=readString.indexOf(2);
I followed the method of get & post from HTTP https://www.w3schools.com/htmL/[Serial Out Here][web page]
How can i change my Set_Temp value from text box.
Take a look to this article, I follow it to turn on and turn off a light in NodeMCU with Arduino IDE. The client in the web is written on PHP.
https://blog.nyl.io/esp8266-led-arduino/
<?php
$light = $_GET['light'];
if($light == "on") {
$file = fopen("light.json", "w") or die("can't open file");
fwrite($file, '{"light": "on"}');
fclose($file);
}
else if ($light == "off") {
$file = fopen("light.json", "w") or die("can't open file");
fwrite($file, '{"light": "off"}');
fclose($file);
}
?>
I hope this help you.
Regards
Related
I have an ESP32 that is running in softap mode with AutoConnect. I'm trying to get the captive portal to always be active, even if the client portion is connected to an AP. The current problem is once the ESP32 establishes the client connection with the router or after the initial timeout period, the captive portal goes away and you have to manually enter the IP address of the of the softap in the web browser.
Is there a setting I'm missing that allows this to happen?
//Config.autoRise = true;
Config.immediateStart = true;
Config.portalTimeout = 30 * 1000;
Config.retainPortal = true;
Config.title = "ESP32 AP";
Config.homeUri = "/";
portal.config(Config);
AutoConnectConfig Config;
//Config.bootUri=URI;
Config.homeUri="/_ac";
Config.apid = "Vedesp32-1";
Config.psk = "vedesp32";
Config.apip=IPAddress(10,1,1,1);
//Config.immediateStart = true;
Config.hostName = "esp32.local";
Config.title = "NBrowser";
Config.autoSave = AC_SAVECREDENTIAL_AUTO;
Config.autoReset = false;
Config.autoReconnect = true;
Config.reconnectInterval = 6;
Config.autoRise = true;
Config.retainPortal = true;
Portal.onDetect(atDetect);
Portal.config(Config);
extern "C" {
#include "freertos/FreeRTOS.h"
#include "freertos/timers.h"
}
#include <WiFiClient.h>
#include <time.h>
#include <sys/time.h>
#include <AutoConnect.h>
#define IND 2
#define BUZZER 5
#define SWITCH_ON "True"
#define SWITCH_OFF "False"
#define CREDENTIAL_OFFSET 0
const char* URI = "/_ac";
TimerHandle_t wifiReconnectTimer;
AutoConnect Portal;
void pinInit() {
pinMode(BUZZER, OUTPUT);
pinMode(IND, OUTPUT);
}
void connectToWifi() {
Serial.println("Connecting to Wi-Fi... ->");
if (WiFi.status() == WL_CONNECTED) {
delay(5000);
Serial.print(".");
}
}
void WiFiEvent(WiFiEvent_t event) {
Serial.printf("[WiFi-event] event: %d\n", event);
switch (event) {
case SYSTEM_EVENT_STA_GOT_IP:
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
digitalWrite(BUZZER, HIGH);
digitalWrite(IND, HIGH);
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("WiFi lost connection");
digitalWrite(IND, LOW);
xTimerStart(wifiReconnectTimer, 0);
break;
}
}
void setup() {
Serial.begin(115200);
Serial.println();
pinInit();
digitalWrite(IND, LOW);
wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));
WiFi.onEvent(WiFiEvent);
AutoConnectConfig Config;
//Config.bootUri=URI;
Config.homeUri="/_ac";
Config.apid = "Ved";
Config.psk = "vedesp32";
Config.apip=IPAddress(10,1,1,1);
//Config.immediateStart = true;
Config.hostName = "esp32.local";
Config.title = "NBrowser";
Config.autoSave = AC_SAVECREDENTIAL_AUTO;
Config.autoReset = false; // Not reset the module even by intentional disconnection using AutoConnect menu.
Config.autoReconnect = true; // Reconnect to known access points.
Config.reconnectInterval = 6; // Reconnection attempting interval is 3[min].
Config.autoRise = true;
Config.retainPortal = true; // Keep the captive portal open.
Portal.onDetect(atDetect);
Portal.config(Config);
// Start
if (Portal.begin()) {
Serial.println("WiFi connected: " + WiFi.localIP().toString());
digitalWrite(IND, HIGH);
}
connectToWifi();
}
bool atDetect(IPAddress& softapIP) {
Serial.println("Captive portal started, SoftAP IP:" + softapIP.toString());
return true;
}
void loop() {
Portal.handleClient();
}
Hello...
My code is working perfect with using dynamic IP's, the LED is connected to server and a push button is connected to client, it work perfect with dynamic IP's addresses of both devices. But when i make static IP addresses, the client can not connect to server, and it always says connection failed.
Client code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_61(192,168,100,59);
//IPAddress gateway612_61(192,168,100,1);
//IPAddress subnet612_61(255,255,255,0);
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char * host = "192.168.100.23"; // IP Server
const int httpPort = 80;
const char* Commands; // The command variable that is sent to the server
int button = 5; // push button is connected
bool btn_press = true; // The variable to detect the button has been pressed
int con = 0; // Variables for mode
void setup() {
// put your setup code here, to run once:
pinMode(button, INPUT_PULLUP); // initialize the pushbutton pin as an input:
Serial.begin(115200); // initialize serial:
Serial.println("");
Serial.println("Client-------------------------------");
Serial.print("Connecting to Network");
WiFi.mode(WIFI_STA); // Mode Station
WiFi.begin(ssid, password); // Matching the SSID and Password
delay(1000);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("Successfully Connecting");
Serial.println("Status : Connected");
//WiFi.config(staticIP612_61, gateway612_61, subnet612_61);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(button) == LOW) {
Serial.println("Client-------------------------------");
Serial.print("Send Command = ");
if (btn_press == true){
if (con >= 2) {
con=0;
}
con++;
switch (con){
case 1:
Commands="LED_On";
Serial.println(Commands);
send_commands();
break;
case 2:
Commands="LED_Off";
Serial.println(Commands);
send_commands();
break;
}
btn_press = false;
}
}
else {
btn_press = true;
}
delay(100);
}
void send_commands(){
Serial.println("Sending command...");
Serial.println("Don't press the button for now...");
Serial.println("");
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
if (!client.connect(host, httpPort)) {
Serial.println("Connection failed");
return;
}
// We now create a URI for the request
Serial.print("Requesting URL : ");
Serial.println(Commands);
// This will send the request to the server
client.print(String("GET ") + Commands + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: Close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Client Timeout !");
client.stop();
return;
}
}
Serial.print("Server Reply = ");
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println("Now you can press the button ...");
Serial.println("-------------------------------------");
Serial.println("");
}
Server code is:
#include <ESP8266WiFi.h>
//IPAddress staticIP612_60(192,168,100,60);
//IPAddress gateway612_60(192,168,100,1);
//IPAddress subnet612_60(255,255,255,0);
int led = 5; // the pin the LED is connected to
const char* ssid = "GravixarATD"; // Your wifi Name
const char* password = "TheRedMonster79"; // Your wifi Password
const char* Commands_Reply; // The command variable that is sent to the client
const char * host = "192.168.100.21"; // IP Client
WiFiServer server(80);
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT); // Declare the LED as an output
Serial.begin(115200); // initialize serial:
delay(10);
Serial.println("");
Serial.println("Server-------------------------------");
Serial.print("Configuring access point");
WiFi.begin(ssid, password);
// Waiting to connect to wifi
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// WiFi.config(staticIP612_60, gateway612_60, subnet612_60);
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
Serial.println("-------------------------------------");
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("Server-------------------------------");
Serial.println("New client");
Serial.print("From client = ");
while(!client.available()){
delay(1);
}
// Read the first line of the request -------------------------------------
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();
//Command LED -------------------------------------------------------------
if (req.indexOf("LED_On") != -1){
Commands_Reply = "LED Status : On";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, HIGH);
}
else if (req.indexOf("LED_Off") != -1){
Commands_Reply = "LED Status : Off";
Serial.print("Server send = ");
Serial.println(Commands_Reply);
client.print(String("GET ") + Commands_Reply + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
digitalWrite(led, LOW);
}
else {
Serial.println("invalid request");
client.stop();
return;
}
client.flush();
Serial.println("Client disonnected");
Serial.println("-------------------------------------");
Serial.println("");
}
NOTE I have commented all the static IP lines, when i comment them and using dynamic ips, client connect to server perfectly and when i use static ips instead of dynamic ips client fails to connect with server. any help will be appreciated.
I am using 2 esp8266, both connected to same network. Esp1 send some data to esp2 using websocket. So basically esp2 connect to esp1 websocket and read data.
My problem is that if esp1 is restarted, after is up again, esp2 does not connect anymore to it and needs restart to connect
This is code I am using on esp2
#include <ESP8266WiFi.h>
#include <WebSocketsClient.h>
#include <ESP8266WebServer.h>
#include <SoftwareSerial.h>
#define USE_SERIAL Serial
#define LEDS 0 //Status led
WebSocketsClient webSocket;
SoftwareSerial COM(5, 4);
long previousMillis = 0;
long interval = 50;
String data;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
switch(type) {
case WStype_DISCONNECTED:
yield();
break;
case WStype_CONNECTED: {
webSocket.sendTXT("Connected");
}
yield();
break;
case WStype_TEXT:
if(payload[0] == '#') {
uint32_t dataz = (uint32_t) strtol((const char *) &payload[1], NULL, 10);
if (dataz < 99911) {
data = "0" + String(dataz);
}
else {
data = String(dataz);
}
}
yield();
if (data.length() == 6 ) {
COM.print('<'); // start marker
COM.print(data);
COM.println('>'); // end marker
}
break;
}
}
void setup() {
pinMode(LEDS, OUTPUT);
digitalWrite(LEDS, LOW);
for(uint8_t t = 4; t > 0; t--) {
delay(1000);
}
WiFi.mode(WIFI_STA);
WiFi.begin("xxx", "xxx");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
// server address, port and URL
webSocket.begin("192.168.0.30", 81, "/");
// event handler
webSocket.onEvent(webSocketEvent);
// use HTTP Basic Authorization this is optional remove if not needed
//webSocket.setAuthorization("user", "Password");
// try ever 5000 again if connection has failed
webSocket.setReconnectInterval(5000);
digitalWrite(LEDS, HIGH);
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
webSocket.loop();
}
}
I would need some help to make it reconnect when the esp1 is available again after was disconnected
Thank you very much
webSocket.loop(); should be outside of if statement.
I try to make an HTTPS GET request and make an HTTPS POST request with the data recieved... I am using an arduino UNO with the library GSM_GPRS_GPS_Shield_GSMSHIELD and the GSM GPRS shield SIM900. Here is my current code below:
//include libs
#include "SIM900.h"
#include "inetGSM.h"
#include <SoftwareSerial.h>
InetGSM inet;
//data holder
int par1 = -1;
int par2 = -1;
void setup() {
Serial.begin(9600);
Serial.println("BEGIN");
boolean started = false;
SIM900power();
//initialize the SIM900
if (gsm.begin(2400)){
Serial.println("READY");
started=true;
}else Serial.println("IDLE");
//connect it to the network
if(started){
if (inet.attachGPRS("free", "", ""))
Serial.println("ATTACHED");
else Serial.println("ERROR");
delay(1000);
gsm.SimpleWriteln("AT+CIFSR");
delay(3000);
gsm.WhileSimpleRead();
//GET request
char * json = "";
while(strlen(json) < 4){
delay(2000);
char msg[200] = "";
Serial.println(inet.httpGET("my.site.com", 80, "/somethingToGet?param=1", msg, 200));
//interpret Json
char * msg_tmp = msg;
json = strstr (msg_tmp, "[{");
}
if(json != ""){
const byte posPar1 = (int)(strstr(json, "par1") - json) + 7;
const byte posPar2 = (int)(strstr(json, "par2") - json) + 7;
if(json[posPar1] != 'u')
par1 = extractNum(json, posPar1);
if(json[posPar2] != 'u')
par2 = extractNum(json, posPar2);
}
if(json == "" || par1 == -1 || par2 == -1){
SIM900power();
Serial.println("A JSON ERROR OCCURED");
while(1){}}
}
};
void loop() {
aPostRequest();
while(1){}
};
void SIM900power()
{
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(8000);
}
//extract the data from the Json string
int extractPar(char * json, byte pos){
int num = 0;
while (json[pos] != '"'){
num = json[pos]-'0' + num * 10;
pos++;
}
return num;
}
//POST request
void aPostRequest(){
if( par1 != -1 && par2 != -1){
boolean dataFound = true;
while(dataFound){
delay(2000);
char params[100];
snprintf(params, 100, "par1=%d&par2=%d", par1,par2);
char msg[200] = "";
dataFound = (inet.httpPOST("my.site.com ", 80, "/something", params , msg, 200) == 0);
}
}
}
I have two web sites, an HTTP one for my tests and the other one in HTTPS. As you can imagine, it's working on my HTTP one.
I don't know how to solve this problem but I think I need to do some tricky things with certificates in the library... can somebody help?
PS: if you want to test the code, you need to uncomment the HTTPPOST() function in the file inetGSM.h of the library. You can edit the functions httpGET() and HTTPPOST() in the file inetGSM.cpp.
UPDATE
There is the library code for the GET function below (httpPOST() works the same) :
int InetGSM::httpGET(const char* server, int port, const char* path, char* result, int resultlength)
{
boolean connected=false;
int n_of_at=0;
int length_write;
char end_c[2];
end_c[0]=0x1a;
end_c[1]='\0';
/*
Status = ATTACHED.
if(gsm.getStatus()!=GSM::ATTACHED)
return 0;
*/
while(n_of_at<3) {
if(!connectTCP(server, port)) {
#ifdef DEBUG_ON
Serial.println("DB:NOT CONN");
#endif
n_of_at++;
} else {
connected=true;
n_of_at=3;
}
}
if(!connected) return 0;
gsm.SimpleWrite("GET ");
gsm.SimpleWrite(path);
gsm.SimpleWrite(" HTTP/1.0\r\nHost: ");
gsm.SimpleWrite(server);
gsm.SimpleWrite("\r\n");
gsm.SimpleWrite("User-Agent: Arduino");
gsm.SimpleWrite("\r\n\r\n");
gsm.SimpleWrite(end_c);
switch(gsm.WaitResp(10000, 10, "SEND OK")) {
case RX_TMOUT_ERR:
return 0;
break;
case RX_FINISHED_STR_NOT_RECV:
return 0;
break;
}
delay(50);
#ifdef DEBUG_ON
Serial.println("DB:SENT");
#endif
int res = gsm.read(result, resultlength);
//gsm.disconnectTCP();
//int res=1;
return res;
}
I have already tried to change the HTTP/1.0 for HTTPS/1.0, but nothing appends.
UPDATE 2
I redirected my request through my HTTP server because I still have not found an answer, if someone could answer for those who could be blocked!
I was trying to make a HTTPS request to a Lambda function that i coded in AWS. The function had to send a json body from a WEMOS D1 mini via a POST to AWS. TBH, I don't know, if this will solve your Issue on your Controller, but it might be worth trying :)
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#ifndef STASSID
#define STASSID "<yourWiFiSSID>"
#define STAPSK "<yourWifiPW>"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "<the host link here (has to look like **google.com** important, dont add the route here) >";
const int httpsPort = 443;
const String data = "<Json Object here e.g -> **{\"temperature\": 20.5, \"humidity\": 60}**>";
// Use web browser to view and copy
// SHA1 fingerprint of the certificate
const char fingerprint[] PROGMEM = "5F F1 60 31 09 04 3E F2 90 D2 B0 8A 50 38 04 E8 37 9F BC 76";
void setup() {
Serial.begin(115200);
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");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;
Serial.print("connecting to ");
Serial.println(host);
Serial.printf("Using fingerprint '%s'\n", fingerprint);
client.setFingerprint(fingerprint);
client.setInsecure();
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
String url = "<your route here e.g **/photos/test**> ";
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n"+
"Content-Length: " + data.length() + "\r\n" +
"Content-Type: application/json;charset=UTF-8\r\n\r\n"+
data +"\r\n");
Serial.println("request sent");
//READ INCOMING HTML
uint8_t * _buffer = new uint8_t[128];
String line = "";
if (client.connected()) {
int actualLength = client.read(_buffer, 128);
// If it fails for whatever reason
if(actualLength <= 0)
{
return;
}
// Concatenate the buffer content to the final response string
// I used an arduino String for convenience
// but you can use strcat or whatever you see fit
//TRANSFORM EVERY CHAR FROM INCOMING HTML
line += String((char*)_buffer).substring(0, actualLength);
if (line == "\r") {
Serial.println("headers received");
}
}
Serial.print("Line: ");
Serial.println(line);
if (line.startsWith("{\"state\":\"success\"")) {
Serial.println("esp8266/Arduino CI successfull!");
} else {
Serial.println("esp8266/Arduino CI has failed");
}
Serial.println("reply was:");
Serial.println("==========");
Serial.println(line);
Serial.println("==========");
Serial.println("closing connection");
}
void loop() {
}
I really hope this might have helped someone.
I am trying to implement a master/slave setup to determine the time of flight between two Arduino Uno boards and ultimately use that as a measure of distance between the two. Using the standard 16MHz crystal and the APC220 from DFRobot communicating between the two is easy but getting a time of flight reading is where I get stuck.
I use the following code on the master side to send the first signal and receive the echo from the slave:
// set pins:
const int switchPin = 3; // pin number of the switch
// variables:
int switchState = 0; // variable for reading switch status
int iDisplay = 1;
unsigned long start, finished, elapsed;
// initialize
void setup()
{
// initialize switch pin as input:
pinMode(switchPin, INPUT);
// initialize serial wireless communication:
Serial.begin(9600);
// read initial state of switch
switchState = digitalRead(switchPin);
}
void displayResult()
{
float h,m,s,ms;
unsigned long over;
elapsed=finished-start;
h=int(elapsed/3600000);
over=elapsed%3600000;
m=int(over/60000);
over=over%60000;
s=int(over/1000);
ms=over%1000;
Serial.print("Raw elapsed time: ");
Serial.println(elapsed);
Serial.print("Elapsed time: ");
Serial.print(h,0);
Serial.print("h ");
Serial.print(m,0);
Serial.print("m ");
Serial.print(s,0);
Serial.print("s ");
Serial.print(ms,0);
Serial.println("ms");
Serial.println();
}
// program loop
void loop()
{
if (Serial.available()>0 && iDisplay == 1)
{
finished=millis();
displayResult();
iDisplay = 0;//Only once
}
// read switch state and print line if state has changed
switch (digitalRead(switchPin)) { // read pin status
case HIGH:
if (switchState == LOW)
{ // check if message has to be sent
start=millis();
delay(200); // for debounce
iDisplay = 1;//Only once
Serial.println(100); // send message about switch
switchState = HIGH; // message has been sent
}
break;
case LOW:
if (switchState == HIGH)
{ // check if message has to be sent
start=millis();
delay(200); // for debounce
iDisplay = 1;//Only once
Serial.println(100); // send message about switch
switchState = LOW; // message has been sent
}
break;
}
}
And the following code for the slave:
// variables:
int intTime = 0;
// initialize
void setup()
{
// initialize serial wireless communication:
Serial.begin(9600);
}
// program loop
void loop()
{
if (Serial.available()>0)
{
intTime = Serial.parseInt();
if (intTime > 1)
{
Serial.println(intTime);
}
intTime = 0;
}
}
Yet this only returns the 200 Milliseconds from the debounce delay, can this be done with the Arduino? Am I getting the math or the code wrong?