message:
Arduino UNO and SPI eeprom (AT93C46D)

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

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!


sender: user

message:
How to speed up

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?

sender: assistant

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.


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

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?

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.


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

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

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


message:
Regulator magic smoke

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?

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.


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

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

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!


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

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.

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.


message:
Arduino Pro Mini

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?

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


message:
Neopixel led strip stops responding after change in brightness

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

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


message:
How to update multiple outputs simultaneously

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

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


message:
Serial monitor listing unreadable characters

[![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

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.


message:
Speed Control L298 motors

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

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.


message:
Programing uploading to Arduino due

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?

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.


message:
ESP8266 Firmware Upgrade

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

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


message:
What Arduino board with WiFi should I choose

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!

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)


message:
Sensor/servo shield for Arduino Mega

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?

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


message:
Send multiple sensor values over serial

I want to send a JSON string over serial from arduiono device to my computer. The JSON string contains a sensor value array. To fill this array I use String.concat("value") function. But If I have more than 100 values I get the JSON string with an empty array and an error message:

    {"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[],"landscape": PUF}
    VMDPE_1|3147_VMDPE

Is there any other way to send more than 100 values in one message? The arduino device is running with a battery and the communication is wireless. So I want to save energy and reduce the send interval.

**EDIT:**

After reading the answers I updated my sketch:

    Serial.print("{\"deviceID\":\"ZB_ROUTER_1\",");
     Serial.print("\"sensorID\":\"MMA8451\",");
     Serial.print("\"sensorType\":\"accelerator\",");

     Serial.print("\"aX\":[");
     for (int i = 0; i < samples; i++)
     {
      if(i != 0)
      {
       Serial.print(",");
      }

      Serial.print(xArray[i]);
     }
     Serial.print("],");

     Serial.print("\"aY\":[");
     for (int i = 0; i < samples; i++)
     {
      if(i != 0)
      {
       Serial.print(",");
      }

      Serial.print(yArray[i]);
     }
     Serial.print("],");

     Serial.print("\"aZ\":[");
     for (int i = 0; i < samples; i++)
     {
      if(i != 0)
      {
       Serial.print(",");
      }

      Serial.print(zArray[i]);
     }
     Serial.print("],");

     Serial.print("\"landscape\":\"");
     Serial.print(orientation);
     Serial.println("\"}");

In the xArray, yArray and zArray, there are 50 double values stored. One double value needs 4B. So that shouldn't be too much. But there are problems when I receive the JSON string on my computer:

    {"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-1.17,-1.31,-1.26,-1.25,-1.16,-1.09,-1.40,-0.91,-0.94,-0.97,-1.39,-1.06,-0.91,-0.75,-0.78,-0.83,-0.72,-0.62,-0.74,-0.53,-0.82,-0.86,-0.84,-0.79,-0.79,-0.76,-0.83,-0.82,-0.97,-1.07,-0.92,-0.87,-0.97,-1.20,-1.51,-1.53,-1.82,-0.99,-1.04,-0.41,-0.54,-0.27,-0.24,-0.08,-0.02,-0.63,-0.{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[0.16,-0.04,-0.18,-0.03,0.01,-0.17,-0.10,-0.30,-0.31,-0.21,-0.16,-0.16,-0.15,-0.19,-0.17,-0.17,-0.17,-0.18,-0.16,-0.17,-0.17,-0.20,-0.18,-0.16,-0.17,-0.16,-0.15,-0.13,-0.20,-0.19,0.37,-0.88,-0.20,-0.05,-0.12,-0.21,-0.20,-0.17,-0.17,-0.17,-0.17,-0.17,-0.19,-0.17,-0.19,-0.16,-0.18,-0.17,-0.18,-0.17],"aY":[9.80,8.63,8.37,9.05,9.19,8.83,9.01,9.69,8.42,7.94,7.72,7.83,8.43,8.82,9.24,9.21,8.79,8.60,8.39,8.44,8.61,8.77,8.87,8.76,8.66,8.59,8.54,8.73,8.879,8.73,8.66,8.60,8.61,8.68,8.71,8.76,8.71,8.66,8.60,8.63,8.69,8.71],"aZ":[-4.81,-4..28,-4.02,-4.02,-4.29,-4.49,-4.67,-4.63,-4.46,-4.32,-4.28,-4.38,-4.42,-4.52,-4.58,-4-4.52,-4.52,-4.42,-4.39,-4.34,-4.40,-4.47,-4.51,-4.47,-4.44,-4.38],"landscape":" PDB{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.18,-0.17,-0.19,-0.20,-0.18,-0.17,-0.18,-0.19,-0.19,-0.20,-0.17,-0.18,-0.17,-0.18,-0.16,-0.18,-0.18,-0.18,-0.17,-0.16,-0.19,-0.18,-0.17,-0.17,-0.16,-0.18,-0.17,-0.18,-0.18,-0.18,-0.16,-0.19,-0.17,-0.16,-0.17,-0.18,-0.17,-0.17,-0.17,-0.16,-0.17,-0.19,-0.18,-0.18,-0.17,-0.18,-0.17,-0.18,-0.17,-0.18],"aY":[8.67,8.68,8.69,8.68,8.68,8.68,8.66,8.68,8.69,8.69,8.69,8.67,8.69,8.70,8.68,8.67,8.68,8.69,8.69,8.68,8.67,8.69,8.69,8.70,8.68,8.66,8.67,8.67,66,8.76,8.80,8.98,8.99,8.76,8.46,8.37,8.55,8.71,8.80,8.85,8.74,8.59,8.58,8.64,8.70,8.44,-4.43,-4.43,-4.44,-4.42,-4.43,-4.43,-4.43,-4.42,-4.44,-4.43,-4.44,-4.43,-4.41,-44.13,-4.20,-4.44,-4.58,-4.68,-4.60,-4.41,-4.31,-4.29,-4.40,-4.50,-4.52,-4.48,-4.41,-{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.18,-0.19,-0.22,-0.15,-0.15,-0.19,-0.23,-0.13,-0.16,-0.21,-0.20,-0.17,-0.15,-0.10,-0.16,-0.18,-0.24,-0.17,-0.12,-0.20,-0.28,-0.20,-0.13,-0.19,-0.21,-0.17,-0.18,-0.20,-0.19,-0.17,-0.17,-0.17,-0.17,-0.15,-0.18,-0.16,-0.18,-0.19,-0.18,-0.16,-0.17,-0.18,-0.19,-0.17,-0.19,-0.18,-0.17,-0.16,-0.17,-0.17],"aY":[8.67,8.55,8.61,8.73,8.82,8.73,8.66,8.54,8.54,8.60,8.67,8.60,8.77,8.88,8.79,8.57,8.60,8.51,8.79,8.72,8.83,8.72,8.66,8.68,8.79,8.76,8.67,8.58,75,8.78,8.63,8.63,8.70,8.79,8.77,8.72,8.71,8.67,8.67,8.66,8.70,8.70,8.70,8.69,8.66,87,-4.47,-4.45,-4.32,-4.36,-4.31,-4.41,-4.30,-4.37,-4.46,-4.42,-4.20,-4.39,-4.49,-4.4.40,-4.35,-4.36,-4.39,-4.41,-4.43,-4.40,-4.41,-4.39,-4.40,-4.40,-4.41,-4.42,-4.44,-4{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.19,-0.18,-0.18,-0.17,-0.17,-0.18,-0.18,-0.17,-0.19,-0.18,-0.18,-0.17,-0.17,-0.17,-0.18,-0.18,-0.18,-0.18,-0.20,-0.18,-0.16,-0.17,-0.17,-0.18,-0.18,-0.17,-0.18,-0.19,-0.17,-0.19,-0.19,-0.19,-0.17,-0.18,-0.16,-0.18,-0.18,-0.18,-0.19,-0.20,-0.18,-0.17,-0.17,-0.17,-0.18,-0.22,-0.18,-0.17,-0.17,-0.17],"aY":[8.69,8.68,8.69,8.68,8.69,8.68,8.69,8.70,8.69,8.69,8.70,8.68,8.69,8.69,8.70,8.70,8.69,8.67,8.66,8.62,8.73,8.80,8.79,8.75,8.68,8.57,8.60,8.66,8,8.67,8.66,8.69,8.62,8.67,8.76,8.75,8.71,8.71,8.70,8.66,8.67,8.66],"aZ":[-4.43,-4.4-4.41,-4.40,-4.41,-4.42,-4.43,-4.44,-4.47,-4.36,-4.30,-4.30,-4.39,-4.45,-4.51,-4.52,,-4.49,-4.42,-4.35,-4.32,-4.37,-4.38,-4.41,-4.42,-4.46,-4.43],"landscape":" PDB"}

Sometimes there is "aZ" missing, sometimes I get wired array values like `8.83.2` (values with two "."). Do I have to many `Serial.print` operations? The sending interval is 500ms.

body:
> Is there any other way to send more than 100 values in one message?

Yes. Don't use String. Don't use `concat()`. Just print each bit as a separate `Serial.print()` function call.


body:
Maybe avoid doing the dynamic string manipulations?

    Serial.print("{\"deviceID\":\"ZB_ROUTER_1\",\"sensorID\":\"MMA8451\",\"sensorType\":\"accelerator\",\"aX\":[");
    for(i=0; i <10000; i++){
       if (! i==0) Serial.print(',');
       Serial.print(i);
    }
    Serial.print("],\"landscape\": PUF} VMDPE_1|3147_VMDPE");


body:
I have had a very similar problem and the Arduino core team has accepted a change from me to facilitate this functionality.
It is a complex story so you may have to reread a couple of times.

1) Serial.print returns before the data is send over serial.
---------------------------------------------------------

The first thing to realize is that when you do serial.print() the data is not actually send over serial.
When your code looks like

    serial.print("I'm dead");
    resetArduino(); //This method does not exists in the arduino core

The message "I'm dead" will not be send over serial. That is because Serial print does not wait until the data has been delivered.

2) There is a software buffer used for serial.
----------------------------------------------

The second thing to realize is that when you do serial.print() the data is not actually send but is put into a software buffer. A interrupted routine sends the data from the buffer over the "transport layer" (like in the osi model) here the serial connection.
This buffer uses the same memory that your string is using. In other words you are storing the string 2 times. This is why I agree with majenko when he states

> Don't use String. Don't use concat(). Just print each bit as a separate Serial.print() function call.

3) If the software buffer is full serial.print will wait
--------------------------------------------------------

If you do serial.print and the software buffer is full the function will not return until all data is in the buffer.
In other words: If a sketch tries to send more data than is transmittable over the serial connection the behaviour of the sketch will change over time.

4) Serial is slow
115200 baut may seem lightning fast but it is slow compared to what your arduino can do.
In other words: if you send lots of data you will need to calculate wether the serial connection can handle that amount of data.

So how can you improve on the situation.
----------------------------------------

 1. As majenko implied: Only use the buffer of serial.
 2. Reduce the amount of data you send. Jason is not a good way to send lots of similar data over a serial line because you have to add the variable name each time. I have split my variable names from the data to do reduce the amount of data to send.
 3. If you send bursts of data bigger than the software buffer; increase the buffer. This is the change Arduino core team accepted from me.you can set the define SERIAL_TX_BUFFER_SIZE for changing the send buffer size and SERIAL_RX_BUFFER_SIZE for changing the receive buffer size. The default is 64 which means 64 characters.
 4. Only send changed data.
 5. Preprocess your data so you can send less data


message:
SN76489 - Ready pin not working?

I'm testing the **SN76489AN** chip with Arduino and I'm able to play the 3 tones I want etc BUT I don't understand why the READY pin is not working? The datasheet says the pin goes high when the chip is ready and low when it's busy with processing a command. But the **READY pin is always low!** I've got 2 brand new pieces of the chip and they both act this way. I've even tried to pull-up this pin but it didn't help. I see everyone is just using `delayMicroseconds` in their examples, so I guess it is a common problem but it's just strange... Is it a bug in the chip or what? Does anyone know?

Thanks!

body:
The READY signal is [open-collector][1]. It will therefore require a pullup-resistor. Test circuit in datasheet shows a 2 kohm resistor. You could try with that. Alternatively use the internal pullup resistor on the input pin but this may be too large (weak).

Cheers!

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


body: I had this problem, but the mistake was that I had missed the clock pin on my breadboard by one row, so there was no clock signal.


message:
Arduino: How to get the board type in code

I want to write a sketch that can be compiled on different Arduino boards.
I want to display on the PC which board is currently connected.

This means that the user connects the PC via USB cable to the Arduino/Teensy board in which runs my sketch and my sketch tells the PC via Serial which board is connected. On the PC runs my C# application which receives this data and displays it.

Therefore I need the board that has been selected when the sketch has been compiled:

[![Arduino Board selector][1]][1]

I found the code on https://github.com/backupbrain/ArduinoBoardManager
but it does not give correct results (apart from the fact that several boards are missing).

Here a snippet from the code:

    static const uint8_t BOARD_MICRO= 0x04;

    ....
    #elif defined(__AVR_Atmega32U4__) // Yun 16Mhz, Micro, Leonardo, Esplora
      static const uint8_t BOARD = 0x04;
      static const uint8_t NUM_BITS = 8;
      static const uint16_t CPU = __AVR_Atmega32U4__;
      static const unsigned long SRAM_SIZE = 2500;
      static const unsigned long EEPROM_SIZE = 1000;
      static const unsigned long FLASH_SIZE = 32000;
    #elif defined(.....

So this code gives the same result (BOARD = 0x04 = Micro) for Yun 16MHz, Micro, Leonardo y Esplora.

Is there any way to get in my C code exactly the string that the user has selecetd in the menu of the Arduino compiler?

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

body: The exact names in the menu come from boards.txt file in your Arduino IDE (Arduino\hardware\arduino\avr\boards.txt). I think you would have to parse the file by yourself and find the detected board there.


body:
note this is a windows mod something similar must exist on linux.

The first is quick and easy. Simply modify the platform.txt files you are using as described nelow. The draw back of this is that you will need to change platform.txt files with each release.

add -DBOARD=\"${build.board}\" to the recipe. This will allow for

       const char boardName[]=BOARD;

Which gives you the string "ARDUINO_AVR_LEONARDO" (for the leonardo) in boardName.

The second way is to switch to a better IDE (like already proposed by others). As the creator of the arduino eclipse plugin I would advice to use the arduino eclipse plugin. In the arduino eclipse plugin you do this as follows:
Right click on the project->properties->arduino->tab "compile options" put

    -DBOARD=\"${A.BUILD.BOARD}\"

in the append to C and C++ field.

This will make the code above to compile

Adendum
-------

I wasn't aware you wanted the "nice name". I'm not sure this can be fixed in the platform.txt in arduino IDE. In the arduino eclipse plugin change the fixe above in

    -DBOARD=\"${A.NAME}\"

to get the nice name (for the leonardo "Arduino Leonardo") in the define Board.


body:
I asked a [related question](https://arduino.stackexchange.com/questions/19892/list-of-arduino-board-preprocessor-defines) a while ago.

An internal *.h file exists which is created by the IDE, and holds in it the type of board that has been selected. The list of possible options is given in the linked question, but only for AVR boards. I believe the non-AVR list is much shorter.

It is simply a matter of adding some conditional statements to send the PC the correct information. A simple example:

<!-- language = C++ -->

    //...within your code, perhaps during setup()...
    #ifdef ARDUINO_AVR_UNO
        serial.println("UNO");
    #endif
    #ifdef ARDUINO_AVR_LEONARDO
        serial.println("LEONARDO");
    #endif
    // etc...

If you need to refer to the board type more than once in the sketch, use the following format:

<!-- language = C++ -->

    //...BEFORE setup(), or otherwise in the global namespace...
    #ifdef ARDUINO_AVR_UNO
        #define __BOARD_TYPE "UNO"
    #endif
    #ifdef ARDUINO_AVR_LEONARDO
        #define __BOARD_TYPE "LEONARDO"
    #endif
    // etc...

    // within your code, wherever necessary:
    serial.println(__BOARD_TYPE);

The latter is much tidier, even if you only need `__BOARD_TYPE` once, as it removes the cumbersome `#ifdef` chunk from your functions.

You will, of course, have to write one for each board that you expect your end-user could have, and you will possibly need to update this list as new models appear.


body:
Thanks to the help of Charlie Hanson and jantje I found the universal solution!

Because it is a pity that every Arduino programmer has to go through the same pain to figure out how to get the board name, I will offer my code to the public so everybody can just copy and paste it.

Here it is:

    #if defined(TEENSYDUINO)

        //  --------------- Teensy -----------------

        #if defined(__AVR_ATmega32U4__)
            #define BOARD "Teensy 2.0"
        #elif defined(__AVR_AT90USB1286__)
            #define BOARD "Teensy++ 2.0"
        #elif defined(__MK20DX128__)
            #define BOARD "Teensy 3.0"
        #elif defined(__MK20DX256__)
            #define BOARD "Teensy 3.2" // and Teensy 3.1 (obsolete)
        #elif defined(__MKL26Z64__)
            #define BOARD "Teensy LC"
        #elif defined(__MK64FX512__)
            #define BOARD "Teensy 3.5"
        #elif defined(__MK66FX1M0__)
            #define BOARD "Teensy 3.6"
        #elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY40)
            #define BOARD "Teensy 4.0"
        #elif defined(__IMXRT1062__) && defined(ARDUINO_TEENSY41)
            #define BOARD "Teensy 4.1"
        #else
           #error "Unknown board"
        #endif

    #else // --------------- Arduino ------------------

        #if   defined(ARDUINO_AVR_ADK)
            #define BOARD "Mega Adk"
        #elif defined(ARDUINO_AVR_BT)    // Bluetooth
            #define BOARD "Bt"
        #elif defined(ARDUINO_AVR_DUEMILANOVE)
            #define BOARD "Duemilanove"
        #elif defined(ARDUINO_AVR_ESPLORA)
            #define BOARD "Esplora"
        #elif defined(ARDUINO_AVR_ETHERNET)
            #define BOARD "Ethernet"
        #elif defined(ARDUINO_AVR_FIO)
            #define BOARD "Fio"
        #elif defined(ARDUINO_AVR_GEMMA)
            #define BOARD "Gemma"
        #elif defined(ARDUINO_AVR_LEONARDO)
            #define BOARD "Leonardo"
        #elif defined(ARDUINO_AVR_LILYPAD)
            #define BOARD "Lilypad"
        #elif defined(ARDUINO_AVR_LILYPAD_USB)
            #define BOARD "Lilypad Usb"
        #elif defined(ARDUINO_AVR_MEGA)
            #define BOARD "Mega"
        #elif defined(ARDUINO_AVR_MEGA2560)
            #define BOARD "Mega 2560"
        #elif defined(ARDUINO_AVR_MICRO)
            #define BOARD "Micro"
        #elif defined(ARDUINO_AVR_MINI)
            #define BOARD "Mini"
        #elif defined(ARDUINO_AVR_NANO)
            #define BOARD "Nano"
        #elif defined(ARDUINO_AVR_NG)
            #define BOARD "NG"
        #elif defined(ARDUINO_AVR_PRO)
            #define BOARD "Pro"
        #elif defined(ARDUINO_AVR_ROBOT_CONTROL)
            #define BOARD "Robot Ctrl"
        #elif defined(ARDUINO_AVR_ROBOT_MOTOR)
            #define BOARD "Robot Motor"
        #elif defined(ARDUINO_AVR_UNO)
            #define BOARD "Uno"
        #elif defined(ARDUINO_AVR_YUN)
            #define BOARD "Yun"

        // These boards must be installed separately:
        #elif defined(ARDUINO_SAM_DUE)
            #define BOARD "Due"
        #elif defined(ARDUINO_SAMD_ZERO)
            #define BOARD "Zero"
        #elif defined(ARDUINO_ARC32_TOOLS)
            #define BOARD "101"
        #else
           #error "Unknown board"
        #endif

    #endif

You can even put this code into a new header file and #include it into your project.

P.D.
If you want to know additionaly to the board also the CPU model, search for the file avr_cpunames.h


body:
The original answer is out of date as new boards have been added.  The basic test is correct, but it's not clear where the list of boards come from.

If you locate the `boards.txt` file and look through it (eg. `~\Library\Arduino\hardware\arduino\avr\boards.txt` on a Mac), each board will have an entry along the lines of `<BOARD>.build.board=<NAME>`, so for example, the MKR1000 would have a line:

  `mkr1000.build.board=SAMD_MKR1000`

The corresponding #define can be generated by prefixing the `<NAME>` with `ARDUINO_` so in this example, the following code will error for an MKR1000 board...

```#if defined(ARDUINO_SAMD_MKR1000)
  #error```


body:
For Adafruit boards, specifically a Feather M4, the following worked for me.

    #ifdef _VARIANT_FEATHER_M4_
    serial.println("Feather M4");
    #endif


message:
Strange behavior on 74HC595 Shift Register IC when its GND pin is used

I was following a tutorial similar to this:
https://www.arduino.cc/en/Tutorial/ShiftOut

That is, an array of 8 LEDs that lit up accordingly to the binary representation of a number, which was given in a loop from 0 to 255.

The problem is that when invoked shiftOut() over certain numbers (such as 5, 9 or 13), the LEDs didn't lit as expected.

I even tried replacing the IC, but what finally solved this issue was to disconnect IC's pin 8 (GND) and let only pin 13 (OE) connected to Arduino's ground pin.

**Does anyone know the reason this strange behavior happens on 595 IC?**

Here's a video showing the circuit finally working (without IC's GND pin connected): https://www.youtube.com/watch?v=NGfpk-kjemo

body:
Disconnecting the ground pin was not a solution.

It is hard to be certain from video but the resistor values are likely too small because I can't see any color on the bands.  They are 100?

Look closely at the driver data sheet.  It may say an output pin maximum current is +/-35 mA which would suggest that the 100 ohm resistor is okay.

For example, a red LED has a of around 1.6 V.  You are using Vcc=3.3, so a 100 ohm resistor limits the current to <17 mA ((3.3-1.6)/100).  The actual current will be a somewhat smaller as the Vf increases with current..

But you also stay within the maximum Icc and Ignd on the data sheet.  These limits are not necessarily 8 x 35 mA.  For example an NXP max Icc is 70 mA.  That means you cannot drive all the outputs at maximum current, just 2.  This is a logic chip, not a driver.

There is other hint that you should not using all the outputs at the max current spec in the section where the Voh and Vol are described.  The current at which the voltage is specified is 6 mA, which is the maximum you should use if all output are going to source or sink at the same time.

A common LED current is 5 mA, so this chip could drive 8 simultaneously.  If you want high brightness, you need to add a driver such as ULN2003.

Note that the schematic shows red LED's.  **The color is important**.  Different LED's have different forward voltage.  The blue LED have the highest in the range of 3.3 V and higher.  So with a Vcc=3.3 there is barely enough voltage to light the blue LED.  The red and yellow have much lower forward voltage.  When the chip tries to light the red and blue at same time, the output voltage is dropping enough that the blue is not visible, but the red is easily lit.

From the video, it looks that you have the same resistor on all the LED's.  On different color LED's this will not achieve the same brightness on all LED's.  You need different resistors for each color if you want them the same brightness.

The solution is

  - Up the Vcc to 5V so that you can reliably light the blue LED's.

  - Increase the resistor values start with 510 for red and 220 for blue.  This should be about 6 mA for both.


message:
What should I do to communicate with GSM module?

Sorry, im a beginner, i tried to program an automatic doorlock using sms. But, I dont understand what happen with this error, what should I do? Add library? The error said that Pstring wasnt declared, but i dont know how to declare this.

    #include <LiquidCrystal.h>
    #include "SIM900.h"
    #include "sms.h"
    #include "SoftwareSerial.h"
    #include "sms.h"

    SMSGSM sms;
    boolean started=false;
    char buffer[160];
    char smsbuffer[160];
    char n[20];
    int pintu=5;
    int buttonState;
    int lastButtonState = LOW;
    long lastDebounceTime = 0;
    long debounceDelay = 50;
    boolean st=false;
    int buzzer=6;

    void setup()
    {
      pinMode(pintu,OUTPUT);
      pinMode(buzzer,OUTPUT);

      digitalWrite(pintu,LOW);
     if (gsm.begin(9600))
     {
      started=true;
       digitalWrite(buzzer,HIGH);
       delay(100);
       digitalWrite(buzzer,LOW);
       delay(100);
       digitalWrite(buzzer,HIGH);
       delay(100);
       digitalWrite(buzzer,LOW);
       delay(100);
       digitalWrite(buzzer,HIGH);
       delay(100);
       digitalWrite(buzzer,LOW);
       delay(100);
      }
       if(started)
      {
       delsms();
       sms.SendSMS("08970869443","Pintu SMS Menyala");
      }
      else{digitalWrite(buzzer,HIGH); delay(2000); digitalWrite(buzzer,LOW);
      }

       }

       void loop()
       {

       int pos=0;
      if (gsm.begin(9600))
      {
      if (started){
      pos=sms.IsSMSPresent(SMS_ALL);
      if(pos)
      {
       sms.GetSMS(pos,n,smsbuffer,100);
       delay(2000);
        if(!strcmp(smsbuffer,"bukapintu"))
        {
          PString str(buffer, sizeof(buffer));
        str.begin();
        str.print("Pintu Dibuka");
        digitalWrite(pintu,HIGH);
       // String a=str
        sms.SendSMS(n,buffer);
        }
        if(!strcmp(smsbuffer,"tutuppintu"))
        {
          PString str(buffer, sizeof(buffer));
        str.begin();
        str.print("Kunci Pintu Ditutup");
        digitalWrite(pintu,LOW);
       // String a=str
        sms.SendSMS(n,buffer);
        }
        delsms();
       }
       }
       }
       }

       void delsms()
       {
       for (int i=0; i<10; i++)
      {
         int pos=sms.IsSMSPresent(SMS_ALL);
        if (pos!=0)
       {
        if (sms.DeleteSMS(pos)==1){}else{}
       }
       }
       }

Error message :

         Arduino: 1.6.7 (Windows 10), Board: "Arduino/Genuino Uno"

          D:\Kuliah\Project\Skripsi\pintu_sms\pintu_sms.ino: In function 'void loop()':

          pintu_sms:67: error: 'PString' was not declared in this scope

           PString str(buffer, sizeof(buffer));

           ^

          pintu_sms:67: error: expected ';' before 'str'

           PString str(buffer, sizeof(buffer));

                   ^

         pintu_sms:68: error: 'str' was not declared in this scope

         str.begin();

         ^

        pintu_sms:76: error: 'PString' was not declared in this scope

           PString str(buffer, sizeof(buffer));

           ^

        pintu_sms:76: error: expected ';' before 'str'

           PString str(buffer, sizeof(buffer));

                   ^

         pintu_sms:77: error: 'str' was not declared in this scope

         str.begin();

         ^

         exit status 1
      'PString' was not declared in this scope

body:
The compiler does not know what PString is. It is not declared in any of the libraries you have included.

You could rewrite to something like this.

    strcat(buffer, "Pintu Dibuka");
    n = strlen(buffer);
    digitalWrite(pintu,HIGH);
    sms.SendSMS(n,buffer);

Please change the other block in the same way.

There are more errors. You also need to change "int n[20]" to "int n".

That is a good start.

Cheers!


message:
Arduino PWM Pins Interrupt

I am creating pwm from an arduino pin with 50% duty cycle. I just want to know how can i detect its every falling edge using timer interrupt? I don't want to connect that PWM pin to an external interrupt pin. Please help me.

body:
You can define an interrupt service routine (ISR) for each Timer and PWM pin that it handles. These are known as TIMERn_COMPA_vect, TIMERn_COMPB_vect and TIMERn_COMPC_vect. The Mega has six Timers (n=0..5).

    ISR(TIMERn_COMPA_vect)
    {
    // Timer/Counter compare match A
    }

Check the PWM configuration for how the pin is set, cleared or toggled.

Cheers!


body:
Referring to the datasheet of ATMega328P: If you want to generate an interrupt every falling edge you must know if the Pin is inverse mode or not. As you can see from the timing diagram the Pin stays high until the compare unit matches (current value of the TCNCT == value stored in OCRn ) and then goes low in the normal mode or works as opposite in the inverting mode.

This could be regulated by changing the bits COMnx in the TCCRn register. If, for example: COM0 = 1 and COM1 = 1 the table says: Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).

Now with these settings the falling edge happens when the timer overflow, so the ISR must occur when the timer reach its maximum value.

 [![PWM timing diagram][1]][1]

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


message:
Arduino app hangs on upload for all boards

I'm at a loss. I have many boards and have not had much trouble in the past uploading to feather, uno, light blue bean and others. I have a lot of boards loaded in the board manager and I'd rather not delete everything just yet.

But, after taking a month off of arduino programming I've come back to the app to discover that I can't upload *anything* to *any* board. I've tried a brand new uno, an adafruit feather and the light blue bean. In each case I can see the port, but the upload just hangs like this:

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

On the board the light that normally blinks during upload never blinks. It's like the upload just isn't happening. But there is no error in the app.

I tried reinstalling the app, but that didn't help. My next thought is to delete everything, and do a fresh install. Which will be annoying. Is that my only hope?

----------
**UPDATE:**

Here are the settings from the tools menu as requested:

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

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

  [1]: https://i.stack.imgur.com/oNxqH.jpg
  [2]: https://i.stack.imgur.com/pb46x.jpg
  [3]: https://i.stack.imgur.com/q7ClZ.jpg

body:
I tried that once. A very common reason for this problem is a different cable. Some USB cables are not suited for uploading the data to the Uno board.

Have you brought a new cable? If so, switch back to the old one. It may not look like it makes a difference, but it requires attention.


body:
I appreciate that this is an old post but I have recently been experiencing this problem.

I found that the issue was caused when I had a wireless SD shield attached to the Arduino. Taking this shield off allowed me to upload. This occurred across 5 different Arduino's.

After some more testing I found that switching the "serial select" toggle on the wireless shield from "MICRO" to "USB" allowed me to upload as well. Switching it back to "MICRO" subsequently blocked the upload.

Hope this help anyone having this problem in the future.


message:
Arduino: Read frequency of input from audio jack

I want to trigger an arduino from a sound from an audio jack from a mobile phone. The audio is a 1 Khz sound that the mobile will play. I want to avoid accidental triggering of the audio by testing for specifically that frequency.

I've found several tutorials using analog read, but the output is not in hertz.

How do i get the output in Hertz?

    int incomingAudio;

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

    void loop(){
      incomingAudio = analogRead(A0);//read voltage at A0
      incomingAudio = (incomingAudio+1)/4 - 1;//scale from 10 bit (0-1023) to 8 bit (0-255)
      if (incomingAudio<0){//deal with negative numbers
        incomingAudio = 0;
      }
      PORTD = incomingAudio;
      Serial.println(PORTD);

    }

body:
You can measure a single "pure" frequency by counting the number of times that the pin changes, by using the inbuilt timers. Here is a sketch from [my page about timers](http://www.gammon.com.au/timers) that accomplishes that:

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

    // Timer and Counter example
    // Author: Nick Gammon
    // Date: 17th January 2012

    // Input: Pin D5

    // these are checked for in the main program
    volatile unsigned long timerCounts;
    volatile boolean counterReady;

    // internal to counting routine
    unsigned long overflowCount;
    unsigned int timerTicks;
    unsigned int timerPeriod;

    void startCounting (unsigned int ms)
      {
      counterReady = false;         // time not up yet
      timerPeriod = ms;             // how many 1 ms counts to do
      timerTicks = 0;               // reset interrupt counter
      overflowCount = 0;            // no overflows yet

      // reset Timer 1 and Timer 2
      TCCR1A = 0;
      TCCR1B = 0;
      TCCR2A = 0;
      TCCR2B = 0;

      // Timer 1 - counts events on pin D5
      TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

      // Timer 2 - gives us our 1 ms counting interval
      // 16 MHz clock (62.5 ns per tick) - prescaled by 128
      //  counter increments every 8 µs.
      // So we count 125 of them, giving exactly 1000 µs (1 ms)
      TCCR2A = bit (WGM21) ;   // CTC mode
      OCR2A  = 124;            // count up to 125  (zero relative!!!!)

      // Timer 2 - interrupt on match (ie. every 1 ms)
      TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

      TCNT1 = 0;      // Both counters to zero
      TCNT2 = 0;

      // Reset prescalers
      GTCCR = bit (PSRASY);        // reset prescaler now
      // start Timer 2
      TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
      // start Timer 1
      // External clock source on T1 pin (D5). Clock on rising edge.
      TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
      }  // end of startCounting

    ISR (TIMER1_OVF_vect)
      {
      ++overflowCount;               // count number of Counter1 overflows
      }  // end of TIMER1_OVF_vect

    //******************************************************************
    //  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
    //  16Mhz / 128 / 125 = 1000 Hz

    ISR (TIMER2_COMPA_vect)
      {
      // grab counter value before it changes any more
      unsigned int timer1CounterValue;
      timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
      unsigned long overflowCopy = overflowCount;

      // see if we have reached timing period
      if (++timerTicks < timerPeriod)
        return;  // not yet

      // if just missed an overflow
      if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
        overflowCopy++;

      // end of gate time, measurement ready

      TCCR1A = 0;    // stop timer 1
      TCCR1B = 0;

      TCCR2A = 0;    // stop timer 2
      TCCR2B = 0;

      TIMSK1 = 0;    // disable Timer1 Interrupt
      TIMSK2 = 0;    // disable Timer2 Interrupt

      // calculate total count
      timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
      counterReady = true;              // set global flag for end count period
      }  // end of TIMER2_COMPA_vect

    void setup ()
      {
      Serial.begin(115200);
      Serial.println("Frequency Counter");
      } // end of setup

    void loop ()
      {
      // stop Timer 0 interrupts from throwing the count out
      byte oldTCCR0A = TCCR0A;
      byte oldTCCR0B = TCCR0B;
      TCCR0A = 0;    // stop timer 0
      TCCR0B = 0;

      startCounting (500);  // how many ms to count for

      while (!counterReady)
         { }  // loop until count over

      // adjust counts by counting interval to give frequency in Hz
      float frq = (timerCounts *  1000.0) / timerPeriod;

      Serial.print ("Frequency: ");
      Serial.print ((unsigned long) frq);
      Serial.println (" Hz.");

      // restart timer 0
      TCCR0A = oldTCCR0A;
      TCCR0B = oldTCCR0B;

      // let serial stuff finish
      delay(200);
      }   // end of loop

Feeding in a 1 kHz sine wave (from 0V to 5V) I get this output:

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

    Frequency Counter
    Frequency: 1000 Hz.
    Frequency: 1002 Hz.
    Frequency: 1000 Hz.
    Frequency: 1000 Hz.
    Frequency: 1000 Hz.
    Frequency: 1000 Hz.
    Frequency: 1002 Hz.
    Frequency: 1000 Hz.
    Frequency: 1000 Hz.
    Frequency: 1000 Hz.

There is the occasional mis-reading but it looks accurate enough. You might sample a few times, and if you get something between 990 and 1010, five times, you might consider that a match.

You will need to make sure that the input is in the range for triggering the input circuitry of the Arduino. It should be around 4 to 5V, and not higher than 5V (for a high). It also should not go negative.

Something like this will protect the input pin:

[![Input protection][1]][1]

**Warning** - audio from an audio jack will be AC and it **will** go negative. Make sure you use a suitable input protection.

---

## Amplification

After looking at [Wikipedia - Line level](https://en.wikipedia.org/wiki/Line_level) it seems likely that the output from your phone will not be high enough (around 700 mV probably). Therefore a simple transistor amplifier will probably be required to raise it to a level that can be detected.

Inspired by [this post](https://electronics.stackexchange.com/questions/36795/using-a-microphone-with-an-arduino) on Electronics Stack Exchange, I made up a simple amplifier:

[![Audio amplifier schematic][2]][2]

Testing out with around 500mV peak-to-peak input indicates that it successfully amplified it to 0 to 5V DC:

[![Audio amplifier scope trace][3]][3]

---

## Alternative method with analog comparator

Based on suggestions by Chris Stratton, there is another way of doing this.

You can use the [analog comparator](http://www.gammon.com.au/forum/?id=11916) to detect an analog signal passing a threshold, like this:

[![Analog comparator schematic][4]][4]

I have set up the voltage divider to trigger at 0.265V, so that a 500 mV signal should provide an acceptable triggering range.

As for the sketch, at these frequencies we can do something simpler than what I posted before:

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

    volatile bool counting;
    volatile unsigned long count;

    ISR (ANALOG_COMP_vect)
      {
      if (counting)
        count++;
      }

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ("Started.");
      ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
      ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
            | bit (ACIE)    // Analog Comparator Interrupt Enable
            | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
       }  // end of setup

    unsigned long startTime;

    void loop ()
      {

      if (!counting)
        {
        startTime = micros ();
        count = 0;
        counting = true;
        }
      else
        {
        // is a second up? (1000000 microseconds)
        if (micros () - startTime >= 1000000)
          {
          counting = false;
          Serial.print (count);
          Serial.println (F(" Hz."));
          }  // end of a second being up

        }  // end of if

      }  // end of loop

  [1]: https://i.stack.imgur.com/FrMkW.png
  [2]: https://i.stack.imgur.com/EhTvy.png
  [3]: https://i.stack.imgur.com/2uAIi.png
  [4]: https://i.stack.imgur.com/cimBo.png


body:
If your signal is a pure 1 kHz tone, then you should use Nick
Gammon's counting method, as it is the most straight-forward solution.
If, however, you are picking the signal through a microphone, chances
are you will also get some background noise, and this can make the
counting method unreliable.

In such a case, you will have to use some kind of digital filter to
extract the desired signal from the noise. I would recommend using
[homodyne detection](https://en.wikipedia.org/wiki/Homodyne_detection),
which is both simple and very robust against wide-spectrum noise: let
_f_ = 1 kHz be the frequency you want to detect, and _t_
be the current time, then

* compute cos(2 π _f t_ ) and sin(2 π _f t_ ): these two periodic signals,
  in quadrature to one another, are called “the local oscillator”
* multiply your signal independently by the above cos() and sin()
* low-pass filter the two products, which gives you the
  [I and Q demodulated](https://en.wikipedia.org/wiki/Quadrature_amplitude_modulation) signals
* compute the instantaneous power = I2 + Q2.

You know the phone is ringing when this power goes above some
experimentally-determined threshold.

I know all this sounds like heavy math, but it need not be:

* All the computations are amenable to efficient fixed-point
  implementations, and you can do the math in parallel with the
  analog-to-digital conversion.
* The scheme works even with crude approximations of the sin() and cos()
  functions. Even square waves (sin() and cos() being always +1 or −1)
  work quite decently.
* The low-pass filter can be implemented as an
  [exponential moving
  average](https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average),
  which is only a bit shift, an add and a subtract.

I can try to write some sample code, but I would go through the trouble
only if there is interest. If your signal is so clean that Nick Gammon's
method works reliably, there probably is no point.

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

**EDIT**: I wrote a program to demonstrate this approach, just for the
fun. It's available as a GitHub gist:
[homodyne.ino](https://gist.github.com/edgar-bonet/0b03735d70366bc05fc6).
I am not copying the whole program here, just adding some explanations:

The first thing is to take care of the sampling frequency. Whenever one
wants to do signal processing, it is very desirable to sample at a fixed
and known frequency. This is next to impossible to achieve by looping
over `analogRead()`, because the CPU time needed to go through the loop
is hard to predict, as it can be influenced by interrupts and by
conditional branches. `analogRead()` is also highly inefficient, as it
locks the CPU in a busy loop while it waits for the analog-to-digital
converter (ADC) to do its job.

The solution is to put the ADC in the so called "free running mode". In
this mode, it starts a conversion as soon as the previous one is
finished, which gives a very steady sampling rate of 9.615 kHz (one
sample every 104 µs). The samples are handled by an interrupt
service routine called `ISR(ADC_vect)` which gets triggered every time a
sample is ready. This is also where all the signal processing is done.

Below is a detailed explanation of every line of code in the ISR:

    int8_t sample = ADCH - 128;

Reading the ADC result is the first thing to do in the ISR. Since we do
not need the full 10 bit resolution, the ADC was configured to
left-adjust its result. Then we get an 8-bit result by just reading the
high byte of the ADC data register. We subtract 128 to remove the DC
offset and get a signed number in the range [−128 .. +127].

Next, we update the phase of our local oscillator:

    static uint16_t phase;
    phase += PHASE_INC;

We need not worry about possible overflows: since the phase is kept in
units of 1/216 cycles, the increment automatically works
modulo one cycle. The phase increment should theoretically be 6815.744,
which is rounded to 6816. This makes the local oscillator fast by
0.0376 Hz, which is negligible given the accuracy of the Arduino
clock. The phase could be kept in an 8-bit variable, but the rounding
error would then make the oscillator fast by 14 Hz, which can be
borderline unacceptable.

Next we need to build two square waves in quadrature, which will be used
as rough approximations of sin() and cos(). But since the most
significant bit of the phase is on during half of the cycle, it can be
used as one of our square waves. The other wave is obtained in a similar
way, after adding 1/4 cycle to the phase. So here is how we multiply our
sample by the square waves:

    int8_t x = sample;
    if (((phase>>8) + 0x00) & 0x80) x = -1 - x;
    int8_t y = sample;
    if (((phase>>8) + 0x40) & 0x80) y = -1 - y;

The expression `phase>>8` is only meant to hint the compiler that it
needs only to consider the most significant byte of the phase. This
should normally not be needed, but I noticed that, without this hint,
gcc generates suboptimal code. The `-1` in the above lines are for
avoiding a possible overflow.

Next comes the low-pass filter:

    signal_I += x - (signal_I >> LOG_TAU);
    signal_Q += y - (signal_Q >> LOG_TAU);

Where `signal_I` and `signal_Q` are `volatile int16_t` globals, and
`LOG_TAU` is 6. This filters with a time constant

> τ = 64 × 104 µs = 6.656 ms

which translates to a −3 dB bandwidth of

> Δf = 1/(2πτ) = 23.9 Hz.

which is fairly narrow for a 1 kHz signal. The significance of τ is
that, once the tone starts, it takes the filter about
2.3 τ ≈ 15 ms to reach 90% of its final output. Both
τ and Δf can be changed by simply changing `LOG_TAU`.

This ISR takes about 176 CPU cycles (11 µs, including the
4 cycles needed to put the CPU in interrupt mode) every
1664 cycles (104 µs). This amounts to about 10.6% of the
available CPU power. And since everything is done inside the ISR, the
program is free to do whatever else needs to be done while the data
acquisition and digital filtering happens in the background.

I tested the program by sending it a sine wave of 4.36 V
peak-to-peak amplitude. The reported power fluctuated quite a bit, but
here are the approximate average readings as a function of the input
frequency:

    frequency  |  power
    -----------+-------
       929 Hz  |   480
       976 Hz  |  2400
      1005 Hz  |  4600
      1028 Hz  |  2700
      1079 Hz  |   480


message:
Dot Matrix Display with Arduino UNO (PROBLEM)

I faced a problem in my graduation project and I hope you can help me to solve it :)

----------

My project is connecting Arduino Uno to 16x32 Dot Matrix Display(DMD) and display messages on it from VB.net program. I wrote my VB.net program to convert the input text into 2D binary array. The number of columns depend on the text width.
as we know Arduino Uno SRAM is too small just 2 KBytes, so can't receive all the columns and display it.

I tried to receive 100 columns in the Arduino code and display it, then send star `*` to computer to receive the second 100 columns and display it and so on but it didn't work. I see the RX and TX of Arduino LEDs flicker but then nothing gets displayed on the DMD.

Can anyone tell me where is the error part in the code, or if you have another idea to solve this problem :)

**VB.net Code for sending the 2D array `ar(,)`**

 Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            SerialPort2.Open()
            Dim la As String
            If CheckBox1.Checked Then
                la = "arabic"
            Else
                la = "english"
            End If
            SerialPort2.Write("#" + cols.ToString + "#" + "*" + la + "*")
            Dim INDEX As Integer = 0

            While INDEX <= cols
                Dim see As String = SerialPort2.ReadLine().ToString()
                If see = "*" Then
                    Dim BUFFER(16) As Byte
                    For I = INDEX To INDEX + 100
                        If I < cols Then
                            For J = 0 To rows - 1
                                BUFFER(J) = ar(I, J)
                            Next
                            SerialPort2.Write(BUFFER, 0, 16)
                        End If
                    Next
                    INDEX += 100
                End If
            End While
            SerialPort2.Close()
 End Sub

**C++ Code for receiving 100 columns and display them:**

    #include <SPI.h>
    #include <DMD2.h>

    SoftDMD dmd(1,1);
    void setup() {
      Serial.begin(9600);
      dmd.setBrightness(255);
      dmd.begin();
    }
    long Wid;
    void loop() {
      if(Serial.available()){
        String st = String(Serial.readString());
        Wid = (st.substring(st.indexOf('#')+1, st.lastIndexOf('#'))).toInt();
        //String Language = st.substring(st.indexOf('*')+1, st.lastIndexOf('*'));
      }
      long ind = Wid ;
      while(ind >= 0 ){
        Serial.println("*");
        if(Serial.available()>1 ){
          boolean pixls[16][100];
          getArray(pixls);
          displayArray(pixls);
          ind-=100;
        }
        if(ind >=Wid){
          ind = wid ;
        }
      }
    }

    void getArray(boolean arr[16][100]){
      byte serialData[16];
      for(int k = 0 ; k < 100 ; k++){
        Serial.readBytes(serialData,16);
        for(int i = 0 ; i < 16 ; i++){
          arr[i][k]= serialData[i];
        }
      }
    }

    void displayArray(boolean arr[16][100]){
      for(int h = 0 ; h <= 100-33 ; h++){
        for (int i = 0 ,g=h; i < 32 ,g<h+32; i++ ,g++){
          for (int j = 0 ; j < 16 ; j++){
            dmd.setPixel(i,j,(arr[j][g] == 1) ? GRAPHICS_ON : GRAPHICS_OFF);
          }
        }
        delay(100);
      }
    }

**This VB code works for me when sending just 100 columns of the array:**

    SerialPort2.Open()

            Dim BUFFER(16) As Byte
            For J = 0 To 100
                For I = 0 To rows - 1
                    BUFFER(I) = ar(J, I)
                Next
                SerialPort2.Write(BUFFER, 0, 16)
            Next
            SerialPort2.Close()

**C++ code:**

    #include <SPI.h>
    #include <DMD2.h>
    SoftDMD dmd(1,1);

    void setup() {
      Serial.begin(9600);
      dmd.setBrightness(255);
      dmd.begin();
    }
    void loop() {
        boolean pixls[16][100];
        for(int i=0 ;i<100 ; i++){
          for(int j=0 ;j<16 ; j++){
            pixls[j][i]=0;
          }
        }
        if(Serial.available()>0){
          getArray(pixls);
          for(int i=0 ; i<100 ; i++)
          {
            displayArray(pixls);
          }
        }
    }
    void getArray(boolean arr[16][100]){
      byte serialData[16];
      for(int k = 0 ; k < 100 ; k++){
        Serial.readBytes(serialData,16);
        for(int i = 0 ; i < 16 ; i++){
          arr[i][k]= serialData[i];
        }
      }
    }

    void displayArray(boolean arr[16][100]){
      for(int h = 0 ; h <= 100-33 ; h++){
        for (int i = 0 ,g=h; i < 32 ,g<h+32; i++ ,g++){
          for (int j = 0 ; j < 16 ; j++){
            dmd.setPixel(i,j,(arr[j][g] == 1) ? GRAPHICS_ON : GRAPHICS_OFF);
          }
        }
        delay(100);
      }
    }

body:
      boolean pixls[16][100];

You are running out of RAM, amongst other possible problems.

That array alone takes 1600 bytes out of 2048 on the Uno. Since you are using Serial that also takes:

* 34 bytes for the HardwareSerial instance (Serial)
* 64 bytes for the Serial transmit buffer
* 64 bytes for the Serial receive buffer
* 4 bytes for the Serial transmit buffer head and tail pointers
* 4 bytes for the Serial receive buffer head and tail pointers

That's another 170 bytes.

    SoftDMD dmd(1,1);

I presume that also uses RAM.

You need to rework. You don't need to store 100 bytes before displaying. How about reading each byte and displaying it? That saves almost 1600 bytes.


body:
You have likely run out of RAM.

The following use up large chunks of your SRAM:

 - `pixls` array = 1600 bytes
 - Serial = 170 bytes
 - DMD > 64 bytes

This is in addition to all your other variables and function calls.

The problem is that the compiler promotes boolean variables to bytes. So where you need 1600 pixels it takes 1600 bytes. Alternatively, you could pack 8 pixels into that byte. This method would only consume 200 bytes instead of 1600.

Also, I don't understand why you have a 16 by 100 array. From the code I can see that you are using a single DMD which has 32 pixels wide by 16 pixels high. Why send/buffer more pixels than needed? A single DMD would only need an array of 64 bytes.

The Arduino Uno only has 2KB of SRAM.

**Solutions:**

1. **I suggest sending the ASCII text to the Arduino and then letting the font library within SoftDMD convert it to pixels. That is why you are using the DMD2 library.**

However if you want to stick to the approach you have taken:

2. Pack 8 pixels into every byte in the array. This will save 1400 bytes of precious SRAM.

3. Only send one DMD word of data at a time. This will save 1536 bytes of precious SRAM.

4. You could use an Arduino with a greater amount of SRAM.

 - Arduino Mega  - 8KB SRAM
 - Arduino ZERO  - 32KB SRAM
 - Arduino Due   - 96KB SRAM
 - Arduino MKR 1000/1010/1400/ZERO - 32KB SRAM


message:
Trying to verify that Arduino Pro Micro ISP is working

I'm trying to program an Arduino Pro Micro with another Arduino Pro Micro. The purpose is to verify that I can use this Pro Micro board reliably as an ISP to program another Arduino device that does not have a USB interface.

These are actually Pro Micro clones but they seem to work quite well using the Arduino Leonardo profile. I'm following [this pinout][1].

Here is the photo of the setup:

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

The "red" Pro Micro is set up as ISP using the stock ArduinoISP sketch (didn't think anything needed changing). The "white" Pro Micro is the one I'm trying to program.

The pins are connected, 5V - 5V, GND - GND, MISO - MISO, MOSI - MOSI, SCLK - SCLK, Pin 10 - Pin 10 (reset? this might be wrong).

I've confirmed the ISP sketch is running by the green heartbeat LED. The three LEDs on the red board are connected to pins 7 (top), 8, 9 (bottom), with 9 being the heartbeat.

I loaded the Blink sketch and changed the LED pin to pin 9 since the default pin 14 on the white board is being used as the MISO pin for programming.

In the IDE, I set the board to Arduino Leonardo, port to the red board's port, programmer to "Arduino as ISP" and ran "Upload Using Programmer".

The only output I get is:

    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

Since I'm really just beginning all of this, I'm a bit confused what might be wrong and what could be a next troubleshooting step. Any help appreciated.

  [1]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#hardware-overview-pro-micro
  [2]: https://i.stack.imgur.com/2rHti.jpg

body:
As Mikael Patel notes, pin 10 on the programmer Pro Micro should run to RST on the target.

That might or might not fix the problem.  In some previous instances of the “Yikes! Invalid device signature” [[1](https://arduino.stackexchange.com/questions/3781/when-using-arduino-uno-as-isp-does-yikes-invalid-device-signature-mean-a-bad),[2](http://forum.arduino.cc/index.php?topic=152587.0)] bad breadboard connections turned out to be the problem.  I suggest you run a second (or even a third) set of jumpers in parallel with the first set.  Of course use matching colors to avoid confusion.


message:
Esp8266-01 AT commands returns random chars and/or "ERROR"

I'm trying to make my esp8266 work with my arduino.

But when I send AT commands I get some weird symbols and some functions return "ERROR"

Here's the code I'm using.

    #include "SoftwareSerial.h"

    SoftwareSerial esp8266(6, 7); // RX, TX

    void setup()
    {
      Serial.begin(9600); // serial port used for debugging
      esp8266.begin(115200);  // your ESP's baud rate might be different
    }

    void loop()
    {
      if(esp8266.available())  // check if the ESP is sending a message
      {
        while(esp8266.available())
        {
          char c = esp8266.read();  // read the next character.

          Serial.write(c);  // writes data to the serial monitor
        }
      }

      if(Serial.available())
      {
        delay(10);  // wait to let all the input command in the serial buffer

        // read the input command in a string
        String cmd = "";
        while(Serial.available())
        {
          cmd += (char)Serial.read();
        }
        // send to the esp8266
        esp8266.println(cmd);
      }
    }

Here's the Serial Monitor:

    AT

    OK
    AT+RST

    OK

     ets Jan  8 2013,rst catse:2, boot lode:(3,7)

    loab 0x40100000& len 1396, qoom 16
    tail 4C�,kk�������e
    load 0x3fge8000, len 776, room 4 tak0  t0�v�
    �!jH+��
    ����(j5�!
    ,�2%1�

    j
    �sl��o�
    Ai,Thinker Technology Co. Ltd.

    invalid
    AT+CWMODE?

    +CWMODE:1

    OK

    AT+GMR

    AT version;0.25.0.0(Juo  5 2015 17:27:16)
    SDK version:1.0
    ryJ 0

    AT+CWLAP

    +CWLAP:(4,"�P��R�*bj��b���*��2��*����Ҋ�b�Jj
    ��*A�B�br������Յź�aj��b����2j
    ":6�*AՉ����J
    "�́������

The commands where, `AT`, `AT+RST`, `AT+CWMODE?`, `AT+GMR`, `AT+CWLAP`

Why am I getting this weird symbols and etc? I haven't upgraded the firmware, should I?  There other commands I tried return "ERROR" or even "ERROQ"

I don't have a USB to TTL or any other board. I connected my board in the arduino with this schematic:

[![esp8266 connection to arduino using voltage regulator][1]][1]

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

Cap = 10uF
VolReg = LM1117 3.3v

body:
The problem is mainly in using Serial and SoftwareSerial together. Or it can be due the esp getting less current than it requires from the Arduino(you are also damaging your Arduino!), use an external 5V source (I use my computer USB)

Why dont you directly use Serial for communication with pins 0 and 1. Just upload a blank sketch, connect Arduino Tx, Rx to esp's Tx, Rx(reverse Tx, Rx if not working). What you type into Serial will then be sent to the esp. Later if you wish to communicate to esp in sketches, use only SoftwareSerial.

Also, the esp is not 5V tolerant so you need to use a level shifter(like the cd4050 ic) or a voltage divider(less efficient) for signals from the Arduino to the esp. 3.3V is considered as a logical HIGH so you dont need to do any changes for signals from esp to the Arduino.

I highly recommend getting a USB TTL converter, this will save you a lot of headaches and debugging will be easy. I did things without it for 1-2months and now I can totally feel the difference.