text:
what is the difference between array of uint16_t data versus an array of uint16_t variables?
I've been struggling with weird behavior, crashes and general problems when trying to use an array of four uint16_t groups of data. When I create four separate variables and load that into an array, it works OK and is smaller.
This is for use with the irlib2 SendBase and HashRaw components.
What's going on here?
The code utterly fails with crashes, unresponsive hardware when I use the following variable assignment with an arduino micro. Additionally this version uses about 400 bytes more of memory than the second example
failed variable assignemnt
uint16_t sources[4][RAW_DATA_LEN] = {
  {8550, 4306, 530, 1606, 530, 566, 502, 1610, //POWER ON/OFF
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000},

  {8546, 4310, 558, 1578, 562, 538, 498, 1638, //sourceCD
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000},

  {8550, 4306, 530, 1606, 534, 566, 502, 1606,  //sourceCDR
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000},

  {8550, 4310, 526, 1634, 506, 566, 502, 1634,  //sourceAUX
  506, 566, 502, 574, 506, 1626, 510, 566,
  506, 1630, 506, 566, 502, 1634, 506, 566,
  502, 1634, 506, 1606, 530, 566, 506, 1630,
  506, 566, 502, 1634, 506, 1630, 506, 1630,
  510, 1602, 526, 570, 510, 566, 502, 1634,
  502, 570, 502, 570, 510, 566, 502, 570,
  510, 562, 506, 1630, 506, 1630, 510, 562,
  506, 1630, 510, 1000}
} ;

When I instead assign each grouping to a variable and then create an array of those variables, the code is significantly smaller (about 400 bytes) and appears to run as expected without crashes.
Successful variable assignment
#define RAW_DATA_LEN 68
uint16_t powerOnOff[RAW_DATA_LEN] = {
  8550, 4306, 530, 1606, 530, 566, 502, 1610,
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000
};

uint16_t sourceCD[RAW_DATA_LEN] = {
  8546, 4310, 558, 1578, 562, 538, 498, 1638,
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000
};

uint16_t sourceAUX[RAW_DATA_LEN] = {
  8550, 4310, 526, 1634, 506, 566, 502, 1634,
  506, 566, 502, 574, 506, 1626, 510, 566,
  506, 1630, 506, 566, 502, 1634, 506, 566,
  502, 1634, 506, 1606, 530, 566, 506, 1630,
  506, 566, 502, 1634, 506, 1630, 506, 1630,
  510, 1602, 526, 570, 510, 566, 502, 1634,
  502, 570, 502, 570, 510, 566, 502, 570,
  510, 562, 506, 1630, 506, 1630, 510, 562,
  506, 1630, 510, 1000
};

uint16_t sourceCDR[RAW_DATA_LEN] = {
  8550, 4306, 530, 1606, 534, 566, 502, 1606,
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000
};

//Set up array of codes
uint16_t sources[4] = {powerOnOff, sourceCD, sourceCDR, sourceAUX};

This is the code as it stands in an unfinished state. In an effort to trace back the crashes and odd behavior I systematically removed most of the code to the point where the last if statement is sending the IR codes.
Entire Code
#include <movingAvg.h>    // moving average library
#include <IRLibSendBase.h>    //We need the base code
#include <IRLib_HashRaw.h>    //Only use raw sender
#include <elapsedMillis.h>    //measure elapsed time

// ====REMOTE CODES====
//define the IR Sender
IRsendRaw mySender;
#define RAW_DATA_LEN 68
uint16_t powerOnOff[RAW_DATA_LEN] = {
  8550, 4306, 530, 1606, 530, 566, 502, 1610,
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000
};

uint16_t sourceCD[RAW_DATA_LEN] = {
  8546, 4310, 558, 1578, 562, 538, 498, 1638,
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000
};

//uint16_t sourceAUX[RAW_DATA_LEN] = {
//  8550, 4310, 526, 1634, 506, 566, 502, 1634,
//  506, 566, 502, 574, 506, 1626, 510, 566,
//  506, 1630, 506, 566, 502, 1634, 506, 566,
//  502, 1634, 506, 1606, 530, 566, 506, 1630,
//  506, 566, 502, 1634, 506, 1630, 506, 1630,
//  510, 1602, 526, 570, 510, 566, 502, 1634,
//  502, 570, 502, 570, 510, 566, 502, 570,
//  510, 562, 506, 1630, 506, 1630, 510, 562,
//  506, 1630, 510, 1000
//};

uint16_t sourceCDR[RAW_DATA_LEN] = {
  8550, 4306, 530, 1606, 534, 566, 502, 1606,
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000
};

//Set up array of codes
uint16_t *sources[3] = {powerOnOff, sourceCD, sourceCDR};//, sourceAUX};

//This causes some sort of horrible crash - maybe an overflow of the uint16 data type?
//#define RAW_DATA_LEN 68
//uint16_t sources[4][RAW_DATA_LEN] = {
//  {8550, 4306, 530, 1606, 530, 566, 502, 1610, //POWER ON/OFF
//  530, 566, 502, 574, 506, 1630, 506, 566,
//  506, 1630, 506, 566, 502, 1610, 530, 566,
//  502, 1634, 506, 1606, 530, 570, 498, 1634,
//  506, 570, 510, 562, 506, 566, 502, 1634,
//  506, 1606, 530, 1610, 530, 562, 538, 538,
//  530, 542, 538, 1598, 538, 1570, 558, 542,
//  538, 538, 530, 542, 538, 1598, 530, 1578,
//  558, 1578, 562, 1000},
//
//  {8546, 4310, 558, 1578, 562, 538, 498, 1638, //sourceCD
//  530, 542, 506, 570, 502, 1634, 502, 570,
//  498, 1638, 534, 538, 498, 1638, 530, 542,
//  506, 1606, 554, 1582, 558, 538, 510, 1602,
//  554, 546, 506, 566, 502, 570, 510, 1602,
//  554, 1582, 558, 538, 510, 566, 502, 1606,
//  554, 546, 502, 1610, 558, 1574, 554, 546,
//  502, 570, 510, 1602, 526, 1610, 526, 574,
//  506, 1602, 526, 1000},
//
//
//  {8550, 4306, 530, 1606, 534, 566, 502, 1606,  //sourceCDR
//  534, 566, 502, 570, 510, 1602, 526, 570,
//  510, 1602, 534, 566, 502, 1606, 534, 566,
//  506, 1602, 530, 1606, 534, 566, 502, 1610,
//  530, 570, 498, 574, 506, 566, 502, 570,
//  510, 1602, 526, 570, 510, 566, 502, 570,
//  510, 1602, 526, 1610, 526, 1606, 534, 1602,
//  534, 566, 502, 1610, 530, 1602, 534, 1602,
//  526, 574, 506, 1000},
//
//  {8550, 4310, 526, 1634, 506, 566, 502, 1634,  //sourceAUX
//  506, 566, 502, 574, 506, 1626, 510, 566,
//  506, 1630, 506, 566, 502, 1634, 506, 566,
//  502, 1634, 506, 1606, 530, 566, 506, 1630,
//  506, 566, 502, 1634, 506, 1630, 506, 1630,
//  510, 1602, 526, 570, 510, 566, 502, 1634,
//  502, 570, 502, 570, 510, 566, 502, 570,
//  510, 562, 506, 1630, 506, 1630, 510, 562,
//  506, 1630, 510, 1000}
//} ;

// ====PIN ASSIGNMENTS====
const int audioPin1 = A1;     //Channel 1
const int audioPin2 = A2;
const int debugPin = A3;     //when low, run in debug mode
const int statusLight = 10;   //active channel indicator light

//  ====CHANNEL MEASUREMENTS====
# define CHANNELS 3     //number of channels to sample from
int audioChannels[CHANNELS] = {audioPin1, audioPin1, audioPin2};      //element 0 will be ignored
int channelValues[CHANNELS] = {0, 0, 0};
const int SAMPLES = 300;
movingAvg audioAverages[CHANNELS] = {movingAvg(SAMPLES), movingAvg(SAMPLES), movingAvg(SAMPLES)};

//  ====CHANNEL VARIABLES====
int currentChannel = 0;     //channel that is currently active (0 is off)
int previousChannel = 0;    //channel that was active before change (0 is off)
const int audioThreshold = 15;      //minimum value for an "active" channel

//  ====TIMERS===
int counter = 0;
const int heartBeat = 500;
int channelReleaseTimeOut = 5000;      //time to wait before releasing an inactive timer
int powerTimeOut = 10000;       //time to wait before turnning off
int powerOnDelay = 7000;
elapsedMillis channelReleaseTimer = 0;
elapsedMillis powerTimer = 0;

// ====CONTROL VARIABLES====
bool debugMode = true;

void sendCode(int myChannel=0) {
//  debug("sending code", -1);
  for (int i=0; i < 20; i++) {
//  INCLUDING THE FOLLOWING LINE BREAKS THE DEBUG FUNCTION AND CAUSES OTHER STRANGE BEHAVIOR
//    mySender.send(sources[myChannel], RAW_DATA_LEN, 36);
    Serial.println("send code here");
    delay(2);
  }
} //END sendCode()

int findActiveChannel() {   //returns first active channel in the array or 0 if none are active
  int myChannel = 0;
  for (int i = 0; i < CHANNELS; i++) {
    if (channelValues[i] >= audioThreshold) {
      myChannel = i;
      break;
    }
  }
  return myChannel;
} //END findActiveChannel()

void debug(String message, int val) {

  if (debugMode) {
    Serial.print(message);
    Serial.println(val);
  }
} //END debug()

void setup() {
  delay(1000); //delay in case of runaway loop - allow programmer time to interrupt
  //  ====PIN SETUP====
  pinMode(statusLight, OUTPUT);
  pinMode(debugPin, INPUT);
  pinMode(audioPin1, INPUT);
  pinMode(audioPin2, INPUT);

  if (debugMode) {
    Serial.begin(9600);
    delay(2000);
    debug("starting up ", -1);
  }

  // ====INIT VARIABLES====
  for (int i = 0; i < CHANNELS; i++) { //init and reset the moving averages
    audioAverages[i].begin();
    audioAverages[i].reset();
  }
}

void loop() {
  int activeChannel = 0;
  for (int i=0; i < CHANNELS; i++) {      //sample channels
    int audioValue = 0;
    if (i > 0) {      //only sample channels > 0
      audioValue = analogRead(audioChannels[i]) - 512;      //voltage divider on amp circuit shifts all values +512 (2.5V)
      audioValue = abs(audioValue);     //abs() funciton is actually a macro; needs to be on own line
      channelValues[i] = audioAverages[i].reading(audioValue);    //update and store the moving average for each channel
    }

//    if (counter >= heartBeat) {
//      debug("channel: ", i);
//      debug("    audioValue: ", audioValue);
//      debug("           avg: ", channelValues[i]);
//    }
  }     //end sample channels

//  if (counter >= heartBeat) {
//    debug("======================", -1);
//  }

  if (channelValues[currentChannel] >= audioThreshold) {      //reset the channel release timer if the current channel is active
    channelReleaseTimer = 0;
    powerTimer = 0;
  } else {
    activeChannel = findActiveChannel();

    //DEBUGGING - show countdown to channel release
    if(channelReleaseTimer < channelReleaseTimeOut and counter >= 500) {
      debug("Channel became inactive: ", currentChannel);
      debug("     releasing in: ", channelReleaseTimeOut - channelReleaseTimer);
    }
    //END DEBUGGING

    if (activeChannel != currentChannel and channelReleaseTimer >=channelReleaseTimeOut) {      //change channel
      debug("Changing channel from: ", currentChannel);
      debug("Changing channel to: ", activeChannel);
      currentChannel = activeChannel;
      powerTimer = 0;
    }
  }
  //END else find active channel

  if (currentChannel > 0) {     //reset the power timeout if there is an active channel
    powerTimer = 0;
  }

  if (previousChannel != currentChannel) {      //check for a channel change and send appropriate codes
    if (previousChannel == 0) {     //state change from off to on
      digitalWrite(statusLight, true);
      debug("power state change -> ON ", -1);
      sendCode(0);
      debug("     delaying for reciver to power up: ", powerOnDelay);
      delay(powerOnDelay);
      previousChannel = currentChannel;
    }

    if (currentChannel < 1 and powerTimer >= powerTimeOut) {
      digitalWrite(statusLight, false);
      debug("power state change -> OFF ", -1);
      sendCode(0);
      previousChannel = currentChannel;
    }

    if (currentChannel > 0) {
      sendCode(currentChannel);
      previousChannel = currentChannel;
    }

  }

  if (counter >= heartBeat) {
    debug("\nheartBeat ", -1);
    counter = 0;
  }

  counter++;
  delay(2);

}

Including the line mySender.send(sources[myChannel], RAW_DATA_LEN, 36); in the sendCode() function causes the debug() function to behave erratically and the arduino to get stuck in a variety of states that require a hard reset, sometimes disconnecting the power.
This is the expected output from the serial console:
20:18:20.188 -> Channel became inactive: 2
20:18:20.188 ->      releasing in: 4666
20:18:20.188 ->
20:18:20.188 -> heartBeat -1
20:18:21.377 -> Channel became inactive: 2
20:18:21.377 ->      releasing in: 3492
20:18:21.377 ->
20:18:21.377 -> heartBeat -1
20:18:22.528 -> Channel became inactive: 2
20:18:22.528 ->      releasing in: 2317
20:18:22.528 ->
20:18:22.528 -> heartBeat -1
20:18:23.713 -> Channel became inactive: 2
20:18:23.713 ->      releasing in: 1144
20:18:23.713 ->
20:18:23.713 -> heartBeat -1
20:18:24.864 -> Changing channel from: 2
20:18:24.864 -> Changing channel to: 1
20:18:24.864 -> send code here

When including the mysender line indicated above, the serial output becomes as follows for a similar situation:
0:21:14.965 -> 1
20:21:14.965 -> 4984
20:21:14.965 -> -1
20:21:16.121 -> 1
20:21:16.121 -> 4986
20:21:16.121 -> -1
20:21:17.299 -> 1
20:21:17.299 -> 3814
20:21:17.299 -> -1
20:21:18.463 -> 1
20:21:18.463 -> 2640
20:21:18.463 -> -1
20:21:19.650 -> 1
20:21:19.650 -> 1468
20:21:19.650 -> -1
20:21:20.804 -> 1
20:21:20.804 -> 294
20:21:20.804 -> -1
20:21:21.116 -> 1
20:21:21.116 -> 0
20:21:21.998 -> -1

In the first example, you probably mean uint16_t sources[4][RAW_DATA_LEN] (4, not 2). In the second one, uint16_t *sources[4] (mind the star). With these fixes, I would expect both to work, But it is impossible to tell what's wrong with your program without seeing it.

those look like remote control codes ..... what is the device? ..... there may be a way to reduce the amount of data

@EdgarBonet Thanks for pointing out the typo in the snip. It does read uint16_t sources[4][RAW_DATA_LEN] in the actual code. The second example appears to work without the star which I find to be unexpected as I was lead to believe that I needed the star to indicate a pointer reference. Both compile, and run though the first example causes issues when a function uses that variable.

If you don't have the star, the second version should not work. That is, unless you do something very wacky in your code. Which seems to be the case: your program may be bug-compatible with the buggy version of the array definitions, and incompatible with the correct definitions. But then, let me repeat again: “it is impossible to tell what's wrong with your program without seeing it”.

@EdgarBonet Thanks for your patience. I've added the entire program. I'm running this against the 1.6.21 board manager due to some incompatibility with the IRLIB2 libraries as suggested here

I have no solution for you, but I would argue that your problem has
nothing to do the choice between an array of arrays and an array of
pointers. You will have to search somewhere else.
I tried a minimal test by removing everything that is not central to the
question. Assuming you are using this library, the prototype of
IRsendRaw::send() is
void IRsendRaw::send(uint16_t *buf, uint8_t len, uint8_t khz)

I thus wrote this dummy test class to replace the library:
class IRsendRaw {
public:
    void send(uint16_t *buf, uint8_t len, uint8_t khz) {
        Serial.print(F("Sending at "));
        Serial.print(khz);
        Serial.println(F(" kHz"));
        for (int i = 0; i < len; i++) {
            Serial.print(" ");
            Serial.print(buf[i]);
        }
        Serial.println();
    }
};

and used it in the following test program:
// Comment this line out to use an array of arrays instead:
#define ARRAY_OF_POINTERS

// ====REMOTE CODES====
//define the IR Sender
IRsendRaw mySender;

#define RAW_DATA_LEN 68

#ifdef ARRAY_OF_POINTERS

uint16_t powerOnOff[RAW_DATA_LEN] = {
  // ...
};

// And so on sourceCD[], sourceCDR[]...

//Set up array of codes
uint16_t *sources[3] = {powerOnOff, sourceCD, sourceCDR};//, sourceAUX};

#else

//This causes some sort of horrible crash
//- maybe an overflow of the uint16 data type?
uint16_t sources[4][RAW_DATA_LEN] = {
  {8550, 4306, 530, 1606, 530, 566, 502, 1610, //POWER ON/OFF
  // ...
  506, 1630, 510, 1000}
};

#endif

void setup()
{
    Serial.begin(9600);
#ifdef ARRAY_OF_POINTERS
    Serial.println(F("== Using an array of pointers =="));
#else
    Serial.println(F("== Using an array of arrays =="));
#endif
    for (int myChannel = 0; myChannel < 3; myChannel++) {
        Serial.print(F("\nChannel "));
        Serial.println(myChannel);
        mySender.send(sources[myChannel], RAW_DATA_LEN, 36);
    }
}

void loop(){}

The parts with ellipses (“...”) are just copied from your question. Now,
this test program works as expected, both in “array of pointers” and in
“array of arrays” mode.
It would then seem your problem comes from somewhere else. How full is
the memory of your Arduino? Quite often memory problems lead to strange
behaviors, where a crash can be triggered by a piece of code that is
perfectly legitimate and has nothing to do with the root cause of the
crash.

I think you're right. I'm starting to think this is a memory issue as well. The compiler reports that the sketch is 8408 bytes (29%) of program space. Global vars use 727 bytes (28%) of dynamic memory. I've narrowed down the problem to the function that calls the ir sender. Moving that fragment into another sketch works fine. Commenting out chunks of the logic in this sketch and getting the the dynamic memory down around 23% also works. Perhaps this micro has some bad memory? Is there a way to test for that?

@AaronCiuffo: You can find Arduino memory test sketches designed to test old RAM ICs. I am not aware of any published sketch designed to test the Arduino's own memory. The chances of the internal SRAM going bad are almost zero. What you can find is code for measuring the memory usage at run time, which accounts for heap and stack allocation. That could be a good thing to check.

I found a great article on this over at Adafruiit Memories of an Arduino. It covers some steps to take to decrease memory usage such as using the F() macro and moving large constants into PROGMEM. I'll give that a shot. Thanks again for your help.


text:
Trying to measure change in light levels over time
I have two LDR's attached to my Arduino Uno and an RGB LED as an output component. The two LDR's are at different offboard heights in order to see the change in light between them. I want to code on Arduino so that if the difference in light between the two LDR's does not change by a large amount over a 1 hour period (i.e stays similar), it will make the RGB  LED flash. I know that I have to use an if and else statement to do this, but does anyone know how I can code it so that I can achieve the above statement?
Thanks

you need to be able to read the values of the LDRs first ....... start by reading the value of one LDR and print the value to the serial port ..... when you are successful, read values of two LDRs and print their values to serial port

The needed algorithm strongly depends on what you really want to detect. Imagine following setup: your sensors are in two dark boxes, and you are putting a flashlight into the first box. After half an hour you take out the flashlight and put it in the second box. Looking each minute at both sensors, you will have the complete hour max. difference. Looking at the whole hour, both sensors have seen the same amount of light. To help you it would be good if you give a little bit more of information what are your use cases.

Break this into pieces. Solve the pieces one at a time.
Write code that reads the 2 photocells and calculates the difference between them. Log that difference to the console.
Then add a global variable to remember the old difference, and a max difference. Each time you take a new set of readings and calculate the difference, compare it to the old difference. If the new difference is greater than the old difference, update the max difference. Then update the "old difference" with the new reading.
Figure out how to use millis() to record a starting time, and monitor the reading difference until an hour has passed. If the reading difference is below your "large amount" threshold, start the light blinking.
Then you need to decide what to do about times greater than an hour. Do you track the max difference over the most recent 60 minutes and flash the light if it is below your threshold? Maybe save a difference reading every 5 minutes into a ring buffer with 12 entries (an hour's worth of entries) and keep checking the ring buffer for a difference value greater than your threshold? (You should be able to Google search "C ring buffer" for sample ring buffer code. It's actually quite simple to implement.
You might also want to calculate a moving average difference reading, and compare each reading to that. I recommend using an Exponential Moving Average (EMA).
I have code in my project that uses EMA to calculate a single brightness value rather than a difference, but the idea is the same. Here is an excerpt from my code:
Define a global:
float   photocellAverage =      0;

#define sampleCountToAverage 100  //The larger the number of samples, the more slowly the average will change with each new reading.

Then
int photocellValue = analogRead(photocellPin);
photocellAverage -= photocellAverage / sampleCountToAverage;
photocellAverage += float(photocellValue)/sampleCountToAverage;

For you, you'd be calculating a difference reading and an EMA of that difference reading:
float   photocellDifferenceAverage =      0;

int photocell1Value = analogRead(photocell1Pin);
int photocell2Value = analogRead(photocell2Pin);
int photocellDifference = photocell1Value - photocell2Value;
photocellDifferenceAverage -= photocellDifferenceAverage / sampleCountToAverage;
photocellDifferenceAverage += float(photocellDifference)/sampleCountToAverage;

I like the way you implemented the EMA. May I suggest for better understandig to change the naming for the difference EMA from ´photocellAverage´ to ´photocellDiffAvarage´. It took me some minutes to puzzle out that the context changed in your second excerpt. I also wonder why you are initialising with 0 instead of initializing with the first sensor value/first difference. Do you have a specific reason for that?

As for not initializing with the first value, it's laziness. I should have. It will settle out to the same value fairly quickly, after all.

Thanks for your answer, I don't whant to be annoying, but could you please  change photocellDifferenceAverage -= photocellAverage / sampleCountToAverage;
to photocellDifferenceAverage -= photocellDifferenceAverage / sampleCountToAverage;? Or I still did not understand your construct ;-)? I tried it in Excel, at the firts glance it looks like a PT1 element, is your EMA a elegant way to implement a PT1 Element or are there differences in mathematics behind?

I fixed the 2nd part of my answer. I must confess I found the code for EMA online, and adapted it to my needs. I don't know enough about the underlying mathematics to compare it to a PT1 Element. (I had to google that to learn what it is.)

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Set local stratum 0 NTP server without internet
Currently, I'm doing a running track timing gate project to measure an accurate acceleration (a runner for example). The idea is when the runner triggers the first gate (start gate), the system will signals all other ESP32 to start the timing, and as the runner triggers other gates, the system will save each of their time. The expected precision is up to 10 ms.

I've managed to set up an NTP client with an NTP Server pool.ntp.org
#include <WiFi.h>
#include <sys/time.h>
struct timeval timeinfo;
volatile boolean flag = 0;
unsigned long prevTime = 0;
const char* ssid     = "********";
const char* password = "********";

void setup() {
  Serial.begin(115200);
  Start_WiFi(ssid, password);
  configTime(0, 0, "pool.ntp.org");
  attachInterrupt(digitalPinToInterrupt(27), printLocalTime, FALLING);
}

void loop() {
  //unsigned long int currTime;
  //currTime = millis();
  //if (currTime - prevTime >= 1000){
    //prevTime = currTime;
    if (timeinfo.tv_sec != 0 && not(flag)){
      Serial.printf("%ld.%06ld\n", timeinfo.tv_sec, timeinfo.tv_usec);
      flag = 1;
    }
  //}
}

void printLocalTime() {
  gettimeofday(&timeinfo, 0);
}

int Start_WiFi(const char* ssid, const char* password) {
  int connAttempts = 0;
  Serial.println("\r\nConnecting to: " + String(ssid));
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
    if (connAttempts > 20) return -5;
    connAttempts++;
  }
  return 1;
}

However as I won't be having an internet connection I think that I need a different approach, I'm thinking of using a single ESP32 to behave like a stratum 0 NTP server or using Android phone as a stratum 0-like NTP server, which will be connected via a portable router. The other ESP32 will behave like a stratum 1 NTP server. I've read a solution to setup an NTP server using GPS, however actual current time is not necessary for this problem in my opinion.
Is this a good way to approach this problem? If yes, how do I setup a local stratum 0 NTP server?

why do you need an NTP server to time a race?

@jsotola I'm thinking to synchronizing 6 ESP32 to start their timer on a precision around 10 ms. Using NTP server is one solution that I can think of.

well, there is https://github.com/DennisSc/PPS-ntp-server

but you need only synchronize millis, not time and date.

I don't think you need to synch all the devices. Just have them send a packet as soon as the runner goes through the gate. The the single receiver-node will do the time measurements, based on the (local) times of the incoming packets. I don't think wifi jitter is more than 10ms, but you'd have to do some tests for that.

@Gerben, that sounds like an answer to the problem .... the OP's question is an X-Y question ...... the OP's system already has WiFi jitter ...... perhaps an initial handshake with one or more of  the sensor modules could be used to determine lag in the signal

@jsotola lag shouldn't matter. It's jitter that's potentially problematic. It is however possible to send raw packets though the ESP, (not adhering to the wifi specification). As far a I can see, that would eliminate all possible jitter.

Thank you for the feedback, I will try to implement the single receiver-node with raw packets.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Is it possible to send data from device (e.g. MPU6050) to Arduino through cut/hacked USB cable?
So I understand the USB cable consists of VCC, GND and Data+, Data-.

Is it possible to connect an MPU-6050 gyro to these 4 pins, especially data+/-, and still receive them normally through the SCL/SDA pins on the Arduino?
The goal is to make an input piece modular by having an USB out at it while having an USB in at the Arduino.
Here is a basic visualization:

No, the i2c bus is not meant to go through a cable.

Just make sure you keep the VCC and GND wires the same as USB, so that in the event someone plugs it into a PC, thinks don't get damaged.

Execellent non-Arduino question about I2C cable so the answer is also non-Arduino. I recommend the following Hackaday blog. https://hackaday.com/2017/02/08/taking-the-leap-off-board-an-introduction-to-i2c-over-long-wires/. You can find a more theoretical model in https://www.analog.com/media/en/technical-documentation/technical-articles/I2C-Cabling.pdf
Basically yes you can use cables. Different cables have different level of capacitance per meter. This will reduce the maximum frequency and may also require adjustment of the pull-up resistors.
Cheers!
BW: "nihil novi sub sole": This question has been asked before, https://forum.arduino.cc/index.php?topic=143337.0

Thanks for the info. I just did it with simply connecting the wires and was suprised that it worked, but it's actually just a long wire in the end, right? So of course it should work. But now I'm wondering what if I needed one more pin (e.g. the AD0 of the MPU)? Can I somehow manually put one more wire inside the USB?

Why all the trouble? There are a lot of different cables out there. USB has four wires so that is a limit. How about using an Ethernet cable? Or even Telephone cable. In any case do not forget to accept the answer if it was just that.

You're right, gonna do something similar!


text:
Reading Digital Pins and Outputing on entire Ports
I'm very new to coding so please don't grill me.
I'm working on a scientific project where I am using a NI-DAQ to digitally trigger mosfets to trigger 300us - 3ms pulses on two high powered LED arrays. My intention is to use the Arduino UNO to basically relay one digital output into many. It remains important to use the NI-DAQ as the pulses are dependent on video cues and other outputs, otherwise the pulses would be purely produced by the Arduino.
I have decided to the port Port reg output to accomplish this as it would appear to have the greatest temporal precision but I’m having a very difficult time getting a single pin to trigger a port. I would greatly appreciate some help.
My code currently looks as such:
int inpin = 2; //input specified as pin 2
int x = 0; // variable to store the read value

void setup() {
pinMode(inpin, INPUT); //sets digital pin 13 as input
DDRD=B11111111; //pin 8-13 is in output mode
DDRC=B11111111; //pin A0-5 designated output
}

void loop() {
x = digitalRead(inpin); //read the input pin
if (inpin = HIGH) PORTB=B11111111; // if digital input is high, all Bport high
if (inpin = HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
if (inpin != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
if (inpin != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low

}

At the moment it seems the board it reading the input but is not relaying the outputs correctly with the PORTB continuously off and PORTC continuously on. Any help would be great!

If your purpose is to just repeat an input why not take an IC meant for the task, They are commonly reffered to as buffers.

Check the Arduino pinout. It would seem you mixed up ports B and D.

Thank you Edgar, I fixed my typo in the set up area. Now both B & C are illuminated continuously.

I agree with ratchet. If you just want to repeat a digital input then use a buffer ship. Those respond in single-digit nanoseconds, with no programming needed. Arduino chips are relatively slow.

You have some coding errors.  You likely meant to write something like:
void loop() {
  x = digitalRead(inpin); //read the input pin
  if (x == HIGH) PORTB=B11111111; // if digital input is high, all Bport high
  if (x == HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
  if (x != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
  if (x != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low
}

Which could be simplified to:
void loop() {
if (digitalRead(inpin) == HIGH)
{
  PORTB=B11111111; // if digital input is high, all Bport high
  PORTC=B11111111; // if digital input is high, all Cport is high
}
else
{
  PORTB=B00000000; // if digital input is low, all Bport is low
  PORTC=B00000000; // if digital input is low, all Cport is low
}
}

Amazing! Thank you, I had been stuggling with that for some time. I thought an else statement would be apropriate I just didn't know how! Cheers

If you are doing this sort of low-level port manipulation, I suggest you
ditch the Arduino core and go the avr-libc way:
#include <avr/io.h>

int main(void)
{
    DDRB = 0xff;  // all port B as output
    DDRC = 0xff;  // all port C as output
    DDRD = 0;     // all port D as input
    for (;;) {
        if (bit_is_set(PIND, PD2)) {  // if PD2 reads HIGH
            PORTB = 0xff;  // all port B goes HIGH
            PORTC = 0xff;  // same for port C
        } else {
            PORTB = 0;     // all port B gos LOW
            PORTC = 0;     // same for port C
        }
    }
}

This compiles to very efficient code that takes at most 7 CPU
cycles per loop iteration. In contrast, a call to digitalRead() can
take hundreds of cycles, greatly increasing the program latency.
Obviously a buffer would still be way better in terms of latency, as
pointed out by ratchet freak in a comment.

I'll explore this option too. Although latency is important In my project it is most important that each pin within a port in in sync with the rest of the pins within the same port. I believe this approach, similar to the buffer approach, will be sufficient. Thank you


text:
Arduino FFT Heart Rate Monitor
Part of my project is to build heart rate monitor from Nano and a PulseSensor. I am having trouble working with the Fast Fourier Transform part of the code.
This code here is from a library (arduinofft) that can be found in the arduino IDE. When testing the arduino the serial printer returns values of about 51 bpm, which is far to low, compared to other devices of about 70bpm.
What i have done:

edited the library to only take the last 25 to 128 samples (only when computing the max peak), to off-set the DC. Previously getting readings of 5 BPM
changed the sampling frequency to 5.6Hz to get the range of 0 to 2.8Hz range for the hate rate

What i don't understand:

the sampling period, if the samples are taken and put into an array every second what does the period do.
Also if samples are taken every second is this enough to get a good reading on a heart rate shouldn't the sample be maybe of 15-30 seconds?
If this is so, should i put another array at the bottom. To capture the results every second upto 15 or 30, print the average then first in first out  the array of new values?

#include "arduinoFFT.h"

arduinoFFT FFT = arduinoFFT(); /* Create FFT object */

#define CHANNEL A0
const uint16_t samples = 128; //This value MUST ALWAYS be a power of 2
const double samplingFrequency = 5.6; //Hz, must be less than 10000 due to ADC

unsigned int sampling_period_us;
unsigned long microseconds;

double vReal[samples];
double vImag[samples];

#define SCL_INDEX 0x00
#define SCL_TIME 0x01
#define SCL_FREQUENCY 0x02
#define SCL_PLOT 0x03

void setup()
{
  sampling_period_us = round(1000000*(1/samplingFrequency));
  Serial.begin(115200);
  Serial.println("Ready");
}

void loop()
{
  /*SAMPLING*/
  for(int i=0; i<samples; i++)
  {
      microseconds = micros();    //Overflows after around 70 minutes!
      vReal[i] = analogRead(CHANNEL);
      vImag[i] = 0;
      while(micros() < (microseconds + sampling_period_us)){
        }
  }

  FFT.Windowing(vReal, samples, FFT_WIN_TYP_RECTANGLE, FFT_FORWARD);    /* Weigh data */
  FFT.Compute(vReal, vImag, samples, FFT_FORWARD); /* Compute FFT */
  FFT.ComplexToMagnitude(vReal, vImag, samples); /* Compute magnitudes */
  double x = FFT.MajorPeak(vReal, samples, samplingFrequency); /* Compute largest peak*/
  double y = round((60/(1/x)));
  Serial.println(y);  //print bpm
  delay(2000); /* Repeat after delay */
}

Thanks for any help

compared to other devices of about 70bpm .... are you sure that the other devices are accurate? ..... check the pulse rate manually

I have checked my heart rate manually and should have rate higher than 60 consistently. Other device is the finger clip that the NHS gives you so should be accurate

it's just the first step in troubleshooting .... confirming that there really is a problem


text:
Serial.parseInt() takes longer time than desired
My whole code for master. Please head to void read() where I've used parseInt()
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

RF24 radio(7, 8); //Set up nRF24L01 on CE pin and CSN pin respectively

const uint64_t pipe = 0x0ABCDEF; //Address for communication between master and slave
uint16_t data[7];
const uint16_t buffer_size = sizeof(data); //Size of the payload for the RF
int i, flag;
int tx_counter = 0;

void read();
void setup() {

  Serial.begin(115200);

  radio.begin();
  radio.setChannel(2);
  radio.setDataRate(RF24_1MBPS);
  radio.setPALevel(RF24_PA_MIN);
  //radio.powerUp();
  radio.openWritingPipe(pipe);
  //radio.setPayloadSize(7);
  radio.stopListening();

  //Default values range from 100 to 700
  for (i = 0; i < 7; i++) {
    data[i] = 100 + (100 * i);
  }
  flag = 0;
  Serial.println("Enter 7 values");
}

void loop() {

  read();

  if (flag) {
    bool tx_ok = radio.write(data, buffer_size);
    tx_counter++;
    Serial.print("Transmission count:\t");
    Serial.println(tx_counter);
    print();
    if (tx_ok) {
      Serial.println("Transmitted Successfully");
      Serial.println("\nEnter Next set of 7 numbers");
    }
    else Serial.println("Transmission failed");

  }
}

void print() {
  for (i = 0; i < 7; i++) {
    Serial.println(data[i]);
  }
  flag = 0;
}

void read() {
  while (Serial.available()) {
    for (i = 0; i < 7; i++) {
      data[i] = Serial.parseInt();
    }
    flag = 1;
  }
}

My problem is that Serial.parseInt() takes some time. The code prints out the values to the serial monitor after sometime. I have timed it and it appears to be around 7 seconds. The arduino page on the function says default timeout is 1 sec. So I think 7 elements in the array takes 1 sec each. If I use Serial.setTimeout(2000), the same thing takes 14 seconds.
This has got to have a simpler way. I want it to behave like when we use Serial.read. Please help me on this.

i think that Serial.available() has a timeout of several seconds before it decides that there is no more data

I am confused. you send a 7 bytes long binary buffer over radio. and then you print the content of the buffer as numbers to local Serial Monitor and you parse data from Serial Monitor. do you enter numbers in Serial Monitor? every Serial.parseInt waits a second for a number sent from Serial Monitor

@jsotola the Serial.available returns how many bytes have been received (and are in the Serial receive buffer, waiting to be read). That's all, nothing else.

@Juraj Yes I enter numbers in the Serial monitor. I am printing it to just keep a track of the values in the array so that it should match at the receiver's end. If I enter the number '2' and wait for some seconds, it automatically timeouts and the rest all becomes zeroes. I want it to wait for the user's input infinitely.

this is what you want:
void read() {
  for (i = 0; i < 7; i++) {
    while (!Serial.available()); // wait forever for some input
    data[i] = Serial.parseInt();
  }
  flag = 1;
}

Thanks for this. Works except with a small issue. The first value transmitted alone is 0. And after each transmission, if I enter next set of integers quick enough this doesn't occur. A sample received value showing this  0 8 84 51 162 21 651


text:
Varible Ramp up speed for motors controlled by joytstick
I trying to create a piece of code which will ramp up the motors speed to a changing value controlled by a joystick. For example joystick requests 120 speed to motors so instead of going 0 to 120 it goes 0, 10, 20 …. 120. But the maximum value will constantly change between 0-130 so it needs to ramp up each time.
This is a snippet of my code to run the motors in the forwards direction.
{
  motorControl = analogRead(joystick);
  motorControl = motorControl / 4;
  if(motorControl > 129)

{

    digitalWrite(pwm2, 0);
    digitalWrite(pwm3, 0);
    speedI = (motorControl - 130);
    speedFadeI =
    Serial.println(speedFadeI-130);
    analogWrite(pwm1, (speedFadeI - 130));
    analogWrite(pwm4, (speedFadeI - 130));

thank you for anyone who has a idea

do you have a question?

I assume from the 0, 10, 20 …. 120 series, that you want to have a linear ramp to the desired speed. This can be done really easily, if your requirements are not to high.
First we define the interval, in which we want to update the speed, and a constant acceleration, that you can choose. The current speed will be saved in a global variable.
#define INTERVAL        100
#define ACCELERATION    51
int current_speed = 0;

I chose an interval of 100ms and the acceleration value, so that it will ramp from 0 to 255 (full speed) in 5s (which results in 51 PWM values per second). Now, in the void loop() function, we use an if-statement with the millis() function to trigger an speed update at the regular interval. For this to work, we need a (here global) variable, that holds a timestamp. (If you don't know this technique, you can see it in the BlinkWithoutDelay example, that comes with the Arduino IDE, and there are many tutorials about this on the web)
Inside the if-statement, we write a second if-statement. It checks, if the current speed is above or below the set point, that comes from the joystick. If it's above, we will substract one speed step (calculated by acceration and interval and divided by 1000, because we used milliseconds and not seconds for the interval), if it's below we will add one speed step.
unsigned long timestamp = 0;

void loop(){
    int setpoint = analogRead(joystick)/4;
    if(millis() - timestamp > INTERVAL){
        if(current_speed > setpoint){
            current_speed -= ACCELERATION*INTERVAL/1000;
        } else {
            current_speed += ACCELERATION*INTERVAL/1000;
        }
        if(current_speed > 255) current_speed = 255;
        else if(current_speed < 0) current_speed = 0;
        analogWrite(pwm1, current_speed);
        timestamp += INTERVAL;
    }

I also added if-statements to cap the current speed between 0 and 255. Otherwise the value would overflow, when written to the corresponding 8-bit timer register by the analogWrite() function.
Of course, this method also has drawbacks. You will have to find a good value combination of ACCELERATION and INTERVAL, because when the current speed reaches the setpoint, it will oscillate around this value. The best way is to set the ACCELERATION, that you need, and choose a good interval based on that.
There are other ways to program this, but I like this way for being really simple.


text:
Serial communication stops when powered with batteries?
Circuit explanation-

Arduino Uno connected to multiple sensors and to 16 x 2 LCD.
Uno's TX pin to ESP-01 RX pin.
Uno has been programmed to read values from sensors and display them on LCD along with printing them on Serial Monitor.
ESP-01 has been programmed to receive values from Serial Monitor and transmit it to ADAFRUIT MQTT server.

Problem -
However when i am using USB to power the Uno it is successfully displaying data on LCD as well as to Serial Monitor and values are succesfully being send on the MQTT server after being read from Uno's serial.
But when Uno is battery powered, serial communication stops.
I have tried adding 2 decoupling capacitors of 100uF to 12V battery supply. Battery are rechargeable cells.
What could be the issue?

Sure that was done, because your question lacks important information. How much current can your battery supply? How are the Uno and the ESP connected to the supply? Have you investigated, if the serial communication stop is really the problem or just a symptom? For example you may have got a reset due to a dip in the power supply. Maybe try to add a life signal like toggling an LED every half second, or let the led blink once at startup, so that you can see, if there was a reset.

Uno is not resetting that i am sure. Right now I am using a 12v/1Amp adapter to power up the Uno and still problem persists. Is even 1A not enough ?

And how is the ESP connected? It uses a lot of power, especially when connecting to a network. I remember something like up to 600mA, but I'm not sure about that.

ESP is separately powered by another uno for a regulated 3.3v supply. 12V +ve >> Vin of Uno. GND is common for all devices except ESP. Capacitor between 12V +ve and GND of Uno.

how can esp-01 communicate over Serial without common ground?

I think you should not power an ESP from the 3.3V pin of an Uno. According to the datasheet of the LP2985 (the voltage regulator on the Uno Rev3) it can provide only 150mA at max. And as Juraj wrote, if you want circuit to interact in some way, you need a common ground or a circuit with something like an optocoupler. There is no electrical circuit with only 1 wire between the devices.

Thank you guys so much, Juraj and Chris. I commonly grounded the Esp's and Uno's supply and it worked. and what's the technical defination for optocoupler?

You should not power an ESP-01 from any Arduino 3.3v supply. The 3.3V line can't supply enough current. And powering your Arduino with 12V, the 5V regulator will get quite hot if you put out a lot of current (at either 3.3V or 5V. On an Arduino the VIN first gets regulated to 5V, and then the 5V goes through a separate regulator to supply 3.3V. Heat from the 5V regulator is related to VIN voltage and the sum of the currents drawn from the 3.3V lines 5V.) Just get a separate 1A 3.3V switching supply to power the ESP. They're cheap and efficient.

I will put the solution from the comments into an answer.
All devices, that should interact through electrical wires with each other, must have a common ground. Ground is the point, from which the voltage is measured, and the devices need a reference, that is not only valid for themselves, but also valid for the communication partner.
You can think of the following analogy: Image that you and a friend have each one ball, that you are throwing into the sky (a positive height/voltage) and catching it again (zero height/voltage --> ground). While you stand on the parking lot, your friend is standing on a high building. As long as you both only play this with yourself, it is easy for you to throw and catch the ball, because you can easily measure the height of the ball and it will always behave the same. But know imagine, that you want to play together. The height/voltage, that your ball reaches is still positive for you. But from the perspective of your friend it will look, like a large negative height/voltage. How should your friend interpet that and how should he now play with you?

In some electrical circumstances you don't want to connect the grounds of two devices together (maybe because of noise on the ground line). Then you have to achieve galvanic isolation, so no electrical connection between those two. An optocoupler is a device, that can achieve this. Basically it's just an LED and a phototransistor in one casing. From one device you power the LED. Due to the LEDs light, the phototransistor (which is connected to the other device) will become conductive. In combination with a pullup/pulldown resistor on the phototransistor you can have communication without common grounds.


text:
Unable to store data in variable from Serial.read()
I have a relay and bluetooth module connected to Arduino Uno. I send data such as digit 1 to the bluetooth module and I view it in the Serial Monitor. If I send 1 from serial monitor I get 4910 printed.
I would like to turn on the relay and have it stay on until I send a different digit. However, in my code below it doesnt work, the relay doesnt stay on.
Only, if I put the digital.write under while(Serial.available()) it works.
const int ledPin =  11;
int relayOn;

void setup() {

  //initialize serial port for logs
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);

}

void loop() {

  while (Serial.available()) {

      Serial.println("Data: ");

      Serial.println(Serial.read());

      if(Serial.read())
      {
        relayOn = Serial.parseInt();
      }

      while (relayOn > 1)
      {
        digitalWrite(ledPin, HIGH);

      }

    }

}

You can make it easier by using commands which are only 1 character. For example '1' or 'A' to turn it on and '0' or 'a' to turn it off. Start with a good description of the commands and the communication. A Serial.read() read a character, and you can not read it again with another Serial.read().

But can I store the data from Serial.read() inside a variable without having to keep sending the data continuously, I want the relay to stay on until I send different data 0 or 1 etc

@condo1234 You are rushing ahead. First describe the data/commands that you transmit. Do you want, for example, make it hard for yourself and be able to send the number "15"? Then step by step write it in code, if possible without the parseInt.

Now I am sending number 5 to turn on relay and 0 to turn off. Would it make a difference to send 1 to turn on? I also tried to assign variable relayOn in my code with Serial.read() and define it as char, but still didn't match. Do you have any example code I am a little confused with how to keep the relay on after I send data from bluetooth

what is the value of relayOn when you input a 1 and and also when you input a  0?

@jsotola when I send 1 I get 0 when doing Serial.printIn(relayOn)

Serial.println(Serial.read()); removes the data from the serial buffer.  if(Serial.read()) will be always false

Actually  the second "Serial.read()" will always return -1, this should be interpreted as true.

@Dorian you are correct!! That was the issue

Your input is "5\n" with '\n' as line ending setting in Serial Monitor.
In the code you have first Serial.println(Serial.read());. It will read and print the '5'. Then you have if(Serial.read()). It will read the '\n'. It is not 0 so the next line is relayOn = Serial.parseInt(). It will find no input and times out returning 0.
if you want to use parseInt():
void loop() {
  if (Serial.available()) {
    Serial.print("Data: ");
    relayOn = Serial.parseInt();
    Serial.println(relayOn);
    if (relayOn > 1) {
      digitalWrite(ledPin, HIGH);
    }
  }
}

Ok thanks that makes sense, I will try send with 1 and 0 and see if that works

Sorry I meant I already tried Serial.parseInt() and that outputs 0 when output relayOn in serial monitor, tried the same as your above code

it is not about what number you send, but how you read it. the answer explains the 0

I have changed to send 1 and used your code with Serial.parseInt() and when I output Serial.printIn(relayOn) I get 0 and Serial.printIn(Serial.read()) I get -1.

replace your loop() function with the loop() function from my answer

Ok I did that and now it outputs 0 if I send 1

I used in void setup() { Serial.begin(9600);}. In serial monitor I use 9600, its strange when I enter 1 from serial I get output 4910 everytime inside Serial.printIn(Serial.read())

49 is ascii code of the character '1'. 10 is ascii code of  the character '\n' (new line)

So, what do I do to make the relay turn on and stay on and then turn off when I send different character... that is all I need to do ... any code ideas? thanks for your help so far. I am sending a 1 from the Serial monitor and android app, seems like both not sending an integer

So in if statement do I check for string, i.e. if (relayOn == '1') instead? And do I change relayOn from int to char?

It's not fair to delete an answer with usefull comments from OP then after the issue was solved to show up with it. The answer wasn'there when I made my comments.

@Dorian, I am really sorry. I deleted the answer, because OP indicated that the problem is something else and the answer didn't solve it. I wrote first a similar comment then yours. It was 3th or 4th comment and was totally ignored by OP and other commenters. Then I wrote the answer and deleted the comment. Then the answer seemed to be off...

It was at least part of the solution, I would upvoted your answer if I would find-it as i did with kuskus's answer posted shortly after my comment to let op know that it really has an issue there.

@Dorian, sorry. it was a bad decision

You could try something like (not tested):
void loop() {
 if(Serial.available()){
   input = Serial.parseInt();
   Serial.print("Data: ");
   Serial.println(input);
   if(input == 1){
      digitalWrite(RELAY, HIGH);
      digitalWrite(LED, HIGH);
   }
   else if(input == 2{
      digitalWrite(RELAY, LOW);
      digitalWrite(LED, LOW);
   }
 }
}

don't forget to declare input variable, use 1 to turn on, 2 off :)

Try using serial interrupt in arduino
void loop() {
}

void serialEvent()
{
  while (Serial.available())
    {
       char inChar = (char)Serial.read();
      Serial.print("Data: ");
      Serial.println(inChar);
       if (inChar == '1')
        {
              digitalWrite(ledPin,HIGH);
              break;
        }
       else
        {
              digitalWrite(ledPin,LOW);
              break;
        }
     }
}

it is not an interrupt. https://github.com/arduino/ArduinoCore-avr/blob/5755ddea49fa69d6c505c772ebee5af5078e2ebf/cores/arduino/main.cpp#L45

but is acts as serial interrupt in arduino


text:
Enable and disable individual interrupts
I am working on timer interrupts and external interrupts.
for external interrupts I understood the functions like attachInterrupt. detachinterrupt for individual interrupts ,noInterrupts() and  interrupts() can be used to enable and disable all interrupts at a time.
But How to enable and disable timer interrupts??
I am writing a code for alarm clock and snooze button. So what I want is
1) whenever alarm time is equal to watch time, start a timer for 5 minutes and a buzzer buzzes.
2) whenever I press the snooze button,  another timer starts and after 30 seconds a buzzer beeps. again I press snooze and again the timer starts and after 30 seconds buzzer beeps.
3) But after 5 minutes of the first timer, both timer interrupts gets disabled as now I dont want any buzzer.
I know how to initialize the timer in setup function, and I am getting the buzzes every 30 seconds. I also know that interrupts will come according to the timer value and I need to call the function after a fix number of counts or 30 seconds or 5 minutes.
But I dont know how to disable and enable timer interrupts wherever I want in code.

Why are you using timer interrupts for this? A software timer (based on millis()) seems more appropriate, as you cannot program a hardware timer to fire more than about 4.2 seconds into the future.

Thank you very much, I have just read about the millis() and I think that it'll be more useful. I'll try to do my project using millis and let you know.

Step 1: Read the datasheet for the chip.
Step 2: Find the registers that control the timers and their interrupts.
Step 3: Set or clear the relevant bits in those registers.

For example, the ATMega328P has the TIMSK1 register for Timer 1, which has three bits related to interrupts:

Bit 2 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable

When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1
  output compare B match interrupt is enabled. The corresponding interrupt vector (see Section 11. “Interrupts” on page 49) is
  executed when the OCF1B flag, located in TIFR1, is set.

Bit 1 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable

When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1
  output compare A match interrupt is enabled. The corresponding interrupt vector (see Section 11. “Interrupts” on page 49) is
  executed when the OCF1A flag, located in TIFR1, is set.

Bit 0 – TOIE1: Timer/Counter1, Overflow Interrupt Enable

When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1
  overflow interrupt is enabled. The corresponding interrupt vector (see Section 11. “Interrupts” on page 49) is executed when
  the TOV1 flag, located in TIFR1, is set.

So to turn off the Compare B Match interrupt you can use:
TIMSK1 &= ~(1 << 2);

And to turn it on again:
TIMSK1 |= (1 << 2);

Both Timer 0 and Timer2 have a TIMSKx register which works in the same way.


text:
need to get values from a function with structure pointer argument and print on serial terminal
I am developing a code in which I need to print value of structure pointer on serial terminal.
Below is my code snippet:
typedef struct
{
  uint8_t AB;     ///< Address byte (Start byte)
  uint8_t CB;     ///< Command (index) "ASCII-byte"
  uint8_t SI;     ///< Action (sub index) "ASCII-byte"
  uint8_t PH_1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
  uint8_t PH_2;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
  uint8_t PL_1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
  uint8_t PL_2;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
  uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
  uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
} rs485_message_t;

int proto485ComposeMsg(rs485_message_t* msg, uint8_t address, uint8_t command, uint8_t action, uint16_t value){
  msg->AB = address;
  msg->CB = command;
  msg->SI = action;
  msg->PH_1 = (int)((value & 0xF000) >> 12) ;
  msg->PH_2 = (int)((value & 0x0F00) >> 8);
  msg->PL_1 = (int)((value & 0x00F0) >> 4) ;
  msg->PL_2 = (int)(value & 0x000F);
  int checksumRaw = (msg->CB) + (msg->SI) + (msg->PH_1) + (msg->PH_2) + (msg->PL_1) + (msg->PL_2);
  setCheckSum(msg);
}

uint8_t proto485Write(uint8_t address, uint8_t command, uint8_t action, uint16_t value)
{
  int i = 0;
  int stringOne[9] = {int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00)}; ;
  rs485_message_t rs485Msg;
  proto485ComposeMsg(&rs485Msg, address, command, action, value); // value is passed in "raw" format
  Serial.write(rs485Msg);       // getting error on this line
}

Please help... Thank you

You can't just print a structure. After all, how is the program supposed to know how it is supposed to be displayed?
Do you want just the raw data, or do you want it formatted in a human readable form?
For just the raw data you need to cast the pointer to a type that can be printed as an array. For example:
Serial.write((uint8_t *)&rs485Msg, sizeof(struct rs485_message_t));

To print it in a human readable form you will need to take each value that you want to see and print it separately with any data manipulation that you may want.  For example:
Serial.print("Checksum 0: ");
Serial.println(rs485Msg.CS0, HEX);

Another thing you can do is to change your structure into a class and inherit the Printable class.  You can then implement the size_t printTo(Print &p); member function which sends the data to the p object for printing in the format you want.  Then you can just print it directly as you are trying to do in your code.

Thank you so much it solved my purpose


text:
Program to run two motors with Motor driver
I'm trying to make a program that would run two motors clockwise and then anticlockwise. But my program is causing my motors to only run clockwise everytime . It doesn't run anticlockwise at all. Can anyone help me find the bug?
Main code:
void loop()
{
  // turn on motor A
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  // set speed to 150 out 255
  analogWrite(EnA, 150);
  // turn on motor B
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  // set speed to 150 out 255
  analogWrite(EnB, 150);
  delay(2000);
   digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
   digitalWrite(In3,LOW);
  digitalWrite(In4, HIGH);
  // now turn off motors
  digitalWrite(In1, LOW);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, LOW);
  delay(2000);
}

How long is there between turning anti-clockwise and stopping the motors...?

I didn't set any delay between anticlockwise rotation.

Which means what...?

check this one
void loop()
{
  // turn on motor A
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  // set speed to 150 out 255
  analogWrite(EnA, 150);
  // turn on motor B
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  // set speed to 150 out 255
  analogWrite(EnB, 150);
  delay(2000);
   digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
   digitalWrite(In3,LOW);
  digitalWrite(In4, HIGH);
  // now turn off motors
  delay(5000);
  digitalWrite(In1, LOW);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, LOW);
  delay(2000);
}


text:
How to build image with ultrasound sensors HC-SR04
There is a simple algorithm on Wikipedia: how to build ultrasound image. And I want to build one. Resolution and presision are of no importance, I just want to do this for the case of study - I want to make such an "image 1D+depth slice" of a 20m^2 room. So I may just use these low frequency sensors - 1cm is enough.
So, as stated in the article, I need a phased array (to direct wave). And accidentally I have a couple of Arduino sensors HC-SR04:

Everyone uses them, but I stumbled how to use them. Interface seems to be totally weird, insuffient and unusable. Despite there are (visually) so many logic ICs soldered on the back.. So why is it designed so poorly and how to fix that?
Could you help me - where and what would you solder/desolder to use it for ultrasound imaging? I think that sensors itself could suit for this task.
PS. Basically I need to measure echoes delay (for depth) and echoes streight (for pixel brightness)
It should work on the phased array principles, without rotating, moving, without using any motors. Desired radiation pattern is illustrated by following animations:

Is it even possible to draw a 2D image with this sensor? There is just one receiver so the triangulation of the source of the echo is impossible. The algorithm description in Wikipedia looks more like "How to draw an owl" meme. https://knowyourmeme.com/photos/572078-how-to-draw-an-owl In reality this task is very complicated. Technically You can use this sensor with 2 steppers to draw image pixel-by-pixel but it will take minutes.

@FilipFranik As it was stated: "And accidentally I have a couple of Arduino sensors HC-SR04".. So its possible. Also, sorry, I dont learn memes (head space is way limited to trash it with remembering useless memes).

What I meant was "the description of algorithm in Wikipedia is misleadingly simple, whereas in reality the task is not". Having couple of those sensors helps, but you will need a device that sends only a single pulse of sound and then several microphones listen to the result (those sensors can't do that), then the tricky part comes, you need to look for local minimums and maximums in the result trying to match them between sensors. This way you can triangulate (in 3D) what pixels should be brighter. This is a very interesting (and difficult) project, and I will think more about it.

@FilipFranik My PC sound card (EMU1212) has 2 Output and 2 Input channels; It can easily sample at 192khz, meaning that generating/recording square wave at 48khz frequency is a simple task, as well as aligning/analysing phase (in software) - just shift signal start in left or right channel.. And 2 SR sensors has exactly 2 transmitters and 2 recievers (to be desoldered from such a poorly designed sensors). But also they have some logic, I wondered can I reuse a part of it?

The datasheet for the sensor doesn't say what chips are located on it. Could you please write the numbers you see on them in the question?. According to here http://osoyoo.com/2018/08/arduino-lesson-ultrasonic-sensor-hc-sr04-module/ they are two LM324 (quad op-amps) and MAX3232 (RS323 transceiver) This would explain the strange interface since this looks like a clever hack to lower cost of the sensor.

This might interrest you http://uglyduck.vajn.icu/ep/archive/2014/01/Making_a_better_HC_SR04_Echo_Locator.html and this http://www.pcserviceselectronics.co.uk/arduino/Ultrasonic/electronics.php There is open-hardware upgraded HC-SR04 board that replaces custom Chinese microcontroller with ATtiny24. Technically you can then upload any program you want on it.

@FilipFranik One amp is really the 324, second is unnamed, no markings on it. And a "max202 cse+1409" IC. Sensors are visually the same, but are non-measurable with standart multimeter. It gives infinite resistance even at 2MOhm. And zero voltage even at 200mV scale when loud sound pushed into it. So they are neither inductors, nor capacitors (upd: I think they're capacitors operated at microvolts scale). And it all is kind of "totally chineese magical stuff".. Thanks, I will read the info :)

This would be a fair first attempt. It may not fit your end-goal, but it's a good intermediary step: https://youtu.be/PlB3c2WaaBg

@Paul This could not help me, because it utilizes motor, but not phased array manipulation, to direct sound.

@jsotola It means that you have 2 sensors. By sensor I assume a transmitter and a reciever in one device. So you have 2 transmitters that could allow you to direct wave without rotating or moving your head to which it is attached. But by playing with wave phase so they cancel out. Having 2 recievers would allow to guess direction of a sound, as you ears do. That would give you one dimension: 1D. Another trick is that you could recieve more than 1 echo, that would give you depth, or second dimension. You havent even bothered reading wiki article in my question! It is described there very well!

@jsotola I want to build a 2D plane, where one dimension is horisontal and lies in the line, connecting human eyes, or ears. And second dimension is a depth. That gives a plane. It could be a fan-shaped image (like medical), showing rough approximation of room (and obstacles the plane crossects). I want to achieve it without rotating actual sensor (not using any kind of motor), that's primary goal. I think that more clever echoes processing could be required, than just "measuring time". For instance, I could need to process arrival phases. And also I'd like to measure echo strenght as well.

@jsotola I think 2 tranmitto-recievers (sensors) could build a fan-shaped figure in a plane, and 3 sensors could build a 3D space figure, limited by some cone, or even tetrahedra.. but all this "is not exact" - I've just started studying this field :)

@jsotola I've added animation to original question to illustrate what I want to achieve.

@xakepp35 i have heard of using a microphone array to record, at a distance, the voice of one person in a crowded room ...... your project is very similar ..... there may be detailed information on the web

@jsotola May. A link could be much useful than a mere rumors..   ;-)

This certainly cannot be done with these modules. But you should be able to reuse the ultrasonic piezo elements. If you really want to be a cheapskate you might be able to also reuse the op amps. Tomorrow I will try to write a somewhat answer, but you won't get a ready to use solution here.

https://www.youtube.com/watch?v=bgz7Cx-qSFw


text:
Can I power an NodeMCU trough VIN providing 5v
I have a spb 8266 board, an ESP-12E NodeMCU.
I broke my micro USB.
There's this piece of information but my case is unclear:
Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?
(The board only has 3.3V and no 5V)

Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

Yes. That is the pin's purpose.  You can use any voltage from about 4.5V up to 20V, although higher voltages will cause more heat from the on-board 3.3V regulator.
VIN just connects to the 5V of the USB.

through a diode... On many (all?) ch340g-based nodeMCU, that pin does does something else, I'm not sure what, but it reads about 1.6v when powered by USB, which means we can't use it to power a sensor.

Stove have a diode on that pin, stone have it on the usb power. Without knowing exactly what model and who made it is impossible to know.

If you are working with the "v3" (Lolin) pcb, USB v5 pin is not directly connected to Vin, but to VU. Vin has a S4 SMD diode (aka Schottky 40V1A 1N5819) between it and the USB v5 pin.


text:
Pass structure pointer as an argument to a function in c
I am developing a code in which I need to pass a structure pointer value to a function as a parameter. I am calling function "proto485Compare()" in "RS485TaskSlave()". "rs485Msg" contains my data for which I need to verify for checksum, I am checking it in "RS485TaskSlave()" using "if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message)))" but it is showing error on this line.
Please help me to get the values of "rs485Msg" & check for checksum on this line
Below is my code snippet:
 typedef struct
    {
      uint8_t AB;     ///< Address byte (Start byte)
      uint8_t CB;     ///< Command (index) "ASCII-byte"
      uint8_t SI;     ///< Action (sub index) "ASCII-byte"
      uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
      uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
      uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
      uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
      uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
      uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
    } rs485_message_t;

    uint8_t proto485ValidCheckSum(rs485_message_t message)
    {
      uint8_t rawChecksum = (message.CB - OFFSET_ASCII) + (message.SI - OFFSET_ASCII) +
        (message.PH1 - OFFSET_ASCII) + (message.PH0 - OFFSET_ASCII) +
          (message.PL1 - OFFSET_ASCII) + (message.PL0 - OFFSET_ASCII);

      uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message.CS1 &&
        ((rawChecksum & 0x0F) + OFFSET_ASCII) == message.CS0;

      return res;
    }

    void RS485TaskSlave(void *p_arg) //b - RS485 communication Task
    {
        uint8_t res;
        rs485_message_t rs485Msg;
        uint8_t command, action, value;

        (void)p_arg;
        while(1)
        {
          res = driver485Read((uint8_t *)&rs485Msg, RS485_MSG_LENGTH);
          if(RS485_MSG_LENGTH == 9)
         {
            res =  proto485Compare((uint8_t *)&rs485Msg, command, action, value);
         }
        }
    }

    int16_t proto485Compare(uint8_t* message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev)
    { int j = 0;
      rs485_message_t rs485Msg;
      char res;
      uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
      uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

     if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message))) //
/*GETTING ERRORVON THIS LINE please help how to pass message value to verify checksum at this line*/
      {
      printf("compare command..........");

        for (j=0; j<9; j++)
        {
          arduinodata[j] = message[j];
          printf("%d ",arduinodata[j]);
        }
        printf("\n");

        if(compareArray(FWmsg,arduinodata,7)==0)
        {
          uint8_t add, fwc, fwa;
          uint16_t fwv;
          res = GetABFWversion(&add, &fwc, &fwa, &fwv);
          res = proto485OnlyWrite(add,fwc, fwa, fwv);
        }
      }
      else
      {
        printf("Arrays have different elements.\n");
      }
      return res;
    }

Remove your casting, and change your message parameter to be rs485_message_t *:
int16_t proto485Compare(rs485_message_t * message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev) {
    int j = 0;
    rs485_message_t rs485Msg;
    char res;
    uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
    uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

    if(proto485ValidCheckSum(message))) { ...

And when you call it, simply:
res =  proto485Compare(&rs485Msg, command, action, value);

To get at the individual bytes you can then cast a new variable:
uint8_t *messageAsBytes = (uint8_t *)message;

Then you can use:
messageAsBytes[i]

etc.
However another cleaner way is to create a union in your structure:
struct rs485_message_t {
    union {
        uint8_t bytes[9];
        struct {
            uint8_t AB;     ///< Address byte (Start byte)
            uint8_t CB;     ///< Command (index) "ASCII-byte"
            uint8_t SI;     ///< Action (sub index) "ASCII-byte"
            uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
            uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
            uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
            uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
            uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
            uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
        };
    };
};

So you can now access message->CS0, etc, as well as message->bytes[3].
You should also pass a pointer when you call proto485ValidCheckSum - purely to save memory.
uint8_t proto485ValidCheckSum(rs485_message_t *message)
{
  uint8_t rawChecksum = (message->CB - OFFSET_ASCII) + (message->SI - OFFSET_ASCII) +
    (message->PH1 - OFFSET_ASCII) + (message->PH0 - OFFSET_ASCII) +
      (message->PL1 - OFFSET_ASCII) + (message->PL0 - OFFSET_ASCII);

  uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message->CS1 &&
    ((rawChecksum & 0x0F) + OFFSET_ASCII) == message->CS0;

  return res;
}

And again call it with a pointer, which the first block of code does anyway.
In general, it's better to pass a single pointer to a struct around from function to function instead of cloning it each time.
You can also use "pass by reference" if you like, but I find it's better to stick to pointers when passing something around alot like this.

Thank you for reply, I have made above mentioned changed & run the code it is showing below errors....   1) on line  "if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message)))" it gives "type name is not allowed" and on line " arduinodata[j] = message[j];" it shows that "a value of type "rs485_message_t" cannot be assigned to an entity of tpe "uint8_t" "

@swanand Read my first code block and compare it to yours.

Sorry my bad, i have changed for message element reading it is working fine but I am still getting error on line " if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message)))" t gives "type name is not allowed" Please inform If I am doing something wrong....

@swanand Read my first code block and compare it to yours.

Thank you so much once again for providing guidance......


text:
Powering arduino with battery
I haven't tried so don't know if it works or not. So I got a 6v battery AA, is it possible to run my arduino uno which already got a code in it if I plug + pin to vin and - to GND? Without its USB?

Get a 5 battery holder and put 5 alkaline batteries into it. (5 battery holders are sometimes used to provide 6 volts from ni-cat or NiMh batteries, which provide ≈1.2V.
5 alkaline AA batteries would give you ≈7.5V, which gives you more "wiggle room" for the voltage regulator.
EDIT:
As Gerben pointed out in their comment, 5 AA batteries will drop below the minium voltage input to the Arduino's voltage regulator well before they are depleted. A 6 battery holder would let you use more of the total battery capacity. (At the cost of wasting the excess voltage as heat.)

With only 5 batteries, the voltage will drop below 6V when the individual batteries reach 1.2V. This will use, at best, only 66% of the capacity of an AA battery. I'd suggest a 6 AA battery holder.

The UNO recommends at least 7 Volts on the Vin. 6 Volt is the absolute minimum. As the AA batteries drain, the voltage will be below this 6 Volts very quickly.
I tend to use a 3xAA battery holder, giving around 4.5Volt, and connect that straight to the Vcc pin (bypassing the voltage regulator). This works just fine in most cases.

Sorry im quite new to this, but where is the vcc pin?

Is it the one in the ISCP?

Because my idea is that i want to use both the 3.3v and 5v pins, without using adapter or the usb cable

That is a very bad idea. You should never feed unregulated power into the VCC pin.

Eh, feeding battery power to VCC is only a moderately poor idea, and not always even that bad.

I meant the 5v pin.

Go and buy some 9v Duracell battery and use it . Put the plus in Vin and the negative in gnd  .
Also i noticed that you are a newbie to arduino  so  be aware.
5v pin in arduino it's an output voltage.
3.3 v also output voltage.
Vin is the vcc is An electronics designation that refers to voltage from a power supply connected to the "collector" terminal of a bipolar transistor. In an NPN bipolar (BJT) transistor, it would be +Vcc, while in a PNP transistor, it would be -Vcc.
Gnd mean ground .
Read this please.
https://www.pcmag.com/encyclopedia/term/53705/vcc


text:
Data Logging without Interfacing SD Card module
I want to log data to a text document without connecting the SD card module. I don't want to print the data on Serial Monitor I want to store it in a file. Is it possible? Can someone help me with it?
I am using a Arduino Nano on a Windows 10 system, and I want to know if there is an Arduino library to write logs to a file.

That is a problem for Ubuntu system, I am currently working on windows. I want to know if there is an Arduino library to write data into a .txt file directly available.

read the up-voted answer

To a file that is stored on the PC the Arduino is connected to?

it your not going to put the data on the serial port, and your not going to have a local storage option(SD card) how do you expect the data to get to said text document?

maybe they have such an Arduino library at Hogwarts

@Gerben Correct

One option, which is doable, but not elegant, is to store data in EEPROM.  You can't store much data, but if you don't want to use an SD card, and you don't want to talk via the serial port (or use Bluetooth, other communication protocols), that might work.  Not pretty, but if you need to store only a tiny bit of data, that is an option.    Here's an example; https://www.norwegiancreations.com/2017/02/using-eeprom-to-store-data-on-the-arduino/   User Juraj made a reference to a duplicate question where someone else mentions this as well.

You're asking the impossible, you want to create a file without attached storage (no SD card) and without outputting the data (via serial) to be stored. How else do you expect the data to be sent from the Arduino to your file?

The simplest answer is to install a program that handles serial connection and can write everything into a logfile. On Linux, CuteCom is a program like that. On Windows, putty can handle serial (as well as SSH and telnet), and has logging.
The more advanced soulution is to write a program (or a simple script) that can do that. You could make it to do some other stuff as well (like configuring the Arduino side), and you can run it in the background without user interaction.


text:
Reading and sending data from a micro SD card using Micro SD card adapter without using buffer
Actually,  I am trying to get data that appears in a .wav file, but I got the problem that it is not as fast as I need because, looking around the SD library I found that most of the bits are saved into the buffer and when the buffer is filled its information is sent.
However, I do not want it to happen. I just need the bits to get readed and next to be sent as soon as possible witout saving in the buffer.
Do you know if is it actually possible, to modify the SD library to change the transmition's parameters because As I wrote previously I do not want the buffer to be used.

To my knowledge, it's a feature of SD cards. Data can only be read in sectors (512 byte). Of course it's possible to modify Arduino libraries, and e.g. combine reading and playing the music. I fear you will learn a lot but won't become happy.

buffering would not slow it down very much. if it's not fast enough, unless just barely, it's for a different reason.


text:
How to control DC motor speed with L298N and Node MCU?
I want to control an RC car with a joystick in mobile. Currently, I can only make the motor move forward and backward but not able to control the speed. Node mcu is used as a processor to receive the message.
Here is the code below:-

#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
#include <L298N.h>

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

const char * pubkey = "";
const char * subkey = "";

const char * subchannel = "base";

#define ENB D6
#define IN1 D3
#define IN2 D4

L298N motorL(ENB, IN1, IN2);

#define ENA D5
#define IN3 D1
#define IN4 D7

L298N motorR(ENA, IN3, IN4);

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(115200);

       Serial.println("Connecting to ");
       Serial.println(ssid);

       WiFi.begin(ssid, pass);
       while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }
      Serial.println("");
      Serial.println("WiFi connected");

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);

}

void loop() {

  int tim = millis();

    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    if (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);

            String X = getStringPartByNr(msg, ':', 0);
            String Y = getStringPartByNr(msg, ':', 1);

            X.remove(0,1);

            int Xcord = X.toInt();
            int Ycord = Y.toInt();

            Serial.print("X: "); Serial.println(Xcord);
            Serial.print("Y: "); Serial.println(Ycord);

            int angle;
            int throttle = (Xcord + Ycord)/2;

            if ((Xcord > 100) && (Ycord > 100)) {
              angle = round(atan2(Ycord-100,Xcord-100)*(180/3.14));
              motorR.forward();
              motorL.forward();
              motorR.setSpeed(abs(int(throttle*sin(angle))));
              motorL.setSpeed(throttle);
              Serial.print("R speed: "); Serial.println(abs(int(throttle*sin(angle))));
              Serial.print("L speed: "); Serial.println(throttle);
              //motorR.forward();
              //motorL.forward();
            }
            else if ((Xcord < 100) && (Ycord > 100)) {
              angle = 180 - round(atan2(Ycord-100,100-Xcord)*(180/3.14));

              motorR.setSpeed(throttle);
              motorL.setSpeed(abs(int(throttle*sin(angle))));
              Serial.print("R speed: "); Serial.println(throttle);
              Serial.print("L speed: "); Serial.println(abs(int(throttle*sin(angle))));
              motorR.forward();
              motorL.forward();
            }
            else if ((Xcord < 100) && (Ycord < 100)) {
              angle = 180 + round(atan2(100-Ycord,100-Xcord)*(180/3.14));

              motorR.setSpeed(200-throttle);
              motorL.setSpeed(abs(int((200-throttle)*sin(angle)*(-1))));
              Serial.print("R speed: "); Serial.println(200-throttle);
              Serial.print("L speed: "); Serial.println(abs(int((200-throttle)*sin(angle)*(-1))));
              motorR.backward();
              motorL.backward();
            }
            else if ((Xcord > 100) && (Ycord < 100)) {
              angle = 270 + round(atan2(Xcord-100,100-Ycord)*(180/3.14));
              motorR.setSpeed(abs(int((200-throttle)*sin(angle)*(-1))));
              motorL.setSpeed(200-throttle);
              Serial.print("R speed: "); Serial.println(abs(int((200-throttle)*sin(angle)*(-1))));
              Serial.print("L speed: "); Serial.println(200-throttle);
              motorR.backward();
              motorL.backward();
            }

            Serial.print("Angle: "); Serial.println(angle);
            //Serial.print("time: "); Serial.println(tim);

        }
    }

    sclient->stop();

}

String getStringPartByNr(String data, char separator, int index)
{
    // splitting a string and return the part nr index
    // split by separator

    int stringData = 0;        //variable to count data part nr
    String dataPart = "";      //variable to hole the return text

    for(int i = 0; i<data.length()-1; i++) {    //Walk through the text one letter at a time

      if(data[i]==separator) {
        //Count the number of times separator character appears in the text
        stringData++;

      }else if(stringData==index) {
        //get the text when separator is the rignt one
        dataPart.concat(data[i]);

      }else if(stringData>index) {
        //return text and stop if the next separator appears - to save CPU-time
        return dataPart;
        break;

      }

    }
    //return text if this is the last part
    return dataPart;
}

Port Reading:-

What can the problem be?

NodeMCU's PWM ranges from 0-1024 I believe. Not just 0-255. Also, make sure the pin is PWM capable. And try a minimal sketch like: motorL.speed(1000); motorR.speed(500); motorR.forward(); motorL.forward();

thanks will try it

That's  because the l298n library are used for the arduino or other microcontroller that have hardware PWM in their systems. The library using hardware pwm by generating pulses and make variations of the cyclic rapport aka "alpha" .
Esp8266 have no pwm in their systems
So try to use software pwm library for the esp8266

this is the link. https://www.arduinolibraries.info/libraries/soft-pwm

Also don't include that library and try to make it work using easy lines of codes.

u mean controlling pwm using duty cycles or analogWrite?


text:
Arduino help adding a second mpu 6050 sensor my working code
Background information: I currently have this arduino code that uses one mpu 6050 sensor to get angles in the x, y, and z directions and then display them to the user nicely. Code can be found here basic MPU 6050 code
The problem: I would like to add a second mpu 6050 to my project and average the values from the two mpu 6050s.
I know how to physically wire the second sensor into the project but don't know how to do the coding side of things. The code I have is below. Any help is greatly appreciated. This is a very fun tool.
#include<Wire.h>
const int MPU_addr=0x68;
int16_t axis_X,axis_Y,axis_Z;
int minVal=265;
int maxVal=402;
double x;
double y;
double z;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);
  axis_X=Wire.read()<<8|Wire.read();
  axis_Y=Wire.read()<<8|Wire.read();
  axis_Z=Wire.read()<<8|Wire.read();
    int xAng = map(axis_X,minVal,maxVal,-90,90);
    int yAng = map(axis_Y,minVal,maxVal,-90,90);
    int zAng = map(axis_Z,minVal,maxVal,-90,90);
       x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
       y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
       z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);
     Serial.print("Angle of inclination in X axis = ");
     Serial.print(x);
     Serial.println((char)176);
     Serial.print("Angle of inclination in Y axis= ");
     Serial.print(y);
     Serial.println((char)176);
     Serial.print("Angle of inclination in Z axis= ");
     Serial.print(z);
     Serial.println((char)176);
     Serial.println("-------------------------------------------");
     delay(1000);
}

Run a i2c scanner and tell us if two sensors are found. Why do you request 14 bytes and then use only 6 bytes? You could try a utf-8 character ° instead of (char)176.

Ok first did YOU wiring theme correctly? Because the mpu use i2c BUS .
Second this code from gitlab it may help you .
https://gitlab.com/shuvashish/batikkrom.com/blob/master/MuttipleMPU/MuttipleMPU.ino
Check it . And use it

Did you write that code? The lines with the while statement should be remove and 0x00000000 is not a byte.


text:
Distance Sensor. Calculating running median and average
I'm trying to smooth out values for my IR distance sensor through running median filtering and a running average. I've tried to do the averaging, but my values don't seem correct and I am confused about how I would do the median filtering. I am also using timer interrupts and I don't want to use libraries when calculating the average and median. I've attached the code where I attempted to calculate the average.
int analogpin = 5;
int sum = 0;
int index = 0;
int averead = 0;
const int numreadings = 9;
int i;
int timer1_counter;
int adc_val;
int int_flag;
int int_array[9];
float V;

void setup() {
  int_flag = 0;
  Serial.begin(9600);
  pinMode(analogpin, OUTPUT);
  for (i = 0; i <= 8; i++) {
    int_array[i] = 0;
  }

  noInterrupts();
  TCCR1A = 0;
  TCCR1B = 0;
  timer1_counter = 59286;
  TCNT1 = timer1_counter;
  TCCR1B |= (1 << CS12);
  TIMSK1 |= (1 << TOIE1);
  interrupts();
}

ISR(TIMER1_OVF_vect) {
  TCNT1 = timer1_counter;
  int_flag = 1;
}

void loop() {
  if (int_flag == 1) {
    adc_val = analogRead(A2);
    V = 5.0 * adc_val / 1023.0;
    analogWrite(analogpin, adc_val / 4);
  }
  sum = sum - int_array[i];
  int_array[i] = analogRead(A2);
  sum = sum + int_array[i];
  index = index++;
  if (i == 9) {
    i = 0;
  }
  averead = sum / numreadings;
  Serial.print("\n"); Serial.print("Average Filter Reading: ");
  Serial.println(averead);
  delay(1);
}

index=index++; does nothing. Either use index=index+1; of index++. Also, you are using i for the array-index, but only (try to) increment index. I think that should be i=i+1. Because nowhere else i is changed, you always overwrite the same element in the array.

You're using int_flag in an ISR, shouldn't it be volatile? Also in loop() you never reset it to 0. This can't be right...

There are two main problems with your program. The first is noted in
Gerben's comment: you (attempt to) increment index (with a bad
syntax), while you should be incrementing i instead. The second
problem is these lines:
for (i = 0; i <= 8; i++) {
    int_array[i] = 0;
}

Fix the index vs. i confusion, remove the lines above, and your
program should work.
Explanation: The first point should be obvious, I hope. I am
discussing here the second issue. At the end of the loop above, the
index i has the value 9. Later, in loop(), and assuming you fixed
the first issue, the program does
i++;
if (i == 9) {
    i = 0;
}

and i has the value 10. From there i will continue incrementing, and
you are always writing outside of the array.
The root of the problem is that you used the same variable i for two
different purposes. There are several solutions to this:

use different variable names for different purposes
use local variables whenever applicable (here: in setup())
be defensive in your tests: instead of if (i == 9) write
if (i >= 9), but note that this alleviates but does not completely
solve the problem
remove the initialization of the array altogether.

I suggest removing the initialization because the array is a global
variable and, per the C++ standard, if not explicitly initialized it is
implicitly initialized to zero, so your initialization is redundant.

Ok thank you. I will try that. Also, would you be able to explain to me how I would be able to calculate a running median as well? I'm pretty confused about that.

The OP does not seem to actually increment i, which might be the real problem. Also, sum isn't initialzed with analog values, so in my understanding averead will just be the last analog value divided by 9.

@SimSon: Indeed. I edited my answer.

@eateat: The simplest way to compute a running median is to copy the circular buffer into a temporary array, sort that array, and return the element in the middle. It may not be the most efficient way though. If you need a more detailed answer, look into existing running median libraries, or ask a proper question on this site.

analogRead() returns an integer and therefore your calculation V=adc_val*(5.0/1023.0) will be casted as int as well. I suggest changing it to V=5.0*adc_val/1023.0.
In general a running mean can be calculated like this:
#define buffer_size 9
#define analog_pin 5

int ring_buffer[buffer_size];
uint8_t index=0;
float running_mean() {
  ring_buffer[index]=analogRead(analog_pin);
  float mean=0;
  for (uint8_t i=0;i<buffer_size;i++) {
    mean+=ring_buffer[i];
  }
  if (++index>=buffer_size) index=0;
  return mean/buffer_size;
}

You should flush the buffer during initialization, otherwise you don't get proper readings before the 9th iteration.

Would that give a  proper average?

You didn't post a complete code snipped, so I can't say. But the line I mentioned will disturb averaging as the resulting resolution will decrease by 200 times.

But there is no magic about averaging: store data in a ring buffer and to calculate the mean: accumulate this biffer and divide by the buffer length

I'm doing that, but the values I am getting are very different from the unfiltered A to D readings (ie. like 247 for unfiltered and 63 for filtered).

I've added my full code.

Ok, I saw that you even don't use V and there are other parts in that code that do not make a lot of sense (at least in this snippet). Provide a minimal example that reproduces the error and is complete so we can compile it. Also you should enable compiler warnings, I'm sure there are some

So when I run the code that I gave you, it returns this:
Average Filter Reading: 61
Average Filter Reading: 61

Average Filter Reading: 60

Average Filter Reading: 61

Average Filter Reading: 61

Average Filter Reading: 61

Average Filter Reading: 61

Average Filter Reading: 61

you should tidy up or rethink/reimplement your code, you will then eliminate some errors, as there are: you don't reset your flag; you do not accumulate sum as you add and substract from it; you don't increment i even though you check its value. Google for "ring buffer" and you will understand how to write to int_array. You then need a function that reads a new analog value, writes it to the array and calculates and returns the average of int_array. This function can somehow substitute the actual analogRead() function.

Ok thank you. I will look into that. Also, how would I calculate a running median?

I can't say by heart, but that will not be the problem and only need some small changes. Also I don't think it will make a change as you only have 9 elements.

I've been kind and edited my answer with a possible function. Please note that I have no chance to test it right now

Re “your calculation V=adc_val*(5.0/1023.0) will be casted as int as well”: No, this is incorrect. It will be floating point.

Also note that, although the OP's original code has some errors, it uses an algorithm that is more efficient than the one you are proposing here.

Here is a simple alternative suggestion: Assuming you already know the average distance d and a new reading v comes in. The difference v-d can be used to update the average. But since you want you want to smooth this out over several readings, you only update d by a fraction of the difference: d += 0.8*(v-d). The factor controls the smoothing.
To get this started, you estimate that the first value you read is the average. This does not require an array to keep past readings around.

As the simplest IIR low pass filter, this is one of the most widely used. It is known as an exponentially weighted moving average.


text:
Maintaining time in Arduino
I am working on development of alarm clock using Arduino.
No doubt RTC will be the best but it increases the Price of the project. Also I opened a digital clock (which I purchased online) and I see that there is only one IC (obviously it is covered with something black wax). But there was that one patch only.
So it seems it used only a controller or RTC. But with only RTC its not possible to control LCD. So it must be only a microcontroller
Now I have three options for maintaining time

I use RTC like DS3231
I use millis() function
I use timer and timer interrupts of micro controller for free running timer.

Can I get accurate time using micro controller.

It depends, can you show us a photo of your arduino board? A 16MHz resonator is not accurate, but a 16MHz crystal is pretty good. You don't need interrupts, the millis can be just as accurate as the 16MHz crystal/resonator (when the sketch uses millis in the right way). The time library can be used with millis, and the time library can be used with the ds3231 as well, so it is easy to upgrade: https://github.com/PaulStoffregen/Time The time library works with the TimeAlarms library. If you want only a clock with hours, minutes and seconds, then you can use millis and write code for it yourself

I see from eBay that you can get the DS1307 for around 10 cents. Is that really too much to pay? You also need a crystal and a backup battery (eg. CR2032). Without a battery the device cannot possibly remember the time if it is powered off.
If your device is battery powered then you could conceivably just use millis(), however you would need to have a way of setting the time. The resonator used on a Uno is not as accurate as a crystal, however that might be good enough depending on your project.
If you are trying to save money I wouldn't use a Uno or Micro, but the bare chip, with a few extra components (eg. decoupling capacitors, a couple of resistors, and a crystal).

Yes, I am now making a project with all the available board, just after proving everything I'll go for separate IC's and components.