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

title: Send multiple sensor values over serial

Answers: 3

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


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

title: SN76489 - Ready pin not working?

Answers: 2

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.


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

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

Answers: 6

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


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

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

Answers: 1

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.


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

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

Answers: 1

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!


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

title: Arduino PWM Pins Interrupt

Answers: 2

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


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

title: Arduino app hangs on upload for all boards

Answers: 2

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.


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

    }

title: Arduino: Read frequency of input from audio jack

Answers: 2

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


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

title: Dot Matrix Display with Arduino UNO (PROBLEM)

Answers: 2

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


body:
I am making a controller for a model railway turntable and I need to control a single DC motor and read a hall effect sensor. I have the hall effect sensor connected to pin 2 on my Uno (since 2/3 are the only pins that support interrupts) but whenever I turn the motor on it triggers the interrupt on pin 2 despite the fact that the motor PWM pin is on pin 11 and I have disconnected alternate PWM pin 3. This is with the official Arduino motor shield and an Uno.

I'm at a loss here, any ideas? I know it's not the motor triggering the hall effect sensor because I connected a resistor in place of the motor and it still happened.

title: Motor shield causing problems with interrupts?

Answers: 0


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

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

Answers: 1

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.


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

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

Answers: 5

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.

body: SoftwareSerial is reliable only up to 9600 baud or so. You can either swap ports and use Software serial as your debug output (but requires disconnecting/reconnecting the ESP8266 chip each time you upload to the UNO); or write a short sketch to set the device's baud rate to 9600 baud (and convince yourself that at least that much ran OK!) and set your SoftwareSerial to that rate.

body:
 - The Arduino pin 7 (TX) signal must be level-shifted from 5V to 3.3V using a voltage divider, because the ESP cant handle 5V signals.
 - The Serial baud is a lot lower than that of SoftwareSerial plus you are spending a lot of time waiting for the whole command to come in. SoftwareSerial is also unreliable at 115200 baud. Use 57600 baud for both serial ports.

Use this code:

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

    void setup()
    {
      Serial.begin(57600);
      esp8266.begin(57600);
    }

    void loop()
    {
      while (Serial.available())
        esp8266.write(Serial.read());
      while (esp8266.available())
        Serial.write(esp8266.read());
    }

It will do the exact same thing you want to do. Good luck.

body:
I had the same issue before and it is a little bug in your code - while reading all the data from the serial port, you also read the CR & NL and then you send that as a line (with probably another NL). I solved it as such:

      if(Serial.available())
      {
        String command="";
        uint8_t c=0;
        while(c!=10) // read the command character by character
        {
          if (Serial.available()) {
            c=Serial.read();
            command+=(char)c;
          }
        }
        //Serial.print("Sending: ");
        //Serial.println(command);
        esp8266.print(command); // send the read character to the esp8266
      }

As you can tell, I was suspicious of the code and echoed back to make sure the reading from the `Serial` function. Also I went back to straight USB->Uno->ESP mode to confirm all was working, even the firmware with the 9600 Baud uploaded and then it clicked.

body:
These values mostly come when you are unable to communicate with any UART device on proper baud rate. Best is to change the baud rate of ESP8266 from dafault 115200 to 9600 using

    AT+UART_DEF=9600,8,1,0,3

And then use the regular program. And you will get what you want.

    #include <SoftwareSerial.h>
    #include<stdio.h>
    SoftwareSerial mySerial(2,3);
    void get_wifi_list();
    uint8_t flag = 0;

    void setup() {

        Serial.begin(9600);
        Serial.println("Starting the code, initial set-up");
        mySerial.begin(9600);
        delay(1000);
        Serial.println("Inside the main loop, going to start communicating with ESP8266");
        delay(1000);

    }

    void loop(){

      char data[1024];
      uint8_t ch = -1;
      uint8_t index = 0;
      memset(&data,0,sizeof(data));
      char data1[200];
      uint8_t index1 = 0;
      memset(&data1,0,sizeof(data1));

      if(mySerial.available())  // check if the ESP is sending a message
        {
        while(mySerial.available())
            {
                char c = mySerial.read();  // read the next character.
                data[index] = c;
                index++;
                if(index >= 2000){
                    Serial.print("Data received exceed allowed length \n");
                    return;
                    }
                    if (c == '+' ){
                        Serial.print("got start char");
                        //data1[index1] = c;
                        //index1++;
                        //if ( c== '\n');{
                        //    Serial.print("First data1 is :  ");
                        //    Serial.println(data1);
                        //    return;
                        //    }

          if( strstr(data,"OK")!=NULL || strstr(data,"CWLAP") !=NULL){
          Serial.print ("Get reply as OK \n");
          Serial.print (data);

            }
          }
        }
      }
      if (flag == 0){
          get_wifi_list();
          Serial.println("Getting the wifi list");
          flag = 1;
          return;
      }

      if(Serial.available()){
        delay(10);
        String cmd = "";
        while(Serial.available()){
            cmd += (char)Serial.read();
            }
        mySerial.println(cmd);
          }

    }

    void get_wifi_list(){
      String cmd = "AT+CWLAP";
      mySerial.println(cmd);
    }


body:
Just trying to find out if my Arduino UNO R1 board is broken or not.

First of all, everything seems normal, Arduino board shows "on" (green) when I plug it on my computer, I also can verify and upload programs to my Arduino board. But, no matter what program I upload the pin 13 turns on and off 3 times and that's it. I'm checkin it by using a LED.
Eg. if I want to use another pin (ex. 7, 8, 12) it doesn't work, or even to write a program for turning on/off 9 times pin 13 doesn't work...

Note: I noticed that pin 8 turns the LED for less than a 1/2 a second.

I already tried to restart board by bridging the reset pin and also by pushing reset directly on the board, I also reinstalled Arduino Genuino Application. I thought to update Atmega8U2 firmware but accordingly to Arduino [site][1] I don't need to update since I have firmware rev. 0.01.

It would be also great not to have to buy a new Arduino UNO. Thanks for your help

Edit:
Here is how I'm trying to make pin 12 work

    int ledPin = 12;

    void setup()
    {
     pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
     digitalWrite(ledPin, HIGH);
     delay(2000);
     digitalWrite(ledPin, LOW);
     delay(2000);
    }

  [1]: https://www.arduino.cc/en/Hacking/DFUProgramming8U2

title: Is my Arduino board defect? No matter what program I upload the pin 13 turns on and off 3 times and that's it

Answers: 1

body:
The best way to check if Arduino is working or not is to install Firmata. Here's the necessary steps:

1) Download Firmata application from the [official website][1].

  [1]: http://www.firmata.org/wiki/Main_Page#Firmata_Test_Program

2) Connect Arduino to the computer

3) Open the Arduino IDE and burn the example Standard Firmata [File - Examples - Firmata - Standard Firmata]

4) Open the application, leaving the Arduino connected.

5) Chose the right serial port and debug every pin =D


body:
I need help with my coding. I'm still learning on how to use interval `millis()`.

Currently I'm working on a water heater with a safety feature. This means that you can only pour water out when you activate the child-lock feature. The child-lock feature will turn on for 5 seconds and within that 5 seconds if you pour the water out, the timer will pause until you finish pouring your water and the 5 second timer will start again and the system goes off after that.

If the child lock feature on for 5 second without any action, it will turn off the system again. My lecturer does not allow me to use the `delay()` function so I already did my coding using `millis()`.

This is my code so far:

    const int redLed = 2;
    const int greenLed = 3;
    const int yellowLed = 4;
    const int greenbigLed = 7;

    const int buttonPin1 = 5;
    const int buttonPin2 = 6;

    int buttonState1 = 0;
    int buttonState2 = 0;
    float tempC ;
    int analogPin = A0;
    int yellowLedState = 0;

    const long interval1 =0;
    const long interval2 = 5000;
    unsigned long previousMillis = 0;

    void setup() {
      // put your setup code here, to run once:
    pinMode(2,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,INPUT);
    pinMode(6,INPUT);
    Serial.begin(9600);
    digitalWrite(yellowLed,yellowLedState);

    }

    void loop() {
      // put your main code here, to run repeatedly:
    int analogValue = analogRead(analogPin);
    int buttonState1 = digitalRead(buttonPin1);
    int buttonState2 = digitalRead(buttonPin2);
    int yellowLedState = digitalRead(yellowLed);
    tempC = analogValue / 10 ;
    Serial.println(tempC);
    unsigned long currentMillis = millis();
    unsigned long currentMillis2 = millis();

    if (tempC <= 89.9 && tempC >= 0){
      digitalWrite(redLed,HIGH);
      digitalWrite(greenLed,LOW);
    }else if(tempC == 102){
      digitalWrite(redLed,LOW);
      digitalWrite(greenLed,HIGH);
    }

    if(currentMillis - previousMillis >= interval2){
      previousMillis = currentMillis;
      if(buttonState1 == HIGH){
       // if(currentMillis2 - previousMillis2 >=interval2){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
      } else{
      digitalWrite(yellowLed,LOW);
        }
    }

    if (buttonState2 == HIGH && yellowLedState == HIGH){
      digitalWrite(greenbigLed, HIGH);
    }else{
      digitalWrite(greenbigLed,LOW);
    }

    }

Now, I'm able to pour out water when child lock feature activated, but the problem is the timer (interval) still ticking.

Is there any solution on how can I pause the interval whenever I'm pouring water (button2) and the interval starts back 5 sec when I release button2 (pouring water)?

I would glad if someone can help me. Ask me anything about my code.

title: Water heater coding problem

Answers: 1

body:
Thanks @Arjan for reminding me. I would love to contribute to the community. So this is my final coding and its worked for me :

    const int redLed = 2;
    const int greenLed = 3;
    const int yellowLed = 4;
    const int greenbigLed = 7;

    const int buttonPin1 = 5;
    const int buttonPin2 = 6;

    int buttonState1 = 0;
    int buttonState2 = 0;
    float tempC ;
    int analogPin = A0;
    int yellowLedState = 0;

    const long interval = 5000;
    unsigned long previousMillis = 0;

    void setup() {
      // put your setup code here, to run once:
    pinMode(2,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,INPUT);
    pinMode(6,INPUT);
    Serial.begin(9600);
    digitalWrite(yellowLed,yellowLedState);

    }

    void loop() {
      // put your main code here, to run repeatedly:
    int analogValue = analogRead(analogPin);
    int buttonState1 = digitalRead(buttonPin1);
    int buttonState2 = digitalRead(buttonPin2);
    int yellowLedState = digitalRead(yellowLed);
    tempC = analogValue / 10 ;
    Serial.println(tempC);
    unsigned long currentMillis = millis();

    if (tempC <= 89.9 && tempC >= 0){
      digitalWrite(redLed,HIGH);
      digitalWrite(greenLed,LOW);
    }else if(tempC == 102){
      digitalWrite(redLed,LOW);
      digitalWrite(greenLed,HIGH);
    }

    if(currentMillis - previousMillis >= interval){
      previousMillis = currentMillis;
          if(buttonState1 == HIGH){
             if (yellowLedState == LOW) {
                  yellowLedState = HIGH;
        }
        digitalWrite(yellowLed, yellowLedState);
      } else{
          digitalWrite(yellowLed,LOW);
        }
    }

    if (buttonState2 == HIGH && yellowLedState == HIGH){
      digitalWrite(greenbigLed, HIGH);
      digitalWrite(yellowLed,HIGH);
    }else{
      digitalWrite(greenbigLed,LOW);
      if(currentMillis - previousMillis >= interval){
      previousMillis = currentMillis;
          if(buttonState1 == HIGH){
             if (yellowLedState == LOW) {
                  yellowLedState = HIGH;
        }
        digitalWrite(yellowLed, yellowLedState);
      } else{
          digitalWrite(yellowLed,LOW);
        }
    }
    }
    }


body:
I would like to connect the Atmega328p chip to my desktop, through the USB, so I can run teraterm or hyperterminal for debugging purposes.
I have already ordered a USB to TTL serial cable but it won't be arriving for about a week.
I recently bought a usbASP ISP to program the chip on my Arduino.
My question is: can I use the usbASP in place of the TTL cable? or is there some conditioning circuit in the usbASP that won't allow this?

It seems for the usb to ttl, all that is required to interface with the chip is VCC, GRD, RX and TX. So, which pins are the RX and TX?

Hope my question makes sense, they usually don't! thanks in advance!

title: Debugging with ISP

Answers: 1

body:
There *is* provision in the USBasp specification for a UART connection, **however**, not all manufacturers copy the original schematic exactly, and no firmware actually contains the appropriate code for CDC/ACM required in order to enable it. And even if they did, technically low-speed CDC/ACM is a violation of the USB protocol and not all operating systems will acknowledge it.

As for your title of "Debugging with ISP", if you have an Atmel programmer and are using Atmel Studio then you *can* perform debugging over ISP (actually debugWIRE, but they use the same connections).


body:
I bought the following USBasp off of Aliexpress.

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

The Arduino UDE doesn't recognize it. When I try to run avrdude with it, it says:

    avrdude -cusbasp -Pusb -patmega328p
    avrdude: error: could not find USB device with vid=0x16c0 pid=0x5dc vendor='www.fischl.de' product='USBasp'

Looking at the USB enumeration, it says:

USBHID:

      Product ID: 0xc8b4
      Vendor ID: 0x03eb  (Atmel Corporation)
      Version: 1.00
      Speed: Up to 1.5 Mb/sec
      Manufacturer: zhifengsoft
      Location ID: 0x14200000 / 8
      Current Available (mA): 1000
      Current Required (mA): 100
      Extra Operating Current (mA): 0

Looking online, I see one blog post (http://www.sciencetronics.com/greenphotons/?p=938) about a device with the same VID/PID, and it says it can be reprogrammed but is not clear how to do it.

In particular, I know there is a jumper that I need to set to put it in self-programming mode but I can't figure out where to put this jumper. Once the jumper is in, I understand I just match the SPI pins and program it using the firmware.

Can someone help?

  [1]: https://i.stack.imgur.com/x4B7c.jpg
  [2]: https://i.stack.imgur.com/Cmd07.jpg

title: Is this a USBasp I can use with Arduino?

Answers: 1

body:
That's not a USBasp, that's some other programmer that has co-opted Atmel's vendor ID invalidly. If you want to use it then you will need to find and use some program called "ProgISP" that is only available for Windows.

That particular device does not show the jumper required for reprogramming, so I wouldn't attempt it (and in fact I would find the nearest bin to toss it in and get a couple from Baite and/or LC Tech instead).


body: I am going to be controlling 2 servo motors with an arduino. I will use an external battery pack for power. Do I need to connect the negative of the battery to ground on the arduino? If I just use the battery pack to power an LED, it works without connecting it to ground. Can someone please explain the logic behind this in simple wording? Thank you

title: Do external battery packs need to connect to ground on the arduino?

Answers: 3

body:
Ground is merely a label. It is a logical point in the circuit relative to which you measure all other voltages against.

For instance the 5V pin on the Arduino is actually 5V *relative to the ground pin*.

A 12V battery's `+` terminal is 12V *relative to the `-` terminal*. In this situation the `-` pin can be labelled Ground.

Electricity only ever flows when there is a circuit.  That is, current can only flow when it has some way of flowing back to where it came from.

A battery with an LED and resistor attached has a circuit: *Battery -> LED -> Resistor -> Battery*.  An Arduino itself is a circuit: *Power -> Arduino -> Internal Gubbins -> Power*

By the rule above, electricity can only ever flow out of an I/O pin if it has some way of getting back to where it came from. That route back is the Ground pin of the Arduino.  Interfacing some external device with the Arduino, whether it has its own power supply or not, requires that connection back to the Arduino's ground in order for the signal you send from the Arduino to have a complete circuit.

body:
I like the Majenko's answer, but I'm going to explain it with a different approach. You know that there are some quantities that are measurable in an absolute way (mass, lenght, weight) and other that need a starting point to refer. Think about the **distance**: you cannot say "New York" is distant 10km.. the question that obviously would come in mind is: 10km from what? So you have to decide a point in the world, from which you can measure the distance of every city.

The voltage measure the potential, that is the energy that a single charge would have. Now the question is: is the potential energy an absolute value? Of course not, i have to define a point where it is zero, and measure everything from it. In a circuit this point is called Ground, evry potential measured in the circuit is calculated to the ground.

The last step is to know that charges goes from the points at higher pot to the lowest one (the ground), usually preferring the path with lower resistsnce (but that's another story). **A wire has the same potential all along it** and in order to compare the voltage of arduino and the battery pack they must refer to the same ground.

body:
> so because the arduino is sending a signal to one of the pins on the servo, the servo needs to be connected to Arduino's ground.

Here is typically how you might wire a servo:

[![Servo wiring][1]][1]

Note the shared ground. The Arduino provides the control signal (data) via the orange wire. The battery provides the motor power via the red wire. The grounds must be shared or the voltages on each wire are meaningless.

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


body:
I'm creating a real-time vehicle tracking Android application using the Arduino Uno and SIM900 GPS. I want to use Firebase as the database for the coordinates which will hold just the longitude and latitude. My question is about sending the data through the GPRS to Firebase. Right now I've only been able to use a terminal program to send AT commands to create a connection but I've been getting errors when connecting to firebase using AT+CIPSEND. I know that it only excepts https traffic so I've been trying commands from [here][1]. Here is some code that I've tried:

    AT
    OK
    AT+CREG?
    +CREG: 0,1

    OK
    AT+CGATT?
    +CGATT: 1

    OK
    AT+CIPSTATUS
    OK

    STATE: IP INITIAL
    AT+CIPMUX=0
    OK
    AT+CSTT="att.mvno","",""
    OK
    AT+CIICR
    OK
    AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","80"
    OK
    CONNECT OK
and

    AT+CIPSHUT
    OK
    AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","443"
    OK
    CONNECT OK
If I use CIPSEND, how should my message be formatted to send lat or long in a way Firebase can interpret?
Or am I going about this in a convoluted manner? Is there an easier way? I appreciate any help/comment. Thank you.

  [1]: http://www.jarzebski.pl/datasheets/SIM900_https-121018-1.00.pdf

title: How to send data from Arduino Uno with SIM900 GPRS to Firebase

Answers: 2

body:
Like you said, Firebase only accepts HTTPS traffic, which the Arduino Uno cant generate. Your HTTP requests first need to be sent through a proxy server that supports SSL, before being sent on to your Firebase database using a PUT or POST request. [This site][1] explains how to do everything from setting up your own proxy server to writing the GPS data (in your case) to Firebase. You may want to look at alternatives if this is too tedious for your purposes.

  [1]: http://www.devacron.com/arduino-firebase/

body: just remove "https://" its working


body:
I'm trying to replicate this: https://zhengludwig.wordpress.com/projects/self-driving-rc-car/ using pretty much the exact same controller and car.

I've soldered 4 wires to the controller, 1 for each direction. If I let the wires touch the ground on the controller everything works perfect. However, when I connect the wires to the Arduino nothing works. Sometimes left/right works for about 0.5 seconds then it goes back to doing nothing. Any idea on what the problem might be? Do I need to connect the controllers ground to the Arduino ground?

I've tried removing the batteries from the controller and connecting 3.3V and ground from the Arduino, which sorta works but I feel like it shouldn't be needed.

If I use the buttons on the controller while it's connected to the Arduino it goes either forward, right or forward+right.

The code I'm using to test everything looks like this:

    void setup() {
      //Initialize the pins and serial
      pinMode(reversePin, OUTPUT);
      pinMode(forwardPin, OUTPUT);
      pinMode(leftPin, OUTPUT);
      pinMode(rightPin, OUTPUT);
    }

    void reset() {
      digitalWrite(forwardPin, HIGH);
      digitalWrite(reversePin, HIGH);
      digitalWrite(leftPin, HIGH);
      digitalWrite(rightPin, HIGH);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      reset();

      digitalWrite(forwardPin, LOW);
      delay(4000);
      reset();
      digitalWrite(reversePin, LOW);
      delay(4000);
      reset();
      digitalWrite(leftPin, LOW);
      delay(4000);
      reset();
      digitalWrite(rightPin, LOW);
      delay(4000);
    }

Images: https://i.stack.imgur.com/mCpcI.jpg

title: Controlling an RC car using Arduino

Answers: 2

body:
Can you measure how much current goes through the wire when grounded (A: 2 mA from measurements in comments) ? And the open circuit voltage between the controller's ground and the control wire?  (A: 3.1V, from 2xAA)

If the current isn't more than the 40mA per pin/100mA per port, 200mA total, and the open circuit voltage of the controller pins is less than 5V, then you should be able to connect the Arduino's output pins and ground to your controller's wires and ground.

If the voltages and currents are higher, then you would need protection to prevent damaging your Arduino.

The controller and the Arduino should share a common ground, but without a circuit and without the controller's voltages and currents, it is hard to tell exactly what is wrong.

Edit: Since the controller's open circuit voltage and short-circuit currents (3.1 V, 2mA max) fit within the Arduino's capabilities, you can wire them directly to the pin outputs, and make sure the controller and the arduino share a common ground.

You need a fifth wire between the controller ground to the Arduino ground to make the logic levels actually communicate between the two devices.

You likely also need some 5V->3V level shifting to isolate the Arduino's output levels from the controller's inputs.   Top of the line would be MOSFETS, but you could possibly use a voltage dividing resistor pair.  See the hints in https://arduino.stackexchange.com/a/419/6628

body:
[![enter image description here][1]][1]We have to add 1k resistors and 2k resistors as 330 ohms instead and follow the link below..!

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


body:
tldr; I am writing a mesh network software using arduinos. I need to wirelessly receive, process, and transmit data, all simultaneously. I am aware of protothreads library, and the other software solutions, such as using interrupts, however, I am using relatively high baud rates. Thus each nanosecond is of the essence. Does anyone have any other ideas for me to achieve this? my initial thought is to have 2 Arduinos functioning as a single node in the mesh. One will receive while the other transmits.

I am currently using [these][1] antennas to receive and send messages. I want to create a mesh network of Arduinos using these modules. I found several mesh libraries for Arduino, but none seem to quite do the task I need. So here is my plan which I will work through using an example. (This is a very naive explanation, and has flaws in it's implementation. This is just to give off the general idea).

Each Arduino will be connected to a receiver *and* a transmitter. Let's say I have just 4 nodes in the mesh.

 1. Node #1 -> Address = 0xA031
 2. Node #2 -> Address = 0xB042
 3. Node #3 -> Address = 0xC053
 4. Node #4 -> Address = 0xD064

I send a message to node A through USB. Let's say the message is "SOS!"
Node A will reconstruct the message in the following way so that the new message is "0xA031_SOS!"

Now, Node A will begin transmitting this message continually. Let's say only Node C picks up the message. Node C will pick up the message and perform the following checks. (I will have 2 queues. A receiving queue and a transmitting queue. So as soon as a node receives a message, it will be placed in the receiving queue. And then it will run the following checks before sending it to the transmitting queue.)

 1. Is the address a recognized/valid address? Handle appropriately
 2. Is the address of the received message the same as the node's own address?

    `If address is same, check if the message received is the same message being transmitted currently by itself. If so, discard the message and tell transmitter to stop transmitting that message(This means that the message was originally transmitted to another node and came back, which means, it doesn't need to be re-transmitted any more). If the address is not the same, then send the message to the transmission queue.`

Now the transmission will be handled the following way.

 1. Check if there is anything in the transmission queue. If there is, transmit this message continually until told not to.
 2. If the transmitter is told to not transmit that message any longer, that message will be popped of the queue.

So what happens? Node A continually sends a message. Node C receives the message and re-transmits. Because Node C was able to pick up Node A's message, it is in range and Node A will pick up Node C's message. Now, Node A will check the address, and say "oh, this is the same address as me." Then it will check if the message being transmitted is the same as what was received. If so, then it will tell the transmission queue to no longer transmit that message. (This almost like a form of back propagation).

Now I realize there are a million ways to have collisions and infinite loops. I will be eventually writing a software to resolve these things. But I hope I am giving off the general idea of how the network will work.

My questions:

 1. As is clear from my explanation, because I am receiving and transmitting simultaneously, is there a way for me to do multi-threading? I am aware of protothreads and the other things mentioned in this [post][2]. However, all of them only offer a software solution, and not a hardware solution. So does anyone have any ideas of how I'd work around this? My initial thought is to have each node be composed of 2 Arduinos. Any one have any other ideas?
 2. Also, does anyone have a better idea of implementing the mesh to do what I want it to?

I know this is a very convoluted, hefty post. Please let me know what I should clarify. Thank you.

  [1]: http://oliverwhysall.co.uk/wp-content/uploads/2015/02/antenna-placement.jpg
  [2]: https://arduino.stackexchange.com/questions/286/how-can-i-create-multiple-running-threads

title: Receiving and transmitting messages simultaneously

Answers: 0


body:
I bought a [Gsm module][1] recently(not official arduino shield) and i connect it to Arduino uno. The problem (I guess) is , i can't set delay properly, the terminal send it too fast that i missed it or too slow even i set its baud rate to 4800 (I have tried it with many baud from 4800-to-115200).

I uploaded the code to Git ,with [this address][2].

More details: For example when i enter `d` in terminal it act like this message came up : `+CMTI: "SM",3` and it want to save it but it miss plus at first of it and it save `CMTI: "SM",3`,

After that it perform this : `AT+CMGR=3` the terminal show the message in half size : `+CMGR: "REC UNREAD","+9*********2","H/E.3D/1","16/02/28,00:27:02+14"` which totally missed body part.

The weird thing is when i put some println on the program it miss more characters , and second weird thing is it missed more character in second run or i push d again.

I have tried to change the delays but no success.How can i fix it ? any help would be appreciated.

**Edit**:

If i make it simpler, when i use these code i get half message :

    #include <SoftwareSerial.h>
    SoftwareSerial serialGPRS(7, 8);
    void setup()
    {
      Serial.begin(19200);
      serialGPRS.begin(19200);
    }
    void loop()
    {
      serialGPRS.println("AT+CMGR=1");
      delay(1000);
      while(serialGPRS.available()!=0)
        Serial.write(serialGPRS.read());
    }
like: `+CMGR: "REC READ","+9*******",".H/E.3D/1`

  [1]: http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0
  [2]: https://github.com/zigi1/Test/blob/master/gsm.c

title: How to set Delay on GSM shield?

Answers: 1

body:
The `SoftwareSerial` receive buffer is getting filled up and discarding characters. You are not reading fast enough from the buffer. Adding `Serial.println()` will slow down your `read`ing even more. The simplest solution to this is to increase the size of the `SoftwareSerial` buffer from its default size of 64 bytes to 256 bytes (or smaller, depending on what works for you).

On a Windows PC, go to `C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial`. Open `SoftwareSerial.h` and change the line:

    #define _SS_MAX_RX_BUFF 64 // RX buffer size

to

    #define _SS_MAX_RX_BUFF 256 // RX buffer size

Save the file and try your sketch again.


body: I'm planning to connect GPS to IMU, Is't possible ? I tried my best to find an article that can help solving my curiosity.  How can i connect GPS and MPU to arduino uno?

title: How to connect GPS to IMU?

Answers: 1

body:
Is not really connecting GPS to IMU, is more like you read GPS values, read IMU values and after apply what is called a sensor fusion algorithm.

One of the most common used sensor fusion algorithms is called Kalman filter (the Extended Kalman Filter more likelly). However, if you do not have some basis on control theory you may have more trouble in applying it.

[here](http://publications.lib.chalmers.se/records/fulltext/159412.pdf) is a good example of use of this kind of sensors and fusion algorithms. It is also very commonly used in drones or autonomous vehicles.

The implementation will be specific to what you are trying to do.


body:
I have been experiment with the arduino uno board from few days but can't seem to make it serve web page stored in SD card of ethernet shield.

If I print the contents of the file to serial it works properly, even embedding the HTML code works fine, but `client.write()` just produces a never ending garbage text of ` ÿÿÿÿÿÿÿÿÿÿÿÿ `

    #include <SPI.h>
    #include <Ethernet.h>
    #include <SD.h>
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 0, 115);
    EthernetServer server(80);

    File webFile;

    void setup()
    {
        pinMode(4, OUTPUT);
        digitalWrite(4, HIGH);
        Ethernet.begin(mac, ip);
        server.begin();
        Serial.begin(9600);

    // initialize SD card
    Serial.println("Initializing SD card...");
    if (!SD.begin(4)) {
        Serial.println("ERROR - SD card initialization failed!");
        return;
    }

    Serial.println("SUCCESS - SD card initialized.");
    // check for index.htm file
    if (!SD.exists("index.htm")) {
        Serial.println("ERROR - Can't find index.htm file!");
        return;  // can't find index file
    }
    Serial.println("SUCCESS - Found index.htm file.");
    }

    void loop()
    {
    EthernetClient client = server.available();  // try to get client

    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    Serial.println("starting to open htm");
                    client.println();
                    // send web page
                    webFile = SD.open("index.htm");        // open web page file
                    if (webFile) {
                        while(webFile.available()) {
                            client.write(webFile.read()); // send web page to client
                        }
                        webFile.close();
                    }
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                }
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
    }

Sorry for the poor formatting, I just copied it from tutorial, please help me out.

title: Simple webpage serve with Arduino ethernet shield on SD card

Answers: 2

body: "ÿ" is character code 255, the erased state of a Flash/EPROM/SD. Check if your SD card format OK, 'index.htm' file is there, and your code can read it.

body:
Me I solve the problem by using : "/index~1.htm"
I see that the file name is seen like that using the cardinfo.ino from Example


body:
I just plugged my arduino in and the light is on, but the blink test failed to upload. here is my error:

Arduino: 1.6.7 (Linux), Board: "Arduino/Genuino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/ttyUSB0": Permission denied
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

title: First time set up- permission denied to usb port- ubuntu 14.04

Answers: 5

body:
From the documentation:

> Open Terminal and type:

>     ls -l /dev/ttyACM*

>you will get something like:

>     crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

>The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

>Now we just need to add our user to the group:

>     sudo usermod -a -G dialout $USER

>then:

>     sudo chmod a+rw /dev/ttyACM0
You will need to log out and log in again for this change to take effect.

Note that the preceding is old Ubuntu instructions. On modern distros that use ConsoleKit create the file `/etc/udev/rules.d/01-ttyusb.rules` containing the following and then reload the udev rules and replug the Arduino device:

    SUBSYSTEMS=="usb-serial", TAG+="uaccess"

body:
Or just use the chown command.

    sudo chown <username> /dev/ttyACM*
This worked for me

body:
All you need to do is add yourself to the dialout group as described in the answer by Ignacio Vazquez-Abrams. This is done in the terminal by typing:

    sudo usermod -a -G dialout $USER

You do not need to use `chmod`. This gives read/write access to all users and not just members of the group. Before attempting to connect, however, you must **logout and log back in**. Once you log back in you will be recognized as a member of the dialout group and will be able to open the device.

body:
On Ubuntu 18.04, the only way I found the Arduino IDE installation to work straight out of the box, was using the documentation steps described here:

https://www.arduino.cc/en/Guide/Linux/

No changing groups nor permissions required.

body: Nothing above have helped me. When I have installed from file, from official site, it doesnt even start. Then I have installed Arduino IDE from "linux app store" and was working but have a problem like our friend from top. So I have uninstalled it and installed via terminal    `sudo apt install arduino `and now it`s working. Cheers.


body:
I have been wondering how to remote control my arduino robot using an old 2.4ghz car toy transmitter which has 4 buttons, up down left and right.
I have the nRF24L01(+) 2.4GHz transceiver to use it as a receiver.

Is there anyway to detect the signals going out from the remote controller and use them to make my arduino works,
I am a newbie so i am sorry if any mistake.

Thanks guys!

title: How to remote control Arduino using an old 2.4Ghz toy remote controller?

Answers: 1

body:
You have two options:

1. Use an nRF24L01+ on the Arduino and dismantle the controller to rip out the innards, replacing them with another Arduino and another nRF24L01+.
2. Do not use the nRF24L01+, instead, rip apart the car and salvage the receiver from it, then work out how you can wire that to the Arduino.

The car's controller will not talk to the nRF24L01+. Yes, they may be in the same frequency band, but they do not talk the same language. After all, your WiFi is on the same band and that doesn't talk to the car, and your microwave, which is also 2.4GHz, doesn't sit and watch satellite TV all day. As you can see the 2.4GHz band is used by a huge number of devices (the band is actually getting quite crowded) and everything talked to everything else in the same band it would be utter chaos.


body: I'm writing a library which controls a device using SPI bus. For the communication I need to manually toggle the chip select pin. On most Arduinos SS pin is on D10, but there are also other models where it's different like D53 on Mega. Is there a way to know where it is? Like a global #define? I would like to avoid any pin configuration parameters in my library. At least for default configuration...

title: Are there any constants for default SPI port pins defined?

Answers: 2

body:
Yes there are. They are defined in pins_arduino.h Below the pins for the yun.

    // Map SPI port to 'new' pins D14..D17
    static const uint8_t SS   = 17;
    static const uint8_t MOSI = 16;
    static const uint8_t MISO = 14;
    static const uint8_t SCK  = 15;

Use SS MOSI MISO and SCK in your code

body:
This is defined in the platform variant specific file `pins_arduino.h` in the variants folder (<arduino>\hardware\arduino\avr\variants). Each platform variant (standard, mega, leonardo etc) gets their pin definitions set here. For instance the mega:

    static const uint8_t SS   = 53;
    static const uint8_t MOSI = 51;
    static const uint8_t MISO = 50;
    static const uint8_t SCK  = 52;


body:
I have switch is a line connected to Digital pins 1,2,3,4,5 . When pins 1 connects, I need a timer to start. as the rest connect i need it to mark the time in the console output of each one and End on the timer on connection to pin 5. ex

    START:
    0.00
    1.43
    2.12
    2.94
    3.89
    END

Also is there a way to Save the data to a log (.txt or whatever) If not its fine but I need to record results.

(This is for a school project)
THANKS!

title: Start timer when pins connected

Answers: 2

body:
I will not give you code, only clues on how to write the code yourself.

The way to tackle this is to (at first) remove the Arduino from the equation. Replace it, instead, with you.

Imagine you are doing the timing yourself. How would *you* go about doing it?

This is how I would set about the task:

1. When the first button gets pressed I would look at the clock and jot down the current time.
2. When the second button gets pressed I would again look at the clock, and subtract the first time from the current time to find out how much time has elapsed. I would jot that down.
3. When the third button is pressed I would do the same again - look at the clock, subtract the start time, and jot down the difference.
4. And I would keep going until I had run out of buttons.

So now you need to find the right code to read what buttons are doing, get the current time, and finally send the times somewhere useful.

For all those there are many many many examples on the web.

body:
Are you familiar with interrupts? The best/most efficient way to do this is with pin interrupts on each input pin (and make sure your switches are wired correctly and debounced).

Unfortunately, within the Arduino libraries, there are only two pin interrupts (0 and 1), which correspond to pins 2 and 3.

You have two options:

Use a polling solution. Use one pin with an interrupt to start the timer (save the value of `millis()`) and then poll the other switches in a loop, capturing the `millis()` value at each switch closure.

Alternatively, the ATmega can fire an interrupt when _any_ pin in a port changes, but IIRC this isn't built into the Arduino libraries and requires direct register manipulation.