text:
About multiple void loops and functions
I'm still a beginner at Arduino coding -- I've been researching on how to make functions using void instead of doing goto because reasons...
one thing I've noticed about void is that it has this void loop() {...} parenthesis, what is it for? (and can you provide an example of using it?)
say I make a void function void function1() to call the function I have to use function1(); can I make a function that loops? like the ol' void loop() {...} command we all know and love or do all void functions loop? if not then what happens to a void function after it reaches the end of its function?

The void in front of the function definition just tells what type the function returns.  In the case of void it means the function returns nothing.  If the function returned an int then it would be defined with int instead of void.
eg:
int addNumbers(int num1, int num2){
    int retval = num1 + num2;
    return retval;
}

int sum = addNumbers(3, 4);
Serial.print(sum);  // prints 7

No, the loop only loops because main (see main.cpp in the core) is the "real" program that is running on your micro and it calls loop over and over.  It's not that the loop function on it's own repeats.  It is literally being called repeatedly by the main function.
That example also gets to what the parenthesis are for.  That's where the arguments that the function takes go.  In the function definition you tell it what types they'll be and give them names.  In the function call you put in whatever values you want to function to use.  In the case of void loop(), it takes no arguments so the parenthesis are empty.
I would suggest you look at a basic tutorial on C++.  There are many good ones on the web.  The concept of functions isn't something that you can reason your way through by doing.  Go read a little and you'll get it pretty quick.

Is there any way to run multiple void functions at the same time?

Not on an Arduino.  It has a single core.  It executes one instruction at a time.

PC's that are capable of multithreading can be running several instructions at the same time, so they could be running multiple functions at the same time.  But Arduino can't do that.

Also note, they're just called functions.  Not "void functions".  The void is the return type.  It just tells you what the function returns.


text:
Arduino Mega - Multithreaded (run two loops simultaneously)
I am new to Arduino and I am not sure about how to get two loops run parallel to each other. I have tested the individual loops and both of them work perfectly before I combined them together.
One loop will take input from the LCD touchscreen. One loop will take input from vibration sensor which will determine the state (on/off) of LED. Once the LED is turned on, it has to stay at the ON state for 3 seconds before switching to OFF state.
The problem I am facing is that when the LED is triggered to ON state by vibration sensor, I have to wait 3 seconds for the input from LCD to get processed. Is there any way I can combine these two loops in such a fashion that I run them simultaneously, i.e. run two inputs together?

Arduino Due, Zero support multi-threading. You can try them.

Please search for delay on this site and you will find several questions similar to yours, and for some, answers that probably are relevant to you. What you want is replace delay(0) with something else: a timer or calls to millis() with comparison to some time reference.

Just answered something really similar here: https://arduino.stackexchange.com/questions/38713/problem-with-measuring-vibrations-arduino-uno-step-motor-accelerometer/38737#38737 please read it for reference

You can combine the 2 programs into 1 program.  But when you start wanting to do multiple things at once then you can't have any code that "blocks" and waits to finish before letting the next thing happen.  The Arduino has a single core, it can't do multithreading.  But if you write non-blocking code you can make things appear to happen at the same time.  I imagine the problem with your code now is that you have probably used the delay function.  That function blocks, so nothing else can happen while the delay is running.  Instead you have to use millis to record the time and periodically check against that time to see if it is time to take the next step instead of calling a delay to wait for the next step.  See the "Blink Without Delay" example that comes with the IDE and any of the multitude of tutorials about it on the web to see how it works.

"The Arduino has a single core, it can't do multi threading." This is simply 100% not true, and is a falsehood (if not a downright lie) that started to appear around the advent of dual core PC's. CPU's of any architecture or core count can do multi-threading. Multi threading != multiple cores .https://stackoverflow.com/a/16117084https://stackoverflow.com/a/16117084
If you want multi-threading on an embedded system such as Arduino or any other microcontroller, you should probably start looking at RTOS's or OS's.

So you're saying that the Arduino UNO or Mega is capable of executing multiple machine instructions at once?  Sure, you can have task schedulers and all sorts of switching back and forth.  But it is just not possible for the processor used in those boards to execute more than one instruction at any time.  If you think there is a way then please explain it.  I'm not talking about a pre-emptive multi-tasking where two processes take turns using the processor.  But true multi-threading where the processor actually does two things at once.

@Delta_G in fact... I also used to agree with you, and went searching for the definition of multi-threading to prove that the temporal multi-threading is a sort of "emulation" but... I discovered that user9993 is right: Multithreading on wikipedia says that the ability to switch from one thread to another, even on the same CPU, is also considered multithreading.

@frarugi87 Yep, I have no reason to lie. Quite frankly I think it shows an appalling lack of knowledge in the "arduino world" when I have to create an account to correct something that is so incorrect it would leave OP in a worse place. Multithreading has not once meant multicore. Threads executing in parallel on multiple cores is an implementation detail.
On Windows open Task Manager (or equivalent on your OS eg top), note how you likely have several thousand threads. Does your CPU also have several thousand cores?

@user9993 in fact I think everybody knows the time-based multithreading; the misconception is about terminology. I've always thought that "real" multithreading was the ability to execute threads concurrently, and so a single core CPU can "emulate" this by dividing the time they are performing tasks and act as if they were run concurrently. It looks like that this behavior is still classified as multi-threading, so... it's just a terminology issue, not a lack of knowledge ;)

Either way, it's a moot point.  Please take a look at the poster's question.  Do you think he needs any sort of complicated task scheduler or multi-threading system to solve it?  Or do you think he could just write a little quick non-blocking millis based code and be done?

I totally second Delta's answer. Make the two loops "non blocking", then run them one after the other.
Just wanted to add another solution, to be applied only when strictly needed. And only if the program really needs it. And only if other solutions are not enough. And... Well, you understood.
You can use FreeRTOS to have a sort of "multi-threading" environment. You have, IIRC, four "threads" which can jump from one loop to the other. You will have to carefully design it (particularly the shared memory) but in the end you will have even blocking "threads" running in parallel. Here are some more infos.

source: Stack Exchange

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

sort: votes


text:
How to access the member of union in loop?
Trying to get the address of receiving XBee's data in the loop in API mode with escape.
Sent data can be received properly. However, in order to identify XBee, I need the address in the loop. In other words I need those address1 to 7 which is in union XbEE_FRAME. How to get the address in main loop. Following is the code. Appreciate your help.
#include <SoftwareSerial.h>

struct SENSOR_DATA{
   char rpm;   // worked
  //float rpm;
  //float strain;
  //unsigned long sampling_interval;
};

boolean xbee_rx(struct SENSOR_DATA *ret) {
  union LEN_FRAME{
    byte len_array[2];
    word len;
  }lenlen;
  static int len_i = -1;

  union XbEE_FRAME{
    byte buf[25]; // 30
    struct {
      byte frame_type;
      byte frame_id;
      byte address1;
      byte address2;
      byte address3;
      byte address4;
      byte address5;
      byte address6;
      byte address7;
      byte reserved1;
      byte reserved2;
      byte recieve_options;
      struct SENSOR_DATA sensor_data;
      byte checksum;
    } frame;
  } xbee;
  static int buf_i = -1;
  static bool escape = false;
  static byte sum;

  while (Serial.available() > 0) {
    byte b = Serial.read();

    //Serial.print(b, HEX);

     //b = Serial.read();
    if (
      b != 0x7e &&
      buf_i == -1 &&
      len_i == -1
      ) {
      continue;
    } else if (b == 0x7e){
      buf_i = 0;
      lenlen.len = 0;
      len_i = 0;
      sum = 0;
      escape = false;
      continue;
    } else if (b == 0x7d){
      //Serial.print("es: ");
      //Serial.println(b,HEX);
      escape = true;
      continue;
    }

    if (escape){
      b = b ^ 0x20;
      escape = false;
    }

    if (len_i < 2){
      lenlen.len_array[1 - len_i] = b;
      len_i++;
    } else {
      xbee.buf[buf_i++] = b;
      sum += b;
    }
    if (
      len_i == 2 &&
      buf_i >= sizeof(xbee.buf)
      ){
      len_i = -1;
      buf_i = -1;
      // frame recieved !!
      if (sum == 0xff){ // check sum!
        *ret = xbee.frame.sensor_data;
        return true;
      }
    }
  }
  return false;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);   // 38400
  Serial.println("overover");
}

void loop() {
  //mySerial.println("work");
  // put your main code here, to run repeatedly:
 struct SENSOR_DATA data;
  if (xbee_rx(&data)){
    //Serial.print(data.rpm);

     // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac
  }
}

Function xbee_rx() only returns the contents of struct SENSOR_DATA which doesn't include those addresses. You could instead 1) return the contents of the entire struct {...} frame which does contain them (making sure loop() 's buffer is large enough; or 2) instead of returning all of that data at all, make the union {...} xbee static so it persists after xbee_rx() exits, and return a pointer to sensor_data, with which loop() can access any member of it, such as p->address1.
Update:
The caller - rather than the called-function - allocates the memory buffer and the called-function uses that memory instead of its own, effectively passing the data to the caller. Here's your code, slightly re-written, with my initialed comments. I have not tried to run it but it does compile:
#include <SoftwareSerial.h>

struct SENSOR_DATA{
   char rpm;   // worked
  //float rpm;
  //float strain;
  //unsigned long sampling_interval;
};

//-jr-: Here we define what an XbEE_FRAME is and make it a data-type
// but we don't allocate any storage. This is just information to the
// compiler:
typedef union {
    byte buf[25]; // 30
    struct {
      byte frame_type;
      byte frame_id;
      byte address1;
      byte address2;
      byte address3;
      byte address4;
      byte address5;
      byte address6;
      byte address7;
      byte reserved1;
      byte reserved2;
      byte recieve_options;
      struct SENSOR_DATA sensor_data;
      byte checksum;
    } frame;
} XbEE_FRAME;

//-jr-: This function expects a pointer to memory (i.e., its address)
// allocated for data of type 'XbEE_FRAME' - the union from your
// original code. Note that we don't allocate any memory for it here;
// the caller is expected to do that, and this function will use what
// the caller allocated.
boolean xbee_rx(XbEE_FRAME *pXbF) {
  union LEN_FRAME{
    byte len_array[2];
    word len;
  }lenlen;
  static int len_i = -1;

  static int buf_i = -1;
  static bool escape = false;
  static byte sum;

  while (Serial.available() > 0) {
    byte b = Serial.read();

    //Serial.print(b, HEX);

     //b = Serial.read();
    if (
      b != 0x7e &&
      buf_i == -1 &&
      len_i == -1
      ) {
      continue;
    } else if (b == 0x7e){
      buf_i = 0;
      lenlen.len = 0;
      len_i = 0;
      sum = 0;
      escape = false;
      continue;
    } else if (b == 0x7d){
      //Serial.print("es: ");
      //Serial.println(b,HEX);
      escape = true;
      continue;
    }

    if (escape){
      b = b ^ 0x20;
      escape = false;
    }

    if (len_i < 2){
      lenlen.len_array[1 - len_i] = b;
      len_i++;
    } else {
       //-jr-: Note how we changed our reference from 'xbee.buf...' to
       // 'pXbF->buf...'! The '.' style addressing is used to refer to
       // memory we can name directly, as when you allocated that union
       // here. But now we  have to refer to it by the  pointer we received -
       // its address. The '->' symbol is how you address members of a
       // union or struct through a pointer:
      pXbF->buf[buf_i++] = b;
      sum += b;
    }
    if (
      len_i == 2 &&
      buf_i >= sizeof(pXbF->buf)
      ){
      len_i = -1;
      buf_i = -1;
      // frame recieved !!
      if (sum == 0xff){ // check sum!
    //-jr-: Notice that here we don't try to return any data;
    // we don't have to. Since We did everything in memory the
    // caller owns, the caller already has the data!
        return true;
      }
    }
  }
  return false;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);   // 38400
  Serial.println("overover");
}

void loop() {
  //mySerial.println("work");
  // put your main code here, to run repeatedly:

   //-jr-: Define the entire XbEE_FRAME here and pass its address to
   // your function. The function will use _this_ local storage
   // (instead of its own) to buffer the data, so it will already
   // be here when your function returns:
   XbEE_FRAME data;     //-jr- Define the entire union here
   if (xbee_rx(&data)){    //-jr-  and pass its address to the function
      //-jr-: You can address a member such as address3 as:
      //      data.frame.address3
    //Serial.print(data.rpm);

     // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac

  }
}

Update:

How to get the SENSOR_DATA sensor_data?

Use: data.frame.sensor_data.rpm (lower case).

SENSOR_DATA only describes the kind of contents in a struct, not any actual data in memory.
sensor_data is one instance of such a struct.

To go a bit further, suppose frame{} contained more than one SENSOR_DATA in it, maybe named sensor_data_a, sensor_data_b, ..., etc. Now to get the data from, say, sensor_data_a it should be clear that you need to refer to the particular instance you're interested in.

JRobert, I am trying method No.1 that you have suggested, though still I cant get. Could you please write the code?

Ok, got the address. But now can not get the SENSOR_DATA sensor_data. How to get the SENSOR_DATA sensor_data?

I tried to get with Serial.print(data.frame.SENSOR_DATA.rpm); but didn't work.

I don't think you can.
The structures are defined within a function so the loop() won't have access to them.
Further the parameter returned from the function xbee_rx() is of type SENSOR_DATA which is a sibling in the frame structure to the data you want to read.

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


text:
In the AnalogRead example, would the thing work if I remove or short the A0 and the ground pin?
What I want to know is that how exactly does analogRead work because I have want to use it with a flex sensor and it has only two pins.I tried to find other examples on the internet, but this is the only example I find.If the middle pin of the 10k potentiometer and a0 pin are shorted or the gnd  pin is removed altogether,then would this thing work?

You did not show us the example which is confusing you.

I moved this to the answer...

I think you are confused because the ADC input measures voltage, not resistance.
To convert from resistance to voltage you need to pull in the opposite direction on the variable resistance with a fixed resistor.  As in the following image from this tutorial.

Hmmm...the image said it all....thank you...


text:
If else statement not mutually exclusive?
When I'm running some test on my encoder motors using the following provided code by Makeblock, it appears that the if..else.. statement is not mutually exclusive ie. I can control Encoder_1 and Encoder_2 at the same time. How come?
case ENCODER_BOARD:
      if(port == 0)
      {
        uint8_t slot = readBuffer(7);
        int16_t speed_value = readShort(8);
        speed_value = -speed_value;`

        if(slot == SLOT_1)
        {
          Encoder_1.setTarPWM(speed_value);
        }
        else if(slot == SLOT_2)
        {
          Encoder_2.setTarPWM(speed_value);
        }
        else if(slot == SLOT_3)
        {
          Encoder_3.setTarPWM(speed_value);
        }
        else if(slot == SLOT_4)
        {
          Encoder_4.setTarPWM(speed_value);
        }
      }

int16_t readShort(int16_t idx)
{
  valShort.byteVal[0] = readBuffer(idx);
  valShort.byteVal[1] = readBuffer(idx+1);
  return valShort.shortVal;
}

uint8_t readBuffer(int16_t index)
{
  if(BluetoothSource == DATA_SERIAL)
  {
    return buffer[index];
  }
  else if(BluetoothSource == DATA_SERIAL2)
  {
    return bufferBt1[index];
  }
  else if(BluetoothSource == DATA_SERIAL3)
  {
    return bufferBt2[index];
  }
}

All the code are taken from here and I am not the owner. I myself still studying how these whole code works. I am hoping someone out there who have experience with these kind of implementations be able to help me out.

if and else if clauses are mutually exclusive. If the if is true then the else if cannot run.
Therefore it must be the case that the code you posted is being executed twice (at least) - once for SLOT_1 and once for SLOT_2.  Just so fast that you think it's happening at the same time.

Exactly one of the blocks in if{..} else {...} will be executed.  Your misunderstanding is elsewhere.

Yes they are mutually exclusive.
Note that the following construct is more appropriate:
switch (slot)
{
case SLOT_1:
     Encoder_1.setTarPWM(speed_value);
     break;

case SLOT_2:
     Encoder_2.setTarPWM(speed_value);
     break;

case SLOT_3:
     Encoder_3.setTarPWM(speed_value);
     break;

case SLOT_4:
     Encoder_4.setTarPWM(speed_value);
     break;

default: // other cases/error
     // Handle error situation
     break;
}

You can do the same with BluetoothSource.
Also you can do multiple commands within one case statement, like:
case SLOT_4:
     Encoder_4.setTarPWM(speed_value);
     Encoder_Extra.setTarPWM(speed_value);
     break;

Note that the switch/case only works where you compare one variable/expression.

am hoping someone out there who have experience with these kind of implementations be able to help me out.

Match out the brackets (to your logic) and the issue will be clear.
Your inadvertently created a duffs machine

I see no Duff’s device in his snippets.


text:
ESP8266 Library Method List
Is there a place that lists all the common methods used with the standard ESP8266 libraries in Arduino?

Look in the source.

The headers (.h files) specifically.

Is the source even stored locally on my computer or does the compiler grab it from the internet when it builds the project? I only ask because I cannot locate the source files.

Its held locally.

Looking at the GitHub page, there is a document explaining how everything works, https://arduino-esp8266.readthedocs.io/en/latest/


text:
Arduino Compiling Error
I recently format my  Windows 8 and installed Windows 8.1 . In Windows 8, I was using Arduino IDE and there was no error in compiling.But then I installed Windows 8.1 and re-installed Arduino IDE.I tried various codes for motor drivers and everything but they didn't compile.So, I tried to compile blink LED example first and even it didn't compile.It shows the following error on UPLOADING BLINK LED Example-
Arduino: 1.8.2 (Windows 8.1), Board: "Arduino/Genuino Uno"

C:\Program Files\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries C:\Users\Admin\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10802 -build-path C:\Users\Admin\AppData\Local\Temp\arduino_build_754363 -warnings=none -build-cache C:\Users\Admin\AppData\Local\Temp\arduino_cache_657645 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -verbose C:\Program Files\Arduino\examples\01.Basics\Blink\Blink.ino
C:\Program Files\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files\Arduino\hardware -tools C:\Program Files\Arduino\tools-builder -tools C:\Program Files\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files\Arduino\libraries -libraries C:\Users\Admin\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10802 -build-path C:\Users\Admin\AppData\Local\Temp\arduino_build_754363 -warnings=none -build-cache C:\Users\Admin\AppData\Local\Temp\arduino_cache_657645 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files\Arduino\hardware\tools\avr -verbose C:\Program Files\Arduino\examples\01.Basics\Blink\Blink.ino
Using board 'uno' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\sketch\Blink.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10802 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\sketch\Blink.ino.cpp" -o "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Admin\AppData\Local\Temp\arduino_build_754363\preproc\ctags_target_for_gcc_minus_e.cpp"
exit status 1
Error compiling for board Arduino/Genuino Uno.

I tried RE-installing the software and drivers.It didn't work
Why is this happening?What is the Solution?

Right click on the Arduino icon, select properties. Under the compatibility tab, check "Run this program in compatibility mode" and select Windows XP. You might also want to run it as administrator.
This should hopefully solve the issue.
Source

I suspect also installing the IDE as a user rather than admin and running it as that user will also fix the problem. (But I have no evidence of that)

Uninstall Arduino. Then find the Arduino folder in your Appdata folder and delete it. Then reinstall Arduino. This is happening because after a library import, there might have been a clash in the Appdata and since uninstalling doesn't delete Appdata, just reinstalling wouldn't help. This happened to me when a PPM and Servo library clashed!
Note: Do this only after you try uploading a blank sketch and it still fails! Also be careful while in the Appdata folder.

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


text:
How can I identify, debug or fix a faulty IMU?
I have an LSM9DS1 breakout board by Sparkfun, and am communicating with it using a Mega 2560 over I2C. The board is given 3.3 V power as defined in the data sheet, though there seems to be confusion whether the SDA and SCL pins need level shifting for communicating with the 5 V Mega. In theory it shouldn't need to.
I am able to connect with the device and get its accelerometer and magnetometer data, however the gyro is just returning noise and no signal. I have dug in to all the registers I know of regarding high pass filters, logging rates, enabling and powering the sensor, but the only hints are that when the gyro is disabled and then polled, it returns a constant nonzero value on all three axes, as though a bit somewhere is stuck. With any other setting the results are unchanged: finite noise on a constant DC signal. Is this even possible? How can I dig deeper to understand and solve this problem?

In theory you must use a level shifter for SDA and SCL. The Arduino Mega 2560 board has internal pullup resistors of about 50k for SDA and SCL and extra 10k pullup resistors of 10k to 5V and according to the datasheet the ATmega2560 requires 3.5V to detect a high level for the I2C bus.
Those pullup resistors might damage the LSM9DS1.
5V-3.3V / 50k//10k times two (both SDA and SCL) = 400nA that might be pushed into the sensor (I assume there are protection diodes, and the maximum voltage is 3.6V, therefor the 400nA is just an indication).
I assume the 10k pullup resistors to 3.3V on the sensor module are enabled. They will take away some over-voltage.
The current by the pullup resistors (to 5V) is a very small current, and I don't know if the sensor is in sleep mode during startup.
To be sure you need to buy another LSM9DS1 and a level shifter. Or even better: buy a 3.3V Arduino board, like the Due or the Zero, M0, and so on.
Have to compared the raw sensor data with others ? Those sensors are very noisy. That is why there is so much to do about filter algoritms to get data that can actually be used. The LSM9DS1 does not do processing or smart filtering with the raw data. All you get is the raw data. Did you assume that the values would be zero ? They never will be, because such sensors are far too noisy and too sensitive for that.

I am confused genreally by your suggestion that I2C communications requires a level shifter. Your description is fair of the reality but I was under the impression the design spec for I2C was for voltage tolerance by communicating on open collector. I am using a 3.3 V supply to the chip, it is only the SDA and SCL that are running at the Mega-native 5 V. On the noise, of course I expect noise that is there, but what I am not getting is any signal on top of it. Additionally this is the second system I've used using the exact same model of IMU and Arduino, the other unit works perfectly.

Further, this is the information I am using to determine the necessity of using a level shifter with I2C. It says that is there is a 3.3 V supply, that I2C will not need level shifting: https://learn.sparkfun.com/tutorials/lsm9ds1-breakout-hookup-guide?_ga=2.254733000.1526785080.1494864932-308821833.1490272070

That voltage tolerance might have been a design feature long ago, but it does not really work with Arduino or todays sensors. They have ESD protection diodes inside, so there is a path from SDA and SCL to VCC. That sentence at Sparkfun says that with a 3.3V board everything is okay at 3.3V. That is the same as when I wrote: "Or even better: buy a 3.3V Arduino board". You have bad luck with the Arduino Mega 2560, it has 10k pullup resistors at SDA and SCL. And the Arduino Mega also requires 3.5V for SDA and SCL for a valid high. It's not a joke, 3.3V sensors have been damaged with Arduino Mega.

Well luckily I have a level shifter in this latest build for the I2C connection with an SD card and it has spare channels, so it's not a bit deal to add this to it. Nonetheless I am able to communicate with the chip and see meaningful data. Are you suggesting that the SCL and SDA pins going over voltage might influence the power to the gyro sensor even it the accelerometer and magnetometer are okay?

Yes. I don't know what the LSM9DS1 will do, but other gyro and accelerator MEMS sensors can get damaged. They might still work, but the data could be noisy and drifting (even when returning to normal voltages). Perhaps the gyro is the most sensitive part in the chip for voltages that are too high.

I needed to get this sorted and ran out of time to do level shifting. I bought a new LSM9DS1 chip, identical to the previous, and wired it the same as the last one. This one works without the shifting. Perhaps the other one is faulty or I've just been lucky 2 from 3 that they can deal with the mismatch. I will hunt for a suitable MOSFET based solution as you mentioned in the other answer when I get a chance.


text:
How can I split data coming from JSON?
In my recent project, I'm working with Arduino and JSON. Now, I get data from JSON and I can able to receive in Arduino side.
Below one is my Arduino code:
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

String response = "";
bool begin = false;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin) response += (in);

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  lcd.setCursor(0, 0);
  lcd.print(response);
}

Output :
{"TPS":"0.40","MAP":"1.05","LOAD":"14"}

Now, I want to split data means store 0.40 in one variable, 1.05 in another variable and 14 in another variable. I don't know how to split this.

Try this: https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/

Can try this JSON library: https://github.com/bblanchon/ArduinoJson

@goddland_16 I try out that library but I face one problem.

if you know the number of variables and it is fixed, and the order of incoming data, you can parse yourself. Well, I can parse the example string provided all the above conditions are met.

Finally, I got it. I have fixed length of data. So, I use a counter to calculate the how many characters are there in my data. Now using the index of this characters, I find out proper data and then store in a different variable.
Below is my code:
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

String responseOne = "";
String responseTwo = "";
String responseThree = "";
bool begin = false;

int counter = 0;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin)
    {
      counter++;

      if(counter >= 9 && counter <= 12)   // This gives 0.40
      {
        responseOne += (in);              // 0.40 store in responseOne variable
      }

      if(counter >= 22 && counter <= 25)  // This gives 1.05
      {
        responseTwo += (in);              // 1.05 store in responseTwo
      }

      if(counter >= 36 && counter <= 37)  // This gives 14
      {
        responseThree += (in);            // 14 store in responseThree
      }
    }

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  float newResponseOne = responseOne.toFloat();  // Convert string into Float
  float newResponseTwo = responseTwo.toFloat();  // Convert string into Float
  int newResponseThree = responseThree.toInt();  // Convert string into Integer

  lcd.setCursor(0, 0);
  lcd.print(newResponseOne);

  lcd.setCursor(8, 0);
  lcd.print(newResponseTwo);

  lcd.setCursor(0, 1);
  lcd.print(newResponseThree);
}


text:
Can't send Data to LCD1602 with I2C
I've been doing fine with my LCD1602 I2C configuration but I discovered that command and data functions are the same even though I change the RS command/data bit, but the result is the same.
This is really strange, I really can't do anything about it??!
#define E   2   // E  bit
#define RW  1   // RW bit
#define RS  0   // RS bit

#define LCDadd_WR  0x4E
#define LCDadd_RD  0x4F

uint8_t bitmask = 0x08;
uint8_t i, arr[]={0x48,0x65,0x6c,0x6c,0x6f ,0x10 ,0x3a,0x29 ,0x10 ,0x48,0x6f,0x77,0x10
,0x61,0x72,0x65,0x10,0x79,0x6f,0x75,0x65,0x76,0x65,0x72,0x79,0x10,0x6f,0x6e,0x65};

// LCD prototypes
void LCD_Init(void);
void sendCMD(uint8_t CMD);
void sendData(uint8_t data);
void LCD_string(uint8_t arr1[]);
void move_cursor (uint8_t row, uint8_t col);

// I2C prototypes
void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

void setup() {
  Serial.begin(9600);
I2C_init();
LCD_Init();
}

void loop() {
//sendData(0x0E); /* I commented this line because it has the same effect as sendCMD(0x0F); in sendCMD function */
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////
void LCD_Init(void)
{
  sendCMD(0x33);
  sendCMD(0x32);
  sendCMD(0x28);
  sendCMD(0x0F);
  sendCMD(0x01);
}

void sendCMD(uint8_t CMD)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  Serial.println("CMD");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = CMD & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (CMD<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

void sendData(uint8_t data)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  Serial.println("data");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = data & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (data<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

uint8_t BF(void)
{
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  I2C_tx(bitmask |= (1<<RW));
  I2C_stop();
  I2C_start(LCDadd_RD);
  I2C_rx();
  while (!(TWDR == (bitmask & (bitmask<<3))));
  I2C_stop();
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  _delay_ms(500);
  I2C_tx(bitmask &= ~(1<<RS));
  _delay_ms(500);
  I2C_stop();
}

void move_cursor (uint8_t row, uint8_t col)
{
  if (row==1)
  sendCMD(0x80+col);
  if (row==2)
  sendCMD(0xC0+col);
}

void LCD_string(uint8_t arr1[])
{
uint8_t cnt=0;
  for (i=0;i<29;i++)
  {
    sendData(arr1[i]);
    _delay_ms(500);
    cnt++;
    if (cnt==16)
    sendCMD(0xC0);
  }
  sendData(0x10);
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

You might want to try a more specific / complete Arduino library specifically for LCDs and, perhaps, specifically for the LCD1602.  That way, if that works, you can eliminate hardware problems.  Then return to your raw i2c code and feel more assured the problem is in the code.  Also, you can check the library solutions against your own and see if there is anything you might have missed.  The i2c protocol allows for some flexibility and, unfortunately, that leads to some confusion from time to time.

Yes, I used a very good Arduino library which works fine, the problem is in my code. And specifically in the sendData function because it works as sendCMD the same, so if I changed the function calls in LCD_init function from sendCMD to sendData, then it works the same, even I set the RS in sendData to 1 !!? But I don't know where is the problem.

You might like to try attaching a logic analyser to examine precisely what is being sent from the Arduino to the LCD.

Hello friends :) I discovered the problem!! One member told me about. Which is that I override the bitmask for the RS in data function, so it would still work as a command function, he solved that for me by adding the RS bitmask with I2C_tx(bitmask = (data<<4) & 0xF0 | 0x08 |= (1<<RS));

I2C_tx(bitmask |= (1<<RS));
I2C_tx(bitmask &= ~(1<<RW));
I2C_tx(bitmask = data & 0xF0 | 0x08);

RS is overridden in the third line, so the solution is:
I2C_tx(bitmask = data & 0xF0 | 0x08 | (1<<RS));

And delete the first two lines :)


text:
Errors reading fixed-length control strings over serial
I am sending a short 12-char control string over serial with Python and Debian Jessie.
It works, but sometimes chars are added or skipped randomly. Here it is an extract of the Arduino code:
void setup() {
  matrix.begin();
  matrix.setTextWrap(true);
  matrix.setFont(&TomThumb);
  matrix.fillScreen(matrix.Color333(0, 1, 1));
  matrix.swapBuffers(false);
  Serial.begin(115200);
}

void loop() {
  char c = 0; // serial char buffer
  byte i = 0; // string counter (reused multiple times)
  // read the equalizer control string
  delay(1);
  if (Serial.available() > 0) {
    turnmatrixoff();
    String control_str = Serial.readStringUntil('\n');
    Serial.println((control_str));
    draw_equalizer(control_str.c_str());
  }

Here is the log of the strings echoed back from the Arduino:
10563942332
00863931110
00773940100
0000974940100
00763940100
10693931211
00593950100
00544840100
00464950100
1050000
004549310744940100
00664961211
00694941111
10784951100
0
00593931100
00373931100
00483920100
00583720110
10473510000
000332710000
00252710000
00142510000
00122620000
002510000
003310100
00334520110
00343520100
00244720100
00355820110
00343611110
10144621210
00424921210
10343921210
00233811310

As you can see, some strings are truncated or padded (they all should be of the same size).
I've tried coding a char-by-char read function but the results were even worse:
char c = 0; // serial char buffer
byte i = 0;

while (Serial.available() > 0) {
  delay(1);  //small delay to allow input buffer to fill
  c = Serial.read();
  if (c == '\n' || i >= EQUALIZER_STR_SIZE - 1) {
    // finished reading the string
    equalizer_str[i] = 0; // terminate the string
    Serial.println(equalizer_str); // debug echo
    draw_equalizer(equalizer_str);
    break;
  } else {
    // append to the string
    equalizer_str[i] = c;
    i += 1;
  }
}

EDIT: here it is the full python script.
Decreasing the baud rate to 9600 seems to fix the issue, but the matrix updates too slowly this way.
Maybe I could use some other serial port initialization trick to prevent buffer overflows?
UPDATE:
I've found another way to reduce the serial traffic by increasing the audio capture chunk. For some reason this way the errors are gone completely.
Here it is a video of the code finally running fine.

Change delay(1);  //small delay to allow input buffer to fill to delay(1); //small delay to allow input buffer to overflow. There is never any excuse for using a delay while reading serial.

do you mean i should remove the delay?

Absolutely. You might like to read this too: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

just tried removing the delay, i still get the truncated strings...

Also you should be aware that there is no handshaking on Arduino serial. If you don't read the data faster than you send it you will overflow. If you need to, slow down your sending with a delay in the python code.

in the python code i have a sleep(0.001). I've tried increasing the delay but it does not fix the problem (it also makes the matrix refreshing too slowly).

removing even the delay before if (Serial.available() almost fixed the issue!

A baudrate of 9600 delays the Python script, so the Arduino can keep up with the incoming data. The Arduino Leonardo/Micro or Arduino Due and M0 can use a CDC SerialUSB port to computer. That is faster than 115200 baud. You probably need a M0+ or M3 processor anyway because it seems that your Arduino is too slow. Are the turnmatrixoff() and draw_equalizer() functions optimized ? The Serial.readStringUntil() uses a default timeout of 1 second. This situation is in my opinion not suitable for a timeout. You need to calculate how much data is transferred and test if the Arduino can handle that.

@Jot: thank you for the tips, i've done some testing and i've found the draw_equalizer() is indeeed too slow. Here it is the full arduino source code. If it can't optimized more i guess i have to try another gfx library or switch to another controller as you suggested.

Check that the serial receive code works first. Estimate the maximum baudrate, e.g. how much time does the rest of the code take. What would happen if the serial buffer is not emptied in time and overruns?


text:
Passing user defined callback functions to a library method
I developed an Arduino library that have a method called "process". This method is a Void function and must be called inside the loop and most of the time the library handles everything by it self:
#include <HookNinja.h>

HookNinja hookninja;

void setup()
{}

void loop()
{
  hookninja.process();
}

The idea is to keep the user program a simple as possible. Sometimes "process" have some data to give back to the user so he can use it as he likes. A simple approach is not to make process void and make the user check for the return value of process:
void loop()
{
  someVariableType foo;
  foo = hookninja.process();
  if(foo) {
    //user defined things
  }
}

But the data returned by process could be anything, from an int to an array of Strings, only the user knows the return type, also this method seems not very elegant. Im not an expert of C++, for me the ideal solution will be an object oriented approach were the user pass a function to process that can be called from the library, but I have no idea how to do this in C++, something like:
void userFunction(type param) {
  //do something with param
}

void loop() {
  hookNinja.process(some how pass userFunction here)
}

A common solution would be to have the user provide a callback which
takes no arguments and returns nothing. This is how attachInterrupt()
works, so it may be the least surprising approach for your users. The
user function can then get data from the rest of the program using
globals.
If you really prefer passing an argument to the user function, the
problem is you do not know the data type. The usual approach in plain C
is to give it a “generic” pointer, and let the user cast it into a
pointer specific for his data type. This is how functions like qsort()
work:
HookNinja hookninja;

void userFunction(void *param) {
    someVariableType foo = * (someVariableType *) param;
    //do something with foo
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process((void *) &foo);
}

A cleaner C++ approach could be to make you class a template that is
specialized for the type of the user data:
HookNinja<someVariableType> hookninja;

void userFunction(someVariableType param) {
    //do something with param
}

void setup()
{
    hookninja.attachCallback(userFunction);
}

void loop() {
    someVariableType foo = something;
    hookNinja.process(foo);
}

But keep in mind that many Arduino users may not be familiar with
templates.


text:
How to light up all LEDs of a 7x5 LED matrix?
I want to light up all the LEDs of a 7x5 matrix with arduino uno. How can i do so?

Mark Smith has answered the question you asked.  If you didn't get an answer to what you want to know (and I presume you want to how to turn them on/off under program control) then edit the question to ask what you actually want to know.  Include LED part numbers and/or links, because LED current requirements will affect how best to do this; and how to treat common anode may differ from common cathode, and affects multiplexing if that's needed

You don't need an Arduino for that, and one will give you no benefit.
Connect all anodes to power, and all cathodes to the appropriate resistors, then ground.

The first thing I thought of when reading this answer was "I would have answered LEDs are not flammable; add some gasoline, enlight the uno with a blowtorch and then you will be able to light them up"


text:
serial write pixels of a bmp image
I'm looking for a way to read a 24 bpp bmp file from a SD cart, and than convert it to text and write it to the serial monitor.
So the output should look something like this:
R255,B255,G255
And that for each pixel

Start here: https://en.wikipedia.org/wiki/BMP_file_format

SO, I have to skip the header somehow, and then read the pixels one by one. But how can you do that in the arduino IDE?

The worst thing with a BMP file is it's backwards. It starts at the bottom of the image not the top. Really annoying. You need first to read the header and get the right data out of it to then know how to get the image data.

And what if you know the data out of the header already, so it's always the same size and format. Can you begin with reading the pixels directly?

Sure, if you know the offset, ordering, and packing already. Just seek to the right location and start reading.

And what will be a command to Read the data in the arduino IDE?

The same one used in all the SD card reading examples.

To read the pixels, start with this:
int32_t readNbytesInt(File *p_file, int position, byte nBytes)
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result
}

void setup()
{
    Serial.begin(9600);
    while (!Serial);

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        while (1); // <- this is how you should block execution, not with returns
    }
    Serial.println("initialization done.");

    // Open
    bmpImage = SD.open("Circle.bmp", FILE_READ);
    textFile = SD.open("test.txt", FILE_WRITE);

    int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

    // Change their types to int32_t (4byte)
    int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
    int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
    Serial.println(width);
    Serial.println(height);

    int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

    if (pixelsize != 24)
    {
        Serial.println("Image is not 24 bpp");
        while (1);
    }

    bmpImage.seek(dataStartingOffset);//skip bitmap header

    // 24bpp means you have three bytes per pixel, usually B G R

    byte R, G, B;

    for(int32_t i = 0; i < height; i ++) {
        for (int32_t j = 0; j < width; j ++) {
            B = bmpImage.read();
            G = bmpImage.read();
            R = bmpImage.read();
            textFile.print("R");
            textFile.print(R);
            textFile.print("G");
            textFile.print(G);
            textFile.print("B");
            textFile.print(B);
            textFile.print(" ");
        }
        textFile.print("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
}`

Source: Arduino StackExchange Question: How to read bitmap image on arduino
The text output of this should be a file with an array of strings like R10G100B25, where R is the red component of the pixel, G is the green component and B the blue one. Work out how to print these to the serial output.
Note this is only compatible with the 24bpp format.

If you feel this answers your question, you may want to "accept" the answer What should I do when someone answers my question?

There is no "command" to read BMP files. They're files like any other. If you know how to read files on an SD card with an Arduino, then you know how to read BMP files. Interpreting the bytes of the file you just read is another matter. If the details of the BMP (width, height, depth, array offset, etc.) are known already, you may seek to the pixel array directly and begin parsing it (in your case, 3 bytes at a time in BGR order), remembering that BMPs are typically arranged bottom-to-top unless the height field in the header is negative.


text:
Turn led on after ringing once, off after two rings when hung up SIM800
I'm trying to make something that has one led and a gsm module which is SIM800L, I'm using seeeduino GPRS library.
What I'm trying to do is that when I call the GSM module and hung up after ringing once (about 2 seconds of ringtone) the led turns on, and when I call again and hang up after the second ringing sound (about 5 seconds of ringtone) the led turns off;
Note that the SIM800 module when starts receiving a call it prints on the serial every ringing period (about 2.5sec):

RING
{number 0664xxxxx}

then it shows up again telling, 2 times for one rington, 3 times for two ringtons, and when I stop calling the GSM the module prints:

NO CARRIER

Here's my code as start:

#include <SoftwareSerial.h>
String inData;
char incomingByte;
//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);

  Serial.println("Setup Complete!");
}

void loop() {
  //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
  if(serialSIM800.available()){
    Serial.write(serialSIM800.read());
    incomingByte = serialSIM800.read();
    inData += incomingByte;
  }

if(inData != "")
   {
     if (inData.indexOf("RING") >= 0) {
      delay(4000);
      serialSIM800.println("ath"); // Hang up at command
      inData = "";
     }
  }

  //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
  if(Serial.available()){
    serialSIM800.write(Serial.read());
  }
}

I did this code so it hangs up 4 seconds after calling printing the message "RING", but it didn't work, can you please help guys, thanks!

If it didn't work, what did it do? What do you see in the serial monitor?

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


text:
ESP8266MOD programing using Arduino uno?
I want to make a very simple webserver who sends welcome message to anyone who joins it using WiFi.
I have a ESP8266MOD module, I want to program it using arduino ide and arduino uno board.
How I can use arduino uno to program this WiFi module without using urat USB serial board?
SoftwareSerial.h is not working with esp.write() command, I believe it is because of low power, can anyone suggest me on power supply too?
Thanks in advance,
Mohan

Why use a mini to tell a Ferrari what to do? Program the esp8266 directly and screw the Arduino.

just short the UNO's reset to ground to use it as an "FTDI" to program the ESP from the Arduino IDE

Hi dandavis, can you please show me an example, because how to use UNO as FTDI is not documented well anywhere...

your absolutely right Majenko, but my problem is that I don't have URAT or FTDI, so to connect to IDE I have to use UNO itself as FTDI

rx>tx,tx>Rx,gnd<gnd, on avr: rst to gnd. then you can use at mode et al

Making Rx > Tx and Tx > Rx not sending data, more I got a weird error now, I was able to connect it, and blue light is blinking, I can also found it working in my phone's wifi list. but in IDE when I try to upload the sketch I am getting error: error: Failed to open COM1
error: espcomm_open failed
error: espcomm_open failed,

When you use the Uno for its UART only, i.e. grounding RST pin, its Rx pin 0 becomes Tx, and Tx pin 1 becomes Rx -- because that's what pins on the UART you are connecting to. AppMonk didn't say what specific breakout/ chip mount he's using, there are many, or say how he's managing level-shifting from the Uno to the ESP if needed. The Tx pin on Uno (0, labeled Rx) is putting out 5v and the ESP would prefer 3.3, so level shifting w/ simple voltage divider is recommended. You don't need to level shift the Tx signal from ESP to Arduino's Rx (pin 1).


text:
LCDs interfere with Adafruit datalogger SD card function
I am using the Adafruit datalogger shield (Rev B) and a pair of cheap 20x4 LCD I2C displays. The displays have a small I2C I/O expansion module board on the back. The LCDs I am using are these;
https://www.amazon.ca/gp/product/B01GPUMP9C/ref=oh_aui_detailpage_o09_s00?ie=UTF8&psc=1
I'm using the NewLiquidCrystal 1.3.4 I2C library. My UNO clone is the iteaduino-BT https://www.itead.cc/iteaduino-bt.html, which is a board I really like.
I am getting interference between the LCD displays and the SD card function. Sometimes I can write to the SD card, and sometimes I can't. I have tried several SD cards. After a lot of experimenting, I think I have identified the problem. The LCDs are interfering somehow with the SD card functions. The LCD objects are created with the following statements;

    // set the lcd1 address to 0x26
    // Set the pins on the I2C chip used for lcd1 connections:
    // addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd1(0x26, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
// set the lcd2 address to 0x27
LiquidCrystal_I2C lcd2(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

If I comment out the LCD lines, the SD problem goes away. My thinking is that the four data lines used by the LCDs (4,5,6,7) may be overlapping with the datalogger card, but after looking at the datalogger schematic, I can't see the problem. I found a couple of websites suggesting mapping the LCDs to use different data lines, but I'm not sure if that is the problem.
I also ran a program to scan the I2C bus and it showed that the LCDs were at 26 and 27 and the Adafruit datalogger at 68. No interference with addresses at least.
I really need this working yesterday. Creating datalogging projects is nothing new and I can't believe that there is no solution for including I2C LCD displays. Should I experiment with different LCD libraries or try mapping the pins differently during the creation of the LCD objects? I also am wondering if I can simply shut off the LCDs when writing to the SD card and then turn them back on after. I plan on taking measurements and writing the results every 5 minutes for several days, so high speed anything is not a requirement.
The code sample below is part of my program. I use the while(1) line as a hard break for debugging purposes.
#include <OneWire.h>              // library for DS18B20 thermocouple
#include <DallasTemperature.h>    // library for DS18B20 thermocouple
#include <Wire.h>                 // used for rtc
#include <SD.h>                   // library for SD card
#include <SPI.h>                  // library used for SD card
#include <RTClib.h>               // library for real time clock
#include <LiquidCrystal_I2C.h>    // library for lcd displays
#define ONE_WIRE_BUS 8            // Data wire for thermocouple is plugged into pin 8 on the Arduino
#define SYNC_INTERVAL 1000        // mills between calls to flush() - to write data to the card

RTC_PCF8523 rtc;                  // define the Real Time Clock object

String datetimestamp;
uint8_t MM;
uint8_t DD;
uint8_t mm;
uint8_t hh;
File logfile;                     // create file object to save results on SD card
const int chipSelect = 10;        // for the data logging shield, we use digital pin 10 for the SD cs line
OneWire oneWire(ONE_WIRE_BUS);        // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
DallasTemperature sensors(&oneWire);  // Pass our oneWire reference to Dallas Temperature.

// set the lcd1 address to 0x26
// Set the pins on the I2C chip used for lcd1 connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd1(0x26, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

// set the lcd2 address to 0x27
LiquidCrystal_I2C lcd2(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

String inputString = "";         // a string to hold incoming data
String ackString = "ack";        // acknowledgement string from terminal
String temperature;              // temperature
boolean stringComplete = false;  // whether the incoming string from serial port is complete with /n
int interval = 60000;            // interval between measurements
long previousMillis;
int cycle = 1;                   // cycle number
int heartbeat = 30000;           // ping teminal to prevent bluetooth from shutting down
String dim_length;
String dim_width;
String dim_height;
String measurements;              // string containing measurements for inclusion in SD file
int firstcomma;
int secondcomma;
int thirdcomma;
String logEntry;
char filename[] = "logdata.txt";

void setup(void) {
  Serial.begin(9600);
  inputString.reserve(20);               // reserve space for the inputString
  pinMode(10, OUTPUT);
  pinMode(ONE_WIRE_BUS, INPUT);          // used for thermocouple

  WaitFor(2000);

  lcd1.begin(20, 4);        // initialize the first lcd for 20 chars 4 lines
  lcd1.backlight();         // turn on backlight
  lcd1.clear();             // clear lcd11

  lcd2.begin(20, 4);        // initialize the second lcd for 20 chars 4 lines
  lcd2.backlight();         // turn on backlight
  lcd2.clear();             // clear lcd11

  //These routines update rows on the LCDs
  Row1("DATE: ");
  Row2("TEST CYCLE: ");
  Row3(" ");
  Row4(" ");

  // check for working real time clock
  if (! rtc.begin()) {
    Row4("RTC failed");
    WaitFor(500);
    while (1);
  }
  else {
    Row4("RTC found");
    WaitFor(500);
  }

  if (! rtc.initialized()) {
    Row4("RTC failed");
    WaitFor(500);
    while (1);
  } else {
    Row4("RTC initialized");
    WaitFor(500);
  }

  UpdateRow1(GetTimestamp());      // display current date and time
  UpdateRow2(cycle);               // display current test cycle

  // initialize SD card
  if (!SD.begin(10)) {
    Row4("SD init failed");
    WaitFor(500);
    while (1);
  } else {
    Row4("SD card initialized");
    WaitFor(500);
  }

  //log file setup
  if (SD.exists(filename)) {
    Row4("log file exists");
    WaitFor(500);
  } else {
    Row4("log doesn't exist");
    WaitFor(500);
  }

  // sample write to SD card
  Row4("opening log file");
  logfile = SD.open(filename, FILE_WRITE);
  Row4("writing log file");
  WaitFor(500);
  logfile.println("DateTime,Temperature");
  WaitFor(500);
  for (int x = 1; x < 6; x++) {
    logfile.print("Test # ");
    logfile.println(x);
    delay(1000);
  }
  logfile.flush();
  WaitFor(500);
  Row4("flushed log file");
  WaitFor(1000);

  while (1);  //temporary stop for debugging

I think your problem is with the way you create the LCD instants.
I've always used LiquidCrystal_I2C lcd(0x27, 20, 4); LiquidCrystal_I2C lcd(address, row, col); when I'm using the I2C modules.


text:
ATmega AVR frequency measurement with timer/counter
I've been rehashing some existing libraries I found on some obscure forums to measure a frequency on digital pin 5, using the ATmega328P/ATmega2560 Timer/Counter modules and an interrupt based approach in order to be able to measure frequencies up to 4MHz(-ish). However, using the code described below, the results are off by a factor of exactly 100. I used a frequency generator to accomplish these readouts. Here is an example of what I've been getting back when generating a 5000Hz square wave (50% duty cycle):

Can someone please point out what might be wrong. I've read the ATmega328P datasheet multiple times by now and it should just work! This is very strange.

Edit:
  As it turns out the AWG I use has a blantant software bug which causes it to generate a wave with a period that's 100 times too long (see picture below). Nevertheless as Edgar pointed out I made some pretty big mistakes by not taking into account race conditions. Therefore the code below has been updated. Also, the test program has been updated to generate a 50% duty cycle square wave @5000Hz for testing purposes as suggested by Edgar.

This is the header file:
#ifndef FreqCounter_h
#define FreqCounter_h

#include <avr/interrupt.h>
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
namespace FreqCounter
{
    extern volatile unsigned long f_freq;
    extern volatile unsigned char f_ready;
    extern volatile unsigned char f_mlt;
    extern volatile unsigned int f_tics;
    extern volatile unsigned int f_period;

    void start(int ms);
}
#endif

This is the source file:
#include <FreqCounter.h>

volatile unsigned long FreqCounter::f_freq;
volatile unsigned char FreqCounter::f_ready;
volatile unsigned char FreqCounter::f_mlt;
volatile unsigned int FreqCounter::f_tics;
volatile unsigned int FreqCounter::f_period;

void FreqCounter::start(int ms) {
    f_period = ms;
    GTCCR = (1<<TSM) | (1<<PSRASY) | (1<<PSRSYNC); //halt all timers

    //set TC1 to normal mode => TOV1 flag set at TOP = 0xFFFF
    TCCR1A &= 0x00; //reset TC1 control register A
    TCCR1B &= 0x00; //reset TC1 control register B

    //set TC1 to use external clock source, clocked on rising edge
    TCCR1B |= (1<<CS10);
    TCCR1B |= (1<<CS11);
    TCCR1B |= (1<<CS12);

    //reset TC2
    TCCR2A &= 0x00; //reset TC2 control register A
    TCCR2B &= 0x00; //reset TC2 control register B

    //set TC2 to CTC Mode with TOP = OCR2A => counter cleared on reaching TOP
    TCCR2A |= (1<<WGM21);

    //TC2 is in CTC mode => set value of OCR2A = TOP
    OCR2A = 124; //TOP is reached every 125 counts (starting from 0)

    //set TC2 to use a prescaler of 1 => 16MHz / 128 = 125kHz
    TCCR2B |= (1<<CS20);
    TCCR2B |= (1<<CS22);

    f_ready = 0; //reset ready flag
    f_tics = 0; //reset TC2 interrupt counter

    //synchronize the value of both timers
    TCNT2 = 0;
    TCNT1 = 0;

    //clear interrupt flags
    TIFR2 |= (1<<OCF2A);
    TIFR1 |= (1<<TOV1);

    TIMSK2 |= (1<<OCIE2A); //enable TC2 Output Compare A interrupt => triggered on reaching TOP = OCR2A
    TIMSK1 |= (1<<TOIE1); //enable TC1 overflow interrupt => triggered on reaching TOP = MAX = 0xFFFF

    GTCCR &= 0x00; //restart all timers => start counting
}

/*
 * This ISR is triggered by TC2 every 1ms because
 * TC2 increments with a frequency of 16MHz / 128 = 125KHz
 * and reaches TOP every 125 counts
 * => trigger frequency = 1kHz
 * => trigger period = 1ms
 *
 * This ISR handles the Gate Time generation
 */
ISR(TIMER2_COMPA_vect)
{
    //increment number of TC2 interrupts (triggers when reaching TOP = OCR2A)
    FreqCounter::f_tics++;

    /*
     * If branch evaluates as true if given gate time (f_period) equals
     * amount of milliseconds TC2 has counted (= f_tics)
     */
    if (FreqCounter::f_tics >= FreqCounter::f_period)
    {
        //end of gate time => measurement ready
        TCCR1B &= ~0x07; //set TC1 to no clk source => TC1 stops counting
        TIMSK2 &= ~(1<<OCIE2A); //disable TC2 Output Compare A interrupt
        TIMSK1 &= ~(1<<TOIE1); //disable TC1 overflow interrupt
        FreqCounter::f_ready = 1; //set software flag for end of gating period

        //increment on overflow of TCNT1
        if (bit_is_set(TIFR1, TOV1))
            FreqCounter::f_mlt++;

        //calculate frequency
        FreqCounter::f_freq = 65536 * FreqCounter::f_mlt;
        FreqCounter::f_freq += TCNT1; //add value of TC1
        FreqCounter::f_freq = (long)(FreqCounter::f_freq * 1000.0 / (double)FreqCounter::f_tics);
        FreqCounter::f_mlt = 0;
    }
}

ISR(TIMER1_OVF_vect)
{
    FreqCounter::f_mlt++;
}

This is the test program:
#include <FreqCounter.h>

long frq;

void setup()
{
    //generate a 5 kHz square wave on OC0B = digital pin 5 = T1
    DDRD |= _BV(PD5); //PD5 = OC0B as output
    TCCR0B = 0; //stop timer
    TIMSK0 = 0; //disable overflow interrupt
    OCR0A = 50 - 1; //period = 50 * 64 cycles
    OCR0B = 50 / 2 - 1; //50% duty cycle
    TCCR0A = _BV(COM0B1) //non-inverting PWM on OC0B
        | _BV(WGM00) //fast PWM, TOP = OCR0A
        | _BV(WGM01); //...ditto
    TCCR0B = _BV(WGM02) //...ditto
        | _BV(CS00) //clock at F_CPU / 64
        | _BV(CS01); //...ditto
    Serial.begin(57600);
    Serial.println("Frequency Counter");
}

void loop()
{
    FreqCounter::start(1000);
    while (FreqCounter::f_ready == 0);
    frq = FreqCounter::f_freq;
    Serial.println(frq);
}

PS: This is my first ever post on this forum. Feel free to comment on the contents of my question. Tips as to how I might improve future questions are always welcome. Have a great day!

Try swapping the order of operations to FreqCounter::f_freq * 1000 / FreqCounter::f_tics

@Gerben unfortunately changing that didn't make a difference and if it did that would've been completely irrational. Thanks anyway!

Not completely irrational. The variables are integers, but you want the calculation to be performed as floating point. Swapping some parts around will negate the need for floats all together, as demonstrated. Too bad that didn't help here. Have you tried measuring different frequencies? Are the all of by a factor of 100?

@Gerben you're right indeed. And to answer your question: yes I have. All other frequency measurements are also off by a factor 100. That's what's strange to me actually. This leads me to believe there might be some default prescaler weirdness I'm not aware off. I'm used to working with STM's and have worked with XMEGA devices in the past but since an Arduino has some pretty annoying default settings I've been bumping into these sorts off things all the time lately. I'm commited to using the Arduino platform for this project unfortunately.

The code looks okay to me. Very weird indeed. What happens if you change the period (e.g. FreqCounter::start(100);)

@Gerben the same problem with a different period. Of coarse the precision also changes but that is to be expected. A period of 100ms gives a precision of 1000Hz but it should be 10Hz.

Not only does your code look fine, it works perfectly well here, on my Arduino Uno compatible board (ATmega328P). You are sending the square wave into pin 5, right?

Do you live in a place of the world with 50 Hz mains? What are the low and high voltages of your square wave? Does your frequency generator share a common ground with your Arduino? Is it sitting close to the event horizon of a black hole?

@EdgarBonet Positive on the 50 Hz mains and I'm not sure but I might be living on the edge of a black hole because I'm constantly wondering how time can go by so slowly, especially when I'm trying to fix sh*t that's just supposed to work ;). They do have common grounds and I'm definitely using pin 5. I will check the frequency of the generated pulse with my oscilloscope (as I already should've done). Also I'm generating a wave on TTL levels.

I am posting this as an answer, just because it doesn't fit as a
comment. But more than an answer it is intended to be a debugging help.
First, I would like to point out that you can use the same Arduino to
both generate the test signal and read it. This can be done by
configuring Timer 0 (the last one you have left...) to output the 5 kHz
square wave on OC0B (digital pin 5), and wire this signal to pin T1
which is... also digital 5. No wiring needed then! You can do this by
adding the following to your test program's setup():
// Generate a 5 kHz square wave on OC0B = digital pin 5.
DDRD  |= _BV(PD5);    // PD5 = OC0B as output
TCCR0B = 0;           // stop timer
TIMSK0 = 0;           // disable overflow interrupt
OCR0A  = 50 - 1;      // period = 50 * 64 cycles
OCR0B  = 50/2 - 1;    // 50% duty cycle
TCCR0A = _BV(COM0B1)  // non-inverting PWM on OC0B
       | _BV(WGM00)   // fast PWM, TOP = OCR0A
       | _BV(WGM01);  // ...ditto
TCCR0B = _BV(WGM02)   // ...ditto
       | _BV(CS00)    // clock at F_CPU / 64
       | _BV(CS01);   // ...ditto

Then I would like to point out a couple of bugs in the library you are
using. First, there is an off-by-one error: the program is counting one
millisecond too much. This can be fixed by moving the lines
//increment number of TC2 interrupts (triggers when reaching TOP = OCR2A)
FreqCounter::f_tics++;

from the bottom to the top if ISR(TIMER2_COMPA_vect).
Next, there is a race condition between the ISRs. Race conditions are
nasty bugs because they are hard to reproduce and most of the time you
don't see them. And then the program just fails at a random time after
many tests showed it works fine.
Here it works as follows: let's say that after the required time has
elapsed, TIMER2_COMPA fires and right after that TIMER1_OVF fires
also. This second interrupt is put on hold (it's a pending interrupt)
while TIMER2_COMPA_vect runs through its prologue. Then you compute
the frequency based on FreqCounter::f_mlt (which has not been updated
to account for the overflow) and TCNT1 (which has already overflown to
zero). Thus you get an incorrect result. Not only that, the overflow
flag remains set, so the ISR will run right away as soon as the
interrupt is enabled again by your next call to FreqCounter::start().
And again you get an incorrect result.
The fix is two fold: first you have to detect the pending interrupt
condition in ISR(TIMER2_COMPA_vect): after stopping the timers and
before computing FreqCounter::f_freq, you need this:
// Did we miss an overflow?
if (bit_is_set(TIFR1, TOV1))
    FreqCounter::f_mlt++;

Next, you have to clear the interrupt flag. This is customarily done
right before enabling the interrupt, and just to be safe you do it for
every interrupt you enable. Thus, in FreqCounter::start(), right
before touching TIMSK2 and TIMSK1, you would:
// Clear interrupt flags.
TIFR2 = _BV(OCF2A);
TIFR1 = _BV(TOV1);

There are a couple of other minor issues, like the statement
TCCR2A &= ~(1<<WGM22); which makes no sense (the bit belongs to
another register). But given that this, like a few other statements, has
no effect whatsoever, it should not affect the working of the program.
It does reveal sloppy programming though.

Wow I can't believe the level of noobishness I displayed by neglecting to even think about race conditions. If my former professor in computer sciences knew about this he would strangle me with his bare hands. Also, I should really check my code before running off to forum threads. I will make the suggested corrections at once and report back to you. If it's fixed I will edit my post. Thanks in advance.


text:
ESP8266 problem with recieved data trasmission via TCP
I am having small project where I want to read couple of analog inputs from Arduino UNO, send it via software serial to ESP8266-01 and from that to python server using TCP.
Data is sent to ESP using this code on Arduino UNO
#include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX
    int pin = 5;

    void setup() {
      mySerial.begin(9600);
      delay(20000);
    }
    void loop() {
      delay(1000);
      int data = analogRead(pin);
      mySerial.println(data);
    }

Code on ESP is bellow
void loop() {
    while(Serial.available()>0){
    char data = Serial.read();
    client.print(data);
    }
}

When data is sent to Python server, it prints it out but data is sent in two seperate parts, so it always looks like this
9
59

, but number sent from arduino is just 959!
Python server code snipet:
while True:

        #Receiving from client
        data = conn.recv(1024)

        print data

        #send data to database
        post.create(
            current = str(data)
        )

         if not data:
            break

So the question is, why data sent to server is separated in two parts? Maybe it have to do something with how data is reading from serial on esp?

Suspect the problem to be with the python code. We'd need a complete minimal verifiable example of it.

Python server code can be found in link

read() in a loop to a buffer, then print() all in once go; the extra read delay might be hampering you

You assume all 5 bytes of 959\r\n are received by the server at the same time. The data is sent byte after byte, based on the client.print(data) in the ESP code and assuming the underlying library doesn't buffer bytes before transmitting, so there's no way they'll arrive at the server simultaneously. Most likely, your first pass with conn.recv(1024) grabs the first byte 9 and times out. And then on the second pass, the others (at least 2) arrive and are read. The newline between the packets is typical Python 2 print behaviour.
What you need to do is parse the data at the server. Basically read data till you get CRLF i.e. \r\n, which is a good enough delimiter and you're sending it already anyways, and then use that to know when to write to your database.


text:
Data logging speed with arduino
I am trying to make some data logging conserining physiological data coming from a bitalino.
My problem is that I would like to collect samples at something like 1 kHz, that is the rate that the bitalino can read the sensors, but I think that the time needed
to write this data to the SD card can't keep up with the speed, and here is why i think that:
I put in the script some timers to check what was consuming the time causing to low sample rate, resulting:
Bitalino: 0, SD: 27
Bitalino: 0, SD: 28
Bitalino: 2, SD: 26
Bitalino: 0, SD: 29

Being that the time in miliseconds.
void loop() {
    time = millis();
    readBIT();
    time2 = millis();
    printDataSD();
    time3 = millis();
    printData();
}

void printData() //Send the data acquired to the pc through the serial port
{
  Serial.print("Bitalino: ");
  Serial.print(time2-time);
  Serial.print(", SD: ");
  Serial.println(time3-time2);
}

void printDataSD() //Send the data acquired to the SD Card
{
    if (myFile) {
    //Bitalino
    myFile.print(_ECG);
    myFile.print(",");
    myFile.print(_EMG);
    myFile.print(",");
    myFile.print(_EEG);
    myFile.print(",");
    myFile.print(_EDA);
    myFile.print(",");
    //Time
    myFile.println(time);
    myFile.flush();

    } else {
    Serial.print("error opening file, ");
    SD.begin(10);
    delay(1000);
  }
}

I would like to know if there is a way to improve my sample rate.
Thank you!
Here is the readBit() like asked:
void readBIT() //Read IMU data
 {
  _ECG = analogRead(ECG);
  _ECG = ((_ECG/1024) - 0.5)*Vcc*1000/gECG; //mV

 _EMG = analogRead(EMG);
 _EMG = ((_EMG/1024) - 0.5)*Vcc*1000/gEMG; //mV

 _EEG = analogRead(EEG);
 _EEG = ((_EEG/1024) - 0.5)*Vcc*1000000/gEEG; //uV

 _EDA = analogRead(EDA);
 _EDA = (_EDA/1024*Vcc-0.259388)/gEDA; // revolution
 }

The serial prints were just for debuging purpose, i intened to remove them before using the device. What do you mean by "write unncecessary data? _EEG is the name of the variable, being printed it is only the value read. How can I know when i need to flush? could i do it every 2,3,4,5 cicles?

You should consider buffering the sensor data. Basically set up a timer to read the sensor every millisecond and place the data in a buffer. Then you write to the SD card when the buffer's full. Your readBIT() function has to satisfy a few conditions for this to be possible though. We need to see it.

I added the readBit() function, but how can I know that the buffer is full?

The OP has likely solved this problem by now, but I know that others will be in the same position, so I am answering for them.
I routinely record ten channels of biological sensors including one of 16-bit sound at 8 kHz (plus the associated FFT data) to an SD card using arduino-compatible systems, so I doubt very much that the SD card writing per se is the problem.
Throughput to an SD card is a function of several variables.

To maximize write throughput you need to write full blocks of data at
the correct block size, since partial blocks take the same amount of
time as full blocks.
You also need to be ready with more data as soon as the SD card is
ready to take more, otherwise precious cycles slip away from you.
You need to ensure that your writes are non-blocking (don't try to
write more than the buffer can receive) so your loop can process and
queue up new data while the SD card is doing its thing.
You need to read any timing-sensitive sensors using interrupt service
routines that write their data either to a circular buffer or to one
of a group of two or three buffers that are cycled between being
filled and being emptied.

Printing debug statements to the serial port can take many tens of milliseconds in a loop that otherwise may take only a few microseconds. If you write more than the serial port buffer can hold, the call will be blocking and you will be at the mercy of the PC that's reading the serial port. This will always be bad enough to mess up the program you're trying to debug... I've encountered situations where this introduced delays of up to 10 seconds (the PC was misbehaving, but still...).
A quick improvement to printing debug statements is to maintain a loop counter and only print a debug statement every N loops.
The program in the original question uses a naive strategy in the sense that it acquires some amount of data and then immediately tries to write it to the SD card, waiting until the write is complete before trying to acquire new data. This will never work at high data rates for the reasons given above. If you use this approach, you are likely wasting 90% of your program cycles in waiting for the SD write and the Serial port write. If either one takes too long, you will miss the next data acquisition window.
My advice: your first step is to research and find or write a circular buffer library.
Then set a timer to call an interrupt service routine that acquires data and puts it into the circular buffer.
Write a loop routine that checks to see whether the SD card is available for writing, and then takes just enough data out of the circular buffer to fit in a single block write for your SD card (look at the documentation for the card adaptor and the card).
At that point you will know whether your system can keep up with your needs.
It's possible that your SD card writing itself is OK but your Arduino is having trouble keeping up either because it's too slow or because you don't have enough room for a sufficiently large circular buffer. I doubt this because I've recorded and played back audio at 8 KHz on the Uno, but then I don't know what else you need to accomplish in your program.
If you do determine that the Arduino itself is too slow or has insufficient memory, take a look at the Teensy series of boards [https://www.pjrc.com/teensy/index.html]. They are entirely compatible with Arduino libraries and IDE but they run hundreds of times faster than the Uno at a larger data width, plus they have oodles of RAM and a gazillion pins. They're also much smaller than the Arduino form factor and the community that uses them is very knowledgeable.
If it turns out that SD card write throughput is OK but that it requires more buffering than you have on-board, you can add an SPI ram breakout board for more fast buffering space.
Finally, if the amount of data you need to collect is so large and so continuous that you simply can't buffer it long enough to get it written out to SD, or if the SD card truly can't keep up, or if the data is larger than any available SD card, you may consider sending your data off the board in near-real-time. I send 10 hours of nightly data from a Teensy over a USB virtual serial port to the PC at about 3Mbps, and others have done better. Ethernet output is also available and can be at least an order of magnitude greater.
glhf!

Why not write a simple program and try to write values like 1, 2, 3 ... 100 to the SD card with a 1 second delay between writes. Then read the values back and send them via serial link to your PC screen.
This way you can make sure that you are writing and reading values in the correct way.
Once this works, you can reduce the delay and see what is the minimum delay between writes that the SD card will support.
It might be advisable to also write a program to fill the SD card with 100 values = 0 to clear it before the next test.

I played a bit with SD cards and on Teensy 3.5 it was 8ms Open/write/close


text:
Turn LEDs on in binary sequence
Could I have some help getting the following code work?
My purpose is to turn on 4(or N) LEDs in a binary sequence with 4 (or N) bits, A,B,C,D. When bit=1, LED on, otherwise LED off,...
I will have 16 combinations, 2^4=16, so:

0000 => All leds off
0001 => All leds off except the one on the right
...

Here's the code I came up with:
int LEDblu=4;
int LEDgiallo=2;
int LEDrosso=5;
int LEDverde=7;
int num_led;
String numeri="";
String output;
int i=0;
int p;

void setup() {
    // put your setup code here, to run once:
    pinMode(LEDblu,OUTPUT);
    pinMode(LEDgiallo,OUTPUT);
    pinMode(LEDrosso,OUTPUT);
    pinMode(LEDverde,OUTPUT);

    Serial.begin(9600);

    if(Serial.available())                //Dimmi numero LED
    {
        num_led=Serial.readString().toInt();
        Serial.print(num_led);
    }
}

void loop() {
    // put your main code here, to run repeatedly:
    int vect[num_led];
    for(int i=num_led-1, c=0; i>=0; i--, c++)
    {
        int num=2^i;
        vect[c]=num;
    }

    output="";

    if(i<2^num_led)
    {
        p=i;

        for(int c=0; c<num_led; c++)     //Convert binary to decimal
        {
            if(p>=vect[c])
            {
                output+="1";
                int d=vect[c];
                p-=d;
            }
            else
                output+="0";
        }

        Serial.println(output);

        if(output[0]=="1")
            digitalWrite(LEDrosso,HIGH);
        else
            digitalWrite(LEDrosso,LOW);

        if(output[1]=="1")
            digitalWrite(LEDverde,HIGH);
        else
            digitalWrite(LEDverde,LOW);

        if(output[2]=="1")
            digitalWrite(LEDgiallo,HIGH);
        else
            digitalWrite(LEDgiallo,LOW);

        if(output[3]=="1")
            digitalWrite(LEDblu,HIGH);
        else
            digitalWrite(LEDblu,LOW);
    }

    delay(1000);
    i++;
}

^ is XOR. I think you want << bitshifting

@Majenko I guess he thinks ^ is for power. For powers use pow (e.g. pow(2, num_led))

For powers of 2 use bitshifting. pow() is very heavyweight.

I don't see any specific initialization of num_led; it should be set to some appropriate value, like 4.
As noted in some comments, the ^ operator is bitwise exclusive-Or.  For example, 2^2 is 0, 2^4 is 6, 2^7 is 5, etc.
To compute the nth power of 2, say 1<<n.
Your convert-binary-to-decimal code is clunky and unnecessary.  Instead, do something like the following, which repeatedly strips off the least significant bit of t:
t = p;
digitalWrite(LEDrosso,t&1);   t>>=1;
digitalWrite(LEDverde,t&1);   t>>=1;
digitalWrite(LEDgiallo,t&1);  t>>=1;
digitalWrite(LEDblu,t&1);

If you want the blue LED instead of the red one to represent the least significant bit, reverse the order of color names in the digitalWrite statements from rosso, verde, giallo, blu to blu, giallo, verde, rosso.
To print data out in binary, use the Streaming.h library, and say, for example,
Serial << _BIN(p) << endl;

Serial.println(p, BIN); should be working too. But Streaming library is usually more usefull.

@KIIV, thanks for that note.  I didn't remember the syntax for Serial.println(p, BIN) and was short of time for looking it up.

Note that this is one of those situations where direct port access
just makes things easier. You did not specify what board you are using,
and I will assume you have some AVR-based board. On those boards, I/O
pins come in groups called ports, with up to eight pins per port. You
can update all the pins of a port at once by writing a number to the
port output register. And guess what? The number you write comes out the
pins in binary, jut like everything works in binary inside the
microcontroller.
For example, on an Arduino Uno, you could wire your LEDs to the first
four pins of port B: i.e. pins 8 (lest significant bit) through 11 (most
significant bit). Then you can output a number to the LEDs just by
writing PORTB = number, and your loop would become:
void loop()
{
    static uint8_t number;
    PORTB = number;              // output to pins 8..11
    Serial.println(number, 2);   // print the value in binary
    number = (number + 1) % 16;  // increment modulo 16
    delay(1000);
}


text:
Why is the SPI response mis-ordered?
I have a Raspberry Pi and an Arduino Micro. The two are connected by a SPI bus, the RPi is the master; the Arduino the slave.
I need to send 5 bytes to the Arduino and get 5 bytes as an answer.
The answer is pre-calculated so when the Arduino receives the first byte, it already knows what to answer.
I don't understand why the response I get is mis-ordered. I get the right bytes (value), but they seem shifted in time.
Arduino code:
// Data received
volatile unsigned char rx_buffer[5];

// Data to be sent
volatile unsigned char tx_buffer[5];

// Triggered to true by the interruption when message is complete
volatile bool message_ready(false);

// Useful to keep trace of where we are in the message
unsigned char bytes_received = 0;

// SPI interrupt routine
// Message consists of 5 bytes: never less, never more
ISR (SPI_STC_vect)
{
  SPDR = tx_buffer[bytes_received];
  rx_buffer[bytes_received] = SPDR;

  if (++bytes_received == 5) // Reached the end of the buffer
  {
    bytes_received = 0;
    message_ready = true;
  }
}

void setup (void)
{
  pinMode(MISO, OUTPUT); // Set Slave Output as output
  SPCR |= _BV(SPE); // Slave mode
  SPCR |= _BV(SPIE); // Turn on interrupts

  // Reponse to be sent
  tx_buffer[0] = 'a';
  tx_buffer[1] = 'b';
  tx_buffer[2] = 'c';
  tx_buffer[3] = 'd';
  tx_buffer[4] = 'e';
}

void loop (void)
{
  // When message is ready, print it on serial port
  if (message_ready)
  {
    message_ready = false;
    Serial.print((char) rx_buffer[0]);
    Serial.print((char) rx_buffer[1]);
    Serial.print((char) rx_buffer[2]);
    Serial.print((char) rx_buffer[3]);
    Serial.println((char) rx_buffer[4]);
  }
}

The RPi uses a C++ program and WiringPi 2.39 to communicate (I also made a similar program with Unix spidev/ioctl calls, same results)
#include <iostream>
#include <thread>
#include <chrono>

#include <wiringPi.h>
#include <wiringPiSPI.h>

using std::cout;
using std::cerr;
using std::endl;

int main(void)
{
  // Initialize wiringPi
  if (!wiringPiSPISetup(0, 150000))
  {
    cerr << "Could not initialize SPI!" << endl;
    return 1;
  }

  // Create message and response arrays
  uint8_t message[5], response[5];
  message[0] = 'z';
  message[1] = 'u';
  message[2] = 't';
  message[3] = ' ';
  message[4] = '!';

  std::chrono::steady_clock::time_point begin, end;
  unsigned count(0);
  while (1)
  {
    // Change the number at the end of the message: "zut 0", "zut 1" etc..
    message[4] = *std::to_string(count++).c_str();
    if (count == 10)
      count = 0;

    // Copy the message into response because reponse is going to be overwritten
    for (unsigned i(0); i < 5; ++i)
      response[i] = message[i];

    // Count time and transfer the message (and get the reponse at the same time)
    begin = std::chrono::steady_clock::now();
    if (!wiringPiSPIDataRW (0, response, 5))
      cerr << "Could not send message!" << endl;
    end = std::chrono::steady_clock::now();

    // Inform user
    cout << "Sent: " << message << endl;
    cout << "Received: " << response << endl;
    cout << "Duration: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << " microseconds" << endl;

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  }

  return 0;
}

The outputs are the following,
Arduino (read over serial):
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5
zut 6
zut 7
zut 8
zut 9
zut 0
zut 1
zut 2
zut 3

Everything looks good on the Arduino receive side!
RPi output (std::cout/cerr):
Sent: zut 0
Received: eabcd
Duration: 374 microseconds

Sent: zut 1
Received: eabcd
Duration: 359 microseconds

Sent: zut 2
Received: eabcd
Duration: 357 microseconds

Sent: zut 3
Received: eabcd
Duration: 384 microseconds

Sent: zut 4
Received: eabcd
Duration: 389 microseconds

Sent: zut 5
Received: eabcd
Duration: 384 microseconds

Sent: zut 6
Received: eabcd
Duration: 386 microseconds

Sent: zut 7
Received: eabcd
Duration: 391 microseconds

Sent: zut 8
Received: eabcd
Duration: 385 microseconds

Sent: zut 9
Received: eabcd
Duration: 387 microseconds

Sent: zut 0
Received: eabcd
Duration: 387 microseconds

Sent: zut 1
Received: eabcd
Duration: 387 microseconds

Sent: zut 2
Received: eabcd
Duration: 390 microseconds

Sent: zut 3
Received: eabcd
Duration: 386 microseconds

I get the bytes eabcd but I expected abcde.
Why isn't the RPi receiving the bytes in the correct order? Don't hesitate to ask for additional information.

Have you tried to send two different strings? It might show you why it's "shifted". Anyway to not be shifted, you'll have to fill the data register in slave device BEFORE master even starts the transfer.

Did you try changing the order of writing and reading the SPI register (SPDR) in the ISR?

Switching the write/read order (before/afer) in the SPDR does not change the behavior. @KIIV you are right, this solved my problem, I'm going to write the answer now!

@RobertoLoGiacco I can't until 13 hours, thanks for the reminder!

@KIIV gave me the answer:

Anyway to not be shifted, you'll have to fill the data register in slave device BEFORE master even starts the transfer.

What happens is that when an SPI transfer is complete, we enter the ISR (SPI_STC_vect), this means that 1 byte (8 bits) has been received. This also means that the response has been sent, because SPI is full duplex!
So the SPDR must be filled with the next byte to be sent before entering the ISR. If you modify the SPDR inside the ISR, this will set the next byte to be sent; it will not be sent until a byte is received.

Fixed Arduino code
// Data received
volatile unsigned char rx_buffer[5];

// Data to be sent
volatile unsigned char tx_buffer[5];

// Triggered to true by the interruption when message is complete
volatile bool message_ready(false);

// Useful to keep trace of where we are in the message
unsigned char bytes_received = 0;

// SPI interrupt routine
// Message consists of 5 bytes: never less, never more
ISR (SPI_STC_vect)
{
  // Store incoming byte
  rx_buffer[bytes_received] = SPDR;

  if (++bytes_received == 5) // Reached the end of the message/buffer
  {
    bytes_received = 0;
    message_ready = true;

    // Let's send another message next time!
    changeTxMessage();
  }

  // When next byte is received, this will be the response
  SPDR = tx_buffer[bytes_received];
}

// This changes the response message sent by the Arduino to the RPi
unsigned count(0);
void changeTxMessage()
{
  // Update message
  switch (count++)
  {
    case 0:
      tx_buffer[0] = 'c';
      tx_buffer[1] = 'r';
      tx_buffer[2] = 'a';
      tx_buffer[3] = 'z';
      tx_buffer[4] = 'y';
      break;
    case 1:
      tx_buffer[0] = 'k';
      tx_buffer[1] = 'a';
      tx_buffer[2] = 'n';
      tx_buffer[3] = 'j';
      tx_buffer[4] = 'i';
      break;
    case 2:
      tx_buffer[0] = 'b';
      tx_buffer[1] = 'u';
      tx_buffer[2] = 'x';
      tx_buffer[3] = 'o';
      tx_buffer[4] = 'm';
      break;
  }

  if (count > 2)
    count = 0;
}

void setup (void)
{
  pinMode(MISO, OUTPUT); // Set Slave Output as output
  SPCR |= _BV(SPE); // Slave mode
  SPCR |= _BV(SPIE); // Turn on interrupts

  // Reponse to be sent
  tx_buffer[0] = 'a';
  tx_buffer[1] = 'b';
  tx_buffer[2] = 'c';
  tx_buffer[3] = 'd';
  tx_buffer[4] = 'e';

  // Prepare first byte to be sent as a response
  SPDR = tx_buffer[0];
}

void loop (void)
{
  // When message is ready, print it on serial port
  if (message_ready)
  {
    message_ready = false;
    Serial.print((char) rx_buffer[0]);
    Serial.print((char) rx_buffer[1]);
    Serial.print((char) rx_buffer[2]);
    Serial.print((char) rx_buffer[3]);
    Serial.println((char) rx_buffer[4]);
  }
}

Changes done:

On setup(), SPDR is filled with the first response byte
Added a new function void changeTxMessage() that changes the response message sent by the Arduino for demo purposes.

Arduino output:
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5

RPi output:
Sent: zut 0
Received: abcde
Duration: 241 microseconds
Sent: zut 1
Received: crazy
Duration: 231 microseconds
Sent: zut 2
Received: kanji
Duration: 232 microseconds
Sent: zut 3
Received: buxom
Duration: 249 microseconds
Sent: zut 4
Received: crazy
Duration: 254 microseconds
Sent: zut 5
Received: kanji
Duration: 254 microseconds

Everything looks good!

Further thoughts
One thing I don't understand with the old code: why did I receive eabcd the first time I get an answer, the first byte should be random because I did not set the SPDR?! Maybe it's kept in memory during Arduino upload.

Performance
I cannot achieve high bit rates with this code. 250 000 Hz is the maximum I can reach (wiringPiSPISetup(0, 250000)) before getting problems in the communication. Example at 0.5 Mhz:
Arduino log:
zut 0
zut 1
zut 2
zut 3
zut 4
zut 5
zut 6
zut 7

RPi log:
Sent: zut 0
Received: bzut
Duration: 143 microseconds
Sent: zut 1
Received: czut
Duration: 136 microseconds
Sent: zut 2
Received: kzut
Duration: 135 microseconds

I expected to reach at least 2 Mhz, I think I'll open a new question for that.

To reach 2 MHz on Arduino Micro you will have to replace the ISR with a tight communications loop. The ISR overhead is just too large on a 16 MHz MCU. You might even have to turn off interrupts (Timer) to achieve reliable communication.


text:
Are (how much are) interupts interfering I2C or SPI communication?
I am thinking over an autonomous rover.
One of the features/components of the rover will be ability to know how fast is the rover moving and what distance did it travel. I would like to use dedicated attiny85 chip for that. The chip will use rotary encoder and interrupts to detect motion. It will be connected throught I2C/SPI (do not know yet) with the main controller. Main controller will ask the attiny85 on speed and distance if needed.
The problem is, I guess, that rotary encoder will use interrupts and so the I2C or SPI may not work properly. I could disable interrupts while communicating but:

Motion sensing won't be precise, as I will loose some motion data.
When attiny85 will be on receiving side, it wont know soon enough that it should disable the interrupts.
There is a chance that SPI/I2C uses the interrupts as well, not sure, have to check.

Am I right? What would you advise?

If your interrupts are brief enough I can't see them being a problem. 90% of the SPI or I2C communication is done in hardware anyway and won't be affected by the interrupts - it's only between each byte that you will be doing anything, and that may be done in interrupts (depending on your implementation) anyway which will mean other interrupts are disabled at the time.

@Majenko Thanks a lot. So this concept is worth trying you say. I will try it and then post the experience.

Certainly worth trying.

@Divisadero how did it work? I'm thinking about using the software serial library with I2C, and I would like to know if interrupts cause problems for I2C communication.

@daweim0 I was/am too busy, didnt get to that. I played a bit with I2C and interrupts and it dependes on the I2C speed. If you do not need high bitrate, you will be fine. But be sure to use hardware I2C for sure.