how can i add a date with the value of sensor in my serial monitor - c++

I want to display the date on my serial monitor with the value of sensor
heres the code:
int redpin= 13;
int greenled = 7;
int buzzer = 11;
int gasA0 = A0;
// Your threshold value
int sensorThres = 400;
int date = date;
void setup() {
pinMode(greenled, OUTPUT);
pinMode(redpin, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(gasA0, INPUT);
Serial.begin(9600);
}
void loop() {
int analogSensor = analogRead(gasA0);
Serial.print(" ");
Serial.println(analogSensor);
// Checks if it has reached the threshold value
if (analogSensor > sensorThres)
{
digitalWrite(greenled,LOW);//green led stay
digitalWrite(redpin,HIGH); //turns on led and buzzer
tone(buzzer,100);
}
else
{
digitalWrite(redpin,LOW); //turns off led and buzzer
digitalWrite(greenled,HIGH);//green led stay
noTone(buzzer);
}
delay(400);
}
I try to create a device that will detect a gas but I want to display the current date in my serial monitor continuously

The time value is prepended by the Arduino Serial Monitor to every line received from Arduino. If you copy the lines from Serial Monitor to Excel, just add a column with the date in Excel directly.
If you want the Arduino to print the timestamp, then you can use the Arduino Time library and some source of time. The source of time can be manual entry, a RTC module or with a networking module you could retrieve time from a time server. See the examples of the Time library

Related

Arduino .read() function interfering with BLE connection

Firstly, I want to apologize as I am new to BLE connectivity and much of Arduino programming. I am busy with a project which in involved making a smart coffee scale which can output data to a smartphone via a BLE connection. I am working with an Arduino nano 33 IoT, and an hx711 load cell amplifier.
I need to create a program where I can send and receive data to and from the Arduino to the smartphone app. I have used standard ArduinoBLE peripheral libraries such as the "BatteryMonitor" sketch and the "ButtonLED" sketch. By combining both of these example sketches together I have managed to established a connection where I can send and receive data.
The problem arises when I try to use functions within the HX711 library such as scale.read(); to retrieve values being output from the hx711 amplifier. When I use a serial read function such as scale.read() the bluetooth connection fails before establishing itself properly. I imagine this is due to the scale.read() function interfering with the serial data being transmitted and received by the Arduino, but I have no clue how to get around this problem.
I basically want to change the battery monitor output to be the output of the value read from the hx711 load cell amplifier but I am struggling to get this to work.
#include "HX711.h"
#include <ArduinoBLE.h>
HX711 scale;
BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // BLE LED Service
// BLE LED Switch Characteristic - custom 128-bit UUID, read and writable by central
BLEByteCharacteristic switchCharacteristic("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
BLEUnsignedCharCharacteristic batteryLevelChar("2A19", // standard 16-bit characteristic UUID
BLERead | BLENotify); // remote clients will be able to get notifications if this characteristic changes
int oldBatteryLevel = 0; // last battery level reading from analog input
long previousMillis = 0; // last time the battery level was checked, in ms
const int ledPin = LED_BUILTIN; // pin to use for the LED
double val;
void setup() {
Serial.begin(9600);
scale.begin(A1, A0); //Initialized scale on these pins
while (!Serial);
scale.set_scale(432.f); // this value is obtained by calibrating the scale with known weights; see the README for details
scale.tare(); // reset the scale to 0
// set LED pin to output mode
pinMode(ledPin, OUTPUT);
// begin initialization
if (!BLE.begin()) {
Serial.println("starting BLE failed!");
while (1);
}
// set advertised local name and service UUID:
BLE.setLocalName("COFFEE");
BLE.setAdvertisedService(ledService);
// add the characteristic to the service
ledService.addCharacteristic(switchCharacteristic);
ledService.addCharacteristic(batteryLevelChar); // add the battery level characteristic
// add service
BLE.addService(ledService);
// set the initial value for the characeristic:
switchCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
Serial.println("BLE LED Peripheral");
}
void loop()
{
// listen for BLE peripherals to connect:
BLEDevice central = BLE.central();
// if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
// while the central is still connected to peripheral:
while (central.connected())
{
// Battery Monitor
// scale.read();
long currentMillis = millis();
// if 200ms have passed, check the battery level:
if (currentMillis - previousMillis >= 200) {
previousMillis = currentMillis;
// scale.read(); // This function alone will prevent the BLE connection from establishing properly.
updateBatteryLevel();
// outputScale();
}
// if the remote device wrote to the characteristic,
// use the value to control the LED:
if (switchCharacteristic.written()) {
if (switchCharacteristic.value()) { // any value other than 0
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // will turn the LED on
} else { // a 0 value
Serial.println(F("LED off"));
digitalWrite(ledPin, LOW); // will turn the LED off
}
}
}
// when the central disconnects, print it out:
Serial.print(F("Disconnected from central: "));
Serial.println(central.address());
}
}
void updateBatteryLevel()
{
/* Read the current voltage level on the A0 analog input pin.
This is used here to simulate the charge level of a battery.
*/
int battery = analogRead(A0);
int batteryLevel = map(battery, 0, 1023, 0, 100);
if (batteryLevel != oldBatteryLevel) { // if the battery level has changed
// Serial.print("Battery Level % is now: "); // print it
Serial.println(batteryLevel);
batteryLevelChar.writeValue(batteryLevel); // and update the battery level characteristic
oldBatteryLevel = batteryLevel; // save the level for next comparison
}
}
void outputScale(){
int t, i, n, T;
double val, sum, sumsq, mean;
float stddev;
n = 20;
t = millis();
i = sum = sumsq = 0;
while (i<n) {
val = ((scale.read() - scale.get_offset()) / scale.get_scale());
sum += val;
sumsq += val * val;
i++;
}
t = millis() - t;
mean = sum / n;
stddev = sqrt(sumsq / n - mean * mean);
// Serial.print("Mean, Std Dev of "); Serial.print(i); Serial.print(" readings:\t");
Serial.print(sum / n, 3); Serial.print("\n"); // Serial.print(stddev, 3);
// Note: 2 sigma is 95% confidence, 3 sigma is 99.7%
//Serial.print("\nTime taken:\t"); Serial.print(float(t)/1000, 3); Serial.println("Secs\n");
/*
scale.power_down(); // put the ADC in sleep mode
delay(5000);
scale.power_up();
*/
}
You are initialising as scale.begin(A1, A0) while trying to read from the same A0 pin.

Setting delay for capacitive touch sensor to prevent "double press"

I am building a number numpad using 3 different capacitive touch sensor. So my function will be to label each the 3 touch sensors with a different number to create a password system.
However i realised that whenever i try to press the button to key in the number, for example the button tagged with number "3", multple values of 3 came out even though i only pressed once. Is there any function on arduino that i can use so that it only generate 1 results with 1 press instead of multiple results in a press.
Is there anyway to change my code such that i can create some sort of debounce for each button so that when i press the button once only 1 result will be shown.
Would appreciate an edit on my code, thanks!
#include <LiquidCrystal.h>
#include <CapacitiveSensor.h>
CapacitiveSensor cs_2_3= CapacitiveSensor(2,3);
CapacitiveSensor cs_2_4= CapacitiveSensor(2,4);
CapacitiveSensor cs_2_5= CapacitiveSensor(2,5);
int pos=0;
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);
char pass[]= "321";
int currentposition=0;
char code=0;
void setup() {
cs_2_3.set_CS_AutocaL_Millis(0xFFFFFFFF);
lcd.setCursor(0,0);
lcd.println("Enter Password: ");
Serial.begin(9600);
lcd.begin(16,2);
}
void loop() {
long total1= cs_2_3.capacitiveSensor(100);
long total2=cs_2_4.capacitiveSensor(100);
long total3= cs_2_5. capacitiveSensor(100);
if(total1>=1000)
{
code= '1';
}
if(total2>=1000)
{
code= '2';
}
if(total3>=1000)
{
code='3';
}
delay(100);
if(currentposition==0)
{
lcd.setCursor(0,0);
lcd.println("Enter Password: ");
}
int lu ;
if(code!=0)
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("PASSWORD:");
lcd.setCursor(7,1);
lcd.print(" ");
lcd.setCursor(7,1);
for(lu=0;lu<=currentposition;++lu)
{
lcd.print(code);
delay(25);
}
if (code==pass[currentposition])
{
++currentposition;
if(currentposition==3)
{
delay(900);
lcd.setCursor(0,0);
lcd.println(" ");
lcd.setCursor(1,0);
lcd.print("Correct Password");
lcd.setCursor(4,1);
lcd.println("HELLO!!");
lcd.setCursor(15,1);
lcd.println(" ");
lcd.setCursor(16,1);
lcd.println(" ");
lcd.setCursor(14,1);
lcd.println(" ");
lcd.setCursor(13,1);
lcd.println(" ");
delay (5000);
lcd.clear();
lcd.setCursor(0,0);
lcd.println("Enter Password: ");
}
}
else
{
delay(500);
lcd.clear();
lcd.setCursor(1,0);
lcd.print("PASSWORD");
lcd.setCursor(6,0);
lcd.print("INCORRECT");
lcd.setCursor(15,1);
lcd.println(" ");
lcd.setCursor(4,1);
lcd.println("GET AWAY!!!");
code=0;
lcd.setCursor(13,1);
lcd.println(" ");
delay(3000);
currentposition=0;
lcd.clear();
lcd.setCursor(0,0);
lcd.println("Enter Password: ");
}
}
}
Just debounce it like any other button. Only accept signal changes longer then a certain time.
From https://www.arduino.cc/en/tutorial/debounce
/*
Debounce
Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
press), the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a
minimum delay between toggles to debounce the circuit (i.e. to ignore noise).
The circuit:
- LED attached from pin 13 to ground
- pushbutton attached from pin 2 to +5V
- 10 kilohm resistor attached from pin 2 to ground
- Note: On most Arduino boards, there is already an LED on the board connected
to pin 13, so you don't need any extra components for this example.
created 21 Nov 2006
by David A. Mellis
modified 30 Aug 2011
by Limor Fried
modified 28 Dec 2012
by Mike Walters
modified 30 Aug 2016
by Arturo Guadalupi
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Debounce
*/
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
// set initial LED state
digitalWrite(ledPin, ledState);
}
void loop() {
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
// set the LED:
digitalWrite(ledPin, ledState);
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
}
You could use INPUT_PULLUP like this:
void setup() {
pinMode(pin, INPUT_PULLUP)
}
But since your using i library this may be an issue.
You could simply use the delay() function, as stated here: https://www.brainy-bits.com/arduino-switch-debounce/
This might be the fastest and simplest way to do it.
Debouncing the button will help - Adafruit got something especially on this topic: https://learn.adafruit.com/make-it-switch/debouncing
But for a quick and dirty solution delay() will do.

Debugging Arduino Uno code running on Arduino MKR1000

So, I am an amateur programmer at Arduino, and have never used Arduino MKR1000 before. I used an Arduino Uno and wrote the attached code that detects heart beat and temperature using the Grove Ear clip heart beat sensor and the Grove Temperature sensor and then prints them in the console every 20 seconds. Previously, this code was written to show in an Grove OLED screen but later simplified it back to using it by reading on just the console.
Because of the wearable nature of my project I have to switch to using a MKR1000 instead. I know the MKR1000 uses the same Arduino code and should work the same way as it did on my Arduino Uno, but I have been having some issues with using the MKR1000 with the same code.
The issue is that the code only runs once and stops after that. While I am aware of the for loops and how it works to certain extent, I cannot find the exact issue why it stops looping instead of taking the data constantly and publishing it on the console, like it did previously with my Uno.
Just for the heads up, following is how my code reacted to Arduino Uno:
The result in the console shows:
Please be ready
This will now begin
then it prints number 1 to 20 every second followed by sensor readings. After publishing this, it repeats this process again.
Again sorry for the inconvenience and thank you for your help.
I used direct codes from the documentation blog of the sensors (bottom of the page of the linked page):
Grove heart bear sensor
Grove Temperature sensor
#define LED 4//indicator, Grove - LED is connected with D4 of Arduino
boolean led_state = LOW;//state of LED, each time an external interrupt
//will change the state of LED
float tempa;
int tempPin = 0;
unsigned char counter;
unsigned long temp[21];
unsigned long sub;
bool data_effect=true;
unsigned int heart_rate;//the measurement result of heart rate
const int max_heartpluse_duty = 2000;//you can change it follow your system's request.
//2000 meams 2 seconds. System return error
//if the duty overtrip 2 second.
void setup()
{
pinMode(LED, OUTPUT);
Serial.begin(9600);
while (!Serial){
;
}
Serial.println("Please be ready");
delay(5000);
arrayInit();
Serial.println("This will now begin.");
attachInterrupt(0, interrupt, RISING);//set interrupt 0,digital port 2
}
void loop()
{
digitalWrite(LED, led_state);//Update the state of the indicator
}
/*Function: calculate the heart rate*/
void sum()
{
if(data_effect)
{
heart_rate=1200000/(temp[20]-temp[0]);//60*20*1000/20_total_time
Serial.print("Heart_rate_is:\t");
Serial.println(heart_rate);
tempa = analogRead(tempPin);
tempa = tempa * 0.11;
Serial.print("Body Temperature = ");
Serial.print(tempa);
Serial.print("*C");
Serial.println();
delay(1000);
}
data_effect=1;//sign bit
}
/*Function: Interrupt service routine.Get the sigal from the external interrupt*/
void interrupt()
{
temp[counter]=millis();
Serial.println(counter,DEC);
switch(counter)
{
case 0:
sub=temp[counter]-temp[20];
break;
default:
sub=temp[counter]-temp[counter-1];
break;
}
if(sub>max_heartpluse_duty)//set 2 seconds as max heart pluse duty
{
data_effect=0;//sign bit
counter=0;
Serial.println("measurement error,test will restart!" );
arrayInit();
}
else if (counter==20&&data_effect)
{
counter=0;
sum();
}
else if(counter!=20&&data_effect)
{
counter++;
}
else
{
counter=0;
data_effect=1;
}
}
/*Function: Initialization for the array(temp)*/
void arrayInit()
{
for(unsigned char i=0;i < 20;i ++)
{
temp[i]=0;
}
temp[20]=millis();
}
Your problem is the interrupt pin. On the Arduino UNO the digital pin D2 is interrupt pin 0, as you have done in your code. On the Arduino MKR1000 the interrupt pin is tha same as the physical pin number, so if you'r connecting to pin 2, change attachInterrupt(0, interrupt, RISING); to attachInterrupt(2, interrupt, RISING);
If you wanna be sure to use the right pin you can use digitalPinToInterrupt(pin) to get the correct interrupt number on any Arduino board. Like this attachInterrupt(digitalPinToInterrupt(pin), interrupt, RISING); where pin is the physical pin number.
Info
On the Arduino MKR1000 you can use pin 0, 1, 4, 5, 6, 7, 8, 9, A1 and A2 as interrupt

Arduino Uno to Particle Photon - Converting Code

Please bear with me. I am an amateur programmer at Arduino, and have never used Particle photon before.
I used an Arduino Uno and wrote the attached code that detects heart beat and temperature using the Grove Ear clip heart beat sensor and the Grove Temperature sensor and then prints them in the console every 20 seconds. Previously, this code was written to show in an Grove OLED screen but later simplified it back to using it without the OLED screen.
I am now looking into using the same application and function using the same sensor on a Particle Photon (as it is smaller and has WiFi capability). I have never previously used this technology before but I saw online that it, more or less, uses the same code application. I have been through the sample codes for this online available on its website but I have no idea how to convert my code for the Arduino into code for the photon (Photon console compiles the code without any error but does not show any sensor data). Can someone either point me to the right direction/ appropriate online resources / help me change this code here to make it work on the Photon? (I just added the Particle.publish() wherever I was using Arduino's Serial.println() but it still doesn't print anything).
The result in the console shows:
Please be ready
This will now begin
then it prints number 1 to 20 every second followed by sensor readings.
Again sorry for the inconvenience and thank you for your help.
I used direct codes from the documentation blog of the sensors (bottom of the page of the linked page):
Grove heart bear sensor
Grove Temperature sensor
#define LED 4//indicator, Grove - LED is connected with D4 of Arduino
boolean led_state = LOW;//state of LED, each time an external interrupt
//will change the state of LED
float tempa;
int tempPin = 0;
unsigned char counter;
unsigned long temp[21];
unsigned long sub;
bool data_effect=true;
unsigned int heart_rate;//the measurement result of heart rate
const int max_heartpluse_duty = 2000;//you can change it follow your system's request.
//2000 meams 2 seconds. System return error
//if the duty overtrip 2 second.
void setup()
{
pinMode(LED, OUTPUT);
Serial.begin(9600);
while (!Serial){
;
}
Serial.println("Please be ready");
delay(5000);
arrayInit();
Serial.println("This will now begin.");
attachInterrupt(0, interrupt, RISING);//set interrupt 0,digital port 2
}
void loop()
{
digitalWrite(LED, led_state);//Update the state of the indicator
}
/*Function: calculate the heart rate*/
void sum()
{
if(data_effect)
{
heart_rate=1200000/(temp[20]-temp[0]);//60*20*1000/20_total_time
Serial.print("Heart_rate_is:\t");
Serial.println(heart_rate);
tempa = analogRead(tempPin);
tempa = tempa * 0.11;
Serial.print("Body Temperature = ");
Serial.print(tempa);
Serial.print("*C");
Serial.println();
delay(1000);
}
data_effect=1;//sign bit
}
/*Function: Interrupt service routine.Get the sigal from the external interrupt*/
void interrupt()
{
temp[counter]=millis();
Serial.println(counter,DEC);
switch(counter)
{
case 0:
sub=temp[counter]-temp[20];
break;
default:
sub=temp[counter]-temp[counter-1];
break;
}
if(sub>max_heartpluse_duty)//set 2 seconds as max heart pluse duty
{
data_effect=0;//sign bit
counter=0;
Serial.println("measurement error,test will restart!" );
arrayInit();
}
else if (counter==20&&data_effect)
{
counter=0;
sum();
}
else if(counter!=20&&data_effect)
{
counter++;
}
else
{
counter=0;
data_effect=1;
}
}
/*Function: Initialization for the array(temp)*/
void arrayInit()
{
for(unsigned char i=0;i < 20;i ++)
{
temp[i]=0;
}
temp[20]=millis();
}

Arduino not reading float level switch signal

Hey I am trying to set up a project at the moment, I have a float level switch connected to pin 2 of my Arduino board, the other end is connected to the 5v in on the arduino.
I want to have the software display a message when the switch goes high but at the moment it goes straight to the message and I know that the switch is not set high as I have it in my hand.
In future it will send a text message when the signal goes high, being used for flood monitoring using a float level switch.
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "sms.h"
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];
int closed=0;//Sets initial signal to 0
const int switchPin = 2;
int switchState = 0; // current state of the button
int lastswitchState = 0; // previous state of the button
void setup()
{
//Serial connection.
Serial.begin(9600);
Serial.println("GSM Shield for Flood Early Warning System \n");
pinMode(switchPin, INPUT);
//Start configuration of shield with baudrate.
//For http uses is recommended to use 4800 or slower.
}
void loop() {
closed=digitalRead(switchPin);
// compare the buttonState to its previous state
if (switchState != lastswitchState) {
// if the state has changed, increment the counter
if (switchState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
Serial.println("on");
} else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state,
//for next time through the loop
lastswitchState = switchState;
if (closed == HIGH) {
Serial.println ("Switch signal received");
if (gsm.begin(2400)){
Serial.println("\n status=READY");
started=true;
}
else Serial.println("\n status=IDLE");
if(started){
//Enable this two lines if you want to send an SMS.
if (sms.SendSMS("0871234567", "Arduino SMS"))//Number you wish to text and the message to be sent
Serial.println("\nSMS sent OK");//Alert for Serial monitor once sms sent
}
}
}
You should connect your input pin to GND via a 10KOhm resistor. See https://www.arduino.cc/en/Tutorial/DigitalPins :
"This also means however, that pins configured as pinMode(pin, INPUT) with nothing connected to them, ... will report seemingly random changes in pin state, picking up electrical noise from the environment, or capacitively coupling the state of a nearby pin. ".
And https://www.arduino.cc/en/Reference/DigitalRead :
If the pin isn't connected to anything, digitalRead() can return either HIGH or LOW (and this can change randomly).
In other words, when your switch is open, the input pin is not in a defined state (either on or off). By adding a pulldown resistor (a 10 KOhm resistor between your input pin and GND, the resistor "pulls down" (=toward the ground) your pin, unless the switch is closed, in which case the connection to +5V prevails (because it is a direct connection, without a resistor).