Turn off analog pins if no serial data for x seconds - arduino

I have a program on my computer that sends serial data to my Arduino that dictates the analog write on the Arduino. How can I check if no new serial data has been sent for x seconds and if there isn't do something. E.G:
if (newDataInLastSeconds(10) {
// Do Something...
}```

For this problem you can use a state machine that tracks the state of the serial link, and setup actions that trigger on state transitions. If you also want to setup actions that happen every loop() depending on the state of the link, that's even easier to set up (not shown).
You're likely already checking Serial.available() to see if there are any bytes received on the serial line, correct? All you need to do is create a very simple two-state state machine:
Determine the timeout you want
Keep track of what state the data timeout is in (bool serial_fresh -- you've either received data recently or not)
Keep a record of the last time you received any data
If the serial line is fresh, compare the current time to the previous time. If greater than your timeout, then set fresh to false (this is a state transition) and do the action you want to do
If the serial line is not fresh, and you just received data, then set fresh to true (another state transition) and do the action you want to do on that transition
// start in the unfresh state, we won't transition to fresh until
// we receive the first byte - if this doesn't match what you want change to fit
bool g_serial_fresh = false;
const unsigned long SERIAL_TIMEOUT_MS = 5000; // or however many milliseconds
unsigned long g_last_serial_rx_ms = 0;
void transitionToFresh() {
g_serial_fresh = true;
/* do what you want to do when the link comes back up - turn on ADC */
}
void transitionToStale() {
g_serial_fresh = false;
/* do what you want to do when the link times out - shutdown ADC */
}
bool serialTimedOut() {
return (millis() - g_last_serial_rx_ms) > SERIAL_TIMEOUT_MS;
}
void doStateMachine() {
bool received_data_this_loop = false;
if (Serial.available() > 0) { // assumes you read all available bytes later
g_last_serial_rx_ms = millis();
received_data_this_loop = true;
}
if (!g_serial_fresh && received_data_this_loop) {
transitionToFresh();
}
else if (g_serial_fresh && serialTimedOut()) {
transitionToStale();
}
}
void loop() {
doStateMachine();
/* do regular programmy things here */
}

You can make a function with a while loop that checks for new data during a specific amount of time by using the Serial.available function:
boolean newDataInInterval(long waitInterval){
long startTime = millis();
while (millis() <= (startTime+waitInterval)) {
if (Serial.available() > 0) {
return true;
}
}
return false;
}
Note that waitInterval should be given in milliseconds.

Related

I'm using interrupts to detect button press lengths, but it will sometimes not detect that I've released the button

#include <DS3231.h>
DS3231 clock;
RTCDateTime dt;
const int INTERRUPT_PIN = 2;
int prevTime, pressedTime, releasedTime, heldTime;
bool settingTimes = false;
int startHour1, startMin1, startHour2, startMin2, endHour1, endMin1, endHour2 = 0;
void setup() {
Serial.begin(9600);
// Initialize DS3231
clock.begin();
clock.setDateTime(__DATE__, __TIME__);
pinMode(INTERRUPT_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), actButtonPress, CHANGE);
}
void loop() {
if (!settingTimes) {
dt = clock.getDateTime();
// For leading zero look to DS3231_dateformat example
Serial.print(dt.hour); Serial.print(":");
Serial.println(dt.minute);
delay(1000);
} else {
//Serial.println("Setting Times, Check the buttons");
}
}
void actButtonPress() {
if (prevTime + 100 < millis()) {
Serial.println("This is being called");
if (digitalRead(INTERRUPT_PIN) == LOW) { //Button has been pressed
pressedTime = millis();
} else {
releasedTime = millis();
heldTime = releasedTime - pressedTime;
if (heldTime > 3000) {
settingTimes = !settingTimes;
} else {
Serial.println("Change Page");
}
}
prevTime = millis();
}
}
I want to be able to press the button for 3 seconds to set times, and anything less times, I want to change pages. I need to use interrupts because the ds3231 get date time function doesn't seem to work without the delay statement (I've already tried the millis() function)
Using interrupts is generally not a good idea for checking button presses. Switch inputs should always be considered as rather dirty signals... The initial contact is never clean-cut, there is always some noise before the signal is clean. That's called "bounce".
To debounce your switch input you should either:
wait a little while using a counter, or a time stamp, (using millis) before checking if the button is released.
or only poll the switches at regular intervals.
The duration of the bounce depends on the switch, and will degrade over time as the switch gets older. In practice, 30 ms is a good value for the delay.
I suggest you try this:
#include <DS3231.h>
DS3231 clock;
RTCDateTime dt;
// putting all switch states in this struct to take advantage of bit-sized
// storage, and save RAM space for the rest of the program.
struct SwitchStates
{
unsigned char action : 1; // state of action switch.
unsigned char sw1 : 1; // add one bit for each switch you have.
};
// you need to keep track of previous switch states to detect changes.
SwitchStates previousSwitchState;
#define ACTION_SWITCH_PIN (2)
#define SWITCH_TIME_SET_DELAY (3000) // time to hold switch for setting time in ms.
#define SWITCH_POLLING_DELAY (30) // switch polling delay, in ms.
#define RTC_READ_DELAY (1000) // RTC read delay in ms.
void setup()
{
Serial.begin(9600);
// Initialize DS3231
clock.begin();
clock.setDateTime(__DATE__, __TIME__); // imho, that's not a very good idea...
pinMode(ACTION_SWITCH_PIN, INPUT_PULLUP);
digitalWrite(ACTION_SWITCH_PIN, HIGH); // you must set the pin high
// for pull-up to work.
}
// only used witin loop()
static unsigned char switchPollingTimeStamp = 0; // char because 30 is less than 256.
static bool settingTimes = false;
static unsigned int rtcReadTimeStamp = 0;
static unsigned int modeSwitchTimeStamp = 0;
void loop()
{
// get current timestamp.
unsigned long now = millis();
if ((unsigned char)now - switchPollingTimeStamp >= SWITCH_POLLING_DELAY)
{
switchPollingTimeStamp = (unsigned char)now;
// all switch inputs will be handled within this block.
SwitchStates curSwitchState;
// polling at regular intervals, first read your inputs.
curSwitchState.action = digitalRead(ACTION_SWITCH_PIN);
// curSwitchState.sw1 = digitalRead(SW1_PIN);
// etc...
// check activity on action (mode) switch and do timing, etc...
if (curSwitchState.action && !previousSwitchState.action)
{
// keep track of how long the switch has been held
modeSwitchTimeStamp = (unsigned int)now;
if (settingTimes)
settingTimes = false; // exit time set mode, for example.
else
Serial.pritln("Next Page"); //
}
else if (curSwitchState.action)
{
// after 3000 ms, switch to timeset mode.
if ((unsigned int)now - modeSwitchTimeStamp >= SWITCH_TIME_SET_DELAY)
{
if (!settingTimes)
{
settingTimes = true:
Serial.println("Entering time set mode");
}
}
}
// That was the most complex one, others should be easier
if (settingTimes)
{
if (curState.sw1 && !previousSwitchState.sw1)
{
// whatever this switch would do in set time state.
}
// etc...
}
else
{
// the same when not in set time state.
}
// to keep track of switch activity.
// by first storing current switch states, then saving them
// like this, you cannot forget one, this avoids any 'I missed one' bugs.
previousSwitchState = curSwitchState;
}
// try to keep your code non blocking, so your device stays responsive...
// in other words, avoid calling delay().
if (!settingTimes && (unsigned int)now - rtcReadTimeStamp >= RTC_READ_DELAY)
{
rtcReadTimeStamp - (unsigned int)millis();
dt = clock.getDateTime();
// For leading zero look to DS3231_dateformat example
Serial.print(dt.hour); Serial.print(":");
Serial.println(dt.minute);
}
}
Note: I don't have an arduino with me, and the laptop I have is not set up for it, so I coud not compile and debug it. It should be very close, though.

Arduino SigFox temperature data Problems

Can someone help me with this Sigfox setup?
What have I done wrong? :-)
The only thing I wanted to achieve was to post the internal temperature and the status to the sigfox backend.
Each 15min, the data would be posted.
A configured an email from the service showing the temperature in degrees Celcius.
Posting to the backend is working.
However the email message and the data seems not to correspond.
When running the code in debug mode. The temperature is showing correctly in degrees Celcius.
Is there a manual available?
Code Arduino MKR FOX 1200
Temp.ino
#include <ArduinoLowPower.h>
#include <SigFox.h>
#include "conversions.h"
// Set oneshot to false to trigger continuous mode when you finisched setting up the whole flow
int oneshot = false;
#define STATUS_OK 0
/*
ATTENTION - the structure we are going to send MUST
be declared "packed" otherwise we'll get padding mismatch
on the sent data - see http://www.catb.org/esr/structure-packing/#_structure_alignment_and_padding
for more details
*/
typedef struct __attribute__ ((packed)) sigfox_message {
int16_t moduleTemperature;
uint8_t lastMessageStatus;
} SigfoxMessage;
// stub for message which will be sent
SigfoxMessage msg;
void setup() {
if (oneshot == true) {
// Wait for the serial
Serial.begin(115200);
while (!Serial) {}
}
if (!SigFox.begin()) {
// Something is really wrong, try rebooting
// Reboot is useful if we are powering the board using an unreliable power source
// (eg. solar panels or other energy harvesting methods)
reboot();
}
//Send module to standby until we need to send a message
SigFox.end();
if (oneshot == true) {
// Enable debug prints and LED indication if we are testing
SigFox.debug();
}
}
void loop() {
// Every 15 minutes, read all the sensor and send the data
// Let's try to optimize the data format
// Only use floats as intermediate representaion, don't send them directly
//sensors_event_t event;
// Start the module
SigFox.begin();
// Wait at least 30ms after first configuration (100ms before)
delay(100);
// We can only read the module temperature before SigFox.end()
float temperature = SigFox.internalTemperature();
msg.moduleTemperature = convertoFloatToInt16(temperature, 60, -60);
if (oneshot == true) {
Serial.println("Internal temp: " + String(temperature));
}
// Clears all pending interrupts
SigFox.status();
delay(1);
SigFox.beginPacket();
SigFox.write((uint8_t*)&msg, 12);
msg.lastMessageStatus = SigFox.endPacket();
if (oneshot == true) {
Serial.println("Status: " + String(msg.lastMessageStatus));
}
SigFox.end();
if (oneshot == true) {
// spin forever, so we can test that the backend is behaving correctly
while (1) {}
}
//Sleep for 15 minutes
LowPower.sleep(1 * 60 * 1000);
}
void reboot() {
NVIC_SystemReset();
while (1);
}
Conversion.h
#define UINT16_t_MAX 65536
#define INT16_t_MAX UINT16_t_MAX/2
int16_t convertoFloatToInt16(float value, long max, long min) {
float conversionFactor = (float) (INT16_t_MAX) / (float)(max - min);
return (int16_t)(value * conversionFactor);
}
uint16_t convertoFloatToUInt16(float value, long max, long min = 0) {
float conversionFactor = (float) (UINT16_t_MAX) / (float)(max - min);
return (uint16_t)(value * conversionFactor);
}
Settings Sigfox Backend - email Callbacks
With the current convertoFloatToInt16, it will not be possible to display the real temperature in an email directly from Sigfox Backend.
You either need to use a callback from Sigfox Backend to a server that implements convertoFloatToUInt16 and then sends the email, or send the temperature in a format that the Sigfox Backend can decode natively (32-bit float is probably the most suitable).

High bit rate in Arduino Mega

I am calculating throughput of BLE module using Arduino Mega. Module works on 3.3V so i have Logic Level Shifter between BLE and Arduino. BLE UART is set at 115200 and is sending data at the speed of 64Kbps(verified using CC2540 BLE packet sniffer). Packet send by BLE are in this format in hex:400102030405060708090A0B0C0D0E0F1011121323{40=#,23=#}. I am sending 100 number of packets.Here is the abstract of my code. Code works fine for lower bit rate 32Kbps but not for 64Kbs(BLE Connection interval to 10ms). It does not show any result in this bit rate.
void loop()
{
if(rxflag)
{
rxflag = false;
switch(rxState)
{
case get_first_header:
if(rxChar=='#')
{
startPoint=millis();
rxState=get_last_header;
}
break;
case get_last_header:
if(rxChar=='#')
{
packetNo++;
if(packetNo==100)
{
endPoint=millis();
totalTime= endPoint-startPoint;
Serial.print("Total Time of Packet=");
Serial.println(totalTime);
}
break;
}
}
}
void serialEvent1()
{
if (Serial1.available()>0)
{
rxChar = (char)Serial1.read();
rxflag = true;
}
}
When you 'purge' the serial buffer:
void serialEvent1()
{
if (Serial1.available()>0)
{
rxChar = (char)Serial1.read(); // was previous value of rxChar read ? mystery...
// this is a serious problem.
// 1 byte at a time? This can slow down
rxflag = true; // reception quite a bit, esp. if there
} // is xon/xoff.
}
When you have an event that's been set in an interrupt routine, you need to reset it before reading the data, unless you use the flag as a lock for interrupt data.
Here's what you should consider to dramatically improve throughput and reduce receive errors.
void serialEvent1()
{
rxflag = true;
}
//...
void lopp()
{
// ...
if (rxflag)
{
rxflag = false; // reset/read order is to avoid stalling.
while (Serial1.available())
{
// reading 4 or up 16 bytes at a time on a local buffer
// would help the tiny mega get this done job done faster.
//
// char buffer[8] buffer; // 2 dwords on the stack. don't overuse!
//
char c = (char)Serial.read();
// run state machine...
}
}
// ...
}

Arduino - weird terminal output

I'm trying to test NRF24L01+ module with example I've found on web.
Here's my code:
/*
Copyright (C) 2011 J. Coliz <maniacbug#ymail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
*/
/**
* Example for Getting Started with nRF24L01+ radios.
*
* This is an example of how to use the RF24 class. Write this sketch to two
* different nodes. Put one of the nodes into 'transmit' mode by connecting
* with the serial monitor and sending a 'T'. The ping node sends the current
* time to the pong node, which responds by sending the value back. The ping
* node can then see how long the whole cycle took.
*/
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
//
// Hardware configuration
//
// Set up nRF24L01 radio on SPI bus plus pins 9 & 10
RF24 radio(9,10);
//
// Topology
//
// Radio pipe addresses for the 2 nodes to communicate.
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
//
// Role management
//
// Set up role. This sketch uses the same software for all the nodes
// in this system. Doing so greatly simplifies testing.
//
// The various roles supported by this sketch
typedef enum { role_ping_out = 1, role_pong_back } role_e;
// The debug-friendly names of those roles
const char* role_friendly_name[] = { "invalid", "Ping out", "Pong back"};
// The role of the current running sketch
role_e role = role_pong_back;
void setup(void)
{
//
// Print preamble
//
Serial.begin(57600);
printf_begin();
printf("\n\rRF24/examples/GettingStarted/\n\r");
printf("ROLE: %s\n\r",role_friendly_name[role]);
printf("*** PRESS 'T' to begin transmitting to the other node\n\r");
//
// Setup and configure rf radio
//
radio.begin();
// optionally, increase the delay between retries & # of retries
radio.setRetries(15,15);
// optionally, reduce the payload size. seems to
// improve reliability
//radio.setPayloadSize(8);
//
// Open pipes to other nodes for communication
//
// This simple sketch opens two pipes for these two nodes to communicate
// back and forth.
// Open 'our' pipe for writing
// Open the 'other' pipe for reading, in position #1 (we can have up to 5 pipes open for reading)
//if ( role == role_ping_out )
{
//radio.openWritingPipe(pipes[0]);
radio.openReadingPipe(1,pipes[1]);
}
//else
{
//radio.openWritingPipe(pipes[1]);
//radio.openReadingPipe(1,pipes[0]);
}
//
// Start listening
//
radio.startListening();
//
// Dump the configuration of the rf unit for debugging
//
radio.printDetails();
}
void loop(void)
{
//
// Ping out role. Repeatedly send the current time
//
if (role == role_ping_out)
{
// First, stop listening so we can talk.
radio.stopListening();
// Take the time, and send it. This will block until complete
unsigned long time = millis();
printf("Now sending %lu...",time);
bool ok = radio.write( &time, sizeof(unsigned long) );
if (ok)
printf("ok...");
else
printf("failed.\n\r");
// Now, continue listening
radio.startListening();
// Wait here until we get a response, or timeout (250ms)
unsigned long started_waiting_at = millis();
bool timeout = false;
while ( ! radio.available() && ! timeout )
if (millis() - started_waiting_at > 200 )
timeout = true;
// Describe the results
if ( timeout )
{
printf("Failed, response timed out.\n\r");
}
else
{
// Grab the response, compare, and send to debugging spew
unsigned long got_time;
radio.read( &got_time, sizeof(unsigned long) );
// Spew it
printf("Got response %lu, round-trip delay: %lu\n\r",got_time,millis()-got_time);
}
// Try again 1s later
delay(1000);
}
//
// Pong back role. Receive each packet, dump it out, and send it back
//
if ( role == role_pong_back )
{
// if there is data ready
if ( radio.available() )
{
// Dump the payloads until we've gotten everything
unsigned long got_time;
bool done = false;
while (!done)
{
// Fetch the payload, and see if this was the last one.
done = radio.read( &got_time, sizeof(unsigned long) );
// Spew it
printf("Got payload %lu...",got_time);
// Delay just a little bit to let the other unit
// make the transition to receiver
delay(20);
}
// First, stop listening so we can talk
radio.stopListening();
// Send the final one back.
radio.write( &got_time, sizeof(unsigned long) );
printf("Sent response.\n\r");
// Now, resume listening so we catch the next packets.
radio.startListening();
}
}
//
// Change roles
//
if ( Serial.available() )
{
char c = toupper(Serial.read());
if ( c == 'T' && role == role_pong_back )
{
printf("*** CHANGING TO TRANSMIT ROLE -- PRESS 'R' TO SWITCH BACK\n\r");
// Become the primary transmitter (ping out)
role = role_ping_out;
radio.openWritingPipe(pipes[0]);
radio.openReadingPipe(1,pipes[1]);
}
else if ( c == 'R' && role == role_ping_out )
{
printf("*** CHANGING TO RECEIVE ROLE -- PRESS 'T' TO SWITCH BACK\n\r");
// Become the primary receiver (pong back)
role = role_pong_back;
radio.openWritingPipe(pipes[1]);
radio.openReadingPipe(1,pipes[0]);
}
}
}
// vim:cin:ai:sts=2 sw=2 ft=cpp
My problem is that after I run this code, on serial port monitor (inside arduino IDE) I'm getting weird chars, it looks like that:
I've tried on two different Arduinos, Nano and Uno (both are Chinese copy), results are the same, so it's probably something with my code.
Can you tell me what is wrong with it?
Here is your mistake:
Serial.begin(57600);
Data rate in bits per seconds (baud) that you set for serial data transmission in Serial.begin() function must match the BAUD rate on the Serial monitor. Change the code to Serial.begin(9600) or the value in the bottom right corner of the serial monitor window to 57600.

Arduino Loop and alarm

I'm working on my first physical computing project with an arduino, well actually a seeduino stalker 2.1. I'm building a device to record water collection rates over time.
Getting the project set up and running hasn't been all that hard, until today that is. Inside the main loop I have a call to the a method that handles the logging. I also now an alarm delay to handle a timer repeat I need in order to summarize data and send it via SMS to a recipient number.
The issue is that when the alarm.repeat() is active it preempts the logging of the data. The question is: why is the logging method inside the loop not working when the alarm.delay is there?
void setup() {
Serial.begin(9600);
Wire.begin();
setTime(1,17,0,1,1,13); // set time
Alarm.timerRepeat(60, Repeats); //set repeater
}
void loop(){
logging(); //call logging
Alarm.delay(1300); //for repeater
}
void Repeats(){
Serial.println("the repeater fired"); // just to see it working
}
void logging(){
val = digitalRead(Sensor_Pin); // read Sensor_Pin
if (val == HIGH) {
// If Sensor N.C. (no with magnet) -> HIGH : Switch is open / LOW : Switch is closed
// If Sensor N.0. (nc with magnet) -> HIGH : Switch is closed / LOW : Switch is open
digitalWrite(Led_Pin, LOW); //Set Led low
//Serial.print("status -->");
//Serial.println("low");
//delay(500);
} else {
digitalWrite(Led_Pin, HIGH); //Set Led high
logdata();
}
}
void logdata(){
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File myFile = SD.open("datalog.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
//DateTime now = RTC.now();
//String myString = readTimestamp(now);
time_t t = now();
String aDate = String(year(t))+"/"+String(month(t))+"/"+String(day(t))+" "+String(hour(t))+":"+String(minute(t))+":"+String(second(t));
myFile.println(aDate);
// close the file:
myFile.close();
Serial.println(aDate);
delay(500); } else {
// if the file didn't open, print an error:
// Serial.println("error opening DATALOG.TXT");
}
}
Q: Why must I use Alarm.delay() instead of delay()? A: Task scheduling
is handled in the Alarm.delay function. Tasks are monitored and
triggered from within the Alarm.delay call so Alarm.delay should be
called whenever a delay is required in your sketch. If your sketch
waits on an external event (for example, a sensor change), make sure
you repeatedly call Alarm.delay while checking the sensor.
From the FAQ of the Alarm library. So it looks like Alarm.Delay is just like the standard delay but can be interrupted by scheduled events. Your logging call isn't scheduled, it just happens at the start of the loop. ..is your logging not happening at all? It looks like it should be called at the start of each loop, then a 1300 delay with your repeater firing during the delay.
On your logdata() function you're calling delay(50) instead of Alarm.delay(50).
As caude pointed, you have to use Alarm.delay when a delay is needed, otherwise the delay will mess up with the alarms.
I think you could have done in other way using timer library. If you say the data has to be logged every second,it easier to done by timer.Example code
#include <SimpleTimer.h>
// the timer object
SimpleTimer timer;
// a function to be executed periodically
void repeatMe() {
Serial.print("Uptime (s): ");
Serial.println(millis() / 1000);
}
void setup() {
Serial.begin(9600);
timer.setInterval(1000, repeatMe);
}
void loop() {
timer.run();
}

Resources