# Question
Title: 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 */

```

# Answer
> 1 votes
.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);
  }
}

```

---
Tags: avrdude, compilation-errors, build, avr-toolchain
---


# Question
Title: Turn off the second builtin Nodemcu 0.9 led
I'm making a low energy consumption device so I'd like to turn off all the led when I'm idle.

Unfortunately the nodemcu turn on a blue led while I'm idle (during `delay(ms)`)

Here is my code:

```
#define LED    16

void setup() {
  initialSetup();
  //Turn off the built-in led
  digitalWrite(LED, HIGH);
}

void loop() {
  //Here I do everything
  doStuff();
  //GO TO SLEEP
  delay(3600000);
}

```

The led that turn on during delay is the one near to D0 pin.

The led that I can control and so turn off (pin #16 -\> D0) is near the 5v pin.

It's possible to completely turn off all led to consume less?

# Answer
See this link which shows your second LED exactly (the image is for v1.0, I have v0.9 and the code below works just the same in this situation):

'Onboard LEDs? NodeMCU's got two!':

https://lowvoltage.github.io/2017/07/09/Onboard-LEDs-NodeMCU-Got-Two

Quote:

> ESP-12 LED Blink:
>
> ```
>  void setup() {
>         pinMode(2, OUTPUT);     //Initialize GPIO2 pin as an output
>  }
>
>  void loop() {
>    digitalWrite(2, LOW);   // Turn the LED on by making the voltage LOW
>    delay(1000);            // Wait for a second
>    digitalWrite(2, HIGH);  // Turn the LED off by making the voltage HIGH
>    delay(2000);            // Wait for two seconds
>  }
>
> ```

Or write it like this (ie. using 'D4' rather than '2'):

> ESP-12 LED Blink:
>
> ```
>  void setup() {
>         pinMode(**D4**, OUTPUT);     //Initialize GPIO2 pin as an output
>  }
>
>  void loop() {
>    digitalWrite(**D4**, LOW);   // Turn the LED on by making the voltage LOW
>    delay(1000);            // Wait for a second
>    digitalWrite(**D4**, HIGH);  // Turn the LED off by making the voltage HIGH
>    delay(2000);            // Wait for two seconds
>  }
>
> ```

Regards, Geoff
> 3 votes

---
Tags: led, nodemcu
---


title: ATmega328 is not recognized by software

text:
# Question
Title: ATmega328 is not recognized by software
I installed the required drivers for the board. But I cannot still upload a program to the board. It says that

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch

```
     System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : usb
     Using Programmer              : stk500v2

```

avrdude: usbdev\_open(): did not find any USB device "usb" (0x03eb:0x2104)

avrdude done. Thank you.

An error occurred while uploading the sketch

# Answer
Can be many causes since you did not provide more info (like what circuit, what application). But in general:

* Wrong software installation
* Try another similar chip/device, maybe this one is broken
* Is it recognized by USB at all?
* Bad USB cable
* Did you select the right board in the IDE (Arduino IDE?)

Possible solution:

* Reinstall IDE
* Change chip
* Change Arduino
* Use different cable
> 1 votes

---
Tags: atmega328
---


title: Use Mac for memory & processing

text:
# Question
Title: Use Mac for memory & processing
I understand that each model of Arduino has limited cpu, ram, etc.

However, I have this very powerful Mac that it’s hooked up to.

Am i able to use my Mac for expensive computation and just pass results to my arduino in real-time?

Basically arduino takes in sensor data - passes it to Mac. Mac computes and returns an output to arduino.

# Answer
This blog describes the author's open-source, cross-platform library in C to talk to an Arduino via serial. The library is available on GitHub. A C project on your Mac can use it to communicate with your Arduino. You'll probably want to create a simple command protocol to keep the two in sync, as serial is pretty "barefoot" by itself, being just a stream of bytes with no markers, packets, or check-sums unless you impose such structures on your data, yourself. It probably doesn't need to be very complex, depending what your application needs.

I have found similar projects in Python and in Java for the Mac/Windows/Linux/\<whatever\> side; there's plenty of work already done for you.
> 1 votes

---
Tags: memory
---


# Question
Title: Ribbon sensor resistance slowly drops when released
I recently bought a ribbon sensor (the one displayed here), with the intention to use it as a touch-enabled music instrument.

I used it correctly (so it seems), but I have two issues :

* When not pressed, the sensor seems to give random data, as if nothing was plugged to the pin.
* When unpressed, the resistance slowly decreases (and so is my sound pitch). Is that a normal behaviour ?

I don't know how to solve both issues. Has anyone an idea ?

A tinker of my test (Currently corrected thanks to @VE7JRO) can be seen here with my code here (The ribbon is replaced by a potentiometer but the principle remains the same). The code is also Available on GitHub.

# Answer
> 3 votes
The Adafruit website says this:

There is a nominal 10K resistance across the two outer leads. The middle pin resistance with respect to either of the outer pins changes depending on where on the strip one presses. When no pressure is applied, the middle pin floats, so be sure to use some sort of weak pullup, such as 100K ohm.

To use Connect one side pin to ground via a 10K resistor in series. Connect the other side pin to your Vcc power line (3V, 5V etc) via a different 10K resistor in series. Then read the analog voltage on the center pin. It will range from 1/3 Vcc to 2/3 Vcc . Do not connect to Ground and Power directly!

Here is a diagram of how I would connect it to a 5V Arduino Uno.

---
Tags: potentiometer
---


# Question
Title: ESP8266 in AP Mode -determining if a station is connected
I have an ESP8266 running in AP mode using softAP and i want to conserve battery life. I am wanting to turn on wifi and advertise SSID for 20 seconds. If no station connects to the ssid within the 20 seconds, I want to go to sleep for 1 minute, otherwise I do not sleep.

My problem is that I cannot get "WiFi.softAPgetStationNum()" working. when I build i get a message that this is not part of ESP8266WiFi class. I have attached simplified code.

Can someone help me to achieve this please?

```
#include <ESP8266WiFi.h>

//WIFI Access point setup
const char* Ssid = "SSID";
const char* Password = "Password";
IPAddress ip(10,0,0,10);
IPAddress gateway(10,0,0,1);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);                    // Set web server port number to
80

// GPIO pins
const int output_set = 5;
int delay_loop=0;

void setup()
{
  // Data Direction
  pinMode(output_set, OUTPUT);

  // Output initial Values
  digitalWrite(output_set, LOW);

  WiFi.softAPConfig(ip,gateway,subnet);
  WiFi.softAP(Ssid,Password);
  server.begin();

// check to see if a station is connected to this AP. If no station
connected within 20 sec timeframe, go to sleep.

while (WiFi.softAPgetStationNum()==0)              //loop here while no AP is connected to this station
{
    delay(1);
    delay_loop++;
    if (delay_loop>=20000)
    {

        ESP.deepSleep(60e6);                          //go to sleep for 60 sec -wake pin externally connected to reset pin
    }
}
}

void loop()
{
   digitalWrite(output_set, HIGH);      //Flash led once station is connected
   delay(200);
   digitalWrite(output_set, LOW);
   delay(400);
}

```

# Answer
Followup answer from comments:

The issue was an outdated version of the ESP8266-Arduino framework. The function `WiFi.softAPgetStationNum()` is available in 2.4.1

For the sake of completeness: The function itself is simply a wrapper for the Espressif non-os SDK function:

```
/**
 * Get the count of the Station / client that are connected to the softAP interface
 * @return Stations count
 */
uint8_t ESP8266WiFiAPClass::softAPgetStationNum() {
    return wifi_softap_get_station_num();
}

```

See Espressif Non-OS SDK API reference chapter 3.5.36.

That function should also be available on older framework versions. However, upgrading is the recommended way to use that function.
> 2 votes

---
Tags: esp8266, wifi, sleep
---


title: Wearable GPS LED help

text:
# Question
Title: Wearable GPS LED help
I'm very new to Arduino and C++ and have been playing with the Flora Wearable GPS. However, nowhere I've looked has given me any help in setting and changing the color of the LEDs. The tutorial on their site is barebones and doesn't explain how to modify code and make the colors change. I've tried mixing what I know, but none of it results in what I want: one color to show when I'm in range of a a point, and another to show when I'm not.

```
// Flora GPS + LED Pixel Code
//
// This code shows how to listen to the GPS module in an interrupt
// which allows the program to have more 'freedom' - just parse
// when a new NMEA sentence is available! Then access data when
// desired.
//
// Tested and works great with the Adafruit Flora GPS module
//    ------> http://adafruit.com/products/1059
// Pick one up today at the Adafruit electronics shop
// and help support open source hardware & software! -ada

#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
#include "Adafruit_NeoPixel.h"
Adafruit_GPS GPS(&Serial1);

// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences
#define GPSECHO false

#define PIN 6

// this keeps track of whether we're using the interrupt
// off by default!
boolean usingInterrupt = false;

//--------------------------------------------------|
//                    WAYPOINTS                     |
//--------------------------------------------------|
//Please enter the latitude and longitude of your   |
//desired destination:                              |
  #define GEO_LAT                44.995012
  #define GEO_LON               -93.228967
//--------------------------------------------------|

//--------------------------------------------------|
//                    DISTANCE                      |
//--------------------------------------------------|
//Please enter the distance (in meters) from your   |
//destination that you want your LEDs to light up:  |
  #define DESTINATION_DISTANCE   20
//--------------------------------------------------|

// Navigation location
float targetLat = GEO_LAT;
float targetLon = GEO_LON;

// Trip distance
float tripDistance;

boolean isStarted = false;

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800);

uint8_t LED_Breathe_Table[]  = {   80,  87,  95, 103, 112, 121, 131, 141, 151, 161, 172, 182, 192, 202, 211, 220,
              228, 236, 242, 247, 251, 254, 255, 255, 254, 251, 247, 242, 236, 228, 220, 211,
              202, 192, 182, 172, 161, 151, 141, 131, 121, 112, 103,  95,  87,  80,  73,  66,
               60,  55,  50,  45,  41,  38,  34,  31,  28,  26,  24,  22,  20,  20,  20,  20,
               20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,
               20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  22,  24,  26,  28,
               31,  34,  38,  41,  45,  50,  55,  60,  66,  73 };

#define BREATHE_TABLE_SIZE (sizeof(LED_Breathe_Table))
#define BREATHE_CYCLE    5000      /*breathe cycle in milliseconds*/
#define BREATHE_UPDATE    (BREATHE_CYCLE / BREATHE_TABLE_SIZE)
uint32_t lastBreatheUpdate = 0;
uint8_t breatheIndex = 0;

void setup()
{
  // connect at 115200 so we can read the GPS fast enough and echo without dropping chars
  // also spit it out
  Serial.begin(115200);

  // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
  GPS.begin(9600);

  // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  // uncomment this line to turn on only the "minimum recommended" data
  //GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
  // For parsing data, we don't suggest using anything but either RMC only or RMC+GGA since
  // the parser doesn't care about other sentences at this time

  // Set the update rate
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate
  // For the parsing code to work nicely and have time to sort thru the data, and
  // print it out we don't suggest using anything higher than 1 Hz

  delay(1000);
  // Ask for firmware version
  Serial1.println(PMTK_Q_RELEASE);

    // Start up the LED strip
  strip.begin();

  // Update the strip, to start they are all 'off'
  strip.show();
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
  // read data from the GPS in the 'main loop'
  char c = GPS.read();
  // if you want to debug, this is a good time to do it!
  if (GPSECHO)
      if (c) Serial.print(c);

  // if a sentence is received, we can check the checksum, parse it...
  if (GPS.newNMEAreceived()) {
    // a tricky thing here is if we print the NMEA sentence, or data
    // we end up not listening and catching other sentences!
    // so be very wary if using OUTPUT_ALLDATA and trytng to print out data
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false

    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
  }

    if (GPS.fix) {
      //Serial.print("Location: ");
      //Serial.print(GPS.latitude, 2); Serial.print(GPS.lat);
      //Serial.print(", ");
      //Serial.print(GPS.longitude, 2); Serial.println(GPS.lon);

      float fLat = decimalDegrees(GPS.latitude, GPS.lat);
      float fLon = decimalDegrees(GPS.longitude, GPS.lon);

      if (!isStarted) {
        isStarted = true;
        tripDistance = (double)calc_dist(fLat, fLon, targetLat, targetLon);
      }

      //Uncomment below if you want your Flora to navigate to a certain destination.  Then modify the headingDirection function.
      /*if ((calc_bearing(fLat, fLon, targetLat, targetLon) - GPS.angle) > 0) {
        headingDirection(calc_bearing(fLat, fLon, targetLat, targetLon)-GPS.angle);
       }
      else {
        headingDirection(calc_bearing(fLat, fLon, targetLat, targetLon)-GPS.angle+360);
      }*/

      headingDistance((double)calc_dist(fLat, fLon, targetLat, targetLon));
      //Serial.print("Distance Remaining:"); Serial.println((double)calc_dist(fLat, fLon, targetLat, targetLon));

    }
  //}

}

int calc_bearing(float flat1, float flon1, float flat2, float flon2)
{
  float calc;
  float bear_calc;

  float x = 69.1 * (flat2 - flat1);
  float y = 69.1 * (flon2 - flon1) * cos(flat1/57.3);

  calc=atan2(y,x);

  bear_calc= degrees(calc);

  if(bear_calc<=1){
    bear_calc=360+bear_calc;
  }
  return bear_calc;
}

void headingDirection(float heading)
{
  //Use this part of the code to determine which way you need to go.
  //Remember: this is not the direction you are heading, it is the direction to the destination (north = forward).
  if ((heading > 348.75)||(heading < 11.25)) {
    Serial.println("  N");
    //Serial.println("Forward");
  }

  if ((heading >= 11.25)&&(heading < 33.75)) {
    Serial.println("NNE");
    //Serial.println("Go Right");
  }

  if ((heading >= 33.75)&&(heading < 56.25)) {
    Serial.println(" NE");
    //Serial.println("Go Right");
  }

  if ((heading >= 56.25)&&(heading < 78.75)) {
    Serial.println("ENE");
    //Serial.println("Go Right");
  }

  if ((heading >= 78.75)&&(heading < 101.25)) {
    Serial.println("  E");
    //Serial.println("Go Right");
  }

  if ((heading >= 101.25)&&(heading < 123.75)) {
    Serial.println("ESE");
    //Serial.println("Go Right");
  }

  if ((heading >= 123.75)&&(heading < 146.25)) {
    Serial.println(" SE");
    //Serial.println("Go Right");
  }

  if ((heading >= 146.25)&&(heading < 168.75)) {
    Serial.println("SSE");
    //Serial.println("Go Right");
  }

  if ((heading >= 168.75)&&(heading < 191.25)) {
    Serial.println("  S");
    //Serial.println("Turn Around");
  }

  if ((heading >= 191.25)&&(heading < 213.75)) {
    Serial.println("SSW");
    //Serial.println("Go Left");
  }

  if ((heading >= 213.75)&&(heading < 236.25)) {
    Serial.println(" SW");
    //Serial.println("Go Left");
  }

  if ((heading >= 236.25)&&(heading < 258.75)) {
    Serial.println("WSW");
    //Serial.println("Go Left");
  }

  if ((heading >= 258.75)&&(heading < 281.25)) {
    Serial.println("  W");
    //Serial.println("Go Left");
  }

  if ((heading >= 281.25)&&(heading < 303.75)) {
    Serial.println("WNW");
    //Serial.println("Go Left");
  }

  if ((heading >= 303.75)&&(heading < 326.25)) {
    Serial.println(" NW");
    //Serial.println("Go Left");
  }

  if ((heading >= 326.25)&&(heading < 348.75)) {
    Serial.println("NWN");
    //Serial.println("Go Left");
  }
}

void headingDistance(float fDist)
{
  //Use this part of the code to determine how far you are away from the destination.
  //The total trip distance (from where you started) is divided into five trip segments.
 Serial.println(fDist);
 if ((fDist >= DESTINATION_DISTANCE)) { // You are now within 5 meters of your destination.
    //Serial.println("Trip Distance: 1");
    //Serial.println("Arrived at destination!");
    int i;
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0, 0, 0);
    }
    strip.show();   // write all the pixels out
  }

  if ((fDist < DESTINATION_DISTANCE)) { // You are now within 5 meters of your destination.
    //Serial.println("Trip Distance: 0");
    //Serial.println("Arrived at destination!");
    breath();
  }

}

unsigned long calc_dist(float flat1, float flon1, float flat2, float flon2)
{
  float dist_calc=0;
  float dist_calc2=0;
  float diflat=0;
  float diflon=0;

  diflat=radians(flat2-flat1);
  flat1=radians(flat1);
  flat2=radians(flat2);
  diflon=radians((flon2)-(flon1));

  dist_calc = (sin(diflat/2.0)*sin(diflat/2.0));
  dist_calc2= cos(flat1);
  dist_calc2*=cos(flat2);
  dist_calc2*=sin(diflon/2.0);
  dist_calc2*=sin(diflon/2.0);
  dist_calc +=dist_calc2;

  dist_calc=(2*atan2(sqrt(dist_calc),sqrt(1.0-dist_calc)));

  dist_calc*=6371000.0; //Converting to meters
  return dist_calc;
}

// Convert NMEA coordinate to decimal degrees
float decimalDegrees(float nmeaCoord, char dir) {
  uint16_t wholeDegrees = 0.01*nmeaCoord;
  int modifier = 1;

  if (dir == 'W' || dir == 'S') {
    modifier = -1;
  }

  return (wholeDegrees + (nmeaCoord - 100.0*wholeDegrees)/60.0) * modifier;
}

void breath()
{
  uniformBreathe(LED_Breathe_Table, BREATHE_TABLE_SIZE, BREATHE_UPDATE, 127, 127, 127);
}

void uniformBreathe(uint8_t* breatheTable, uint8_t breatheTableSize, uint16_t updatePeriod, uint16_t r, uint16_t g, uint16_t b)
{
  int i;

  uint8_t breatheBlu;

  if ((millis() - lastBreatheUpdate) > updatePeriod) {
    lastBreatheUpdate = millis();

    for (i=0; i < strip.numPixels(); i++) {
      breatheBlu = (b * breatheTable[breatheIndex]) / 256;
      strip.setPixelColor(i, 0, 0, breatheBlu);
    }
    strip.show();

    breatheIndex++;
    if (breatheIndex > breatheTableSize) {
      breatheIndex = 0;
    }
  }
}

```

What gets me the most is this part

```
void headingDistance(float fDist)
{
  //Use this part of the code to determine how far you are away from the destination.
  //The total trip distance (from where you started) is divided into five trip segments.
 Serial.println(fDist);
 if ((fDist >= DESTINATION_DISTANCE)) { // You are now within 5 meters of your destination.
    //Serial.println("Trip Distance: 1");
    //Serial.println("Arrived at destination!");
    int i;
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0, 0, 0);
    }
    strip.show();   // write all the pixels out
  }

  if ((fDist < DESTINATION_DISTANCE)) { // You are now within 5 meters of your destination.
    //Serial.println("Trip Distance: 0");
    //Serial.println("Arrived at destination!");
    breath();
  }

}

```

Since the comments say both are for within 5 meters but have opposite conditions and "fDist" isn't defined anywhere that I can see, I don't know which is for near or far or how to set a color to either one. I tried setting colors for the first if statement and they seemed to work, but I couldn't get it to work consistently for some reason.

# Answer
I think others have addressed the need for you to modify the strip colors based on distance or bearing or... whatever you want to show.

Here's a NeoGPS version of that sketch. I think it may be easier to understand what's going on, and where you need to focus:

```
// Flora GPS + LED Pixel Code
//   Modified to use NeoGPS library.
//
// Adafruit Flora GPS module
//    ------> http://adafruit.com/products/1059
// Pick one up today at the Adafruit electronics shop
// and help support open source hardware & software! -ada

#include "Adafruit_NeoPixel.h"
#include <NMEAGPS.h>

NMEAGPS gps;
gps_fix fix;
#define gpsPort Serial1

const int NEOPIXEL_PIN = 6;

//----------------------------------------------------|
//                     WAYPOINTS                      |
//----------------------------------------------------|
// Please enter the latitude and longitude of your    |
// desired destination:                               |
NeoGPS::Location_t destination( 449950120L, -932289670L );
//  To be more accurate, these are degrees * 10000000 |
//----------------------------------------------------|

//--------------------------------------------------|
//                    DISTANCE                      |
//--------------------------------------------------|
//Please enter the distance (in meters) from your   |
//destination that you want your LEDs to light up:  |
const float DESTINATION_DISTANCE = 20.0;

//--------------------------------------------------|
// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel( 8, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800 );

uint8_t LED_Breathe_Table[]  =
  {
     80,  87,  95, 103, 112, 121, 131, 141, 151, 161, 172, 182, 192, 202, 211, 220,
    228, 236, 242, 247, 251, 254, 255, 255, 254, 251, 247, 242, 236, 228, 220, 211,
    202, 192, 182, 172, 161, 151, 141, 131, 121, 112, 103,  95,  87,  80,  73,  66,
     60,  55,  50,  45,  41,  38,  34,  31,  28,  26,  24,  22,  20,  20,  20,  20,
     20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,
     20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  22,  24,  26,  28,
     31,  34,  38,  41,  45,  50,  55,  60,  66,  73
  };

#define BREATHE_TABLE_SIZE (sizeof(LED_Breathe_Table))
#define BREATHE_CYCLE      5000      /*breathe cycle in milliseconds*/
#define BREATHE_UPDATE     (BREATHE_CYCLE / BREATHE_TABLE_SIZE)
uint32_t lastBreatheUpdate = 0;
size_t   breatheIndex      = 0;

void setup()
{
  Serial.begin(115200);
  gpsPort.begin(9600);  // default baud rate for Adafruit MTK GPS's - some use 4800

  gps.send_P( &gpsPort, F("PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") ); // RMC+GGA
  delay(100);
  gps.send_P( &gpsPort, F("PMTK220,1000") ); // 1Hz
  delay(100);
  gps.send_P( &gpsPort, F("PGCMD,33,0") ); // No antenna status

  strip.begin();
  strip.show();  // Update the strip, to start they are all 'off'
}

void loop()
{
  if (gps.available( gpsPort ) ) {
    fix = gps.read();

    const bool spoof = false; // change to true for spoofing
    if (spoof) {
      float t           = fix.dateTime.seconds / 4.0;  // 15 second cycle (60 / 4)
      float offsetAngle = (TWO_PI / 20.0) * t;         // 20 steps around circle
      float offsetDist  = 0.005 * t / NeoGPS::Location_t::EARTH_RADIUS_KM;
                           // 5m per second, 75m away or less. In RADIANS!
      fix.location = destination; // start here and step away
      fix.location.OffsetBy( offsetDist, offsetAngle );
    }

    //Serial.print( F("Location: ") );
    //Serial.print( fix.latitude(), 5 );
    //Serial.print( F(", ") );
    //Serial.print( fix.longitude(), 5 );

    if (fix.valid.location) {
      float distance = fix.location.DistanceKm( destination ) * 1000.0; // meters

      // Set below to true if you want your Flora to navigate to a
      //  certain destination.  Then modify the showDirection function.
      const bool showNavigationHints = true;

      if (showNavigationHints) {

        float bearing = fix.location.BearingToDegrees( destination );

        //  If we're moving fast enough, show the user which way to go, left or right.
        if (fix.valid.heading and (fix.valid.speed and fix.speed_kph() > 3.0)) {

          float courseCorrection = bearing - fix.heading();
          if (courseCorrection < 0.0)
            courseCorrection += 360.0;

          showDirection( courseCorrection );

        } else {
          // We're not moving very fast, show a compass direction.
          showDirection( bearing );
        }
      }

      showDistance( distance );
    }
  }
}

void showDirection( float bearing )
{
  //  Use this to show which way you need to go.
  //    Some times, it's an absolute compass direction.
  //    Other times, it's a course correction (left or right from current heading)

  const __FlashStringHelper *dir = compassDir( bearing );
  size_t dirLen = strlen_P( (const char *) dir );
  for (uint8_t i = 0; i < (3 - dirLen); i++)
    Serial.print( ' ' );
  Serial.println( dir );
}

void showDistance(float distance)
{
  Serial.println( distance );

  // Are we close enough?
  if (distance >= DESTINATION_DISTANCE) {
    // No.

    const uint8_t level = 0; // you might set this based on distance

    for (int i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor( i, level, level, level );
    }
    strip.show();   // write all the pixels out

  } else {
    // Yes!
    // Serial.println("Arrived at destination!");
    breath();
  }

}

//------------------------------------------------------------
// This is copied from the NeoGPS NMEAaverage.ino example program

const char nCD  [] PROGMEM = "N";
const char nneCD[] PROGMEM = "NNE";
const char neCD [] PROGMEM = "NE";
const char eneCD[] PROGMEM = "ENE";
const char eCD  [] PROGMEM = "E";
const char eseCD[] PROGMEM = "ESE";
const char seCD [] PROGMEM = "SE";
const char sseCD[] PROGMEM = "SSE";
const char sCD  [] PROGMEM = "S";
const char sswCD[] PROGMEM = "SSW";
const char swCD [] PROGMEM = "SW";
const char wswCD[] PROGMEM = "WSW";
const char wCD  [] PROGMEM = "W";
const char wnwCD[] PROGMEM = "WNW";
const char nwCD [] PROGMEM = "NW";
const char nnwCD[] PROGMEM = "NNW";

const char * const dirStrings[] PROGMEM =
  { nCD, nneCD, neCD, eneCD, eCD, eseCD, seCD, sseCD,
    sCD, sswCD, swCD, wswCD, wCD, wnwCD, nwCD, nnwCD };

const __FlashStringHelper *compassDir( uint16_t bearing ) // degrees CW from N
{
  const int16_t directions    = sizeof(dirStrings)/sizeof(dirStrings[0]);
  const int16_t degreesPerDir = 360 / directions;
        int8_t  dir           = (bearing + degreesPerDir/2) / degreesPerDir;

  while (dir < 0)
    dir += directions;
  while (dir >= directions)
    dir -= directions;

  return (const __FlashStringHelper *) pgm_read_ptr( &dirStrings[ dir ] );

} // compassDir

//--------------------------

void uniformBreathe
  ( uint8_t *breatheTable, size_t breatheTableSize,
    uint16_t updatePeriod,
    uint16_t r, uint16_t g, uint16_t b )
{

  if ((millis() - lastBreatheUpdate) > updatePeriod) {
    lastBreatheUpdate = millis();

    for (int i=0; i < strip.numPixels(); i++) {
      uint8_t breatheBlu = (b * breatheTable[breatheIndex]) / 256;
      strip.setPixelColor( i, 0, 0, breatheBlu );
    }
    strip.show();

    breatheIndex++;
    if (breatheIndex > breatheTableSize) {
      breatheIndex = 0;
    }
  }
}

void breath()
{
  uniformBreathe(LED_Breathe_Table, BREATHE_TABLE_SIZE, BREATHE_UPDATE, 127, 127, 127);
}

```

I am always amazed by how much a little whitespace can improve the readability. Good variable and function names are also important. You are also being misled by bad comments. :P

I have added some location "spoofing" code that lets you test it without having to walk around. That spoofing section can be removed when you're done testing.

If you want to try it, NeoGPS is available from the Arduino Library Manager, under the menu **Sketch-\> Include Library-\> Manage Libraries**. BTW, this saves about **500 bytes** of RAM.

**To answer your original question**, the `showDistance` and `showDirection` functions should be modified to do whatever you want.
> 3 votes

# Answer
Three comments:

1. For someone who is new to Arduino and programming (or perhaps just new to C / C++), you have taken on a large challenge.
2. It should be widely said (but it is not) that not all Arduino libraries are compatible with one another. And that it is up to the user (or community) to identify conflicts. As there are far too many combinations for any one person to test them all.
3. You should ask only 1 question per post. I think you are most interested about programming different colors for a WS2812 LED. So we should not talk about GPS for now.

Most if not all Adafruit.com software source code are available free to the community at github.com. The Adafruit\_NeoPixel github repository at github should contain all the source code for this project as well as several files of example code. In the example code is this segment of code that changes the LED color:

```
  switch(i){
    case 0: colorWipe(strip.Color(0, 0, 0), 50);    // Black/off
            break;
    case 1: colorWipe(strip.Color(255, 0, 0), 50);  // Red
            break;
    case 2: colorWipe(strip.Color(0, 255, 0), 50);  // Green
            break;
    case 3: colorWipe(strip.Color(0, 0, 255), 50);  // Blue
            break;
...removed some code for clarity...
    }

```
> 1 votes

# Answer
It is not really clear what your actual problem is. I will go with the following:

1. **How to set the colors of the RGB LEDs:** You are already using the `Adafruit_NeoPixel` library. The definition of `Adafruit_Neopixel strip` shows, that you have a strip with 8 LEDs. In setup the sketch calls `strip.begin()` to initiate it. After that, everytime you want to change the color/state of any number of LEDs on the strip, you can set them one by one with `strip.setPixelColor()`, which takes the number of the LED and the color in RGB format as parameters. To make the LEDs show your changes you have to call `strip.show()`, which sends the data to the LEDs.
2. **What your sketch does:** In the function `headingDistance(float fDist)` the colors of the LEDs are set according to the previously calculated distance. `fDist` comes as parameter to this function, so it is declared in the function header. The value comes from the function `calc_dist()`. Now you have 2 if-statements:
    1. The first one (if you are farer away from your target) will set the color of all LEDs to black (turning them off) by calling `strip.setPixelColor(i, 0, 0, 0)` for every LED and then calling `strip.show()`. So this is easy.
    2. The second one (if you are within the 5m radius) calls the function `breath()`. It will set the intensity of the blue color component for all LEDs dependent on it's parameter `b` and the time that passed since it set the LEDs color the last time (this is done with the `millis()`-if-statement). The function `headingDistance()` is called in `loop()`, whenever the `fix` variable of the GPS is set. Calling the `breath()` function (which is called from `headingDistance()`) very often results in a timed update of the LEDs every `updatePeriod` milliseconds. Refer to the `BlinkWithoutDelay` example in the Arduino IDE for this working principle. It leaves you time to do other things during the wait periods, because it is non-blocking. The `breath()` function is a more complex thing, than simply turning on and of the LEDs with the right color. If you just want to do that, replace it's call in `headingDistance()` with your own code, setting the LEDs like I explained above.

So:

> one color to show when I'm in range of a a point, and another to show when I'm not.

Set the color values in RGB format in the first if-statement, to set for the case that your are not in the range of your GPS point. And replace the `breath()` function by a similar code with the color values in RGB format for the case, that you are within the range of your point.

If it still doesn't work, try if the original sketch works correctly. This would verify, that the measurement and calculation of the distance works as intended.
> 1 votes

---
Tags: gps, rgb-led
---


# Question
Title: Is there a way to send data from Tensorflow to Arduino via Bluetooth?
I am not sure if such a question is accepted here. If not please direct me to a more suitable Exchange.

I am planning a small project involving Machine Learning using TensorFlow and Python, which involves GAIT learning of a quadrupedal robotic system. The robotic system will be controlled by a simple Arduino. This will send data to the 8 servo motors located in the 4 legs of the robot. (2 on each leg) The robot is similar to this.

My question is if there a way to transfer data to and from Tensorflow via Bluetooth to the Arduino.

The Arduino will not be connected serially to my PC, so serial communication is not an option. Bluetooth and Wireless remain, of which, Bluetooth is generally easier.

I have done several projects involving HC-05 modules to transfer data from different systems to an Arduino so that part is not an issue. What I am interested in is if Tensorflow offers this kind of support, or if there is an easier way to do this. Searching online did not yield any results related to what I am after.

Any tips or suggestions would be appreciated.

# Answer
> 1 votes
The question is more "Is there a way to send data from Python ?" than "Is there a way to send them from Tensorflow to an Arduino ?" and the Answer is yes. In Tensorflow your can recover your result in a tensor (which you can easily transform in a Python array) and then send it with Python through whatever support you want to the Arduino.

---
Tags: arduino-uno, arduino-nano, bluetooth, python
---


# Question
Title: PCM audio, PROGMEM sounds through speaker, multiple clips (using speaker_pcm)
I downloaded the PCM Audio speaker\_pcm (see link below) and it worked easily with the supplied Mac startup chime. I also got my own sounds parsed properly via a combination of sox and wav2c incantations as described. However, when I tried to store and play two or more (very short e.g. 150ms, 8K) sound clips in sequence, I couldn't seem to get it to work. It only sounds like it is playing the last clip in order. I only modified the code (see below) from the original to address the multiple clips. My pointer dereferencing seems to be working (it plays the last clip in sequence), but it won't play a group of them. What am I doing wrong?

(You can download the 01.h 02.h 03.h files from my website, pete dot zelchenko dot com slash 2017 slash the file name. I can't post lots of links here. You can also create your own using the incantations about sox and wav2c in the documentation below, but it takes time. The three files are the words "one" "two" "three" and that's it.)

```
/*
 * (PCM Audio speaker_pcm downloaded from http://playground.arduino.cc/Code/PCMAudio)
 *
 * speaker_pcm
 *
 * Plays 8-bit PCM audio on pin 11 using pulse-width modulation (PWM).
 * For Arduino with Atmega168 at 16 MHz.
 *
 * Uses two timers. The first changes the sample value 8000 times a second.
 * The second holds pin 11 high for 0-255 ticks out of a 256-tick cycle,
 * depending on sample value. The second timer repeats 62500 times per second
 * (16000000 / 256), much faster than the playback rate (8000 Hz), so
 * it almost sounds halfway decent, just really quiet on a PC speaker.
 *
 * Takes over Timer 1 (16-bit) for the 8000 Hz timer. This breaks PWM
 * (analogWrite()) for Arduino pins 9 and 10. Takes Timer 2 (8-bit)
 * for the pulse width modulation, breaking PWM for pins 11 & 3.
 *
 * References:
 *     [links]
 *
 * Michael Smith <michael [at] hurts.ca>
 */

#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 8000

    /*
     * The audio data needs to be unsigned, 8-bit, 8000 Hz, and small enough
     * to fit in flash. 10000-13000 samples is about the limit.
     *
     * sounddata.h should look like this:
     *     const int sounddata_length=10000;
     *     const unsigned char sounddata_data[] PROGMEM = { ..... };
     *
     * You can use wav2c from GBA CSS (OR use EncodeAudio? http://highlowtech.org/?p=1963):
     *     http://thieumsweb.free.fr/english/gbacss.html
     * Then add "PROGMEM" in the right place. I hacked it up to dump the samples
     * as unsigned rather than signed, but it shouldn't matter.
     *
     * [link deleted]
     * mplayer -ao pcm macstartup.mp3
     * sox audiodump.wav -v 1.32 -c 1 -r 8000 -u -1 macstartup-8000.wav
     * sox macstartup-8000.wav macstartup-cut.wav trim 0 10000s
     * wav2c macstartup-cut.wav sounddata.h sounddata
     *
     * (starfox) nb. under sox 12.18 (distributed in CentOS 5), i needed to run
     * the following command to convert my wav file to the appropriate format:
     * sox audiodump.wav -c 1 -r 8000 -u -b macstartup-8000.wav
     */

    //#include "sounddata.h"
    #include "toolow.h"
    #include "toohigh.h"

    #include "01.h"
    #include "02.h"
    #include "03.h"

    int      ledPin   = 13;
    int      speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

    volatile uint16_t sample;
    byte lastSample;

    int sounddata_length;

    /*int sounddata_length;
    signed char *sounddata_data[10000]; */

    void stopPlayback()
    {
        // Disable playback per-sample interrupt.
        TIMSK1 &= ~_BV(OCIE1A);

        // Disable the per-sample timer completely.
        TCCR1B &= ~_BV(CS10);

        // Disable the PWM timer.
        TCCR2B &= ~_BV(CS10);

        digitalWrite(speakerPin, LOW);
    }

    unsigned int sounddata_addr;

    // This is called at 8000 Hz to load the next sample.
    ISR(TIMER1_COMPA_vect) {
        if (sample >= sounddata_length) {
            if (sample == sounddata_length + lastSample) {
                stopPlayback();
            }
            else {
                if(speakerPin==11){
                    // Ramp down to zero to reduce the click at the end of playback.
                    OCR2A = sounddata_length + lastSample - sample;
                } else {
                    OCR2B = sounddata_length + lastSample - sample;
                }
            }
        }
        else {
            if(speakerPin==11){
                OCR2A = pgm_read_byte(sounddata_addr + sample);
            } else {
                OCR2B = pgm_read_byte(sounddata_addr + sample);
            }
        }

        ++sample;
    }

    void startPlayback(int clip)
    {

    signed char *sounddata_data[10000];

        switch (clip) {
          case   1:  sounddata_data[0] = &s_01_data[0]; sounddata_length = s_01_length; break;
          case   2:  sounddata_data[0] = &s_02_data[0]; sounddata_length = s_02_length; break;
          case   3:  sounddata_data[0] = &s_03_data[0]; sounddata_length = s_03_length; break;

        }

    sounddata_addr = sounddata_data[0];

        pinMode(speakerPin, OUTPUT);

        // Set up Timer 2 to do pulse width modulation on the speaker
        // pin.

    *  // Use internal clock (datasheet p.160)
        ASSR &= ~(_BV(EXCLK) | _BV(AS2));

        // Set fast PWM mode  (p.157)
        TCCR2A |= _BV(WGM21) | _BV(WGM20);
        TCCR2B &= ~_BV(WGM22);

        if(speakerPin==11){
            // Do non-inverting PWM on pin OC2A (p.155)
            // On the Arduino this is pin 11.
            TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
            TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2A = pgm_read_byte(&sounddata_data[0]);
        } else {
            // Do non-inverting PWM on pin OC2B (p.155)
            // On the Arduino this is pin 3.
            TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
            TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2B = pgm_read_byte(&sounddata_data[0]);
        }

        // Set up Timer 1 to send a sample every interrupt.
        cli();

        // Set CTC mode (Clear Timer on Compare Match) (p.133)
        // Have to set OCR1A *after*, otherwise it gets reset to 0!
        TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
        TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

        // No prescaler (p.134)
        TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set the compare register (OCR1A).
        // OCR1A is a 16-bit register, so we have to do this with
        // interrupts disabled to be safe.
        OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

        // Enable interrupt when TCNT1 == OCR1A (p.136)
        TIMSK1 |= _BV(OCIE1A);

        lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
        sample = 0;
        sei();
    }

    void setup()
    {
    // audio pins
        pinMode(ledPin, OUTPUT);
        digitalWrite(ledPin, HIGH);

        startPlayback(01);
        startPlayback(02);
        startPlayback(03);

    }

    void loop()
    {
      loop();
    }

```

# Answer
> 2 votes
I think it's just a case of `startPlayback()` being asynchronous. It doesn't block; it doesn't wait for playback to finish. It just sets up the 8000 Hz timer interrupt and returns.

The original code calls `stopPlayback()` when it runs out of samples. You could change that block (under `if (sample >= sounddata_length)`) to have it cycle on to the next clip, rather than stopping.

(Note: I'm the original author of the PCM sample but it's been quite a while so take this with a grain of salt. Surprised it still works with newer boards. Have fun!)

# Answer
> 0 votes
The Mega2560 apparently has to use pin 10 instead of pin 11 for PCM output. It would be better if this were defined in the main sketch instead of the library.

---
Tags: pwm, audio, progmem, speaker
---


# Question
Title: How to create TCP server on Arduino UNO WiFi?
I'm currently trying to make my Arduino UNO WiFi work as a TCP host, so I can send him a TCP message and it sends a response.

I had no problem doing this on the Arduino Galileo Gen 2 using the EthernetServer, but since this one is using WiFi, EthernetServer isn't an option.

I can, however, run a web server, but that's not what I want.

So how do I make the Arduino receive, handle and respond to sent TCP/IP messages?

# Answer
> -1 votes
Ethernet and wifi are basically the same thing but only joinig Ethernet is codewise different than joining a wifi address and thus these two need 100% different code because wifi and Ethernet are a different thing.

See, compare codes in below links, and you see the difference is on making up the level 1 connection, and tcp and ip on 2 and 3 do not change.

https://github.com/evothings/evothings-examples/blob/master/examples/arduino-led-onoff-tcp/arduinoethernet/arduinoethernet/arduinoethernet.ino

https://github.com/evothings/evothings-examples/blob/master/examples/arduino-led-onoff-tcp/arduinowifi/arduinowifi/arduinowifi.ino

# Answer
> 1 votes
For Arduino UNO Wifi, you have to use library "UnoWiFi-Developer-Edition-Lib". You can directly download and install it through library manager or can get it offline through the following link "https://github.com/arduino-libraries/UnoWiFi-Developer-Edition-Lib".

Hope this can help you.

---
Tags: tcpip, arduino-uno-wifi-dev-ed
---


title: connecting 5 mq sensor at a time

text:
# Question
Title: connecting 5 mq sensor at a time
I want to take a reading from 5 different mq sensor at a time. do I need an external power source to power these sensors or it will be ok to power sensors from 5v available from the board? I am using arduino uno board .

# Answer
I only had experience with the MQ2 sensor (more info here), so I'm going to use it as an example. If you have different sensors double check their datasheets.

Now, the main current consumption for these comes from the heater. Can you turn the heater off to save some power? Apparently not, since they say that

> Please note that the best preheat time for the sensor is above 24 hours.

So, for the moment, let's consider all five sensors turned on at the same time.

The heater specs say that its resistance is around 33 ohm +/- 5% in the worst case this means 31.35 ohms. At 5V, this means 160mA for each sensor. Five of them are 800mA, and then let's add something like 50mA for the rest of the circuit (just a random number, and highly depends on the rest of the circuit).

Now, how is the UNO powered? If it is powered from the USB, the maximum current you can draw is 500mA (so 850mA is not allowed). So.. No powering from USB. If, on the other hand, the board is powered by the barrel jack, the onboard regulator can dissipate roughly 1-1.5W (taken from this thread). The power dissipation comes from the input voltage. With a 9V input, about 3V (slightly more) will need to be handled by the regulator. At 850mA, this means 2.5W (Not ok). In both cases you will need an external 5V power supply. With a 7V input (the very minimum you can apply) you will have to dissipate roughly 1.2V, at 850mA this means 1.02W. Please beware that this means something like 80-90°C of temperature increase in that area, so the part will become very hot. And moreover its lifespan will be reduced. So use this path only if really necessary.

If you reduce the performances and start powering just one sensor at a time (this means longer time before having it fully operational, and adding some transistor to switch them on and off) this data can change. I mean, if put a transistor to stop powering it, and then turn on one sensor at a time, you will be able to reduce the maximum current consumption to 210mA.

This means that you will be able to get power from the USB port; moreover you will be able to use the external power connector for voltages up to 10.5V (0.8V on the diode, so 4.7V on the regulator - around 1W). This comes at a price, of course: the heater will work for 1/5 of the time, so it will be harder to reach the temperature required for the measurement
> 3 votes

---
Tags: sensors
---


title: Arduino Mega Sensor shield

text:
# Question
Title: Arduino Mega Sensor shield
I'm using an Arduino Mega Sensor Shield on a Mega 2560 board and so far I have 12 servos attached to it from PWM pins 2 to 13.

I want to add 5 more servos but there are no more PWM pins.

So which pins do I do I use for these.

# Answer
> 0 votes
There seems to be a library called

According to this Answer you have some possibilities:

* Using ShiftPWM library
* Using a timer with a generic GPIO

---
Tags: arduino-mega
---


title: Problem with motor driver shield

text:
# Question
Title: Problem with motor driver shield
I have recently bought a L293D shield and 2 BO motors. Whenever I connect the motors to the shield it makes a beeping noise. I searched online and found that I need to change PWM frequency but I know nothing about it and anyone please tell me about the PWM frequency and how to change it.

I have used almost every sketch found online but condition remains same. I am using 9V battery as External power supply and it is absolutely new. Please help me.

# Answer
Acting as a conduit for Google: `Arduino Change PWM Frequency` shows me:

https://playground.arduino.cc/Code/PwmFrequency

Which has the following example function:

```
/**
 * Divides a given PWM pin frequency by a divisor.
 *
 * The resulting frequency is equal to the base frequency divided by
 * the given divisor:
 *   - Base frequencies:
 *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
 *      o The base frequency for pins 5 and 6 is 62500 Hz.
 *   - Divisors:
 *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
 *        256, and 1024.
 *      o The divisors available on pins 3 and 11 are: 1, 8, 32, 64,
 *        128, 256, and 1024.
 *
 * PWM frequencies are tied together in pairs of pins. If one in a
 * pair is changed, the other is also changed to match:
 *   - Pins 5 and 6 are paired on timer0
 *   - Pins 9 and 10 are paired on timer1
 *   - Pins 3 and 11 are paired on timer2
 *
 * Note that this function will have side effects on anything else
 * that uses timers:
 *   - Changes on pins 3, 5, 6, or 11 may cause the delay() and
 *     millis() functions to stop working. Other timing-related
 *     functions may also be affected.
 *   - Changes on pins 9 or 10 will cause the Servo library to function
 *     incorrectly.
 *
 * Thanks to macegr of the Arduino forums for his documentation of the
 * PWM frequency divisors. His post can be viewed at:
 *   http://forum.arduino.cc/index.php?topic=16612#msg121031
 */
void setPwmFrequency(int pin, int divisor) {
  byte mode;
  if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
    switch(divisor) {
      case 1: mode = 0x01; break;
      case 8: mode = 0x02; break;
      case 64: mode = 0x03; break;
      case 256: mode = 0x04; break;
      case 1024: mode = 0x05; break;
      default: return;
    }
    if(pin == 5 || pin == 6) {
      TCCR0B = TCCR0B & 0b11111000 | mode;
    } else {
      TCCR1B = TCCR1B & 0b11111000 | mode;
    }
  } else if(pin == 3 || pin == 11) {
    switch(divisor) {
      case 1: mode = 0x01; break;
      case 8: mode = 0x02; break;
      case 32: mode = 0x03; break;
      case 64: mode = 0x04; break;
      case 128: mode = 0x05; break;
      case 256: mode = 0x06; break;
      case 1024: mode = 0x07; break;
      default: return;
    }
    TCCR2B = TCCR2B & 0b11111000 | mode;
  }
}

```

And numerous results from this SE community also:

https://www.google.com/search?q=arduino+change+PWM+frequency+site:arduino.stackexchange.com

Which note methods for calculating/setting specific frequencies and pitfalls and side-effects of making such changes.
> 1 votes

---
Tags: arduino-motor-shield
---


title: Building an EEZYBOTARM MK1

text:
# Question
Title: Building an EEZYBOTARM MK1
My bot arm building is complete, I'm using it with Arduino and 2 joysticks with 4 servos ( mg90s), running with the 9v battery, but still, the servos could not lift the bot arm once it is going down and the servo keeps fluctuating. It is a 3d printed bot so it is not so heavy. please help?

# Answer
Even if your device is not so heavy, a 9V battery has a maximum practical current draw in the 10s of milliamps. It's not a good choice for operating motors.

A better choice would be AA, C, D, or Lithium-Ion/Lithium-Polymer batteries, wired in series to produce the desired voltage.
> 1 votes

---
Tags: servo, battery
---


# Question
Title: Trouble using proximity sensor as input and LED output
I was wondering if anyone had any pointers or advice to make this project work. Essentially I would like to have the LED fade (meaning like fade on and off at a calm rate) at one rate when there is nothing close to the proximity sensor, and then to speed up the fade amount when there is something close to the sensor.

```
#include <NewPing.h>   //include the library

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount;    // how many points to fade the LED by

int triggerPin = 12;   //pin conneccted to the Trig pin on the sensor
int echoPin = 11;       //pin connected to the Echo pin on the sensor
int maxDistance = 200;  //set the max distance for the sensor to read (helps with errors)
int distanceVal;        //variable to hold the distance val

int sampleRate = 200;   //how fast to sample the value
long lastReading;       //used for the timer

NewPing proximity1(triggerPin, echoPin, maxDistance);   //sets up the sensor object

void setup()
{
  Serial.begin(9600);  //start the serial port
  pinMode(led, OUTPUT);
}

void loop() {

    if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
  {
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);

if(distanceVal<20){

fadeAmount = 5;
}
else{
  fadeAmount = 2;
}

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
  }
}

```

https://github.com/sanaalla/Fade-LED-with-Proximity-sensor

Above is my code, which is not working. I am fairly new to Arduino and so would greatly appreciate some more seasoned wisdom!

# Answer
You want 2 independant loops, one for the measurement and one for the dimming effect. The latter one must also be able to run when not measuring.

```
if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
{
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);
}

if(millis() - lastFade >= fadeRate) //other timer
{
  lastFade = millis();
  if(distanceVal<20){
    fadeAmount = 5;
  }else{
    fadeAmount = 2;
  }

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
}

```
> 1 votes

# Answer
\*update! I fixed the code and got it to do what I want.

```
#include <NewPing.h>   //include the library

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount1 = 10;    // how many points to fade the LED by
int fadeAmount2 = 2;    // how many points to fade the LED by

int triggerPin = 12;   //pin conneccted to the Trig pin on the sensor
int echoPin = 11;       //pin connected to the Echo pin on the sensor
int maxDistance = 200;  //set the max distance for the sensor to read (helps with errors)
int distanceVal; //variable to hold the distance val
int lastFade;
int fadeRate = 200;

int sampleRate = 200;   //how fast to sample the value
long lastReading;       //used for the timer

NewPing proximity1(triggerPin, echoPin, maxDistance);   //sets up the sensor object

void setup()
{
  Serial.begin(9600);  //start the serial port
  pinMode(led, OUTPUT);
}

void loop() {

  if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
{
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);
}

if(distanceVal<20){

    // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount1;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount1 = -fadeAmount1;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

else{

    // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount2;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount2 = -fadeAmount2;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

}

```
> -1 votes

---
Tags: sensors, led, proximity
---


# Question
Title: LED strip problem... getting red when expecting white with lots of pixels. Fine with 1 pixel
I have an Arduino Uno. I bought this LED strip: https://www.amazon.com/gp/product/B019DYZNO6/ref=oh\_aui\_detailpage\_o08\_s02?ie=UTF8&psc=1

Starting initially using FastLED library. When I tried to set the entire strip to white (255,255,255), it was coming out red. Any color close to white was coming out red.

I thought maybe there was an issue with the library, so I tried the neopixel library. Same thing until... If I just set one pixel to 255,255,255 and don't set any other, it comes out white! If I set about 10 pixels, they still look white. As I set more pixels, they start to loose their whiteness and become red.

I want to say that maybe this was a power issue... but I tested this both when it was running off my PC and running standalone with a power supply (supplying 5V).

Any suggestions?? I also thought that maybe it's a bum strip, but I also bought https://www.amazon.com/gp/product/B01AG923GI/ref=ask\_ql\_qh\_dp\_hza and did the same experiment, and am getting the same results...

# Answer
> 3 votes
According to https://learn.adafruit.com/adafruit-neopixel-uberguide/powering-neopixels a Neopixel can consume 60 mA at full brightness white.

> Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue). In actual use though, it’s rare for all pixels to be turned on that way. When mixing colors and displaying animations, the current draw will be much less. It’s impossible to estimate a single number for all circumstances, but we’ve been using 1/3 this (20 mA per pixel) as a gross rule of thumb with no ill effects. But if you know for a fact that you need every pixel on at maximum brightness, use the full 60 mA figure.

So your 144 Neopixels would require 8.4 **amps**. You would need a pretty solid power supply to supply that much.

One way of confirming that would be to measure the voltage in to the Neopixel strip (at the strip end) when it is displaying all white. I'd be surprised if it measures 5V.

The Amazon page you linked says:

> Voltage: DC 5V
>
> Power: 0.3W ± 0.01% per LED

That agrees with the figure of 60 mA (0.060A * 5V = 0.3W)

---

To put it another way, your power supply would need to supply 43.2W (144 * 0.3W). None of the bench power supplies I have here can put out 43W (or 8A), nor any of the wall-warts. You may have a really massive one, but you haven't specified what sort of power supply you are using.

---

> I run them with a power supply (one that is working as expected, but still have it connected to the PC/USB?

Yes, there is a technique for doing that (similar to powering motors etc.).

* You have one low-current supply to the Arduino (this could be your USB port even).
* You have a high-current supply to the pixels/motor/whatever. This would require thicker cables.
* You **connect the grounds** of both supplies so that they have a common ground reference.
* The data line (the pixel information) is sent from the Arduino to the Neopixels

The one power supply can do both roles, just connect the wires together at the power supply end (this automatically connects the grounds, of course).

This way, the heavy-duty current does not go through the Arduino board.

---

If you are using the USB port for logic power you still connect the grounds like this:

---
Tags: led, neopixel, ws2812
---


# Question
Title: MFRC522 won't detect cards after the first loop
Edit: I have found out that it was something wrong with the cables. I have solved the problem. Thanks for everyone who tried to help.

I am working a project that should basically do:

1. Read the RFID card UID.
2. Get the selection from user using pushbuttons.
3. Restart the code for new cards.

**The problem is, It reads the card and gets the input from pushbuttons. But after the first loop, It doesn't detect other cards (or the same card again).** Here is my code: (I am using miguelbalboa's MFRC522 library and Arduino UNO)

```
#include <MFRC522Hack.h>
#include <MFRC522Extended.h>
#include <deprecated.h>
#include <MFRC522Debug.h>
#include <require_cpp11.h>
#include <MFRC522.h>

// protype 1 copy
#include <SPI.h>

// Define pin numbers for mfrc522
#define SS_PIN 10
#define RST_PIN 9
#define BLUE_BUT A0
#define RED_BUT A1

// Define pin numbers for lcd
const int RS = A0 , EN = A1 , D4 = A5 , D5 = A4 , D6 = A3 , D7 = A2;
int uids[] = {14805 ,25673};
int votedArray[] = {};
String uidNames[] = {"WHITE" , "BLUE"};
// Create LCD and MFRC522 instances
MFRC522 mfrc522(SS_PIN , RST_PIN);

unsigned long getCardID(int showCardData = 0){
  /* this function gets the uid of the rfid card
   and returns the uid in unsigned long format */
  /* this fn. should be called with argument 1
  if printing the card data to the serial monitor
  is needed. */

  unsigned long UID_unsigned;
   UID_unsigned =  mfrc522.uid.uidByte[0] << 24;
   UID_unsigned += mfrc522.uid.uidByte[1] << 16;
   UID_unsigned += mfrc522.uid.uidByte[2] <<  8;
   UID_unsigned += mfrc522.uid.uidByte[3];

  if(showCardData==1){
  Serial.println("UID Unsigned int");
  Serial.println(UID_unsigned);

  String UID_string =  (String)UID_unsigned;
  long UID_LONG=(long)UID_unsigned;

  Serial.println("UID Long :");
  Serial.println(UID_LONG);

  Serial.println("UID String :");
  Serial.println(UID_string); } // print card data to the serial monitor
int UID_int = (int) UID_unsigned;
 return UID_int;

 }

void showCardData(){
  /* this fn. calls getCardID function
  with argument 1 to print the data to
  the serial monitor (kind of shortcut)*/
  getCardID(1);
}

int findInList(int uid , int uidArray[]){
  /* this fn. returns the index of the uid in the array if found,
  returns -1 if not found*/
  int numOfElements = sizeof(uidArray)/sizeof(uidArray[0]); // calculate the num.of elem. in array
  for (int i = 0 ; i <= numOfElements ; i++) {
    if(uid == uidArray[i]){
      return i; // if element is found in the array, return true
    }
  }
  return -1;
}

String getCardName(int cardUID){
  int UIDIndex = findInList(cardUID , uids);

  if(UIDIndex == -1){
    return "ERROR";
    }

  else {
    String cardName = uidNames[UIDIndex];
    return cardName;
    }

}

void printCardName(int cardUID){
  String cardName = getCardName(cardUID);
  if(cardName == "ERROR"){
    Serial.print("ERROR! CARD UID: ");
    Serial.println(cardUID);
    }

  else {
    Serial.print("CARD NAME: ");
    Serial.println(cardName);
    }
}

void setup() {
  Serial.begin(9600); // Init. serial comm. with the PC
  SPI.begin(); // Init. SPI bus for MFRC522
  mfrc522.PCD_Init(); // Init. MFRC522 card
  pinMode(BLUE_BUT , INPUT);
  pinMode(RED_BUT , INPUT);
}

void loop() {

    // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()){
  Serial.println("CARD NOT PRESENT");
    return;
 }

  // Verify if the NUID has been readed
  if ( ! mfrc522.PICC_ReadCardSerial()) {

    Serial.println("CARD NOT read");
    return;  }

  int cardUID = getCardID();

  Serial.println("CARD UID READ");
  printCardName(cardUID);

  Serial.println("SELECT WITH BUTTONS");

//getVote(cardUID);
  int blueState = LOW , redState = LOW ;
  while(1) {
   blueState = digitalRead(BLUE_BUT);
   redState = digitalRead(RED_BUT);

  if(blueState == HIGH){
    Serial.println("BLUE");

    break;
    }

  if(redState == HIGH){
    Serial.println("RED");
    mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
    break;
    }

  }

Serial.println("PROGRAM COMPLETE");

}

```

I have already tried adding

```
    mfrc522.PICC_HaltA();
    mfrc522.PCD_StopCrypto1();

```

but didn't help.

And here is the screenshot of the Serial Monitor after reading the first card and getting the button input.

I have checked the similar problems, but the solutions didn't help me.

# Answer
> 1 votes
I assume, `Buttons` and `RFID reader` both connected to the 3.3v pin on arduino. Move buttons to the 5v, leave RFID on 3.3v alone.

---
Tags: rfid
---


title: Powering servos with external source

text:
# Question
Title: Powering servos with external source
I understand why servos and motors require an external power source when run from the Uno, but I've seen a lot of tutorials (for example, this one), where the servo is connected directly to the Arduino's 5V port. I did this, and I think it fried my servo. This is also the method shown on the official Arduino tutorials for Knob and Sweep. In fact, the knob tutorial was the first and last tutorial I tried with my servo -- after trying it, the servo didn't work.

It went like this:
1) Try sweep code without using external supply. Works fine.
2) Try knob code without using external supply. Servo hums without moving and heats up (a lot).

Why do tutorials say to do this if it's not advisable?

# Answer
Most likely you fried the voltage regulator or the diode on your Arduino board (depending in which power source you used), because the servo has drawn too much current.

Many Arduino Kits or Starter Packs come with really small servos. These do not need much power (especially when no mechanical load is attached to them), so you can power them directly from the 5V pin. Greater/stronger Servos draw much more current and cannot be safely run in the 5V pin.

Many tutorials show this, because it is an easy start for a beginner. And with the right servo it works. More sophisticated cases are not covered there.

EDIT:

Since your Arduino works fine, the voltage regulator and/or the diode should be fine. I tested the `Knob` example on my Arduino Nano, while powering the servo on the Arduinos 5V pin (and the Arduino is powered over USB). When the Servo is moving, you can see that there is a significant power draw (The power LED gets a bit dimmer), but not so much, that it would be a problem for the Arduino or USB port. Also the example code works as it should, without the servo heating up. I also used a SG90 Micro Servo (9g, by Tower Pro; same as in the tutorial you linked). I also tried the same with an external power source (5V from a powerful USB charger). It still works as intended, but with more power, since the servo now can draw much more current to produce a higher thrust.

So the only thing, I can think of for your problem is, that you either have corrupt hardware, or you have connected it wrong (for example wrong polarity). My Servo has the same color coding for the wires as in the tutorial you linked. Brown is ground, Red is 5V Vcc and Yellow is for the pulse signal.
> 1 votes

---
Tags: arduino-uno, power, servo
---


title: Infrared frequency recorded with saleae

text:
# Question
Title: Infrared frequency recorded with saleae
i'm trying to decode infrared signal recorded with the saleae. It makes me wonder why saleae shows so low values for the frequencies from 0.1kHz to 0.8kHz. I found that standard for the IR is around 38kHZ. Is there something wrong with my record? Or did i misread the sample?

# Answer
> 7 votes
What you are looking now is NOT the IR frequency, but the de-modulated signal.

Here is what I'm talking about:

(image taken from http://www.electronicwings.com/sensors-modules/ir-communication)

As you can see, the various pulses are made of smaller pulses.

In your case you are seeing what is here called "Serial data", which is different from the carrier frequency. What the saleae board is telling you is that the width of the high part is 1.625ms, while the width of the low part is 0.631 ms; as you can see, the waveform is NOT periodic, so the "frequency" is meaningless (it's the reverse of the time marked on the view, which is the sum of one large high value and one low value).

Your plot resembles the NEC protocol (see for instance here). A logic '0' is a 562.5µs pulse followed by a 562.5µs space, while the logic '1' is a 562.5µs pulse burst followed by a 1.6875ms space (this is similar to by 0.631 ms and 1.625 ms measurement)

---
Tags: arduino-uno, led, infrared
---


title: Readings changing in hall effect sensor

text:
# Question
Title: Readings changing in hall effect sensor
I am using a A1324 hall effect sensor for a distance measuring.

The voltage output keeps changing even if the distance between the magnet and sensor does not change. The output changes +-0.200V and I am trying to measure the distances at steps of 0.01V.

# Answer
> 2 votes
From https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/

> `analogRead()`
>
> Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or, **.0049 volts (4.9 mV) per unit**.

It is likely what you are seeing is noise and is to be expected. The source of the noise is likely multiple and could be environmental physical metallic or magnetic objects some distance away that are moving, electrical wiring (mains) nearby, and noise introduced by the power supply to the Arduino.

If you want to get a stable precise reading that close to the minimum step size, you will want to take several readings and average them. The more you read and average, the more you can eliminate the random effect of the noise, but the tradeoff is that it is slower because you are taking tens or hundreds of readings just for one result.

---
Tags: arduino-uno, sensors, hardware, electronics
---


# Question
Title: adafruit LSM9DS0 Library - ok with Uno but compile error with LinkitOne?
I'm calling an adafruit Flora LSM9DS0 magnetometer using the Adafruit library with the following sketch:

```
        #include <Wire.h>
        #include <SPI.h>
        #include <Adafruit_LSM9DS0.h>
        #include <Adafruit_Sensor.h>  // not used in this demo but required!

        unsigned long timeNow = 0;
        unsigned long mSecInHour = 3600000;
        unsigned long TimeNow =0;
        int millisecs =0;
        int seconds = 0;
        byte minutes = 0;
        byte hours = 0;

        int mag_raw_x;
        int mag_raw_y;
        int mag_raw_z;

        // i2c
        Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0();

        // You can also use software SPI
        //Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(13, 12, 11, 10, 9);
        // Or hardware SPI! In this case, only CS pins are passed in
        //Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(10, 9);

        void setupSensor()
        {
          // 2.) Set the magnetometer sensitivity
          lsm.setupMag(lsm.LSM9DS0_MAGGAIN_2GAUSS);
        }

        void setup()
        {
        #ifndef ESP8266
          while (!Serial);     // will pause Zero, Leonardo, etc
        #endif
          Serial.begin(9600);

          // Try to initialise and warn if we couldn't detect the chip
          if (!lsm.begin())
          {

            while (1);
          }
          Serial.println(F("Found LSM9DS0 9DOF, measurements in Gauss"));
         }
         void loop()
        {
          lsm.read();
          TimeNow = millis();
          mag_raw_x = lsm.magData.x;
          mag_raw_y = lsm.magData.y;
          mag_raw_z = lsm.magData.z;

```

Which compiles and runs fine on the Arduino Uno, but I don't understand why the same sketch causes this compile error in the LSM9DS0 library when I compile for the LinkitOne?

```
    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'bool Adafruit_LSM9DS0::begin()':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:77:16: error: 'SPCR' was not declared in this scope

         SPCRback = SPCR;

                    ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'void Adafruit_LSM9DS0::write8(boolean, byte, byte)':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:365:18: error: 'SPCR' was not declared in this scope

           SPCRback = SPCR;

                      ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:374:7: error: 'SPCR' was not declared in this scope

           SPCR = SPCRback;

           ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'byte Adafruit_LSM9DS0::readBuffer(boolean, byte, byte, uint8_t*)':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:415:18: error: 'SPCR' was not declared in this scope

           SPCRback = SPCR;

                      ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:426:7: error: 'SPCR' was not declared in this scope

           SPCR = SPCRback;

           ^

```

Any suggestions welcome !

# Answer
> 2 votes
The Adafruit library for the LSM9DS0 is written to run on an 8-bit Arduino. The LinkitOne isn't - it's an ARM board.

Either get a different library that is written to work on ARM, write your own library to work on ARM, or don't use that combination of components.

---
Tags: arduino-uno, i2c, library, adafruit, magnetometer
---


# Question
Title: I'm trying to make a program which you choose an angle
I'm trying to make a program which you choose an angle, and it tells you it's respective Sin, Cos and Tan. But, I can't figure out why all of the angles I use have the same answer (Sin 0, Cos 1 and Tan 0. Can someone help me out?

```
#include <math.h>
double angulo;
double seno;
double cosseno;
double tangente;
double rad;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {

 Serial.println("Programa para calcular sen, cos e tg");
 delay(1000);
 Serial.println("Digite o angulo");
 angulo = Serial.parseInt();
 rad = angulo*0,0174533;
 seno = sin(rad);
 Serial.println("Seno");
 Serial.println(seno);
 cosseno = cos(rad);
 Serial.println("Cosseno");
 Serial.println(cosseno);
 tangente = tan(rad);
 Serial.println("Tangente");
 Serial.println(tangente);

}

```

# Answer
> 3 votes
You have written

```
rad = angulo*0,0174533;

```

But, C++ uses the american decimal notation:

```
rad = angulo*0.0174533;

```

Thus, you have been multiplying `angulo` by zero every time.

---
Tags: arduino-uno
---


title: Which EEPROM has a long lifecycle?

text:
# Question
Title: Which EEPROM has a long lifecycle?
I would like to build a box counter for machine, so I'm going to use EEPROM in Arduino to save count. But the lifecycle is limited to 100,000 writes. Please suggest an external EEPROM with a long lifecycle or any other solution.

# Answer
> 6 votes
You can cycle through all the addresses in the EEPROM like a ring buffer.

You'll need to reserve a bit so you can binary search for the head of the buffer during startup.

You can also reduce how often you write in general especially when the count will increment in bursts, try and wait out those bursts instead of writing on every increment.

# Answer
> 2 votes
The EEPROMs from Microchip have a guaranteed erase count of 1 million. The ones from ST offer 4 million. So it's not hard to find EEPROMs with a higher endurance.

But for a device which writes a lot, a better solution would be a NVRAM, FRAM or EERAM. Those usually come with virtually no limitations to the write cycles but usually are more expensive than EEPROMs but that might very well be worth it compared to the hassle you can get in otherwise.

Adafruit offers SPI and I²C variants for FRAM boards.

# Answer
> 0 votes
If you use something like an SD card, they have internal logic that will move the data around when a call is used up. This should give you virtually unlimited storage for something as simple as a count.

---
Tags: arduino-uno, i2c, eeprom
---