element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
In Reach! – Ultrasonic Sensor Sensing Challenge
  • Challenges & Projects
  • Design Challenges
  • In Reach! – Ultrasonic Sensor Sensing Challenge
  • More
  • Cancel
In Reach! – Ultrasonic Sensor Sensing Challenge
Forum Early Flood Warning and Monitoring System #4 - Wiring the Brains: Hooking Up the TDK Ultrasonic Sensors to the MKR 1010
  • News
  • Forum
  • Projects
  • DC
  • Files
  • Members
  • More
  • Cancel
  • New
Join In Reach! – Ultrasonic Sensor Sensing Challenge to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • Replies 0 replies
  • Subscribers 41 subscribers
  • Views 18 views
  • Users 0 members are here
  • design challenge
  • TDK waterproof sensors
  • Ultrasonic Sensor Sensing Challenge
  • flood warning system
Related

Early Flood Warning and Monitoring System #4 - Wiring the Brains: Hooking Up the TDK Ultrasonic Sensors to the MKR 1010

sandeepdwivedi17
sandeepdwivedi17 3 days ago

So the fun part begins — wires, boards, and the faint smell of solder.
This is where the project goes from “cool idea” to “actual blinking lights.”

Here in this blog we will discuss the wiring of all components and the Code inside the Arduino Board.

Circuit Arrangement:

Final Circuit

Required Hardware:

  • TDK USSM Distance measurement sendor — the stars of the show.They send ultrasonic pings and measure how long it takes for echoes to come back.
  • Arduino MKR WiFi 1010 — the brain that reads data, processes it, and sends it to the online google sheet for collection anf furture analysis as well as initiate warning email when danger mark is near.
  • BS170 MOSFET , 15 k Ohm Resistance , used for logic level converter to safely operate our arduino
  • LM2596S DC-DC Buck Converter Power Supply to poweup the sensor with 12 v
  • A bunch of colorful jumper wires — because what’s a DIY project without a rainbow of cables?

image

image

image

Open Arduino IDE and Upload following code into it

// TDK-MKR-Logger - MKR WiFi 1010 sketch (simulation mode) - API key + server-config reflect
// Paste into Arduino IDE and upload to MKR WiFi 1010
// Requires: WiFiNINA, ArduinoJson (v6.x)

// ------------------------ user config (replace placeholders) ------------------------


// set this to the API_SECRET / key you put in ConfigDetails (column Value for key API_SECRET)
const char* API_KEY = "jlkajlkj"; // <--- replace to match your sheet's API_SECRET

const char* SENSOR_NAME = "MKR_UltraSim_01"; // change if needed
const unsigned long POST_TIMEOUT_MS = 30UL * 1000UL;     // wait up to 30s for server response
// ------------------------------------------------------------------------------------

#include <WiFiNINA.h>
#include <ArduinoJson.h>
#include "arduino_secrets.h" // must contain SECRET_SSID and SECRET_PASS
#include <TDK_USSM.h>

//-- Instanciate Single Sensor
TDK_USSM TdkUssm(2); //Initialize Sensor Pins (IoPin)

unsigned long POST_INTERVAL_MS = 10000; // default if server doesn't override
float THRESHOLD_VALUE = 15.0;           // default if server doesn't override

unsigned long lastPost = 0;

void setup() {
  Serial.begin(115200);
  while (!Serial && millis() < 4000) ; // wait for Serial (short)
  Serial.println();
  Serial.println("TDK-MKR-Logger (with API key) starting...");

  randomSeed(analogRead(A0)); // seed random for simulation

  connectWiFi();

  // Optional: if you set GAS_CONFIG_URL and want to fetch config on boot, uncomment:
  // if (strlen(GAS_CONFIG_URL) > 0) tryFetchConfig();

  lastPost = millis() - 1000;
}

void loop() {
  unsigned long now = millis();

  // Only try posting on interval
  if (now - lastPost >= POST_INTERVAL_MS) {
    lastPost = now;

    int value = readDistanceSim();           // you changed to int
    bool alertNeeded = (value < THRESHOLD_VALUE);

    // Build JSON payload
    StaticJsonDocument<256> doc;
    doc["sensor_name"] = SENSOR_NAME;
    doc["value"] = value;
    doc["alert_requested"] = alertNeeded;
    doc["device"] = "MKR1010";
    doc["uptime_ms"] = now;
    doc["api_key"] = API_KEY;

    String payload;
    serializeJson(doc, payload);

    Serial.print("Posting payload: ");
    Serial.println(payload);

    String serverResp;
    const int MAX_POST_ATTEMPTS = 3;
    bool postOk = false;
    int attempt = 0;
    unsigned long backoff = 500; // ms - initial backoff

    while (attempt < MAX_POST_ATTEMPTS && !postOk) {
      attempt++;
      Serial.print("POST attempt ");
      Serial.println(attempt);
      if (httpPostJson(FLOOD_POST_URL, payload, serverResp)) {
        postOk = true;
        Serial.println("POST succeeded.");
        Serial.print("Server raw response: ");
        Serial.println(serverResp);
        // parse & apply server config (same as before)...
        StaticJsonDocument<512> respDoc;
        DeserializationError err = deserializeJson(respDoc, serverResp);
        if (!err) {
          if (respDoc.containsKey("config")) {
            JsonObject cfg = respDoc["config"].as<JsonObject>();
            if (cfg.containsKey("THRESHOLD_VALUE")) {
              float newTh = cfg["THRESHOLD_VALUE"].as<float>();
              Serial.print("Server requested THRESHOLD_VALUE = ");
              Serial.println(newTh);
              THRESHOLD_VALUE = newTh;
            }
            if (cfg.containsKey("POST_INTERVAL_MS")) {
              unsigned long newInterval = cfg["POST_INTERVAL_MS"].as<unsigned long>();
              Serial.print("Server requested POST_INTERVAL_MS = ");
              Serial.println(newInterval);
              POST_INTERVAL_MS = newInterval;
            }
          }
          if (respDoc.containsKey("alert")) {
            const char* alertText = respDoc["alert"];
            Serial.print("Server alert: ");
            Serial.println(alertText);
          }
        } else {
          Serial.print("Failed to parse server JSON: ");
          Serial.println(err.c_str());
        }
        break;
      } else {
        Serial.println("POST failed on attempt.");
        // small delay with backoff before retrying
        delay(backoff);
        backoff = min(backoff * 2, 5000UL); // cap at 5s
      }
    } // end attempts

    if (!postOk) {
      Serial.println("All POST attempts failed.");
      // Only attempt WiFi reconnect if link is actually not connected
      if (WiFi.status() != WL_CONNECTED) {
        Serial.print("WiFi status != CONNECTED (");
        Serial.print(WiFi.status());
        Serial.println(") - attempting reconnect.");
        connectWiFi();
      } else {
        Serial.println("WiFi appears connected; not reconnecting. Will try again on next interval.");
        // Optionally: you could force a reconnect if you see many consecutive POST failures
      }
    }
  }

  // If WiFi truly drops outside POST, try reconnecting (small check once every 10s)
  static unsigned long lastWifiCheck = 0;
  if (millis() - lastWifiCheck > 10000) {
    lastWifiCheck = millis();
    if (WiFi.status() != WL_CONNECTED) {
      Serial.print("WiFi status check: not connected (");
      Serial.print(WiFi.status());
      Serial.println("). Reconnecting.");
      connectWiFi();
    }
  }

  delay(50);
}


void printConfig() {
  Serial.println(F("\n--- Current Configuration ---"));
  Serial.print(F("THRESHOLD_VALUE: "));
  Serial.println(THRESHOLD_VALUE);
  Serial.print(F("POST_INTERVAL_MS: "));
  Serial.println(POST_INTERVAL_MS);
  Serial.println(F("------------------------------\n"));
}

/* -------------------- helpers -------------------- */

int readDistanceSim() {
  TdkUssm.GetDistanceCm();  // Prints Distance in cm.
}


void connectWiFi() {
  Serial.print("Connecting to WiFi SSID: ");
  Serial.println(SECRET_SSID);

  WiFi.end();
  delay(200);

  int status = WiFi.begin(SECRET_SSID, SECRET_PASS);
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && (millis() - start) < POST_TIMEOUT_MS) {
    delay(500);
    Serial.print(".");
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println();
    Serial.print("WiFi connected. IP: ");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println();
    Serial.print("WiFi connect failed, status=");
    Serial.println(WiFi.status());
  }
}

// Simple HTTPS POST with JSON payload; returns server response body
bool httpPostJson(const String &url, const String &jsonPayload, String &responseBody) {
  responseBody = "";
  if (url.length() == 0) {
    Serial.println("GAS_POST_URL not set!");
    return false;
  }

  String host = hostFromUrl(url);
  String path = pathFromUrl(url);
  if (host.length() == 0 || path.length() == 0) {
    Serial.println("Invalid GAS_POST_URL.");
    return false;
  }

  WiFiSSLClient client;
  Serial.print("HTTPS POST to host: ");
  Serial.print(host);
  Serial.print(" path: ");
  Serial.println(path);

  if (!client.connect(host.c_str(), 443)) {
    Serial.println("Connection failed (POST).");
    return false;
  }

  // Build request
  client.print(String("POST ") + path + " HTTP/1.1\r\n");
  client.print(String("Host: ") + host + "\r\n");
  client.print("Connection: close\r\n");
  client.print("Content-Type: application/json\r\n");
  client.print(String("Content-Length: ") + jsonPayload.length() + "\r\n");
  client.print("User-Agent: MKR1010\r\n");
  client.print("\r\n");
  client.print(jsonPayload);

  unsigned long timeout = millis();
  while (client.connected() && !client.available()) {
    if (millis() - timeout > 8000) {
      Serial.println("Timeout waiting for POST response.");
      client.stop();
      return false;
    }
  }

  // read status line
  String statusLine = client.readStringUntil('\n');
  statusLine.trim();
  Serial.print("Status: ");
  Serial.println(statusLine);

  // skip headers
  while (client.available()) {
    String line = client.readStringUntil('\n');
    line.trim();
    if (line.length() == 0) break;
  }

  // read body
  String body = "";
  unsigned long start = millis();
  while (client.available()) {
    char c = client.read();
    body += c;
    if (millis() - start > 8000) break;
  }

  client.stop();
  responseBody = body;
  return true;
}

// URL helpers
String hostFromUrl(const String &url) {
  int idx = url.indexOf("://");
  int start = (idx >= 0) ? idx + 3 : 0;
  int slash = url.indexOf('/', start);
  if (slash < 0) return url.substring(start);
  return url.substring(start, slash);
}

String pathFromUrl(const String &url) {
  int idx = url.indexOf("://");
  int start = (idx >= 0) ? idx + 3 : 0;
  int slash = url.indexOf('/', start);
  if (slash < 0) return "/";
  return url.substring(slash);
}

// arduino_secrets.h
// Put this in the same folder as your sketch or in your Arduino sketchbook/libraries folder.
// Replace the values between the quotes exactly (case-sensitive). No trailing spaces.

#ifndef ARDUINO_SECRETS_H
#define ARDUINO_SECRETS_H

#define SECRET_SSID "WIFIname"      // <-- replace with your Wi-Fi SSID (2.4 GHz)
#define SECRET_PASS "wifipass"  // <-- replace with your Wi-Fi password







#define HTTPS_PORT_NUMBER 443

#define FLOOD_POST_URL   "https://script.google.com/macros/s/AKfycbw27cP9jphgyeJNA7Mr2523E2NE8FiNO1ZGUrQqqFY99Hr-roe357eSuJDAVEvfmZKCzw/exec" 
// OPTIONAL: endpoint that returns JSON config { "THRESHOLD_VALUE": 15, "POST_INTERVAL_MS": 10000 }
// If you don't have this, set GAS_CONFIG_URL to "" and sketch will use defaults below.
#define FLOOD_CONFIG_URL "https://script.google.com/macros/s/REPLACE_WITH_YOUR_CONFIG_URL/exec"

#endif





In Next Blog we will see the testing and results

  • Sign in to reply
  • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube