text:
Return mean of observations for a given sample time
new to this StackExchange site. I have an experimental setup with three inputs - two from a laser distance sensor to measure planar distance and one digital input from a set of callipers.
All sensors readings fluctuate over a small range (which is acceptable for my use case). Is it possible to have the Arduino record all inputs for a given period of time and output only the mean value for each sensor?

Just use an array. There's a tutorial on Smoothing on the Arduino site that may help.

To make life easy: https://github.com/MajenkoLibraries/Average

@Majenko That's pretty neat. Is there anything you don't have a library for?

@sempaiscuba I don't have one for making money :(

@Majenko That's a shame. I could really use one of them too. :)

https://stackoverflow.com/questions/4611599/smoothing-data-from-a-sensor?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

I have this:
int readElSens() {
  long sum = 0;
  int n = 0;
  long start_time = millis();
  while(millis() - start_time < 400) {
    sum += analogRead(ELSENS_PIN);
    n++;
  }
  return sum / n;
}


text:
Getting error while uploading a sketch through Ardunio IDE
I recently used the Ardunio board and powered with the AVR pocket programmer along with the AVR ISP cable and it worked just fine and no issues were experienced. However now that i switch back to the default method of powering Ardunio board with USB, getting this error while trying to upload the sketch.
There are forums available on Arduino platform but no definitive resolution.
The board is recognized by the IDE.

Did you put the bootloader back on after wiping it with the ISP programmer?

No i didnt. Do i need to put burn the bootlloader through USB cable or through the AVR ISP programmer?

Through the ISP programmer. The USB cable won't work until you put the bootloader back on.

Reinstall the bootloader using your ISP programmer.
Installing a sketch using ISP first wipes the chip clean, and that includes the bootloader. Without the bootloader the USB interface won't be able to communicate with the main MCU.

I have marked your answer as accepted and it worked ... thanks!!

source: Stack Exchange

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

sort: votes


text:
Custom function like yield
As far as I understand, yield() is used when you have long code (e.g. loop) so the background processing required by the esp8266 is not suspended for long time.
I have application where some sound should be running all the time and in the same time the program has to do other things which may includes long loops (that I call yield() inside them). Those long loops cause the sound to be discontinues.
What is the best idiomatic way of imitating the yield() function in my program so I do some thing like this:
for(int i=0;i<10000;++i){
    yield();
    customeYield();
    someFunction(i);
}

Where customeYield() contains the necessary instruction for playing the sound. It is exactly like this (I am using ESP8266Audio):
if (mp3_->isRunning()) {
    if (!mp3_->loop()) {
        mp3_->stop();
        return true;
    }
    return false;
}
return true;

Of course, I can just call it like I did (making it global or something). However, I was wondering if there is a standard way for such a task.

yield() must be called in some time interval or watchdog restarts the esp8266. you must call your function or the music stops. no magic. yield() does what is needed and returns.

Without any hint, what you are actually doing in your long loops, it is difficult to say, what way would be the best for your case. I don't believe, there is a standard way of doing this, but there are basically only two ways of multitasking on a microcontroller:

Interrupt driven: You can set a timer interrupt, that occurs regularly to call the AudioGenerator::loop() function (which fills the buffer with the next data).
Non-blocking code: If you are using non-blocking code, you can first do one thing and then do another in sequence, so fast, that both codes are executed often enough. Thats exactly what the library you use is designed for (according to the README file).

If you are using more than one of these long loops in your loop() function, you may consider doing things with a finite state machine (FSM), so that you don't have to always add the AudioGenerator::loop() function to your long loops, but only once for the normal loop() function.

Thank you very much for your reply. Actually, yes I am using FSM. However, I did not understand exactly how this will change things? At the end, if some state main function contains long loop it will still suspend the other code from being executed.. Did I miss sth ?

The FSM can help you to divide your long loops into small parts, so that one execution of the main loop() function does not take long. Then you execute the AudioGenerator::loop() in every cycle of the main loop() function. With this you suspend the long loop a bit for executing the background task (here: playing audio) in between. That is just a coding style. How exactly to divide the long loops into small parts depends on the code inside of them. I hope this is now clearer.

AH Ok! I got it now.. I thought there is native support for the pattern. I am implementing it the way you advice and It seems working.. Thank you very much!

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


text:
interrupt pin of attiny85 unstable
I'm trying to learn how to program a MC, so maybe I didn't know much about a MC. I tried to test interrupt pin of ATtiny85 with this simple code
#include <avr/io.h>
#include <avr/interrupt.h>

void setup()
{
  GIMSK = 0b00100000;
  PCMSK = 0b00000001;
  sei();
  DDRB = 0b00010000;
}

void loop()
{
  PORTB = 0b00010000;
  _delay_ms(500);
  PORTB = 0b00000000;
  _delay_ms(500);
}

ISR(PCINT0_vect)
{
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);

}

This is just a blink code with an interrupt to make the LED blink faster 10 times. My question is why sometimes the LED blink faster many times with the interrupt pin is not connected to anything (open)? Didn't it have internal pull up or should I use external pull up in my circuit?
Thank you

You only get an internal pullup if you actively turn that internal pullup on.

@Majenko so how to enabling internal pullup with use it as interrupt pin too? is it possible?

The interrupt functionality is completely separate to the IO functionality. Make sure the pin is an INPUT and set it HIGH will turn on the pullup. You need to know which DDR and PORT for the pin you're using as an interrupt of course.

You really shouldn’t have interrupts that take multiple seconds to finish executing. Interrupts should finish quickly so your main program can get back to its processing.

More than an answer, these are some comments and suggestions on your
program, that I hope will help you write cleaner code:

Since you seem to be avoiding using the Arduino core library, you may
as well write your own main() instead of relying on the one from
the core. This way you have a plain C program that can be compiled
either within or outside of the Arduino framework.
Instead of opaque constants, like 0b00100000, use the bit names.
These names are defined in the datasheet and are provided by the
avr-libc. They are normally used with the _BV() macro, which
expands to (1<<(x)).
For those of us who do not have the full datasheet in our head, a
comment or two stating what each bit does is helpful.
To change only one bit from a port, use the syntax PORTB |= ...;
or PORTB &= .... The compiler is smart enough to turn this into
single assembly instructions, namely sbi and cbi.
Rather than repeating ten times the same lines, use a loop.

Applying these suggestions, your program would like like;
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

ISR(PCINT0_vect)
{
    for (int i = 0; i < 10; i++) {
        PORTB |= _BV(PB4);
        _delay_ms(100);
        PORTB &= ~_BV(PB4);
        _delay_ms(100);
    }
}

int main(void)
{
    PORTB = _BV(PB0);     // internal pullup on PB0
    GIMSK = _BV(PCIE);    // enable pin change interrupt
    PCMSK = _BV(PCINT0);  // sense pin change on PCINT0 = PB0
    DDRB  = _BV(PB4);     // pin PB4 as output
    for (;;) {
        PORTB |= _BV(PB4);
        _delay_ms(500);
        PORTB &= ~_BV(PB4);
        _delay_ms(500);
    }
}

Wow thank you very much this is very helpful. This is very useful for beginners. And what's the double semicolon for? Is it like while(1)? Since there are so many tutorials with Arduino library, it's pretty difficult to find some code examples with plain C program (or not?)

The for(;;) is an infinite loop, just like while(1).

Did this code solve your problem with the double execution, that you mentioned below?

@juliussin: As stated by @chrisl, for (;;) introduces an infinite loop. I prefer it over while (true) because it feels natural to me to read it like “for (ever)”.

@chrisl I just tried this code, and this code didn't  solve the double ISR if I connect the interrupt pin to the ground with a jumper (I use breadboard to place my ATtiny85) and the repeated ISR if I touch the jumper pin. And unfortunately I doesn't have scope to check the signal of the interrupt pin :(

Is it because a bounce like on tactile push button? Just my opinion btw

I thought about this, but your ISR is way longer that any bounce from the button should be. During the ISR no other interrupt of the same kind can be queued, I think

The internal pullup is only activated, if you activate it in your code. To so, you have to write a 1 to the corresponding bit in the PORTB register, while the DDRB register is set for the pin to be an input.
So you the interrupt gets triggered randomly, because the pin was floating.
Since you are currently always write to the whole PORTB, you have to change the last bit to 1 on every PORTB write. Or you can write a 1 to it in setup() and only change the one output bit in PORTB by using
PORTB ^= 0b00010000;

This will toggle only your output pin.

Wow thank you, I'm using PORTB because I want to learn how register work and avoid to depend on library. So based on your suggestion I changed the last bit to 1 on every PORTB I wrote. I think this is worked pretty good. But if I touch the interrupt pin with my hand, the ISR run repeated. Is this because the trigger is unstable if I touch it?

This should not happen, if you activated the internal pullup resistor. I tried this with my ATTiny85 and it works perfectly.

I activated the internal pullup as you said by changed the last bit to 1 on every PORTB I wrote. But with the human touch, it's still unstable. And another problem, If i connect the interrupt pin to VCC, nothing happened (because it is pulled up right?) but if i connect it to GND, it run ISR twice, and then I release it, it run ISR once.

Odd behavior (that with the double execution). I couldn't reproduce that on my hardware. Maybe there is something odd with your wiring.


text:
Wake Huzzah Feather ESP8266 With Reed Switch
Forgive me if this is a really dumb question but I am new to IOT and hardware in general.
I have a Huzzah Feather ESP8266 and I am trying to make a bathroom occupancy sensor.  I am using a standard reed switch door sensor (example here).
Ultimately what I want this device to do is:

The plan is to wake the device from deep sleep when the door is closed, according to the documentation GPIO16 needs to be connected to RST to send a wake signal.
Once awoken check the reed switch and send a message to Azure IoT hub that says the bathroom is occupied if door is closed.
Put the device into deep sleep, waking every 30 seconds.
Every time the device wakes check the switch, once the door is opened I send a message to Azure that the bathroom is not occupied and then put into deepSleep(0) (i.e asleep until the door is closed again, then the process repeats)

Right now this all works but in the opposite. I can wake the device when the door is opened, the message sends successfully to Azure.
From my super limited understanding of this it seems like what I want to do should be possible.  I imagine I am missing something very simple, but I have hit a wall here.
I dont know how to make wiring diagrams so hopefully a description of my setup will suffice:

GPIO 16: Door sensor wire #2
RST: GPIO 16
GND: Door sensor wire #2

Simplified code sample:
void setup()
{
    initSerial(); //inits serial
    initWifi(); //initis wifi
    door_open(); //sends message
}

void door_open() {
  IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);

  if (iotHubClientHandle == NULL)
  {
    Serial.print("Failed on IoTHubClient_LL_Create\r\n");
  }
  else
  {
    // Because it can poll "after 9 seconds" polls will happen
    // effectively at ~10 seconds.
    // Note that for scalabilty, the default value of minimumPollingTime
    // is 25 minutes. For more information, see:
    // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
    unsigned int minimumPollingTime = 9;

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK)
    {
      Serial.print("failure to set option \"MinimumPollingTime\"\r\n");
    }

    if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK)
    {
      Serial.printf("failure to set option \"TrustedCerts\"\r\n");
    }

    if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, IoTHubMessage, NULL) != IOTHUB_CLIENT_OK)
    {
      Serial.print("unable to IoTHubClient_SetMessageCallback\r\n");
    }

    IOTHUB_MESSAGE_HANDLE messageHandle;
    if(digitalRead(DOOR) == LOW)
    {
      messageHandle = IoTHubMessage_CreateFromString("closed");
      Serial.println("Door closed");
    }
    else
    {
      messageHandle = IoTHubMessage_CreateFromString("open");
      Serial.println("Door Open");
    }

    if (messageHandle == NULL)
    {
      Serial.print("unable to create a new IoTHubMessage\r\n");
    }
    else
    {
      MAP_HANDLE propMap = IoTHubMessage_Properties(messageHandle);

      if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, sendCallback, (void*)1) != IOTHUB_CLIENT_OK)
      {
        Serial.print("failed to hand over the message to IoTHubClient");
      }
      else
      {
        Serial.print("IoTHubClient accepted the message for delivery\r\n");
      }
      IoTHubMessage_Destroy(messageHandle);
    }

    while (1)
    {
      IoTHubClient_LL_DoWork(iotHubClientHandle);
      ThreadAPI_Sleep(100);
    }
  }
}

To clarify:  Right now my device will wake when the door sensors magnetic parts are separated.  I want the device to wake when the circuit is complete (i.e the sensors are together).

Your code IS important here. It is most likely the cause of your problem. So show us your code (as text and properly formatted). Also: what do you mean with "AND RST"?

@chrisl added code sample, although the code is what I am most comfortable with (.NET developer).  The problem currently is that it wakes when the sensors are apart (door opened), I want it to wake when sensors are together (door closed)

@chrisl I tried to clarify my wire diagram in the edit too, One of the door sensor wires is in GPIO16, then RST has a wire to GPIO16, then the other door sensor wire is in GND

Why are you connecting the Reset pin of your ESP to the reed switch? This will hold it in a reset state, until you open the door

@chrisl I thought I was supposed to do that to get the device to reset.  I want the device to be turned on/woken from deep sleep when the door is closed.  According to what I have read about the ESP8266 to "wake" from deep sleep a signal needs to be sent to RST (from the docs: "GPIO16 needs to be tied to RST to wake from deepSleep").  This was just how I thought it worked.

I would get an NC or NO reed switch, the opposite of whatever you have now that's backwards. I would then get rid of all the sleep wakeup stuff and turn the unit on through the reed switch, so it has power when the door is closed, if that's more common than it being open. When closed (powered), the MCU sends a ping on boot to a server that says "hey i closed", and go to deep sleep for 10 seconds.
Once re-awaking, send out a ping that says "I'm still busy". The server needs a tiny bit of smarts, a time-out feature that sets the door state as open 12 seconds after the last ping (10s + some accounting for wifi delays).
This setup uses NO standby power, and only a tiny amount of battery-killing on-time, so it should last a lot longer than trying to sleep and externally wakeup.
For added efficiency, consider building an ESPNOW router with two more ESP8266s. Once you have that ESPNOW router up and running, you can fire off a ping in about 200ms (from a cold/warm boot) instead of 2000ms with wifi, and go back to sleep. This extends your battery life ~10x, at the cost of running two more ESPs 24/7 where power is easily available.

The RST (reset) pin of the ESP works as the reset pin of any other microcontroller. If you pull it to LOW long enough (the threshold is surely listed in the datasheet), the whole microcontroller will reset as if you had cut and reestablished the power supply. So it will not wake it from sleep, but reset it completely.
It is correct, that you can use GPIO16 connected to RST, to let the ESP reset itself from a deep sleep. This seems to be an internal hardware functionality, that is distinct from the normal IO hardware. But you cannot use the same pin for some other functionality at the same time. Your reed switch is closed, if the door is closed. So it gives a LOW level to GPIO16 and RST, holding it in reset state. In this state no code is executed, thus you never get a message, that the door is closed. When you then open the door, the switch opens too. Since the RST pin isn't pulled to LOW anymore, the ESP can boot and execute your code. The door is open, so you get the corresponding message.
So you have to use a different pin for the reed switch.

Is it possible to include a very straightforward "wiring diagram" to achieve what I want to do, I am very new to this haha

Just connect the one wire from the reed switch to an unused pin of the Feather and set your code to the corresponding pin. I don't have a Feather and cannot be sure, what a good choice would be. But how about GPIO4 or 5. You don't seem to need the I2C hardware on them.

So one wire from the reed switch into GPIO5 lets say, then where would the other go, RST?  Doe's the switch need to be grounded?

Do you know how detecting the state of a switch works? It doesn't seem so. The other wire from the reed switch has to go to ground, so that the pin is pulled to LOW, when the switch is closed. Also you should activate the internal pullup resistor with pinMode(DOOR, INPUT_PULLUP), else the pin will be floating when the door is open and will randomly change it's state. You should study a tutorial for switches/buttons, so that you really understand, whats happening there

Like I said in the post, I am an absolute beginner in hardware.  I have zero electrical engineering experience.  I want to make sure I am understanding you right, thats why I am asking supplemental questions.  Are you saying that my exact setup will work if I switch from GPIO16 to GPIO5?  So Reed switch 1 to GPIO5, GPIO5 to RST and Reed Switch 2 to GND

No, Reed switch 1 to GPIO5, RST to GPIO16 and Reed Switch 2 to GND. The whole point of my answer was to NOT use the same pin for reed switch and wake up simultaneously. Waking up from deep sleep is a hardware function, that can only be used on GPIO16. So you have to move the switch to another pin.

Ok so with that setup my switch will not wake the device up at all right?  Since nothing is attached to RST.  This is why I was confused with your comments.  As far as I can tell that setup would move me further from my goal.

Let us continue this discussion in chat.


text:
LiPo + charge/boost circuit vs pre-built "power bank" - contrasting portable power sources
Portable 5V power for my projects - I was about to get the necessary parts to wire up an OEM LiPo battery (3.7V battery, boost circuit, charging circuit) when I took a peak at pre-built "power banks".  From all the sources I see the LiPo batteries alone cost more than the power bank, at much lower capacity.  For reference:

a 10400 mAh power pack (max output 3A @ 5V) is 26$ on Amazon
a 10000 mAh power pack (max output 2.1A @ 5V) is 9$ on Hobby King
a 2500 mAh LiPo is 17$ on Amazon
a 5000 mAh Lipo is 8$ on Hobby King

The power packs already have charging and voltage regulation circuitry! The price difference makes me think I am missing something.
Reading around I notice issues with power packs auto-shutdown at low current draws. But other than this power packs seem cost optimal and technically equivalent - at least within the output amperage range of the power banks.
Questions:

Are there any technical differences in output voltage, lifetime, or otherwise I am missing here?
Are there any "surprises" I'm going to face by using a power pack?
Can you recommend a solid power pack that doesn't shut down at arduino level draws. (My app will draw 800mA @ 5V max, but during sleep, the draw of an Arduino Nano)

Thanks!

This would be better posted at https://electronics.stackexchange.com - perhaps someone can move it?

fwiw, i've bought about 10 power banks and diy shells. All of them want at least ~70ma to stay away. You can get creative with supercaps or watchdogs to work around that. Or KISS: don't use sleep and they are great. Also, some battery charging modules have the same feature, so check your datasheet.

The thing to remember with power banks bought on places like eBay and Amazon is:

THEY LIE ABOUT THE CAPACITY

A typical power bank you would expect to get around 3600mAh from, even though it may say 10000mAh, 50000mAh, 1,000,000,000,000mAh, etc.
The only technical difference between rolling your own circuit and a power bank is the low-current switch-off that many (but not all) of them have.  That switch-off is fine if you are always drawing a good amount of current, but once your device goes to sleep and the current drops right down you'll find the power bank will switch off and your device will never wake up again.
However, with rolling your own system you know what you are getting. You know the capacity of your battery.
One further thing to consider: Do you really need 5V? The majority of electronics run from 3.3V nowadays, and the Arduino is no different. There are Arduino boards designed to run from 3.3V, and even 5V boards can be tweaked to run at 3.3V (albeit slower than normal).
So the ideal solution would be:

A single-cell Li-Poly / Li-Ion giving nominal 3.7V
A Li-Ion charger circuit
A low-dropout or switching regulator with max 400mV dropout.

And no boost circuit needed. Also, no logic level shifting when communicating with 3.3V devices.


text:
How to configure location of preferences
I had been using Arduino 1.0.5 on my Pi, and in September last year downloaded arduino-1.8.4-linux32.tar.xz (which I have since updated).
I have been successfully using 1.8.5, but just noticed it seems to have been /home/pi/.arduino15 for preferences and packages.
I probably did this inadvertently when I was briefly running both 1.8.4 and 1.0.5 (which is long gone). I have /home/pi/.arduino but this only contains preferences.txt and has not been used since September.
There seems to be no  way of changing this to the normal directory; where is this configured?

That is the normal directory.

they can be in a couple places, grep is your friend.

Since the introduction of many enhancements in the IDE, such as the Boards Manager, and the Arduino Builder system, it was decided that this would break backwards compatibility with older versions of the IDE.  In version 1.5.0 of the IDE it was therefore decided that the location of all the Arduino data files (of which there are now many, not just a preferences.txt file) should be moved to a new location, and .arduino15 was chosen to reflect the current version.
Since then a version number war broke out between the two Arduino factions, which was then subsequently resolved, and we ended up with the 1.8.x group of versions. These, since they haven't introduced anything drastic to the underlying system since 1.5.x, haven't needed to change the location of the data files (indeed, to do so would be undesirable), so it has remained as .arduino15.
I don't believe it's possible to change the preferences location, since the only place would be in preferences, and it would need to load the preferences to know where to load the preferences from.
If you really need to access the preferences.txt file yourself as ~/.arduino/preferences.txt (why would you?) then you can just delete the old .arduino directory and create a link to the new one:
$ rm -rf .arduino
$ ln -s /home/pi/.arduino15 .arduino

Update:
There is a command-line argument to the Arduino IDE that lets you set the location of the preferences.txt file (detailed here):
$ arduino --preferences-file /home/pi/.arduino/preferences.txt

However what that will do with an old preferences.txt file is anyone's guess.

Thanks for the explanation. I probably jumped to the conclusion that this was related to the older 1.0.5. The question now becomes do I need .arduino and where did it come from? It seems to date from the installation of 1.8.4

.arduino was created by 1.0.5.


text:
Stopping / starting DC motor with Limit Switches and on/off button
I have an Arduino UNO with 3 switches attached (2 limit switches, 1 activation switch). I'm trying to make the activation switch turn the motor forwards once hit, then wait for any of the limit switches to be hit and stop the motor. The next step is to wait for the activation switch to be hit again and turn the motor in the opposite direction and wait for the limit switch to be hit and stop the motor.
But the issue I'm facing right now is when i press the activation switch the arduino board and H bridge board restart. The LED's turn on and off and the code restarts. And nothing happens. I know all the switches and motor is working because i have tested them by simplifying the code with just the functions.
(edit) Here is a picture of the schematic:
Can someone please review my code below to see if my logic is correct.
const byte  frontButtonPin = 2;
const byte  backButtonPin = 4;
const byte  onOffButtonPin = 11;
const int   motorPin =  8;
const int   motorPin2 =  7;

boolean  frontButtonState = 0;
boolean  backButtonState = 0;
boolean  onOffButtonState = 0;

/**
    setup inputs for switches and outs for motor pins
    serial begin to read the switches to test for errors
*/
void setup() {
  // initialize the pin as an inputs:
  pinMode(motorPin, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(frontButtonPin, INPUT);
  pinMode(backButtonPin, INPUT);
  pinMode(onOffButtonPin, INPUT);
  Serial.begin(9600);
}

/**
   this function turns motor foward
*/
void drawMovesForward() {
  // turn motor foward:
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, HIGH);
}

/**
   this function turns motor backwards
*/
void drawMovesBackward() {
  // turn motor in other direction:
  digitalWrite(motorPin, HIGH);
  digitalWrite(motorPin2, LOW);
}

/**
   Stop the motor form moving
*/
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}

/**

*/
void loop() {

  frontButtonState = digitalRead(frontButtonPin);
  backButtonState  = digitalRead(backButtonPin);
  onOffButtonState = digitalRead(onOffButtonPin);

  if (onOffButtonState == HIGH) {
    if ( frontButtonState == LOW ) {
      drawMovesForward();

    }

    else if (backButtonState == LOW ) {
      drawMovesBackward();
    }

  }
  else {
    if ( frontButtonState == HIGH ) {
      stopDrawFromMoving();
    }

    else if (backButtonState == HIGH ) {
      stopDrawFromMoving();
    }
  }
}

Welcome to StackExchange. I'm pleased to say you have made an excellent start by formatting your code and giving details in your description of your problem. Your logic looks good to me. To start troubleshooting, I would put println() statements in each of the functions, and try to work out where the program is hanging. When you say the "LEDs turn on and off", what LEDs are you referring to? This is where a schematic might help us troubleshoot, but you have mentioned that the parts are working by themselves.

Presumably you are currently testing with the parts disconnected (not installed in the drawer?). This makes it a lot easier to identify what is going wrong.

Thanks, I had a professional programmer help me program the Arduino but he has never used Arduino stuff before so he recommended using this website to look for other peoples advice. The LED's are the LED's on the arduino board. they turn on and off again and the arduino boards reset (they turn off and off again) when the back limit switch is hit and i hit the on/off switch at the same time.

Can you edit your question to mention whether the circuit is using a "toggle" or push-button activation switch? I presume it is a "toggle" switch as otherwise your code would only work by holding down a pushbutton switch.

Yeah there just momentary push buttons, push the button and let go. Also i actually fixed the code and now it works fine. Should i update the original post to say "problem solved" and then insert the code and how i fixed it? or do i do that somewhere else?

That's brilliant news! If you solved the answer, please post a new answer below with your solution (how you solved it, and your latest code), to help anyone else with the same issue. Your answer will then rise to the top, so people can see what the solution was. Then "mark your answer" (select the check/tick icon), and upvote any other questions or answers you find helpful on the site (you may not have the privileges yet, but you soon will). Well done!

I am currently working on a dumb-waiter project. things seems to go smooth when I made the simulation on the breadboard and using buttons. Once I replaced some of the buttons (the switch for each floor) with limit switches, everything go wrong. and then I read this post, and it saved me. all I need is just "delay(100)" inside the loop . thanks Man.

What is the correct code for this Project that is working right?
I would like to try it thanks.

@andiyunus That may fix the issue for now but it's not the right way to do it, and you may run into issues down the track. The real way to fix that is by using debouncing in your code (google that) as well as pull-up (or down) resistors on your limit switches.

@ChrisBrand I kept adding to this project over the years so it has become a little more complex. You can view the source code here in the repo:

I know this was opened years ago now but I just wanted to add some clarification. When I started this project and created this question I had 0 understanding of software development and didn't understand the code I was writing at the time. Now 3 years later I have revised this project multiple times.
The logic for a project like this is pretty simple, but if you're new to programming and trying to get into the STEM field with Arduino school projects and such, here is what my code now looks like for this same project:
https://github.com/LeehamElectronics/Automated-Cabinet
I have tried to comment it as best I could to help other students understand it. The project is simply a timber cabinet that has an electrically automated draw inside that can be opened and closed at will.
If you are stuck with a similar problem with your own project, I would suggest that you watch a free YouTube video course for C++ programing or even a Arduino programming video course. Even just a few hours of doing that will be enough to get started. That's the one thing I wish someone told me to do when I was starting off 3 years ago, I was wasting hours and hours debugging code that I didn't understand because I just jumped straight into Arduino with little understanding of coding.
I hope this comment helps someone else out there in a similar situation to mine 3 years ago.
Cheers
edit: the answers given about debouncing and pull-up resistors are also important in these types of projects.

Check your switches have pull-up resistors
It would be helpful if your question included a schematic. Do you have pullup resistors in line with your activation and limit switches? If not, you might find the input is "floating" - that is, it will randomly return either HIGH or LOW. This would possibly cause the motor to go forwards and backwards, but because the loop is possibly occurring hundreds of times per second, you might not see anything moving. You need pull-up or pull-down resistors in the circuit so the Arduino can see a definite LOW or HIGH. See https://www.arduino.cc/en/Tutorial/Button for a tutorial with a resistor, or even better, use https://www.arduino.cc/en/Tutorial/InputPullupSerial and use the existing onboard pullup resistors on the Arduino, as suggested by Juraj below.
Potential Logic Error
There might be a logic error in this part of the code:
  if (onOffButtonState == HIGH) {
    if ( frontButtonState == LOW ) {
      drawMovesForward();
    }
    else if (backButtonState == LOW ) {
      drawMovesBackward();
    }
  }
  else {
    if ( frontButtonState == HIGH ) {
      stopDrawFromMoving();
    }
    else if (backButtonState == HIGH ) {
      stopDrawFromMoving();
    }
  }

Loop #1: Let's say the onOffButtonState is HIGH (someone has pressed the switch to ON). The drawer is closed, so the front limit switch is depressed, so frontButtonState is HIGH. So the program will execute stopDrawFromMoving, and do nothing. Currently you are saying nothing is happening, so this might be your issue.
What you will probably need to do is use flags and while loops. For example:
At the start of the loop() declare this
drawerMovingOutFlag = 1;

Then change the loop to contain:
if (onOffButtonState == HIGH) {
    if ( frontButtonState == HIGH ) {
        while(drawerMovingOutFlag == 1)
            drawMovesForward();
            if ( backButtonState == HIGH ) {
                drawerMovingOutFlag = 0;
                stopDrawFromMoving()
            }
        }
    }
    else ...

I'll let you do the rest!

not that button tutorial, please. use the the input_pullup tutorial https://www.arduino.cc/en/Tutorial/InputPullupSerial

Hey thanks for the fast reply. Yes i have resistors going down to GND on all 3 switches. And I've used the serial monitors to check all the switches and they work and are read correctly.

I'm working on the schematic now (:

Schematic is uploaded (: Thanks for your help

I actually had the right code all along but I just had to add delays when reading the limit switches and detecting the activation switches. Here is one of the original programs i wrote that i threw out thinking it doesnt work, but once the delays were added it works fine.
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin3 = 11;     // the number of the pushbutton pin
const int buttonPin2 = 2;     // the number of the pushbutton pin
const int motorPin =  8;      // the number of the LED pin
const int motorPin2 =  7;      // the number of the LED pin

// variables will change:
boolean buttonState = 0;         // variable for reading the pushbutton status
boolean buttonState2 = 0;         // variable for reading the pushbutton status
boolean buttonState3 = 0;   // variable for reading the pushbutton status

int drawPosition = 2;  // Tells progam what position the draw is in

/**
 *  setup inputs for switches and outs for motor pins
 *  serial begin to read the switches to test for errors
 */
void setup() {
    // initialize the pin as an inputs:
    pinMode(motorPin, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);
    pinMode(buttonPin2, INPUT);
    pinMode(buttonPin3, INPUT);
    Serial.begin(9600);
}

/**
 * this function turns motor foward
 */
void drawForward() {
     // turn motor foward:
     digitalWrite(motorPin, LOW);
     digitalWrite(motorPin2, HIGH);
}

/**
 * this function turns motor backwards
 */
void drawBackward() {
     // turn motor in other direction:
     digitalWrite(motorPin, HIGH);
     digitalWrite(motorPin2, LOW);
}

/**
 * Stop the motor form moving
 */
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}

/**
 *
 */
void loop() {
   // read the state of the pushbutton value:
   buttonState = digitalRead(buttonPin);
   buttonState2 = digitalRead(buttonPin2);
   buttonState3 = digitalRead(buttonPin3);

   // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
   if (buttonState == HIGH) {
      drawPosition = 2;
      Serial.println(F("Front button state is high draw is open"));
      stopDrawFromMoving();
   }else if (buttonState2 == HIGH) {
      drawPosition = 1;
      stopDrawFromMoving();
  }

  if (buttonState3 == HIGH) {
    if( drawPosition  == 1 ){
      drawBackward();
      delay(100);
      drawPosition = 2;
      delay(100);
    }else if (drawPosition == 2 ) {
      delay(100);
      drawForward();
      delay(100);
      drawPosition = 1;
    }

  }
}

Please "Mark this as Answer", because this is the real answer to your problem.

That is an excellent project. Great work.
Some suggestions for improvement. You could use a enum class byte instead of a String for the drawer position and the drawer moving direction:
/* Allows the program to keep track of the last known position of the drawer */
enum class DrawerPositions : byte
{
  Closed,
  Open
} drawerPosition = DrawerPositions::Closed;

/* Keep track of what direction the drawer is moving, can one of the following:  Null | Closing | Opening */
enum class DrawerMovingDirections : byte
{
  Null,
  Closing,
  Opening
} drawerMovingDirection = DrawerMovingDirections::Null;
...
if (drawerPosition == DrawerPositions::Closed)
...
else if (drawerPosition == DrawerPositions::Open)
...
if (drawerMovingDirection == DrawerMovingDirections::Opening)
...

It would also be a good idea to add debouncing for all the switch inputs. There are many debouncing algorithms on the internet, but here is a very simple debouncer I put on GitHub which could be implemented something like this:
#include "Debouncer.h"
...
void loop()
{
  static Debouncer limitSwitch0(limitSwitchPin0);
  static Debouncer limitSwitch1(limitSwitchPin1);
  static Debouncer manualToggleButton(manualToggleButtonPin);

  limitSwitch0.Update();
  limitSwitch1.Update();
  manualToggleButton.Update();

  if (drawerIsMoving == true)
  {
    if (drawerMovingDirection == DrawerMovingDirections::Opening)
    {
      if (limitSwitch0.Output() == LOW)  // Get the debounced output of the switch.
      {
        drawerPosition = DrawerPositions::Open;
  ...
  if(manualToggleButton.Rise())   // For rising edge trigger.
  //if(manualToggleButton.Fall())  // For falling edge trigger.
  {
    ...
  }
  ...
}

Here is a debounce demo I put on Wokwi.

Thanks for your advice. I guess some of my laziness from Python crept into my c++ work doing silly things like using reference types to store, effectively 1s and 0s. I definitely should be using a primitive type such as a byte like you mentioned, I will most likely make those changes soon. As for debouncing, I haven't really had the need to use it much but I know I should, I'll add that to the to-do list. Thanks!!


text:
GPS is working but Distance is always showing 0. Can't calculate Distance in this code
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
static const int RXPin = 4, TXPin = 5;
static const uint32_t GPSBaud = 9600;

TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);
float temp1, temp2;

const char* ssid = "LYN TECH";
const char* password = "pass word";
const char* host = "your host name";
const int trigPin = 2; //D4
const int echoPin = 0; //D3
long duration;
int distance;
int t = 27;

void setup()
{
    Serial.begin(115200);
    Serial.println();
    ss.begin(GPSBaud);

    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    Serial.begin(115200);
    delay(100);
    //Serial.print("Connected to..");
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
}

void checkGPS()
{
    if (gps.charsProcessed() < 10) {
        Serial.println(F("No GPS detected: check wiring."));
    }
}

void loop()
{

    while (ss.available() > 0) {
        // sketch displays information every time a new sentence is correctly encoded.
        if (gps.encode(ss.read()))
            if (gps.location.isValid()) {

                float latitude = (gps.location.lat()); //Storing the Lat. and Lon.
                temp1 = latitude;
                delay(2000);
                float longitude = (gps.location.lng());
                temp2 = longitude;
                delay(2000);

                Serial.print("LAT:  ");
                Serial.println(latitude, 6); // float to x decimal places

                Serial.print("LONG: ");
                Serial.println(longitude, 6);
            }
    }

    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("Connection failed");
        delay(1000);
        return;
    }

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    distance = duration * 0.034 / 2;
    Serial.print("Distance: ");
    Serial.println(distance);
    Serial.println(WiFi.localIP());
    String url = "your url.php?dist=" + String(distance) + "&lat=" + String(temp1, 6) + "&lng=" + String(temp2, 6);
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                "Host: " + host + "\r\n" +
                "Connection:close\r\n\r\n");
}

You never set duration to anything. Also... what? It looks like you're mixing ultrasonic range finding code in with your GPS system.

Exactly ! i have tried to merge ultrasonic code with my gps code. But i failed maybe ! GPS is working fine but distance can't calculation in this code.

Do you have an ultrasonic range finder?

am using ultrasonic sensor to measure distance .

So how about you actually read from it then?

Oh, and ditch those delays. There is no call to use delay where you use it. And introduce some concept of time into your sending of data, so you don't flood your web server.

in my code i have written how it will works...but unfortunately isn't working . Only gps portion is working. Can you plz rewrite it for me. so that i can test again. i have to must send value of measuring levels with gps data. plz help me..

You never set duration to anything. ...

can you please rewrite it for me so that i can test again .

No, I can't. Just add in the missing code. The line that you didn't copy over from wherever you found the code. The line that actually reads the duration from the echo pin and saves it in the duration variable.

distance= duration*0.034/2; thats was the missing portion . i found it now. Thanks a lot @Majenko . now encountered another problem is my gps portion is executing after executing 80 times of printing distance in serial monitor . i just wondered why its taking too times to get inside GPS portions ?

Can you plz rewrite it for me? No, strong no, that's not why we come here.

extreamly sorry dear @dandavis . for the first time i have posted question in here. In rewrite i have mean which portion is need to correct . didn't mean to whole bunch of code again. Thanks to all of you for help me a lots .

no problem, welcome to stack!

To actually do the distance measurement with the ultrasonic sensor, you have to read in the echo pulse, that comes from the sensor. This is normally done with the pulseIn() function. Without it, you won't get any meaningful value. You have 2 portions of code: GPS and Ultrasonic distance measurement. Nice you say GPS works, try an example code for measurement with the ultrasonic sensor and understand it completely. Then you can merge the two codes


text:
Using TxD pin and NeoPixel library for RGB LEDs
I have no free pin on my ESP-12 but GPIO16 and TxD (GPIO1). I use Neo Pixel Library and this design:

GPIO16 powers it on/off
TxD uses to handle single-wire-based for LEDs (GPIO1)

It works but it has one issue. I use USB <> TTL converter to program my ESP, it just worked for 1 2 times and after that burned the converter! I'm afraid there's something wrong with my design. Any better idea to use GPIO16 and TxD to do that? I need to power down LEDs when I don't need them to save power.

I would consider optimising the rest of your design and free up some other pins to use.

There probably is something electrically wrong, but what cannot be determined from the information you posted.  You could disconnect the LED power supply while programming, but that only lessens the chance - whatever damaged components could still damage something else.


text:
ESP8266 and DHT22 frequent hangs
I have DHT22 sensor attached to an ESP8266. When running a sketch that read the sensor values, it suffer from frequent hangs (something like each 1 second).
All outputs are stopped (Sound from speaker or even the Serial output) during those hangs.
Here is a small Sketch to reproduce:
#include "DHT.h"
DHT dht(D1,DHT22);
void setup(){
  Serial.begin(115200);
}
void loop(){
  Serial.println(dht.readTemperature(true));
  Serial.println(dht.readHumidity());
  delay(1);
}

P.S. it is not about the small delay(1). Even if I read the sensor values each 1 second, this problem will occur. To make sure, you may run this example:
#include "DHT.h"
DHT dht(D1,DHT22);

void setup(){
  Serial.begin(115200);
}

unsigned long last = 0UL;
void loop(){
  if(millis() - last > 1000){
      Serial.println("#########" + String(dht.readTemperature(true)));
      Serial.println("#########" + String(dht.readHumidity()));
      last = millis();
  }
  Serial.println(String(rand()));
  delay(10);
}

After flashing it, opens serial monitor and you can see clearly the hangs (I put random number printing so your eyes can not cheat you by an cashed old value;) )

I have something with my nodemcu. Every day, at a random time, I get a shift in the values reported to thinger. Very odd, and I haven't got to the bottom of it yet.

@Majenko Does your setup also include a DHT22 with this library?

Certainly a dh22 though I don't know if it's the same library.

I just checked the library and it seems it disables all interrupts briefly while reading. That would explain the Serial (and other) blips, I think. It's not only blocking but also prevents others from interrupting it.

does it hang if you explicitly disable wifi (or use a brand-new ESP)?

@dandavis yes the same happens when WiFi was explicitly disabled

@TisteAndii Is this behavior the only way to make the library work? I mean should I accept it and go on. Or it could be done better?

@HumamHelfawi You can try this interrupt-driven library https://github.com/chaeplin/PietteTech_DHT-8266 and if it works, then make it an answer.


text:
Is this Arduino NANO counterfeit?
Today i bought my second NANO(First one was made of Gravitech).I have some doubts that if it is a counterfeit product.I have noticed some points & they are as follows.
1)No "NANO" printed on the top of the board.
2)The atmega328p is in MLF package.
3)A diode soldered on the back side of a board is not properly positioned.
4)No version is printed anywhere.
5)The word "ICSP" not printed near the ICSP header.
6)No pin marking(white dot) for ICSP pin#1.
The seller is a very reputable one in India.That's why i can't be 100% sure if it is a counterfeit product.
I am attaching some pics.Please take a look & give your valuable feedback.

enter image description here

I am just guessing when I say: the mlf package is no problem, the missing label "nano" on top and missing version might indicate a first test run. The misalignment is bad, that should not happen. The soldering quality is good. Is that a real ftdi chip, it probably is or else it stops working in windows. Overall it seems a genuine arduino board, but it might be a production test run.

Thanks a lot,that is a news of relief!
I tested the FTDI chip & it is still running correctly(without getting bricked).Also i have a counterfeit FTDI & some real FTDIs laying around.I compared this one with those side by side.Also from the physical appearance,this one looks genuine.

Have you seen the newest photos? https://store.arduino.cc/arduino-nano Two of the three photos have the mlf package, the white button, the yellow foil on the usb connector. After they made your board, they decided to add the name "nano" on top and the dot at pin 1 of the icsp connector.

Where did you find the arduino nano with mlf package in the Arduino page?I can see only two images both with tqfp packages!!And in my case,seems like they didn't decide to put the name nano on it

This is the same as the package in your photo: https://store-cdn.arduino.cc/uni/catalog/product/cache/1/image/500x375/f8876a31b63532bbba4e781c30024a0a/a/0/a000005_iso.jpg

strange!
I can't find this photo in arduino.cc website...But the direct link you provided is working fine!!


text:
Passing reference to hardware between methods in custom class
I'm a C++ / Arduino newbie, trying to build a custom library for the first time. I created a unit called CDSensors.cpp, which has two methods, SetupSensor and ReadSensors. The sensor is a SparkFun accelerometer/magnetometer.
If there are any errors in the settings, the sensor returns all zeros for compass and accelerometer. If there is no pointer or other connection between the SetupSensor and ReadSensor methods, the sensor returns all zeros as if it hasn't been setup.
So I'm trying to pass a reference to the sensor library between the methods as shown with the Limu object in the code below. I now get mag data but the accelerometer returns all zeros so something in my object references is messing with the sensor setup? (the accelerometer works ok in the SparkFun demo code, on which my code is based).
Main.ino
#include <CDSensors.h>
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>

CDSensors* LSensors = &CDSensors     (0);
CDSerialPrint* LSerialPrint = &CDSerialPrint (0);
MPU9250_DMP Limu = MPU9250_DMP ();
unsigned long LTimeNow = 0;

struct meas {
  int BUx;
  int acc_x
};

struct meas r;

void setup() {
  LSensors->SetupSensors (Limu);
}

void loop() {
  LSensors->ReadSensors  (Limu, LTimeNow, r.BUx, r.acc_x);
  Serial.print((int) (r.BUx) );
  Serial.print((int) (r.acc_x) );
}

CDSensors.h
#ifndef CDSensors_h_h
#define CDSensors_h
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>

class CDSensors {
  public:
    CDSensors(int);
    static void SetupSensors(MPU9250_DMP *imu);
    void ReadSensors (MPU9250_DMP *imu, unsigned long& TimeNow, int&     BUx,int& BUy,int& BUz,int& acc_x,int& acc_y,int& acc_z,int& a0,int& a1,int& a2,int& a3 );
  private:
    int value;
};
#endif

CDSensors.cpp
#include <Wire.h>
#include <SPI.h>
#include <SparkFunMPU9250-DMP.h>
#include "CDSensors.h"

//MPU9250_DMP imu;
boolean       MPU9250_found = false;
unsigned long TimeNow = 0;
CDSensors::CDSensors(int givenValue) {
  value = givenValue;
}

static void CDSensors::SetupSensors(MPU9250_DMP imu) {
  if (imu.begin() != INV_SUCCESS) {
    while (1) {
      Serial.println("No MPU-9250 found, Check connections");
      delay(5000);
    }
  }
  imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
  imu.setGyroFSR(2000);
  imu.setAccelFSR(2);
  imu.setLPF(188);
  imu.setSampleRate(100);
  imu.setCompassSampleRate(100);
}

void CDSensors::ReadSensors(MPU9250_DMP imu, unsigned long& TimeNow, int& BUx, int& acc_x) {
  TimeNow = millis();
  if (imu.dataReady()) {
    imu.update(UPDATE_ACCEL | UPDATE_GYRO | UPDATE_COMPASS);
  }
  BUx = imu.calcMag(imu.mx);
  acc_x = imu.calcAccel(imu.ax);
}

Is there a reason, why you are defining the MPU9250_DMP outside of your class and in your main sketch? If you declare it inside of the class as a member variable you can ditch the reference handling

Try passing the imu parameter by-reference (instead of by-copy), i.e. MPU9250_DMP& imu, to the SetupSensors and ReadSensors member functions.

@ChrisL When it was defined just in CDSensors class ithe sensor returned all zeros. I checked with local serialprint, I suppose somehow the connection between settings and reading data is lost.

@Nisse sorry tidied indents & typo, resolved your comment I think.

How die you define it in the class? Did you execute its constructor? If not, that might have been the problem

Can you post CDSensors.h?   I can't make any sense of CDSensors*     LSensors      = &CDSensors     (0); CDSerialPrint* LSerialPrint  = &CDSerialPrint (0);   As the warning says, you are taking the address of a temporary, something that ceases to exist at the end of that line.

Why are you using classes at all? Are there going to be lots of sensors? If so, making a member function static doesn't make any sense.

@Mikael, new to pointers, I tried MPU9250_DMP* imu and MPU9250_DMP *imu Either way I get  this error - no known conversion for argument 1 from 'MPU9250_DMP' to 'MPU9250_DMP& imu gives the same sub-sensor returning zeros problem.

@Nick re why classes - reason for moving this bit of code into a seperate .cpp unit is that the program is about to get a lot more complex, plenty of maths and GPRS comms, so the sensor setup/read seemed like a logical chunk to move out of the main.ino I am presuming that the seperate .cpp unit necesitates defining a class?

No, not at all.

And if you have changed the code, please post the amended code. We can't debug code we can't see.

Change static void SetupSensors(MPU9250_DMP *imu); to static void SetupSensors(MPU9250_DMP& imu); in both source and header file. Do the same change to ReadSensors. BW why are you using static for SetupSensors.

I don't think you are creating instances of these classes correctly. Instead of:
CDSensors*     LSensors      = &CDSensors     (0);
CDSerialPrint* LSerialPrint  = &CDSerialPrint (0);
MPU9250_DMP   Limu = MPU9250_DMP ();

How about:
CDSensors LSensors (0);
CDSerialPrint LSerialPrint (0);
MPU9250_DMP Limu;

I can't get your code to compile, but what I suggest looks a lot simpler.

Is your intention here:
if (imu.begin() != INV_SUCCESS)
  imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
  imu.setGyroFSR(2000);
  imu.setAccelFSR(2);
  imu.setLPF(188);
  imu.setSampleRate(100);
  imu.setCompassSampleRate(100);

.. to really be:
if (imu.begin() != INV_SUCCESS)
  {
  imu.setSensors(INV_XYZ_ACCEL | INV_XYZ_GYRO | INV_XYZ_COMPASS);
  imu.setGyroFSR(2000);
  imu.setAccelFSR(2);
  imu.setLPF(188);
  imu.setSampleRate(100);
  imu.setCompassSampleRate(100);
  }

The indentation suggests so.

if I understood correctly the class is created on startup with
       CDSensors* LSensors = &CDSensors (0);

and is then persistent.

LSensors is a persistent pointer but CDSensors (0) is a temporary object created for the purpose of doing an assignment. For example:
int foo = 2 + 3;

Now the compiler calculates 2 + 3 (giving 5), assigns that to foo, and then discards the temporarily-calculated 5 used to do the assignment.
In your case CDSensors (0) calls the constructor for CDSensors, creating a temporary object. Then the "&" operator takes its address (somewhere on the stack I would guess). This address is copied into LSensors. Then the object is destroyed because its lifetime is over. The compiler even warns you this is happening:
 CDSensors*     LSensors      = &CDSensors     (0);
                                                 ^
sketch_may07a:5: error: taking address of temporary [-fpermissive]

That means the pointer is now invalid because the underlying object (that it is pointing to) has now been discarded.

I've even seen people do something like this quite a bit:
     CDSensors LSensors = CDSensors (0);

This isn't so bad because pointers aren't involved, but it still involves making a temporary instance of the class, then copying that into LSensors, and discarding the original one.
This is how to make a new instance of a class:
 CDSensors LSensors (0);   // the actual class, not a pointer

Or if you want a pointer:
 CDSensors * pLSensors;  // a pointer to the class (initially NULL)

Then in setup you create the instance:
pLSensors = new CDSensors (0);

thanks Nick, I tried this variation, it also compiles ok, but still have the same problem with the accl sub-sensor returning zeros

Add some debugging prints, don't thrash around adding pointers in the hope it will fix things.

Also see my amended answer.

Re if (imu.begin() != INV_SUCCESS) sorryyyyyyy typo in code at the top, which is now corrected.

I wondered if it might be to do with constructors, but if I understood correctly the class is created on startup with CDSensors* LSensors  = &CDSensors (0); and is then persistent. (unlike what i'm used to in delphi where you can type create/destroy all over the place).

Pointers - right -  I suppose adding pointers saves resources but unlikely to fix a runtime bug.

See amended answer.

The third part is misleading. There's no point in talking about "invalid pointer", since the code itself is simply invalid: the language does nog allow applying built-in & to a temporary. This is non-compilable. I don't know why the OP keeps guessing whether the object is persistent or not. There's no point is that when the code is simply non-compilable.

The fourth part is misleading as well. Even in the old "classic" C++ the copy-initialization syntax is immediately interpreted as direct-initialization when the types on the LHS and RHS are the same. There's no temporary object created, there's no copying performed. The constructor arguments are immediately passed to the LHS object. Copy-initialization syntax in this case is repetitive, bulky and unnecessary, but it does not suffer fron inefficiencies you describe in your answer. It is fully equivalent to the "short" version.

I would add to AnT's comment in this way, why pass the Limu as a parameter to both functions when the constructed object is already global.  Just use Limu and remove the parameter in both methods.  If you really wanted to be 'OO' about it, you would pass Limu to the constructor. As it is you are passing an int that looks like is never used which I don't understand unless there is code missing or is planned for later.


text:
Arduino Libraries: Declaring variables as public?
How come I never see any Arduino Library expose some of it's internal variables as public in the header file? I only see functions which are declared as public, while every variable is declared private.
Background: I want to write my first Arduino library. And I thought of making some variables of this library public, so that I don't have to call a function later on when I import the library.
E.g. I want:
#include MyLibrary
...
MyLibrary instance();
instance.avariable = 12345;

instead of:
#include MyLibrary
...
MyLibrary instance();
instance.setVariable(12345);

Sometimes setting a variable isn't enough, as the library might have to do some additional thing with that new value. E.g. when setting the size of a buffer object, that object would also need to allocate memory for this (new) size. As far as I can see C++ doesn't have true getters and setters like other programming languages. getters and setters would make it seem like you are setting a variable, but will actually call a function.

I'd like to challenge the premise of this question.
Some Arduino classes do expose their member variables as public.
For example EERef exposes index, as does EEPtr.
Additonally, some classes declare their member variables as protectedso that inheriting clases can make use of them. The main reason though is usually because functions allow side effects to happen.

Classes are used to hide away the complexity of a certain task. The user of the class should not worry about how the library exactly works in the inside, but instead only worry about how it should be used. In many cases directly writing to a member variable can be not only convenient, but hurtful if a wrong value is set. If you instead use a function to set the variable, the author can add code to prevent wrong values from actually being written to the variable. Also there might be some other logic involved, that is not triggered, if you write directly to the variable. So - for the ease of use - the users might want the library to be responsible for this, not themselves.
If you write a library, you have thought about how it should be used. Hiding other ways away is a common way of leading the user through the usage. Ways of usage, that don't go along with the purpose of the library can be hided away to make the correct way clearer. A manufacturer of a saw doesn't give the user instructions how to use the wrong side of the blade, because it doesn't help you with sawing.
This does not mean, that you shouldn't make variables public at all, but only if it makes sense. For example: If you are defining a class, that just represents a point in a coordinate system without hooks to other code, it is totally OK to make the coordinates public. But if you defined the class, so that the point is directly shown on a display, you might want to change the position on the display, whenever one of the coordinates is changed. In this case you can use a set-function to trigger the display update, when a new value was given for the variable.

The Arduino ecosystem is meant mostly for beginners. This often means that people with very little knowledge will be using it and will often try random things to make stuff work. (and once they found something that works will teach it to the next guy that has the dame problem).
Disallowing things that would easily break the invariants of the library from the outset reduces the amount of support you need to give to people that inadvertently break the library by randomly changing some variable.


text:
Arduino: load variables with values read from SD card
I am having a bit of trouble loading values stored on an SD card and assigning them to variables within my program. I can achieve this as one big block of data, but would much prefer them to be saved to variables whilst in a loop or some other process.
My txt file has the following 6 ints & floats values, which are displayed vertically in the file:
2
0.003200
312
1
0.720000
8
Each of these values I want assigned to variables data1,....2,3,4,5,6. Unfortunately, the code I use below will never achieve this, but I am clueless as to any theory to solve this problem. Thanks in advance.
myFile = SD.open("test.txt", FILE_READ);
    if (myFile) {
    while (myFile.available()) {
        data = myFile.read();
    }
myFile.close();
}
else {
    Serial.println("Read Error");
}

These are values that change if anyone's thinking why don't I just hard code it instead.

Putting all such variables in a struct could be a good choice, as you can then copy the contents of the struct as raw data to/from the card (though getting at it from another system like a PC would require knowledge of how the Arduino compiler packs structs).  But you can also read the variables one by one; the big problem at present is that your code doesn't have any variables that it even attempts to load from the card.

File implements Stream just like Serial. so you can use parseInt and parseFloat
int n = File.parseInt();
float x = File.parseFloat();
Serial.println(n);
Serial.println(x, 6);

Thanks for the response. I have just had a search for readByteUntil, it sounds like it could be what I'm looking for, but how would this be implemented into my code. How would I distinguish which goes where?

Would I list the parseInts and floats according to the order within my list? And would I put this within the 'available()' method? Thanks.

in your case you do not need readBytesUntil. only parse the numbers like in the code snippet in my answer. parseInt and parseFloat skips the spaces.

myFile = SD.open("test.txt", FILE_READ);
if (myFile) {
while (myFile.available()) {
km = myFile.parseInt();
kmTemp = myFile.parseFloat();
kmrevs = myFile.parseInt();
miles = myFile.parseInt();
milesTemp = myFile.parseFloat();
milesrevs = myFile.parseInt();
        Serial.println(km);
        ........other printlns()
        }
    myFile.close();
    }
else {
    Serial.println("Read Error");
}

Is that what you mean. I could only squeeze in so many characters in this comment.

yes. are there more lines? then while (available()) is ok

The parse functions are only appropriate if you store the values as text.  If they are something like files created by a text editor on a PC that could indeed be appropriate.  OTOH if they are saved from one Arduino session to another, a direct binary copy of how the values would be stored in Arduino RAM may be more fitting.

No there is not more lines, the same data is replaced as and when required.


text:
Problem connecting Android app to Arduino
Sorry for doing this, I really don't know where to post beacuse this is both Android Studio code and Arduino code so I've posted to both sites.
I want to create a project of using controlling pan-tilt (2 servos combined) using the accelerometer and gyroscope data in smartphone. Creating Android app and sending the accelerometer and gryroscope data to Arduino so that the pan-tilt can determine its location.
My problem is when I connect the Android app to Arduino, no data is shown in serial monitor of Arduino and the pan-tilt is not locating the smartphone.
Please help me to solve this problem.
This MainActivity is the class to identify the data of accelerometer and gyrscope.
MainActivity:
public class MainActivity extends AppCompatActivity implements SensorEventListener{

    private final String TAG = "MainActivity";//log our activity

    SensorManager sm;//define sensor manager
    Sensor accelerometer, gyrometer;//define accelerometer

    TextView xValue, yValue, zValue, xGyroValue, yGyroValue, zGyroValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        xValue = (TextView)findViewById(R.id.xValue);
        yValue = (TextView)findViewById(R.id.yValue);
        zValue = (TextView)findViewById(R.id.zValue);

        xGyroValue = (TextView)findViewById(R.id.xGyroValue);
        yGyroValue = (TextView)findViewById(R.id.yGyroValue);
        zGyroValue = (TextView)findViewById(R.id.zGyroValue);

        Log.d(TAG, "onCreate: Initializing Sensor Services");

        sm =(SensorManager) getSystemService(Context.SENSOR_SERVICE);//permission to use the sensor

        accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (accelerometer != null) {

            sm.registerListener(MainActivity.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
            Log.d(TAG, "onCreate: Registered accelerometer listerner");
        }else {

            xValue.setText("accelerometer is not supported");
            yValue.setText("accelerometer is not supported");
            zValue.setText("accelerometer is not supported");
        }
        gyrometer = sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        if (gyrometer != null) {

            sm.registerListener(MainActivity.this, gyrometer, SensorManager.SENSOR_DELAY_NORMAL);
            Log.d(TAG, "onCreate: Registered gyrometer listerner");
        }else {

            xGyroValue.setText("gyrometer is not supported");
            yGyroValue.setText("gyrometer is not supported");
            zGyroValue.setText("gyrometer is not supported");
        }
    }

    public void connect(View v){

        DataSender dataSender = new DataSender();
        dataSender.execute((String) xValue.getText(), toString());
        dataSender.execute((String) yValue.getText(), toString());
        dataSender.execute((String) zValue.getText(), toString());
        dataSender.execute((String) xGyroValue.getText(), toString());
        dataSender.execute((String) yGyroValue.getText(), toString());
        dataSender.execute((String) zGyroValue.getText(), toString());

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        Sensor sensor = sensorEvent.sensor;
        if(sensor.getType() == Sensor.TYPE_ACCELEROMETER){

            Log.d(TAG, "onSensorChanged: X: " + sensorEvent.values[0] + "Y: " + sensorEvent.values[1] + "Z:" + sensorEvent.values[2]);

            xValue.setText("xValue:   " + sensorEvent.values[0]);
            yValue.setText("yValue:   " + sensorEvent.values[1]);
            zValue.setText("zValue:   " + sensorEvent.values[2]);
        }else if (sensor.getType() == Sensor.TYPE_GYROSCOPE){

            xGyroValue.setText("xGyroValue:   " + sensorEvent.values[0]);
            yGyroValue.setText("yGyroValue:   " + sensorEvent.values[1]);
            zGyroValue.setText("zGyroValue:   " + sensorEvent.values[2]);

        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

This DataSender is the class for sending the data to Arduino.
DataSender:
public class DataSender extends AsyncTask<String, Void, Void> {

    Socket s;
    DataOutputStream dos;
    PrintWriter pw;

    @Override
    protected Void doInBackground(String... voids) {

        String data = voids[0];

        try {
            s = new Socket("192.168.1.100",80);
            pw = new PrintWriter(s.getOutputStream());
            pw.write(data);
            pw.flush();
            pw.close();
            s.close();

        } catch (IOException e){
            e.printStackTrace();
        }

        return null;
    }
}

This is code that are uploaded in wifi module (esp8266-01) that are connected in Arduino.
Arduino code:
#include <SoftwareSerial.h>
#include <Servo.h>

#define DEBUG true

SoftwareSerial esp8266(10, 11); // RX, TX

char tiltChannel=0, panChannel=1;

//These are the objects for each servo.
Servo servoTilt, servoPan;

//This is a character that will hold data from the Serial port.
char serialChar=0;

// Center servos
int tiltVal = 90;
int panVal =90;

//smaartphone value
String inText;
float value0, value1, value2;

void setup() { // Open serial communications and wait for port to open:

  servoTilt.attach(2);  //The Tilt servo is attached to pin 2.
  servoPan.attach(3);   //The Pan servo is attached to pin 3.
  servoTilt.write(90);  //Initially put the servos both
  servoPan.write(90);      //at 90 degress.

  Serial.begin(9600); //for monitoring purposes
  esp8266.begin(9600);

  //sendCommand("AT+CIFS+RST\r\n", 2000, DEBUG); // reset module
  sendCommand("AT+IPR=9600\r\n", 1000, DEBUG);
  sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"EceConnect\",\"1234\"\r\n", 3000, DEBUG); //connec to
a network with name EceConnect with password 1234
  delay(1000);
  sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
  sendCommand("AT+CIPSTA=\"192.168.1.100\"\r\n", 1000, DEBUG);
  sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple
connections
  sendCommand("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // turn on server on port
80
  Serial.println("Server Ready");

  Serial.println("Android Sensor Type No: ");
  Serial.println("1- ACCELEROMETER  (m/s^2 - X,Y,Z)");
  Serial.println("2- GYROSCOPE (rad/s - X,Y,Z)");
  Serial.flush();

}

void loop() { // run over and over

  Serial.flush();
  int inCommand = 0;
  int sensorType = 0;
  unsigned long logCount = 0L;

  if (Serial.available() < 1) return; // if serial empty, return to loop().

    char getChar = ' ';
    if (esp8266.available()) {
      if (esp8266.find("+IPD,0,")) {
        delay(10);
        esp8266.find(":");
        delay(10);
        char letter = esp8266.read();
        Serial.print(letter); //for monitoring purposes
        //Gets the value/char from android app
      }
    }

    // parse incoming command start flag

    if (getChar != serialChar) return; // if no command start flag, return to
loop().

    // parse incoming pin# and value
    sensorType = Serial.parseInt(); // read sensor typr
    logCount = Serial.parseInt();  // read total logged sensor readings
    value0 = Serial.parseFloat();  // 1st sensor value
    value1 = Serial.parseFloat();  // 2rd sensor value if exists
    value2 = Serial.parseFloat();  // 3rd sensor value if exists

    // send smartphone readings to serial monitor/terminal
    if (DEBUG) {
      Serial.print("Sensor type: ");
      Serial.println(sensorType);
      Serial.print("Sensor log#: ");
      Serial.println(logCount);
      Serial.print("Val[0]: ");
      Serial.println(value0);
      Serial.print("Val[1]: ");
      Serial.println(value1);
      Serial.print("Val[2]: ");
      Serial.println(value2);
      Serial.println("-----------------------");
      delay(10);
    }

    // Check sensor type. If not for  Accelerometer (#1) then ignore readings
    // sensorType 1 is the Accelerometer sensor

  if (sensorType !=1) return;

  panVal = value0; // value0 = X sensor reading
  tiltVal = value1;  // value1 = Y sensor reading

  tiltVal = map(tiltVal, 10, -10, 0, 179);   // Map Accelerometer Y value to
tilt servo angle.
  servoTilt.write(tiltVal);
  delay(10);

  panVal = map(panVal, -10, 10, 0, 179);  // Map Accelerometer X value to pan
servo angle.
  servoPan.write(panVal);
  delay(10);
}

String sendCommand(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command); // send the read character to the esp8266
  long int time = millis();
  while ((time + timeout) > millis()) {
    while (esp8266.available()) {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug) {
    Serial.print(response);
  }
  return response;
}

"SoftwareSerial esp8266(0, 1); // RX, TX" you can't do that without breaking the serial monitor - whatever tutorial you are following is dead wrong.  Those pins are the hardware serial, you need to move your ESP to some other pins.

Possible duplicate of cannot read from softwareserial which covers the pin conflict mistake you have repeated here.

i change it to (10, 11) sir..
but still no data..

Try some basic ESP8266 examples before your worry about the whole Android integration problem.  Until you've proved your ESP8266 is connected and working, this has far too many parts to debug.

do you use Arduino Uno WiFi? you did tag the question with it

oh sorry sir..
i only use arduino uno and esp8266

In the loop function you have a line
If (Serial.available() < 1) return;

This prevents further code to be processed if there is nothing in the hardware serial buffer. Think about that.


text:
compare two hex files
I need to check if the code burned on the some Arduino is the same one as I have.
I know how to get the hex file from the Arduino. My question is what influence the hex code? Board Type? Microprocessor type? avrdude version? anything else?

The lines in a typical hex file include a VLI (variable length indicator). The hex files output from the IDE might have different lengths than those produced by avrdude. As a simple example:
File 1:
03ABC
03DEF

File 2:
06ABCDEF

Those files will compare differently to each other but convey the same information, split differently between lines.
To do a genuine comparison you would need to account for that.

Board Type?

Different boards, but with the same processor, might have identical files.

Microprocessor type?

Different processor would almost certainly have different hex files.

avrdude version?

Probably not, however see my comments above about the VLIs.

anything else?

As I said, the compiler may generate lines with (say) 16 bytes per line, but avrdude might read back lines with 32 bytes per line. Thus they would look different but convey the same hex codes, once you allow for that.

You may be able to use the copy of avr-objcopy included in the Arduino installation to copy a hex file to a newly generated hex file passing it through the same output generating code as would be used for a newly complied project made with that toolchain.  Then you can use diff.

dose compiler version also influance Hex file?

It might, because of different levels of optimization. Or even, that the command-line switches sent to your compiler are different to the ones used to make the hex file.


text:
Sound localization using two mics, Arduino Uno on MATLAB
I have been trying to achieve this for a long time using the ITD method and have gone through various articles on the net.
I want to know if its possible to actually achieve sound localization using an Arduino Uno and two MEMS mics with a high gain (https://www.sparkfun.com/products/9868).
I have been trying this on MATLAB using the a=arduino() command and readVoltage command but the main issue I face is that for a particular sound (clapping for instance) the time difference between the two mics is not always the same which results in different direction predictions.
We managed to increase the low resolution of the Arduino by removing unnecessary operations. Now we are able to get an array of size 750 for 10 secs giving a resolution of 0.01 secs. I am not sure if that is enough.
I basically have 3 arrays, one storing the sampling times, and the other two storing the amplitudes of the two analog inputs at that particular time in the first array.
Now I look for a peak in one and then the corresponding near peak in the second one and then compute the time difference. After this I can compute the angle using the speed of sound and the distance between the mics.
Please let me know how I can make this work or where I am going wrong.

Calculate the minimum distance given your setup. What do you get? And what parameter determines this and the increment/resolution? Also check your memory requirements. Remember that Uno has a total of 2K SRAM (and that must hold stack, heap, global variables).

What do you mean by minimum distance? The resolution improves with less number of operations and no delay statements. I tried changing the baud rate but it did not make a difference.

How far does sound travel (at normal room temperature and air pressure) in 0.01 sec and/or the time to perform an analogRead()? Software Engineering is also about "doing the numbers".

@MikaelPatel Do you mean to say I should put the sound source at a distance of at least ~3.43 meters (or multiples of this) for there to be measurable time difference?

How about the distance between the microphones? It is the delta between the source and the microphones you want to measure to determine the angle?

Yes,I'm sorry I meant that. But isn't there a better way out around 4 meters is a lot of distance between two mics...maybe to increase the resolution somehow? is the resolution proportional to the clock speed of the micro controller @MikaelPatel ?

Let us continue this discussion in chat.

Here is some info that might help you with the engineering: https://ese.wustl.edu/ContentFiles/Research/UndergraduateResearch/CompletedProjects/WebPages/fl09/rms3/Introduction.htm Please remember that the Arduino has a max sample rate of approx. 9 K samples per second when collecting all samples on the Arduino before processing.

I'm voting to close this question as off-topic because the limitations of an Arduino mean that it is not a useful part of a practical solution to the problem.  Further, an MCU board is entirely unnecessary here; instead of using an Arduino, you should just route your two microphones to the PC's stereo microphone inputs, and surely Matlab has some capability or plugin that can capture audio from there.  If your PC doesn't have stereo mic inputs, get a suitable solution to that problem like a stereo USB audio ADC (beware the cheap ones are mono, and you can't use two for this).

@ChrisStratton I wanted to build something wearable for source localization. Also I don't think I can connect the MEMs mics to the laptop.

If you are building a wearable, you cannot usw matlab for processing. Iit doesn't work on an Arduino. or you will habe to use an embedded system (that might work). Doing the processing on the Arduino might be the bigger Problem, depending in the logic.

You can absolutely connect analog output MEMS microphones to a laptop with analog stereo in; for digital out ones you'd need a suitable USB interface chip.  A higher end ARM MCU might be able to do it, but not an ATmega-based Arduino.  Even if your goal is to make something wearable, you should gain experience with the algorithms on a PC first.   Then port the algorithm to a smartphone type SoC or possibly a high end bare-metal ARM part (or if it's your preference, maybe a dsPIC)

@ChrisStratton thanks for the advice. Could you guide me to a suitable and reasonable analog stereo input device/jack I can buy for two mems microphones(https://www.sparkfun.com/products/9868).

Selecting PC peripherals is not really on topic here.  Just be sure you get something that has actual stereo input; the cheap dongle ones are typically only mono input, either with the channels shorted together or only one connected (but will have "stereo" in the name as their output side is).  You might try audio-oriented forums for recommendations.

@ChrisStratton I have asked the question  in sound stackexchange- https://sound.stackexchange.com/questions/44280/connecting-two-mems-mics-to-laptop-for-sound-source-localization

Let's assume a microphone distance of 0.5m (which may be just small enough for you). Sound travels with about 300m/s in normal conditions. Let's also say, that you want at least a precision in the angle measurement of 15°.
As stated in the project Mikael linked, it is important that the distance to the sound source is big enough (so that the waves can be seen as planar). Then you have the following situation:

We are interested in the difference in distance, that the waves have to travel to the two microphones. It can be calculated by delta s = d * sin(alpha). With 15° we get delta s = 0.13m. The time difference is calculated by delta t = delta s/v, where v is the speed of sound. We get delta t = 0.43ms which equates to 2.32kHz sampling frequency. Since we use two microphones that must be sampled sequentially, the sampling frequency must be doubled. In the end we have a sampling frequency of 4.64kHz. So your sampling time of 0.01s wouldn't be enough for that.
The largest time difference in this setup (with the sound source in line with the microphones) would be 1.6ms, so your sampling time would be too big even for this.
Regarding the transmission with a baudrate of say 115200 baud this shouldn't be a problem.
But the actual speed of your setup highly depends on your code, which you haven't shown. Maybe this forum post can help you going further.

Yes, but using an Arduino to sample audio on behalf of a PC only introduces extra complexity while drastically reducing the quality and amount of information compared to the internal sound card.

@chrisl Thanks for the detailed well explained answer. I'll try the procedure in the link. Please tell me if using a better micro controller (like- the NRF52 series https://www.sparkfun.com/products/13990) help in getting a better resolution.

also is there a way to speeden up readVoltage on Matlab somehow to get this working maybe to a less precision of 30-90 degrees and d=1-1.5m.

I don't know anything about the matlab functions. But Chris is right, that it will be easier to achieve with a direct connection from microphone to PC.

You should use the Arduino interrupt function.
This will get it to 4 micros. You cannot use delay on Arduino counting in micros that is needed.
You can have ca 10 cm between mics doing as follows:
You may use accelerometer instead of mic.
Serial read, don't work, too slow. Use ISR..together with Arduino clock is 16 MHz.
Gives a error in +- 10 micros.
Given that it's possible to get the angle within 0.5 degrees if using Sine/Cosine. But, the trigg appear at different places on the waves sinus, giving you extra errors at low freq.
Don't give up.  This works:

Attach interrupt (ISR) on 2 pins. Make all variable used in ISR volatile.
Use internal clock with micros() to stop at interrupt, flag a variable true if rising/falling/change.
Use the time difference from trigs for calculations.
Calculations do in loop, not ISR calculate using radians.
Don't try to read or write anything while in ISR or before calculations, that mess up the clock!
Use 11500 baudrate.
If in loop or ISR = true then disable interrupt by state variable.

I fixed a bunch of things in this post.  Please fix more and avoid texting shorthand.


text:
Arduino variables loaded from SD card
I am trying to load some variables from an SD card on the start up of my arduino Uno. I have been given some advice but am unable to communicate at the same hours. Using this advice, I have the following edited code, but it doesn't work and I believe that it's my implementation that is the problem. All help would be greatly appreciated.
myFile = SD.open("test.txt", FILE_READ);
    if (myFile) {
        while (myFile.available()) {
            myFile.read();

            km = myFile.parseInt();
            kmTemp = myFile.parseFloat();
            kmrevs = myFile.parseInt();
            miles = myFile.parseInt();
            milesTemp = myFile.parseFloat();
            milesrevs = myFile.parseInt();

            }
        myFile.close();
        }
    else {
        Serial.println("Read Error");
    }

How is it not working? Describe further. And what is actually written in the file you want to read?

The program gathers/calculates 6 pieces of data which is then saved to a text file on an SD card. The text file displays the 6 pieces of data in a vertical list. On power up of the arduino, I am trying to make the program read these 6 bits of data, assigning the values to 6 different variables before the program hits the loop (this script is within setup() if that eliminates a question).

When ran and then restarted the data output is at the programs defaults of '0' & '0.000000' where floats apply....not the data that is saved on the disk.

You still have not listed the file from your SDCard.  Make sure you are using a plain text editor for this.  For example, Microsoft Word or Adobe Framemaker would add an unbelievable amount of overhead that would confuse the parsing library.

what is actually written in the file you want to read? please answer this question.

After the parseInt, the next character will be you delimiter. For example a comma (,). The next time you call parseInt, it will see the comma, and return 0. Try putting a myFile.read(); between each parseInt/parseFloat.

myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
        myFile.println(km);
        myFile.println(kmTemp, 6);
        myFile.println(kmrevs);
        myFile.println(miles);
myFile.println(milesTemp, 6);
        myFile.println(milesrevs);
        myFile.close();
    }
else {
        // SD SAVE ERROR
        Serial.println("Save Error");
    }

That is how I save it. The test.txt file contains the following example numbers : 1, 0.001600, 12, 0, 0.072000, 0. These are listed vertically in the text file using println() in the save method just posted.

Gerben - I tried the myFile.read() which hasn't done anything different

in you previous question, where I answered, you had no commas or new-lines in the example file content. the parseInt and parseFloat ignores only spaces by default.
remove the commas or read them or ignore them with parseInt parameter SKIP_ALL
km = myFile.parseInt(SKIP_ALL);

Hi there is no commas, it's just in the comments section, whenever I press enter it posts the message instead of starts a new line....so I used commas to seperate the different data.

Hi Juraj. I have to admit, I have never analysed anything as much as your two answers. I feel that my bank holiday was no longer wasted as I have finally worked out what you meant. All is rolling amazingly now and it's just what I wanted. Thank you.


text:
Can increasing the size of the software RX buffer cause problem in Arduino Uno
If I were to increase the of the buffer array from 64 to say 512 will this bring any long term problem in the Arduino Uno.
Changing from this:
#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 64 // RX buffer size
#endif

to this:
#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 512 // RX buffer size
#endif

This is the header file of the software serial.

The buffer is in the UNO's limited (2K) RAM; you'd be using 1/4 of it for the input buffer. If your app is small enough and simple enough (limited call depth, specifcally), there may still be enough RAM for your app to run successfully. If you have lots of globals (remember to include libraries when you're considering RAM use), allocate much memory from the heap (with new or malloc()) or have a complex call structure such that funcA() calls funcB() calls funcC() calls ... (etc) so that many functions' stack-frames remain allocated at once - at any point in your program - your program could suffer a stack-collision: the call-stack descends low enough that it can overwrite, or get over-written by, your heap or global data.
Why do you want so large an input buffer? Will data be coming in a high rate or in large bursts, while processing of the data will be infrequent or occur at irregular times? Given the limited RAM in the UNO, running complex programs on one can require something of a balancing act in how you use resources.
Update:

i was performing some AT commands with software serial and buffer limitation generated junk value

Other reasons why SoftwareSerial might return bad data are:

Using too high a baud rate (9600 baud seems to be about the max);
Code that turns the interrupts off too often or for too long;
Other devices creating too many interupts (perhaps a built-in timer running at a high rate).

The replies to most devices' AT commands that I know of are short enough to not require a huge receive buffer. Asking for list of WiFi SSIDs from an ESP8266 could generate a large reply but most responses should not overflow a more modest buffer.

Thanks for the advice the thing is that i was performing some AT commands with software serial and buffer limitation generated junk value  but i think by just editing my code a little a bit i was able to fix this problem but i still a little bit more buffer memory

Most arduino modules have 2k ram. So think about that. Whether you need more buffer or more working space. Keep in mind that other libraries are also using the same ram.

I am  sending some character over software serial and 64 byte limitation is generating junk values i therefore increased the default to four times for more space to store my buffer

@Nolawisolomon maybe you can send the length of the message first, and then send the rest like in http. Thus receiver knows how many bytes it needs to reserve.

@Nolawisolomon - the RX buffer has little to do with transmission, unless you mean that you are transmitting in a blocking fashion and not paying any attention to received data until your lengthy transmission is done.


text:
Need help optimizing snake game code for Arduino Nano
Here's the code:
https://pastebin.com/ypWe4NZw
This is the output when I compile:
Sketch uses 13086 bytes (42%) of program storage space. Maximum is 30720 bytes.
Global variables use 1456 bytes (71%) of dynamic memory, leaving 592 bytes for local variables. Maximum is 2048 bytes.
Everything runs smoothly until getNextFood(), Line 194.  I try to make a LinkedList of integers from 0 to 255 (since I am using a 16x16 LED grid).  However, my list only fills up to about 39, then the rest are set to zero.  I suspected that I was out of memory, so I tried optimizing a few things and was able to get to 42.  I changed all the ints to bytes in the getNextFood function and got up to 61, but that broke my program somehow (inf loop).
Any suggestions on how to fix this?  If I can get this list to fit, the program is basically done, I have nothing else to add assuming it works as intended.
Also, why I am running out of RAM in the first place?  Can someone explain which parts of the program are gobbling up those bytes during runtime (because I would expect the integer list to take up around 512 bytes leaving 80 bytes left, so why I am getting cut off around 40 integers or 80 bytes?)
Thanks.
Edit1:  People have pointed out that linked lists take up a lot of space.  I am using this library because the way the program is designed, I needed to make an array that could change size.  I needed to be able to add and remove elements.  Maybe there is a better way to do it, I don't know.  I thought about making a single 16x16 array for the whole thing and using a different number for each type of piece.  I don't know how I would do the snake movement in that case though, because each piece is "connected" to the one in front of it.
If anyone knows of a similar library that would save space I'd be happy to try it.  Also there might be a way for me to avoid using the tempSnake list.
Edit2:  Per Paul's suggestion, I rewrote the code using a single 16x16 array to represent the entire game board, removing the need for LinkedList.  However, it seems I am still falling short, unless there is something else wrong with my code.  The program resets when I try to generate the food tiles.
https://pastebin.com/ZU4hX477

Stack Exchange sites are really reserved for problems that can be concisely stated on the question page itself.  You'll need to reduce your scope to something you can present without relying on a link.  Why are you using a linked list in the first place?  That will be extraordinarily costly on a system like this.  You should use a simple array - but unless you have brightness control even that is excessive, probably you want a bit-mapped array with only 1 bit per pixel.  You may also want to consider a more suitable platform like an ARM MCU with more memory, some work with the Arduino IDE.

If you are short on RAM, you should try to avoid making full copies of the lined lists. Also, you wrote //implement modulus for position: this operator is already implemented in C++, and you can write newRow = (newRow+1)%16, etc. But note that the numbers should be unsigned in order to get the desired behavior.

Do you really need the complexity and bloat of linked lists?

Using the F macro for Serial.print would shave off a few bytes. Serial.println(F(“example”));

You don't need a linked list to determine the neighbors of grid squares; that's a fairly simple math operation with some limits at the edges.  Crudely speaking left is index-1, right is index+1, up is index-16, down is index+16, etc then you check the edge limits.  Having a linked list for the snake itself is vaguely reasonable, though instead of an actual linked list perhaps what you should have is a fixed-length array of the index-differences to the next segment.

16x16 = 256
So there are 256 possible places to put a piece of snake.
The max length of the snake will be 256 (fill the board completely).
So if we take an array of bytes (0-255) that is 256 bytes long we could completely map the snake.
Every step you move (unless if the snake just ate some food) you put it's head forward one step, and remove the last part.
So if we make the new head the value of "snakeLength" and do each piece of the body -1 every round. We will get this "decaying" effect.
For example:
[ 6][5][4] (all -1, head down) [ 5][4][3]
[ 0][0][3]                     [ 6][0][2]
[ 0][1][2]                     [ 0][0][1]

This probably isn't the most efficient method (especially not if you scale it up), but in this case the logic would be very easy.
If the head collides with a position that is not 0, it'll be game over. For the food/apple you could use an x/y value.
If a space is not 0, do it -1.
The upside of this is that you don't allocate memory runtime and you know exactly how many you use.
This setup should also make it easier for you to avoid "copying" the whole list all the time, you can basically loop through the array and do -1 for all but those who are 0.

I like this idea, for the food what do you mean by x/y value?  Like just storing the row and column of the food somewhere? I was thinking to use some negative number like -1.

Great idea. You could reserve the value 255 for fruit, and add a check to see that it’s not 255 before decrementing. Maybe reserve 254 for walls. 253 for a teleport q-;

Still running out of RAM, LOL!  225 bytes available at compile time, crashes when generating new food tiles...
https://pastebin.com/ZU4hX477

Hmm, you should use bytes (8bit/1byte values), if you do -1, you'll either use an integer (2bytes) or have a range of -128 to +128

Hmm, check the variable 'int foodSquares[numZeros] = { 0 };' which uses 255x 2bytes. As well as your gameboard is using int instead of byte (which is half the size).

Also the LEDs take quite some space, if you use an SPI based ledstrip instead of neopixels, you can runtime calculate the values (since you're not bound to the clockspeed of neopixels), so they do not have to be saved.