I am collecting data from vibration sensor and than store it on a csv file on SD Card and send that file to ThingSpeak cloud. Although, I can send data to ThingSpeak but not the file. I am posting my code.
#include "SD.h"
//src: https://robotzero.one/posting-data-server-esp32/
#include <SPI.h>
#include "esp_http_client.h"
#include <WiFi.h>
#include <PubSubClient.h>
#include "ADXL355.h"
#include "pindef.h"
#include "DebugUtils.h"
#include "arduinoFFT.h"
#include "Arduino.h"
ADXL355 adxl355 = ADXL355(ADXL355_CS);
const char *ssid = "ABC"; //Pixel XL Pixel IoT Advice ZONG4G-30FC SSMA1234
const char *password = "548";
const char* serverName = "http://api.thingspeak.com/update";
WiFiClient espClient;
PubSubClient client(espClient);
#define ODR_Freq 2000 // ODR Frequency 30 10 5
#define data_collection_time_sec 60 // 60 seconds required for 1/60hz gap between FFT Frequencies prev: 60 1490 RPM
const int samples_to_read1 = ODR_Freq * data_collection_time_sec;
const int samples_to_read = 120000;
bool drdy = false;
bool init_intr = true;
unsigned long tempx; unsigned long tempy; unsigned long tempz;
float x; float y; float z;
int counter=0;
float *magx;
float *freqx;
float *array_int_x; float *array_int_y; float *array_int_z;
float *fft_inputx;
float *fft_outputx;
char * out;
const unsigned long fourMinutes = 6 * 40 * 1000UL; //240 secs
static unsigned long lastSampleTime = 0 - fourMinutes; // initialize such that a reading is due the first time through loop()
unsigned long timeBegin;
const char *post_data = "field1=value1&field2=value2";
const int chipSelect = 13;
#define SCK 14
#define MISO 2
#define MOSI 15
#define CS 13
File myFile;
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
Serial.print("Initializing SD card...");
SPIClass spi = SPIClass(HSPI);
pinMode(SS, OUTPUT);
spi.begin(SCK, MISO, MOSI, CS);
if(!SD.begin(CS,spi)) {
Serial.println("Card Mount Failed");
return;
}
Serial.println("SD initialization done.");
//myFile = SD.open("test.txt", FILE_WRITE);
array_int_x = (float *) ps_malloc(samples_to_read * sizeof(float)); //Create an float array of n_elements
array_int_y = (float *) ps_malloc(samples_to_read * sizeof(float)); //Create an float array of n_elements
array_int_z = (float *) ps_malloc(samples_to_read * sizeof(float)); //Create an float array of n_elements
// If the data.txt file doesn't exist, Make File and write top labels to it
//open the file if it exists
myFile = SD.open("readings_sensorid_timestamp.csv");
if (!myFile) {
Serial.println("File doens't exist");
Serial.println("Creating file...");
myFile = SD.open("readings_sensorid_timestamp.csv", FILE_WRITE);
//myFile.println("S.No. x y z");
Serial.println("File Created");
}else{Serial.println("File already exists");}
//myFile.close();
adxl355.init(RATE_2000); //Previously RATE_2000 4000 Hz Here we are setting just the default ODR, user can set it again on the web server
adxl355.isDeviceRecognized();
attachInterrupt(digitalPinToInterrupt(DRDY), readings_ISR, RISING);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
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("Connected to the WiFi Network");
Serial.println("IP address: "); //Assigns IP address to ESP32. 10.57.138.13 Try to assign static IP address to ESP32 as we did in company
Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
esp_err_t _http_event_handler(esp_http_client_event_t *evt)
{
switch (evt->event_id) {
case HTTP_EVENT_ERROR:
Serial.println("HTTP_EVENT_ERROR");
break;
case HTTP_EVENT_ON_CONNECTED:
Serial.println("HTTP_EVENT_ON_CONNECTED");
break;
case HTTP_EVENT_HEADER_SENT:
Serial.println("HTTP_EVENT_HEADER_SENT");
break;
case HTTP_EVENT_ON_HEADER:
Serial.println();
Serial.printf("HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
break;
case HTTP_EVENT_ON_DATA:
Serial.println();
Serial.printf("HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
if (!esp_http_client_is_chunked_response(evt->client)) {
// Write out data
// printf("%.*s", evt->data_len, (char*)evt->data);
}
break;
case HTTP_EVENT_ON_FINISH:
Serial.println("");
Serial.println("HTTP_EVENT_ON_FINISH");
break;
case HTTP_EVENT_DISCONNECTED:
Serial.println("HTTP_EVENT_DISCONNECTED");
break;
}
return ESP_OK;
}
static esp_err_t post_something()
{
esp_err_t res = ESP_OK;
esp_http_client_handle_t http_client;
esp_http_client_config_t config_client = {0};
config_client.url = serverName;
config_client.event_handler = _http_event_handler;
config_client.method = HTTP_METHOD_POST;
http_client = esp_http_client_init(&config_client);
esp_http_client_set_header(http_client, "Content-Type", "readings_sensorid_timestamp/csv"); // sending a jpg file
esp_err_t err = esp_http_client_perform(http_client);
if (err == ESP_OK) {
Serial.print("esp_http_client_get_status_code: ");
Serial.println(esp_http_client_get_status_code(http_client));
}
esp_http_client_cleanup(http_client);
}
//upload the file on server than delete/remove it
//create a new file again inside: if (now - lastSampleTime >= fourMinutes)
void loop() {
// Now write data to sd card and send the file to server
if(counter > 5 - 1){
Serial.println("Now writing to SD card");
long int t1 = millis();
//writing to SD Card
for(int i=0; i < 5; i++){
myFile.print(i); myFile.print(" "); myFile.print(array_int_x[i]); myFile.print(" "); myFile.print(array_int_y[i]); myFile.print(" "); myFile.print(array_int_z[i]); myFile.println(" ");
}
//send file to server here
//Serial.println("File Uploaded to server");
long int t2 = millis();
Serial.print("Time taken by the task: "); Serial.print(t2-t1); Serial.println(" milliseconds");
Serial.println("--------------------------------------------------");
free(array_int_x); free(array_int_y); free(array_int_z);
array_int_x = (float *) ps_malloc(samples_to_read * sizeof(float));
array_int_y = (float *) ps_malloc(samples_to_read * sizeof(float));
array_int_z = (float *) ps_malloc(samples_to_read * sizeof(float));
counter=0;
}
myFile.flush(); //remove("test.csv");
post_something();
unsigned long now = millis();
if (now - lastSampleTime >= fourMinutes) //7 mins to collect and print data(in future our processing): 7+4mins delay = 11mins delay + 1mins delay to collect the readings
//it'll take to collect readings
{
lastSampleTime += fourMinutes;
// add code to take temperature reading here
Serial.println("reattaching");
timeBegin = millis(); //create new file again
attachInterrupt(digitalPinToInterrupt(DRDY), readings_ISR, RISING);
}
}