message:
Make a stepper motor move

I am at the moment trying to make a bipolar stepper motor move.
I am interfacing it through a control board, which takes the input `Step`, `Dir`, `En`, and 5V.

I am providing those input signal via an Arduino, but can't get the damn thing to move. all it does it move a step forward and backwards, like it being stuck or and tries to wiggle out of something.. What could the reason be..

Here is the Code:

    #include "stepper_motor.h"
    int max_step = 200;
    stepper_motor::stepper_motor()
    {
      pinMode(BUILTIN_LED,OUTPUT);
      pinMode(step_pin,OUTPUT);
      pinMode(dir_pin,OUTPUT);
      pinMode(en_pin,OUTPUT);

      alive_bool = true;
      position_bool = false;
      step_count = 0;
    }

    void stepper_motor::step_pwm()
    {

      if(position_bool==true)
      {
        //Dir pin low
        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,LOW);
        digitalWrite(en_pin,LOW);

        delay(0.005);

        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,LOW);
        digitalWrite(en_pin,HIGH);

        delay(0.005);

        int step = 0;
        while(step < max_step)
        {
          digitalWrite(step_pin,HIGH);
          delay(1);
          digitalWrite(step_pin,LOW);
          delay(1);
        }

        //digitalWrite(en_pin,LOW);
        //position_bool = false;
      }
      else
      {
        //Dir pin high
        delay(1000);
        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,LOW);
        digitalWrite(en_pin,LOW);

        delay(0.005);

        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,LOW);
        digitalWrite(en_pin,HIGH);

        delay(0.005);

        digitalWrite(step_pin, LOW);
        digitalWrite(dir_pin,HIGH);
        digitalWrite(en_pin,HIGH);

        int step = 0;
        while(step < max_step)
        {
          digitalWrite(step_pin,HIGH);
          delay(1);
          digitalWrite(step_pin,LOW);
          delay(1);
        }

        //digitalWrite(en_pin,LOW);
        //position_bool = true;
      }

    }

Updated step_pwm():

    void stepper_motor::step_pwm()
    {
        //Start -  En Low , DIR HIGH, STEP high
        //init configuration!
        digitalWrite(step_pin, HIGH);
        digitalWrite(dir_pin,HIGH);
        digitalWrite(en_pin,LOW); // Previous LOW

        delay(0.005);

        //T1-  En HIGH , DIR HIGH, STEP HIGH
        //Enable high
        //digitalWrite(step_pin, HIGH);
        //digitalWrite(dir_pin,HIGH);
        digitalWrite(en_pin,HIGH);

        delay(0.005);

        //T2-  En HIGH , DIR low, STEP HIGH
        //Direction choosen
        //digitalWrite(step_pin, HIGH);
        digitalWrite(dir_pin,LOW);
        //digitalWrite(en_pin,HIGH);

        delay(0.005);
        //T2-  En HIGH , DIR low, STEP HIGH
        //STEP  step between low and high with 2.5µs between

        while(1)
        {
          digitalWrite(step_pin,LOW);
          delay(2.5);
          digitalWrite(step_pin,HIGH);
          delay(2.5);
        }

    }

The control board i am using is a [ST330-v3][1]
The motor i am using is [this one][2]
here is a little block diagram of how things are connected.

[![enter image description here][3]][3]

  [1]: http://www.sainsmart.com/zen/documents/20-019-201/ST330  Stepper Motor Driver Board User Manual.pdf
  [2]: https://www.orientalmotor.com.sg/products/st/list/detail/?product_name=PK244-01A&brand_tbl_code=ST&series_code=G000&type_code=Unipolar 6 lead wires&type=Standard Type
  [3]: https://i.stack.imgur.com/jsaYI.png

body:
You must set EN BEFORE you set DIR.  The datasheet says EN must be high for at least 5 microseconds before you set DIR.  You should probably just set EN high when your program starts, then not fool with it until your program ends.

The next thing is that I don't see you incrementing the variable "step" anywhere.  So, if you did get the stepper to turn, it wouldn't stop.

-------------

The updated code looks like it ought to work.

You should use DelayMicroseconds instead of Delay(0.005) though.  Delay takes an integer instead of a decimal value, so you won't get what you expect.  Curse the Arduino IDE for not throwing a fit when pass a float for an int.

-------------

It looks like anything working properly is purely luck.  The board you are using(NOT an Arduino) uses 3.3V logic levels.  The ST330 says a high must be at least 4V, so if it reacts to your control signals at all it is just luck.

The 8266 outputs are rated for 12mA, the ST330 inputs need about 20mA, so you are over doing it.  The 8266 might put up with, and might just die on you.

You might be able to drive the ST330 by switching the mode of the pins.

Low would be "set pin to mode output and set low."

A high would be "set mode input."

Input mode leaves the pin floating, which the ST330 will interpret as a high.

Other than that, you could use NPN transistors to drive the ST330 inputs, then invert your output signals.

The NPN would invert your signal (a high becomes a low) so you would have to set an output to low to get a high going into the ST330.

----------

You can use NPN transistors like this to drive the ST330:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/PzYWz.png)

<!-- End schematic -->

Setting the  GPIO from the ESP8266 to high would cause a low on the ST330 input.

Setting the GPIO pin to low would cause a high on the ST330 input.

This is the solution I would prefer if I needed to use the ESP8266 with the ST330.

----------

If you'd like to try a purely software solution, then do this:

 1. To send a low to the ST330 input, set the GPIO to pin mode output and set the output to low. (pinMode(step_pin,INPUT) then DigitalWrite(step_pin,LOW))
 2. To send a high to the ST330 input, set the pin mode to INPUT (pinMode(step_pin,INPUT)

When the GPIO pin is in input mode, it floats.  It doesn't have a voltage level of its own - it acts like it is disconnected.

If that works, I'd still prefer to use the transistors.

----------

You can avoid all of this using the UNO.  It has 5V logic levels on the outputs.


sender: user

sender: assistant

body:
This is problematic:

     delay(0.005);

The Arduino delay() function takes an `unsigned long` as an input, which is an integer rather than floating point type.  As a result, the argument you pass to it will be treated as zero.  Depending on how delay() is implemented this will result in either no delay (beyond overhead), or a minimum that may be longer than you intended.

Of course you now seem to only be running this code once, and then going into an unending loop which uses a 2.5 ms delay that will, for the same reason, be more of a 2ms delay.


message:
How to power two stacked motor shields with one 3S Lipo battery (11.1V)?

I have these 2 motor shields:
**Adafruit Motor Shield V2** and
**Seed Motor Shield V2**.

They are stacked on top of an **Arduino UNO**.

My question is, how can I power 2 of those motor shields with one 3S Lipo battery(**Turnigy 3S 2200mAh 20C**), given that I have 6 identical 4.6-6V DC gearmotors?

Thanks!

body:
You can avoid using a linear voltage regulator. Try using [this][1] voltage regulator.

You will get 5 Volts 2 Amp output which should be easy to connect to motor shield's input power ports.

  [1]: https://www.amazon.com/DROK-Converter-Step-down-Transformer-Stabilizer/dp/B00JUFJ1GA/ref=sr_1_2?s=electronics&ie=UTF8&qid=1475207248&sr=1-2&keywords=voltage+regulator+5+volt&th=1


message:
How to properly understand verbose compiler error text? For beginner level

I'm an Arduino newbie, no background in C/C++, needing help to understand Arduino IDE verbose output about compiler errors. My searching failed to find suitable info - have I missed a relevant guide?

Below example of compiler errors produced when I try to compile Example sketch (TestRTC) from a downloaded library. I assume this Example code is valid. Guessing that my errors relate to missing components. The library was one of two recommended in answer to [question][1]. I used IDE Manage Libraries to install from downloaded zip files. Windows file manager shows both library folders are present.

In example below: Which components did the compiler find/not find? Where did compiler search for needed components? What other useful info could be gleaned from this error output?

Would be very grateful for general advice on interpreting error text as well as this particular example. Many thanks.

    Arduino: 1.6.11 (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 C:\jdocs\00_arduino\duinosketches\libraries -fqbn=arduino:avr:uno -ide-version=10611 -build-path C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.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 C:\jdocs\00_arduino\duinosketches\libraries -fqbn=arduino:avr:uno -ide-version=10611 -build-path C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.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=10611 -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" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.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=10611 -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" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.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=10611 -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" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.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=10611 -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" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\Wire.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=10611 -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" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility\twi.c" -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=10611 -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" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master\DS3232RTC.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=10611 -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" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -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=10611 -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" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
    "C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino10/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\preproc\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "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 -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10611 -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" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src" "-IC:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master" "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp" -o "C:\Users\Jules\AppData\Local\Temp\build8b85ae284f2ad840f4c667e76a0588ca.tmp\sketch\TestRTC.ino.cpp.o"
    In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:82:22: error: 'tmElements_t' has not been declared

         static void read(tmElements_t &tm);

                          ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:83:23: error: 'tmElements_t' has not been declared

         static void write(tmElements_t &tm);

                           ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:84:27: error: 'tmElements_t' has not been declared

         static void writeTime(tmElements_t &tm);

                               ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:85:27: error: 'tmElements_t' has not been declared

         static void writeDate(tmElements_t &tm);

                               ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:61: error: 'tmElements_t' has not been declared

         static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                                                                 ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:88:61: error: 'tmElements_t' has not been declared

         static void writeAlarm(uint8_t alarm, alarmMode_t mode, tmElements_t tm);

                                                                 ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:110:24: error: 'tmElements_t' has not been declared

         static void _wTime(tmElements_t &tm);

                            ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:111:24: error: 'tmElements_t' has not been declared

         static void _wDate(tmElements_t &tm);

                            ^

    TestRTC:79: error: 'tmElements_t' does not name a type

     inline uint8_t monthLength(const tmElements_t *date)

                               ^

    TestRTC:297: error: 'tmElements_t' does not name a type

     void printAlarm(byte alarmNum, const alarmMode_t mode, const tmElements_t time)

                                                                  ^

    TestRTC:79: error: 'tmElements_t' does not name a type

     inline uint8_t monthLength(const tmElements_t *date)

                                      ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'uint8_t monthLength(const int*)':

    TestRTC:81: error: request for member 'Month' in '* date', which is of non-class type 'const int'

         if (date->Month != 2 || !isLeapYear(date->Year))

                   ^

    TestRTC:81: error: request for member 'Year' in '* date', which is of non-class type 'const int'

         if (date->Month != 2 || !isLeapYear(date->Year))

                                                   ^

    TestRTC:82: error: request for member 'Month' in '* date', which is of non-class type 'const int'

             return monthLengths[date->Month - 1];

                                       ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdTime(const char*)':

    TestRTC:213: error: 'tmElements_t' was not declared in this scope

         tmElements_t tm;

         ^

    TestRTC:218: error: expected unqualified-id before '.' token

             tm.Hour = readField(args, posn, 23);

               ^

    TestRTC:219: error: expected unqualified-id before '.' token

             tm.Minute = readField(args, posn, 59);

               ^

    TestRTC:221: error: expected unqualified-id before '.' token

                 tm.Second = readField(args, posn, 59);

                   ^

    TestRTC:223: error: expected unqualified-id before '.' token

                 tm.Second = 0;

                   ^

    TestRTC:224: error: expected primary-expression before '.' token

             if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                   ^

    TestRTC:224: error: expected primary-expression before '.' token

             if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                                    ^

    TestRTC:224: error: expected primary-expression before '.' token

             if (tm.Hour == 99 || tm.Minute == 99 || tm.Second == 99) {

                                                       ^

    TestRTC:228: error: expected primary-expression before ')' token

             RTC.writeTime(tm);

                             ^

    TestRTC:233: error: expected primary-expression before ')' token

         RTC.read(tm);

                    ^

    TestRTC:234: error: expected primary-expression before '.' token

         printDec2(tm.Hour);

                     ^

    TestRTC:236: error: expected primary-expression before '.' token

         printDec2(tm.Minute);

                     ^

    TestRTC:238: error: expected primary-expression before '.' token

         printDec2(tm.Second);

                     ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdDate(const char*)':

    TestRTC:245: error: 'tmElements_t' was not declared in this scope

         tmElements_t tm;

         ^

    TestRTC:256: error: expected unqualified-id before '.' token

             tm.Day = (byte)(value % 100);

               ^

    TestRTC:257: error: expected unqualified-id before '.' token

             tm.Month = (byte)((value / 100) % 100);

               ^

    TestRTC:258: error: expected unqualified-id before '.' token

             tm.Year = CalendarYrToTm( (unsigned int)(value / 10000) );

               ^

    TestRTC:259: error: expected primary-expression before '.' token

             if (tm.Month < 1 || tm.Month > 12) {

                   ^

    TestRTC:259: error: expected primary-expression before '.' token

             if (tm.Month < 1 || tm.Month > 12) {

                                   ^

    TestRTC:263: error: expected primary-expression before ')' token

             uint8_t len = monthLength(&tm);

                                          ^

    TestRTC:264: error: expected primary-expression before '.' token

             if (tm.Day < 1 || tm.Day > len) {

                   ^

    TestRTC:264: error: expected primary-expression before '.' token

             if (tm.Day < 1 || tm.Day > len) {

                                 ^

    TestRTC:269: error: expected primary-expression before ')' token

             RTC.writeDate(tm);

                             ^

    TestRTC:274: error: expected primary-expression before ')' token

         RTC.read(tm);

                    ^

    TestRTC:275: error: expected primary-expression before '.' token

         if (tm.Wday > 0) Serial.print(days[tm.Wday - 1]);

               ^

    TestRTC:275: error: expected primary-expression before '.' token

         if (tm.Wday > 0) Serial.print(days[tm.Wday - 1]);

                                              ^

    TestRTC:276: error: expected primary-expression before '.' token

         Serial.print(tm.Day, DEC);

                        ^

    TestRTC:277: error: expected primary-expression before '.' token

         Serial.print(months[tm.Month - 1]);

                               ^

    TestRTC:278: error: expected primary-expression before '.' token

         Serial.println(tmYearToCalendar(tm.Year), DEC);  // NB! Remember tmYearToCalendar()

                                           ^

    TestRTC:278: error: 'tmYearToCalendar' was not declared in this scope

         Serial.println(tmYearToCalendar(tm.Year), DEC);  // NB! Remember tmYearToCalendar()

                                                ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: At global scope:

    TestRTC:297: error: 'tmElements_t' does not name a type

     void printAlarm(byte alarmNum, const alarmMode_t mode, const tmElements_t time)

                                                                  ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void printAlarm(byte, alarmMode_t, int)':

    TestRTC:324: error: request for member 'Second' in 'time', which is of non-class type 'const int'

                 printDec2(time.Second);

                                ^

    TestRTC:328: error: request for member 'Minute' in 'time', which is of non-class type 'const int'

                 printDec2(time.Minute);

                                ^

    TestRTC:330: error: request for member 'Second' in 'time', which is of non-class type 'const int'

                 printDec2(time.Second);

                                ^

    TestRTC:336: error: request for member 'Day' in 'time', which is of non-class type 'const int'

                   Serial.print(time.Day);

                                     ^

    TestRTC:340: error: request for member 'Wday' in 'time', which is of non-class type 'const int'

                   Serial.print(days[time.Wday - 1]);

                                          ^

    TestRTC:343: error: request for member 'Hour' in 'time', which is of non-class type 'const int'

                 printDec2(time.Hour);

                                ^

    TestRTC:345: error: request for member 'Minute' in 'time', which is of non-class type 'const int'

                 printDec2(time.Minute);

                                ^

    TestRTC:347: error: request for member 'Second' in 'time', which is of non-class type 'const int'

                 printDec2(time.Second);

                                ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdAlarms(const char*)':

    TestRTC:359: error: 'tmElements_t' was not declared in this scope

         tmElements_t time;

         ^

    TestRTC:362: error: no matching function for call to 'DS3232RTC::readAlarm(byte&, alarmMode_t&, time_t (&)(time_t*))'

             RTC.readAlarm(alarmNum, mode, time);

                                               ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:362:43: note: candidate is:

    In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note: static void DS3232RTC::readAlarm(uint8_t, alarmMode_t&, int&)

         static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                     ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note:   no known conversion for argument 3 from 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}' to 'int&'

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino: In function 'void cmdAlarm(const char*)':

    TestRTC:373: error: 'tmElements_t' was not declared in this scope

         tmElements_t time;

         ^

    TestRTC:391: error: request for member 'Hour' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

                 time.Hour = readField(args, posn, 23);

                      ^

    TestRTC:392: error: request for member 'Minute' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

                 time.Minute = readField(args, posn, 59);

                      ^

    TestRTC:393: error: request for member 'Hour' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

                 if (time.Hour == 99 || time.Minute == 99) {

                          ^

    TestRTC:393: error: request for member 'Minute' in 'time', which is of non-class type 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}'

                 if (time.Hour == 99 || time.Minute == 99) {

                                             ^

    TestRTC:417: error: no matching function for call to 'DS3232RTC::readAlarm(byte&, alarmMode_t&, time_t (&)(time_t*))'

         RTC.readAlarm(alarmNum, mode, time);

                                           ^

    C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:417:39: note: candidate is:

    In file included from C:\Users\Jules\AppData\Local\Temp\arduino_modified_sketch_461291\TestRTC.ino:49:0:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note: static void DS3232RTC::readAlarm(uint8_t, alarmMode_t&, int&)

         static void readAlarm(uint8_t alarm, alarmMode_t &mode, tmElements_t &tm);

                     ^

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:87:17: note:   no known conversion for argument 3 from 'time_t(time_t*) {aka long unsigned int(long unsigned int*)}' to 'int&'

    Multiple libraries were found for "DS3232RTC.h"
     Used: C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master
     Not used: C:\Program Files (x86)\Arduino\libraries\RTC
    Using library Wire at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire
    Using library DS3232RTC-master in folder: C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master (legacy)
    exit status 1
    'tmElements_t' does not name a type

  [1]: https://arduino.stackexchange.com/questions/29577/how-to-improve-date-time-control-from-rtc/29581#29581

body:
Consider the Arduino paradigm as a collection of well established (very) sophisticated computing tools. Arguably, the C compiler is the most complex of these tools.  So understanding the compilers output can be challenging at times.

That said, the normal way to approach compiler problems is to solve the 1st error the compiler finds then recompile.  More often then not solving the 1st error will resolve many other errors.

A guess, in this particular case, is that an include file has been omitted.  Find where the type "tmElements_t" is defined and check to see if the include file (a.k.a. header file) where it is defined needs to be included into the source code file where the 1st errors shows up.

Added later...

Ug, the 1st error is not even your code!  It is in the DS323RTC library you downloaded.  We can probably assume this library is working and compiles.  So that leaves the burden on us to find the reason why your code does not compile.  Besides, you can't go back to GitHub saying there is a bug in the library with out trying to solve the problem first.

The 1st stop is to read any readme.txt file at GitHub or the copy of it you downloaded with the library.  We find in the 1st few dozen lines this:

    To use the DS3232RTC library, the Time and Wire libraries must also be included. For brevity, these includes are not repeated in the examples below:

    #include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
    #include <Time.h>         //http://www.arduino.cc/playground/Code/Time
    #include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

So right away we see we need to include Time.h.  If you look in the Time library (another library you need to download if you have not already) you will find that it is where tmElements_t is defined.  It does bother me that Time.h is included after DS323RTC.h.  If you are still having problems try including Time.h first.


body:
As @st2000 said, it's best to start with the first error shown as that error may be causing other errors that will go away once you fix the first one. You should be aware of the difference between warnings and errors. Warnings may or may not be related to the error preventing your code from compiling so I'd just focus on the error at first. So scroll the console window all the way up and then start reading down until you find the first error. If the output is very long you may find it useful to copy the output and paste into a text editor then do a search for the word error, starting from the beginning of the file.

In your compiler output the first error listed is:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h:82:22: error: 'tmElements_t' has not been declared

         static void read(tmElements_t &tm);

                          ^
The first thing we can learn from this is the file where the error occurred:

    C:\jdocs\00_arduino\duinosketches\libraries\DS3232RTC-master/DS3232RTC.h

The next part of the error message is:

    :82:22

This means that the error occurred at line 82, column 22 of the file DS3232RTC.h. This makes it easy for you to find that code in the file. Any decent text editor will show the current line number and column at the cursor.

The next part of the error message is a description of the problem:

    error: 'tmElements_t' has not been declared

Often you may not understand exactly what it means. This is where your favorite search engine comes in handy. You can try searching for "'tmElements_t' has not been declared". The 'tmElements_t' part is very specific to this code so you will get less results but they may lead you to others who have had the same problem and the solutions they found.

Searching for the general error "has not been declared" will give you a broader description of what the compiler is trying to tell you.

Finally is the actual code line:

     static void read(tmElements_t &tm);

                      ^
The carat shows the column number of the error.

Unfortunately the actual bug may often be in previous code so this isn't as simple as it may seem.

Now lets talk about your specific issue. A search for "'tmElements_t' has not been declared" does yield some results from others having similar problems but you will probably find after going through their solutions that none of them fix the error. This is because the error is caused by a recent update to a new version of avr-libc in Arduino IDE 1.6.10/Arduino AVR Boards 1.6.12 and later. This version of avr-libc contains a file named time.h. On a case insensitive operating system such as Windows this will cause

    #include <Time.h>
to include the wrong file, time.h which causes the error since indeed that file doesn't declare tmElements_t. This problem is known to the author of the Time library and he has moved the code to a file named TimeLib.h as a workaround. The file Time.h was left for backwards compatibility. So the solution is to change:

    #include <Time.h>

to:

    #include <TimeLib.h>

I was able to get the TestRTC sketch to compile by just making this change in TestRTC.ino but you may also need to change line 25 of DS3232RTC.h.

I have submitted a pull request to fix this issue to the DS3232RTC repository: [https://github.com/Tecsmith/DS3232RTC/pull/9][1]

EDIT: My pull request has now been merged so the issue can also be solved by installing the updated Tecsmith/DS3232RTC library.

If this solves your problem please also update [your other question][2] so that the people trying to help you there will know it's fixed.

  [1]: https://github.com/Tecsmith/DS3232RTC/pull/9
  [2]: https://arduino.stackexchange.com/questions/29577/how-to-improve-date-time-control-from-rtc/29581#29581


message:
How to use millis()

I'm trying to have a keypad do two one of three things when a key is pressed:

 1. If the 1 is pressed I want LED 1 to blink twice then stay on
 2. If either the 2 or the 3 is pressed I want LED 2 to blink forever
 3. If the # key is pressed I want it to cancel whatever's going on with the other LEDs

How can I use `millis()` to blink forever? Or just blink twice then stay on? When in my blinking should I be checking for another keypress? What's frustrating me is that I know how to do all this with `delay()`, and I've written 70% of the code for it with delay, but if I use delay I don't think it'll be able to check for another key input, will it?

Thanks for any help.

body:
> How can I use `millis()` to blink forever?

The algorithm is essentially as follows:

    if (it_is_time_to_toggle_the_led()) {
        toggle_the_led();
    }

The details are thoroughly covered in the [Blink Without Delay][]
Arduino tutorial. It is essential to understand this technique: as soon
as you have more than one thing to do in your program (here: blink an
LED and monitor button presses), `delay()` is toxic because it blocks
_all_ the program. You should really ban `delay()` from your vocabulary,
except for the simpler single-task programs.

> Or just blink twice then stay on?

For this and your other questions, the canonical answer is “implement a
[finite state machine][]”. I recommend the [Finite State Machine
tutorial][] by Majenko.

In this particular instance, I would probably implement _two_ FSMs, one
for each LED. The first one would have three states: (OFF, BLINKING,
ON), and a counter for the number of blinks. The transition rules:

1. If button 1 is pressed and the state is not BLINKING go to the
   BLINKING state
2. If it is BLINKING and it's time for it to toggle, do it
3. If it is BLINKING and it is switching on for the third time, go to
   the ON state
4. If '#' has been pressed, go to the OFF state.

Or maybe you could split the state BLINKING into BLINKING\_ON and
BLINKING\_OFF.

The second LED would be essentially the same, except for lacking the ON
state and rule number 3.

I am not writing the code, but you may want to take a look at this [code
for automatic door][]. It is an answer to a seemingly unrelated
question, but it gives a good example on how to combine `millis()`-based
timing with a finite state machine. Your program could be written mostly
along the same lines.

[Blink Without Delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[finite state machine]: https://en.wikipedia.org/wiki/Finite-state_machine
[Finite State Machine tutorial]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/
[code for automatic door]: https://arduino.stackexchange.com/a/29137


message:
Does serial speed affect performance of other tasks?

I have explored Google and the Arduino site and this site and cannot find a mention of this, so my guess is that serial is handled by a separate component to the core processing and so different serial communication rates will not affect code performance.

Is this correct?

Where can I find information about how serial passing is handled? For instance, when I call Serial.prinlnt("test"), how does that get to the serial line?

body:
No, it affects code performance always. For how much is dependent on used data types, baudrate, tx buffer size.

**Data types:**

* AVR doesn't have hardware floating point operation support. Software support is super slow, so if you want to print some floats, it will be affecting performance a lot (but it's same as just using it).
* There is no integer division either (except for bit shifts/rotates which is division by powers of two). So printing bytes, integers, longs in DEC base takes some performance.

**Baud rate settings and transmit buffer size:**

Sending data over `Serial` is limited by its speed (baud rate). So if you use common `9600` baud rate you'll be limited by this speed. If you're sending data at higher rate. Transmit buffer gets filled and next `write` into `Serial` will be blocked until another character from buffer is sent.


body:
It depends. Serial data is received into, or sent from, buffers (one for sending and one for receiving). If you have a processor with 1024 bytes of RAM or more, then the buffer size is 64 bytes, otherwise it is 16 bytes. (See the HardwareSerial.h file in your distribution).

If the buffer fills up when sending, it will *block* (that is, the code will wait for the buffer to empty). If it fill up when receiving the extra bytes will be discarded.

If the buffer does not fill up, then the baud rate will not affect performance. That is because data is sent, or received, by an interrupt service routine, in the background.

As a rule of thumb, you can expect data to be sent or received at the baud rate divided by 10. That is because each byte is 8 bits, plus a start and a stop bit (10 bits in total).

So, for example, at 9600 baud you can send 960 characters per second. If you are sending something simple, like a temperature which is 20 bytes, every second, then the baud rate won't affect performance at all. If you are trying to send thousands of bytes per second, it *will* affect performance, because the `Serial.println` will probably block once the buffer fills up.

---

> For instance, when I call Serial.prinlnt("test"), how does that get to the serial line?

If the buffer is not full, then "t" "e" "s" "t" are copied into the buffer, and the code returns immediately. If the buffer *is* full then it waits for it to become not-full.

As an efficiency measure, if you are sending a single byte, and the buffer is empty, then the byte is placed in the hardware register immediately (saving a small amount of time). In this case, if the buffer was empty, "t" would be sent immediately, and "est" would be sent afterwards, as a "byte has been sent" interrupt is raised.1

This is described in the code comments:

    size_t HardwareSerial::write(uint8_t c)
    {
      _written = true;
      // If the buffer and the data register is empty, just write the byte
      // to the data register and be done. This shortcut helps
      // significantly improve the effective datarate at high (>
      // 500kbit/s) bitrates, where interrupt overhead becomes a slowdown.
      if (_tx_buffer_head == _tx_buffer_tail && bit_is_set(*_ucsra, UDRE0)) {
        *_udr = c;
        sbi(*_ucsra, TXC0);
        return 1;
      }
      tx_buffer_index_t i = (_tx_buffer_head + 1) % SERIAL_TX_BUFFER_SIZE;

      // If the output buffer is full, there's nothing for it other than to
      // wait for the interrupt handler to empty it a bit
      while (i == _tx_buffer_tail) {
        if (bit_is_clear(SREG, SREG_I)) {
          // Interrupts are disabled, so we'll have to poll the data
          // register empty flag ourselves. If it is set, pretend an
          // interrupt has happened and call the handler to free up
          // space for us.
          if(bit_is_set(*_ucsra, UDRE0))
     _tx_udr_empty_irq();
        } else {
          // nop, the interrupt handler will free up space for us
        }
      }

      _tx_buffer[_tx_buffer_head] = c;
      _tx_buffer_head = i;

      sbi(*_ucsrb, UDRIE0);

      return 1;
    }

Notice that the byte is not placed in the buffer at all if it is empty, and nothing is being sent.

---

For more information see my [question and answer about serial processing](https://arduino.stackexchange.com/questions/19756/how-does-serial-communications-work-on-the-arduino).

---

1. Strictly speaking, after discussing this in the comments with Majenko, the interrupt that is raised is really that the hardware "send" buffer is empty. When the send buffer empties then the interrupt is called so that the interrupt code can put a new byte into it.


message:
FastLED and Neopixel Help

I'm in the process of trying to create a "Aurora Glow" effect using a Particle Photon and a Neopixel ring.

I have the code fully working using a single Breadboard-friendly NeoPixel however when upgrading this to a NeoPixel Ring (16 LED) the code does not run as expected

The current working code for a single NeoPixel can be found here: http://pastebin.com/Yj1cywpx

It was my assumption that i could change Line 33 from one LED to Sixteen e.g.:

    FastLED.addLeds<NEOPIXEL, 6>(&led, 1);

to

    FastLED.addLeds<NEOPIXEL, 6>(&led, 16);

However when I run this code rather than all NeoPixels cycling through the Aurora Colours, only the very Top LED does and rest are either off or a static colour (e.g. https://i.stack.imgur.com/6rY38.jpg)

Could someone please advise what i missing? Apologies if this is a "Noob" question but this is my 2nd Arduino project and I cannot understand why this would not work.

Thanks

body:
Never used neoPixels in arduino before so this is a complete guess based on reading the code but it looks like you are only setting the colour of the first LED.

Try creating 16 LED colours:

    CRGB led[16];

and then setting them all:

    for (int i = 0;i<15; i++) {
      int colourIndex = index + i;
      if (colourIndex > 15)
        colourIndex -= 15;
      led[i] = ColorFromPalette(auroraPalette, colourIndex , 255, LINEARBLEND);
    }

edit - as @rDg indicates in his answer

    FastLED.addLeds<NEOPIXEL, 6>(&led, 16);

becomes

    FastLED.addLeds<NEOPIXEL, 6>(led, 16);

since led is now an array not a single value

Finally I think paletteSize should only be 16 not 5*16, you only have 16 colours in there.


body:
In addition to the above, you need to tweak your addLeds line:

    FastLED.addLeds<NEOPIXEL, 6>(led, 16);


message:
Ensuring specific frequency at specific time?

I, at the moment am trying to come up with a simple way where I can program an Arduino to provide a step signal with a given frequency, at a specific time.

The frequency has to be ramped up, and within a time duration of 10 seconds shall the frequency go from 0 Hz to 48000 Hz.

How do I ensure both the specific time of when the frequency occurs, and the specific frequency of the step signal?

Signal has to be used to driver a stepper motor.

**Edit: Code current:**

So i currently wrote this piece of code:

    int timestep = 1;
    while(1)
    {
      unsigned long startTime = millis()
      while(startTime != 500)
      {
        digitalWrite(step_pin,LOW);
        delayMicroseconds(208/timestep);
        digitalWrite(step_pin,HIGH);
        delayMicroseconds(208/timestep);
      }

      timestep++;
    }

For each 0.5s should the frequency be doubled..  would this work?

**Edit 2.0:**

I made an new implementation using @EdgarBonet 's answer, and with the help of Timer1 [library][1] that arduino provide (I guess?).

.h file

    #ifndef stepper_motor_h
    #define stepper_motor_h

    #include "Arduino.h"
    #include <TimerOne.h>

    #define step_pin  13
    #define dir_pin   12
    #define en_pin    11
    #define max_step  200

     class stepper_motor
    {
      public:
        stepper_motor();
        void step_pwm();
        static void callback();
        TimerOne timer1;
      private:
        //uint32_t period;
        bool alive_bool;
        //int step_count;
        bool position_bool;
    };

    #endif

.cpp file

    #include "stepper_motor.h"

    int step_count = 0;
    uint32_t period = 40825UL << 16; // 20412,5 us fixed point arithmetic time = 0

    stepper_motor::stepper_motor()
    {
      //pinMode(BUILTIN_LED,OUTPUT);
      pinMode(step_pin, OUTPUT);
      pinMode(dir_pin, OUTPUT);
      pinMode(en_pin, OUTPUT);
      alive_bool = true;
      position_bool = false;
      step_count = 0;

    }

    static void stepper_motor::callback()
    {
      if (step_count < 240)
      {
        uint32_t new_period = sqrt(2 * step_count / 4.8);
        period -= new_period;
        step_count++;
      }
      else
      {
        return;
      }
    }

    void stepper_motor::step_pwm()
    {

      digitalWrite(en_pin, HIGH);

      delay(0.005);

      digitalWrite(dir_pin, HIGH);
      //LOW  - Move towards the sensor
      //HIGH -  Move away from the sensor

      delay(0.005);

      timer1.initialize(period);
      timer1.attachInterrupt(callback);
      timer1.pwm(step_pin, 512);

    }

  [1]: https://code.google.com/archive/p/arduino-timerone/downloads

body:
There are three points:

1. Try to work in the terms of pulse duration. 48 000 Hz will give say 167 ticks for 8 MHz clock (83 ticks for HIGH level on active pin and 83 - LOW). Division on fly is very time consuming, so better to use period instead of frequency. 0 - switch the timer off. 1 Hz - 8 000 000 ticks (4000000 for High and 4000000 for LOW).

2. As I understand the stepper motor will have to drive some load, so acceleration needed depends not only on the parameters of motor itself but on the total mechanical system. So, to calculate needed data from the scratch will be rather difficult and inaccurate. Better try to calibrate the system. Tat will take a piece of job but will be more accurate.

3. You do not need to make smooth decrease of period but you can use several predefined steps. This will give you two arrays `t[i]` for period to be set in timer and `d[i]` - number of steps, done with this period. The total time for the given period will be `d[i]*t[i]`. The total time of acceleration then will be the simple sum of time slices in the sequence `i` from 0 to max. So you can get it rather accurately.

It will take at least two timers - one for the period setting, other for counting periods in a time slice. After one time slice is finished you just increment array index and load new data in timers. Calibration will take to define best real data for array `t[]` and `d[]`.

If you will hold in `t[]` half-periods, then you need to double values in `d[]`, or taking values from `t[]` you can divide them by 2 (it's a simple shift so it takes little time) for one half-period is HIGH and next is LOW. The decision is up to you.


body:
Generating a linear frequency ramp with accurate timings is not an easy
task. I am providing here only a partial answer, where I first go
through the math of the problem, then give some ideas for the
implementation.

## The math

We are dealing with a frequency-modulated signal, with the frequency
ramping linearly from _f_ = 0 at _t_ = 0 up to a
maximum _f_ = _f_M at
_t_ = _t_M. Specifically, we have
_f_M = 48 kHz and
_t_M = 10 s.
Then, the instantaneous frequency is

_f_(_t_) = _a_ _t_

where _a_ = _f_M/_t_M = 4.8
kHz/s is the “acceleration” of the pulsed signal.

Let's define the “integrated frequency” as

_n_(_t_) = ∫ _f_(_t_) dt = _a_ _t_²/2

This quantity can be interpreted as the number of cycles completed at
time _t_, except that it is a continuous variable. The first cycle
starts when _n_ = 0 and ends when _n_ = 1, the next
cycle starts when _n_ = 1 and ends when _n_ = 2, and
so on. The output signal would be high when the fractional part of _n_
is between 0.25 and 0.75 (or maybe between 0 and 0.5, depending on your
choice of initial phase).

From here, we can calculate at what time each cycle should start:

_t_(_n_) = √(2 _n_/_a_)

and, by successive differences, the length of each cycle:

    n       0     1       2       3      ... 239,998    239,999    240,000
    t       0     20,412  28,868  35,355 ... 9,999,958  9,999,979  10,000,000
    length   20,412   8,455   6,488      ...        20.833     20.833
    diff          -11,957 -1,967  -1,018 ...            -0.000043
    approx        +81,650 -1,408  -913   ...            -0.000043

In the table above, all times are in microseconds. The lines are:

* _t_: time
* length: length of one cycle
* diff: difference between lengths of successive cycles
* approx: approximated formula for that difference

The columns are staggered because each cycles spans the duration between
two successive values of _t_, and duration differences are computed
between successive cycles. The approximated formula is based on the
Taylor expansion:

T(_n_+1) − T(_n_) ≈ dT/dn + 1/2 d²T/dn² = −aT³(1 − 3/2 aT²)

where T = 1/_f_, the instantaneous period, approximates the
length of one cycle. The approximation is not good for the very first
cycles, but it converges pretty fast to the correct value.

## Implementation

I did not write an implementation, so I am giving here only some ideas
on how to do it.

I would use Timer 1 of the Arduino Uno, in one of the modes that allows
frequency-modulation, i.e. a PWM mode where the counter TOP is set by a
register (mode 8, 9, 10, 11, 14 or 15). I would set the prescaler to 8
in order to allow for the maximum required period length. The period
resolution would then be:

* 8 CPU cycles = 0.5 µs in modes 14 or 15 (fast PWM)
* 16 CPU cyels = 1 µs in the other modes

It could be noted that single-cycle resolution is possible with the
prescaler set to 1, but the first 5 cycles are too long for this
setting. Maybe the prescaler could be changed after the fifth cycle, but
it would be tricky to do so without any glitch.

The timer overflow interrupt would fire at the end of each cycle, and
it's ISR (namely `TIMER1_OVF_vect`) would be responsible for updating
the timer period in order to make the next cycle shorter than the one
just elapsed. It would do something like

    period -= delta(period);

The period should be computed with 32-bit arithmetic, because the
changes get tiny by the end of the ramp. Only the 16 most
significant bits of the computed period would actually be written to the
timer register. The `delta()` function should be inlined and fast. I may
try the approximation from the previous section implemented in
fixed-point. Or maybe just a table lookup using only the most
significant bits of the period as an index, with the table in PROGMEM.

For details on how to actually program the timer, see
the [datasheet of the ATmega328P][], section 16.

------------------------------------------------------------------------

**Update**: The following algorithm seems to work well. At least in
simulation, I did not put it inside an ISR. It assumes fast PWM, i.e. a
0.5 µs timer resolution. It remembers the current value of delta
and divides it by 2 each time the period falls below some threshold. The
computed _f_(_t_) is almost as smooth as you can expect given the
limited resolution of the timer.

    uint32_t period = 40825UL << 16;  // 1st cycle is 20412.5 us
    void update_period()  // should be in ISR(TIMER1_OVF_vect)
    {
        static const uint16_t thresholds[] = {
                17633, 13309, 10229, 7954, 6230, 4905, 3873, 3063,
                2426, 1923, 1525, 1211, 960, 762, 605, 480, 381,
                302, 240, 190, 151, 120, 95, 76, 60, 48};
        static uint16_t threshold = 29000;
        static uint8_t index = 0;
        static uint32_t delta = 6UL << 27;

        uint16_t period_h = period >> 16;
        if (period_h <= 42) return;  // final frequency achieved
        if (period_h < threshold) {
            threshold = thresholds[index++];
            delta >>= 1;
        }
        period -= delta;
        // set the timer period register to (period >> 16) - 1.
    }

[datasheet of the ATmega328P]: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_datasheet.pdf


body:
As mentioned in comments and other answers, using timer 1 for hardware-timed bit toggling is likely to produce better results than code using delays based on calls like `delayMicroseconds()`, primarily because of overhead causing poor resolution or jitter.

Using timer 1 in a PWM mode offers an advantage: loading of the OCR1A register is double buffered in PWM modes.  This makes it possible to smoothly transition from one frequency to another without glitches due to setup delays.  The code shown below (program `freqSweep.ino`) illustrates one way of steadily ramping the period of a waveform.  The *initial count, delta count*, and *number of steps* parameters `ic, dc, ns` also are double buffered, with the first set loaded via `rampInit ()`, and new sets loaded opportunely from time to time via `rampNext ()`.

In operation, the ramper causes timer 1 to produce a waveform with half cycles of lengths `ic, ic+dc, ic+2dc, ... ic+(ns-1)dc`.  That is, it generates `ns` steps of varying lengths, using timer 1 interrupts to trigger its execution in the background.  While the ISR produces a ramp of cycles, the user's `loop()` code can be computing parameters for the next ramp.  Note, if `dc>0`, periods grow larger so the frequency ramp descends.  If `dc<0`, periods grow smaller so the frequency ramp ascends. If `dc==0`, the ramp is flat.  Note, `ic` and `dc` are 32-bit fixed-point numbers, with 16 binary places.  Thus, while hardware only generates time intervals with integral numbers of cycles, the ramper software works with fractional values, so `dc` can have values like 0.5, 3.375, .076171875 (39/512) etc.

By generating a seamless series of small ramps, one can accurately approximate larger patterns of frequency ramps.  For example, to generate a frequency-linear ramp from say 100 Hz up to 48 KHz in 10 seconds, one might divide that time into 100 parts.  If f(t) denotes the frequency desired at time t, one would then (for each 0.1 second time step) compute half-periods p and q corresponding to frequencies f(t) and f(t+0.1).  About n = 0.1*f(t+0.05) cycles are available in 0.1 seconds for frequencies between f(t) and f(t+0.1), or about `ns` = 2*n half-cycles.  Choose `dc = (q-p)/ns` [using 32:16 fixed point arithmetic, and noting that `dc` can be negative] to smoothly ramp from frequency f(t) to f(t+0.1) in `ns` steps that take about 0.1 seconds total.  0.1 seconds, or 100 ms, is enough time to calculate and load a new set of parameters.  See program comments (under the heading *General form of use of ramper*) re computing parameters.

Here is the example program:

    // Sweep a frequency, on dig. pin 7, PD7 - jw 27 Sep 2016
    #include <Streaming.h>

    enum { outpin=7, mOutpin=1<<7 }; // Arduino dig. pin# & its bit mask
    void setup() {
      pinMode(outpin, OUTPUT);
    }

    long RAMdcl, RAMdcn; // dc is signed to allow ramps up or down
    unsigned long RAMicl, RAMicn;
    unsigned int RAMnsl, RAMnsn;
    volatile unsigned int RAMrampsDone; // Number of ramps done so far
    volatile byte RAMsendPars; // Flag is 1 when ok to send params

    void rampInit(unsigned long ic0, unsigned long dc0, unsigned long ns0, byte clockSource) {
      /* clockSource should be a 3-bit number, from 0 to 5:
       ..Bits.. ....Effect....   [See Table 16-5, p. 134 in specs]
        0 0 0   No clock source (Timer/Counter stopped).
        0 0 1   IOclock / 1    (No prescaling)
        0 1 0   IOclock / 8    (From prescaler)
        0 1 1   IOclock / 64   (From prescaler)
        1 0 0   IOclock / 256  (From prescaler)
        1 0 1   IOclock / 1024 (From prescaler)
      */
      TIMSK1 = 0;   // Turn off timer 1 interrupts
      // ic and dc (initial count and delta count) values
      // are 32:16 fixed point values; ie with 16 binary places.
      RAMicl = RAMicn = ic0;
      RAMdcl = RAMdcn = dc0; // Set initial param values
      RAMnsl = RAMnsn = ns0;
      RAMrampsDone = 0;  // No ramps done yet
      RAMsendPars = 1;  // Next param set can load

        // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
      TCNT1 = 0;     // Zero the counter
      TCCR1A = 1<<WGM11 | 1<<WGM10; // for Fast Pwm with TOP from OCR1A
      OCR1A = (uint16_t)(RAMicl >> 16); // Initial TOP = integer part of icl
      TCCR1B = 1<<WGM13 | 1<<WGM12 | // for Fast Pwm with TOP from OCR1A
               clockSource;    // Start timer 1 with selected prescale
      TIMSK1 = 1<<TOIE1;    // Enable timer 1 overflow interrupt at TOP
    }

    // timer 1 overflow interrupt handler
    ISR(TIMER1_OVF_vect) {
      OCR1A = (uint16_t)(RAMicl >> 16); // Update TOP with integer part of ic
      PIND = mOutpin;       // Toggle the output pin, eg dig pin 7, PD7
      // (Output bits toggle when a 1 is written to their input port bit)

      RAMicl += (unsigned long)RAMdcl;  // dc is signed but we need bare bits
      --RAMnsl;
      if (!RAMnsl) {  // Go on to next section?
        RAMicl = RAMicn;
        RAMdcl = RAMdcn;  // Set next param values
        RAMnsl = RAMnsn;
        ++RAMrampsDone;  // We are in the last half cycle of section
        RAMsendPars = 1;  // Ready for next param set
      }
    }

    // rampNext() busy-waits until it can load new param values
    void rampNext (unsigned long ic, unsigned long dc, unsigned int ns) {
      while (!RAMsendPars) {}
      RAMsendPars = 0;
      RAMicn = ic;
      RAMdcn = dc;  // Set next param values
      RAMnsn = ns;
    }

    // rampStop() stops the ramp-processor, right now
    void  rampStop() {
      TIMSK1 = 0;   // Turn off timer 1 interrupts
      RAMrampsDone = RAMsendPars = 0;
      digitalWrite(outpin, LOW); // Turn off output bit
    }

    /*
      // General form of use of ramper:
      ...
      rampInit(icj, dcj, nsj, scaleBy1);  // Send first param set
      for (byte j=0; j<rampSections; ++j) {
        // Compute next param set ...
        icj = ...
        dcj = ...
        nsj = ...
        // Do other stuff here
        // ...
        // rampNext will busy-wait while sendPars is clear
        rampNext (icj, dcj, nsj);
      }
      // Busy-wait while last ramp finishes
      while (RAMrampsDone <= rampSections) {}
      rampStop();  // Stop the ramp-processor
    */

    // Example: Play a sound with 5 ramp parts in loop(), with brief pauses
    void loop() {
      enum { scaleBy1=1};
      unsigned long icj, dcj;  // My ramp param calc vars
      unsigned int nsj=1000;  // # of steps per ramp
      icj = ((unsigned long)1600)<<16; // ic = initial count
      dcj = ((unsigned long)1)<<16;  // dc = step size
      nsj = 5000;
      rampInit (icj*3, dcj/2, nsj, scaleBy1);
      rampNext (icj, dcj, nsj/3);
      rampNext (icj*2, -dcj, nsj/2);
      rampNext (icj*2, -dcj, nsj/2);
      rampNext (icj, dcj, nsj/3);
      while (RAMrampsDone < 5) {};
      rampStop();   // Stop the ramp-processor
      delay(2500);   // silence-separator
    }


message:
Control Arduino through ethernet. How to contact from outside network and securely

I'm new to Arduino so please bear with me if my question is too simple or broad (I did try and research it) or guide me if it belongs elsewhere (networking forum?)

I would like to be able to control my Arduino remotely.  By remotely, I mean I would like to be able to access it over the internet.  I've done some research and know about the Arduino Ethernet Sheild (see:  https://arduino.stackexchange.com/questions/432/how-can-i-connect-to-an-arduino-using-wifi?rq=1)

But I'm a newbie and it's not clear to me how I'm going to make my device "discoverable" from outside my local network.  I gather it involves "opening a port on my router"  Can someone expand on this or provide an example/tutorial? If I can do this, it would also be nice if there was some security so that not just anyone could control my robotic killer dog or whatever :).  I would think these are both common desires,  and there is probably tons of material (maybe even tutorials) but perhaps because I'm new to Arduino, I'm having a hard time finding material.

I thought a nice first step would be to have my Arduino Uno board connected to a single LED.  If I could then have a simple webservice on it, I could connect via my phone from work with a http post request.  Of course, I'd need someone at home to verify the led went on/off (or set up a camera for remote access).

Let me know if I can provide more detail or clarifications.  And Thank you!

Dave

body:
The easiest way to do this is to use [Blynk][1], an Internet Of Things (IoT) web service that includes an Arduino library, apps for iOS and Android, and a central server that the smartphone app and the Arduino both connect to. Since both connections are outgoing (and matched up by the Blynk server), each one works just fine from behind NAT routers without any ports needing forwarding. See Blynk's demo video for how to create a basic working app in 5 minutes (including your described LED controller and much more). Ok, I'll admit that starting from cold, it takes most of us a little longer than 5 minutes to get it going, especially if you like to read about and understand what you're doing as you do it. But it will still be minutes, not hours. This is the quickest, most painless way to get an IoT device up and running.

That basic app (which can read & write to ports, PWM, and A/D) is then extensible to work with your own code & hardware. The functions available lend themselves to just what you are looking to do, with the possible exception of uploading the images it takes. And the Arduino itself isn't really well suited to that task, given its memory constraints.

Update:
I use the ESP8266 like the one you linked to. They're cheap and easy to use but with a gotcha: they are 3.3v only on both power & signal lines, which can be a challenge when working with a 5v MCU board. Here's how to wire one up for a 5v Arduino. Note the dedicated 3.3v regulator; the Arduino's on-board 3.3v supply isn't sufficient for an ESP8266:

[![enter image description here][2]][2]

For quick & dirty, you can wire this up on a breadboard. Ultimately you'll want something more stable (mechanically) than breadboard wiring. I made up a few 5v ESPs on strip-board (aka Vector board or Vero board), but that's another project:

[![enter image description here][3]][3]

--

\*\* (Disclaimer: I have no connection to the organization other than as a happy user/experimenter.)

  [1]: http://blynk.cc
  [2]: https://i.stack.imgur.com/6Xl9X.jpg
  [3]: https://i.stack.imgur.com/VTpQf.jpg


message:
Function only taking the first 4 elements of a character array

I'm writing a function for my arduino program that takes a character array of any size and will mark all the characters that aren't in the alphabet by changing their value to '1'.

I have a switch variable (foundSym) that will turn to 0 if the character IS part of the alphabet. At the end of my first for loop if the switch never changed, that means the character was NOT a letter and will be marked. Note I also don't want to mark space characters (' ').

The issue I have is every array I pass into the function will only have a length of 4, no matter the size.

I've checked the length of each array before it enters the function and when it is in the function, everytime the size gets shortened to 4 elements!

Here is my function...what am I doing wrong??

    void markSymbols(char str[]){
      for(int i = 0; i<sizeof(str); i++){
        int foundSym = 1;
        for (int j = 0; j<26; j++){
          if (str[i] == alphabet[j]) {
            foundSym = 0;
            break;
            }
        }
        if (str[i] == ' ') foundSym = 0;
        if (foundSym == 1) str[i] = '1';
      }

    }

body:
You are passing a pointer (`char str[]`) and the `sizeof` operator is giving you the size of that pointer (4 bytes it appears in your case - on some Arduinos it would be 2 bytes).

The length of a character array is found by using `strlen` - assuming the string is terminated by a null (0x00).


body:
I think this will do the same as your code.  I understand it doesn't directly answer the question, but I hope it shows you an alternative way of doing it using the library functions.  But they are very difficult to find unless you know about them already.

    void markSymbols(char* str)
    {
      for(int i = 0; i < strlen(str); i++)
      {
        if (! ((isAlpha(str[i]) || (str[i] == ' ')))
        {  // If the character is not an letter of the alphabet (upper and lower case) and it is not a space (char 32).
            str[i] = '1';
         }
      }
    }


message:
Cant connect to localhost

I have a project um Visual Studio with a GET method:
http://localhost:4548/Arduino/request?id=12&user=username&pass=password
When I open it in my browser, it works fine
But I want http GET in my Arduino, using the WebClient exemple:

**EDIT**
I used solution number 1. of @Matt and it worked:
Get a full licensed copy of IIS.
And this is the code after all:

    #include <SPI.h>
    #include <Ethernet.h>

    //Informacoes de endereco IP, gateway, mascara de rede
    byte mac[] = { 0xA4, 0x28, 0x72, 0xCA, 0x55, 0x2F };
    byte ip[] = { 192, 168, 1, 200 };
    byte gateway[] = { 192, 168, 1, 1 };
    byte subnet[] = { 255, 255, 255, 0 };
    byte server[] = { 192, 168, 1, 100 };

    EthernetClient client;

    void setup() {

      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }
      // give the Ethernet shield a second to initialize:
      delay(1000);
      Serial.println("connecting...");

      // if you get a connection, report back via serial:
      if (client.connect(server, 80)) {
        Serial.println("connected");
        // Make a HTTP request:
        client.println("GET /myProject/request?id=12&user=username&pass=password HTTP/1.1");
        client.println("Host: 192.168.1.100");
        client.println("Connection: close");
        client.println();
      } else {
        // if you didn't get a connection to the server:
        Serial.println("connection failed");
      }
    }

    void loop() {
      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();

        // do nothing forevermore:
        while (true);
      }
    }

My Serial displays as connected, but the http GET does not work
Am I missing something?

body:
Visual Studio's web server is restricted to only servicing clients on the machine it is running on.
To do what you want to do there are a number of things you can do.

 1. Get a full licensed copy of IIS. (Please stop laughing)

 2. Get a version of Apache (might affect your server code and will take a while to setup)

 3. Write yourself a 'proxy server'.  I think if you write a program to run on you PC that creates a socket that listens to port 8080 and forwards any messages on to the VS Web Server (use `"C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.EXE" /port:6666 /path:C:\WebServer\Root` to start it on a fixed port) and forward any replies back to you client.


message:
Can I power two 5V with Arduino powered with 9V power adapter?

I have a setup where I have a 5V IR receiver and 5V relay board and Arduino Uno.

I am currently powering the Arduino from the PC USB and both the IR receiver and the relay board from the Arduino. And it works fine.

Now I want to know how it would work when I power it with a 9 volts wall adapter. Will the voltage be enough for both the IR receiver and the relay board? And will Arduino work fine?

body: If you're connecting the 9V wall adapter to the Power socket of the arduino, then sure its going to work. It can supply both for the IR and relay boards.


body:
The voltage will be fine - as long as you plug it into the DC barrel jack, and don't try to wire directly to the 5V pins. The barrel jack has a voltage regulator on it that will convert 7-12V down to the required 5V.

But there's a second reading that you need to look at, not just voltage. The 9V adapter will also have a current rating expressed in milliamps (mA) or amps (A, which is 1,000 mA). The Arduino needs around 25 mA to do its thing, and your adapters add to the total current - maybe 20 mA each again. So if your adapter only provides 50 mA, it won't be able to provide enough current and the system won't work.

The USB port provides 5V, but it also provides up to 500 mA, which is more than enough for the job. If your wall adapter is 100 mA or above, that should be enough. And unlike voltage, a larger number for current is better - that's its maximum capacity of supply, rather than something that will burn out the equiment!


message:
Referencing local libraries from higher dir levels

How can I include libraries not contained in any direct subdirectories of a sketch, using the Arduino IDE?

I want my project structure to look like this:

    Project
    └> MCUa
       └> MCUa.ino
    └> MCUb
       └> MCUb.ino
    └> Libraries
       └> TimerLib
          └> TimerLib.cpp
          └> TimerLib.h
So in my project two sketches `MCUa` and `MCUb` share a resource, namely the library `TimerLib`.

I've tried to include the libraries like this:

    #include "../Libraries/TimerLib/TimerLib.h"
or this:

    #include "./../Libraries/TimerLib/TimerLib.h"
But none of them will compile - this is the error message:

    fatal error: ./../Libraries/TimerLib/TimerLib.h: No such file or directory
     #include "./../Libraries/TimerLib/TimerLib.h"
                                                  ^
    compilation terminated.
    exit status 1
    Error compiling.

If I put the library directly in of the directories and reference it like this:

    #include "./Libraries/TimerLib/TimerLib.h"
Everything goes well.

Using an absolute path like in [this answer][1] is not a possibility in this case, as it should compile out of the box for others, without modifying any absolute paths.

  [1]: https://arduino.stackexchange.com/a/9575

body:
The problem with a relative path for an include is that it has to be relative to one of the predefined list of existing include directories. This includes:

* Compiler include locations
* The Arduino core files
* The locations of other included libraries
* The build folder for the sketch

What it does not include is the location of the sketch, so you cannot specify a location relative to the sketch itself.

Further, even if you could, the compiler wouldn't know what library it was supposed to be referencing so, while the header would be found, any source files associated with it would be ignored and linking would fail miserably.

Instead you will have to place the library in a standard library location, such as the libraries folder in your sketch book.


message:
Arduino Due randomly slows down, serial communications stops

I've got an Arduino Due connected to a Raspberry Pi via Serial3. The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours. Using an oscilloscope, I can see that the Pi keeps transmitting to the Due, but there is no response from the Due. I'm also getting the Due to echo everything it gets from the Pi to Serial, which is connected to my PC. I can see that the Due will stop echoing characters mid way through receiving a message from the Pi.

I then set one of the pins as an output and just keep toggling that regularly. When the Due is waiting for data from the Pi, this signal has a frequency of about 100Hz, i.e. a period of 10ms. I have a counter that goes from 0 to 1000 to control this frequency somewhat. When this error happens and communications stops, I can see that the pulses now have a period of 2.14 seconds, i.e. 214 times slower.

I'm using [Arduino-MemoryFree][1] to check for memory leaks but I haven't found any problems yet and I don't seem to be running out of memory. In case it matters, I'm also using the [ArduinoJson][2] library. Arduino IDE version is 1.6.7, I've updated the Arduino SAM Boards package to version 1.6.9 (problem was present before the update as well).

Could someone please advise me on what could be causing this slow down?

  [1]: https://github.com/mpflaga/Arduino-MemoryFree
  [2]: https://github.com/bblanchon/ArduinoJson

body:
> The Due will randomly stop sending data to the Pi after a few days, or sometimes after several hours.

Here is the typical manifestation of [heap fragmentation](https://cpp4arduino.com/2018/11/06/what-is-heap-fragmentation.html) in an Arduino sketch.

Solution:

1. Remove as many `String`s as possible and replace them with `char[]`
2. Use a `StaticJsonBuffer` instead of a `DynamicJsonBuffer`

If you remove all the `String`s and use a `StaticJsonBuffer`, your program will run without any heap. No heap, no fragmentation! Not only it will be **more reliable**, it will also be **smaller** and **faster**.

**If you must** use `String`, then call [`String::reserve()`](https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/reserve/) to make sure the size is the same at each iteration. Indeed, [repeated allocation of the same size doesn't increase fragmentation](https://cpp4arduino.com/2018/11/06/what-is-heap-fragmentation.html).


message:
Errors seen whilst compiling with AdaFruit Motor Shield ("invalid library")

Whenever I compile a sketch, change the **Tools > Board** selection, or open/close Boards Manager/Library Manager I get the following message in the console:

    > WARNING: Spurious .github folder in 'Adafruit Motor Shield library' library
    > WARNING: Spurious .github folder in 'Adafruit Motor Shield V2 Library' library
    >
    >
    > Invalid library found in
    > C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master:
    > C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master
    > Invalid library found in C:\arduino-1.6.8\libraries\robotarm:
    > C:\arduino-1.6.8\libraries\robotarm Invalid library found in
    > C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master:
    > C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master
    > Invalid library found in C:\arduino-1.6.8\libraries\robotarm:
    > C:\arduino-1.6.8\libraries\robotarm

body:
Arduino IDE 1.6.6 and higher are picky about what you have in your libraries folders. There are two general valid library formats, the old "pre-1.5" format and the newer 1.5 format, the specification of which is at [https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification][1].

Any folder in any of the Arduino libraries folder that doesn't follow a valid library format will cause the "Invalid library" message. Common causes of this issue are:

 - Putting a sketch folder in the libraries folder. Libraries may
   contain example sketches but a sketch by itself is not allowed.
 - Libraries that are in a subfolder, rather than the library folder
   being in the root of the libraries folder as required.

Now lets look at your specific messages:

    Invalid library found in C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master: C:\arduino-1.6.8\libraries\Adafruit-Motor-Shield-for-Arduino-master

By looking at the [Adafruit-Motor-Shield-for-Arduino repository][2] we see that it's not a library but the PCB design files for the shield and thus has no business being in the libraries folder. Please move it to a different location.

    Invalid library found in C:\arduino-1.6.8\libraries\robotarm: C:\arduino-1.6.8\libraries\robotarm

Without being able to see what's in this folder I can't say exactly the problem. If you will provide a directory listing I could update this answer with specific directions. As it is now, that folder is doing you no good in the libraries folder.

  [1]: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification
  [2]: https://github.com/adafruit/Adafruit-Motor-Shield-for-Arduino


message:
Do I need an Arduino for BLE?

I have built a prototype that uses RedBear Lab's Blend micro board (http://redbearlab.com/blendmicro/). The board combines Arduino and a BLE chip (Nordic nRF8001). The application is fairly simple

1. iPhone finds and connects to BLE chip
2. When user presses a button on iPhone a message is sent to the Blend Micro board
3. Based on the message (3 choices) the Arduino reads analog input from one of the pins
4. The reading is passed back to the phone via BLE

Everything works well. My question is

1. If I were to evolve this into something that can be taken closer to production, do I need the arduino? Seems like the Arduino is only adding a small amount of value in interpreting the message from phone and transmitting the reading
2. If I don't need Arduino, how do I program the BLE chip (Nordic nRF8001) directly? I have seen some kits on the internet and they all seem much more complex than programming Arduino.

I am a newbie to H/W - deep background in S/W engineering - but definitely motivated and interesting in making my project a reality. Advice and guidance are appreicated.

body:
The nRF8001 can not run custom code, so you need an external microcontroller to use it. However, the nrf5 series (for example [nrf51822][1]) has a microcontroller and can run custom code.

Nrf5 is Arduino compatible thanks to [sandeepmistry's nrf5 arduino core][2].

You will need a programmer though, since the nrf51822 uses swd programming. References to recommended programmers are available [here][2].

  [1]: https://www.nordicsemi.com/eng/Products/Bluetooth-low-energy/nRF51822
  [2]: https://github.com/sandeepmistry/arduino-nRF5


message:
Read speed between two ultrasonic sensors

I'm new to Arduino and in need of help for this small project.

I'm trying to build an Arduino code that reads the speed of an object passing through two ultrasonic sensors. The plan now is to ping the first ultrasonic sensor once an object passes. The second sensor will then activate and wait for the object to pass by. The time it takes to reach the second sensor will be given into the equation.

Speed will be calculated by the distance between the two ultrasonic sensors divided by the time for the object to reach the second sensor. I would like to display the speed if possible on my computer screen.

Here is my code so far. Any help will be appreciated:

<!-- language: lang-cpp -->

    int trig1 = 3; //Trig 1
    int trig2 = 4; //Trig 2
    int echo1 = 5; //echo1
    int echo2 = 6; //echo2
    int ECHO1;
    int ECHO2;
    double first_time;
    double second_time;
    double final_time;
    double speed;

    void setup()
    {
       pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
       pinMode(trig2, OUTPUT);  //sets the digital pin 4 as output
       pinMode(echo1, INPUT);  //sets the digital pin 5 as input
       pinMode(echo2, INPUT);  //sets the digital pin 6 as input
    }

    void loop()
    {
      ECHO1 = digitalRead(echo1);

      while (ECHO1 == 0)
      {
        digitalWrite(trig1,HIGH);
        delay(100);
        digitalWrite(trig1,LOW);
        ECHO1 = digitalRead(echo1);
      }

      first_time = time();

      ECHO2 = digitalRead(echo2);

      while (ECHO2 == 0)
      {
        digitalWrite(trig2,HIGH);
        delay(100);
        digitalWrite(trig2,LOW);
        ECHO2 = digitalRead(echo2);
      }

      second_time = time();

      final_time = second_time - first_time;

    }

body:
There are several issues with these ultrasonic modules and your code:

* How fast are these objects moving? If you don't have any reflection, it'll take almost 20ms for one measure. So precision will be low.
* What if the object is moving in oposite direction?
* What if the object stucked between?

and so on.

Anyway Laser interrupter circuit (or similar) would be much more suitable for this job.

Or if you want to use ultrasonic, you can use Doppler effect. But it's not possible with those `PING)))` modules (or clones).


body:
If I understand correctly you are using the ultrasonic sensors like light barriers.

Measuring speed with ultrasonic would be done by sending the sound towards the object of interest and measuring the time for the reflected sound. The traveling speed of sound in air is somehow a [constant][1]. You will get the distance of the object * 2. With two measurements in a defined time period you are able to determine the speed of the object.

When using light barriers (infrared) I would try to trigger interrupts with the photo diodes and measure the time between the triggerings like you described. If hooked to the same interrupt the direction of the object should be irrelevant. If two interrupts are used even the direction is known.

  [1]: https://en.wikipedia.org/wiki/Speed_of_sound


message:
Is there a portable timer interrupt library?

I have a need for timer interrupt (for the sake of this exercise - say I need to execute something every second)

I found code in many places on the internets that does this using ISR for 328/Uno.  (or specifically for other chips) But of course that does not work on other chipsets.

Is there a **portable** timer library that works across many/most/all arduino boards/chipsets?

For now it is a simple project - I have no other motors or tones, etc.

In my current project I have conditional compiles for different chipsets, to set up a callback/interrupt but would rather use a library that hides this all.

body:
I think it would be hard, or impossible, to make such a library. Already there are problems with pin-change interrupt libraries, and Software Serial (which uses pin-change interrupts).

Plus, to have a generic "callback" might tempt people to do things which they shouldn't anyway in an ISR, like do serial printing.

Let's say you choose to use a spare timer (eg. Timer 1). You have the issue now that you won't be able to do (some) PWM output because that uses Timer 1.

The closest would be to lever off the existing `millis()` code and just have a test in `loop` to see if the time interval is up, and then call a function - however that wouldn't be an ISR.


message:
use only one input pin in L293?

I have an L293 motor driver chip, in which the two input pins are used in order to turn the motor forward or reverse, or stop it. So I wοnder if I could use only one input pin, ...

**For running mode:** Since `Input1` should be the opposite of `Input2`, why not sending a signal from `Input1` to `Input2` via a hex inverter?

**For stop mode:** why not just sending `analogWtite(Enable, 0)` to Enable pin?

That way I could save an extra Output pin from Arduino. Do I lack some important detail?

My question goes the same for all the L29x family.

body:
A H-Bridge has 3 modes of operation *in addition to disabled*. The **EN**able pin, when driven low, disconnects the power and stops the motor from being actively driven it is true. However that is not the same as the STOP mode of the H-Bridge.

The logical internal connections in the H-Bridge for the three modes are like this:

[![enter image description here][1]][1]

When in STOP mode the motor is effectively short circuited and the power supply is disconnected. When the motor is spinning and not being actively driven it is generating power. By feeding that power into a load you increase the load on the motor itself, slowing it down. The bigger the electrical load the slower the motor will go - and you can't get bigger than a dead short. So this mode effectively stops the motor in its tracks. It puts the breaks on.

Conversely, if you just disconnect the power, there is nothing much to stop the motor spinning, so it will keep going depending on the amount of friction, wind resistance, inertia, momentum, etc.

If you are happy with that kind of operation then yes, your method will work fine, since you will have access to forward, reverse, and a way of controlling the power to the motor. You just won't be able to apply the brakes, and you will have to either rely on the natural slow-down of whatever you are driving, or do something clever involving using just enough reverse to stop the motor before cutting the power.

  [1]: https://i.stack.imgur.com/KcQfK.png


message:
Sending Large Packets and Reassembling over Serial

I'm trying to send info of about 30-40kB over the Serial ports on an Arduino Due. But I'm running into a few problems.
First, before we get into the actual transfer over the Serial, I want to try storing 30000 Bytes into a char * array.

Also as a disclaimer, I've modified the SAM library's `RingBuffer.h` `SERIAL_BUFFER_SIZE` to 256 from 128.

    void setup() {
      Serial.begin(115200);
    int i,j=0, cksum=0;
    int *test;
    test = (int*)calloc(1,30000);
    Serial.println("Starting...\n");

    for(i=0;i<30000;i++){
      test[i]=i;
      cksum +=j;
      j++;
      if(j>255){j=0;}
    }
    Serial.print("cksum is: ");
    Serial.println(cksum);
    cksum = 0;
    for(i=0;i<30000;i++){
      if(i<300){ //only print out the first 300 characters, otherwise it's hard to see anything
        Serial.print("[");
        Serial.print(test[i],HEX);
        Serial.print("]");
      }
      cksum+=(int)test[i];
    }
    Serial.print("\nNow cksum is: ");
    Serial.println(cksum);
    }

Obviously, since `*test` is a byte array, I'm only storing int8 into there - so from 0-255.
That means that the data received in `*test` increments from `test[255]= 255` to `test[256] = 0`. The way around this would be to use some kind of `itoa` function to write out multiple bytes that represent the numbers being written (causing an overflow because it would no longer be an array for 30000 Bytes). But for these purposes is it ok to simply realize that this is happening and just write the bytes to the array.

Ok, so for part two, I want to do the same thing, but by writing to Serial2 from Serial3 and receiving all of the bytes:

    void setup() {
      Serial.begin(115200);
      Serial2.begin(115200);
      Serial3.begin(115200);
    int i,j=0;
    double cksum=0;
    char *buf;
    Serial.println("Starting...\n");
    buf = (char*)calloc(1,30000);

    Serial.println("Writing to Serial3");
      for(i=0;i<30000;i++){
        Serial3.write((byte)i);
        cksum+=j;
        j++;
        if(j>255){j=0;}
      }
     Serial.println(cksum);
     Serial.println("Reading from Serial2");
     Serial2.readBytes(buf,30000);
     cksum = 0;
      Serial.print("Buf is: ");
      for(i=0;i<30000;i++){
        if(i<300){ //only print out the first 300 characters
          Serial.print("[");
          Serial.print(buf[i],HEX);
          Serial.print("]");
        }
        if(buf[i] != j){
          Serial.print("\nMismatch at i = ");
          Serial.print(i);
          Serial.print("\nBuf is: ");
          Serial.print(buf[i-1],HEX);
          Serial.print(",");
          Serial.println(buf[i],HEX);
        }
        cksum+=buf[i];
        j++;
        if(j>255){j=0;}
      }
      Serial.println("\n\nEnd");
      Serial.println(cksum);

    }

What happens here is that I get a mismatch at byte 255. The increment (in hex) goes:

    [254] = FE
    [255] = 30
    [256] = 31

But it **should** read:

    [254] = FE
    [255] = FF
    [256] = 0

After reading some other forums, and the fine AVR Arduino post [here][1], I feel like something is happening on the Serial interrupt level that I am not aware of. All of the data is properly transferred to the Serial and I am able to see all of the bytes in the correct order coming out of TX and into RX on my logic analyzer.
I've also experimented with different baud rates, but see no reason why a 84Mhz chip would not be able to handle a baud rate of 115200.

Has anyone else run into this? How do you handle these transfers of continuous data that is larger than the buffer? Is the only option here to run `readBytes` in `SERIAL_BUFFER_SIZE` increments until Serial is no longer available? Or can I still salvage using readBytes all in one go as I am trying to do?

I know this question has been asked in certain forms in other threads like [here][2] and [here][3] but they do not solve this particular problem I am experiencing, most likely because they are not Due specific.

  [1]: https://github.com/arduino/Arduino/issues/2405
  [2]: https://arduino.stackexchange.com/questions/25295/how-to-send-large-strings-100-characters-from-arduino-serial-monitor
  [3]: https://arduino.stackexchange.com/questions/203/sending-large-amounts-of-serial-data

body:
Let me dissect your program and show you precisely what is going on and why your approach is completely wrong:

Your first step is to throw 30,000 bytes at the serial port. Those go via the TX ringbuffer, which is (as you have changed it for some reason) 256 bytes:

    buf = (char*)calloc(1,30000);

    Serial.println("Writing to Serial3");
      for(i=0;i<30000;i++){
        Serial3.write((byte)i);
        cksum+=j;
        j++;
        if(j>255){j=0;}
      }

At this point 29744 bytes have left the hardware UART. 256 are still sat in the TX ringbuffer being sent out by the TX interrupt routine.  The first 256 bytes that were sent out were picked up by the RX interrupt routine and stored in the RX ringbuffer. The next 29488 bytes were discarded (they are now all over the carpet with your marbles).

     Serial.println(cksum);
     Serial.println("Reading from Serial2");

Now you try and read 30,000 bytes from the 256 byte RX ringbuffer. While you are doing that the remaining 256 bytes in the TX ringbuffer are being slowly sent out. You are now making some room in that RX ringbuffer since you are removing bytes from it, so some of the remaining 256 received bytes can now be stored in it. The first one of those happens to be 0x30.

     Serial2.readBytes(buf,30000);

Now you go and print out your array, which has only a tiny fraction of the 30,000 bytes you sent in it.

     cksum = 0;
      Serial.print("Buf is: ");
      for(i=0;i<30000;i++){
        if(i<300){ //only print out the first 300 characters
          Serial.print("[");
          Serial.print(buf[i],HEX);
          Serial.print("]");
        }
        if(buf[i] != j){
          Serial.print("\nMismatch at i = ");
          Serial.print(i);
          Serial.print("\nBuf is: ");
          Serial.print(buf[i-1],HEX);
          Serial.print(",");
          Serial.println(buf[i],HEX);
        }
        cksum+=buf[i];
        j++;
        if(j>255){j=0;}
      }
      Serial.println("\n\nEnd");
      Serial.println(cksum);

    }

The simple fact is, you are transmitting, en-masse, far more bytes than the Arduino's RX ringbuffer can hold. In order to receive more than the 256 bytes of the ringbuffer you have to read the bytes from that ringbuffer to make room for more to arrive. And since you are the one that is transmitting that means you have to do your receiving *at the same time as the transmitting*.

The only possible way that your arrangement of program could work would be if you increased the RX ringbuffer to greater than 30,000 bytes so it can store all the received bytes as you transmit them for you to then, afterwards, copy the contents of that ringbuffer into your own buffer.


body:
<!-- language: lang-c++ -->

>     int *test;
>     test = (int*)calloc(1,30000);

First, I would be testing if that calloc worked. 30000 bytes is a lot on any microprocessor. For example:

    test = (int*)calloc(1,30000);
    if (test == NULL)
      {
      Serial.println ("Insufficient memory.");
      exit (1);
      }

---

Second, can't you calculate the sumcheck on-the-fly?

>     for(i=0;i<30000;i++){
>       test[i]=i;
>       cksum +=j;
>       j++;
>       if(j>255){j=0;}
    }

If you want to send a sumcheck at the end, calculate as you send each byte and then send it afterwards. That way you don't need the 30000 byte array.

---

Your technique of sending 30000 bytes and then trying to read them back is hoping that the 30000 bytes will be saved somewhere while you are writing and before you read. Where?

>  I've modified the SAM library's RingBuffer.h SERIAL_BUFFER_SIZE to 256 from 128.

Certainly not there. That now holds 128 bytes.

So you are expecting a buffer of 30000 bytes which you set up, plus another 30000 bytes somewhere to hold the data while you send it. Even on the Due you are using most of your available RAM for this exercise.

---

What are you *really* trying to do here?

<http://xyproblem.info/>