body:
I'm looking for a simple way to send a signal from my arduino to a vga monitor.

What would be the easiest method, and what components would be needed?

I don't need to display an image, just a solid colour.

title: Sending colours to vga monitor

Answers: 3

body:
A quick Google search for "Arduino VGA" will give you a lot of information. There are a few variations on both circuits and programming, which also vary in resolution and color depth.

I was searching for this a few days ago, and these are my favorite (so far):

- http://labdegaragem.com/profiles/blogs/gerando-sinal-vga-colorido-com-arduino-completo (it is in portuguese, but you can get a pretty good idea of what to do)

- https://forum.arduino.cc/index.php?topic=320238.0 (read the whole discussion, pretty nice results)

If using a TV is also a plausible option, check the Arduino TV out library. It can be installed directly from the Arduino IDE and has a good demo.

body:
Not needing to display an actual image simplifies things substantially, as an Arduino lacks the memory and (except in a crude sense) the bandwidth to do so.

However, you cannot simply apply a steady analog voltage to the R, G, and B lines.  Not only do you have to drive horizontal and vertical sync signals, you have to blank the RGB signals when not on the active portion of the screen, otherwise the monitor will assume their steady voltage means "black" and your colors will last only as a brief flash when your device is first connected or enabled.

Generating a large rectangular field of color from an Arduino is likely to be rather challenging, but probably not impossible.  You may be able to use hardware PWM channels for the horizontal and a "color enable", and tightly coded software counters for the vertical aspect.  You can then use the "color enable" to gate a network of potentially variable resistors to establish the single color of particular interest.

body:
My page about [Arduino Uno output to VGA monitor](http://www.gammon.com.au/forum/?id=11608) has a lot of theory on it, including a sketch that produces colour bars like this:

[![Colour bars][1]][1]

---

## Code

To produce a single colour is slightly simpler, this sketch did it for me:

<!-- language-all: lang-C++ -->

    /*
     VGA colour video generation

     Author:   Nick Gammon
     Date:     22nd April 2012
     Version:  1.0

     Connections:

     D3 : Horizontal Sync (68 ohms in series) --> Pin 13 on DB15 socket
     D4 : Red pixel output (470 ohms in series) --> Pin 1 on DB15 socket
     D5 : Green pixel output (470 ohms in series) --> Pin 2 on DB15 socket
     D6 : Blue pixel output (470 ohms in series) --> Pin 3 on DB15 socket
     D10 : Vertical Sync (68 ohms in series) --> Pin 14 on DB15 socket

     Gnd : --> Pins 5, 6, 7, 8, 10 on DB15 socket

    */

    #include <TimerHelpers.h>
    #include <avr/pgmspace.h>
    #include <avr/sleep.h>

    const byte hSyncPin = 3;     // <------- HSYNC

    const byte redPin = 4;       // <------- Red pixel data
    const byte greenPin = 5;     // <------- Green pixel data
    const byte bluePin = 6;      // <------- Blue pixel data

    const byte vSyncPin = 10;    // <------- VSYNC

    const int horizontalBytes = 60;  // 480 pixels wide
    const int verticalPixels = 480;  // 480 pixels high

    // Timer 1 - Vertical sync

    // output    OC1B   pin 16  (D10) <------- VSYNC

    //   Period: 16.64 ms (60 Hz)
    //      1/60 * 1e6 = 16666.66 µs
    //   Pulse for 64 µs  (2 x HSync width of 32 µs)
    //    Sync pulse: 2 lines
    //    Back porch: 33 lines
    //    Active video: 480 lines
    //    Front porch: 10 lines
    //       Total: 525 lines

    // Timer 2 - Horizontal sync

    // output    OC2B   pin 5  (D3)   <------- HSYNC

    //   Period: 32 µs (31.25 kHz)
    //      (1/60) / 525 * 1e6 = 31.74 µs
    //   Pulse for 4 µs (96 times 39.68 ns)
    //    Sync pulse: 96 pixels
    //    Back porch: 48 pixels
    //    Active video: 640 pixels
    //    Front porch: 16 pixels
    //       Total: 800 pixels

    // Pixel time =  ((1/60) / 525 * 1e9) / 800 = 39.68  ns
    //  frequency =  1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

    // However in practice, it we can only pump out pixels at 375 ns each because it
    //  takes 6 clock cycles to read one in from RAM and send it out the port.

    const byte verticalBackPorchLines = 35;  // includes sync pulse?
    const int verticalFrontPorchLines = 525 - verticalBackPorchLines;

    volatile int vLine;
    volatile byte backPorchLinesToGo;

    #define nop asm volatile ("nop\n\t")

    // ISR: Vsync pulse
    ISR (TIMER1_OVF_vect)
      {
      vLine = 0;
      backPorchLinesToGo = verticalBackPorchLines;
      } // end of TIMER1_OVF_vect

    // ISR: Hsync pulse ... this interrupt merely wakes us up
    EMPTY_INTERRUPT  (TIMER2_OVF_vect)

    void setup()
      {

      // disable Timer 0
      TIMSK0 = 0;  // no interrupts on Timer 0
      OCR0A = 0;   // and turn it off
      OCR0B = 0;

      // Timer 1 - vertical sync pulses
      pinMode (vSyncPin, OUTPUT);
      Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
      OCR1A = 259;  // 16666 / 64 µs = 260 (less one)
      OCR1B = 0;    // 64 / 64 µs = 1 (less one)
      TIFR1 = bit (TOV1);   // clear overflow flag
      TIMSK1 = bit (TOIE1);  // interrupt on overflow on timer 1

      // Timer 2 - horizontal sync pulses
      pinMode (hSyncPin, OUTPUT);
      Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
      OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
      OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)
      TIFR2 = bit (TOV2);   // clear overflow flag
      TIMSK2 = bit (TOIE2);  // interrupt on overflow on timer 2

      // prepare to sleep between horizontal sync pulses
      set_sleep_mode (SLEEP_MODE_IDLE);

      // pins for outputting the colour information
      pinMode (redPin, OUTPUT);
      pinMode (greenPin, OUTPUT);
      pinMode (bluePin, OUTPUT);

    }  // end of setup

    // draw a single scan line
    void doOneScanLine ()
      {

      // after vsync we do the back porch
      if (backPorchLinesToGo)
        {
        backPorchLinesToGo--;
        return;
        }  // end still doing back porch

      // if all lines done, do the front porch
      if (vLine >= verticalPixels)
        return;

      PORTD = bit (5) | bit (6);  // cyan (green + blue)
      delayMicroseconds (27);     // one scan line

      PORTD = 0;  // back to black
      // finished this line
      vLine++;

      }  // end of doOneScanLine

    void loop()
      {
      // sleep to ensure we start up in a predictable way
      sleep_mode ();
      doOneScanLine ();
     }  // end of loop

As @ChrisStratton suggested, the hardware timers are a big help.

---

## Wiring

I wired it up like this:

[![VGA wiring][2]][2]

[![VGA pins][3]][3]

---

## TimerHelpers library

The **TimerHelpers.h** library is described on my [timers](http://www.gammon.com.au/timers) page, a copy is below:

    /*
     Timer Helpers library.

    Devised and written by Nick Gammon.
    Date: 21 March 2012
    Version: 1.0

    Licence: Released for public use.

    See: http://www.gammon.com.au/forum/?id=11504

     Example:

     // set up Timer 1
     TCNT1 = 0;         // reset counter
     OCR1A =  999;       // compare A register value (1000 * clock speed)

     // Mode 4: CTC, top = OCR1A
     Timer1::setMode (4, Timer1::PRESCALE_1, Timer1::CLEAR_A_ON_COMPARE);

     TIFR1 |= bit (OCF1A);    // clear interrupt flag
     TIMSK1 = bit (OCIE1A);   // interrupt on Compare A Match

    */

    #ifndef _TimerHelpers_h
    #define _TimerHelpers_h

    #include <Arduino.h>

    /* ---------------------------------------------------------------
     Timer 0 setup
     --------------------------------------------------------------- */

    namespace Timer0
    {
      // TCCR0A, TCCR0B
      const byte Modes [8] [2] =
      {

      { 0,                         0 },            // 0: Normal, top = 0xFF
      { bit (WGM00),               0 },            // 1: PWM, Phase-correct, top = 0xFF
      {               bit (WGM01), 0 },            // 2: CTC, top = OCR0A
      { bit (WGM00) | bit (WGM01), 0 },            // 3: Fast PWM, top = 0xFF
      { 0,                         bit (WGM02) },  // 4: Reserved
      { bit (WGM00),               bit (WGM02) },  // 5: PWM, Phase-correct, top = OCR0A
      {               bit (WGM01), bit (WGM02) },  // 6: Reserved
      { bit (WGM00) | bit (WGM01), bit (WGM02) },  // 7: Fast PWM, top = OCR0A

      };  // end of Timer0::Modes

      // Activation
      // Note: T0 is pin 6, Arduino port: D4
      enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T0_FALLING, T0_RISING };

      // what ports to toggle on timer fire
      enum { NO_PORT = 0,

        // pin 12, Arduino port: D6
        TOGGLE_A_ON_COMPARE  = bit (COM0A0),
        CLEAR_A_ON_COMPARE   = bit (COM0A1),
        SET_A_ON_COMPARE     = bit (COM0A0) | bit (COM0A1),

        // pin 11, Arduino port: D5
        TOGGLE_B_ON_COMPARE  = bit (COM0B0),
        CLEAR_B_ON_COMPARE   = bit (COM0B1),
        SET_B_ON_COMPARE     = bit (COM0B0) | bit (COM0B1),
      };

      // choose a timer mode, set which clock speed, and which port to toggle
      void setMode (const byte mode, const byte clock, const byte port)
      {
      if (mode < 0 || mode > 7)  // sanity check
        return;

      // reset existing flags
      TCCR0A = 0;
      TCCR0B = 0;

      TCCR0A |= (Modes [mode] [0]) | port;
      TCCR0B |= (Modes [mode] [1]) | clock;
      }  // end of Timer0::setMode

    }  // end of namespace Timer0

    /* ---------------------------------------------------------------
     Timer 1 setup
     --------------------------------------------------------------- */

    namespace Timer1
    {
      // TCCR1A, TCCR1B
      const byte Modes [16] [2] =
      {

      { 0,                         0 },            // 0: Normal, top = 0xFFFF
      { bit (WGM10),               0 },            // 1: PWM, Phase-correct, 8 bit, top = 0xFF
      {               bit (WGM11), 0 },            // 2: PWM, Phase-correct, 9 bit, top = 0x1FF
      { bit (WGM10) | bit (WGM11), 0 },            // 3: PWM, Phase-correct, 10 bit, top = 0x3FF
      { 0,                         bit (WGM12) },  // 4: CTC, top = OCR1A
      { bit (WGM10),               bit (WGM12) },  // 5: Fast PWM, 8 bit, top = 0xFF
      {               bit (WGM11), bit (WGM12) },  // 6: Fast PWM, 9 bit, top = 0x1FF
      { bit (WGM10) | bit (WGM11), bit (WGM12) },  // 7: Fast PWM, 10 bit, top = 0x3FF
      { 0,                                       bit (WGM13) },  // 8: PWM, phase and frequency correct, top = ICR1
      { bit (WGM10),                             bit (WGM13) },  // 9: PWM, phase and frequency correct, top = OCR1A
      {               bit (WGM11),               bit (WGM13) },  // 10: PWM, phase correct, top = ICR1A
      { bit (WGM10) | bit (WGM11),               bit (WGM13) },  // 11: PWM, phase correct, top = OCR1A
      { 0,                         bit (WGM12) | bit (WGM13) },  // 12: CTC, top = ICR1
      { bit (WGM10),               bit (WGM12) | bit (WGM13) },  // 13: reserved
      {               bit (WGM11), bit (WGM12) | bit (WGM13) },  // 14: Fast PWM, TOP = ICR1
      { bit (WGM10) | bit (WGM11), bit (WGM12) | bit (WGM13) },  // 15: Fast PWM, TOP = OCR1A

      };  // end of Timer1::Modes

      // Activation
      // Note: T1 is pin 11, Arduino port: D5
      enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T1_FALLING, T1_RISING };

      // what ports to toggle on timer fire
      enum { NO_PORT = 0,

        // pin 15, Arduino port: D9
        TOGGLE_A_ON_COMPARE  = bit (COM1A0),
        CLEAR_A_ON_COMPARE   = bit (COM1A1),
        SET_A_ON_COMPARE     = bit (COM1A0) | bit (COM1A1),

        // pin 16, Arduino port: D10
        TOGGLE_B_ON_COMPARE  = bit (COM1B0),
        CLEAR_B_ON_COMPARE   = bit (COM1B1),
        SET_B_ON_COMPARE     = bit (COM1B0) | bit (COM1B1),
      };

      // choose a timer mode, set which clock speed, and which port to toggle
      void setMode (const byte mode, const byte clock, const byte port)
      {
      if (mode < 0 || mode > 15)  // sanity check
        return;

      // reset existing flags
      TCCR1A = 0;
      TCCR1B = 0;

      TCCR1A |= (Modes [mode] [0]) | port;
      TCCR1B |= (Modes [mode] [1]) | clock;
      }  // end of Timer1::setMode

    }  // end of namespace Timer1

    /* ---------------------------------------------------------------
     Timer 2 setup
     --------------------------------------------------------------- */

    namespace Timer2
    {
      // TCCR2A, TCCR2B
      const byte Modes [8] [2] =
      {

      { 0,                         0 },            // 0: Normal, top = 0xFF
      { bit (WGM20),               0 },            // 1: PWM, Phase-correct, top = 0xFF
      {               bit (WGM21), 0 },            // 2: CTC, top = OCR2A
      { bit (WGM20) | bit (WGM21), 0 },            // 3: Fast PWM, top = 0xFF
      { 0,                         bit (WGM22) },  // 4: Reserved
      { bit (WGM20),               bit (WGM22) },  // 5: PWM, Phase-correct, top = OCR2A
      {               bit (WGM21), bit (WGM22) },  // 6: Reserved
      { bit (WGM20) | bit (WGM21), bit (WGM22) },  // 7: Fast PWM, top = OCR2A

      };  // end of Timer2::Modes

      // Activation
      enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_32, PRESCALE_64, PRESCALE_128, PRESCALE_256, PRESCALE_1024 };

      // what ports to toggle on timer fire
      enum { NO_PORT = 0,

        // pin 17, Arduino port: D11
        TOGGLE_A_ON_COMPARE  = bit (COM2A0),
        CLEAR_A_ON_COMPARE   = bit (COM2A1),
        SET_A_ON_COMPARE     = bit (COM2A0) | bit (COM2A1),

        // pin 5, Arduino port: D3
        TOGGLE_B_ON_COMPARE  = bit (COM2B0),
        CLEAR_B_ON_COMPARE   = bit (COM2B1),
        SET_B_ON_COMPARE     = bit (COM2B0) | bit (COM2B1),
      };

      // choose a timer mode, set which clock speed, and which port to toggle
      void setMode (const byte mode, const byte clock, const byte port)
      {
      if (mode < 0 || mode > 7)  // sanity check
        return;

      // reset existing flags
      TCCR2A = 0;
      TCCR2B = 0;
      TimerHelpers.h
      TCCR2A |= (Modes [mode] [0]) | port;
      TCCR2B |= (Modes [mode] [1]) | clock;
      }  // end of Timer2::setMode

    }  // end of namespace Timer2

    #endif

---

## References

* [Timers](http://www.gammon.com.au/timers)
* [Interrupts](http://www.gammon.com.au/interrupts)
* [Arduino Uno output to VGA monitor](http://www.gammon.com.au/forum/?id=11608)

  [1]: https://i.stack.imgur.com/EBkxW.jpg
  [2]: https://i.stack.imgur.com/KpXrW.png
  [3]: https://i.stack.imgur.com/zvu7k.jpg


body:
I'have been looking at the [AdaFruit NeoPixels][1] recently and am trying to understand how the addressing scheme works.

All of the examples I've seen explicitly identify the length of the string (number of neopixel units) and are typically set using an array of 24-bit values to control the color of a particular neopixel.

My question is two fold:

 1. How do the neopixels know where they are in a string to allow for addressing?
 2. If the neopixels know where they are in the string, would it not be possible to potentially feed the output of the last neoxpixel back to a microcontroller to determine the number of neopixels in the string?

**OP Note** (this is my interpretation and may be suspect, but it is more or less my take away)

Thank you for all the answers on this - it has been very enlightening from ALL of the answers. General take away, the NeoPixel is not "directly" addressable in the sense that you can pick pixel "X" of "n" pixels. The string of NeoPixels acts essentially as a gigantic shift-register (as stated in one of the answers) so to "address" a particular pixel you have to update a buffer that represents the state of the entire string and then shift it down the wire. This is why micro-controllers, such as an Arduino, would have limitations on how many NeoPixels it could control. This is also why it is more practical to define the number of pixels in the string and allocate memory to represent that state.

  [1]: https://learn.adafruit.com/search?q=neopixels

title: Is it possible to infer the length of a neopixel string using 1-wire protocol?

Answers: 5

body:
As far as I can make out (eg. [NeoPixels Revealed: How to (not need to) generate precisely timed signals](http://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/)) the NeoPixels are not in fact addressed, but are like a long shift register. Thus if you have 10 pixels, you have to send out 10 lots of RGB colours and then latch them. This is why you need to know how many pixels you have, so that you send out the right number of RGB bytes.

I don't think it would be particularly practical to try to detect how many pixels are in the chain, because the individual ones "reshape" the timing pulses.

body:
Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain.  Although the data wire may look continuous it isn't - the signal is electrically re-driven from each unit to the next.

For the RGB ones, they are logically three monochrome pixels of different colors, so they peel off three words rather than just one.

At any point in the chain you can determine how many logical pixels potentially remain to be updated, by counting the words you are passing on.  You can't of course tell if they are actually there, or if there are further pixels for which no data is being provided.  And you can't tell how many pixels preceded, other than to bound it by the amount of gap time from the previous update you received.

body:
As noted in Chris Stratton's answer, “Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain”.

This behavior is spelled out clearly in WS2812.pdf and WS2812B.pdf datasheets from http://www.world-semi.com :

>    The data transfer protocol use single NZR communication mode. After the pixel power-on reset, the DIN port receive data from controller, the first pixel collect initial 24bit data then sent to the internal data latch, the other data which reshaping by the internal signal reshaping amplification circuit sent to the next cascade pixel through the DO port. After transmission for each pixel, the signal to reduce 24bit. pixel adopt auto resha-ping transmit technology, making the pixel cascade number is not limited the signal transmission, only depend  on the speed of signal transmission.

This means that each WS2812 unit in a chain picks off the first 24-bit data packet, latches that data into an internal register, and passes the rest of the data on out, through reshaping circuitry.  Hence, if you put *m* packets of data into a chain and *k* packets come out, the chain length is *m-k* or more.  (The chain length may be more than *m-k* when *k* is zero.)

body:
It is possible to do this by feeding the end of the strip back into the arduino.  bunnie Huang blogged about doing this a few years ago: http://www.bunniestudios.com/blog/?p=3345

He has [schematics](http://bunniefoo.com/bunnie/phage-armband.PDF) and [firmware](https://github.com/ThePhage/phage-armband) which uses a [modified neopixel library](https://github.com/bunnie/Adafruit_NeoPixel) that can measure the length of the strip.

body:
This is certainly possible as I have now confirmed.

The code below will detect the length of a string of NeoPixels up to 10000 long.

<!-- language-all: lang-C++ -->

    /*
     *
     * Find length of NeoPixel string.
     * Author: Nick Gammon
     * Date:   11 March 2016
     */

    #include <SPI.h>

    const unsigned long LIMIT = 10000;  // maximum pixels to test

    // Note: Connect NeoPixels to MOSI (pin D11 on a Uno, pin D51 on a Mega)
    //       Connect the other end of the NeoPixels to D2 (External Interrupt 0)

    void sendByte (byte b)
      {
        // send one byte to the Neopixels - note that the "off" gap is partly handled by the loop overhead
        //   gaps measured empirically to be 1.7 µs to 2 µs, so we don't need to add any more of our own
        for (byte bit = 0; bit < 8; bit++)
          {
          if (b & 0x80) // is high-order bit set?
            SPI.transfer (0b11111100);  // 1 bit - 750 ns on + 250 ns off (acceptable "on" range 550 ns to 850 ns)
          else
            SPI.transfer (0b11100000);  // 0 bit - 375 ns on + 625 ns off (acceptable "on" range 200 ns to 500 ns)
          b <<= 1; // shift next bit into high-order position
        } // end of for each bit
    } // end of sendByte

    void ledsetup()
    {
      SPI.begin ();
      SPI.setClockDivider (SPI_CLOCK_DIV2);
      SPI.setBitOrder (MSBFIRST);
      SPI.setDataMode (SPI_MODE1);   // MOSI normally low.
    } // end of ledsetup

    void sendPixel (const byte r, const byte g, const byte b)
      {
      sendByte (g);
      sendByte (r);
      sendByte (b);
      } // end of sendPixel

    void show()
      {
      delayMicroseconds (7);
      } // end of show

    volatile bool triggered;

    void myISR ()
      {
      triggered = true;
      } // end of myISR

    void setup()
      {
      ledsetup();
      Serial.begin (115200);
      Serial.println (F("Starting ..."));
      attachInterrupt (0, myISR, RISING);
      } // end of setup

    unsigned int increment = 1000;
    unsigned int counter = increment;

    void loop()
      {
      noInterrupts ();
      triggered = false;
      EIFR = bit (INTF0);  // clear flag for interrupt 0

      for (unsigned int i = 0; i < counter; i++)
        sendPixel (5, 0, 0);
      TIMSK0 = bit (TOIE0);  // throw away timer overflow interrupt
      interrupts ();
      show ();  // latch the colours - handle the interrupt meantime

      if (triggered)
        {
        if (increment <= 1)
          {
          Serial.print (F("There are "));
          Serial.print (counter - 1);
          Serial.println (F(" NeoPixels in the string."));
          Serial.flush ();
          exit (0);
          }
        else
          {  // binary search
          counter -= increment;
          increment /= 2;
          } // end of if
        } // end of if triggered

      counter += increment;

      if (counter > LIMIT)
        {
        Serial.print (F("Could not find any NeoPixels after trying "));
        Serial.print (LIMIT);
        Serial.println (F(" pixels."));
        Serial.flush ();
        exit (0);
        }

      } // end of loop

It works by sending out increasingly long strings of 24 bits, and waiting for one to "shuffle off" the other end of the string.

Connect the Data In of the NeoPixels to MOSI (pin D11 on a Uno, pin D51 on a Mega) as this sketch uses SPI to generate the timed sequences. Connect the far end of the NeoPixels (Data Out) to pin D2 which is External Interrupt 0.

The sketch pumps out batches of pixels, and waits for an external interrupt. When that occurs it indicates that the last pixel in the chain was reached, and passed the pixel data out Data Out to the non-existent pixel past the end of the chain.

The number of pixels needed to do this is then noted.

The sketch does a "binary search" to speed things up for long strings of pixels. The worst-case scenario (where you have either 10000 pixels, or none at all) takes 6 seconds to execute. With less pixels it will be faster. I had under a second execution time for 3 pixels in my test string.

The sketch outputs a dull red (intensity 5) so you should see the pixels light up in red if all is well. If you wanted to do it unobtrusively, you could output black (as that still results in bits being sent down the string).

Example output:

<!-- language-all: lang-none -->

    Starting ...
    There are 3 NeoPixels in the string.


body: The way I understand SPI is that 3 wires are shared (MOSI, MISO, & SCHK). The slave select is pulled high when you want to write to a specific device. The 3 shared wires can be daisy chained. The TLC5940 LED Driver says that it uses SPI but I don't see any documentation about a slave select. Can I just include this in the standard daisy chaining and assign a new slave select? In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices. I thought that was the whole point of SPI. Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

title: Can I use the TLC5940 LED Driver if I'm already using other SPI devices on my Arduino mega?

Answers: 1

body:
> Can I just include this in the standard daisy chaining and assign a new slave select?

SPI is normally used as a parallel bus and requires MISO to be tri-state (disconnected when not selected).

> In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices.

The device does not have a chip select which gives a challenge. No direct wiring is possible but can be solved.

> Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

It is possible to connect the [TLC5940][1] but it requires some extra logic. You can for instance block the clock signal when it is not selected. This can be done with a MOSFET or [74HC125][2] and a pull-low resistor.

Cheers!

  [1]: http://www.ti.com/lit/ds/symlink/tlc5940.pdf
  [2]: http://www.nxp.com/documents/data_sheet/74HC_HCT125.pdf


body: I'm trying to setup home automation system controlled with webpage stored in SD card of Arduino, I was thinking if it was possible to set a login page, only combination of correct user id & password will be able to access the control page.

title: A simple login page on Arduino Uno

Answers: 5

body:
I guess you could do it with Javascript and HTML, and put the pages in the micro SD card.

But it will make it harder (if not impossible) to make the automation.

body:
Make simple webpage and put it in sd card. If it's just one page with few buttons and bit js even flash memory of controller would suffice.

In arduino code add lines that can detect click on particular button of webpage and control relay/motor etc.

Knowledge of basic post request using js can help. You can't implement php page in arduino as it needs complex processing at arduino side

body:
<s>Arduino cannot run a web server so it is not possible to do what you want with just using an Arduino board?.</s>
It seems we can run a web server, look at the answer by @Nick Gammon below.

By using a wifi shield and connecting to a local or public web server where your page is hosted you should be able to to do it.

Don't expect to load a full fledged page on an Arduino you have to try posting a few post and get requests to get this working. It will look like a terminal based login.

What is the control page you are trying to do?

If you are ok with spending more money try using a Raspberry pi + Arduino combination.

body:
Have you tried to change Arduino Uno board to Arduino Yun board?
Yun has a Linux distribution onboard and you can easy configure a web page to control physical objects.

**Here some examples:**
http://scuola.arduino.cc/lesson/b4EoRkV/Arduino_Yn_Intro_to_web_server
https://github.com/mat-lo/yun-examples

body:
I have a page about [a tiny web server](http://www.gammon.com.au/forum/?id=12942) for the Arduino Uno or similar boards. It simply isn't true that you can't make one, or that a much more powerful processor would be better. There are *some* limitations imposed by small amounts of RAM, but the library described there decodes incoming HTTP information "on the fly" so it can handle a reasonably large page.

You could put the data to be display into PROGMEM (more information [here](http://www.gammon.com.au/progmem)) or onto an SD card as someone suggested.

The login and password could be stored in EEPROM.


body:
If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

I am actually using an Intel Galileo, with the same pinout as an Arduino Uno Rev3.

title: Can I use IO10 as digital IO while using SPI interface?

Answers: 1

body:
> Can I use IO10 as digital IO while using SPI interface?

On AVR it must be OUTPUT when using SPI in master mode and INPUT in slave mode.

> If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

The SS pin (D10) has to be OUTPUT when using SPI master mode. It can be used for chip select on the SPI bus (slave select) or some other output function.

So far the Arduino design with AVR (e.g. ATmega328). The Intel Galileo based Arduino has the following block diagram:

[![Intel Galileo Logic Schematics][1]][1]

IO10-IO14 are multiplexed from SPI1 or GPIO. This implies that the SPI SS (IO10) signal is hardwired to the SPI controller when enabled. Last, according to the [product info][2] SPI is master only. More details schematics details [here][3].

Cheers!

  [1]: https://i.stack.imgur.com/57yHU.jpg
  [2]: https://www.arduino.cc/en/ArduinoCertified/IntelGalileo
  [3]: http://www.intel.com/content/dam/support/us/en/documents/galileo/sb/galileo_schematic.pdf


body:
I'm trying to control an Arduino Barebone from an arduino with relays.
Basically when the attiny starts it should switch on the arduino for 4 seconds.
The Arduino sends a signal back to a digital pin of the attiny and as long as it is set to high the attiny should leave it working.
If it is low the attiny should switch the relay of.

the problem is some changes to the code make the interrupt reset the attiny (which would switch of the arduino) othertimes- in this case.
the interrupt doesn't work at all.

<!-- language-all: c -->

    #include <avr/sleep.h>
    #include <avr/wdt.h>
    #include <avr/io.h>
    #include <avr/interrupt.h>

    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    int pinBoard = 0;
    bool boardOn = false;
    bool startBoard_flag = false;
    int pinBoardReturn = 3;

    volatile boolean f_wdt = 1;

    void setup() {
      cli();//disable interrupts during setup
      pinMode(pinBoard, OUTPUT);
      pinMode(pinBoardReturn, INPUT);
      setup_watchdog(9);
      cbi(ADCSRA, ADEN);                   // switch Analog to Digitalconverter OFF
      // cli();//disable interrupts during setup
      for (int i = 0; i < 10; i++) {
        digitalWrite(pinBoard, HIGH);
        delay(100);
        digitalWrite(pinBoard, LOW);
        delay(100);
      }

      PCMSK |= (1 << PCINT1); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
      GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

      startBoard();

      DDRB &= ~(1 << DDB1); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
      PORTB |= (1 << PB1); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
    }

    void startBoard() {
      digitalWrite(pinBoard, HIGH);
      boardOn = true;
      startBoard_flag = false;
      cli();                                  // Disable interrupts
      delay(4000);
    }

    void shutdownBoard() {
      digitalWrite(pinBoard, LOW);
      boardOn = false;
    }

    void loop() {
      if (f_wdt == 1) { // wait for timed out watchdog / flag is set when a watchdog timeout occurs
        f_wdt = 0;     // reset flag
        if (startBoard_flag) {
          startBoard();
        }
        bool boardReturn = digitalRead(pinBoardReturn);
        if (boardOn && !boardReturn) {
          shutdownBoard();
        }
        system_sleep();
      }
    }

    //****************************************************************
    // set system into the sleep state
    // system wakes up when wtchdog is timed out
    void system_sleep() {

      // GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
      // PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin

      set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
      sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
      sleep_cpu();                            // sleep

      // PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
      sleep_disable();                        // Clear SE bit

      // sei();                                  // Enable interrupts
    }

    //****************************************************************
    // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
    // 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
    void setup_watchdog(int ii) {

      byte bb;
      int ww;
      if (ii > 9 ) ii = 9;
      bb = ii & 7;
      if (ii > 7) bb |= (1 << 5);
      bb |= (1 << WDCE);
      ww = bb;

      MCUSR &= ~(1 << WDRF);
      // start timed sequence
      WDTCR  |= (1 << WDCE) | (1 << WDE);
      // set new watchdog timeout value
      WDTCR  = bb;
      WDTCR  |= _BV(WDIE);
    }
    //****************************************************************
    // Watchdog Interrupt Service / is executed when  watchdog timed out
    ISR(WDT_vect) {
      f_wdt = 1; // set global flag
    }

    ISR(PCINT_VECTOR) {
      for (int i = 0; i < 4; i++) {
        digitalWrite(pinBoard, HIGH);
        delay(1000);
        digitalWrite(pinBoard, LOW);
        delay(1000);
      }
      startBoard_flag = true;
      f_wdt = 1; // set global flag
    }

title: ATTiny watchdog and interrupt

Answers: 1

body:
Disassembling the `delay` code indicates it uses `micros` which needs interrupts on to work.

    void delay(unsigned long ms)
    {
     27a: cf 92        push r12
     27c: df 92        push r13
     27e: ef 92        push r14
     280: ff 92        push r15
     282: cf 93        push r28
     284: df 93        push r29
     286: 6b 01        movw r12, r22
     288: 7c 01        movw r14, r24
     uint16_t start = (uint16_t)micros();
     28a: d3 df        rcall .-90      ; 0x232 <micros>
     28c: eb 01        movw r28, r22

     while (ms > 0) {
     28e: c1 14        cp r12, r1
     290: d1 04        cpc r13, r1
     292: e1 04        cpc r14, r1
     294: f1 04        cpc r15, r1
     296: 79 f0        breq .+30      ; 0x2b6 <delay+0x3c>
      yield();
     298: ea d0        rcall .+468     ; 0x46e <yield>
      if (((uint16_t)micros() - start) >= 1000) {
     29a: cb df        rcall .-106     ; 0x232 <micros>
     29c: 6c 1b        sub r22, r28
     29e: 7d 0b        sbc r23, r29
     2a0: 68 3e        cpi r22, 0xE8 ; 232
     2a2: 73 40        sbci r23, 0x03 ; 3
     2a4: a0 f3        brcs .-24      ; 0x28e <delay+0x14>
       ms--;
     2a6: 81 e0        ldi r24, 0x01 ; 1
     2a8: c8 1a        sub r12, r24
     2aa: d1 08        sbc r13, r1
     2ac: e1 08        sbc r14, r1
     2ae: f1 08        sbc r15, r1
       start += 1000;
     2b0: c8 51        subi r28, 0x18 ; 24
     2b2: dc 4f        sbci r29, 0xFC ; 252
     2b4: ec cf        rjmp .-40      ; 0x28e <delay+0x14>
      }
     }
    }
     2b6: df 91        pop r29
     2b8: cf 91        pop r28
     2ba: ff 90        pop r15
     2bc: ef 90        pop r14
     2be: df 90        pop r13
     2c0: cf 90        pop r12
     2c2: 08 95        ret

---

That appears to confirm that the code in `wiring.c` is indeed what is being used on the ATtiny85 core:

    void delay(unsigned long ms)
    {
     uint16_t start = (uint16_t)micros();

     while (ms > 0) {
      yield();
      if (((uint16_t)micros() - start) >= 1000) {
       ms--;
       start += 1000;
      }
     }
    }

Turning interrupts off and then doing a `delay` is a Bad IdeaTM.

---

> So i would rather have a counter for the watchdog in order to wait for the specified time?

Using the watchdog timer is certainly one way of waiting for 4 seconds.


body:
I'm researching options for a project in which I need to send/receive SMS messages to/from multiple users of different service providers.
Hoping to reduce costs, I'm thinking of forwarding the messages to a different SIM card, depending of the user's service provider (since all of them have plans with free SMS for numbers of the same provider).
Arduino GSM Shield seemed like a good option, except the shield has only one SIM card slot.
I wonder: would it be possible to stack 3 shields (there are 3 mayor service providers in my country) on the same Arduino Board and use some reasonably straightforward programming to handle the task?
Thanks in advance.

title: Arduino GSM Shields stacking

Answers: 3

body:
Stacking might be hard, since they communicate on pins 2&3.  But if you work around that somehow, you could use Software Serial to access multiple GSM devices.

I think the GSM library has hardcoded the pins, and it might not share well with multiple, but you might be able to use SoftwareSerial or AltSoftSerial to do multiple connections, but that would be less straightforward.

body: Yes, that is easy. You need multiplexer (MUX) to forward communication pins (2 & 3) to the right GSM shield. Google for it to find the one that suits your budget.

body:
Hardware-wise this should be pretty easy to do. You need to connect pins 2 and 3 of each GSM shield to separate serial ports on the Arduino board. The best way to do this is to use an Arduino Mega, which has 4 hardware serial ports, this leaves you Serial for uploading sketches and communication to Serial Monitor. It's also possible that you could use a software serial library like AltSoftSerial but I wouldn't recommend it. You can carefully bend the pins 2 and 3 of two of the shields out before stacking them and then use jumper wires to connect those pins to the hardware serial pins of the Mega. The other pin of interest is pin 7, which is the modem reset pin. If you leave all the modems connected to pin 7 on the Arduino that means that there is no way to only reset a single modem. I'm not sure how much of an issue that would pose. So you might be better off to bend pin 7 on two of the shield out also and connect those to separate pins. You will also need to be sure to provide a power supply capable of supplying sufficient current. The [product page](https://www.arduino.cc/en/Main/ArduinoGSMShield) says each shield may require up to 1000mA.

Software-wise it gets much more tricky. Unfortunately the stock Arduino GSM library was not written to be very flexible. Instead of allowing you to pass it a Serial object it's hardcoded to do software serial on pins 2 and 3 so you would need to do quite a bit of work on the library to make it work for your needs. I'd recommend looking around to see if a more suitable library exists.


body:
I was surprised that this question had no answer on Stack Exchange and I can't find much about it elsewhere so, in the hopes that it will be useful to people other than myself, I'd like to ask:

How can one power two arduinos using the same power source? Such that the first is connected by barrel jack to a 12v transformer.

I saw [this youtube video][1] which _very_ briefly mentions doing this by make the connections:

> Ardu1 --> Ardu2
>
> 5V --> 5V
>
> GND --> GND

This surprised me as I was not aware the 5V could operate as a power input. I was expecting the use of the `VIN` pin somewhere along the line.

Am I correct in thinking that the second arduino would take power on it's `VIN` pin from `5V` on arduino one?

If so, where should the second arduino ground to?

  [1]: https://www.youtube.com/watch?v=Jndb2vpAWwU

title: Two arduinos one power source

Answers: 4

body: You could put the 12v from the barrel jack on both Arduninos Vin pins by jumpering the Vin pins together instead of the Vin->+5 or +5->+5.  Then they'd have independent protection and regulation of 1A, 5V through their NCP1117ST50T3G chips.

body:
I have powered numerous arduino's via the 5V pin. I would however call this an advanced usage because there are some limitation/dangers.

First of all: Power your arduino via 5V and plugin a powered USB cable or a powered plug and it may (probably will) damage your USB or arduino or both.

Secondly; it is best to assume that all arduino's are different on behalf of the behaviour of the +5V pin. I know for a fact there is a difference with uno,yun,due.

thirdly: The way it is used on the video -you linked to- (power jack 5V arduino 1 to 5V arduino 2 and ground arduino 1 to ground arduino 2) makes that all power goes through the voltage converter on the Arduino 1.
These voltage converters can not handle much current. This is only sufficient in very low power drawing applications.

It s not a good idea to connect the 5V pin of arduino 1 to Vin of the arduino 2. This because the voltage converter on arduino 2 will not be able to provide 5V to The 5V cirquitry.

It is mutch smarter to connect the Vin from arduino 1 to Vin of Arduino2.

When I power arduino's from "standard batteries" I use a switching power supply that powers the arduino over a cut in halve USB cable. This way it is lots safer as I can add power over the jack and I can not plugin a second USB cable.

body:
Connecting the +5V pins together is acceptable providing you don't exceed the total load that the source of the +5V can provide. This would be either:

* The maximum the *USB interface* can provide:

        Bus 003 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
        Device Descriptor:
        ...
          bDeviceClass            2 Communications
        ...
          idVendor           0x2341 Arduino SA
          idProduct          0x0043 Uno R3 (CDC ACM)
        ...
          Configuration Descriptor:
        ...
            MaxPower              100mA
That would seem to be 100 mA from doing `lsusb -v` on my Ubuntu system.

* The maximum that the *voltage regulator* can provide (if you are using the power jack, **or** Vin). This would depend on the model of Arduino, plus what your input voltage is (the higher the input voltage, the hotter the voltage regulator will get).

---

When I am testing things like sending I2C from one Arduino to another, I will often connect the USB to one of them, and just connect together the +5V pins (**and ground** of course) so that the second Arduino gets powered.

---

**Caveat** : my [page about power](http://www.gammon.com.au/power) indicates that without using sleep modes and other techniques, a Uno may consume 50 mA on its own. Thus connecting two Unos is likely to be reaching the limit that the USB interface can provide. Connecting three or more is likely to be problematic.

---

Regarding the USB power issue, see [How to get more than 100mA from a USB port](https://electronics.stackexchange.com/questions/5498/how-to-get-more-than-100ma-from-a-usb-port). On that page it says:

> **USB-100mA**

> USB by default will deliver 100mA of current (it is 500mW power because we know it is 5v, right?) to a device. This is the most you can pull from a USB hub that does not have its own power supply, as they never offer more than 4 ports and keep a greedy 100mA for themselves.

> ...

> Near the end of enumeration you setup device parameters. Very specifically the configuration descriptors. If you look on this website they will show you all of the different pieces that can be set. It shows that you can get right up to 500mA of power requested.

As the negotiation in this case appears to be requesting 100 mA (and not 500 mA) the port on the PC may well limit you to that.

body:
> This surprised me as I was not aware the 5V could operate as a power input. I was expecting the use of the VIN pin somewhere along the line.

Power is just power. It doesn't have a "direction" like an IO pin. It just flows from a point of higher potential to a point of lower potential. If you put a load onto the 5V pin then the power will flow out of the 5V pin, through the load, to the lower GROUND potential. And that is all the other Arduino is - a load. The power flows out of the 5V, into the other Arduino, through it, and down to the lower GROUND potential.

It's just like a rechargeable battery. Put a light on the battery and the electricity flows out of the battery to light the lamp. Apply a higher voltage to the battery from another supply and the power flows out of the supply into the battery, recharging it (or making it explode if the voltage is too high).


body:
I'm using a hall effect sensor A1356 (linear application) to measure the amount of fluid in a container. The fluid is in constant use. My doubt is I'm placing the sensor and the magnet assembly in place, such that when it is exactly half filled, the magnet's center will align with the center of the sensor. In this condition I get 100% duty cycle output from the sensor.

Condition 1: If the fluid is filled then the magnet moves above the sensor and the duty cycle reduces say to 90%.

Condition 2: If the fluid is consumed then the magnet will move below the sensor and the duty cycle reduces to say 90%.

How do I differentiate between the rise and fall of the fluid? Or is there a better way of orienting the magnet and the sensor such that this problem could be avoided?

I'm interfacing it with an Arduino UNO

title: Hall effect sensor direction detection using arduino

Answers: 1

body:
According to the data sheet (see below) the no-field PWM output is mid-range; north poles reduce it & south increase.

So if you had an arrangement whereby the float had north down & south up, ie a vertical bar-magnet, this would presumably give a rise-before-0 or fall-before-0 at the float vanishes, or a fall-to-minimum an rise-to-maximum as the float centres? The bit in the middle could be interesting!

From the datasheet:
"The presence of a south polarity magnetic field,
perpendicular to the branded surface of the package face,
increases the output duty cycle from its quiescent value toward
the maximum duty cycle limit. The amount of the output duty
cycle increase is proportional to the magnitude of the magnetic
field applied. Conversely, the application of a north polarity
field decreases the output duty cycle from its quiescent value."


body:
I have an Adafruit Motor Shield, the V1. I have been using this thing with my OPSEPP Uno and a stepper motor with no issues. (Powered by 12v DC wall wart [CASIO]).

My question, or issue, not sure yet, is this:

Why when I connect my motor directly to the 12v power supply it operates efficiently (for my purposes) and when I run it through my Arduino with the Adafruit Motor.h library does it not power the same.

Basically on direct connection it works fine, but I want to be able to regulate the connection and reverse it, change the speed, etc.

It is possible I am utilizing the library or the board wrong.

Can someone indicate why the power or, torque seems to drop when through the board. I have tried all KHZ all speeds etc, no way to get the same 12v power directly and modulate it?

title: Motor Shield not giving full power, LED DIMS

Answers: 1

body:
According to the [Adafruit page](https://www.adafruit.com/products/81) the V1 version of the shield is not as powerful as their V2 version.

Where is the 12V coming from to get to the shield? There isn't really 12V broken out on the Uno anywhere. If it comes from Vin then there is a 0.7V drop through the reverse polarity protection diode. Plus, the tracks on the Arduino board may not be thick enough to provide enough current.

It looks like the shield may take an external power source (it is hard to tell because they discontinued it). You could try using that.


body:
ESP8266 (01-512k,) Arduino Uno (clone), Arduino IDE, Python 2.7.6 on Macbook pro running OSX 10.10.4 64-bit.

Hello!

I'm using a motion sensor with the following setup:

Arduino Uno+motion sensor >>>sensor values>>>USB Serial>>>Laptop running Python code>>>Notification>>>WiFi>>>Web

The sensor generates a value. The value is displayed on the serial monitor. The python program is triggered into action by a specific value appearing on the serial monitor and the program sends an email notification.

I would like to replace that setup with the following:

Arduino Uno+motion sensor>>>sensor values>>>ESP8266 as transparent WiFi to Serial bridge>>>Laptop running Python code>>>Notification>>>WiFi>>>Web

Essentially, I want to get rid of the USB cable and use the ESP8266 as a transparent WiFi to Serial bridge. Of course, a battery would power the Arduino and ESP8266.

I read [this post][1]  and the Jeelabs/ ESP Link Readme. It seems that the ESP8266, once flashed with ESP Link, could replace a serial cable. But, can ESP Link replace the USB Serial in my current setup? If so, are there tutorials explaining how this can be done?

I did some further reading and researched the matter but so far I only found one use case similar to what I want to do. In the said use case, a virtual serial connection through WiFi was being executed via a server within the ESP8266. Unfortunately, there were no detailed explanations on how this was achieved and I don't think this would be suitable for my specific use.

Please let me know if further information or clarification is needed.

  [1]: http://hackaday.com/2015/09/18/transparent-esp8266-wifi-to-serial-bridge/

title: Is replacing USB serial WITH ESP8266+ESP link feasible?

Answers: 0


body:
I'm trying to write to and read from an AT93C46D eeprom using an Arduino UNO but for some reason the output I'm getting is not what I expect.

The eeprom has a data structure of 128 words of 8 bits each and I'm trying to write 10000010 to each word. When reading back the data however I get 11000001.
When I write 00000000 to all words I get 10000000 for all words when reading. I tested my code on 2 AT93C46D eeproms and both gave the same result.

It looks like the MSB is always 1 (when reading) for some reason.

I'm probably making a stupid mistake but I can't seem to find it, any help is greatly appreciated!

Datasheet: http://www.atmel.com/images/atmel-5193-seeprom-at93c46d-datasheet.pdf

    #include<SPI.h>
    #define DATAOUT 11//MOSI
    #define DATAIN  12//MISO
    #define SPICLOCK  13//sck
    #define SS 10//ss

    void setup()
    {
      pinMode(SS,OUTPUT);
      pinMode(DATAOUT, OUTPUT);
      pinMode(DATAIN, INPUT);
      pinMode(SPICLOCK,OUTPUT);
      digitalWrite(SS,LOW);

      Serial.begin(9600);

      SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));

      fill();

      dump();
    }

    void loop()
    {

    }

    void fill()
    {
      Serial.println("Send EWEN opcode");
      digitalWrite(SS,HIGH);
      SPI.transfer(B10011); //EWEN
      SPI.transfer(B0000000);
      digitalWrite(SS,LOW);

      delay(100);

      for (int i=0; i < 128; i++) {
        digitalWrite(SS,HIGH);
        SPI.transfer(B101);
        SPI.transfer(i);
        SPI.transfer(B10000010);
        delay(10);
        digitalWrite(SS,LOW);
      }

      delay(100);

      Serial.println("Send EWDS opcode");
      digitalWrite(SS,HIGH);
      SPI.transfer(B1000); //EWDS
      SPI.transfer(B00000000);
      digitalWrite(SS,LOW);

      delay(10);
    }

    void dump(){
      Serial.println("Dumping AT93C46D");

      byte b;

      for (int i=0; i < 128; i++) {
        digitalWrite(SS,HIGH);
        SPI.transfer(B110); //read opcode
        SPI.transfer(i);
        b = SPI.transfer(B00000000); //clock data out
        digitalWrite(SS,LOW);
        Serial.println(b, BIN);
      }
    }

title: Arduino UNO and SPI eeprom (AT93C46D)

Answers: 1

body:
After looking at the product spec again I think it might be possible to get this working. The protocol is MSB with a start bit S followed by two bit op-code, and parameters. SPI on AVR is 8-bit transfer but transfer can be byte aligned with the start bit.

READ is op-code(10) followed by 7-bit address, a dummy bit and the read value. That is in total 11+8-bits. Mapping that to 8-bit transfer would be:

    spi.transfer(0b110);
    spi.transfer(addr << 1);
    data = spi.transfer(0);

That will give 5-bit zero, start-bit, op-code in the first transfer, and followed by 7-bit address and dummy bit (LSB) in second transfer. The third transfer is the read data.

EWEN would map to:

    spi.transfer(0b1001);
    spi.transfer(0b10000000);

EWEN has op-code(00), followed by 9-bits, 0b11XXXXXXX.

The WRITE operation becomes:

    spi.transfer(0b10);
    spi.transfer(0x80 | addr);
    spi.transfer(data);

Cheers!


body:
I found that using more float variable in arduino uno(atmega328p) slows it down (very muck that i can get slow response)

so, how to speed up it processing ?

my data are euler's angle with 2 digits and 2 decimals like give below

XX.XX , where X is number Eg.(85.63,34.65,etc) (from MPU6050)

How to process it fast?

title: How to speed up

Answers: 1

body:
A technique commonly used in digital signal processing is using [fixed-point arithmetic](https://en.wikipedia.org/wiki/Fixed-point_arithmetic) instead of [floating point](https://en.wikipedia.org/wiki/Floating_point).  In fixed-point arithmetic, one calculates using numbers multiplied by some power of two or ten, and in effect mentally positions a binary or decimal point several bits or digits up while calculating. [Numerical analysis](https://en.wikipedia.org/wiki/Numerical_analysis#Generation_and_propagation_of_errors) may be needed to determine if the arithmetic is accurate enough and whether numbers will stay in bounds, or overflow.

The question doesn't say what's being calculated; it's possible fixed-point arithmetic might work, or might not.  A short self-contained fixed-point calculation that starts with MPU6050 sensor readings is likely to be ok, but long-term calculations (eg, integration of accelerations to get velocities and positions) that let error accumulate without reset may go too far astray.  In such a case, numerical analysis can indicate what intermediate results need to be stored most accurately.

Typically, when slow code is posted someone can point out speedups, from a few percent up to dozens of times faster.  Changes may range from adding or removing parentheses or temporary variables, to refactoring, to substitution of a new algorithm.


body:
I am new to Arduino and physical computing When I measure the wire coming from any **UNSET** Arduino uno pin, the result is approximately 2 volts **even the "ANALOG IN" pins**. Considering that the pins which been set to HIGH and LOW are giving 5 and 0 volts "which is cool".
Is that the nature of Arduino or is that a failure caused by short or anything else?

title: Why all unset pins of my Arduino Uno are outputting 2 volts?

Answers: 3

body:
After a microcontroller reset, AVR IO pins default to input.  In this state they have high impedance.  For example, according to the Atmel ATmega328 spec sheet doc8271 Table 29-15, analog input impedance typically can be taken as 100 MΩ for design purposes.  (Input pin impedance may in fact be orders of magnitude more, effectively an open circuit except for leakage currents of a few nanoamps.)  Each pin has a few pF (5-10?) of capacitance [[1](https://electronics.stackexchange.com/questions/67171/input-impedance-of-arduino-uno-analog-pins),[2](http://www.avrfreaks.net/forum/avr-input-capacitance),[3](http://www.avrfreaks.net/forum/avr-io-pin-capacitance-considerations),[4](http://www.avrfreaks.net/forum/comparator-input-impedance?name=PNphpBB2&file=viewtopic&t=73009)] which in general is small compared to stray capacitances of attached wiring.

When stray electromagnetic fields charge the pin and stray capacitances, a small voltage develops on the pin.  You could connect a 1 to 10 MΩ resistor between the pin and ground, to avoid the 2 V you are seeing.

body:
The electric shocks being felt is due to leakage current from the laptop's switchmode power supply. All unearthed mains powered switchmode plug pack power supplies leak a few micro amps and voltages in excess of 80 volts AC as measured from the plug packs output socket to ground will be observed when measuring with multimeters having 10 meg ohm input impedance.

The solution is to have the GND pin of the arduino board connected to earth. Here in Australia all computer power supplies are grounded via the 3 pin power plug.

body:
The pin is default to Tri-State or High-impedance(Hi-Z) which means they do not either sink or source current. Just as others say it's a matter about electromagnetic or some such. A voltmeter can measure its voltage because the current it takes is small enough(close to or smaller than the leakage current). The real value is undefined when you are not measuring it. Instead of reading analog pin values, You can try reading digital pins to take a better look at "floating".

A Hi-Z pin can absolutely power nothing from LED to other big stuffs. If all you want is just stable readings, well, this is where pull-up or pull-down resistors come in place. Typically these resistors can be from 10KΩ to 10MΩ, ensuring that when the pin is not connected they will provide the pins with stable values while when connected the influence of pulls can be safely ignored.


body:
I am using an Arduino Due as a prototyping board for a microcontroller project. The due has the chip Atmel ATSAM3X8E, with an ARM Cortex-M3 core. I am programming the flash directly using Atmel Studio and SAM-BA over USB, I am not using the arduino tools or bootloader in any way, at least not to my knowledge. I am powering it over the USB port on the arduino.

I am able to program the flash and select flash for boot, but the problem is that the chip never works the first time I plug in the power. But if I cut the power and try again, it boots normally and the program starts. Then if I cut the power and wait a while, I have to power it up another two times before it works. It's like there is some volatile charge or RAM in there that needs to have been powered within the last minute for the chip to boot at power up like it should, but I don't know what. The result is the same if I plug the USB into my computer, or from a phone charger. Also the same whether I use the native or arduino programming USB port to power it.

title: Atmel SAM MCU (on Arduino Due) only boots after second power up

Answers: 0


body:
I have an Arduino Leonardo that I am using to emulate a Keyboard using the keyboard.press function with the Keyboard.h libraries. I have gotten the Keyboard.press function to work on my windows and mac- the keystroke I used was CTRL N to test- this worked well. So my ultimate goal was to emulate a keystroke ,F1, on a PC that is not running an OS- meaning I want the sketch to run in BIOS. for context, This keystroke (F1) tells the computer to use the a bootable USB to run a certain MathWorks OS.
The problem, when it is plugged in the Arduino shows that power is receieved by lighting the POWER LED but it does not begin the sketch. The RED LED that usually flashes ( TX or RX im not sure) when it is running a sketch is not happening (not illuminating).
How can I troubleshoot this and what could be happening? I have read that maybe too much serial info is going to the board so it confuses the board and does not begin the sketch.

I appreciate all the following help!!

title: Arduino Leonardo Pro Mini will not begin sketch when connected to BIOS not an OS

Answers: 2

body:
Because the computer doesn't have a full OS at POST time any USB keyboards attached to the system have to operate in a special "Boot Keyboard" mode.

> Keyboards that implement the USB Boot Keyboard profile specified in the USB Device Class Definition for Human Interface Devices (HID) v1.11 and are explicitly configured to use the boot protocol will interrupt the CPU every time the keyboard is polled even if there is no change in state unless the USB controller overrides this behavior, and are limited to 6-key rollover (6KRO). This profile is intended to allow the BIOS to handle a USB keyboard in the absence of a USB-aware operating system. The recommended profile for keyboards that are not in boot mode in this specification limits keyboards to 6KRO and causes them to respond to an interrupt with a status report at least every half second even if there is no state change in the keyboard unless the USB controller overrides this behavior in order to implement typematic (the function that causes keys to repeat when they are held long enough). However, keyboards in non-boot mode are free to implement an alternative HID profile.
>
> -- Wikipedia

Since it was not expected that anyone would be using the Leonardo to operate in the BIOS that functionality has never been implemented. The choice was to implement the entire system, which would have left less room for your sketch, or to just implement the parts that the majority of people would find useful (that is keyboard, mouse, joystick, etc) and leave out the extra stuff, leaving as much room for sketches as possible.

They chose the latter, since as I am sure you are well aware: "The needs of the many outweigh the needs of the one".

For your rather specific case it may be easiest to butcher an old USB keyboard and work out which pair of inputs to the matrix, when connected together, perform the function you require and design some small interface circuit to allow the Arduino to trigger that function.

body: Thanks for the Input, you were quite right Majenko. The keyboard.press does not work in BIOS. The problem has been solved by a patch ( I'm not sure if that's the correct terminology) I found on github. By a Nicohood, here is the project if anyone find this having the same issues as me.https://github.com/NicoHood/HID?files=1


body:
I have accidentally released the magic smoke from the regulator on a digispark board. I did this when I accidentally plugged a circuit into the 5V and the VIn instead of the 5V and Gnd, and then plugged the board into the USB port.

The attiny chip still works - I know because I plugged it in to the USB ,with no circuitry attached, and the uploaded program still runs happily.

My question is, is there any possibility that when the magic smoke was released from the regulator, the attiny was also damaged?

Secondly, is there any harm in leaving the dead regulator on the board? Or am I better off cutting it off?

title: Regulator magic smoke

Answers: 1

body: Linear voltage regulators have an internal parasitic diode that shorts the output to the input. You have burned out this diode which has destroyed the regulator, but it is highly unlikely that any other components have been damaged. You can get away with cutting away the legs of the regulator, but complete removal will be difficult due to the large size of the tab connection and will likely result in damage to the other components.


body:
Here is my setup:

I'm trying to read the GPS data from SKG13BL which is connected to an Arduino Uno.

The GPS seems to be working fine as I could see the green status light blinks after a while (I think it takes time to fix the position).

I connected TTL of SKG13BL to UNO Digital pins 2 & 3 and connected the ground as well.

Here is the image of the connection:

[![Photo of GPS Receiver SKG13BL and Arduino][1]][1]

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

I'm using the TinyGPS test with GPS device sketch to read the data. but I always get something like this,

> **** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   30862 0         116
**** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   30885 0         116
**** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   30929 0         117
**** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   30952 0         117
**** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   30985 0         117
**** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   31019 0         117
**** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   31041 0         117
**** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   31086 0         117
**** **** *******  *******   **** *******    *******    **** ******* ****** ***** ***   0        0.00   ***   31109 0         117

I tried swapping the pins, using external power source instead of Arduino's  3.3, but there is no change in the result, any advice would greatly help.

**Update 2/26**

I changed the pin here to 10 & 11, and using this code

<!-- language: c -->

    #include <SoftwareSerial.h>
    #include <TinyGPS.h>

    SoftwareSerial mySerial(10, 11); // RX, TX
    TinyGPS gps; // create gps object

    long lat,lon; // create variable for latitude and longitude object

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(57600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Goodnight moon!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      mySerial.println("Hello, world?");
    }

    void loop() { // run over and over
      if (mySerial.available()) {
        Serial.write(mySerial.read());
        //gps.encode(mySerial.read());
        if(gps.encode(mySerial.read()))
          { // encode gps data
          gps.get_position(&lat,&lon); // get latitude and longitude
          // display position
          Serial.print("Position: ");
          Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
          Serial.print("lon: ");Serial.println(lon); // print longitude
          }

      }

    }

But this only displays the below, `lon` and `lat` not coming up in the feed even after waiting for an hour.

> $GPRMC,043721.000,A,1301.6666,N,07740.9169,E,0.13,343.86,260216,,,D*61
> $GPGGA,043722.000,1301.6666,N,07740.9169,E,2,7,1.36,902.9,M,-88.1,M,0000,0000*72 $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88*37
> $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28*71
> $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,*46
> $GPGSV,4,3,13,27,18,238,12,25,15,087,16,26,13,180,,08,11,268,*7A
> $GPGSV,4,4,13,11,09,311,20*43
> $GPRMC,043722.000,A,1301.6666,N,07740.9169,E,0.26,343.86,260216,,,D*64
> $GPGGA,043723.000,1301.6665,N,07740.9169,E,2,7,1.36,902.9,M,-88.1,M,0000,0000*70 $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88*37
> $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28*71
> $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,*46
> $GPGSV,4,3,13,27,18,238,12,25,15,087,16,26,13,180,,08,11,268,*7A
> $GPGSV,4,4,13,11,09,311,20*43
> $GPRMC,043723.000,A,1301.6665,N,07740.9169,E,0.33,343.86,260216,,,D*62
> $GPGGA,043724.000,1301.6664,N,07740.9170,E,2,7,1.36,902.9,M,-88.1,M,0000,0000*7E $GPGSA,A,3,10,31,18,11,193,14,22,,,,,,1.62,1.36,0.88*37
> $GPGSV,4,1,13,41,73,157,43,31,72,187,37,10,47,048,33,14,41,003,28*71
> $GPGSV,4,2,13,18,32,088,16,193,30,107,29,22,27,330,21,21,26,154,*46
> $GPGSV,4,3,13,27,18,238,,25,15,087,16,26,13,180,,08,11,268,*79
> $GPGSV,4,4,13,11,09,311,20*43

**Updated code on 3/1**

This one works perfectly and provides the latitude and longitude.

Thank you @slash-dev and @altinturk

<!-- language: c -->

    #include <SoftwareSerial.h>
    #include <TinyGPS.h>

    SoftwareSerial mySerial(10, 11); // RX, TX
    TinyGPS gps; // create gps object

    long lat,lon; // create variable for latitude and longitude object

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(57600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Goodnight moon!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      mySerial.println("Hello, world?");
    }

    void loop() { // run over and over
      if (mySerial.available()) {

    char c = mySerial.read();
    Serial.write( c );
    if (gps.encode( c ))
          { // encode gps data
          gps.get_position(&lat,&lon); // get latitude and longitude
          // display position
          Serial.print("Position: ");
          Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
          Serial.print("lon: ");Serial.println(lon); // print longitude
          }

      }

    }

Here is the output

> $GPGSA,A,3,14,20,21,18,29,15,10,,,,,,2.59,1.13,2.33*0E
> $GPGSV,4,1,13,29,63,172,35,40,59,241,34,15,45,039,43,18,44,324,51*7A
> $GPGSV,4,2,13,21,42,350,46,10,27,284,46,24,27,116,19,14,25,209,17*76
> $GPGSV,4,3,13,20,24,037,46,193,23,064,39,25,10,180,16,26,08,268,*44
> $GPGSV,4,4,13,16,01,294,*42
> $GPRMC,003218.000,A,1301.6703,N,07740.9225,E,0.02,0.00,010316,,,D*6D
> **Position: lat: 1******8 lon: 7*****42**

title: GPS Receiver SKG13BL + Arduino - Having trouble receiving data

Answers: 2

body:
Seems you are able to receive data properly (according to your the update.) I was using TinyGPS++, an advanced version of TinyGps (http://arduiniana.org/libraries/tinygpsplus/), maybe those can help you:
Try

    Serial.print("LAT=");  Serial.println(gps.location.lat(), 6);
    Serial.print("LONG="); Serial.println(gps.location.lng(), 6);

GPS cannot get any data indoors. Put your gps close to a window or better -directly outside. First of everything you will get a date&time data on the output, then number of satellites, then the Lat/lon data. But GPS has to receive data indoors.
On some chips there is a LED starts blinking once it gets a fix from any satellite. Keep an eye on it.

I realized this small issue when my phone (used for "calibration") couldn't get a fix by its embedded GPS without any cell/network assistance. You should try if you get any signals where you put your device.

body:
You are consuming the received characters with the debug print:

    Serial.write(mySerial.read());
    //gps.encode(mySerial.read());
    if(gps.encode(mySerial.read()))

Instead, do this:

    char c = mySerial.read();
    Serial.write( c );
    if (gps.encode( c ))

Also, `SoftwareSerial` is a real CPU-killer.  Try [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) instead.  It's much more efficient and reliable.  Sometimes other interrupts, like `Serial.print`, can cause `SoftwareSerial` to be unreliable.  Echoing the received characters may be enough to cause characters to be lost.  NeoSWSerial is not nearly as susceptible.

And while you're at it, take a look at another library I wrote, [NeoGPS](https://github.com/SlashDevin/NeoGPS).  It's the fastest and smallest library out there, especially when you configure it to only parse the fields and messages that you use.  For example, if you only need lat/lon, disable all the other fields (time, alt, speed, sats, etc.) and all the other messages (just RMC, no GGA, no GSA, no GSV).  Saves lots of RAM and CPU time!


body:
I've nine functions each of type void as follow:

    void zero();
    void one();
    void two();
    void three();
    void four();
    void five();
    void six();
    void seven();
    void eight();
    void nine();

I've put all these functions into an array pointer as follow (without any error):

    typedef void (*num_func) ();
    num_func functions[] = { zero, one, two, three, four, five, six, seven, eight, nine};

Now I'm writing an arduino library and wanting to achieve the same, but after hours of thinking I'm not able to achieve. Please help me how can I accomplish this in a library?

Thanks in advance.

title: How to write array of functions in arduino library?

Answers: 2

body:
First you need a header file - let's say lib.h:

    #ifndef LIB_H
    #define LIB_H

    typedef void (*num_func) ();
    extern num_func functions[];

    #endif

And then the implementation, lib.cpp:

    #include "lib.h"

    void zero();
    void one();
    void two();
    void three();
    void four();
    void five();
    void six();
    void seven();
    void eight();
    void nine();

    num_func functions[] = { zero, one, two, three, four, five, six, seven, eight, nine};

The functions could be declared as static (if you want to hide them) and they do need implementation. They are only forward declarations above. Below is a snippet of a sketch using the library (assuming that it is within the sketch folder).

    #include "lib.h"

    void setup()
    {
      ...
    }
    void loop()
    {
      ...
      // Call to the one() function
      functions[1]();
      ...
    }

Cheers!

body:
This was a bit fiddly to get right. I got inspiration from [How do I create and use an array of pointer-to-member-function?](https://isocpp.org/wiki/faq/pointers-to-members#array-memfnptrs)

Based on my [post about Function pointers / function callbacks / function variables](http://www.gammon.com.au/forum/?id=12607) I modified it to work with class functions:

    class foo {

      public:

       void doAction0 ()
        {
          Serial.println (0);
        }

        void doAction1 ()
        {
          Serial.println (1);
        }

        void doAction2 ()
        {
          Serial.println (2);
        }

        void doAction3 ()
        {
          Serial.println (3);
        }

        void doAction4 ()
        {
          Serial.println (4);
        }

       // typedef for class function
       typedef void (foo::*GeneralFunction) ();

       // array of function pointers
        GeneralFunction doActionsArray [5] =
        {
          &foo::doAction0,
          &foo::doAction1,
          &foo::doAction2,
          &foo::doAction3,
          &foo::doAction4,
        };

    };  // end of class foo

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ();
      Serial.println (F("Starting"));

      // test instance of foo
      foo bar;

      for (int i = 0; i < 5; i++)
        {
        // get member function pointer from array
        foo::GeneralFunction f = bar.foo::doActionsArray [i];
        // call the function
        (bar.*f) ();
        }  // end of for loop

    }  // end of setup

    void loop () { }

This compiles OK and prints:

    Starting
    0
    1
    2
    3
    4

---

## Amended answer

I was wondering why you needed to specify `bar` in this line above:

        foo::GeneralFunction f = bar.foo::doActionsArray [i];

The reason is that the code above had the array as non-static, and thus a copy belonged to each instance of the class. This doesn't make a huge amount of sense, so the modified code below makes the array `static` and `const`. That is, the array should be the same for every instance of `foo` and also never change.

Modified code below:

    class foo {

      public:

       void doAction0 ()
        {
          Serial.println (0);
        }

        void doAction1 ()
        {
          Serial.println (1);
        }

        void doAction2 ()
        {
          Serial.println (2);
        }

        void doAction3 ()
        {
          Serial.println (3);
        }

        void doAction4 ()
        {
          Serial.println (4);
        }

       // typedef for class function
       typedef void (foo::*GeneralFunction) ();

       static const GeneralFunction doActionsArray [5];

    };  // end of class foo

     // array of function pointers
    const foo::GeneralFunction foo::doActionsArray [5] =
      {
        &foo::doAction0,
        &foo::doAction1,
        &foo::doAction2,
        &foo::doAction3,
        &foo::doAction4,
      };

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ();
      Serial.println (F("Starting"));

      // test instance of foo
      foo bar;

      for (int i = 0; i < 5; i++)
        {
        // get member function pointer from array
        foo::GeneralFunction f = foo::doActionsArray [i];
        // call the function
        (bar.*f) ();
        }

    }  // end of setup

    void loop () { }

This will also save RAM, as the array of function pointers only exists once, not once per instance of the class.


body:
I have the following problem

I have a pro mini clone, with 328/5V. It was successfully working in my board. I pulled it out of the board, and wanted to update my software. I connected it to my FTDI, arduino was normal by this time. Power on LED was on. I stared uploading, my sketch compiled and started writing. While it was writing, my 3.5 year old daughter who approached me from behind and whom I did not see pulled the Arduino out of FTDI - "what is that nice red light?" Of course writing failed.
Now, when I connect the arduino to FTDI, it is dead. No LEDs light up, no sync... what to do? Any chance to revive it?

title: Arduino Pro Mini

Answers: 1

body: Check for physical damage! Solder connection of the programming pins to the board was damaged in my case. Resoldering helped!


body:
I have an arduino UNO hooked up to a neopixel LED strip with 148 lights.  Most of the time it works fine, but when I upload a program that changes the brightness frequently, particularly when I increase brightness, only the first 8 LEDs continue responding.  The rest get stuck.

Here's an example of the kind of code that sets this issue off.  To fix it, I usually have to restart the lights and the arduino and sometimes upload a blank program to the arduino.

I'm pretty new to arduino programming so and help would be really appreciated.  Thank you.

    #include "FastLED.h"

    FASTLED_USING_NAMESPACE

    // FAST LED definitions
    #define DATA_PIN    3
    #define LED_TYPE    WS2812B
    #define COLOR_ORDER GRB
    #define NUM_LEDS    148

    CRGB leds[NUM_LEDS];
    #define DATA_PIN 3 // Output Pin to Data Line on Strip

    int fadeAmount = 5;
    int brightness = 0;

    void setup()
    {
       FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
    }

    void loop()
    {
       for(int i = 0; i < NUM_LEDS; i++ )
       {
       leds[i].setRGB(0,255,0);
       leds[i].fadeLightBy(brightness);
      }
      FastLED.show();
      brightness = brightness + fadeAmount;
      // reverse the direction of the fading at the ends of the fade:
      if(brightness == 0 || brightness == 255)
      {
        fadeAmount = -fadeAmount ;
      }
      delay(20);
    }

title: Neopixel led strip stops responding after change in brightness

Answers: 2

body:
It is almost certainly a power issue. The [Adafruit page](https://www.adafruit.com/products/2547) about one of those types of Neopixels says:

> Don't forget, with 256 LEDs, you could use over 15A of current if you turn on all the LEDs on to white (which we really do not recommend because we don't think the flex PCB can handle that much current). Try to keep the current draw at under 5A ...

Increasing the brightness increases the current drawn. Do you have a heavy-duty power supply? Are the connecting leads sufficient for (say) 8 amps of current?

---

## New information based on comments made

Based on comments by Lorenz I now think it is more likely to be that they are overheating.

>  I have the strip embedded in a picture frame with epoxy resin over it.

That makes it difficult for the ICs to cool down, and LEDs generate heat. If you search for "neopixels heat" you find quite a few matches. Some suggestions made are to use a heat sink or a fan. If this isn't practical for you, then running at a lower PWM rate (ie. not as bright) and not as saturated colour, could help keep the heat down.

You don't want to "cook" one of the early pixels, because each one has to pass the data on to the next one in sequence, so if you lose an early one, you lose everything after it, particularly if you can't get at it to replace one.

---

## Postscript regarding heat

I have been testing a NeoPixel with a temperature sensor. Displaying full white (255/255/255) it has reached about 44°C. So clearly it warms up. However this is in the open air with just some sticky-tape holding the sensor onto the LED. According to the spec the chip can operate at up to 80°C, so this is within range.

However if the whole thing was sealed in epoxy, then the heat being generated would have much less chance of escaping into the ambient air, and thus would be likely to get a lot hotter.

body:
After doing more research and getting feedback on the Adafruit forum [here][1], it appears that the problem was a cracked solder joint.  I managed to get access to the strip and wiggled it a little and the problem has gone away.  The recommendation is to reflow the joint by adding a little solder over the data connection between where the LEDs stop being responsive.

  [1]: https://forums.adafruit.com/viewtopic.php?f=8&t=91214&p=459815


body:
I need to update simultaneously all the outputs of a specific port.

I am familiar with using micro-processors assembly language. After initializing a port (Data Direction Register), I can write to that port and all outputs will update simultaneously.

In the Arduino commands  : I am aware of how to configure pins, such as pinMode(pin, mode), to make a pin an output or input.

I know of the digitalWrite(pin, value) , but this only updates one pin per command.

For timing reasons, I need to update several (same port) outputs without any time delay.

Normally (using assembly language) , I would keep a register with the data I desire on the output port, and write that register's data to the port.

Is there a command I can use in Arduino to accomplish the same thing?
If not a single command, what other choices do I have?

I use Arduino  micro,  UNO,  but I think the question might be valid for most Arduino

title: How to update multiple outputs simultaneously

Answers: 2

body:
Yes, the ports of an Uno are addressed in C/C++ as PORTB, PORTC, and PORTD respectively, each 8 bits wide. You can read them or assign to them. Other processors' ports have similar names. Of course the pins' port assignments and functions differ from one to the other, which is one reason for providing the single-pin pinMode() and digitalRead(), digitalWrite() functions. But where you need to deal directly with the hardware (and probably don't care about chip-to-chip portability), the registers are exposed with the above symbols.

Also note that most other CPU registers are exposed the same way - the ports' data-direction registers as DDRA, DDRB, DDRC. You may not care about setting them up simultaneously, but if you wanted to make all of your hardware accesses similarly (and save the flash space for the portable pin functions), you could.

Update:

> Is there a specific command I can use ? Such as Write PortD ?

Yes, you can use the PORTx names like any other C/C++ variable:

`PORTD = 0xFF;`

`PORTD ^= 0x02;`

`if( (PORTD & 0x40) != 0 ){`
, for just a couple of examples - just like real C! :-)

PS: [Pighixxx][1] makes absolutely top-notch pinout diagrams for boards & processors. Here is his diagram for the [28-pin DIP-packaged AtMega328p][2] for instance. They're extremely useful when you're working with a chip at the port or board level.

  [1]: http://www.pighixxx.com/test/
  [2]: http://www.pighixxx.com/test/portfolio-items/atmega328/?portfolioID=337

body:
If you need to do more than 8 (especially LOTS more), and timing is very critical, you can use a Serial In, Parallel Out (SIPO) chip, such as the 74HC595 - it also saves a lot of pins on the Arduino.

To use it, you need 3 pins connected to the Arduino. You send one bit to the chip from the Arduino for each output, then when you have them all set, you toggle the Latch pin - all output pins change at the same time. The chip has 8 outputs.

Another advantage of a chip like this is that you can daisy-chain them - with the same 3 pins, you can control as many pins as you like (subject to power availability, of course!).

Read https://www.arduino.cc/en/Tutorial/ShiftOut for more information on how to use them. They are dirt cheap (about US$1.26 each if you buy 10 from AliExpress, shipped to NZ, which is where I am).


body:
[![Serial Monitor][1]][1]

My Serial Monitor is displaying unreadable characters.  If anybody can give me some insight on why this would be happening please let me know.

Thank You.

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

title: Serial monitor listing unreadable characters

Answers: 3

body:
Change `Serial.write` to `Serial.print` (or `Serial.println`).

`write` writes in binary, which gives you unprintable characters.

body: Make sure the selected baud (like 115200, 57600) in Serial Monitor matched the one specified in code like Serial.begin(115200)

body: I had the same problem, baud rate was the same in the code as it was in the serial monitor. I tried changing the baud rate in the code to 19200 and the same in the serial terminal and that fixed the problem. Hope this helps, not sure why it wasn't working with the 9600 baud value. Also found that clicking on the wrong baud rate in the terminal and back on the right one fixed the issue with it displaying gibberish.


body:
Proceeding is the relevant part of the code for the problem I'm asking assistance with.  I'm attempting to vary the speed of the robots motors with PWM. The left motor speed can be varied numerical. The right motor fails to move. Any ideas is appreciated. The motor speed code is at the end of the sketch.
Any assistance is greatly appreciated.

    //Below are the symbolic constants. Instead of having to type in a non-sensical pin number each time we want to do something we can write an easy to understand name which represents the pin, the compiler will then replace the names with the numbers
     #define LeftMotorForward 8
     #define LeftMotorBackward 9
     #define LeftMotorSpeed 10
     #define RightMotorForward 6
     #define RightMotorBackward 7
     #define RightMotorSpeed 5
     #define USTrigger 3
     #define USEcho 2
     #define MaxDistance 100
     #define LED 13

    //Here we have created two 'objects', one for the servo and one for the ultrasonic sensor
     Servo servo;
     NewPing sonar(USTrigger, USEcho, MaxDistance);

    //Below we are creating unsigned integer variables which we will use later on in the code. They are unsigned as they will only have postive values
     unsigned int duration;
     unsigned int distance;
     unsigned int FrontDistance;
     unsigned int LeftDistance;
     unsigned int RightDistance;
     unsigned int Time;
     unsigned int CollisionCounter;

     void setup()                                            //This block happens once on startup
     {
      Serial.begin(9600);                              //I have included the serial initialize but commented it out, if you want to debug and print information to the serial monitor just uncomment

      //Here we are setting the pin modes. As we will sending out signals from the pins we set them as outputs
      pinMode(LeftMotorForward, OUTPUT);
      pinMode(LeftMotorBackward, OUTPUT);
      pinMode(LeftMotorSpeed, OUTPUT);
      pinMode(RightMotorForward, OUTPUT);
      pinMode(RightMotorBackward, OUTPUT);
      pinMode(RightMotorSpeed, OUTPUT);
      pinMode(LED, OUTPUT);
      servo.attach(11);                                    //The servo is attached to pin 4
     }

     void loop()                                           //This block repeats itself while the Arduino is turned on
     {
      servo.write(90);                                    //Rotate the servo to face the front
      scan();                                             //Go to the scan function
      FrontDistance = distance;                           //Set the variable FrontDistance to the value of the distance returned from the scan function
      Serial.println("Front distance = ");
      Serial.print(distance);
      if(FrontDistance > 40 || FrontDistance == 0)        //If there is nothing infront of the robot within 40cm or the distance value is 0 (which for the newping libary means no ping was returned) then...
      {
       moveForward();                                     //Go to the moveForward function
      }
      else                                                //Else (if there is something infront of the robot within 40cm) then...
      {
        CollisionCounter = CollisionCounter + 1;
        moveStop();                                       //Go to the moveStop function
        navigate();
      }
     }

     void moveForward()                                    //This function tells the robot to go forward
     {

      Serial.println("");
      Serial.println("Moving forward");
      //Turn on left motor
      digitalWrite (LeftMotorBackward, LOW);
      digitalWrite(LeftMotorForward, HIGH);
      //set speed
      analogWrite(LeftMotorSpeed, 100);

     // turn on right motor
      digitalWrite(RightMotorBackward, LOW);
      digitalWrite(RightMotorForward, HIGH);
    // set speed
       analogWrite (RightMotorSpeed, 75);

title: Speed Control L298 motors

Answers: 3

body:
First try commenting out the

     Servo servo;

line, and all other bits using the servo.  If it works then there's your problem - use the Mega possibly as this allows more PWM outputs.

If it doesn't work with the Servo bits removed, then report back and include the Arduino model you're using.

Good luck!

body:
I commented all references to servo, the same results. Comment out the servo code doesn't seem to make a difference. What's going on is when the speed is numerically controlled the motor speed varies. At 50 the right motors slows down and the left motor HALTS, Not sure what's going on.

    //This function tells the robot to go forward
    int value;
    for(value = 0 ; value <= 75; value+=5)
        //if value is <=50 left motor does not spin. >75 both motors turn
        Serial.println("");
        Serial.println("Moving forward");
        analogWrite(LeftMotorSpeed, value);//int value has no effect on speed
        analogWrite(RightMotorSpeed, value);// same as LeftMotor)

        digitalWrite(LeftMotorBackward, LOW);
        digitalWrite(LeftMotorForward, HIGH);
        digitalWrite(RightMotorBackward, LOW);
        digitalWrite(RightMotorForward, HIGH);

body: You are not sending a speed command to the motor, you are sending it an analog voltage with the analogWrite. If that voltage is too low, the motor will stall. A higher value should make it spin faster. If you want the speed to be more tightly controlled, you will need encoders on the motors to sense how fast they are spinning, or use stepper motors.


body:
I am new to Arduino and bit blur on how it works. lack of info on the net about it. please help me with these questions!

1. Does Arduino due allow you to upload a program on programming port and then run it through Native port?

2. Can I work with SerialUSB instance in Programming port?

title: Programing uploading to Arduino due

Answers: 1

body:
> Does Arduino due allow you to upload a program on programming port and then run it through Native port?

You don't run a program *through* anything. You run it *on* the Due. Where you send text to is entirely up to you.

> Can I work with SerialUSB instance in Programming port?

I have no idea what you are asking there. Both the Programming port and Native port are capable of being used as virtual USB COM ports. They use CDC/ACM. One is directly connected to the SAM3X chip's USB peripheral, and the other is connected to the SAM3X's UART interface via another microcontroller as a USB to UART converter.


body: Can I upgrade my ESP8266 firmware by connecting the pins in Arduino Uno, or do I still need a USB UART to Serial?

title: ESP8266 Firmware Upgrade

Answers: 1

body:
Looking at the schematic of arduino UNO [here](https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf) you can see that Pin 0 and Pin 1 are connected to the same line of RX TX of the ATMEGA8U2. So in theory (and assuming the ATMEGA8U2 behaves like any usb to uart IC) if you remove or disable the ATMEGA328P, your arduino should behave like any cheap usb to serial. The way you can "disable" ATMEGA328P is by setting it in constant reset mode as explained [here](http://www.princetronics.com/arduino-uno-as-usb-to-serial-ttl-converter/)

By manually reseting and setting the esp into flashing mode, you should be able to upload the new firmware to it from arduino IDE for example by selecting the ESP device.

**Two notes on this**

**1** - The TX line of the ATMEGA8U2 is the marked RX on arduino Uno board and RX line of the ATMEGA8U2 is the marked to TX on arduino Uno board. That means your ESP RX should connect to pin 0 on arduino and TX of ESP should connect to pin 1.

**2** - You might need voltage level conversion on pin 0 as ESP is a 3.3V device although in schematic there is 1K resistor in that line


body:
I want to implement an Arduino module with some sensors and send the info through WiFi to a server. I'm looking for the best board or component combination to make this. What is the best board or solution you would use in my case? Maybe Arduino Yun or Intel Edison Kit for Arduino...¿?

I've developed a sensor module with Redbear Blend board which use Bluetooth to communicate with an Android app to send sensor data, but now looking for WiFi connection.

Sorry if it's a stupid question, I'm new in this Arduino world. Thanks in advance!

title: What Arduino board with WiFi should I choose

Answers: 1

body:
I'd recommend ESP8266 (model 07) based board.
[![ESP8266 model 07][1]][1]

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

 - Can be programmed the same way as other Arduinos
 - Cheap
 - Enough storage for code
 - Fairly low power
 - Large community (more code examples and better library support)


body: Is there Arduino shields with blocks of 4 pins that you can plug your servos into and use the fourth pin as signal pin to the Arduino Mega board?

title: Sensor/servo shield for Arduino Mega

Answers: 1

body:
Do you mean something like a [sensor shield](https://arduino-info.wikispaces.com/SensorShield#SSM)? They have three pins (Vcc, GND, signal), not four (because servos have three pins), but they are designed for connecting a large number of servos [![Arduino Mega sensor shield][1]][1]

These can be found easily and cheaply all over the internet.

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


body:
I have a Micro (original) and I am (trying to) using it under windows XP.
I was successful in installing its drivers (by swithching to ad Admin account) and uploading sketches to it, no problem. Even when I switched to my limited account, I was able to upload new sketches without error.

But...

Everytime I reboot my computer, as soon as I connect the Micro to the usb port, I get a "New hardware found" popup window from Windows. If I ignore the window I do not see the board in Arduino's IDE. If I choose to install the drivers (by loggin in that window as an admin and then fetching them from the Arduino folder) I end up seeing the board, selecting the COM port and then when compiling, getting the dreadful

    avrdude: butterfly_recv(): programmer is not responding

If I press the reset button I get the "Found new hardware window" again and the cycle repeats.

To make it work again I have to log off, log in in an admin user account, and install the friggin drivers from there. After that, if I log off and enter into my limited account, I can see board, port and I can finally upload my sketches (or at least that was the case the last two times).

Is it supposed to work this way?
Can I make it work like a Nano: install drivers **only once** and then just use the board?

PS
I have to mention that I happen to have 5 compatible Nanos with a ch340G chipset that work like a charm (and cost one tenth of the Micro). I installed the drivers ONCE and forgot about that.
I also happen to have a keyboard and a mouse, and they do not require me to install their drivers every time I plug the USB connector off.
Why is the Micro misbehaving this way?

title: Micro + restricted user Win XP = avrdude: butterfly_recv(): programmer is not responding

Answers: 0