0% found this document useful (0 votes)
54 views

New Text Document

This document contains code for an IoT device that measures water level using a capacitive sensor and GPS location. It includes code to initialize hardware components, read sensor data, log data to an SD card, and transmit data over Bluetooth. The device uses an ESP32, TinyGPS library, FDC1004 capacitive-to-digital converter, and SPIFFS for the file system. Sensor readings are averaged and processed to calculate water level and capacity. Date, time, location and sensor data are logged to a text file on the SD card. Bluetooth commands can retrieve the log file.

Uploaded by

senith lasen
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

New Text Document

This document contains code for an IoT device that measures water level using a capacitive sensor and GPS location. It includes code to initialize hardware components, read sensor data, log data to an SD card, and transmit data over Bluetooth. The device uses an ESP32, TinyGPS library, FDC1004 capacitive-to-digital converter, and SPIFFS for the file system. Sensor readings are averaged and processed to calculate water level and capacity. Date, time, location and sensor data are logged to a text file on the SD card. Bluetooth commands can retrieve the log file.

Uploaded by

senith lasen
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

include <TinyGPSPlus.

h>
#include <SoftwareSerial.h>
#include <ESP32Time.h>
#include <Wire.h>
#include <Protocentral_FDC1004.h>
#include "SPIFFS.h"
#include <cstring>
#include "BluetoothSerial.h"
#include <cmath>

#define LED_BUILTIN 2 // turn on in_built LED when receive commands via Bluetooth

#define FORMAT_SPIFFS_IF_FAILED true

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)


#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

// For NEO 6 ----------------------------


#define txPin 26
#define rxPin 27
#define GPS_PIN 25
#define CAP_PIN 14

TinyGPSPlus gps;
SoftwareSerial SerialGPS(rxPin, txPin);
ESP32Time rtc(3600);

BluetoothSerial SerialBT;

// For FDC1004 -------------------------


#define UPPER_BOUND 0X4000 // max readout capacitance
#define LOWER_BOUND (-1 * UPPER_BOUND)
#define CHANNEL 2 // channel to be read
#define MEASURMENT 2 // measurment channel

int capdac = 0;
float sum = 0;
float capacitance2 = 0;
int i = 0;
float average = 0;
float water_level = 0;
float water_capacity = 0;

int minute_slst;
int hour_slst;
bool isRTCUpdated = false;

FDC1004 FDC;

String date_str, time_str, lat_str, lng_str, speed_str;

void setup() {
Serial.begin(115200); // serial baud rate
Wire.begin(); // i2c begin
SerialGPS.begin(9600);

pinMode(GPS_PIN, OUTPUT);
pinMode(CAP_PIN, OUTPUT);
// Turn On GPS and FDC1004
digitalWrite(GPS_PIN, HIGH);
digitalWrite(CAP_PIN, HIGH);

SerialBT.begin("Saranga"); //Bluetooth device name


// SerialGPS.begin(9600, SERIAL_8N1, 16, 17);
if (!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)) {
Serial.println("SPIFFS Mount Failed");
return;
}
delay(2000);
listDir(SPIFFS, "/", 0);
delay(2000);
deleteFile(SPIFFS, "/log.txt");
//readFile(SPIFFS, "/saranga.txt");
//delay(2000);

delay(3000);
}

void loop() {

readDataForm_FDC1004();

while (SerialGPS.available() > 0)


if (gps.encode(SerialGPS.read())){
// Set Date and Time to RTC
if(!isRTCUpdated){
setDateAnDTime();
}
//Start Data fetching from NE0 6 and FDC1004
processAndShowData();
}

if (millis() > 5000 && gps.charsProcessed() < 10){


Serial.println(F("GPS Module Not Detected"));
// while (true);
}

if (SerialBT.available() > 0) {
char c = SerialBT.read();
if (c == 'r') {
//SerialBT.print(c);
readFile(SPIFFS, "/log.txt");
//SerialBT.print('\n');
// deleteFile(SPIFFS, "/log.txt");
delay(10);

// Only for testing, trun on in_built LED when receive commands via
bluetooth
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
}
}
}

void readDataForm_FDC1004(){
FDC.configureMeasurementSingle(MEASURMENT, CHANNEL, capdac);
FDC.triggerSingleMeasurement(MEASURMENT, FDC1004_100HZ);

//wait for completion


delay(15);
uint16_t value[2];
if (! FDC.readMeasurement(MEASURMENT, value)){

int16_t msb = (int16_t) value[0];


int32_t capacitance = ((int32_t)457) * ((int32_t)msb); //in attofarads
capacitance /= 1000; //in femtofarads
capacitance += ((int32_t)3028) * ((int32_t)capdac);

capacitance2 = ((float)capacitance/1000);
//Serial.println(capacitance2, 4);

if (msb > UPPER_BOUND){ // adjust capdac accordingly


if (capdac < FDC1004_CAPDAC_MAX)
capdac++;
}
else if (msb < LOWER_BOUND){
if (capdac > 0)
capdac--;
}
}
}

void processAndShowData(){
sum = sum + capacitance2;
i++;
if(i == 50){
if (gps.location.isValid()){
// Display Info ----------------------
displayInfo();
}else{
Serial.println(F("searching for satellites..."));
}

i = 0;
average = 0;
sum = 0;
}
}

void setDateAnDTime(){
// Convert UTC to SLST
minute_slst = gps.time.minute();
hour_slst = gps.time.hour();

minute_slst = (minute_slst + 30);


if (minute_slst > 59){
minute_slst = minute_slst - 60;
hour_slst = hour_slst + 1;
}

/*
* To convert UTC to SLST need to add 5.30 to UTC.
* But Here NEO6 give BST.
* BST to SLST, need to add 4.30.
*/
hour_slst = (hour_slst + 4);
if (hour_slst > 23){
hour_slst = hour_slst - 24;
}

// Set time For RTC (second, minute, hour, day, month, year);
rtc.setTime(gps.time.second(), minute_slst, hour_slst, gps.date.day(),
gps.date.month(), gps.date.year());
}

void displayInfo(){
// // Water Level info ------------------------
average = sum / 50;
// Serial.print("Avg:");
// Serial.print(average, 4);
// Serial.print("pf");
// Serial.print("\t");
//
water_level = ((average - 45.743) / 0.7061); // add 64.78 to error correction
// Serial.print("Liq.Lvl:");
// Serial.print(water_level, 4);
// Serial.print("cm");
// Serial.print("\t");
//
water_capacity = water_level * 94.724;
// Serial.print("Liq.Cap:");
// Serial.print(water_capacity, 4);
// Serial.print("ml");
// Serial.print("\t");
//
// //GPS Info --------------------------------
// Serial.print("Lat:");
// Serial.print(gps.location.lat(), 6);
// Serial.print(F("\t"));
// Serial.print("Lng:");
// Serial.print(gps.location.lng(), 6);
// Serial.print(F("\t"));
// Serial.print(rtc.getTime("%A %B %d %Y %H:%M:%S"));
// Serial.println();

int myear = gps.date.year();


int mmonth = gps.date.month();
int mday = gps.date.day();

date_str = String(mday) + ":" + String(mmonth) + ":" + String(myear);


time_str = String(rtc.getTime());
lat_str = String(gps.location.lat(), 6);
lng_str = String(gps.location.lng(), 6);

String data = date_str + "\t" + time_str + "\t" + lat_str + "\t" + lng_str +


"\t" + water_level;
int str_len = data.length() + 1;
char char_array[str_len];
data.toCharArray(char_array, str_len);

Serial.println(char_array);

appendFile(SPIFFS, "/log.txt", char_array);


}

// SPIFFS methods
---------------------------------------------------------------------

void listDir(fs::FS& fs, const char* dirname, uint8_t levels) {


Serial.printf("Listing directory: %s\r\n", dirname);

File root = fs.open(dirname);


if (!root) {
Serial.println("? failed to open directory");
return;
}
if (!root.isDirectory()) {
Serial.println(" ? not a directory");
return;
}

File file = root.openNextFile();


while (file) {
if (file.isDirectory()) {
Serial.print(" DIR : ");
Serial.println(file.name());
if (levels) {
listDir(fs, file.name(), levels - 1);
}
}
else {
Serial.print(" FILE: ");
Serial.print(file.name());
Serial.print("\tSIZE: ");
Serial.println(file.size());
}
file = root.openNextFile();
}
}

void readFile(fs::FS& fs, const char* path) {


// Serial.printf("Reading file: %s\r\n", path);

File file = fs.open(path);


if (!file || file.isDirectory()) {
Serial.println("? failed to open file for reading");
return;
}

//Serial.println("? read from file:");


while (file.available()) {
SerialBT.write(file.read());
}
}

void writeFile(fs::FS& fs, const char* path, const char* message) {


//Serial.printf("Writing file: %s\r\n", path);

File file = fs.open(path, FILE_WRITE);


if (!file) {
// Serial.println("? failed to open file for writing");
return;
}
if (file.println(message)) {
// Serial.println("? file written");
}
else {
// Serial.println("? frite failed");
}
}

void deleteFile(fs::FS& fs, const char* path) {


Serial.printf("Deleting file: %s\r\n", path);
if (fs.remove(path)) {
Serial.println("− file deleted");
}
else {
Serial.println("− delete failed");
}
}

void appendFile(fs::FS& fs, const char* path, const char* message) {


//Serial.printf("Appending to file: %s\r\n", path);

File file = fs.open(path, FILE_APPEND);


if (!file) {
Serial.println("− failed to open file for appending");
return;
}
if (file.println(message)) {
// Serial.println("− message appended");
}
else {
Serial.println("− append failed");
}
}

void renameFile(fs::FS& fs, const char* path1, const char* path2) {


Serial.printf("Renaming file %s to %s\r\n", path1, path2);
if (fs.rename(path1, path2)) {
Serial.println("− file renamed");
}
else {
Serial.println("− rename failed");
}
}

bool compare_float(float x, float y, float epsilon = 0.01f) {


if (fabs(x - y) < epsilon)
return true; //they are same
return false; //they are not same
}

You might also like