body:
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.

title: How to use millis()

Answers: 1

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


body:
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?

title: Does serial speed affect performance of other tasks?

Answers: 2

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.


body:
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

title: FastLED and Neopixel Help

Answers: 2

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);


body:
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

title: Ensuring specific frequency at specific time?

Answers: 3

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
    }


body:
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

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

Answers: 1

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


body:
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';
      }

    }

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

Answers: 2

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';
         }
      }
    }


body:
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?

title: Cant connect to localhost

Answers: 1

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.


body:
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?

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

Answers: 2

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!


body:
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

title: Referencing local libraries from higher dir levels

Answers: 1

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.


body:
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

title: Arduino Due randomly slows down, serial communications stops

Answers: 1

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).


body:
I am working with a bunch of sensors and everything is fine so far, but I figured on analog PINS 4 & 5 the output voltage read is 0.09V higher than on 0-3... for my Sensors this is a crucial issue.

So I unplugged everything to see whats happening and found the voltage (which would supposedly be 5.0V as nothing is connected) varies, too.

    PIN 0   PIN1   PIN2   PIN3   PIN4   PIN5
    4.9365,4.8631,4.8045,4.7507,5.0000,5.0000
    4.9218,4.8436,4.7752,4.7165,5.0000,5.0000
    4.9120,4.8289,4.7605,4.6970,5.0000,5.0000
    4.9316,4.8583,4.7898,4.7263,5.0000,5.0000
    4.9462,4.8729,4.8045,4.7410,5.0000,5.0000
    4.9169,4.8387,4.7654,4.7019,5.0000,5.0000
    4.9022,4.8192,4.7507,4.6823,5.0000,5.0000

So i thought, OK, maybe my board is broken, but another one delivers similar results with NOTHING plugged in...

why is this?

All I do is `analogRead` on my PINs and multiply with `5.0/1023.0`...

I appreciate every hint.

title: Voltage on open circuit jumping on Arduino R3

Answers: 0


body:
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

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

Answers: 1

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


body:
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.

title: Do I need an Arduino for BLE?

Answers: 1

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


body:
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;

    }

title: Read speed between two ultrasonic sensors

Answers: 2

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


body:
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.

title: Is there a portable timer interrupt library?

Answers: 1

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.


body:
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.

title: use only one input pin in L293?

Answers: 1

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


body:
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

title: Sending Large Packets and Reassembling over Serial

Answers: 2

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/>


body:
I have a prototype using RedBear Lab's Blend micro platform (http://redbearlab.com/blendmicro/). I am able to discover the BLE chip on my iPhone and connect / control the unit. However, the device is constantly advertising - how do I enable advertising only on user request.

For example, if I use my bluetooth headphone, it pairs only when I press a button to enable pairing. Can I do the same with this BLE chip?

title: Enable BLE pairing on request

Answers: 0


body:
I am checking for ways to implement multi threathing in Arduino, I have also tried using the library `TimerOne` but it doesn't seem to work, what I'm trying to make is an Arduino application then, every time a certain amount of time passes, it pops an item from the stack, and between these times, the application allows me to add items to the stack, both processes working in parallel of course.

The items popped and pushed are numbers.

I have already tried some other questions, but their solutions don't work, especially one that seems very useful, but for some reason doesn't work, I'm speaking about the one of the `TimerOne` library.

Any suggestion to fix the problem some other way would be cool.

Here is the code:

    #include <TimerOne.h>
    #include <QueueList.h>
    #include <StackList.h>

    const uint16_t  NOTE_B0     =   31;
    const uint16_t  NOTE_C1     =   33;
    const uint16_t  NOTE_CS1    =   35;
    const uint16_t  NOTE_D1     =   37;
    const uint16_t  NOTE_DS1    =   39;
    const uint16_t  NOTE_E1     =   41;
    const uint16_t  NOTE_F1     =   44;
    const uint16_t  NOTE_FS1    =   46;
    const uint16_t  NOTE_G1     =   49;
    . . . ETC . . .
    const uint16_t  NOTE_DS8    = 4978;

    uint16_t Notas[] =
    {
          NOTE_B0
        , NOTE_C1
        . . . ETC . . .
        , NOTE_C8
        , NOTE_CS8
        , NOTE_D8
        , NOTE_DS8
    };

    QueueList<int> KeyNotesNode = QueueList<int>();
    StackList<int> StackNote = StackList<int>();

    char receivedChar1 = '<';
    char receivedChar2 = '<';

    char receivedChar[] = {receivedChar1, receivedChar2};

    int TempInt = 0;
    bool newData = false;

    bool itPopUp = false;

    int modality = 0;

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

      if(modality == 0){
        Serial.println("Ingrese el tipo de funcionalidad deseada");
        Serial.println("1.- Constructor de canciones en tonos");
        Serial.println("2.- Juego de imposicion musical");
      }

      Timer1.initialize(150000);
      Timer1.attachInterrupt( setForPop );
    }

    void loop() {
      //Checa y controla la recepcion de los char a traves de la consola de arduino

      if (Serial.available())
      {
        receiveChar();
        showReceivedChar();
      }

    //   . . .  Here is some code to process the reception of data from serialData  . . .

    // From somewhere here start the loop

    // . . . LOOPED . . .

        //Here is used the data
        if(modality == 1){
           //This option doesn't matter
        }
        else if(modality == 2){
          StackNote.push( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
          Serial.println("Agregado receivedChar exitosamente a la Pila");
          Serial.print("Tamano Total Lista: ");
          Serial.println(StackNote.count());
          Serial.print("Dato:");
          Serial.println( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
          Serial.print("Dato(get):");
          receivedChar[0] = '<';
          receivedChar[1] = '<';
        }
    }

        //Run and show the data on the stack
         if(modality == 1)
         {
               //This option doesn't matter
          }
          else if(modality == 2)
          {

            if(itPopUp){   //With this variable i want to control when it is show, this code is inside loop()
              Serial.print("Reproducido con exito la nota: "); //se escribe 'éxito' pero la consola no acepta tildes, que se arrepienta :P
              TempInt = StackNote.pop();
              Serial.println(TempInt);
              tone(9,Notas[((int)TempInt)],500);
              delay(500);
            }
          }

      } //Here the loop() end

    //This function i want to run it asyncronously
     void setForPop(){
        if(itPopUp){
          itPopUp = !itPopUp;
        }
        else{
          itPopUp = !itPopUp;
        }
     }

title: How can i do something like multi threathing in arduino?

Answers: 2

body:
You will not have full parallel execution in an Arduino (only one CPU).

 - You might do multi-threading by implementing a small OS (e.g. FreeRTOS)
 - Or write your own task scheduler.
 - Or even just do state machine looping forever checking if push or pop has to be executed.
 - Last and preferred solution: I would consider running the normal Push task always and execute the Pop task (function in fact) using interrupts.

body:
I haven't used the TimerOne library, but I have had good success with the SimpleTimer library.   http://playground.arduino.cc/Code/SimpleTimer

It's served me well in handling building small iot apps.  As the arduino has to both maintain connection info as well as doing it's processing data, this library seems to handle keeping both happy pretty well.

Here's an example in use: https://github.com/adbacker/bcc2016/blob/master/bcc2016.blynk.kitchensink/bcc2016.blynk.kitchensink.ino

The money bit is at the end => the setup and loop functions. (note: yes, I know. the comment says every second, but it's actually every 2 seconds...)

    void setup()
    {
      Serial.begin(115200); // See the connection status in Serial Monitor
      pinMode(WATER_SENSOR_PIN, INPUT); //water sensor pin, init as input
      Blynk.begin(auth, WIFI_SSID, WIFI_PW);
      while (Blynk.connect() == false) {
        Serial.println("trying to connect ....");
      }

    dht.begin();

    // Setup a function to be called every second
    timer.setInterval(2000L, sendTemp);
    timer.setInterval(2000L, updateLcd);
    timer.setInterval(2000L, checkForWater);
    }

    void loop()
    {
      Blynk.run(); // Initiates Blynk
      timer.run(); // Initiates SimpleTimer
    }


body:
I am at the moment working with an Arduino Uno, and am struggling to understand how I perform 32-bit arithmetic using it.

The expression I have to calculate is this: √(2 n/a) in which `n` is an integer and `a` constant float.

I am at all not sure how I should do this so any advise would be helpful here.

title: Performing 32-bit arithmetic on embedded device

Answers: 2

body:
Since you are using floats and need more than a quick approximation, I would recommend one of the following methods:

[The Babylonian method][1]

[Digit-by-Digit][2]

The first is a fast approximation with a known bound on the error, the second will give a known exact result but with more computation steps in general. Both obviously round to the precision of your data type.

EDIT:

For really fast computations check out the crazy [fast inverse square root][3]

of the first algorithm on [this page][4].
Disclaimer: I have never had to implement a square root like this, but I've done others like Sine(x).

EDIT 2: @pipe made a good point. If you just want it to work, use [sqrt(x)][5]

  [1]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
  [2]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Digit-by-digit_calculation
  [3]: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  [4]: https://stackoverflow.com/questions/19611198/finding-square-root-without-using-sqrt-function
  [5]: https://www.arduino.cc/en/Reference/Sqrt

body:
You wrote:

> the 16 most significant should be accurate.

Are you absolutely sure about that? Please reconsider. It is easy, when
asking a question, to ask for something better than what you strictly
need... until you realize the cost of fulfilling those expectations.

I have been working recently on a fixed-point implementation of the
square root. It is meant to work with numbers in [0, 1) represented in
0.16 format, i.e. unsigned, 0 bits integer part, 16 bits
fractional part. It is based on the polynomial approximation

√_x_ ≈ 0.1908901 + 1.5392302 _x_ − 1.4475870 _x_2
+ 1.0217778 _x_3 − 0.3043110 _x_4

which is quite good for _x_ ∈ [0.25, 1]. Numbers in (0, 0.25) can be
moved to that interval by successive multiplications by 4, and then
dividing the result by 2. In other words, by using the fact that

√_x_ = √(4 _x_) / 2

The maximum error is 2.56e-4, i.e. 16.8 ulps (units in the last
place). It takes 298 CPU cycles to execute in the worst case. Note
that, in order to achieve this performance, I had to implement the
multiplication in assembly. Otherwise gcc would give me inefficient
code.

Here is the code:

    /*
     * Convert x to a 16-bit fixed point number
     * with n bits after the binary point.
     */
    #define FIXED(x, n) ((uint16_t)((float)(x) * (1UL << (n)) + .5))

    /*
     * Fixed point multiplication.
     *
     * Multiply two fixed point numbers in unsigned 0.16 format.
     * Returns result in the same format.
     * Rounds to nearest, ties rounded up.
     */
    static uint16_t mul_fix_u16(uint16_t x, uint16_t y)
    {
        uint16_t result;
    #if defined(__AVR_HAVE_MUL__) && defined(__AVR_HAVE_MOVW__)
        /* Optimized ASM version. */
        asm volatile(
            "mul  �, �\n\t"
            "movw �, r0\n\t"
            "ldi  r19, 0x80\n\t"
            "clr  r18\n\t"
            "mul  �, �\n\t"
            "add  r19, r1\n\t"
            "adc  �, r18\n\t"
            "adc  �, r18\n\t"
            "mul  �, �\n\t"
            "add  r19, r0\n\t"
            "adc  �, r1\n\t"
            "adc  �, r18\n\t"
            "mul  �, �\n\t"
            "add  r19, r0\n\t"
            "adc  �, r1\n\t"
            "adc  �, r18\n\t"
            "clr  r1"
            : "=&r" (result)
            : "r" (x), "r" (y)
            : "r18", "r19"
        );
    #else
        /* Generic C version. Compiles to inefficient 32 bit code. */
        result = ((uint32_t) x * y + 0x8000) >> 16;
    #endif
        return result;
    }

    /*
     * Fixed point square root.
     * Argument and result in unsigned 0.16 format.
     *
     * If defined(REALLY_ACCURATE):
     *   max error = 7.67e-6
     *   execution time:
     *     937   cycles (worst case)
     *     828.1 cycles (average)
     * else
     *   max error = 2.56e-4
     *   execution time:
     *     298   cycles (worst case)
     *     184.7 cycles (average)
     */
    uint16_t sqrt_fix(uint16_t x)
    {
        if (x == 0) return 0;
        uint8_t n;
    #ifdef REALLY_ACCURATE
        if (x == 0xffff) return 0xffff;
        uint16_t x0 = x;
    #endif
        for (n = 0; x < 0x4000; n++) x <<= 2;  // scale the operand
        uint16_t y;
        y = FIXED(0.30435, 15);
        y = FIXED(1.02173, 15) - mul_fix_u16(x, y);
        y = FIXED(1.44754, 15) - mul_fix_u16(x, y);
        y = FIXED(1.53925, 15) - mul_fix_u16(x, y);
        y = FIXED(0.19089, 16) + (mul_fix_u16(x, y) << 1);
        while (n--) y >>= 1;                   // scale the result
    #ifdef REALLY_ACCURATE
        y = (y + ((uint32_t)x0 << 16) / y + 1) / 2;  // Babylonian iteration
    #endif
        return y;
    }

If you really need a very accurate result, you can
`#define REALLY_ACCURATE`. This will add a single iteration of the
[Babylonian method][], which is essentially Newton's method applied to
the square root:

_y_ ← (_y_ + _x_/_y_) / 2

where _y_ is our approximation of √_x_. This looks like an easy win:
just a division, an addition and a bit shift. And it makes the result
practically perfect, with a maximum error of 7.67e-6 (0.502 ulps).
But the execution time is increased more than threefold, at
937 cycles in the worst case. This is because the AVR chip has no
hardware support for division, and the software alternative provided by
the compiler is awfully slow.

[Babylonian method]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method


body:
I would like to ask you if I can display real time view from Camera in Arduino Uno with LCD.

**I have that components:**

- Camera OV7670 VGA 0.3 MPX
- LCD TFT 2.4 SPI ILI9341
- Arduino Uno R3

On a website: arducam.com there are used another components. I bought that parts because in a documentation in auction was that is compatible with Arduino.
I see that in Arduino UNO is not so much pins.

Could somebody help me to resolve this challenge?

Regards

title: Arduino Uno with Camera and LCD

Answers: 1

body:
No, this is not possible.

The camera outputs a JPEG image. To display that on the TFT screen it is necessary to decompress that JPEG image and send the raw 16-bit (RGB565) colour information to the screen.

The Arduino doesn't have enough memory to do the job.

I wrote an absolute minimal JPEG decompressor a while back. It uses the absolute minimum memory possible (it operates on one macroblock at a time), and still requires around 100KB. That's 50x more than the Arduino Uno has.

Also on a 200MHz, 32-bit chip with FPU it takes about a minute to decompress a 320x240 pixel image. I can't even begin to imagine how many days that would take on a little Arduino Uno even if it did have enough memory to do the job...

As has been suggested, you need a more powerful board. And if you're going that route you may as well drop the useless OV7670 and get a Raspberry Pi with a proper Pi Camera module (or at least a USB webcam).


body:
I'm running my accelerometer through my Arduino mini and outputting my values using the following values

     // print the sensor values:
      Serial.print(analogRead(xpin));
      // print a tab between values:
      Serial.print("\t");
      Serial.print(analogRead(ypin));
      // print a tab between values:
      Serial.print("\t");
      Serial.print(analogRead(zpin));
      Serial.println();
      // delay before next reading:
      delay(100);

Here's an example.

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

The x,y,z values that are outputted are quite high even the arduino is not moving. I'm new to Arduino programming and would love some understanding on how to convert these x,y,z to an Acceleration value ie. Is the arduino moving or not?

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

title: How to interpret accelerometer output data?

Answers: 2

body:
The accelerometer will output a specific number of volts (or millivolts) per *g*.  You need to find that information in the datasheet for your accelerometer.

Then you need to take the readings you make through `analogRead()` and convert them to a voltage. Then that voltage can be used, combined with the value you found above, to determine the *g* reading.

body:
As has been noted by @Majenko, you are reading voltages with your `analogRead()` as a ratio of the A/D reference voltage specified for the Arduino you are using rather than true accelerations. For example, your first pass readings of x=9, y=8, z=8 were really saying x = Vref * 9 / 1023 volts. The datasheet for your accelerometer sensor will specify a calibration factor to be applied in terms of Volts/g.

Therefore, if you wish to read in terms of actual acceleration g. then you will need to first convert the value read from the A/D to volts and then convert the voltage to g by applying the datasheet sensitivity factor.

You can brute force this conversion calculation if you wish by using variables of type `float`. If you wish to avoid floating point arithmetic and use fixed point calculations, you can consider defining the result as being multiplied by 10 or 100. (Example: a reading of 1.0g might be reported as 10 if using 10x reporting or it might be reported as 100 if using 100x reporting.

Additionally, if you suspect some jitter in your measurements, you can read multiple times to average and smooth the readings. You can then divide the total of the readings to get an average.

Example Code for Single Axis Using Integer Variables (Untested)

    #define AXIS_PIN A0

    void setup() {
      // Insert Setup Code Here

    }

    void loop()
    {
      int reading;

      reading = 0;

      // Read the sensor axis value 4 times
      //  Use a short delay between reads if you might exceed
      //    the read frequency of the sensor.
      // Use millis() for non-blocking aspects if needed
      for (int readLoop = 0; readLoop < 4; readLoop++)
      {
        reading += analogRead(AXIS_PIN);
        delay(2);
      }

      // Map the reading to a voltage using a 100x multiplier
      //  The raw reading has a range of (0 to 1023) * 4
      //  The mapped reading has a range of (0 to 3300) * 4
      //    (assuming a 3.3v reference voltage)
      //    (Use 0 to 4 * 5000 if required by the choice of sensor and
      //      Arduino used.)
      reading = map(reading, 0, 4 * 1023, 0, 4 * 3300);

      // Find the average by now dividing by 4
      reading = reading >> 2;

      Serial.print(F("Average axis reading (x100) is: "));
      Serial.println(reading);

      // Read the axis once per second
      // Use millis() for non-blocking aspects, if needed
      delay(1000);
    }

EDIT NOTE: I see you have now specified an Adafruit ADXL345 sensor. Be aware that this sensor references 3.3v (offset ratio-metric, ie +/- 1.65v) even though it runs off of a 5v power source. Depending on which Arduino you are using, you may have to adjust the map() function input above to account for the proper output. You can try something like `map(reading, 0, 4 * 1023, -2 * 3300, 2 * 3300);`.

ADDED EDIT: The above will output a converted voltage. If you would like to output directly in units of g (x100), then you can change the `map()` function to something like `map(reading, 0, 4 * 1023, -2 * 300, 2 * 300)` assuming the Adafruit ADXL345 (PRODUCT ID: 163) which reads to +/- 3g.


body:
I am trying to use the Arduino Uno to read an AVCLan bus on a Toyota vehicle.  Logic 0 is when +/- drive are 120mV or more apart, and logic 1 is 20mV or less.  See [Toyota AVC-Lan description][1].

I currently set the TCNT1 timer to /1 prescaler for resolution, and waiting in a loop until the ACO bit sets in ACSR.  Using this, I measure the amount of time the signal was logic 0, and calculate each bit based on the how long the timer ran, and then resetting it.

While this works fine for most messages, I do receive a "glitch" every couple messages, with on-times around 2uS - 4uS, which shouldn't happen on this bus.  I'm guessing the analog comparator is tripping up if the drive is around 10mV - 20mV, when it shouldn't set.

Is there any way to set up a threshold, so that it will only fire the comparator at say 100mV or above?

  [1]: http://softservice.com.pl/corolla/avc/avclan.php

title: Using Analog Comparator on Uno to Read Differential Voltage Signaling

Answers: 0


body:
I've been unable to resolve a coding problem I've been having with the Arducam Mini 2MP and I was hoping someone might be willing to give me some pointers or clear up any apparent misconceptions I've had regarding the cameras capabilities.

I have my loop setup so the camera captures an image and following this, a lux measurement is taken. If lux exceeds a specified threshold, the image is transferred to an SD card. If not, then fifo is flushed and start_capture is returned to zero.

What I'd like to have is a series of say 3 images, leading up to the point in time when lux exceeds the threshold.

I can buffer more than one frame by writing to the Arduchip registry
    (myCAM.write_reg(ARDUCHIP_FRAMES. 0x03);

The tricky part for me has been transferring multiple buffered images to the SD card. After multiple attempts, I was able to save the images. However, only the first image from the series is viewable. The remaining images, when opened with a hex editor contain a varying number of zeros before the FFD8, causing them to be unrecognizable as jpegs).

This is the code in its entirety, complete with some debugging techniques I was fortunate to stumble upon while trying to resolve the issue (serial printing an asterisks after each 256 byte transfer really helped to develop some understanding of how the SPI transfer was being achieved).
<!-- language-all: lang-cpp -->

    // Logs a lux reading and time stamp at approximately ___ms intervals
    // 1. three image frames are acquired
    // 2. A lux reading and corresponding time of reading is written to the log
    // 3. If lux exceeds threshold, the log is closed and the three buffered images are written to the SD card,
    // 4. If lux does not exceed threshold, the buffer is wiped
    // Image file names indicates the time at which the log was closed and order of image acquisition
    // lux readings resume when images are saved (within __s of last lux reading)
    // Note: flush command have been removed to speed up sampling rate. lux readings are written to SD when the buffer is full (some data at end will be lost)

    #include <SD.h>
    #include <Wire.h>
    #include <ArduCAM.h>
    #include <SPI.h>
    #include "memorysaver.h"
    #include "RTClib.h"
    #include <Adafruit_Sensor.h>
    #include "Adafruit_TSL2591.h"
    #if defined(__arm__)
    #include <itoa.h>
    #endif

    /* SPI (Serial Peripheral Interface) synchronous  serial communications interface. */
    /* CS (chip select) or SS (slave select)- command pin which enables or disables slave device access to shared I/Os */
    const int chipSelect = 10;     // pin 10 is the SS for the SD-card
    const int SPI_CS = 23;         // SPI slave select for Arducam
    ArduCAM myCAM(OV2640, SPI_CS); // instruct the arducam that its SS is SPI_CS which we just defined as pin 23

    float LUX;
    char charFileName;
    int q;
    int k;
    unsigned long T;
    volatile uint32_t length;

    RTC_DS1307 RTC;                                // define Real Time  Clock
    File logfile;                                  // logging file
    Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // the sensor identifier

    #define ECHO_TO_SERIAL   1           // zero shuts off serial output
    #define WAIT_TO_START    1           // Wait for serial input in setup()

    void configureSensor(void)
    {
     tsl.setGain(TSL2591_GAIN_LOW);    // 1x gain (bright light)
     tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS);
    }

    void stamp()
    {
      if (! logfile) {
        logfile = SD.open("test.csv", FILE_WRITE);
      }
      DateTime now;
      now = RTC.now();                  // fetch the time
      logfile.print(now.month(), DEC);
      logfile.print("-");
      logfile.print(now.day(), DEC);
      logfile.print("-");
      logfile.print(now.year(), DEC);
      logfile.print("__");
      logfile.print(now.hour(), DEC);
      logfile.print(":");
      logfile.print(now.minute(), DEC);
      logfile.print(":");
      logfile.println(now.second(), DEC);
    }

    void setup()
    {
      uint8_t vid, pid;
      uint8_t temp;
      Wire.begin();
      Serial.begin(115200);

      #if WAIT_TO_START
        Serial.println("Type any character to start");
        while (!Serial.available());
      #endif //WAIT_TO_START

      Serial.println("ArduCAM Start!");

      pinMode(SPI_CS, OUTPUT);            // set the SPI_CS as an output.
      SPI.begin();                        // initialize SPI
      myCAM.write_reg(ARDUCHIP_TEST1, 0x55);  // is ArduCAM SPI bus is OK
      temp = myCAM.read_reg(ARDUCHIP_TEST1);
      if (temp != 0x55)
      {
        Serial.println("SPI interface Error!");
        while (1);
      }

      myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
      myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
      if ((vid != 0x26) || (pid != 0x42))
        Serial.println("Can't find OV2640 module!");
      else
        Serial.println("OV2640 detected");

      myCAM.set_format(JPEG);
      myCAM.InitCAM();
      myCAM.write_reg(ARDUCHIP_FRAMES,0x03);  //Number of frames to captured

      //Initialize SD Card
       if (!SD.begin(10, 11, 12, 13))
      {
        //while (1);        //If failed, stop here
        Serial.println("SD Card Error");
      }
      else
      {
        Serial.println("SD Card detected!");
      }

      if (!RTC.begin()) {
        Serial.println("RTC failed");
      }

      if (tsl.begin())
      {
        Serial.println("Found a TSL2591 sensor");
      }
      else
      {
        Serial.println("No sensor found ... check your wiring?");
        while (1);
      }

    configureSensor();
    stamp();
    }

    void loop()
    {
     acquire();
     k=0;
    }

    void acquire(){
      char str[8];
      File outFile;
      byte buf[256];
      static int i = 0;
      uint8_t temp, temp_last;
      uint8_t start_capture = 0;
      int total_time = 0;
      start_capture = 1;
      if (start_capture)
      {
    myCAM.flush_fifo(); // reset the fifo read pointer to 0 (clear the camera buffer?)
    myCAM.clear_fifo_flag(); //clears flag before next capture command
    myCAM.start_capture();
      }

      while (!myCAM.get_bit(ARDUCHIP_TRIG , CAP_DONE_MASK));  // what does "CAP_DONE_MASK" mean? Seems like this does nothing. "Polling the capture done flag". Why?
    //determine ambient light intensity
    uint32_t lum = tsl.getFullLuminosity();
    uint16_t ir, full;
    ir = lum >> 16;
    full = lum & 0xFFFF;
    LUX = tsl.calculateLux(full, ir);
    T = (millis());
    if (! logfile) {
    logfile = SD.open("test.csv", FILE_WRITE);
    }
    #if ECHO_TO_SERIAL
          Serial.print (T); Serial.print(" ");
          Serial.print(LUX); Serial.println("  ");
    #endif //ECHO_TO_SERIAL
          logfile.print(" "); logfile.print(T); logfile.print(" ");
          logfile.print(" "); logfile.print(LUX); logfile.println(" ");
        // Did is suddenly get very bright? If it did, retrieve the last series of frames so we can figure out what's going on in this environment.
        if (LUX > 10000) {
        logfile.print ("threshold_exceeded_"); logfile.print (T); logfile.println ("_ms");
        Serial.print ("threshold_exceeded_"); Serial.print (T); Serial.println ("_ms");
        logfile.close();
        length = myCAM.read_fifo_length();
        Serial.print("The fifo length is :");
        Serial.println(length, DEC);

             for  (int q=0; q<3; q++)
              { transfer();
              }
          /* Clear the capture done flag */
            myCAM.clear_fifo_flag();
          /* Clear the start capture flag. */
            start_capture = 0;
              }
        }

    void transfer(){
    char str[8];
    File outFile;
    byte buf[256];
    static int i = 0;
    uint8_t temp, temp_last;
    int total_time = 0;

      //Construct a file name
        k = k + 1;
        String fileName = String();
        fileName = T;
        fileName += "_";
        fileName += k;
        fileName += ".jpg";
        char charFileName[fileName.length() +1];
        fileName.toCharArray(charFileName, sizeof(charFileName));
        outFile = SD.open(charFileName, O_WRITE | O_CREAT | O_TRUNC);
      if (! outFile)
      {
        Serial.println("open file failed");
        return;
      }
      Serial.print("Writing to: ");
      Serial.println(charFileName);

                total_time = millis();
                i = 0;
                myCAM.CS_LOW();
                myCAM.set_fifo_burst();
                temp = SPI.transfer(0x00);
                Serial.print ("temp= "); Serial.println(temp,HEX);
              /* Read JPEG data from FIFO  to temp until the final memory address is reached. */
            while ( (temp != 0xD9) | (temp_last != 0xFF))
            {
              temp_last = temp;
              temp = SPI.transfer(0x00);
            length--;
          /* Write image data to buffer if not full. The buffer can hold 256 bytes of data. Increment through the cells of the buffer, adding the data from temp until the buffer is full. */
              if (i < 256)
                buf[i++] = temp;
              else
              {
          /* Write 256 bytes image data to file. */
                myCAM.CS_HIGH();
                Serial.print("*");    // each time 256 bytes of data is written to the file, serial print an "*"
                outFile.write(buf, 256);
                i = 0;
                buf[i++] = temp;
                myCAM.CS_LOW();
                myCAM.set_fifo_burst();
              }
            }
            Serial.print("finished (?) temp=0x");Serial.print(temp,HEX);Serial.print(" temp_last=0x");Serial.println(temp_last,HEX);
          /* Write the remain bytes in the buffer */
            if (i > 0)
            {
              myCAM.CS_HIGH();
              outFile.write(buf, i);
            }
          /* Close the file. */
            outFile.close();
            total_time = millis() - total_time;
            Serial.print("Total time used:");
            Serial.print(total_time, DEC);
            Serial.println(" ms");

        Serial.print("The fifo length is :");
        Serial.println(length, DEC);
        }

Can someone recommend a way to avoid writing these anomalous 0x00 into my jpeg images?

title: How can I transfer multiple frames from the Arducam's fifo buffer to file without zero padding?

Answers: 0


body:
I'm attaching a picture of my board which has the push button I want to use, but I cannot because I don't know what pin number should I write in my code.

my code:

    int switchPin = Button;
    int ledPin =13;

    void setup() {
      // put your setup code here, to run once:
    pinMode(switchPin, INPUT);
    pinMode(ledPin, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    if(digitalRead(switchPin) == HIGH)
    {
      digitalWrite(ledPin, HIGH);
    }
    else
    {
      digitalWrite(ledPin, LOW);
    }
    }

This is a picture shows the button on the top right "green"
[![][1]][1]

  [1]: https://i.stack.imgur.com/kc5Np.jpg

title: I already have a button on my Arduino board, but I don't know what pin number should I use in my code?

Answers: 1

body:
The [schematic at makeblock.com of the mbot mcore board](https://support.makeblock.com/hc/en-us/articles/4412894402967-mCore-Main-Control-Board-for-mBot) shows switch S3 feeding pin A7, which is an analog input pin.  Note, there is a deplorable 0.1 μF capacitor in parallel across S3, probably intended as hardware-level debouncing.

Also see the [Port wiring mBot mCore board](https://forum.makeblock.com/t/port-wiring-mbot-mcore-board/1379) thread on the Makeblock forum, where one of the posts says there are multiple versions of the board, and provides reference links.

For example, sample code at
[newinnovators.ca's “mblock-to-arduino/button-control” page](http://www.newinnovators.ca/index.php/mbot/mblock-to-arduino/button-control) (Dead link) shows pin 2 being used to sense the button.  You may need to run some tests.


body:
I have an Arduino UNO, a NRF24L01 as receiver (receive data from elsewhere), and [this touch screen from Adafruit][1] for display and control.

The Adafruit TFT is a shield so it fits the UNO perfectly.

I wonder if this TFT shield can share SPI pins with NRF24L01?

Given that I use pin 10 (=SS) for TFT and pin 8 (=SS) for NRF24L01, with set (SS, low) to toggle between two slaves (TFT and nRF24)?

Somehow it doesn't work once I start to share SPI pins (11, 12, 13) between two slaves.

  [1]: https://www.adafruit.com/product/1947

title: Arduino UNO with NRF24l01 + touch screen

Answers: 0


body:
I am new to electronics and especially Arduino-based products. I am currently trying my hand at using 5 segments of WS2812 RGB LEDs and using a Nano to control them. I included the picture below for the pin numbers.

If I wanted to run 5 groups of LEDs and use a library like the Adafruit Neopixel or Fastled to control the leds, what would be the best way of wiring them up to the Nano?

I am under the impression that the positives should all be connected to pin 27, the 5v pin, with a 1000 µF 25V capacitor. The ground wires will all be connected together to pin 04, Ground. The data pins will be wired to pins 6, 8, 9, 12 and 13 and each will have a 470 ohm 1/2W resistor on each pin.

I am unsure whether any of the other pins can be used for data pins. The input voltage will vary since this is used on a multi-rotor that I am building. The battery voltage will vary from 12.6V all the way down to maybe 9 volts. I was thinking of using a step down adjusted to 12V to keep the voltage at or under 12v and that will be connected to pin 30. I would love to hear if there are any better ways of wiring this project up.

Also would it be a better idea to power the LEDs from a 5V dedicated source and just use the Nano for the data pin connection? I will only be using roughly 30-40 WS2812s.

[![Nano Pin Out][1]][1]

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

title: Arduino Nano and WS2812

Answers: 1

body:
Regarding “The data pins will be wired to pins 6, 8, 9, 12 and 13 and each will have a 470 ohm 1/2W resistor on each pin”, note that WS2812s typically are connected together in strings, with the DO (data out) pin of each upstream unit connected to the DI (data in) pin of the next unit downstream. Thus, there is no need to allocate five Arduino IO pins; one is enough.

For further background on WS2812 mechanisms, see for example [Is it possible to infer the length of a neopixel string using 1-wire protocol?](https://arduino.stackexchange.com/q/21034), and see discussions and diagrams at [adafruit.com](https://learn.adafruit.com/adafruit-neopixel-uberguide/power) and [sparkfun.com](https://learn.sparkfun.com/tutorials/ws2812-breakout-hookup-guide).

Regarding use of an efficient step-down switching-supply voltage regulator set for 12 V out, if you use an adjustable regulator you might as well set it lower than that, for example at 8 or 9 volts. Typically, the regulators on Arduino boards that convert Vin to +5 or +3.3 V are linear regulators rather than switching regulators, so every unnecessary extra volt (above the dropout limit) proportionally increases the amount of wasted energy.

In typical use, a WS2812 draws 20 to 60 mA current, supposing up-to-five-volt power. Thus, a string of 30 to 40 of them will draw at least 0.6 A, in most cases, and up to 2.4 A, if all are on at top brightness. In either case, an external power supply would be de rigueur. You would connect the external supply's ground to the Nano's ground; the +5Vs need not be connected together.

*Edit: Addressing questions from comments*

Re “if one data in will control the entire array of LEDs, it should be connected to D13”, I'm not aware of any reason for that idea, and indeed would recommend against it. On many Arduino models, D13 drives an LED. While the Uno uses a buffer amplifier to drive the LED, the Nano just has a 680 Ω resistor in series with an LED. I'd not load it further.

Wiring each of several strips in its own chain seems quite reasonable. Yes, you could wire all the DIs of 30 or 40 WS2812 units in parallel. However, parallel inputs would require 30 or 40 wire runs, vs. the simple wiring chain the WS2812 is intended for. Note, per its spec sheet the WS2812 DI load is ±1 µA max, so one '328 IO pin could drive hundreds of them. But input capacitance, up to 15 pF each, probably precludes driving thousands in parallel.

If performance is an issue, possibly use short chains (up to several dozen units long) in parallel, rather than one long chain of hundreds of units. The spec sheet says, “When the refresh rate is 30fps, low speed model cascade number are not less than 512 points, high speed mode not less than 1024 points.” (Low speed refers to 400Kbps signalling; high speed, 800Kbps).

Note, paralleled chains improve refresh rates only when multiple chains are used to show the same pattern. Otherwise, each chain being refreshed separately is no faster than refreshing the same number of units in series. The library that drives a chain of WS2812s hogs the whole processor each time it sends a chain of data. Also note that scan rates of 400 Hz are mentioned in the spec sheet. It is likely to be futile to try to exceed that by paralleling units.

Summary: If you have a dozen or so units on a rotor arm, I'd wire them in series. If it's more convenient to keep each arm's wiring separate from that of other arms, then do so. If each arm will show the same pattern as other arms, you could wire the chain inputs (the first units in each chain) in parallel, else would use separate driver pins.