text:
avr_g++ compiler error: expected primary-expression before '.' token (C code in .ino)
The compiler is complaining about a macro defined in mjson.h
Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

#define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                           ^

The code compiles and links ok on Windows 7 platform running Visual Studio and Ubuntu running gcc.
The full build errors are:
Arduino: 1.8.5 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path AppData\Local\Temp\arduino_build_106446 -warnings=all -build-cache AppData\Local\Temp\arduino_cache_49629 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose Documents\Arduino\test_microjson\test_microjson.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries Documents\Arduino\libraries -fqbn=arduino:avr:uno -ide-version=10805 -build-path AppData\Local\Temp\arduino_build_106446 -warnings=all -build-cache AppData\Local\Temp\arduino_cache_49629 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose Documents\Arduino\test_microjson\test_microjson.ino
Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
"C:\Program Files (x86)\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=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp" -o "nul"
"C:\Program Files (x86)\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=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IDocuments\Arduino\libraries\microjson" "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp" -o "nul"
"C:\Program Files (x86)\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=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IDocuments\Arduino\libraries\microjson" "Documents\Arduino\libraries\microjson\mjson.c" -o "nul"
Generating function prototypes...
"C:\Program Files (x86)\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=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IDocuments\Arduino\libraries\microjson" "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp" -o "AppData\Local\Temp\arduino_build_106446\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "AppData\Local\Temp\arduino_build_106446\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -Wall -Wextra -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "-IDocuments\Arduino\libraries\microjson" "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp" -o "AppData\Local\Temp\arduino_build_106446\sketch\test_microjson.ino.cpp.o"
In file included from Documents\Arduino\test_microjson\test_microjson.ino:7:0:

Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

 #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                            ^

Documents\Arduino\test_microjson\test_microjson.ino:31:29: note: in expansion of macro 'STRUCTOBJECT'

   { "start_pin", t_integer, STRUCTOBJECT(lights_t, start_pin) },

                             ^

Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

 #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                            ^

Documents\Arduino\test_microjson\test_microjson.ino:32:27: note: in expansion of macro 'STRUCTOBJECT'

   { "end_pin", t_integer, STRUCTOBJECT(lights_t, end_pin) },

                           ^

Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

 #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                            ^

Documents\Arduino\test_microjson\test_microjson.ino:33:30: note: in expansion of macro 'STRUCTOBJECT'

   { "colour_red", t_integer, STRUCTOBJECT(lights_t, colour_red) },

                              ^

Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

 #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                            ^

Documents\Arduino\test_microjson\test_microjson.ino:34:32: note: in expansion of macro 'STRUCTOBJECT'

   { "colour_green", t_integer, STRUCTOBJECT(lights_t, colour_green) },

                                ^

Documents\Arduino\libraries\microjson/mjson.h:135:28: error: expected primary-expression before '.' token

 #define STRUCTOBJECT(s, f) .addr.offset = offsetof(s, f)

                            ^

Documents\Arduino\test_microjson\test_microjson.ino:35:31: note: in expansion of macro 'STRUCTOBJECT'

   { "colour_blue", t_integer, STRUCTOBJECT(lights_t, colour_blue) },

                               ^

test_microjson:40: error: expected primary-expression before '.' token

   { "type", t_string, .addr.string = thenode.type, .len = sizeof(thenode.type) },

                       ^

In file included from Documents\Arduino\test_microjson\test_microjson.ino:7:0:

Documents\Arduino\libraries\microjson/mjson.h:137:2: error: expected primary-expression before '.' token

  .addr.array.element_type = t_structobject, \

  ^

Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

   { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                          ^

Documents\Arduino\libraries\microjson/mjson.h:138:2: error: expected primary-expression before '.' token

  .addr.array.arr.objects.subtype = e, \

  ^

Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

   { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                          ^

Documents\Arduino\libraries\microjson/mjson.h:139:2: error: expected primary-expression before '.' token

  .addr.array.arr.objects.base = (char*)a, \

  ^

Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

   { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                          ^

Documents\Arduino\libraries\microjson/mjson.h:140:2: error: expected primary-expression before '.' token

  .addr.array.arr.objects.stride = sizeof(a[0]), \

  ^

Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

   { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                          ^

Documents\Arduino\libraries\microjson/mjson.h:141:2: error: expected primary-expression before '.' token

  .addr.array.count = n, \

  ^

Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

   { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                          ^

Documents\Arduino\libraries\microjson/mjson.h:142:2: error: expected primary-expression before '.' token

  .addr.array.maxlen = (int)(sizeof(a)/sizeof(a[0]))

  ^

Documents\Arduino\test_microjson\test_microjson.ino:41:26: note: in expansion of macro 'STRUCTARRAY'

   { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },

                          ^

Using library microjson in folder: Documents\Arduino\libraries\microjson (legacy)
exit status 1
expected primary-expression before '.' token

test_microjson.ino:
#include <stdlib.h>
#include <stdbool.h>

#include <stddef.h>  // offsetof - used in STRUCTOBJECT macro

#include <mjson.h>

#define MAX_SECTIONS 6  // we support up to six different sections on strip

// in json sections is an array of these light options
typedef struct light_section {
  int start_pin;
  int end_pin;
  int colour_red;
  int colour_green;
  int colour_blue;
}lights_t;

typedef struct node {
  char type[20];
  lights_t thelight[MAX_SECTIONS];
} node_t;

node_t thenode;

static int num_sections;

const struct json_attr_t section_attrs[] = {
  { "start_pin", t_integer, STRUCTOBJECT(lights_t, start_pin) },
  { "end_pin", t_integer, STRUCTOBJECT(lights_t, end_pin) },
  { "colour_red", t_integer, STRUCTOBJECT(lights_t, colour_red) },
  { "colour_green", t_integer, STRUCTOBJECT(lights_t, colour_green) },
  { "colour_blue", t_integer, STRUCTOBJECT(lights_t, colour_blue) },
  { NULL },
};

static const struct json_attr_t json_attrs[] = {
  { "type", t_string, .addr.string = thenode.type, .len = sizeof(thenode.type) },
  { "sections", t_array, STRUCTARRAY(thenode.thelight, section_attrs, &num_sections) },
  { NULL },
};

void setup() {

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  Serial.println("microjson test");

  static const char *s =
    "{ \"type\": \"section\", \"sections\": [{ \"start_pin\": 0, \"end_pin\": 71, \"colour_red\": 0, \"colour_green\": 255, \"colour_blue\": 0 }, { \"start_pin\": 216, \"end_pin\": 287, \"colour_red\": 255, \"colour_green\": 0, \"colour_blue\": 0 }] }";

  int status = json_read_object(s, json_attrs, NULL);

  if (status != 0)
    Serial.println(json_error_string(status));

  Serial.print("found ");
  Serial.print(num_sections);
  Serial.print(" sections");

  Serial.print("type=");
  Serial.println(thenode.type);

  //printf("type=%s\n", thenode.type);
  for (int i = 0; i < num_sections; ++i) {
    Serial.print("section [");
    Serial.print(i);
    Serial.print("]: start_pin=");
    Serial.print(thenode.thelight[i].start_pin);
    Serial.print(", end_pin=");
    Serial.print(thenode.thelight[i].end_pin);
    Serial.print(", red=");
    Serial.print(thenode.thelight[i].colour_red);
    Serial.print(", green=");
    Serial.print(thenode.thelight[i].colour_green);
    Serial.print(", blue=");
    Serial.println(thenode.thelight[i].colour_blue);
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

And the offending macro in mjson.h STRUCTOBJECT.  And also STRUCTARRAY.  Here they are:
 * Use the following macros to declare template initializers for structobject
 * arrays.  Writing the equivalents out by hand is error-prone.
 *
 * STRUCTOBJECT takes a structure name s, and a fieldname f in s.
 *
 * STRUCTARRAY takes the name of a structure array, a pointer to a an
 * initializer defining the subobject type, and the address of an integer to
 * store the length in.
 */
#define STRUCTOBJECT(s, f)  .addr.offset = offsetof(s, f)
#define STRUCTARRAY(a, e, n) \
    .addr.array.element_type = t_structobject, \
    .addr.array.arr.objects.subtype = e, \
    .addr.array.arr.objects.base = (char*)a, \
    .addr.array.arr.objects.stride = sizeof(a[0]), \
    .addr.array.count = n, \
    .addr.array.maxlen = (int)(sizeof(a)/sizeof(a[0]))

How can I fix this to get it to compile using Arduino avr-g++ ?
mjson.h is from microjson library.  I can provide more details of that if required.
mjson.h header:
/* Structures for JSON parsing using only fixed-extent memory
 *
 * This file is Copyright (c) 2014 by Eric S. Raymond.
 * BSD terms apply: see the file COPYING in the distribution root for details.
 */

#include <stdbool.h>
#include <ctype.h>
#include <stdio.h>
#include <sys/types.h>

#define NITEMS(x) (int)(sizeof(x)/sizeof(x[0]))

typedef enum {t_integer, t_uinteger, t_real,
          t_string, t_boolean, t_character,
          t_time,
          t_object, t_structobject, t_array,
          t_check, t_ignore}
    json_type;

struct json_enum_t {
    char    *name;
    int     value;
};

struct json_array_t {
    json_type element_type;
    union {
      struct {
        const struct json_attr_t *subtype;
        char *base;
        size_t stride;
      } objects;
      struct {
        char **ptrs;
        char *store;
        int storelen;
      } strings;
      struct {
        int *store;
      } integers;
      struct {
        unsigned int *store;
      } uintegers;
      struct {
        double *store;
      } reals;
      struct {
        bool *store;
      } booleans;
    } arr;
    int *count, maxlen;
};

struct json_attr_t {
    char *attribute;
    json_type type;

    union {
      int *integer;
      unsigned int *uinteger;
      double *real;
      char *string;
      bool *boolean;
      char *character;
      struct json_array_t array;
      size_t offset;
    } addr;

    union {
      int integer;
      unsigned int uinteger;
      double real;
      bool boolean;
      char character;
      char *check;
    } dflt;

    size_t len;
    const struct json_enum_t *map;
    bool nodefault;
};

#define JSON_ATTR_MAX   31  /* max chars in JSON attribute name */
#define JSON_VAL_MAX    512 /* max chars in JSON value part */

#ifdef __cplusplus
extern "C" {
#endif
int json_read_object(const char *, const struct json_attr_t *,
             /*@null@*/const char **);
int json_read_array(const char *, const struct json_array_t *,
            /*@null@*/const char **);
const /*@observer@*/char *json_error_string(int);

void json_enable_debug(int, FILE *);
#ifdef __cplusplus
}
#endif

#define JSON_ERR_OBSTART    1   /* non-WS when expecting object start */
#define JSON_ERR_ATTRSTART  2   /* non-WS when expecting attrib start */
#define JSON_ERR_BADATTR    3   /* unknown attribute name */
#define JSON_ERR_ATTRLEN    4   /* attribute name too long */
#define JSON_ERR_NOARRAY    5   /* saw [ when not expecting array */
#define JSON_ERR_NOBRAK     6   /* array element specified, but no [ */
#define JSON_ERR_STRLONG    7   /* string value too long */
#define JSON_ERR_TOKLONG    8   /* token value too long */
#define JSON_ERR_BADTRAIL   9   /* garbage while expecting comma or } or ] */
#define JSON_ERR_ARRAYSTART 10  /* didn't find expected array start */
#define JSON_ERR_OBJARR     11  /* error while parsing object array */
#define JSON_ERR_SUBTOOLONG 12  /* too many array elements */
#define JSON_ERR_BADSUBTRAIL    13  /* garbage while expecting array comma */
#define JSON_ERR_SUBTYPE    14  /* unsupported array element type */
#define JSON_ERR_BADSTRING  15  /* error while string parsing */
#define JSON_ERR_CHECKFAIL  16  /* check attribute not matched */
#define JSON_ERR_NOPARSTR   17  /* can't support strings in parallel arrays */
#define JSON_ERR_BADENUM    18  /* invalid enumerated value */
#define JSON_ERR_QNONSTRING 19  /* saw quoted value when expecting nonstring */
#define JSON_ERR_NONQSTRING 19  /* didn't see quoted value when expecting string */
#define JSON_ERR_MISC       20  /* other data conversion error */
#define JSON_ERR_BADNUM     21  /* error while parsing a numerical argument */
#define JSON_ERR_NULLPTR    22  /* unexpected null value or attribute pointer */

/*
 * Use the following macros to declare template initializers for structobject
 * arrays.  Writing the equivalents out by hand is error-prone.
 *
 * STRUCTOBJECT takes a structure name s, and a fieldname f in s.
 *
 * STRUCTARRAY takes the name of a structure array, a pointer to a an
 * initializer defining the subobject type, and the address of an integer to
 * store the length in.
 */
#define STRUCTOBJECT(s, f)  .addr.offset = offsetof(s, f)
#define STRUCTARRAY(a, e, n) \
    .addr.array.element_type = t_structobject, \
    .addr.array.arr.objects.subtype = e, \
    .addr.array.arr.objects.base = (char*)a, \
    .addr.array.arr.objects.stride = sizeof(a[0]), \
    .addr.array.count = n, \
    .addr.array.maxlen = (int)(sizeof(a)/sizeof(a[0]))

/* json.h ends here */

why do you want to use this library with Arduino?

.ino is compiled as C++. your test is C code. put the C code in a .c file and the declaration in .h file and include the .h in .ino
I created a test.c, copied the content of your main.c into it and renamed the main function to test().
Then I created a test.h with
#ifndef test_h
#define test_h

extern "C" void test(char * buff);

#endif

and in ino setup() I call test();
it compiles. It runs. Output:
2 sections
type=section
section [0]: start_pin=  0, end_pin= 71, red=  0, green=255, blue=  0
section [1]: start_pin=216, end_pin=287, red=255, green= 53, blue=  0

in ino
void setup()
{
  Serial.begin(115200);
  char buff[700];
  test(buff);
  Serial.print(buff);
}

in .c
void test(char* buff) {

  static const char *s =
      "{ \"type\": \"section\", \"sections\": [{ \"start_pin\": 0, \"end_pin\": 71, \"colour_red\": 0, \"colour_green\": 255, \"colour_blue\": 0 }, { \"start_pin\": 216, \"end_pin\": 287, \"colour_red\": 255, \"colour_green\": 0, \"colour_blue\": 0 }] }";

  int status = json_read_object(s, json_attrs, NULL);

  if (status != 0) {
    sprintf(buff, json_error_string(status));
    return;
  }

  int pos = sprintf(buff, "%d sections\n", num_sections);

  pos += sprintf(buff + pos, "type=%s\n", thenode.type);
  for (int i = 0; i < num_sections; ++i) {
    pos +=
        sprintf(buff + pos,
            "section [%d]: start_pin=%3d, end_pin=%3d, red=%3d, green=%3d, blue=%3d\n",
            i, thenode.thelight[i].start_pin, thenode.thelight[i].end_pin,
            thenode.thelight[i].colour_red, thenode.thelight[i].colour_green,
            thenode.thelight[i].colour_blue);
  }
}

Sorry about the confusion, I uploaded wrong exercising code.  Changed now to code I used in ino file

Do I put the test.h and test.c in the same folder as the test_microjson.ino or would I put in same folder as /Android/libraries/microjson ?

to project folder. to .ino.

Better but getting multiple definition of `test' at link stage now. Actually changed to testmj and now just getting error multiple definition of section_attrs

add guard #ifdef to mjson.h and test.h. https://en.wikipedia.org/wiki/Include_guard

yes already added guard - but still get this error. I put mjson.c & h and testmj.c & h in libraries/microjson folder.


text:
Is the strange problem I'm having to do with comparing floats?
I have a timer interrupt that controls a stepper motor, on an UNO board. In the interrupt handler it checks the speed of the motor and compares it to the target speed. This allows the motor to accelerate to the target speed in a non-blocking way.
This is the relevant part of the interrupt handler:
ISR(TIMER1_COMPA_vect){
    if (targetSpeed > 0 || motorSpeed > 0){
        // leading edge of the step cycle
        if (leadingEdge){
            digitalWrite(STEP_PIN, HIGH);
            stepNumber++;
            // check speed and adjust if necesary
            if (motorSpeed < targetSpeed){
                motorSpeed += speedIncrement;
            }
            else if (motorSpeed > targetSpeed){
                motorSpeed -= speedIncrement;
            }

            leadingEdge = false;
        }
        // trailing edge
        else{
            digitalWrite(STEP_PIN, LOW);
            leadingEdge = true;
        }
    }
    OCR1A = minInteruptsPerStep + (minInteruptsPerStep * (1 - motorSpeed));
}

In the loop() I have a function that checks the state of motorSpeed to control other functions
if (motorSpeed == targetSpeed) {
    motorState = RUNNING;
} else if (motorSpeed < targetSpeed) {
    motorState  = ACCELERATING;
} else if (motorSpeed > targetSpeed) {
    motorState  = DECELERATING;
}

motorSpeed and targetSpeed are floats and range from 0-1, in steps of 0.1 speedIncrement is 0.001 As far I can see that should ramp the speed up until motorSpeed == targetSpeed, in 100 steps. And this mostly what happens. The speed gets to targetSpeed and motorState switches from ACCELERATING to RUNNING, as expected.. mostly. The problem is that it occasionally starts flipping between the three states, for no reason I can see--there is nothing that should modify the value of motorSpeed outside the interrupt handler, so once it stops accelerating it should be stable.
Is this because I'm using and comparing floats? Should I scale the speed variables up and use an int or even a byte?

is motorSpeed  declared volatile?

Yep, all the variables in the interrupt handler are volatiles

There is a library for that: https://www.airspayce.com/mikem/arduino/AccelStepper/

I tried that, but had some problems with it and the LCD library I'm using, the two wouldn't co-exist for some reason.

They do not use the same timer, it should work. Perhaps they use too much memory. Which LCD library is it and is that working now?

it's liquidCrystal, I did some initial testing using another library for menus and the accelStepper. But then I ended up developing my own menu class, and learning about both interrupts and C++ classes, so I'm happy.

The biggest problem here is that floats don't compare well.  The issue is that a float isn't an exact number. It is, to a large extent, an approximation.
Some numbers cannot be represented by floats, so your "100" may be actually "100.00001", or "99.999999".
It is better to use integers whenever possible. Do your calculations using larger numbers, and then scale down the results when you need to use them.
If you're working in steps of 0.1 between 0 and 100, you should really be working instead in steps of 1 between 0 and 1000, and then divide by 10 later on when you need to use the value (if you even really need to do that).
Here's a little example I knocked up on Linux:
#include <stdio.h>

void main() {
    float f = 0;
    while (f < 100) {
        f += 0.1;
    }
    printf("%.6f\n",f);
}

You'd expect it to give "100.000000" as the answer. It doesn't. Instead you end up with 100.099045. That's because the closest it gets to 100 is actually the previous iteration: 99.999046.
If you do want to compare floats the best way is to use a "within X" operation.  Here's a little macro:
#define WITHIN(A,B,DIFF) (fabs((A) - (B)) <= (DIFF))

Then you can:
if (WITHIN(motorSpeed, targetSpeed, 0.1)) {
    ...
}

That should give you TRUE if the motorSpeed and targetSpeed are within 0.1 of each other.

Thanks. I haven't done much low level programming before, so I wasn't aware of the float issue. I might try changing to a more appropriate data type.

You already know, from previous answers, why the comparison doesn't give
you the result you expect: you assumed that any multiple of 0.1 is also
a multiple of 0.001, which is true for real numbers but nor for floats.
To fix the issue, it has been suggested to you to allow for some
fussiness in the comparison. I would suggest a different approach: keep
your comparisons as they are, and instead change the way the speed is
updated in the ISR:
if (motorSpeed < targetSpeed) {
    motorSpeed = min(motorSpeed + speedIncrement, targetSpeed);
}
else if (motorSpeed > targetSpeed) {
    motorSpeed = max(motorSpeed - speedIncrement, targetSpeed);
}

With this logic, motorSpeed will always end up being exactly equal
to targetSpeed, irrespective of whether the speed change is a multiple
of the increment or not.
A common misconception about floating point numbers has it that they are
not exact. Truth is, most floating point calculations involve rounding
errors, but the floating point numbers themselves are exact numbers,
if not the numbers you expect¹. Then, when you do the assignment
motorSpeed = targetSpeed;

which the code above ends up doing at some point, you can test
if (motorSpeed == targetSpeed) ...

and it will be true.
¹ When you write “0.1” in the source code, you get the float which is
closest to 0.1, which happens to be 0.100000001490116119384765625
exactly.

Nice idea, but it still elaves the problem of the comparison in the main loop() which checks the motor state. I've been reading about floats and I undertand the problem better, but what still puzzles me is that it doesn't seem to be deterministic. Since the value of motorSpeed and the value of targetSpeed is constant once the motor reaches a stable state—and in my tests it does report that motorSpeed == targetSpeed, why then after reporting this as true for hundreds of steps does it suddenly switch to false, even though there's nothing in the code that changes the value of either variable?.

Note that motorSpeed is not a measurement, it's the speed the arduino is telling the motor to run at, so it's not a mechanical issue.

I used this technique with ints, which solved the problem of speedIncrement not necessarily being a multiple of targetSpeed, and also the main loop() problem

@stib: Computations with floats are deterministic. If you witness non deterministic behavior, you will have to search somewhere else in your code.

You should never compare two floats with == or != directly. The reason is that floats are not accurate, so maybe 1.0 can be 0.99999999999, and the other value 1.0 might be 1.00000000001 (simplification).
Instead, use a 'range', like:
if (fabs(motorSpeed - targetSpeed) < 0.001)
{
   // Equal
}

This means the difference should be smaller than 0.001. fabs means the absolute value of a float (mathematic symbol |x| for the absolute value).
If you make more compares this way, make 0.001 a #define or const.

source: Stack Exchange

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

sort: votes


text:
How to handle a ESP8266 webserver only to the access point?
I'm developing a application that needs to be somewhat secure, so to configure the parameters it handles a GPIO interrupt (from a button) to open a server, that lets you configure it. The problem is that it is configured to send an email, so it is connected to the wifi.
With this in mind, I need to detect the source of the connection so I can serve the html only to the access point connections.
Is it possible?

I think what you want is that it's only accessible on the local network, and not from the internet, right?

Not only the local, no. I don't really know the exact terms, but I create a WiFi with my ESP and I want only people accessing from this exclusive WiFi to be able to change the configuration. Someone in the internet or accessing the same WiFi my esp is connected to gets rejected.

When the flag from the interrupt is 1, it puts the WebServer in STA_AP mode, I want it only be accessible via the AP side of the WebServer. I don't know if this clarifies.

So it's set to both be a client on the Wifi that's connected to the internet, and be an Accesspoint at the same time. Now it makes sense. (I didn't even know the ESP could do that.) I think you can filter based on IP address.

Maybe this is a good solution that I simply overlooked. I'll take a look.

Yep, thats absolutely simple. My access point is a 192.168.4.XXX and my LAN ip is 192.168.88.XXX, I can filter it very very easily. Thanks for the light.

You could also use the less used 10.x.x.x private range, to make it less likely that the network uses the same IP range.

It is not documented, but you can construct WiFiServer or ESP8266WebServer with IP address. If you use the IP address of the AP, the server will be available only on the SoftAP. If you use the IP address of the station, the server will be available only on STA interface.
#include <ESP8266WiFi.h>

WiFiServer telneServer(23);

void setup() {
  ...
  telneServer = WiFiServer(WiFi.softAPIP(), 23);
//  telneServer = WiFiServer(WiFi.localIP(), 23);
  telneServer.begin();

Thanks! I had already solved with the comment from above, but your answer seemed a lot more elegant, so I tried and it works just fine!
I just used had to declare the server with the IP and configure the softAP to be the same using: ESP8266WebServer server(local_ip,80) and WiFi.softAPConfig(local_ip, local_ip, IPAddress(255, 255, 255, 0)) .

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


text:
cross correlation of two analogread value on arduino?
I am working on a final project called sound source localization using Arduino Uno. I want to use two sound sensor to capture a sound. The nature of the sound is clap or speech sound. I want to use the cross correlation method to estimate the time delay between the microphones then find the position and angle. My supervisor said to me you have to store the values on analogRead in two arrays then cross correlation the element of two arrays. But i am struggle the cross correlation part. I will appreciate any help from you guys.
#define LED_NORTH 2
#define LED_SOUTH 4

#define MIC_NORTH A0
#define MIC_SOUTH A2

/* let's said we want to read 100 samples */
const unsigned int numReadings = 100;
unsigned int analogVals[numReadings];
unsigned int i = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED_NORTH, OUTPUT);
  digitalWrite(LED_NORTH, LOW);
  pinMode(LED_SOUTH, OUTPUT);
  digitalWrite(LED_SOUTH, LOW);
}

void loop() {
  int north = analogRead(MIC_NORTH);
  Serial.println(north);
  int south = analogRead(MIC_SOUTH);
  Serial.println(south);
  /* take numReadings # of readings and store into array */
  for(unsigned int i = 0; i < numReadings; i++)
  {
    analogVals[i] = analogRead(A0);
    delay(1000);
  }

What have you tried so far? Show us your code. What is its expected behavior? What is the actual behavior?

thanks Edgar Bonet , i update my question and i post my code i have done so far

The code you posted is incomplete. It cannot be compiled nor tested.

İ change a little bit the code.now i assume i can compile

Don't assume. Try.

Once you know how cross correlation works (https://en.m.wikipedia.org/wiki/Cross-correlation), the answer in this question might help you: https://arduino.stackexchange.com/q/11754/38721

you really need to think about what you need to do ... your code indicates that you have not done that yet ... in the loop() block, you read a value from the north mic, then you spend time printing, then you read a value from the south mic, then spend some time printing .... why are you doing that? ....... in the for loop, you read a value from the north mic and store the value, then you pause for one second and repeat .... why are you pausing? .... why are you not reading the south mic at the same time?

If you need to find a direction of sound in a full 360 you need at least 3 microphones. Otherwise will you not be able to detect the if the location of the sound is directly from front or behind.

I am not going to directly answer the question, as I think it is
ill-posed. Before posting a question here, you are supposed to have done
your research, and come with very specific problems you cannot solve
by your own. I may be mistaken, but it looks to me like you are at a
very preliminary stage where you barely started to think about the
project.
So, instead of trying to answer an overly broad question, I will try to
provide some guidance by asking questions back to you. Below is a list
of some problems and challenges you will have to consider for advancing
your project. It may not be complete: it's just what I can think off the
top of my head. This will hopefully help you tackle the right problems.
Non-stereo sampling
Your Arduino is incapable of stereo sampling. Since it has only one ADC,
it can only sample one channel at a time. This means you will have to
alternatingly sample the left channel, then the right channel, then the
left channel... Since the left and right samples are not taken at the
same time, this will have an implication on how you interpret the
results from the cross-correlation. Did you think about how you will
handle this? Is this acceptable? Will you have to instead use external
ADC chips in order to have real stereo sampling?
Slow sampling rate
If you analogRead() in a tight loop, you are taking at most one sample
every 112 µs. And since you are alternating between the channels,
on each channel you get one sample every 224 µs. This is a sampling
rate of 4.46 kHz, and a Nyquist frequency of 2.23 kHz. Is this
fast enough for your application?
In 224 µs, the sound travels about 76 mm, which is thus the
spatial resolution of your cross-correlation. How does this translate into
angular resolution? Is this resolution satisfactory? Do you plan to use
interpolation methods to try to improve it?
If the time resolution is not good enough, you can speed up the ADC by a
factor 2 or 4 at the cost of lowered accuracy. You will have to dig on
the MCU datasheet (or the Internet...) in order to learn how to do that.
Inconsistent sampling rate
When you use analogRead(), the time between consecutive samples can
depend on the code you run between the consecutive calls to
analogRead(). It can also depend on how your code gets interrupted by,
say, the timer interrupt, or the UART interrupt if you are sending data
out. An inconsistent sampling rate is something you want to avoid when
doing cross-correlations.
You could try to mitigate this problem by running the acquisition with
interrupts disabled. However, the only way to guarantee periodic
sampling is by configuring the ADC to be triggered automatically, either
by a timer or by itself (free running mode). Walking this path will
require you to forego the comfort of the Arduino library (analogRead()
is just so easy to use...), and carefully study the datasheet, which
would be a very significant time investment.
Do you have the time and energy for this? If you end up learning all
this low-level details on the configuration of the ADC, will this
learning be relevant to the course for which this is a project?
Finite data arrays
Mathematically, the cross-correlation is typically defined for infinite
series of samples. In your experiment, you will have to deal with finite
arrays, and this makes a subtle difference. Did you think about how you
will deal with the finiteness of the arrays? Are you going to zero-pad?
Remove the average before zero-padding? Apply a windowing function?

I hope it is clear by now that the “cross correlation part” is only one
of the many issues you will have to face. I suggest you discuss all
these questions with your supervisor. He might be able to advise you on
how to tackle them, whether it's worth it, where you may cut corners...


text:
analogRead() output oscillates even though the pin is grounded
I'm using Arduino Micro to read from 5 flex sensors and display the corresponding angles to the Serial monitor. I am currently having quite some problems with the oscillating values I am getting from the analogRead(). It doesn't seem to matter whether the pin is connected to a flex sensor or just grounded - the output is oscillating a lot.
Originally everything was being read and outputted just fine but I wanted to have an exact 100Hz sampling frequency and tried to play a bit with Timer Interrupts. And that's when this oscillating behaviour started. I reversed to my original code, which just uses some delay(), and simplified to only read from two pins, but cannot seem to shake off the oscillations.
I think I may have messed up something about ADC when trying to implement Interrupts, but I don't know how to check it or fix it. Please, help me figure out how to fix this!
This is the raw output of analogRead. The drop in values occurs when I bend the flex sensor:

And this is the resulting calculated angle. Also oscillating:

This is the code I've been using to read the pins:
int fin;
const int input[5] = {A0,A1,A2,A3,A4}; // the analog pins

int flex[5]; // analog signal read
float flexV;
float flexR[5]; // resistance on the 47k resistor
int angle[5]; // joint angles

const float VCC = 4.98; // Measured voltage of Arduino 5V line
// Measured resistance of the 47k resistors R1-R5
const float R[5] = {45900.0,45900.0,45900.0,45900.0,45900.0};

// Calibration values of resistance measured during straight phase and 90 deg bend phase
const float R_STRAIGHT[5] = {37651.0,37651.0,37651.0,37651.0,37651.0};
const float R_BEND[5] = {71783.0,71783.0,71783.0,71783.0,71783.0};

void setup() {

}

void loop() {

  for(fin = 0; fin <= 4; fin++) {
   flex[fin] = analogRead(input[fin]);
   flexV = flex[fin]*VCC/1023.0;
   flexR[fin] = R[fin] * (VCC/flexV - 1.0);
   angle[fin] = map(flexR[fin],R_STRAIGHT[fin],R_BEND[fin],0,90.0);
   delay(1);
    }
    Serial.print(angle[0]);
    Serial.print(" ");
    Serial.print(angle[1]);
    Serial.print(" ");
    Serial.print(angle[2]);
    Serial.print(" ");
    Serial.print(angle[3]);
    Serial.print(" ");
    Serial.print(angle[4]);
    Serial.print(" ");
    Serial.println(millis());
    delay(6);
}

The first graph looks to me like to are plotting two channels interspersed.

You have nothing in your setup loop. You need to set up all the inputs as inputs.
You setup() should look like this:
void setup()
 {
   Serial.begin(9600);
   for (int i = 0; i < 5; i++);
    {
      pinMode(input[i], INPUT);
    }
 }

The code cycles through your array "input", setting all the pins as inputs. Try that.

As I remember, the pinmode doesn't matter for analogRead, since pinMode(pin, INPUT) will set the pin as digital input. analogRead() will configure the pin to use the ADC, which has nothing to do with digital input. This is only often done for readability, so that the reader directly sees, which pins are inputs and which are outputs.

Gpios are input by default

I think the pins should be input by default? Anyways, I've tried that. No change. I think I somehow messed up the ADC by have no idea how to test it out...

You can easily test your ADC by connecting it to a variable power source. You should be seeing 1023 when it's at 5v and 0 when it's at 0v. If you don't have a variable power source use a 10K potentiometer, with the left side connected to 5v, middle pin to your ADC pin, and your right to GND. Turning the knob will produce the same results. You can also use a multimeter to verify the flex sensors are working properly.

Tried that out. I'm getting nice 1023 at 5V but anything between 220 and 800 at 0V...

Hmm sounds like a bad grounding issue to me. How are you powering the Arduino?


text:
Cannot create a PWM with 20% duty cycle using micro() timer
I have been working with Arduino for almost a year, because I found it easy for beginners in electronics. But now, I have a major problem, I'm trying to get rid of my delay() function because I want my Arduino Nano to handle to tasks at once:
1-Read MIDI data and transfert it into a pwm signal, as well as monitoring the on and off of the signal (which are bytes). This part works correctly, but i'm not using the mirco(), i'm using a library called Timer1.
2-Generate a PWM signal of 20% dutycycle with a frequency ranging from 1 to 103 Hz using a potentiometer to adjust the frequency.
So, what happens is that the signal I measure on my oscilloscope is a PWM at 50% duty cycle and with frequencies that don't match my calculations at all. Also, It doesn't change smoothly, the frequency goes from 159Hz to let's say 180Hz only at one particular point on the potentiometer, just like if all the rest of it was useless. I decided to monitor all my values with Serial and everything was good, the values were OK and nothing was wrong. Then I decided to change all my variables to floats so I could maybe get more precision... Didn't work as well. So now I'm kind of desesperate.
//MANUAL MODE TEST WITH MICROS()
//VARIABLES ASSIGNEMENT
unsigned long current=0.0;
unsigned long previous=0.0;

float TimeOn = 0.0;
float TimeOff = 0.0;
float manuelF = 0.0;
float sensor = 0.0;

int pin = 11;

byte state = LOW;

//SETUP AND PIN ASSIGNEMENT
void setup() {
  pinMode(9, OUTPUT);//MUSIC SIGNAL OUTPUT
  pinMode(11, OUTPUT);//MANUAL SIGNAL OUTPUT
  pinMode(A5, INPUT);//POTENTIOMETER MANUAL
  pinMode(A6, INPUT);//POTENTIOMETER MUSIC
  Serial.begin(9600);
}

void loop() {

  sensor = analogRead(A5);
  manuelF=((sensor+10.0)/10.0); //Capture la fréquence sur A5
  TimeOn=1000000.0*(0.2*(1.0/manuelF));
  TimeOff=1000000.0*(0.8*(1.0/manuelF));
  current = micros();

  Serial.println(TimeOn);

  //Serial.print("A5 read:");
  //Serial.println(analogRead(A5),8);
  //Serial.println("-----------");
  //Serial.print("Fréquence: ");
  //Serial.println(manuelF,8);
  //Serial.print("timeon:");
  //Serial.println(TimeOn,8);
  //Serial.print("timeoff:");
  //Serial.println(TimeOff,8);

  if ((state == LOW)&&(current - previous >= TimeOff)){
      state = HIGH;
      digitalWrite(pin,state);
      previous = current;
    }
  else{
    if (current - previous >= TimeOn){
      state = LOW;
      digitalWrite(pin,state);
      previous =current;
    }

  }
 }

As you can see I'm still monitoring the TimeOn variable. Well, It shows exactly (to 4 micro seconds precise) the time that it is supposed to be ON.
My output at that moment is a 50% duty cycle with a frequency of 53Hz when I pass the 7k on the potentiometer (it is a 10k). Before that, it doesn't even outputs a signal.
What is going on?
EDIT#1:
I have done the modifications that @Edgar Bonet suggested me. It partially worked. What i'm left with now is a PWM that can go from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....

I have found the problem. Part of it was the code, thank you @Edgar Bonet. The other part was the pin I was using to generate the PWM signal. Throughout my reasearch, I found that on the arduino nano, the timer pins are the same than those on the arduino Uno. Thus:
Timer0 :pins 5-6
Timer1 :pins 9-10
Timer2 :pins 3-11
Since I was using the function micros() which uses the timer0, I had to send the signal to the right pin. I cannot describe why it did send a certain PWM to discrete frequencies, but the important is that it now works.
In parallel, because the other part of my program is using timer1, the two data transmission won't interfere with each other!
Time inversted in researches: 4hours
Hope this helps someone! Thanks.

You wrote:
if ((state == LOW)&&(current - previous >= TimeOff)){
    state = HIGH;
    digitalWrite(pin,state);
    previous = current;
  }
else{
  if (current - previous >= TimeOn){
    state = LOW;
    digitalWrite(pin,state);
    previous =current;
  }

While you probably mean:
if (state == LOW && current - previous >= TimeOff) {
    state = HIGH;
    digitalWrite(pin, state);
    previous = current;
}
else if (state == HIGH && current - previous >= TimeOn) {
    state = LOW;
    digitalWrite(pin, state);
    previous =current;
}

Thank you! It solved a good part of the problem. Now, I can control a PWM from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....

changed current=micros() to current=millis(), gives even worse results...

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


text:
Multiple random Fire2012 sequence in same strip
I am trying to simulate 4 flickering flames on a single LED strip.
The ws2812b strip has 60 LEDs. I cut and chained it into 4 chunks of 15 LEDs. Each chunk has a random Fire2012 sequence, however the entire sequence seems to start and stop at the same time, and therefore they all look extremely similar.
What is the best way to overlap the fire sequences so that timing looks different for each chunk?
Here is my code so far...
#include <FastLED.h>

#define LED_PIN     5
#define COLOR_ORDER GRB
#define CHIPSET     WS2812B

#define NUM_CHUNKS           4
#define NUM_LEDS_PER_CHUNK   15
#define NUM_LEDS NUM_CHUNKS * NUM_LEDS_PER_CHUNK

#define BRIGHTNESS  80
#define FRAMES_PER_SECOND  30

#define gReverseDirection false

CRGB leds[NUM_LEDS];

void setup() {
  delay(3000); // sanity delay
  FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness( BRIGHTNESS );
}

void loop()
{
  // Add entropy to random number generator; we use a lot of it.
  // random16_add_entropy( random());

  // Get LED Chunks
  for(int i = 0; i < NUM_CHUNKS; i++){
    //random16_add_entropy( random());
    Fire2012(i); // run simulation frame
  }

  FastLED.show(); // display this frame
  FastLED.delay(1000 / FRAMES_PER_SECOND);
}

// Fire2012 by Mark Kriegsman, July 2012
// as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY
////
// This basic one-dimensional 'fire' simulation works roughly as follows:
// There's a underlying array of 'heat' cells, that model the temperature
// at each point along the line.  Every cycle through the simulation,
// four steps are performed:
//  1) All cells cool down a little bit, losing heat to the air
//  2) The heat from each cell drifts 'up' and diffuses a little
//  3) Sometimes randomly new 'sparks' of heat are added at the bottom
//  4) The heat from each cell is rendered as a color into the leds array
//     The heat-to-color mapping uses a black-body radiation approximation.
//
// Temperature is in arbitrary units from 0 (cold black) to 255 (white hot).
//
// This simulation scales it self a bit depending on NUM_LEDS; it should look
// "OK" on anywhere from 20 to 100 LEDs without too much tweaking.
//
// I recommend running this simulation at anywhere from 30-100 frames per second,
// meaning an interframe delay of about 10-35 milliseconds.
//
// Looks best on a high-density LED setup (60+ pixels/meter).
//
//
// There are two main parameters you can play with to control the look and
// feel of your fire: COOLING (used in step 1 above), and SPARKING (used
// in step 3 above).
//
// COOLING: How much does the air cool as it rises?
// Less cooling = taller flames.  More cooling = shorter flames.
// Default 50, suggested range 20-100
#define COOLING  55

// SPARKING: What chance (out of 255) is there that a new spark will be lit?
// Higher chance = more roaring fire.  Lower chance = more flickery fire.
// Default 120, suggested range 50-200.
#define SPARKING 60

void Fire2012(int chunk)
{
// Array of temperature readings at each simulation cell
  static byte heat[NUM_LEDS_PER_CHUNK];

  int startLed = NUM_LEDS_PER_CHUNK * chunk;
  int endLed = NUM_LEDS_PER_CHUNK * chunk + NUM_LEDS_PER_CHUNK;

  // Step 1.  Cool down every cell a little
    for( int i = 0; i < NUM_LEDS_PER_CHUNK; i++) {
      heat[i] = qsub8( heat[i],  random8(0, ((COOLING * 10) / NUM_LEDS_PER_CHUNK) + 2));
    }

    // Step 2.  Heat from each cell drifts 'up' and diffuses a little
    for( int k= NUM_LEDS_PER_CHUNK - 1; k >= 2; k--) {
      heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
    }

    // Step 3.  Randomly ignite new 'sparks' of heat near the bottom

    if( random8() < SPARKING ) {
      int y = random8(7);
      heat[y] = qadd8( heat[y], random8(160,255) );
    }

    // Step 4.  Map from heat cells to LED colors
    for( int j = 0; j < NUM_LEDS_PER_CHUNK; j++) {
      CRGB color = HeatColor( heat[j]);
      int pixelnumber;
      if(gReverseDirection) {
        pixelnumber = (endLed - 1) - j;
      } else { //0 15
        pixelnumber = startLed + j;
      }
      leds[pixelnumber] = color;
    }
}

Instead of calling them all back to back like that in the for loop, break them up with a little delay between each one.

https://github.com/darrenpmeyer/Arduino-FireBoard/ is built on the FastLED fire example, but supports configurable width. Could that be a viable alternative?

@MikaelFalkvidd that might provide the effect I am looking for, however I would like to know how to accomplish it by way of setting up the loop and delay correctly.

#include <FastLED.h>

 #define LED_PIN     5
 #define COLOR_ORDER GRB
 #define CHIPSET     WS2811
 #define NUM_LEDS    (kMatrixWidth * kMatrixHeight)
 #define FRAMES_PER_SECOND 60
 //////////////////////////////////////////////////////
 const uint8_t kMatrixWidth  = 15;
 const uint8_t kMatrixHeight = 4;
 const bool    kMatrixSerpentineLayout = true;
 //////////////////
 int BRIGHTNESS = 250;

//////////////////////////////////////////////////
bool gReverseDirection = false;

CRGB leds[NUM_LEDS];

void setup() {
Serial.begin(115200);
Serial.println("*** Inicialization");
///////////////////////////////////////////////
delay(3000); // sanity delay
FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS);
FastLED.setBrightness( BRIGHTNESS );
}
/////////////////////////////////// end setup

void loop()
{

 Fire2012();
 FastLED.show(); // display this frame
 FastLED.delay(1000 / FRAMES_PER_SECOND);
 FastLED.setBrightness( BRIGHTNESS );
 }

 void Fire2012()
 {
  int COOLING = 90;
  int SPARKING = 100;
   // Array of temperature readings at each simulation cell

    static byte heat[kMatrixWidth] [kMatrixHeight];

    // Step 1.  Cool down every cell a little
    for (int n = 0; n< kMatrixHeight; n++)
   {

     for ( int i = 0; i < kMatrixWidth; i++) {
       heat[i][n] = qsub8( heat[i][n],  random8(0,
       ((COOLING * 10) / (kMatrixWidth)) + 2));
       }

       // Step 2.
      for ( int k = (kMatrixWidth- 1); k >= 2; k--) {
      heat[k][n] = (heat[k - 1][n] + heat[k - 2][n] +
      heat[k - 2][n] ) / 3;
      }

       // Step 3.
      if ( random8() < SPARKING ) {
       int y = random8(3);
       heat[y][n] = qadd8( heat[y][n], random8(160, 255) );
      }
     }

  // Step 4.  Map from heat cells to LED colors

for ( int i= 0; i < kMatrixWidth; i++) {
  for (int j = 0; j < kMatrixHeight; j++) {

    CRGB color = HeatColor(heat[i][j]);
    leds[XY(i, j)] = color;

     }
   }

 }

   /////////////
    uint16_t XY( uint8_t x, uint8_t y)
    {
    uint16_t i;
    if ( kMatrixSerpentineLayout == false) {
    i = (y * kMatrixWidth) + x;
    }
    if ( kMatrixSerpentineLayout == true) {
    if ( y & 0x01) {
     // Odd rows run backwards
     uint8_t reverseX = (kMatrixWidth - 1) - x;
     i = (y * kMatrixWidth) + reverseX;
     } else {
    // Even rows run forwards
      i = (y * kMatrixWidth) + x;
     }
    }

    return i;

   }/////

I've adjusted the lights to be WS2812B and it works as expected

Instead of calling the function on all 3 chunks back to back in the for loop and then only doing show() after you've updated all three chunks, break it up a little and put a little delay between them.
    byte i = 0;

    void loop(){
       Fire2012(i);
       FastLED.show();
       FastLED.delay(1000 / NUM_CHUNKS / FRAMES_PER_SECOND);
       i = (i + 1) % NUM_CHUNKS;
    }

You could even make the delay a little bit random if you wanted to.

right. I was considering this. I wasn't quite sure how to ensure the first show would exceed the delay so that it would overlap then next loops show. I'll give this a go.

@delta-g  unfortunately it has the same effect.

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


text:
Unstable ESP8266 - flickering lights
A while ago I have bought NodeMCU board along with few sensors to play with. I have coded everything, and, when powered via USB, works like a charm. Problem begins, when I try to use my contraption as a standalone system. It works for few minutes, then it starts giving me false readings from the sensors (like, luminosity of few thousands in a dark room).
I am powering the system with (pics at the bottom of the post) AC-DC step down module, 230v -> 5v (1A of current), which then I am stepping down with DC-DC step down module, 5v -> 3v (800mA of current). Using only these two modules, I power NodeMCU and all of my sensors - currently luminosity, temp&humid, motion, SSR (I had led matrix too. I thought that maybe it drags too much current, but no luck there - after disconnecting it I have same problems).
My main indicator that something is not right, is SSR module. It has a built-in diode of the same size that NodeMCU has. It lights immediately as I start the system, and it (it's diode) flickers (it's intensity changes). It does not flicker, when I connect everything through USB.
I have also tried to put 50uF capacitor into the wiring, but no luck either, system is still unstable. What am I doing wrong? Why does the light flickers? Is 1A/800mA not enough power for my system?
Edit: I know what is the cause. I just do not know how to fix it. I just kept my multimeter on for 10mins for both of the step down modules. 5V -> 3V step down (2nd item in the pics below) is initially giving me 800mA, but then gradually losing current (right now it's at 350mA after just few minutes of work). Is there anything I can do here? Or just throw the thing away and look for some other power supply? It's a standard AMS 1117 with some capacitors on it.
Below are the pictures, of my step-down modules and SSR module:

The VIN pin on the NodeMCU board can take the 5V directly. Had no problem with that way until now.
What is strange to me is that the current from your 5V to 3V regulator  is degrading. The regulator on the board it's self is basically the same (maybe another manufacturer). What may be the cause is that the regulator is overheating and somehow that the effects the output current and/or voltage.
What you can also try is a LM2596 step down regulator.
Those are pretty cheap as well and have a good output capacitance. They can deliver up to 3A at down to ~1.3V. Input voltage is somewhere between 40V and your output voltage plus 1 or 2 volts to let it properly regulate.
You can use that module to transform your 5V down to 3.3V easily - i've done it so often with it, i lost count.

Take care how you power the nodemcu. the VU pin is 5v from USB and i am not sure it can be powered with this pin. I do think it is safe to power your device with the 3.3v pins.
does that solid state relay want 5v?
it may be best to put 5v (upto 20v max) into the VIN pin (which goes to the on-board voltage regulator).

You still ask a question in the second paragraph. I suggest Check to see if the solid state relay really needs 5V.

I am powering the NodeMCU with 3.3v (into 3.3v pins), as I plan on running standalone (non-nodeMCU) esp modules, so need 3.3v there. The SSR takes 5v.


text:
SIM808 module: GSM location command (AT+CIPGSMLOC=1,1) giving wrong value after execution of sending message command (AT+CMGS=+91xxxxxxxx)
I wrote the code that if an interrupt is generated, get GSM location and send a  message.
The first time the interrupt is generated, I got the correct GSM location using AT+CIPGSMLOC=1,1 and successfully sent a message using the AT+CMGS=+91xxxxxxxxcommand.
But the next time an interrupt was generated, AT+CIPGSMLOC=1,1 gave a wrong location. When I commented out the code to send a message, on every interrupt generated I am getting the correct GSM location. So it seems like the problem is occurring after sending a message. But I have no clue what exactly is going wrong. Following is my code.
Note: on restarting the module, I'm again getting the correct location the first time, before sending a message.
void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  while (!Serial) {
  }
  // initialize the pushbutton pin as an input:
  pinMode(sensorPin, INPUT);
  // Attach an interrupt to the ISR vector
  attachInterrupt(0, pin_ISR, FALLING);
}

/////////***GSM RESPONSE***///////////
String DisplayGSMResponse() {
  if(mySerial.available()) {
    String gsm_input="";
    while(mySerial.available()) {
      gsm_input+= (char)mySerial.read();
    }
    gsm_input.trim();
    delay(1000);
    Serial.println(gsm_input);
    return gsm_input;
  }
}

void SendMessage(String mobNum,String Location) {
  Serial.println("Sending message..");
  mySerial.println("AT+CMGF=1");
  //Sets the GSM Module in Text Mode
  delay(2000);
  // Delay of 1000 milli seconds or 1 second
  DisplayGSMResponse();
  mySerial.println("AT+CMGS=\""+mobNum+"\"\r");
  // mobile Number
  delay(4000);
  DisplayGSMResponse();
  cleanBuffer();
  mySerial.print("test");
  // The SMS text you want to send
  delay(100);
  mySerial.println((char)26);
  // ASCII code of CTRL+Z
  delay(8000);
  DisplayGSMResponse();
}

void gprsInit() {
  if (isGPRSInit) {
    return;
  }
  Serial.println("GPRS INITIALIZING");
  mySerial.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
  delay(2000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=3,1,\"APN\",\"INTERNET\"");
  delay(2000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=1,1");
  delay(8000);
  DisplayGSMResponse();
  mySerial.println("AT+SAPBR=2,1");
  delay(2000);
  DisplayGSMResponse();
  isGPRSInit = true;
}

void gprsterm() {
  mySerial.println("AT+SAPBR=0,1");
  delay(1000);
  DisplayGSMResponse();
  isGPRSInit = false;
}

String getGPS() {
  Serial.println("GETTING GPS LOCATION");
  String loc = "";
  String location = "";
  mySerial.println("AT+CIPGSMLOC=1,1");
  delay(3000);
  loc = DisplayGSMResponse();
  return location;
}

void loop() {
  if (buttonState == 1) {
    detachInterrupt(0);
    gprsInit();
    location = getGPS();
    SendMessage(mobileNumber, location);
    gprsterm();
    Serial.println("location = " + location);
    buttonState = 0;
    location = "";
    attachInterrupt(0, pin_ISR, FALLING );
  }
}

void pin_ISR() {
  buttonState = 1;
  Serial.println("interrupt");
}

EDIT: added gprsterm function.
Note: I removed the interrupt and called the code inside the loop function twice. The first time I got a correct result. The second time a wrong result. So it seems like the interrupt is not be causing the problem.
EDIT2:
One interesting thing I found is that at my home it is showing correct results every time, but in the office it is showing a wrong location on second location call i.e after the SMS was sent and we get the GSM location using AT+CIPGSMLOC=1,1.

What does your gprsterm() function do? But more importantly, review how you are using interrupts, please consult how to use attachInterrupt() on arduino.cc

added gprsterm func. I removed the interrupt and called the code inside loop function twice. first time got correct result. second time wrong result. so it interrupt seems not be causing problem.

Check the function getGPS(). Especially the usage of the local String variables. You might find something there :)

I checked local string variable all are well means intialized with empty string then with data. on interesting thing I found is that at my home it is giving correct results every time, but in office it is showing wrong location on second location call,

It might be due to the command giving the nearest cell tower location. And for sending SMS it might be shifting to a different cell tower depending on your network. This could maybe be easily checked using a different cell provider or as you said its working at your home so I believe I am correct in assuming this is the answer

Serial.println("location = " + location);

I think in upper line you should remove + sign from the code.


text:
Changing the mode when pressing/holding down a buttton
And first of all sorry for my bad English.
I am trying to write code that allows the user to change between continuous or manual mode, but I am having some issues getting it to work. The goal is to be able to switch from manual SOS (user pressing the button to SOS) and automatic SOS (the led automatically blinking SOS morse).
Currently, when I press down the button it loops once the automatic SOS and returns back to its normal state with LED on.
How would I make it, for an example switch the mode to manual when holding down button and giving user some sort of indication when changing the mode (etc blinking the led for X amount of time?)
What I am looking to achieve is:

Turn LEDS on when pressing the button.
Start looping automatic SOS signal
Press or hold down the button to change mode.

Blink LEDS to indicate the mode change.

Switch to manual SOS signal (user pressing the button to signal)
Press or hold down the button to change mode.

Blink LEDS to indicate the mode change.

Switch back to an automatic loop.

The code so far:
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin =  13; // the number of the LED pin
int mode;

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  mode = digitalRead(buttonPin);

  // Manual SOS mode.
  buttonState = mode;

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
    digitalWrite(ledPin, HIGH); // turn LED on:
  } else {
    digitalWrite(ledPin, LOW); // turn LED off:
  }

  // Automatic SOS mode.
  if (mode == HIGH) {
    // check if the pushbutton is pressed.
    // if it is, starts looping automatic SOS.
    int i = 0;
    for (i=0; i<3; i++) {
      digitalWrite(ledPin, HIGH);   // turn the LED on
      delay(300); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(300); // wait for a second
    }

    for (i=0; i<3; i++){
      digitalWrite(ledPin, HIGH); // turn the LED on
      delay(1200); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(1200); // wait for a second
    }

    for (i=0; i<3; i++){
      digitalWrite(ledPin, HIGH); // turn the LED on
      delay(300); // wait for a second
      digitalWrite(ledPin, LOW); // turn the LED
      delay(300); // wait for a second
    }
    digitalWrite(ledPin, LOW);
    // waits 3 seconds before starting the loop again
    delay(3000);
  }
}

What you want to achieve is definitely not clear to me: can you please clearly state what would you expect your Arduino to do?
Eq: "when button is pressed automatic SOS is interrupted and manual SOS signal is emitted once, then no signal is emitted until the button is pressed again".

Sorry, English is not my primary language but I will try my best: What I want is the program to have 2 different modes: mode 1: automatic SOS signal and mode 2: manual SOS signal (led blinking). And then the option to swap between these two modes by pressing/holding down the button

Ok, I'll try to split the code into multiple sections for clarity, but all this goes into one single sketch.
First we define the PINs: defines are pre-processor macros, even better than const in terms of performance and space consumption:
#define BTN_PIN 2
#define LED_PIN 13

Let's initialize the board as per our requirements:
void setup() {
  pinMode(BTN_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
}

Now we define the code which emits and SOS signal in morse code using the standard timing:

a long pulse lasts 3 times a short one
a space lasts 6 times a short pulse

That boils down to the following definitions considering a standard unit of 300ms:
#define UNIT 300
#define SHORT (UNIT)
#define LONG (UNIT*3)
#define PAUSE (UNIT*3)
#define SPACE (UNIT*6)

I'm also going to define another macro to emit a generic light pulse, for simplicity I'll use the delay(...) function, but this will prevent detecting button presses while signalling:
#define PULSE(TYPE) digitalWrite(LED_PIN, HIGH);delay(TYPE); digitalWrite(LED_PIN, LOW);delay(UNIT)

With the above in place we can define a function to send an SOS which should be both very compact and also readable:
void sendSOS() {
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
  PULSE(PAUSE); // inter letter pause
  PULSE(LONG);PULSE(LONG);PULSE(LONG);
  PULSE(PAUSE); // inter letter pause
  PULSE(SHORT);PULSE(SHORT);PULSE(SHORT);
}

Now, let's describe what the mode changing should be notified to the user:
#define QUICK 100
bool autoMode = true;

void switchMode() {
  autoMode= !autoMode;
  for (unsigned int i = 0; i < 25; i++) {
    digitalWrite(LED_PIN, HIGH);
    delay(QUICK);
    digitalWrite(LED_PIN, LOW);
    delay(QUICK);
  }
}

Now our main loop will have to check the button and act accordingly, right?
#define LONGPRESS 500
unsigned long elapsed;
bool clicked = false;
unsigned long duration;

void loop() {
  if (autoMode) {
    sendSOS();
  }
  elapsed = millis();
  while(clicked || millis() - elapsed <= SPACE) {
    // keep waiting to emit a SPACE or until the button is released

    if (digitalRead(BTN_PIN)) {
      // button has been clicked: trace it and start counting time
      clicked = true;
      duration = millis();
    } else if (clicked) {
      // button has been released: stop tracing and verify click duration
      clicked = false;
      if (millis() - duration <= LONGPRESS) {
        // switch mode on long press
        switchMode();
      } else if (!autoMode) {
        // short press has a meaning only when not in auto mode
        sendSOS();
      }
    }
  }

The solution above has great space for improvement:

there is no de-bouncing on the button
the board is unresponsive while signalling
keeping the button pressed forever will prevent any signalling to occur in any mode
the code is afflicted by millis() rollover if you keep the button pressed for long periods (around 49 days)

UPDATE: I've added the inter-letter pause as suggested in the comments.
UPDATE: apparently auto is a reserved word, so I changed it to autoMode.

#define is not better than const in C++. 2. You forgot the short inter-letter space. 3. Your code is not afflicted by the millis() rollover.

While better is definitely arguable (what's better for me might not be better for you) #define does not increase memory usage, const requires an additional pointer. 2. you are right 3. it is affected by millis() rollover if you keep the button pressed for 49 days...

Thank you, I will take a look at this once I am back at home. It seems complicated but I am sure I can understand it if I just give it enough time.

No, const doesn't cost more memory than #define. Try it! 3. You are right, I edited the answer accordingly.

Once again your comment on point 1 is correct: I thought #define uses FLASH while const uses SRAM but I believe my assumption is not always correct... not sure about all the details and how much compiler optimization options have influence on this. Thanks for the corrections!

So I tried your code, but I can't seem to get it work. It is giving me an error saying: ''expected unqualified-id before '=' token''. Notice that I didn't use the macros as I need to take a better look at those, so I slightly modified the code to use const instead. Anyways here is the current code: http://pastebin.com/mAF6tApf

I identified an issue in my code and updated it accordingly, but you have other issues in your code as a consequence of your manipulations: missing replacement of some defines and a missing closed curly brace, for what I saw.

Yeah, I noticed that too and fixed it again. Now it kinda works but it doesn't have the method for manual SOS from my original code. I added the method to the code but I am not sure how to implement it to your code in order to make it work. Currently, it loops the automatic SOS until I hold down the button for switching the mode, but doesn't change the mode. Here is the updated code: http://pastebin.com/5v6g3igE

You wrote: “I thought #define uses FLASH while const uses SRAM”. On this architecture, numeric literals and #defines tend to be compiled into immediate arguments. Same for const in C++. In plain C, const does cost RAM because it defaults to external linkage. #defines are OK, static const is probably also fine.


text:
Can't read from / write to SPI EEPROM
I'm currently trying to write to and read from an 25LC256-E EEPROM with my Arduino Uno via SPI. I've made a program which is supposed to do this, but I only get weird answers.
I'm sending in a Serial-string.
This string should start with 'w', 'r' or 'e', depending on what action I want to perform. The second character should be an int between 0 and 3 to determine witch PIN I should use as slave (currently I'm using only 1 slave, so the int should always be 0).
The rest of the string gets written to the EEPROM, one byte/character at the time.
What am I missing?
CODE:
    #include <SPI.h>

    #define WREN  6
    #define WRDI  4
    #define RDSR  5
    #define WRSR  1
    #define READ  3
    #define WRITE 2

    // Multiple slaves for future project
    const int CHANNELS[4] = {10, 8, 7, 4};
    String readResult;

    void setup() {

      Serial.begin(9600);
      channelSetup(); // Set all slave pins in CHANNELS to OUTPUT and HIGH

      SPI.begin();
      SPI.setDataMode(SPI_MODE3);
      SPI.setClockDivider(SPI_CLOCK_DIV2);
      SPI.setBitOrder(MSBFIRST);

    }

    void loop() {

      Serial.println("START");

      while(!Serial.available());
      delay(20);

      // Get all available bytes/characters
      String serialInput = getSerialStream(Serial.available());

      // Second character in serialInput is an int between 0 and 3
      int channel = makeValidChannel(serialInput[1]);

      // "channel" must be between 0 and 3
      // to be able to point to CHANNELS
      if (channel >= 0 && channel <= 3) {

        // First character decides what to do
        switch (serialInput[0]) {

          case 'w':
            writeToChannel(channel, serialInput.substring(2));
            break;

          case 'r':
            readResult = "EMPTY";
            readResult = readFromChannel(channel);
            Serial.print("Result: ");
            Serial.println(readResult);
            break;

          case 'e':
            overWriteEEPROM(channel);
            break;

          default:
            Serial.println("INVALID FIRST OPERATION");

        }

      }

      else
        Serial.print("INVALID CHANNEL: ");
        Serial.println(channel);

    }

    void channelSetup() {

      for (int i = 0; i < sizeof(CHANNELS); i++) {

        pinMode(CHANNELS[i], OUTPUT);
        digitalWrite(CHANNELS[i], HIGH);

      }

    }

    String getSerialStream(int numOfChars) {

      char serialStream[numOfChars + 1];
      int i;

      for (i = 0; i < numOfChars; i++) {

        serialStream[i] = char(Serial.read());
        delay(5);

      }

      serialStream[i] = '\0';
      return String(serialStream);

    }

    int makeValidChannel(char chIn) {

      int channel = chIn - '0';
      //channel -= 48;

      if (channel >= 0 && channel <= 3)
        return channel;
      else
        return -1;

    }

    void writeToChannel(int channel, String message) {

      int slaveselect = CHANNELS[channel];
      int i;

      // Write enabled
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WREN);
      digitalWrite(slaveselect, HIGH);
      delay(5);

      // Disable Write Protection
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WRSR);
      SPI.transfer(0);
      digitalWrite(slaveselect, HIGH);
      delay(5);

      for (i = 0; i < message.length(); i++) {

        digitalWrite(slaveselect, LOW);
        SPI.transfer(WRITE);
        SPI.transfer(0);
        SPI.transfer(i);
        SPI.transfer(message[i]);
        digitalWrite(slaveselect, HIGH);
        delay(5);

      }

      // When writing of "message" is done,
      // add a 0-byte as terminating character
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WRITE);
      SPI.transfer(0);
      SPI.transfer(i);
      SPI.transfer(0x00);
      digitalWrite(slaveselect, HIGH);
      delay(5);

      // Enable Write Protection
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WRSR);
      SPI.transfer(3);
      digitalWrite(slaveselect, HIGH);
      delay(5);

      // Write Disabled
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WRDI);
      digitalWrite(slaveselect, HIGH);
      delay(5);

    }

    String readFromChannel(int channel) {

      Serial.println("Reading started");

      int slaveselect = CHANNELS[channel];
      char outputArr[64];
      int i = 0;

      while (true) {

        digitalWrite(slaveselect, LOW);
        SPI.transfer(READ);
        SPI.transfer(0);
        SPI.transfer(i);
        outputArr[i] = SPI.transfer(0x00);
        digitalWrite(slaveselect, HIGH);
        delay(5);

        if (outputArr[i] == 0x00 || i >= 64) {

          outputArr[i] = '\0';
          return String(outputArr);

                }

        else
          i++;

      }

    }

    void overWriteEEPROM(int channel) {

      char zeroArr[64];
      for (int i = 0; i < 256; i++) {

        zeroArr[i] = 0;

      }

      writeToChannel(channel, String(zeroArr))

    }

Don't know if this is the issue, but the else part of your if statement in the loop is missing opening and closing curly brackets....

@AnnonomusPenguin : No, but thanks for noticing. It's just a minor bug that causes Serial.println(channel); to run regardless of if/else.

"but I only get weird answers". That's kind of vague, could you give us some sample outputs?

@Gerben : I tested some more, and I think I found out what the "weird answers" were: I filled the first 8 adressfields of my EEPROM (using working demo code) with int values ranging from 59 and upwards, and when I tried reading the values later they printed out in ASCII. I.E., "59" became ";".

@DoTheGenes great work. So it's solved then!

@Gerben : Sort of. I've solved the mystery of what the weird answers was, but the readFromChannel() will not stop when the string i wrote to the EEPROM is read out, it just continues to read through all addresses.
Basically, the only reason it stops is because I put the i >= 64-condition in the if-statement. The null-terminator will not work as intended.

That's weird. Try adding Serial.print(outputArr[i], BIN) to see the individual bits being read. Check if there is indeed a 0x00 present.


text:
How can I connect 2 Arduinos using ESP8266 transiver: ESP01
I have: 2 arduinos UNO, 2 ESP01 transivers. But if that's not enough, I'm ready to buy something else
I need to use one of Arduinos as a wifi hot spot, and the second as a modem. They should just be connected to each other :)
P.S. This is for my school project! Subsequently, I will put some obstacles between the Arduinos to see how much the signal strength degrades.

what research have you done for your school project?

Have you googled for how to use these with an Uno? Have you searched for libraries, that make it easier? Have you tried writing a program for the Uno? Have you searched for tutorials on how to setup an access point and how to connect to an access point?

Thank you very much for corrective questions. I'm from Russia, so I wanted to find content that could help me in the most accessible way - in Russian. But, on the Russian-speaking Internet, there are very small amount of people who are really interested in this topic. Most of the tutorials rested on controlling the Arduino with a phone via wifi, but this is not exactly what I needed :)

Here is the ESP8266 WiFi library:
https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi
In there You'll find an example for a WiFi access point:
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino
And an example for WiFi client:
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino
That should provide enough information for you to build your project.
To get the signal strength without connecting, you can use WiFiScan:
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino

Thanks a lot a lot a lot!!! Do you have any information about how to correctly connect modules with arduinos?

https://www.google.com/search?q=esp8266+arduino+wiring


text:
Can Arduino Sketch be used for production
There are lot of device support with the help of Boards Manager today and is on going in Arduino IDE.
So I am curious to know about can one use those for production purpose. Or it is recommended for quick prototyping purposes only...

Are you asking about using an Arduino board in production or its board description? If the board, what is your concern about production vs. prototyping (I'm assuming you've already done a cost comparison of Arduino boards vs. custom board for your anticipated production quantity)?

Are you thinking about copyright of the IDE or the Arduino libraries? Please read the statements on that issue.

That greatly depends on the requirements, that you have for the production environment

My plan is not to use Arduino Board into production. I will explain by an e.g suppose I did a prototype on Arduino UNO it uses ATmega328p and it worked as per expectations. So I want to push them into production. But instead of using whole Arduino UNO what I do is I will flash ATmega328p with Arduino Bootloader and by using AVRDude I will flash the .hex file. And I will place into my design. Will it work. Are there any copyright issues?

Are you using libraries? If yes, then search for an issue on Github or create one if you're allowed to use them.

Related: Using Arduino for Industrial process

Also related: LGPL and Arduino in Commercial Products

Industrial applications tend to steer more towards ladder logic vs C programming. The Do More PLC is an open source PLC that has some characteristics of an Arduino. Look at automation direct to see line up. However, you need to ask who is going to maintenance your project when you are gone? That is the big reason why companies love Allen Bradley and Seimens controllers.

There's a lot of controversy on this issue, but if it works for your needs, absolutely do it!
Basically, there are 2 questions you have to answer:

Should I use actual Arduino boards in production?
The answer is generally "no", simply because you need to customize the boards to add components to support your project, and to make them more robust, and cheaper, if possible. So, use an Arduino schematic as a guideline, then modify it to suit your needs.
One big exception to this, however, could be if you create a "mother board" onto which you will plug in a "daughter board" such as an Arduino Nano, Pro Mini, Pro Micro, or similar. You could make the Nano removable by soldering male headers onto it, and female headers onto the main "mother board", then you just plug in the Nano into the headers on the main board. Or, you could make it permanent by soldering male headers onto the Nano and then also solder that straight onto the "mother board" directly into the holes where female headers would otherwise be soldered. Both of these are great options, and this vastly simplifies your design and assembly process as you learn to get started manufacturing. Legal Arduino Nano clones are ~$1~$4 each, with shipping, on Ebay, and Pro Minis (not as good--here I recommend the Nano) are about the same, so buying a pre-made Nano is generally cheaper than buying just the raw chips on the Nano anyway, oddly enough. And again, this vastly simplifies your design and makes designing and assembling boards and products much much easier for the beginner/entry-level manufacturer (you) or micro business. It also allows you to make hand-made boards using perf-boards or proto (prototyping) boards, as I show in my other answer here.
For designing your own board, I recommend KiCad, which is Free and Open Source, and no cost ("free" == "free to modify"; "free" != "no cost"!), and actively developed by a volunteer team of about 6 people on a daily basis (I'm on their mailing lists and see this daily). It is a great product and is highly-capable. It is used by hobbyists and professionals alike, and has been used on many professional products world-wide. CERN, Arduino, and DigiKey have all contributed to KiCad in one way or another. See the lists of sponsors under the "Sponsors" tab at the top of the KiCad website, here:

Corporate Sponsorship
In Kind Sponsors
Historical Sponsors

The CERN Open Hardware Repository states here:

We think that KiCad can do to PCB design what the gcc compiler did to
software: ensure there are no artificial barriers to sharing so that design and
development knowledge can flow more freely.

That's an incredibly exciting mission!
There is also Autodesk Eagle, which is also popular among hobbyists and small businesses. It is a paid product, but has a no cost version for hobbyist, non-commercial use. It is also actively developed, by a tiny team of paid software developers on a pier in San Francisco. I've been to their office, and they are very excited about their work on it. They are doing a great job at making it a more-professional product. They've made some great improvements to Eagle over the last few years, hence why its price has gone up. It is also a great product.
Both products work on Windows, Mac, and Linux.
The Arduino board schematics are open-source hardware, so follow the licenses and provide attribution to where your design stemmed from. Ex: here's the Uno schematic. It shows the CC BY SA license logo at the bottom. I don't see a license version, but if it's 1.0, here's that license in plain terms. So, if you copy parts of the original schematics, release your design under the same license, and give credit to the original design.
You can NOT, however, use the Arduino logo or name. Those are trademarked and copyrighted, respectively. Arduino clones which do NOT use the Arduino name or logo are legal, and any clones which DO use the Arduino name or logo are illegal. There's no excuse for making an illegal Arduino clone. The schematics are intentionally open-source.
See also: Since Arduino uses Creative Commons licenses, do I also need to do that on my product?

Deriving the design of a commercial product from the Eagle files for an Arduino board requires you to release the modified files under the same Creative Commons Attribution Share-Alike license. You may manufacture and sell the resulting product.

And: Can I design my own Arduino board and sell it?

Since the hardware designs of Arduino are open source it is allowed to copy and further develop them. However this is not the same thing as making an Arduino board, only the company Arduino can design and produce Arduino products.
Your finished product is a product compatible with Arduino which should have its own name and brand. In case a copy uses the Arduino name and/or logo on it, this board is no longer a copy but a counterfeit which is illegal to manufacture and produce.

Should I use the Arduino software (build system and core libraries, and my program / "sketch") in production?
The answer is generally, "yes". This may be using the IDE for building or using the Arduino CLI command-line build interface.
The Arduino core and build system works great and has tons of internal and 3rd-party library support. The Arduino IDE itself is released under the GPL license (see below), and the core libraries are LGPL-licensed, which means if you modify them for your project, and put your project result into someone else's hands, you MUST release your modifications you made to the core code and libraries to those who have your project in their hands. See the main license file here:

this file includes licensing information for parts of arduino.
first, the gnu general public license, which covers the main body
of the processing/arduino code (in general, all the stuff inside the 'app'
and 'core' subfolders).
next, the gnu lesser general public license that covers the arduino core
and libraries.

But, you can keep your programs/"sketches" and main bits of project closed-source if you wish. Your programs are your own. They are copyrighted solely by you and you can license, use, and/or sell them however you wish. This includes the right to sell your Arduino/C and C++ programs as software or as firmware within a commercial product.
As a matter of fact, the GPL and LGPL licenses on the Arduino IDE and source code even allow you to sell the Arduino IDE and source code itself if you wish! This is really important, and is a fundamental right that "free and open source" software grants you. The Free Software Foundation, which is the owner of the copyrights on the license text itself, and the author of the GNU GPL and LGPL and other free and open source licenses, has this official guidance about selling and even reselling free software (they strongly encourage it!) (italics added):

Selling Free Software
Some views on the ideas of selling exceptions to free software licenses, such as the GNU GPL are also available.
Many people believe that the spirit of the GNU Project is that you should not charge money for distributing copies of software, or that you should charge as little as possible—just enough to cover the cost. This is a misunderstanding.
Actually, we encourage people who redistribute free software to charge as much as they wish or can. If a license does not permit users to make copies and sell them, it is a nonfree license. If this seems surprising to you, please read on.
The word “free” has two legitimate general meanings; it can refer either to freedom or to price. When we speak of “free software”, we're talking about freedom, not price. (Think of “free speech”, not “free beer”.) Specifically, it means that a user is free to run the program, study and change the program, and redistribute the program with or without changes.
Free programs are sometimes distributed gratis, and sometimes for a substantial price. Often the same program is available in both ways from different places. The program is free regardless of the price, because users have freedom in using it.
Nonfree programs are usually sold for a high price, but sometimes a store will give you a copy at no charge. That doesn't make it free software, though. Price or no price, the program is nonfree because its users are denied freedom.
Since free software is not a matter of price, a low price doesn't make the software free, or even closer to free. So if you are redistributing copies of free software, you might as well charge a substantial fee and make some money. Redistributing free software is a good and legitimate activity; if you do it, you might as well make a profit from it.
Free software is a community project, and everyone who depends on it ought to look for ways to contribute to building the community. For a distributor, the way to do this is to give a part of the profit to free software development projects or to the Free Software Foundation. This way you can advance the world of free software.
Distributing free software is an opportunity to raise funds for development. Don't waste it!
In order to contribute funds, you need to have some extra. If you charge too low a fee, you won't have anything to spare to support development.

This is only the first portion of their stance on the topic. Read the rest of the Free Software Foundation's encouragement to sell free software here.

That's the gist of it.
I am not a lawyer, and even if I was, none of my words herein are official legal advice.
When words come from the Free Software Foundation, who authors the GPL and LGPL licenses, however, those words are automatically extra legitimate.
Related:

Using Arduino for Industrial process
LGPL and Arduino in Commercial Products

There is two cases. First you use arduino boards. I would avoid this because it will be more expensive and harder to assemble the product. There is one exception, the new arduino nano family. These boards are made to be easily use in production (they can be soldered as a SMD components) but it's always expensive.
The second case is to use arduino software on custom microcontroller setup. It cheaper and easier tu put in production. The limitations are the choice of microcontroller (mostly Atmel) and speed and memory usage of microcontroller. As you use an extra layer of software (the Arduino bootloader) there is a risk of bug.
To conclude : it's possible but as most of the people that put projects in production know how to use microcontrollers without Arduino hardware or software and there is limitations to Arduino software there is not a lot of case of uses and it's not reccomended.

Note that if you use a bare microcontroller, you probably won't use the bootloader, as you can burn the firmware through ISP instead.

The "Arduino software" is fine. Some of it is written to help beginners. But you can write production quality code in it as well. Much the same as a pencil and paper. You can write rubbish, or something really good.