Arduino SD card shield and RTC Cannot write in datalog with time - android-sdcard

we been working on the SD card module and RTC, The main purpose of this is just to display the time and date then store the data to the SD card it's reading just fine but soon as we read the txt file it came out empty. my question is how can we display the data log in our txt file? here's the code:
#include <SD.h>
#include "RTClib.h"
const int chipSelect = 4;
int i=0;
int t;
#if defined(ARDUINO_ARCH_SAMD)
#define Serial SerialUSB
#endif
RTC_Millis rtc;
void setup(void)
{
Serial.begin(9600);
Serial.println("MICRO"); //Test the serial monitor
//RTC Module Initialization
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
rtc.begin(DateTime(_DATE_,__TIME__));
delay(2000);
//SD Card Module Initialization
Serial.print("Initializing SD card...");
// make sure that the default chip select pin is set to
// output, even if you don't use it:
pinMode(10, OUTPUT);
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
}
Serial.println("card initialized.");
delay(500);
}
void loop() {
//DATE&TIME
DateTime now = rtc.now();
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
//delay(3000);
delay(2000);
//SD.begin(chipSelect);
//DATALOGGING w DATE&TIME STAMP
i++;
int erick=i%5;
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
if (erick==0){
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println();
dataFile.print(now.year(), DEC);
dataFile.print('/');
dataFile.print(now.month(), DEC);
dataFile.print('/');
dataFile.print(now.day(), DEC);
dataFile.print(' ');
dataFile.print(now.hour(), DEC);
dataFile.print(':');
dataFile.print(now.minute(), DEC);
dataFile.print(':');
dataFile.print(now.second(), DEC);
dataFile.print(' ');
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
i=0;
}
}
Any help would be much appreciated

Related

MH-z19 giving -1 value after some time

I'm trying make an mqtt co2 sensor for home assistant. And I got it to work, but only for a couple of hours. At some point it starts giving me -1 values instead of the proper co2 value. What could this be?
Below my code:
#include <Arduino.h>
#include <Mhz19.h>
#include <SoftwareSerial.h>
SoftwareSerial softwareSerial(D3, D4);
Mhz19 sensor;
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ID";
const char* password = "pw";
const char* MQTT_BROKER = "192.168.1.25";//"test.mosquitto.org";
int mqttPort = 1883;
const char* mqttUser ="mqtt-user";
const char* mqttPassword ="pw";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
// Connect to Wi-Fi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("Connected to Wi-Fi");
}
void reconnect() {
// Loop until connected
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("Test1", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT");
} else {
Serial.print("Failed MQTT connection with state: ");
Serial.println(client.state());
// Re-try in 3 seconds
delay(3000);
}
}
// Once connected, publish an announcement, and subscribe
client.publish("sensor/test", "Hello from ...");
client.subscribe("sensor/test");
}
void setup() {
Serial.begin(115200);
setup_wifi(); // Connect to Wi-Fi network
client.setServer(MQTT_BROKER, mqttPort);
//client.setCallback(callback);
reconnect(); // Connect to MQTT broker
softwareSerial.begin(9600);
sensor.begin(&softwareSerial);
sensor.setMeasuringRange(Mhz19MeasuringRange::Ppm_5000);
sensor.enableAutoBaseCalibration();
Serial.println("Preheating..."); // Preheating, 3 minutes
while (!sensor.isReady()) {
delay(50);
}
Serial.println("Sensor Ready...");
}
void loop() {
if (!client.connected()) { reconnect(); }
//client.publish("Time", ctime(&now));
auto carbonDioxide = sensor.getCarbonDioxide();
if (carbonDioxide >= 0) {
Serial.println(String(carbonDioxide) + " ppm");
}
char co2String[8];
dtostrf(carbonDioxide, 1,0, co2String);
//Serial.println(co2String);
client.publish("Floating/climate/CO2", co2String);
delay(2000);
}
I also tried flashing it via ESPHome, but then I run into issues from UART. The chip doesn't work propperly as long as the sensor is connected to it.
The sensor may not be receiving enough current. Try connecting the sensor directly to a separate breadboard power supply. The sensor seems to have a warm up time. Try waiting for longer with the independent power supply connected. I hope this will solve your issue.
Thank You,
Naveen PS

Arduino - unable to connect to wifi

I have this (partial) code, that is used to read the ssid and password from a text file on a SD card.
This data should then be used to connect to the local wifi. But it is unable to connect, and keeps saying "Establishing connection to WiFi..."
I also dont seem to be able to print what I have read from the SD card. Previously my readline function returned a string. That I was able to print properly and verified that the file is read as expected. Then, since wifi requires a Char* I changed the code to Char* and since then it didnt work anymore:
#include <SD.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <WiFi.h>
File myFile;
char* ssid;
char* password;
void setup() {
// put your setup code here, to run once:
pinMode(thetaPos, INPUT);
pinMode(rhoPos, INPUT);
Serial.begin(115200);
Serial.print("Initializing SD card...");
if (!SD.begin()) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
myFile = SD.open("/config.txt");
if (myFile) {
// read from the file until there's nothing else in it:
ssid = readLine();
password = readLine();
Serial.println(ssid);
Serial.println(password);
connectToNetwork();
// close the file:
myFile.close();
} else {
// file didn't open
}
}
void loop() {
}
char* readLine() {
char* received = "";
char ch;
while (myFile.available()) {
ch = myFile.read();
if (ch == '\n') {
return received;
} else {
received += ch;
}
}
return received;
}
void connectToNetwork() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Establishing connection to WiFi..");
}
Serial.println("Connected to network");
}
what am I doing wrong?
this is the serial output:
Initializing SD card...initialization done.
ore calibration nvs commit failed(0x%x)
wdt_config->intr_handle)
Establishing connection to WiFi..
Establishing connection to WiFi..
Establishing connection to WiFi..
Establishing connection to WiFi..
Well, where is the error? This won't work as you hope:
char* readLine() {
char* received = ""; // poiner to \0 somewhere...
char ch;
while (myFile.available()) {
ch = myFile.read();
if (ch == '\n') {
return received;
} else {
received += ch; // move pointer to location ch bytes after...
}
}
return received;
}
You are utilizing pointer arithmetic - you are moving pointer around the memory and you are not storing anything anywhere. It's not String class that overloads += char and allows you to concatenate character to the end of it.
Basically you can use:
String readLine() {
String received;
while (myFile.available()) {
ch = myFile.read();
if (ch == '\n') {
return received;
} else {
received += ch;
}
}
return received;
}
and it'll work (althrough it's not a good idea to append character by character to the String - heap memory gets fragmented really fast by this approach)
To avoid other mistakes, usage is something like:
String ssid = readLine();
String pass = readLine();
Wifi.begin(ssid.c_str(), pass.c_str());
//// definitely do not do something like:
// Wifi.begin(readLine().c_str(), readLine().c_str()); // !!! WRONG !!!
//// as the order of executing parameters isn't specified (and in the GCC it's from the last to the first)

Sim800l save input as a string

I'm trying to save my received SMS into a string but it doesn't work. This is my error message :
recive_0_1:50:28: error: invalid conversion from 'int' to 'char' [-fpermissive] exit status 1 invalid conversion from 'int' to 'char'
[-fpermissive] This report would have more information with "Show
verbose output during compilation" option enabled in File ->
Preferences.**
#include <SoftwareSerial.h>
#include <string.h>
char message[160]; // max size of an SMS
char* text;
String data;
//Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(4, 5); //SIM800L Tx & Rx is connected to Arduino #3 & #2
void setup()
{
//Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
Serial.begin(9600);
//Begin serial communication with Arduino and SIM800L
mySerial.begin(9600);
Serial.println("Initializing...");
delay(1000);
mySerial.println("AT"); //Once the handshake test is successful, it will back to OK
updateSerial();
mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
updateSerial();
mySerial.println("AT+CNMI=1,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
updateSerial();
}
void loop()
{
updateSerial();
}
void updateSerial()
{
// char c;
delay(500);
while (Serial.available())
{
mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
//char data=Serial.read();
//Serial.println(data,DEC);
}
while(mySerial.available())
{
Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
text=mySerial.read();
Serial.print(text);
//}
}
}
It looks like you're running into problems from trying to convert integers to characters. I use the below code to read from my SIM card to my SIM900 device:
1st: my software serial is defined and my setup script run:
SoftwareSerial gprsSerial(7, 8);
void setup()
{
pinMode(13, OUTPUT);
gprsSerial.begin(19200);
Serial.begin(19200);
delay(200);
// set up your AT COMMANDS HERE - I HAVE NOT INCLUDED THESE
}
Then I run my loop function as follows, calling the additional functions specified thereafter, :
void loop() {
readSMS();
delay(2000);
}
void toSerial(){
delay(200);
if(gprsSerial.available()>0){
textMessage = gprsSerial.readString();
delay(100);
Serial.print(textMessage);
}
}
void readSMS() {
textMessage = "";
gprsSerial.print("AT+CSQ\r");
toSerial();
gprsSerial.print("AT+CMGF=1\r");
toSerial();
gprsSerial.println("AT+CNMI=2,2,0,0,0\r");
delay(2000);
toSerial();
}
With the above you should not get any data type conversion hassles.

How to send float values from one bluetooth module to other(HC 05)

I am doing a project where I need to send data from ultrasonic sensor wirelessly present in one arduino to other arduino where I need these values in Serial monitor. But the problem is I cannot able to send these values through bluetooth. I tried to send one character, it is appearing in serial monitor.. But when I tried to the same for integer values it is not appearing in serial monitor.
I have configured Master and Slave modes for the Bluetooth. I have uploaded the image of the code which I am using to send these values. Please help me on this. Thanks in advance .
code
//# transmitting end
#define trigPin 12
#define echoPin 11
void setup() {
Serial.begin(38400); // Default communication rate of the Bluetooth module
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration;
float distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
Serial.println(distance,2); // Sends floatValue
delay(500);
}
//# receving end
#include <SoftwareSerial.h>
#define led 13
SoftwareSerial BTSerial(10, 11);
int data=0;
void setup() {
pinMode(led,OUTPUT);
Serial.begin(38400);
BTSerial.begin(38400); // Default communication rate of the Bluetooth module
}
void loop() {
int number;
if(Serial.available() > 0){ // Checks data is from the serial port
data = BTSerial.read(); // Reads the data from the serial port
//analogWrite(led,data);
delay(10);
//Serial.println(data);
}
Serial.println(data);
}
I need integer values at the serial monitor. But there I am getting some symbols like ?/<>..
From the Arduino reference, Serial.read() only reads the first available byte available in the Serial buffer. As an int is coded on 8 bytes, I would say that you need to read the incoming bytes sequentially in order to get the full value.
Maybe you can implement this by putting (Serial.available() > 0) in a while loop, concatenate the values you get in a char[8] for instance and then convert this char to a integer value.
Also, beware that you are sending floats and not int.
Thanks for the help..!
I modified the code in the receiver end to get the float values from the transmitter.. Here is my modified code
#include <SoftwareSerial.h>
int bluetoothTx = 10;
int bluetoothRx = 11;
String content; //content buffer to concatenate characters
char character; //To store single character
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup(){
bluetooth.begin(38400);
Serial.begin(9600);
}
void loop(){
bluetooth();
}
void bluetooth(){ //
while(bluetooth.available()){
character = bluetooth.read();
content.concat(character);
if(character == '\r'){ // find if there is carriage return
Serial.print(content); //display content (Use baud rate 9600)
content = ""; //clear buffer
Serial.println();
}
}
}

Measuring bluetooth connection force with ESP32

How can I measure the bluetooth connection force with ESP32? I'm using the available example of BLE to detect the possibility of connection, but I need to measure its strength. Thank you.
I'm using:
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
int scanTime = 30; //In seconds
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str());
}
};
void setup() {
Serial.begin(115200);
Serial.println("Scanning...");
BLEDevice::init("");
BLEScan* pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
BLEScanResults foundDevices = pBLEScan->start(scanTime);
Serial.print("Devices found: ");
Serial.println(foundDevices.getCount());
Serial.println("Scan done!");
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000);
}`
Just a few lines added to your MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks :
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str
int rssi = advertisedDevice.getRSSI();
Serial.print("Rssi: ");
Serial.println(rssi);
}
};
in wifi i am using this function:
// Take a number of measurements of the WiFi strength and return the average result.
int getStrength(int points){
long rssi = 0;
long averageRSSI=0;
for (int i=0;i < points;i++){
rssi += WiFi.RSSI(); // put your BLE function here
delay(20);
}
averageRSSI=rssi/points;
return averageRSSI;
}
and you have the same function for BLE than WiFi.RSSI(): (see in github source code)
int BLEAdvertisedDevice::getRSSI() {
return m_rssi;
} // getRSSI

Resources