body:
I am trying to read the fuse values for the Arduino Uno, but keep getting the following results returned back to me:

    enter code hereavrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/usr/local/CrossPack-AVR-20131216/etc/avrdude.conf"
         User configuration file is "/Users/hd334/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbmodem1421
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f
    avrdude: safemode: lfuse reads as 0
    avrdude: safemode: hfuse reads as 0
    avrdude: safemode: efuse reads as 0

    avrdude: safemode: lfuse reads as 0
    avrdude: safemode: hfuse reads as 0
    avrdude: safemode: efuse reads as 0
    avrdude: safemode: Fuses OK (H:00, E:00, L:00)

    avrdude done.  Thank you.

I have tried using avrisp as the programmer too, but this reports an invalid device signature. If I override the device signature check with -F I get the same results as above.

I am using an Uno as the ISP to another uno and have connected the two together as detailed in
https://www.arduino.cc/en/Tutorial/ArduinoISP

I have boot loaded the Arduino Atmega328P boot loader and from the fuse settings given in the boards.txt file expect to see:
lfuse reads 0xff
hfuse reads 0xde
efuse reads 0x05

Another question is with the low fuse set to 0xff the CKDIV8 is programmed so won't the clock be set to 2MHz?

Please help

title: Arduino Uno Reading Fuses

Answers: 2

body:
I'm using a stk500 (USB <> ISP programmer) to read atmega328p fuses. I use this cmd:

    C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avrdude.exe -CC:"\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega328p -cstk500 -PCOM9 -e -Ulfuse:r:-:i -Uhfuse:r:-:i -Uefuse:r:-:i

Sometime ago I had some issues with device signatures because I missed the "p" in atmega328p definition.

As a tip, you can check the Arduino verbose to help you with more information:

FILE >> PREFERENCES

SHOW VERBOSE OUTPUT DURING: [x] COMPILATION [x] UPLOAD

body:
Concerning your questions about clock division settings: have a look at [this pretty tool][1], it gives you a avrdude query for setting fuses (take care!). The CKDIV8 bit of the low fuse is set by default, so an AT328p will run at 1MHz, clearing this bit will result in 8 MHz.

When flashing you should never override any checks as this may damage/lock your chip.

I see that avrdudes states the supply voltage to be 0.3 volts which is far to low for communication. Any received bits would be low level and therefore any information read will be 0. ISPs usually provide a supply voltage which often can be selected by switches on the programmer. If you are sure your programmer is allright, check your circuit in general.

Btw, which ISP-model do you use?
Is your mcu assembled on a custom pcb (setup?)? If yes, do you have an arduino(like) board to verify this behaviour?

  [1]: http://www.engbedded.com/fusecalc/


body:
I'm using an ESP8266 version 1 with the [WiFiEsp library](https://github.com/bportaluri/WiFiEsp) to connect to WiFi, and that works just fine.

I'm setting up the device using the same code as in the example [`WebClientRepeating`](https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClientRepeating/WebClientRepeating.ino).

I need to send a POST request instead of a GET request, but I can't get it to work as I want. If I create my POST request like this, it works just fine:

    if (client.connect(server, 3005)) {
      Serial.println("Connecting...");

      // send the HTTP POST request
      client.println("POST /open/peripherals HTTP/1.1");
      client.println("Host: 192.168.10.137:3005");
      client.println("User-Agent: Arduino/1.0");
      client.println("Connection: close");
      client.println();

      // note the time that the connection was made
      lastConnectionTime = millis();
    }
    else {
      // if you couldn't make a connection
      Serial.println("Connection failed");
    }

I get the response like this:

    [WiFiEsp] Connecting to 192.168.10.137
    Connecting...
    HTTP/1.1 200 OK
    X-Powered-By: Express
    Content-Type: application/json; charset=utf-8
    Content-Length: 19
    ETag: W/"13-jSAaqMh5E3R94/b2aONzvg"
    Date: Sun, 13 Nov 2016 10:20:58 GMT
    Connection: close

    {"temp":"Testdata"}

However, if I try to send some body data in the request it fails:

    if (client.connect(server, 3005)) {
      Serial.println("Connecting...");

      // send the HTTP POST request
      client.println("POST /open/peripherals HTTP/1.1");
      client.println("Host: 192.168.10.137:3005");
      client.println("User-Agent: Arduino/1.0");
      client.println("Connection: close");
      client.println("Content-Type: application/x-www-form-urlencoded");
      client.println("Content-Length: 16");
      client.println();
      client.println("temperature=22.7");

      // note the time that the connection was made
      lastConnectionTime = millis();
    }
    else {
      // if you couldn't make a connection
      Serial.println("Connection failed");
    }

Then the response from serial output is:

    [WiFiEsp] Connecting to 192.168.10.137
    Connecting...
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] Data packet send error (1)
    [WiFiEsp] Failed to write to socket 0
    [WiFiEsp] Disconnecting  0

However, the POST request including the body is received by the Web server just fine, but the response sent to the Arduino I can't read because it shows me an error instead of a proper response. From my webserver the response for the POST call that works and the POST call that fails is the same.

Does anyone knows why this fails when I add `Content-Type`, `Content-Length` and some body data?

Thanks in advance!

title: Problem with sending a POST request using the WiFiEsp library

Answers: 2

body:
Your problem is the content you are sending. While this format works well e. g. in Python libraries, this library seems to have a problem with it.
I solved it this way, when I happened to face this problem:

    //all your other code, including the remaining HTTP-Request
    String content = "{\"temperature\":\""+String(value)+"\"}";
    client.println("Content-Length: 16"); //insert, well, your content length
    client.println(content);

body:
One major problem seems to exists within the AT firmware of most ESP's. By default, the http headers it sends include **"Connection: close"**. However, the firmware seems to be buggy and unable to cope with the server closing the connection after it sends the response. Thus, in order to be able to get a response back from the target server you need to have **"Connection: keep-alive"** instead. This means you must explicitly add this to your header since **"Connection: close"** will be added if nothing else is said.
Also to make life easier for the WifiEsp library you could make sure your server returns an already well-known status string for the library like fx **"SEND OK"**… I'm doing this on a barometer logger that sends data to a MVC Web Api written in C# and it works perfect...

Here's my code:

    String PostHeader = "POST http://" + server + ":" + String(port) + "/api/values HTTP/1.1\r\n";
    PostHeader += "Connection: keep-alive\r\n";
    PostHeader += "Content-Type: application/json; charset=utf-8\r\n";
    PostHeader += "Host: " + server + ":" + String(port) + "\r\n";
    PostHeader += "Content-Length: " + String(jsonString.length()) + "\r\n\r\n";
    PostHeader += jsonString;
    Serial.println(PostHeader);
    client.connect(server.c_str(), port);
    client.println(PostHeader);
    client.stop();

And the full log looks like this:

    POST http://192.168.10.197:8001/api/values HTTP/1.1
    Connection: keep-alive
    Content-Type: application/json; charset=utf-8
    Host: 192.168.10.197:8001
    Content-Length: 144

    {"IpAddress":"192.168.10.230","MacAddress":"5c:cf:7f:d9:2f:c8","Temperature":34.6,"Pressure":1007,"Altitude":48.48573,"PressureAtSeaLevel":1007}

    [WiFiEsp] Connecting to 192.168.10.197
    [WiFiEsp] Disconnecting  3

In the file debug.h located in the WifiEsp library source code you could alter a define and get more output to your serial console. Open the file and change

    #define _ESPLOGLEVEL_ 3
to

    #define _ESPLOGLEVEL_ 4
Save the file and recompile/deploy your source code to your Arduino and you will get extensive information about all AT commands the library sends and what the library receives in return.


body:
Since I don't like the text editor of the Arduino IDE, I decided to write a python script that I can invoke from my text editor to compile and upload my source. I program the popular esp8266 chip. So far I found that there is a python builder [here][1]. This did not work for me. So is there any way to compile my source (e.g. main.ino) via a terminal command?

  [1]: https://github.com/esp8266/Arduino/blob/master/tools/build.py

title: Compiling sketch vi command line

Answers: 2

body: In the Arduino IDE  preferences, select  external editor. Then you can write/ edit your sketches with any editor you choose. When you click compile or upload on the IDE toolbar, it will load your changes each time you compile.

body:
I found a [makefile][1] created to compile ESP8266 sketches. You can use this makefile from command line:

    cd /path/to/sketch
    make -f /path/to/makefile/makeEspArduino.mk upload

  [1]: https://github.com/plerup/makeEspArduino


body:
Has anyone experience configuring the Atmega328P to work with an 8Mhz external clock?

I want to reduce the power consumption of the device. If I just connect an 8MHz external quartz oscillator then simple programs like LED blink still work (With the time delays doubled), but if I try to use communication like UART, then I am unable to. So no programming new sketches.

title: Atmega328P 8MHz External Clock

Answers: 3

body:
If you reduce the main clock speed by 50% then everything else is reduced by 50% as well.

The whole chip runs at half the speed. That includes things like the UART.

For example, the bootloader is set to run at 115200 baud on a 16MHz chip. If you run that same chip, with the same bootloader, at 8MHz then the bootloader will actually be running at half the baud rate, so 115200 / 2 = 57600 baud.

Unless you tell the IDE that your board is now running at 8MHz (by creating or using the correct board configuration information to set F_CPU to 8000000) then time runs at half the speed in your sketches too. So a delay of one second will last two seconds. Every two milliseconds a single millisecond will pass. And again baud rates will be wrong. If you use:

    Serial.begin(9600);

you will actually be running at half that speed (4800 baud) and so you would have to set your serial terminal program to that speed instead of the one you requested.

To to do things properly you will have to:

1. Replace the crystal
2. Edit, compile, and install a new version of the bootloader that runs at 8MHz
3. Create (or edit) a suitable board definition (in boards.txt) to compile sketches that expect to run at 8MHz.

body:
Firstly, you can buy 8MHz Atmega328P Pro-Minis from China. They are cheap and run at 3.3V. Look at eBay.

If you want to reduce the power consumption of Arduino boards, you have three primary attack vectors:

- Removing the power LED
- Removing the voltage regulator
- A Low-Power library

All of these have different impacts on the power consumption of your respective board.

An extensive comparison can be found [here in this blog-post](https://andreasrohner.at/posts/Electronics/How-to-modify-an-Arduino-Pro-Mini-clone-for-low-power-consumption/).

body:
The easiest way is to use the settings:

**Tools > Board > Arduino Pro or Pro Mini**

**Tools > Processor > ATmega328 (3.3V, 8MHz)**

The problem with that is the Pro Mini bootloader is 2kB and has a [bug](https://github.com/arduino/Arduino/issues/4492) that causes an endless reset loop if you do a watchdog reset.

The better option is to use https://github.com/MCUdude/MiniCore, which includes the Optiboot bootloader, saving 1.5kB of flash memory vs using the Pro Mini bootloader and doesn't have the watchdog bug.

After selecting the correct configuration for your hardware from the **Tools** menu, do **Tools > Burn Bootloader**, which will set the fuses on your ATmega328P and upload the correct bootloader.


body:
I'm writing a library for my project, which interfaces sensors used and structures them in different systems.

But I'm such a noob at C++. The compiler is throwing this error:

    libraries/cec-core/cec-core.cpp: In member function 'void Habitaculo::Update()':
    libraries/cec-core/cec-core.cpp:15:8: error: expected unqualified-id before '.' token
    _Sluz.Update();

This is the header of that class:

    class Habitaculo
    {
     public:
     Habitaculo(int refrate, int luzpin, int dhtpin);
     //Values from Indoor Sensors
     int temp;
     int hum;
     int luz;
     //Update Methods
     void Update();  //Updates sensors value
     void UpdateReg(); //writes to SD or enabled output method
     private:
     //Clock Managing
     long _PreviousMillis;
     unsigned long _CurrentMillis;
     int _RefreshRate;
     //Sensor instances
     class _Sluz;
     class _SDHT;
    };

This are the member functions affected:

    Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin){
     //Clock management
     _RefreshRate = refrate;
     _PreviousMillis = 0;
     //Systems to initialize
     LDR _Sluz(luzpin);   //analogpin
     DHT11 _SDHT(dhtpin); //buspin
    }
    void Habitaculo::Update(){
     _CurrentMillis = millis();
     if (_CurrentMillis-_PreviousMillis > _RefreshRate){
      _Sluz.Update();  //unqualified-id before '.' token
      _SDHT.Update();  //unqualified-id before '.' token
      temp = _SDHT.temp;  //expected primary-expression before '.'
      hum = _SDHT.hum;  //expected primary-expression before '.'
      luz = _Sluz.value;  //expected primary-expression before '.'
      _PreviousMillis = _CurrentMillis;
     }
    }

The error is thrown in every step of the `Update` method. But I can copy that piece of code right in the `Habitaculo` constructor and it works well. So I assume I'm missing something basic about language syntax, because I'm really new to all this scene.

Every class involved in this (LDR, DHT11) works fine. It's when I try to put all this together into a new class - inside an unified Update method - that everything crashes.

title: Debugging library - Error- expected unqualified id before '.' token

Answers: 2

body:
    class _Sluz;
    class _SDHT;

You're forward declared two classes but I see nothing about what those classes are. You then to and use those class declarations as if they were class instances.

I think you are lacking a bit of basic syntax knowledge there. You may have meant:

    Sluz _Sluz;
    SDHT _SDHT;

Though not knowing what those classes are meant to be or how they are even defined I cannot know really what you think you're meaning.

body:
From what I guess in your code, here is how you want your class declared:

    class Habitaculo
    {
        public:
        Habitaculo(int refrate, int luzpin, int dhtpin);
        //Values from Indoor Sensors
        int temp;
        int hum;
        int luz;
        //Update Methods
        void Update();      //Updates sensors value
        void UpdateReg();   //writes to SD or enabled output method
        private:
        //Clock Managing
        long _PreviousMillis;
        unsigned long _CurrentMillis;
        int _RefreshRate;
        //Sensor instances
        LDR _Sluz;
        DHT11 _SDHT;
    };

Of course, in your header file, you will have to `#include` the proper header files for `DHT11` and `LDR` classes.

Then you will need to change your constructor as follows:

    Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
    :_Sluz(luzpin), _SDHT(dhtpin)
    {
        //Clock management
        _RefreshRate = refrate;
        _PreviousMillis = 0;
    }

Note the `:_Sluz(luzpin), _SDHT(dhtpin)` line before the constructor body, in C++, this is how members of your class that are instances of another class must be instantiated.

Actually, you could even empty the whole cosntructor body by also initializing `_RefreshRate` and `_PreviousMillis` in the same manner:

    Habitaculo::Habitaculo(int refrate, int luzpin, int dhtpin)
    :_PreviousMillis(0), _RefreshRate(refrate), _Sluz(luzpin), _SDHT(dhtpin) {}

which is a bit more idiomatic C++.


body: I have an Arduino Uno and I'd like to read a signal from a co-ax cable with it. The cable carries 12VDC (power for other components) along with a signal (of about 1 Ghz frequency). How do I go about recording this signal with my Uno? I'm new to this field so I don't know the full capabilities of the ADC. Also, the Uno can't handle >5 VDC, so what should I do to make the signal readable?

title: Read signal from co-ax cable with ADC

Answers: 1

body:
It's not possible. To sample a 1GHz signal you need to sample at least 2 billion times per second (a sample rate of 2Gsps). You can maybe get a couple of hundred KILO samples (thousand) per second on an Arduino.

Also the 1GHz signal itself is of no interest to you. What is of interest is what is *modulated* on the 1GHz signal.

What is normally done is:

1. Down-mix (filter) the carrier signal to an IF (Intermediate Frequency) usually in the order of a few kilohertz
2. Demodulate the signal using whatever modulation scheme was used to encode it.
3. Extract the encoded information from the demodulated signal.

To do that you'd need

1. the precise carrier frequency (1GHz is not the same as 1.029GHz)
2. the modulation scheme used (there's loads to choose from)
3. knowledge about any data formats and encodings used in the signal

As well as the hardware to do all that.

So no, you're never going to come even anywhere close with an Uno. You need specialised RF hardware just to prepare the signal for working with.


body:
Does anyone know how to configure the Atmega32u4 to run using an external 8MHz oscillator ?

I needs to still be responsive to the Arduino IDE

Thanks

title: Atmega32u4 external 8MHz clock

Answers: 1

body:
See §28.2 in [Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf), which explains usage of various fuse bits.

Also see [engbedded.com/fusecalc](http://www.engbedded.com/fusecalc/), which lets you easily figure out fuse settings.  Fusecalc also tells you the strings to use as part of avrdude command strings.

Once you know the fuse settings, send them to your device via a command like

    avrdude -p m32u4 -c usbasp -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

or like

    avrdude -p m32u4 -P $port -c arduino -u -U lfuse:w:0xEF:m -U hfuse:w:0xD5:m -U efuse:w:0x07:m

where `$port` represents a port name like `/dev/ttyUSB0`.

Note, it makes sense to read the fuses first, and put the readings into Fusecalc to see what they correspond to.  You can read the fuses via a command like

    avrdude -p m32u4 -P $port -c arduino -U hfuse:r:-:i


body:
I am using an EthernetServer and EthernetClient with Arduino in order to make a simple webpage. I have a web form for a user to enter various codes that can reset data stored on the back end. However, once I enter text into the web form once, it seems to be continually being included in the HTTP header after that. I have the URL: http://192.168.1.30, which becomes (and stays at) http://192.168.1.30/?data=5935 once I enter '5935'. My code is:

    void loop() {

    // Listen for incoming clients
    client = server.available();
    if (client) {

    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if(HTTPHeader.length() < 100) {
          HTTPHeader += c;
        }

        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {

          // Calcuate weather parameters for serial and web
          calcWeather(); //Go calc all the various sensors

          // Send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");

          client.println("
");
          client.println("");
          client.println("
");
          client.println("Web Server and Radio Receiver ");
          client.println("
");
          client.println("version November 14, 2016");
          client.println("
");
          client.println("");

          client.println("INSIDE");
          client.println("
");
          client.print("Temperature (F) = ");
          client.println(templm34);
          client.println("
");

          client.println("Transmission Errors: ");
          client.print("");
          client.print(numberReceived);
          client.println("
");

          client.println("Transmissions Received : ");
          client.print("");
          client.print(numberOfErrors);
          client.println("
");

          client.println("Transmission Error Rate: ");
          client.print("");
          client.print((numberReceived==0)?(0.0):(numberOfErrors/numberReceived));
          client.println("%
");

          client.println("
");
          client.println("
");
          client.println("
");
          client.println("
");

          // Display the table of illuminance values
          client.println("
");
          client.println("
");
          client.println("Illuminance	");
          client.println("Real World Light Value	");
          client.println("
");
          client.println("
");
          client.println("0	");
          client.println("Absolute Dark	");
          client.println("
");
          client.println("
");
          client.println("10	");
          client.println("Night	");
          client.println("
");
          client.println("
");
          client.println("100	");
          client.println("Dark Day	");
          client.println("
");
          client.println("
");
          client.println("1000	");
          client.println("Overcast	");
          client.println("
");
          client.println("
");
          client.println("
");

          client.println("
");
          client.println("<form action='/' method=get>");
          client.println("<input type=text name=data maxlength=4>");
          client.println("<input type=submit value=Submit>");
          client.println("</form>");

          client.println("");
          client.println("");

          break;

        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    }

    // give the web browser time to receive the data
    delay(1);
    client.stop();
    if (HTTPHeader.indexOf("5935") > 0) {
      resetData();
      Serial.print("Found!");
    }
    HTTPHeader = "";
    }

"Found" is printed to the serial every time the page refreshes even though I have not actually pressed the submit button to submit it more than once. I've tried the temporary redirect, but the linux machine I need to use for this project already does a redirect so my redirect doesn't work. Is there a way to do this without a redirect?

title: Getting data from web form

Answers: 0


body:
I want to transmit some values from arduino uno to my phone using bluetooth.
Which sensor i can use?I want to see some options because i'm a little bit uncertain.Thanks to all which can give me an advice !  :)

title: Which sensor i can use to transmit some values from Arduino Uno to phone using bluetooth?

Answers: 1

body:
It's not a sensor, its a module. A quite popular module is the [HC-05][1]. It's a very simple to use module with a lot of support by the community. Cheap and great for projects.

  [1]: https://www.amazon.com/Wireless-Bluetooth-Serial-Transceiver-Module/dp/B00INWZRNC/ref=sr_1_1?ie=UTF8&qid=1479068592&sr=8-1&keywords=hc05


body:
I recently purchased an LiPower shield from SparkFun.

I also bought a Lithium Polymer battery off eBay and it appears to have a JST male connector (i could be wrong)?

I expected it to slot right into the board however the fit is slightly too large. Can any advise me of the name of the connector for the board battery supply, or have I mistaken the battery output connector?

Please see pictures below, thanks!

[![Iso view][2]][2]

[![Battery connection lead][4]][4]

  [2]: https://i.stack.imgur.com/aP0P7.jpg
  [4]: https://i.stack.imgur.com/MotH2.jpg

title: Can anybody advise what type of connector this is?

Answers: 3

body: The board uses a JST PH connector, with 2.0mm spacing. The battery has a JST XH connector, with 2.5mm spacing. You will need to replace the battery connector or put a XH socket on the board.

body:
That is generically a "JST" connector.  Named from the company that originally designed and made them.  But I believe there are many "second-source" (and likely counterfeit) sources of similar or identical connectors.

They are avaiable in a variety of mechanical configurations (horizontal, vertical, PC board mount, wire-end, etc. etc.)  And there are several variations with different pin sizes and pin-pitch (distance between the pins). They all look very similar, especially in photographs, but as you demonstrate, the different pitch families are NOT inter-connectable.

If you had bought the battery from SparkFun, it is quite likely that it would have the mating connector.  But since there is no standardization here, you will end up dealing with these kinds of mismatches.

body:
header on the board IS jst XHA connector,but wirinhg harness is XH,[![enter image description here][1]][1]

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


body:
I am an Arduino (and C/C++) newbie so apologies if I am missing something obvious.

I am using [IRremote (github link)][1] as my IR library.

I can get the simple send and receive demos working  individually.

However, I cannot get send AND receive working in the same Arduino at the same time.

I do not wish to do something like the "IRrecord" example but what I do want to do is have Arduino send and receive at all times and then trigger alarm/LED once the "beam" is broken.

I am using a TSOP 22 series as my IR receiver. I have tried to use protothreads but no luck. Any tips appreciated.

My current code snippet:

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);
    IRsend irsend;

    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      Serial.println("IR Receiver... Started");
    }

    void loop() {
      //single threaded nature seems to break below

      // i want to start receiver here
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        irrecv.resume(); // Receive the next value
      }
      //delay(5000);

      //trying to send here
      for (int i = 0; i < 3; i++) {
        irsend.sendSony(0xa90, 12);
        Serial.println("Sent Sony......");
        delay(40);
      }
      //delay(5000); //5 second delay between each signal burst
    }

  [1]: https://github.com/z3t0/Arduino-IRremote /"IRremote"

title: IRRemote send and receive same Arduino

Answers: 3

body:
I **THINK** the problem is that the Arduino takes some time (very minimal) to send the signal, but when it comes to receive it, the signal has already dissipated though your room.

---

>send and receive at all times and then trigger alarm/LED once the "beam" is broken.

Use a laser, it's cheaper, more acurate, and more "James Bond'ish'" :)

body:
I managed to do this using solution from [Ken Sheriff's Blog][1]. Ken provides a simple example and documents it perfectly. Due to the nature of my IR Receiver (rejecting continuous beam) I used the sample code provided by Stephane Deniaud in the comments section. Thanks to both...

    #include <IRremote.h>

    #define PIN_DETECT 2
    IRsend irsend;

    void setup()
    {
        pinMode(PIN_DETECT, INPUT);

        Serial.begin(115200);
        Serial.println("READY");

        attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);

        // Note : the IR emitter is on PIN #3
        irsend.enableIROut(38);
        IREmitterOn();
    }

    // Use this function instead of delay() as delay() does not work in interrupt callbacks
    void pause(int ms) {
        // We need a loop as the largest value for delayMicroseconds that will produce an accurate delay is 16383
        for (int i = 0; i < ms; i++) {
            delayMicroseconds(1000);
        }
    }

    void IREmitterOff() {
        irsend.space(0);
        pause(60); // 60 ms is OK for my TSOP but should be tuned
    }

    void IREmitterOn() {
        irsend.mark(0);
        pause(10);
    }

    void switchOffOnIREmitter() {
        IREmitterOff();
        IREmitterOn();
    }

    void checkIRBeamBreak() {
        int val = digitalRead(PIN_DETECT);
        // LOW : no beam break
        // HIGH : beam break
        if (val == LOW)
            return;

        detachInterrupt(digitalPinToInterrupt(PIN_DETECT));
        switchOffOnIREmitter();
        if (digitalRead(PIN_DETECT) == HIGH) {
            Serial.println("IR BEAM BREAK !!!!");
        }
        attachInterrupt(digitalPinToInterrupt(PIN_DETECT), checkIRBeamBreak, RISING);
    }

    void loop() {

    }

  [1]: http://www.righto.com/2010/03/detecting-ir-beam-break-with-arduino-ir.html
  [2]: http://Stephane Deniaud

body:
based on the concept of [user1843591 answer](https://arduino.stackexchange.com/a/31339/13509), i researched some more and found the [example of Nick Gammon](https://forum.arduino.cc/t/how-to-create-a-38-khz-pulse-with-arduino-using-timer-or-pwm/100217/44) in the arduino forum.

after some tweaks i came up with the following:
(based on both)
it uses Timer1 to generate a 38kHz signal and
Timer2 to generate a 760Hz cycle that switches the 38kHz signal on and off.
this way [the recommend pulse-cycles and gap times](https://www.vishay.com/docs/82459/tsop48.pdf#page=6&zoom=250,-155,381) for the Receiver (for me TSOP4438) is preserve.
it also implements *global flags* to decouple  the ISRs & mainloop.

(both files should be in a folder `IR_TSOP4438_light_barrier`)

`IR_TSOP4438_light_barrier.ino`
```
// simple light barrier test

extern volatile bool light_barrier_broken;

void setup(){
    Serial.begin(115200);
    Serial.println("IR_TSOP4438_light_barrier");
    Serial.println("setup...");
    setupIRLightBarrier();
    Serial.println("running.");
}

void loop() {
  if(light_barrier_broken) {
    Serial.println("light barrier 1 break detected");
    delay(20);
    digitalWrite (LED_BUILTIN, LOW);
    light_barrier_broken = false;
  }
}

```

`ir_light_barrier.ino`
```
// based on
// Example of modulating a 38 KHz carrier frequency at 500 Hz with a variable duty cycle
// Author: Nick Gammon
// Date: 24 September 2012
// https://forum.arduino.cc/t/how-to-create-a-38-khz-pulse-with-arduino-using-timer-or-pwm/100217/44

// tweaked for TSOP4438
// https://www.vishay.com/docs/82459/tsop48.pdf
// find max burst length and min gap times:
//
// Minimum burst length 10 cycles/burst
// After each burst of length 10 to 40 cycles
//  a minimum gap time is required of ≥ 10 cycles
// Maximum number of continuous short bursts/second: 1500
//
// translates to:
// 38kHz = 26,3 us / Pulse → *10= 263us
// max burst length: <= 1052us  (26,3*40)
// min gap   length: >=  263us  (26,3*10)
// total cycle time of (1052+263=) 1315us
// that violates the max bursts/second (666us/burst)
//
// on option is to optimize for the most bursts/second:
// so we use the min gap time as given and use the rest of the available time.
// 666us - 263us = 403 us burst length
// hopefully this way the AGC does not filter our stream...
// we now have to fit this to the best available prescaler / counter values:
// 672us fits good (this way we have less than the 1500 burst)
// this translates to 42 counts a' (0,0625us*256=) 16us
// so we use a gap length of 16us*17 = 272us
// this gives us a burst length of 16us*(42-17)= 400us
//
// second option is to optimize for the longest burst length and have less bursts/second.
// here we will use a in-between leaning towards longer bursts:
// 0,0625us*256=16us
// 16us*50counts =  800us = 0,80ms = 1250,00Hz = 1250bursts/s
// 16us*80counts = 1280us = 1,28ms =  781,25Hz = 781,25bursts/s
// gap   length: 16us*17      =  272us
// burst length: 16us*(80-17) = 1008us

// http://www.gammon.com.au/forum/?id=11504
// Timer 1
//   OC1A: D9
//   OC1B: D10
const byte LED = 9;

// Timer 2 (8bit)
//   OC2A: D11
//   OC2B: D3

// https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const byte light_barrier_PIN = 2;
// const byte light_barrier_PIN = 3;

// global flags to be handled in the main loop...
volatile bool light_barrier_broken = false;

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;
// (16000000 / 38000) = 421,05
// this only works on Timer 1 - as it is a 16bit timer.

// // ------------------------------------------
// // this is about the slowest possible setting.
// // timer2 target counts:
// // CPU          16MHz (0,0625us)
// // target       63Hz (16000us = 16ms)
// // prescaler    1024
// const long timer2_top = F_CPU / 63L / 1024;
// // (16000000 / 63 / 1024) = 250

// // ------------------------------------------
// // optimized for ~1500 bursts /second
// // target counts:
// // CPU          16MHz (0,0625us)
// // prescaler    256
// // target       1,488kHz (672us = 0,672ms)
// const long timer2_top = (F_CPU / 256L) / 1488L;
// // (16000000 / 256) / 1488 = 42
// // calculate on / off ratio (toggle point)
// const long timer2_compare = timer2_top * 400L / 672L;
// // 42 * 400 / 672   = 42 - 17   = 25

// ------------------------------------------
// in-between -  leaning for longer bursts
// target counts:
// CPU          16MHz (0,0625us)
// prescaler    256
// target       781kHz (1280us = 1,28ms)
const long timer2_top = (F_CPU / 256L) / 781L;
// (16000000 / 256) / 781 = 80
// calculate on / off ratio (toggle point)
const long timer2_compare = timer2_top * 1008L / 1280L;
// 80 * 1008 / 1280   =  80 - 17  =  63

volatile bool sender_active = false;

void light_barrier_ISR() {
    if (
        sender_active
        && digitalRead(light_barrier_PIN) == HIGH
    ) {
        digitalWrite (LED_BUILTIN, HIGH);
        light_barrier_broken = true;
        // if() {
        // }
    } else {
        digitalWrite (LED_BUILTIN, LOW);
    }
}

ISR (TIMER2_COMPA_vect) {
    // used to combine the two timers...

    // toggle D13
    // PINB = bit (5);
    // digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)) ;

    if (sender_active == false) {
        // enable timer1 output
        TCCR1A |= bit(COM1A0) ;  // Toggle OC1A on Compare Match
        // digitalWrite (LED_BUILTIN, HIGH);
        delayMicroseconds(100);
        sender_active = true;
    } else {
        sender_active = false;
        delayMicroseconds(100);
        // disable IR-Receiver Input check
        //detachInterrupt(digitalPinToInterrupt(light_barrier_PIN));
        // disable timer1 output
        TCCR1A &= ~bit(COM1A0) ;  // DO NOT Toggle OC1A on Compare Match
        digitalWrite (LED, LOW);  // ensure off
        // digitalWrite (LED_BUILTIN, LOW);
    }
}

void setupIRLightBarrier() {
    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, LOW);

    // set up Timer 1 - gives us 38.095 KHz
    TCCR1A = bit (COM1A0); // toggle OC1A on compare
    TCCR1B = _BV(WGM12) | _BV (CS10);   // CTC to OCR1A, No prescaler
    OCR1A =  (16000000L / 38000L / 2) - 1;  // zero relative

    // setup Timer 2
    TCCR2A = 0;
    TCCR2B = 0;
    // toggle OC2A on compare
    // TCCR2A |= bit(COM2A0);
    // fast pwm to OCR2A
    TCCR2A |= bit(WGM21) | bit(WGM20);
    TCCR2B |= bit(WGM22);
    // prescaler 1024
    // TCCR2B |= bit(CS22) | bit(CS21) | bit(CS20);
    // prescaler 265
    TCCR2B |= bit(CS22) | bit(CS21);
    // top
    OCR2A = timer2_top - 1;  // zero relative
    // switch point
    OCR2B = timer2_compare - 1;  // zero relative
    // enable interrupts
    TIMSK2 = bit(OCIE2A);
    // TIMSK2 = bit(OCIE2B) | bit(OCIE2A);

    // enable IR-Receiver Input check
    attachInterrupt(
        digitalPinToInterrupt(light_barrier_PIN),
        light_barrier_ISR,
        CHANGE
    );
}

```


body:
I am currently reading a DS1307 adafruit breakout board and I need to drive two nixie tubes from a shift register. The shift register is running two 74141 IC chips. I have code that loops through all the nixie digits one at a time with a delay of 1 second between each. Now I need to write some code to pull min, hour, and second and change the shift register low/high outputs to display the correct nixie digit. I have the DS1307 returning the correct time on my com by using

     Serial.print(now.hour(), DEC);
     Serial.print(now.minute(), DEC);
     Serial.print(now.second(), DEC);

However, I am not sure how to dimension a string, set that string equal to the two digits on the hour, minute, or time, and then divide the two digits and write if statements to correctly display the tubes. I am used to VB.NET and now C coding.

=======================UPDATE=======================

I am using this code to set any individual digit of the nixie tube to on.

           //Turn on 0
     sr.set(4, LOW);
     sr.set(5, LOW);
     sr.set(6, LOW);
     sr.set(7, LOW);

The sr is the shift register and each number is which leg of the shift register I am turning low or high. This specific piece turns on the digit 0.

title: Read time digits from DS1307 and run code based on return

Answers: 1

body:
You can set up an array containing the bit patterns to turn on different digits, and then use code that sends the bits for the high digit of `now.hour()/12` and the bits for the low digit of `now.hour()`.  For example:

    const byte digiBits[] = { B0000, B0001,
    // and so forth for all the digits ...
    };

    void send1Digit(byte digiVal, byte whichDigit) {
      // somehow use whichDigit to direct the bits someplace...

      // To send the bits:
      byte bits = digiBits[digiVal];
      for (byte i=4; i<8; ++i) {
        sr.set(i, bits & 1);  // Set a bit in SR to 0 or 1
        bits >>= 1; // shift out the used bit
      }
    }

    void send2Digits(byte numVal, byte whichDigit) {
      send1Digit(numVal/10, whichDigit);
      send1Digit(numVal, whichDigit+1);
    }

    void loop() {
      // other stuff, then:
      send2Digits(now.hour(), HourSpot);
      send2Digits(now.minute(), MinuteSpot);
      send2Digits(now.second(), SecondSpot);
      // other stuff ...
    }

Note 1:  If your `sr.set()` routine is doing any complicated masking or shifting, you may be able to avoid some of that by ORing `digiBits[digiVal]` with whatever number `sr.set()` might be building up to shift out.

Note 2:  If the numerical value of `digiBits[digiVal]` is equal to `digiVal`, then don't bother defining `digiBits[]`, but instead in `send1Digit()` just say `byte bits = digiVal`, or use `digiVal` directly in place of `bits`.


body:
I've got project that needed to have some (4) digits display, and had plenty of 7 seg. displays lying around. I didn't have any multiplexers left but have instead wired it up as per this diagram:
[![enter image description here][1]][1]

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

I've the wired my duemilanove with the a-dp pins on the 13-6, and the transistors on 5-2.

Getting the right segments on has been a breeze, but I'm finding that if I have any kind of counting logic, the displays dim to about 20%.
What I mean by this is that I can have my sketch run with all digits full brightness displaying 8s no problem, but if anywhere in the loop I have a variable that I increment up (say by incrementing up 1 per loop), and change nothing else, the display will go from 100% brightness, to 20% (at best).

Below is the demo code I'm using (there are tons of weird things in it at the moment as I've been desperately trying to track this dimming issue down), and all I have to change to see the effect take place is to uncomment the line at the end of the loop: "//count = count + 1;"

    const int sub_delay = 1000;

    const int middle_middle = 13;
    const int middle_top = 11;
    const int middle_bottom = 8;

    const int top_left = 12;
    const int top_right = 10;
    const int bottom_left = 9;
    const int bottom_right = 7;
    //Build the digit quick table

    int digits_all[] = {top_left, top_right, middle_top, middle_bottom, bottom_right, bottom_left, middle_middle};
    int digits0[] = {top_left, middle_top, top_right, middle_bottom, bottom_right, bottom_left};
    int digits1[] = {top_right, bottom_right};
    int digits2[] = {middle_top, middle_middle, middle_bottom, top_right, bottom_left};
    int digits3[] = {middle_top, middle_middle, middle_bottom, top_right, bottom_right};
    int digits4[] = {};
    int digits5[] = {};
    int digit_selector0 = 2;
    int digit_selector1 = 3;
    int digit_selector2 = 4;
    int digit_selector3 = 5;
    int digit_selectors[] = {digit_selector0, digit_selector1, digit_selector2, digit_selector3};

    int last = digits_all;
    int last_size = sizeof(digits_all);
    int last_selector = digit_selector0;

    String test = "12, 13, 10, 8, 7, 9";

    int count = 0;

    // the setup function runs once when you press reset or power the board
    void setup() {
      //Initialize the digit segments
      for (int c = 0; c < sizeof(digits0); c++) {
        //digitalWrite(digits0[c], HIGH);
        pinMode(digits0[c], OUTPUT);
      }

    //demo
      //digitalWrite(middle_middle, HIGH);
      //digitalWrite(top_left, HIGH);
      //digitalWrite(middle_top, HIGH);
      //digitalWrite(top_right, HIGH);
      //digitalWrite(bottom_left, HIGH);
      //digitalWrite(middle_bottom, HIGH);
      //digitalWrite(bottom_right, HIGH);

        Serial.begin(9600);

    }

    void turn_off_all (int digit, int digits[], int digits_size, int num) {

      last = digits;
      last_size = digits_size;

      digitalWrite(last_selector, LOW);
      last_selector = digit;

      digitalWrite(digit, HIGH);
    int temp = 1;
      if (num == 0) {
        digitalWrite(top_left, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(bottom_left, HIGH);
        digitalWrite(middle_top, HIGH);

        digitalWrite(middle_middle, LOW);
      }

      if (num == 1) {
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);

        digitalWrite(top_left, LOW);
        digitalWrite(middle_bottom, LOW);
        digitalWrite(bottom_left, LOW);
        digitalWrite(middle_top, LOW);
        digitalWrite(middle_middle, LOW);
      }

      if (num == 2) {
        digitalWrite(middle_top, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_left, HIGH);

        digitalWrite(top_left, LOW);
        digitalWrite(bottom_right, LOW);
      }

      if (num == 3) {
        digitalWrite(middle_top, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);

        digitalWrite(top_left, LOW);
        digitalWrite(bottom_left, LOW);
      }

      if (num == 4) {
        digitalWrite(top_right, HIGH);
        digitalWrite(top_left, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(middle_middle, HIGH);

        digitalWrite(middle_bottom, LOW);
        digitalWrite(middle_top, LOW);
        digitalWrite(bottom_left, LOW);
      }

      if (num == 5) {
        digitalWrite(top_left, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_top, HIGH);

        digitalWrite(top_right, LOW);
        digitalWrite(bottom_left, LOW);
      }

      if (num == 6) {
        digitalWrite(top_left, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(bottom_left, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_top, HIGH);

        digitalWrite(top_right, LOW);
      }

      if (num == 7) {
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(middle_top, HIGH);

        digitalWrite(bottom_left, LOW);
        digitalWrite(middle_bottom, LOW);
        digitalWrite(middle_middle, LOW);
        digitalWrite(top_left, LOW);
      }

      if (num == 8) {
        digitalWrite(top_left, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(bottom_left, HIGH);
        digitalWrite(middle_bottom, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_top, HIGH);
      }

      if (num == 9) {
        digitalWrite(top_left, HIGH);
        digitalWrite(top_right, HIGH);
        digitalWrite(bottom_right, HIGH);
        digitalWrite(middle_middle, HIGH);
        digitalWrite(middle_top, HIGH);
        digitalWrite(middle_bottom, HIGH);

        digitalWrite(bottom_left, LOW);
      }

    }

    // the loop function runs over and over again forever
    void loop() {

        turn_off_all(digit_selector0, digits0, sizeof(digits0), 1);
      delay(1000);

      //count = count + 1;

    }

Any suggestions welcome!

Extra notes: I haven't yet tried another arduino board, but I've never had issues with this particular board before (Though I am hoping to switch to an ESP8622, but that is irrelevant to this issue).

title: 7 Segment display dimming

Answers: 2

body:
You seem to be trying to do this from scratch. I haven't analysed the code, but you would be better off using one of the established libraries.

The code is unclear - I am not sure what much of it is trying to do (a few comments would help). There are obvious errors - in particular the incorrect use of `sizeof()` which is a common error.

I use the following http://playground.arduino.cc/Main/SevenSegmentLibrary

This just requires a single call to set the digits to be displayed and includes a Brightness call.

body:
If, as comments suggest, the problem also occurs when you are using a library, it's possible the problem is hardware related.  The 10KΩ base resistors are inordinately large, and are so large the transistors probably are limiting the total current per display to under 50 mA.

When you turn on one of d2 ... d5 (your digit-select drives), at most half a milliamp (5V/10KΩ) will enter the base.  If transistor beta is 100, that will allow 50 mA to flow.  (Not knowing the transistor type you used, I don't know its range of betas.)

Consider replacing the 10KΩ base resistors with 500-700 Ω resistors.

I see no place in the circuit where capacitors would make any positive difference.


body:
When compiling a sketch, after linking, the build outputs a kind of forecast on RAM usage, e.g.:

> Minimum Memory Usage: 1456 bytes (71% of a 2048 byte maximum)

Is it possible to somehow get a breakdown or itemization of these 1456 bytes and details on exactly where in my code, or in included libraries, they are used?

title: Detailed analyse of memory usage

Answers: 4

body:
Looking at an assembly listing of your code is the most direct method for finding out details of space allocation.  On my Ubuntu Linux system, I use a shell script (that is, a file containing shell commands) like the following to produce an assembly listing of the most-recently-compiled `.ino` file, which must be in the working directory when the script executes:

    #!/bin/sh
    # Look for .ino in current directory, and find recent /tmp/build...
    item=*.ino
    [ -z "$item" ] && echo ino file not found && exit
    BDIR=/tmp/$(ls -t /tmp | egrep -m1 build.*tmp)
    BASE=$(basename $item .ino)
    avr-objdump -S -I$PWD $BDIR/$BASE.cpp.elf > $BASE.ino.asm

All the stuff before the `avr-objdump` line allows the script to find out the name of the current `.ino` file and the name of the `/tmp/` subdirectory where the `.ino`'s `.elf` file is found.

You can also use `avr-objdump` to get a more concise size listing, as follows, where `$BDIR` and `$BASE` are as in the script above and represent the build directory in `/tmp/`, and the basename of the `.ino` file.

    avr-objdump -C -d $BDIR/$BASE.cpp.o| egrep -C2 '^Disassembly' | egrep -v '^--|^$|^Disassembly' | less

This will produce a list with two-line entries like the following, in which each line beginning with 00000000 is a subroutine name, and the next line shows the last line of its compiled code.  In this example output, the `setup_PowerDown()` routine has `0xA4` bytes of code, ISR `__vector_13` has `0xC6` bytes, `keepAlive()` has `0x10` bytes, etc.

    00000000 <setup_PowerDown()>:
      a4:   08 95           ret
    00000000 <__vector_13>:
      c6:   18 95           reti
    00000000 <keepAlive()>:
      10:   08 95           ret
    00000000 <eeWrite1(unsigned char, unsigned char)>:
      3a:   08 95           ret
    00000000 <eeWrite2(unsigned char, unsigned char)>:
      18:   0c 94 00 00     jmp     0       ; 0x0 <eeWrite2(unsigned char, unsigned char)>
    00000000 <parValidate(unsigned char, unsigned char, unsigned char)>:
      64:   08 95           ret
    00000000 <loadSettings()>:
      e0:   08 95           ret
    00000000 <applySettings()>:
      84:   08 95           ret

Some IDEs provide symbol table information that includes sizes of routines, stack frames, and data.  I don't know if that's available via Arduino IDE, AVR-libc, or [GNU Binutils](http://www.sourceware.org/binutils/).  The symbol table provided by `avr-readelf -s` (as in following command) provides quite detailed symbol information that seems quite useless in its raw form.

    avr-readelf  -s  $BDIR/$BASE.cpp.o

The methods described above are somewhat ad hoc, and depend on files left after `avr-gcc` or `avr-g++` run.  I don't know of any “official” methods for getting the information you want to see.

body:
Since you seem interested about RAM, rather than flash usage, I suggest
you look at the symbol table of your compiled program, which will be
more telling than the disassembly. On my Linux system, I usually do the
following:

    avr-nm -Crtd --size-sort the_program.elf | grep -i ' [dbv] '

`avr-nm` is the utility for displaying the symbol table. It is normally
packaged with the Arduino IDE. It is invoked here with the following
options:

* `--size-sort` is quite explicit
* `-C` means “demangle the C++ names”
* `-r` means “reverse sort”, i.e. sort from largest to smallest
* `-td` means “display numbers in decimal rather than hexadecimal”

This will output the list of all symbols that have a size, in three
columns: size, type and name. You are only interested in the symbols
that consume RAM, i.e. those of type `b` (BSS, or uninitialized data),
`d` (initialized data) and `v` (vtable), either in upper or lower case.
The `grep` command is a standard Unix utility which is used here to
extract only the relevant lines from the output of `avr-nm`.

Example output for a small program:

    00000068 B tx_buffer
    00000068 B rx_buffer
    00000034 B Serial
    00000016 V vtable for HardwareSerial
    00000004 B timer0_overflow_count
    00000004 B timer0_millis
    00000002 b loop::last_print
    00000001 b timer0_fract

The first 4 entries come from the `Serial` object. The 3 entries
starting with `timer0_` are used by the Arduino timekeeping functions
(`millis()`, `micros()` and `delay()`). The entry named
`loop::last_print` is a static local variable I declared in `loop()`.

body:
You can automatically generate a "map" file every time you compile. This gives you a full breakdown of how everything is linked together by the linker, including the size of each section and other useful debugging information.

A simple modification to platforms.txt in `hardware/arduino/avr` is all that is needed.  Find the line starting `compiler.c.elf.flags=` and add to the end of it:

     -Wl,-Map,"{build.path}/{build.project_name}.map"

If you like you can replace `{build.path}` with a hard-coded path, such as your desktop, and the `.map` with `.txt` to allow it to easily be opened by notepad or whatever you use (assuming Windows, of course).

body:
This was a great question and helped me recently as I'm building quite an extensive Arduino app using a Nano (ATMega328 and 32K of program memory).
At one point I was almost out of program memory and I was a bit shocked.
I didn't think the code was that large.

**My Tests and Results**

With the comments I read through the posts on this answer I decided to build a blank app and examine the results as I added libraries etc.  Here are my results (*Using Arduino IDE 1.8.13*):

1.  blank sketch takes up 444 bytes of program storage space (max is 30720 bytes).
2. Sketch which includes 6 libraries✔ uses up 6218 bytes

    `<LiquidCrystal_I2C.h>, <Wire.h>,<ds3231.h>,<SD.h>,<EEPROM.h>,<SoftwareSerial.h>`

3. adding one line `Serial.begin(9600);` uses 6324 bytes **NOTE**: 6324 - 6218 = 106 bytes even though I only added 19 bytes (the characters for that line).
4. Adding on more line `Serial.print("a");` results in 6342 bytes used. That's 18 more bytes (6324 - 6342 = 18) which is the exact number of characters I added with that line (including semicolon).
5. Adding a 2nd line with `Serial.print("a");` results in 6358 (16 bytes)
6. Adding a 3rd line of `Serial.print("a");` results in 6374 (16 additional bytes).

I hope this helps a bit. I'm going back to my app now and removing all the Serial lines I used for debug output.  They're just eating up program memory now.
Actually, I'll probably even use the conditional compilation ([shown in this SO answer][1]) so I can still print when in debug.

 Blank sketch means one with only the `void setup() {} void loop() {}` structures and nothing else.

✔ These are the libraries which I am using in my project.

 I came back and added these additional lines with the amount of Program Memory used because there was a comment that lines of code do not impact memory at all. Of course they do.  At some point all Program Memory is used up and your program will no longer fit into flash.  This is what I was having a challenge with as my extensive program (which includes sensors, LCD, sd card, and bluetooth) continues to grow.

  [1]: https://stackoverflow.com/questions/57554719/how-to-provide-conditional-compilation-to-arduino-code


body:
I've scoured the LANGUAGE REFERENCE in the [Arduino web-site][1], and I can't find a non-Float equivalent to `pow()`  I've got to be missing something big, but for the life of me, I'm stumped!  I found `pow()` in the FUNCTIONS column under the Math heading (like I would expect), but it says that both parameters,  [base] and [exponent] are both (float). And there are only six other entries under the Math heading; none of them seem to be seem to be an integer version. All I want to do is generate the powers of 2 using the exponents from 0 to 10. Like 2^0=1 then 2^1=2 then 2^2=4 then 2^3=8 then 2^4=16 then 2^5=32 then 2^6=64 then 2^7=128 then 2^8=256 then 2^9=512 then 2^10 is 1024

Is using floats the only way I can do this? I'm starting to feel like I'm at odds with reality, and have actually counted my medication, but I'm right where I should be. Let me apologize in advance for this egregious oversight that I've wasted your time with, but I've gone through all 9 pages of tags and have done ever search I could think of. I'll admit that I haven't spent all THAT much time, but I was sure this was only going to be like a five minute thing!

  [1]: https://www.arduino.cc/en/Reference/HomePage

title: Is there a non-float alternative to pow()?

Answers: 2

body:
It works with `int`, `double`, `long` and `float`. `unsigned long` and `unsigned int` should also work. You are not required to use ONLY floats.

Hope it helped!

body:
For the general case, @dat_ha 's answer is correct, but it is worth noting that you want a very special case... powers of two. Because computers use binary arithmetic, operations involving powers of two often have some shortcuts available.

Multiplying a number by a power of two can be accomplished by the left shift operation (`<<`), which literally shifts the digits of the binary representation of the number (i.e., bits) leftward.  In base two, shifting bits one place to the left is the same as multiplying by 2, just as in base 10 shifting digits one place to the left is the same as multiplying by 10. For a full explanation of the left shift operator in C++, see [this answer on Stack Overflow][1].

It is important to note that left shifting can lose information; bits shifted off the end are lost. Because you need powers of 2 up to 10, you are safe when working with signed integers, which [have a max value of `2^15-1` on Arduino Uno][2].

Given those caveats, here's a function to calculate powers of two within these constraints.  This is very fast code because the left shift operation is a very low level operation, and no multiplication is actually performed.

    int pow2(int p){
        return 1 << p;
    }

[1]: https://stackoverflow.com/a/141873
[2]: https://www.arduino.cc/en/Reference/Int


body:
I have an application where I would like to include an external multiline script as a const in my sketch. As far as I understand from C++11, this should work:

**raw_string_literal_test.ino**

    const char *script =
    #include "script.txt"
    ;

    void setup() {
      // put your setup code here, to run once:

    }

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

    }

**script.txt**

    R"(Line 1
    Line 2
    Line 3
    Line 4
    Line 5
    Line 6)"

script.txt is placed in the same folder as raw_string_literal_test.ino

However, upon clicking Verify (selected board is Arduino/Genuino Uno, Arduino version is 1.6.12 on Mac OS 10.11.6) I get the following error:

    /Users/owner/Desktop/raw_string/raw_string.ino:2:22: fatal error: script.txt: No such file or directory
     #include "script.txt"
                          ^
    compilation terminated.
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

What am I doing incorrectly?

title: Difficulties with raw string literals

Answers: 1

body:
Unlike other more "normal" build systems, the Arduino IDE doesn't compile the files in the project directory.

Instead it loads all the files with certain extensions into the IDE, each in its own tab. When you press the compile button it then writes the contents of each of those tabs to files in a temporary build folder and then compiles there.

Because of that only files with certain extensions ever get placed in the build folder. Those include:

* `.pde` and `.ino` for sketch files
* `.c` and `.cpp` for C and C++ source
* `.h` for headers
* `.S` for assembly source.

There may be a few others as well but those are the main ones. Things like text files aren't considered source files and thus aren't ever seen by the IDE.


body:
I have googled a lot, and mostly every website you can link me I have already explored, some are outdated and don't work, others aren't clear in their documentation, and use equipment too expensive to run the risk of buying it and it not working.

https://github.com/edinburghhacklab/dali

https://github.com/sde1000/python-dali

https://github.com/krzychb/DimSwitch/blob/master/extras/pictures/PHILIPS-HF-REGULATOR-TOUCH-a-DALI 18-58w-T8- 1-a-2-LAMPS.pdf

http://microcontrollershop.com/product_info.php?products_id=5384

Moreover, like any free protocol, you have to pay to access the DALI standard.

What can I do to control a network of connected DALI dimmable ballasts?

title: Can I connect to a DALI network as a master node using an Arduino?

Answers: 1

body:
I have made a simple DALI controller with Arduino Nano. Maybe it will be useful for you. Look here: [Simple DALI Controller][1]

  [1]: https://create.arduino.cc/projecthub/NabiyevTR/simple-dali-controller-506e44


body:
I have an ESP8266 module that must receive some data and send it to a server, my problem is that this data is given by a temperature sensore and a light sensor which must be connected to analog pins and my ESP has only 2 digital pins.

So I thought that I can measure the temperature and the light with an arduino (the sensors are the ones included in arduino starter pack) and then connect my esp digital pins to arduino digital pins and write a sketch to send digital data as output of arduino.

I think this is possible but I can't figure out how to do it because I can only set pins to high or low.

Can somebody help me? Thanks a lot

P.S: I already tried ther solutions like connecting tx and rx of esp to arduino but they didn't work so I prefer to use ESP8266 as standalone

title: Arduino as analog to digital converter for temperature sensor

Answers: 1

body:
Both the ESP8266 and the Arduino have UART serial interfaces. This is by far the simplest method of communicating between two boards.

Connect the TX of the Arduino, through a voltage divider to drop it to 3.3V, to the RX of the ESP8266. Connect the grounds together. That's all you need. Yes, you can connect the TX of the ESP8266 to the RX of the Arduino but if you are never going to send anything from the ESP8266 to the Arduino then there is little point.

Then, with both devices set to the same baud rate, you can `Serial.print` on the Arduino, and `Serial.read` on the ESP8266. Just follow one of the many many tutorials about communicating between Arduinos using UART.


body: I only currently have 2 arduinos and I find that any project I build I feel bad because I have to rip it apart to get the arduino because I want to build something else. Is there a way to get arduinos for cheap? (I'm new to arduino)

title: What can I do in this situation

Answers: 1

body:
Possibly not "genuine" Arduinos, but eBay has many sellers in China and Hong Kong who sell boards that are just like Arduinos, if you're willing to wait several weeks for delivery.

I was able, just now, to find an Arduino UNO compatible board for US$3.59, plus less than $2 shipping to the US. Note that they do not come with tech support, and none of the profit goes to support the official Arduino developers.


body:
I have several Arduino Uno's if I am using several NRF24L01 modules to transmit a simple pulse (1 bit of information which can be high or low) between them-from one Arduino to the rest of them. Then I was considering, because the information is one bit of information only can I replace the other receiving NRF24L01 module's with something cheaper (and probably simpler) ?-may something based on like a simple tank LC circuit?-or it maybe another simple circuit instead of the LC one. The intuition for asking the question is because only 1 bit of information (which maybe represented by a string of 1's or another known string X if it makes the decoding simpler)  is transmitted then the receiving circuit maybe simplified somehow -rather than use something like the full circuitry of a NRF24L01 module. Elaborating further on a possible scheme for decoding X may be done by just counting the "marks ratio"-as done "in a marks and spaces style scheme"-e.g. if there are known ratio of 1's, than compared to the usual ratio, then we can consider that to be a high signal received -the number of 1s sent is such that the binary information from the NRF24L01 protocol, that sends X, would not significantly affect the ratio of the 1s. however I don't know how accurate my intuition is here.

So in a nutshell, I want to know if there is a simple circuit that does what I want - an answer may include a custom Arduino sketch suggestion for the transmitter and/or receiver.

title: Lowering cost of using NRF24L01 radio module for communication between several Arduinos

Answers: 2

body:
To receive a signal from an nRF24L01 you either need another nRF24L01 or to reimplement the nRF24L01 in discrete components. That's a big, complex circuit requiring precision components and PCB layout. At 2.4GHz, with GFSK modulation, you need amazing skills to create something that would work reliably - and the cost would be astronomical compared to the cost of an nRF24L01.

Your thought that you are "only sending 1 bit of data" is completely wrong. Yes, you may be providing only 1 bit of data to the library that controls your nRF24L01 - however the nRF24L01 then encapsulates that single bit into a fixed length packet including source and destination addresses, checksums, and even implements a reliable ACK/NACK system for packet retransmission. None of that can be thought of as a "single bit" once it gets out onto the airwaves - so the system that you came up with would have to be able to interpret and handle that entire packet and provide any requested ACK/NACK signals back to the transmitter.

If you want to receive with a simpler system then you need to also transmit with a simpler system. The simplest system is probably the [433MHz PAM systems you find on eBay](http://www.ebay.co.uk/itm/252503539009). You pull the input pin HIGH on the transmitter and the output pin on the receiver goes HIGH. You pull the transmitter pin LOW and the receiver pin goes LOW. (Basically you turn the carrier on and off at one end, and the other end tells you if the carrier is on or off - Pulse Amplitude Modulation [also known as On Off Keying - OOK]).

Coupling that with UART signals it's possible to send actual data, but if all you need is HIGH/LOW signalling then you can drive it direct with any GPIO pin.

They are incredibly crude, and would never pass any kind of emissions testing, but they get the job done at a very low cost.

While it may be possible to create a crude 2.4GHz PAM transmitter and receiver, owing to the broadband spectrum harmonics you would have unless you managed to produce an absolutely pure sine-wave with zero harmonic distortion, the interference it would cause to other devices nearby (such as your WiFi connection) would cause untold problems. No doubt your neighbours would have something to say about that - and maybe FCC / OFCOM / whoever.

body:
> I have several Arduino Uno's if I am using several NRF24L01 modules to transmit a simple pulse (1 bit of information which can be high or low) between them-from one Arduino to the rest of them.

Let us assume that the broadcast has to reach all. None of the listeners are allowed to drop messages. How would this be achieved? Each listener would have to acknowledge the message.

Anyway reasoning about the application requirements and communication protocol may help determine if a "cheaper" solution is possible.

IMHO using NRF24L01+ is a cheap solution in this scenario.

Cheers!


body:
I can't set a COM port to my paired BT module. For better understanding [I recorded a YouTube video](http://youtu.be/vu9cK6emnIo) to make sure I show everything.

Hardware:

 - Arduino Nano knock-off by [RobotDyn](http://robotdyn.com) (atmega168)
 - Bluetooth module HC-05 (zs-040) which looks [like this](https://cdn.instructables.com/FLP/2YI3/HX6ARQKC/FLP2YI3HX6ARQKC.MEDIUM.jpg)
 - Windows 10 Home 64 bit on tablet

I have wired them up like this ![](https://i.stack.imgur.com/lwMAs.jpg).

However, before that, I tried to wire it up without the resistors (so I hope I didn't damage anything).

Here is my very simple code which should just echo back what it get.

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

    void loop() {
      if(Serial.available())
      {
        Serial.println(Serial.parseInt());
      }
      delay(100);
    }

title: Cannot assign COM port to HC-05 bluetooth device

Answers: 1

body:
Based on my experience, there is nothing wrong (yet) on the Arduino. You can check  [this][1] or [this][2]. Unlike previous windows version, Win 10 tend to "ignore" bluetooth connection, so you have to assign the COM port manually.

  [1]: http://www.technorms.com/46164/bluetooth-guide-windows-10
  [2]: https://www.verizonwireless.com/support/knowledge-base-20605/


body:
I am working on a project involving an Aduino and screen.

As i was going through the [u8glib (Arduino Monochrome Graphics Library for LCDs and OLEDs)][1], something caught my attention:

    #define U8G_ESC_DLY(x) 255, ((x) & 0x7f)
    #define U8G_ESC_CS(x) 255, (0xd0 | ((x)&0x0f))

How can i interpret this macro for a given x value ?

  [1]: https://github.com/olikraus/u8glib

title: Comma between two values in a macro

Answers: 1

body:
> How can i interpret this macro for a given x value ?

As normal. First expand the macro, and *then* worry about what the comma means in context. In an expression the result is the expression on the right of the comma. In a function call it stands in for two arguments. Just look at where it's used and that's what it will mean.


body:
I am controlling 2 motors from my Arduino Pro Mini and L293D motor driver module. Problem is, I have to set a pin high and after 1 second set it to LOW. But that doesn't happen... The pin just stays HIGH and is never LOW.

Here's my Code -

        int IN2Left = 10;
        int E1 = 12;
        int E2 = 7;
        int IN3RevRight = 6;
        int trigPin1 = A0;
        int echoPin1 = A1;
        int distance1 = 0;
        int IN4Right = 5;
        int IN1RevLeft = 11;

        void setup()
        {
          pinMode(IN2Left, OUTPUT);
          pinMode(E1, OUTPUT);
          pinMode(E2, OUTPUT);
          pinMode(IN3RevRight, OUTPUT);
          pinMode(IN4Right, OUTPUT);
          pinMode(IN1RevLeft, OUTPUT);
          pinMode(trigPin1, OUTPUT);
          pinMode(echoPin1, INPUT);
          pinMode(13, OUTPUT);
          Serial.begin(9600);
        }

        void loop() {
      digitalWrite(13, HIGH);
      digitalWrite(E1, HIGH);
      digitalWrite(E2, HIGH);
      digitalWrite(IN2Left, HIGH);
      digitalWrite(IN4Right, HIGH);
      delay(3000);
      digitalWrite(IN4Right, LOW);
      digitalWrite(IN3RevRight,HIGH);
      delay(500);
      digitalWrite(IN3RevRight, LOW);
      digitalWrite(IN4Right, HIGH);
      delay(1500);
      digitalWrite(IN2Left, LOW);
      digitalWrite(IN1RevLeft, HIGH);
      delay(500);
      digitalWrite(IN1RevLeft, LOW);
      digitalWrite(IN2Left, HIGH);
      delay(100000);
        }

The `IN2Left` Pin never goes LOW... I am assuming a faulty Arduino but my Arduino seems to be working just fine as it runs other stuff (tested blink and reading an Ultrasonic sensor) just fine.

My deadline is 2 hours from now...

EDIT: Here's the complete void loop function... Note the two pins on top which go HIGH? They Never go LOW again in the entire code.

title: Cannot set Pins to LOW

Answers: 2

body: Your code sets it high, delays for 1000ms, sets it low, and then... turns around and sets it high almost immediately after. Try delaying in between.

body:
      digitalWrite(IN2Left, HIGH);
      delay(1000);
      digitalWrite(IN2Left, LOW);

It would go LOW for a few microseconds. Maybe put a delay after going LOW?


body:
I am working on my graduation Project. I want to use the cayenne (mydevices) platform to control my Arduino. Mainly I want to be able to control a servo Motor through the Cayenne app and I want to use a gyro sensor that would also control the servo using the app after obtaining the readings from the sensor. The Options are:
1- Yun arduino
2- Arduino Ethernet
3- Arduino uno (which I currently have) + Arduino Ethernet shield or arduino wifi shield

Cayenne (mydevices) APP supports all of the above Options

What is the easiest to implement? I have short time period and working on the mechanical design for the Project in the same time.

Your help is appreciated

title: The easiest and most time efficent way to connect to the internet regardless of the cost

Answers: 2

body:
The Arduino Uno and Arduino Ethernet are very simple to program, to connect it to the Internet.

I never used the Yun Arduino, but it seems a little bit harder.

body:
If you want to stick with Arduino (instead of SBC), I suggest you use Arduino Yun.

 The Linux side of the Yun will provide very much greater scope for web programming compared to Arduino+Ethernet shield. There also a bridge library to communicate with the Yun.


body:
In my project I need three arrays to store data inside.

I define a maximal number of elements as a macro variable. However, at a certain point in the setup function, the program could determine, that the arrays would actually store a smaller number of elements. In other words, it is possible (and even likely) that there is more memory reserved for the arrays than actually necessary.

As I think that memory might be a critical factor on a micro controller like the Arduino, I would like to set the excess memory free.

Is there a way to dynamically resize **and shrink** the arrays at runtime?

Something like this (pseudocode)

    #define maxSize 50
    int theArray[maxSize];

    int actualSize = getActualArraySize();
    // sets actualSize to a value <= 50, let's assume actualSize = 20
    shrinkArray(theArray, actualSize);
    // shrinkArray doesn't exist :) I need something like that.

title: Shrink array to save memory

Answers: 1

body:
This is a common question when designing software. The simple answer (rule of thumb) is **statically allocate the maximum size of the array**. In this case the maximum size of the arrays. This simple rule will keep you out of trouble and make testing etc much simpler.

Using dynamic allocation (adjusting array size etc) especially for small scale embedded systems such as the Arduino opens a "can of worms" with possible memory (heap) fragmentation and hidden concurrency and performance issues.

If the required maximum size of the array is 32 elements the application has to allow that and there is no memory to save. Statically allocating will make the sketch simpler and easier to test.

Cheers!


body:
Today I received normally closed solenoid valve which I am going to use in automated pot watering system ,
I realised the valve takes 24 dc volt as input and Arduino has maximum of 5volt , using some power booster I can convert it to some extent but I think 24 volt is too much .

So how should power 24volt solenoid valve from Arduino uno?![enter image description here](https://i.stack.imgur.com/CRrtO.jpg)

title: Powering 24 volt solenoid valve with Arduino uno

Answers: 3

body:
[![enter image description here][1]][1]Since the solenoid requires higher current than the arduino can provide you can use an alternative power source for the solenoid (maybe a couple of batteries) and switch it with a TIP120 transistor.

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

body:
You have 2 choices:

1 - Preferably, use a N-channel MOSFET. Best for usage of voltage between 9 and 60, these are great little modules that can control voltage flow.

2 - Use a relay. A little more expensive, but can handle main's voltage.

body:
24V AC or DC?  Relay would be good for either.

Low Rds N-channel logic level MOSFET (IRFL540) would be good for sinking DC current.


body:
I have an NPN transistor that's connected over a 12V adapter. I have tried using a potentiometer to change the resistance of the incomming current. Even if i take the resistance down to 0, I end up with at most 11 Volts when measuring over the magnet.

I have measure the energy without the transistor, in that case it's 12V. Is this expected behaviour of a transistor or is something wrong?

title: Will a transistor always reduce the voltage?

Answers: 1

body: Yes, it is, as both VCE(sat) and the "Collector-Emitter Saturation Voltage vs Collector Current" chart in the datasheet tells you.


body: I'm putting an MPU6050 on an arduino Micro but the interrupt is different than the arduino uno. The external interrupt #0 pin on an arduino uno is pin 2 but its not pin 2 on an arduino micro. So I'm trying to figure out what pin it is on an arduino micro

title: What pin is the external interrupt #0 for an arduino micro?

Answers: 1

body: The ATmega32U4 pin mapping says 3.


body:
Trying to setup a server on Arduino to support multiple clients,
I am able to support one but I don't want to flush that client to make another connection.

    #include <ESP8266WiFi.h>
    const char* ssid = "your-ssid";
    const char* password = "your-password";
    // Create an instance of the server
    // specify the port to listen on as an argument
    WiFiServer server(80);

    void setup() {
      Serial.begin(115200);
      delay(10);

      // prepare GPIO2
      pinMode(2, OUTPUT);
      digitalWrite(2, 0);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.println(WiFi.localIP());
    }

    void loop() {
      // Check if a client has connected
      WiFiClient client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      while(!client.available()){
        delay(1);
      }

      // Read the first line of the request
      String req = client.readStringUntil('\r');
      Serial.println(req);
      client.flush();

      // Match the request
      int val;
      if (req.indexOf("/gpio/0") != -1)
        val = 0;
      else if (req.indexOf("/gpio/1") != -1)
        val = 1;
      else {
        Serial.println("invalid request");
        client.stop();
        return;
      }

      // Set GPIO2 according to the request
      digitalWrite(2, val);

      client.flush();

      // Prepare the response
      String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\nGPIO is now ";
      s += (val)?"high":"low";
      s += "</html>\n";

      // Send the response to the client
      client.print(s);
      delay(1);
      Serial.println("Client disonnected");

      // The client will actually be disconnected
      // when the function returns and 'client' object is detroyed
    }

Using this code, the server handles only one client at a time, but I need to connect multiple clents simultaneously.

title: Multiple client server over wifi

Answers: 3

body:
You need to keep track of multiple `WiFiClient`s - declare an array of them, for example, and each time `server.available()` gives you a new one, store it in the array.

Then you need to make sure your code doesn't stick waiting for data from each item.  You could service each WifiClient in turn: if it has data waiting (`client[i].available()` is true), read the data (`client[i].read()`) and store it. When you get a `\r` from a client, you know you have a whole line, and you can process it.

Here's a nearly-complete (but untested) example so you can see what I'm talking about.  Naturally it's not the only way to do it.

    #include <ESP8266WiFi.h>
    const char* ssid = "your-ssid";
    const char* password = "your-password";
    #define MAX_CLIENTS 10
    #define MAX_LINE_LENGTH 50
    // Create an instance of the server
    // specify the port to listen on as an argument
    WiFiServer server(80);
    WiFiClient *clients[MAX_CLIENTS] = { NULL };
    char inputs[MAX_CLIENTS][MAX_LINE_LENGTH] = { 0 };

    void setup() {
      Serial.begin(115200);
      delay(10);

      // prepare GPIO2
      pinMode(2, OUTPUT);
      digitalWrite(2, 0);

      // Connect to WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");

      // Start the server
      server.begin();
      Serial.println("Server started");

      // Print the IP address
      Serial.println(WiFi.localIP());
    }

    void loop() {
      // Check if a new client has connected
      WiFiClient newClient = server.available();
      if (client) {
        Serial.println("new client");
        // Find the first unused space
        for (int i=0 ; i<MAX_CLIENTS ; ++i) {
            if (NULL == clients[i]) {
                clients[i] = new WiFiClient(newClient);
                break;
            }
         }
      }

      // Check whether each client has some data
      for (int i=0 ; i<MAX_CLIENTS ; ++i) {
        // If the client is in use, and has some data...
        if (NULL != clients[i] && clients[i]->available() ) {
          // Read the data
          char newChar = clients[i]->read();

          // If we have the end of a string
          // (Using the test your code uses)
          if ('\r' == newChar) {
            // Blah blah, do whatever you want with inputs[i]

            // Empty the string for next time
            inputs[i][0] = NULL;

            // The flush that you had in your code - I'm not sure
            // why you want this, but here it is
            clients[i]->flush();

            // If you want to disconnect the client here, then do this:
            clients[i]->stop();
            delete clients[i];
            clients[i] = NULL;

          } else {
            // Add it to the string
            strcat(inputs[i], newChar);
            // IMPORTANT: Nothing stops this from overrunning the string and
            //            trashing your memory. You SHOULD guard against this.
            //            But I'm not going to do all your work for you :-)
          }
        }
      }

    }

body:
Here , I have  used array of WiFiClient .
The reason is  array pointer will hold previous plus latest WiFiClients (emoteIP and remotePort ) and user will be able to choose which WIFiClient to be used for communication.

We can store  IPAddress , Port as well as whole WiFiClient object in an array

     //===========================================
           WebServer  Wserver(80);

           WiFiClient Wclient;

           WiFiClient *Wificlients[10] = { NULL };

           int  Clientindex=-1;

           Wclient = Wserver.client(); // or  server.avilable() if WiFiServer

           Wificlients[Clientindex++]=new WiFiClient(Wclient);

           int   cntloggedinclient=0;
           int kk=0;

           while(Wificlients[kk] != NULL)
               {
                   cntloggedinclient++;  // Total clients count
                   kk++;
               }

             // Multicasting bytes to all connected clients.
             int kkk =0;
             while(kkk<cntloggedinclient)
             {
               Wificlients[kkk]->write((unsigned char*) &newbuff,len);
               kkk++;
             }

body:
I have a solution using RTOS Tasks, I think this is the best way to manage multiple clients at same time. I test this code in ESP32 dev module.
```
#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE 0
#else
#define ARDUINO_RUNNING_CORE 1
#endif
#include <WiFi.h>

const char* ssid = "[YOUR-NETWORK-SSID]";
const char* password = "[YOUR-SSID-PASSWORD]";

void TaskClientSocket( void *pvParameters );

WiFiServer wifiServer(80);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(1000);
  WiFi.begin(ssid,password);
  Serial.println("Connecting to Wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("Connected to WiFi network");
  Serial.println(WiFi.localIP());

  wifiServer.begin();
}

void loop() {
  WiFiClient client = wifiServer.available();
  if( client){
    Serial.println("New Client Connected...");
    xTaskCreatePinnedToCore(
    TaskClientSocket
    ,  "TaskClientSocket"
    ,  4098
    ,  &client
    ,  2
    ,  NULL
    ,  ARDUINO_RUNNING_CORE);
  }
}

void TaskClientSocket( void *pvParameters )
{
    WiFiClient clientHandle = *((WiFiClient*)pvParameters);
    for (;;)
    {
      while(clientHandle.connected()){
        while(clientHandle.available()>0){
          char c = clientHandle.read();
          clientHandle.write(c);
        }
        vTaskDelay(100);
      }
      clientHandle.stop();
      Serial.println("Client disconnected");
      vTaskDelete(NULL);
    }
}
```


body: I have a simple GET webform that takes in text. Once that text is submitted the URL permanently displays the text as the parameter. This causes echoing issues when I check the input from the web form; the string I am looking for is always found because the URL is never cleared. I cannot use an HTTP redirect and am looking for a way to do this based upon code.

title: Clear GET params from URL

Answers: 1

body: this is exaclty waht get are supposed to do. Use a POST or use a redirect; a POST is way better as the "back" button of the browser will take care of it


body:
I have a GPS code that I need to run only once, but every different try gives me errors, including placing the whole code in `void setup()`. Is there any way that this code can be run just once? As of now, the code repeats itself, putting out data over and over again - I need just one set, right when the code is activated.

Here is the code:

    #include <Adafruit_GPS.h>
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(3, 2);
    Adafruit_GPS GPS(&mySerial);
    #define GPSECHO  true
    boolean usingInterrupt = false;
    void useInterrupt(boolean);

    void setup() {
      Serial.begin(115200);
      Serial.println("Adafruit GPS library basic test!");
      GPS.begin(9600);
      GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
      GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);
      GPS.sendCommand(PGCMD_ANTENNA);
      useInterrupt(true);
      delay(1000);
      mySerial.println(PMTK_Q_RELEASE);
    }

    SIGNAL(TIMER0_COMPA_vect) {
      char c = GPS.read();
    #ifdef UDR0
      if (GPSECHO)
        if (c) UDR0 = c;
    #endif
    }

    void useInterrupt(boolean v) {
      if (v) {
        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
      } else {
        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
      }
    }

    uint32_t timer = millis();
    void loop() {                  // run over and over again
      if (! usingInterrupt) {
        char c = GPS.read();
        if (GPSECHO)
          if (c) Serial.print(c);
      }
      if (GPS.newNMEAreceived()) {
        if (!GPS.parse(GPS.lastNMEA()))
          return;

      if (timer > millis())
        timer = millis();

      if (millis() - timer > 2000) {
        timer = millis(); // reset the timer
        Serial.print("\nTime: ");
        Serial.print(GPS.hour, DEC); Serial.print(':');
        Serial.print(GPS.minute, DEC); Serial.print(':');
        Serial.print(GPS.seconds, DEC); Serial.print('.');
        Serial.println(GPS.milliseconds);
        Serial.print("Date: ");
        Serial.print(GPS.day, DEC); Serial.print('/');
        Serial.print(GPS.month, DEC); Serial.print("/20");
        Serial.println(GPS.year, DEC);
        Serial.print("Fix: "); Serial.print((int)GPS.fix);
        Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
        if (GPS.fix) {
          Serial.print("Location: ");
          Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
          Serial.print(", ");
          Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
          Serial.print("Location (in degrees, works with Google Maps): ");
          Serial.print(GPS.latitudeDegrees, 4);
          Serial.print(", ");
          Serial.println(GPS.longitudeDegrees, 4);
          Serial.print("Speed (knots): "); Serial.println(GPS.speed);
          Serial.print("Angle: "); Serial.println(GPS.angle);
          Serial.print("Altitude: "); Serial.println(GPS.altitude);
          Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
        }
      }
      }
    }

I've been trying to get this for a while, and I'm new to programming!

title: Making a current GPS code run once, and only once, after the code is 'activated'

Answers: 2

body:
Put everything from your `void loop()` into your `void setup`. Put them AFTER the original setup and you should be good to go.

**DO NOT DELETE THE VOID LOOP!! ONLY KEEP IT EMPTY!!**

Here, try this:

    #include <Adafruit_GPS.h>
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(3, 2);

    Adafruit_GPS GPS(&mySerial);

    #define GPSECHO  true

    boolean usingInterrupt = false;
    void useInterrupt(boolean);

    void setup()
    {

      Serial.begin(115200);
      Serial.println("Adafruit GPS library basic test!");

      GPS.begin(9600);

      GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);

      GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);

      GPS.sendCommand(PGCMD_ANTENNA);

      useInterrupt(true);

      delay(1000);

      mySerial.println(PMTK_Q_RELEASE);

      if (! usingInterrupt) {

        char c = GPS.read();

        if (GPSECHO)
          if (c) Serial.print(c);
      }

      if (GPS.newNMEAreceived()) {

        if (!GPS.parse(GPS.lastNMEA()))
          return;

        if (timer > millis())  timer = millis();

        if (millis() - timer > 2000) {
          timer = millis(); // reset the timer

          Serial.print("\nTime: ");
          Serial.print(GPS.hour, DEC); Serial.print(':');
          Serial.print(GPS.minute, DEC); Serial.print(':');
          Serial.print(GPS.seconds, DEC); Serial.print('.');
          Serial.println(GPS.milliseconds);
          Serial.print("Date: ");
          Serial.print(GPS.day, DEC); Serial.print('/');
          Serial.print(GPS.month, DEC); Serial.print("/20");
          Serial.println(GPS.year, DEC);
          Serial.print("Fix: "); Serial.print((int)GPS.fix);
          Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
          if (GPS.fix) {
            Serial.print("Location: ");
            Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
            Serial.print(", ");
            Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
            Serial.print("Location (in degrees, works with Google Maps): ");
            Serial.print(GPS.latitudeDegrees, 4);
            Serial.print(", ");
            Serial.println(GPS.longitudeDegrees, 4);

            Serial.print("Speed (knots): "); Serial.println(GPS.speed);
            Serial.print("Angle: "); Serial.println(GPS.angle);
            Serial.print("Altitude: "); Serial.println(GPS.altitude);
            Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
          }
        }
      }
    }

    SIGNAL(TIMER0_COMPA_vect) {
      char c = GPS.read();

    #ifdef UDR0
      if (GPSECHO)
        if (c) UDR0 = c;

    #endif
    }

    void useInterrupt(boolean v) {
      if (v) {

        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
      } else {

        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
      }
    }

    uint32_t timer = millis();

    void loop()                     // run over and over again
    {
    }

body:
Here's your sketch, modified to use my library, [NeoGPS](https://github.com/SlashDevin/NeoGPS).  It is smaller, faster, more reliable and more accurate than all other libraries.

I added a `waitForFix` routine that, well, waits for the GPS to get a fix.  Then it calls `printFix`, just once:

    #include <NMEAGPS.h>
    #include <NeoSWSerial.h>

    NeoSWSerial gpsSerial(3, 2);
    NMEAGPS     GPS;
    gps_fix     fix;

    void setup()
    {
      Serial.begin(115200);
      Serial.println( F("Run once!") ); // F macro saves RAM!

      gpsSerial.begin(9600);
      gpsSerial.println( F("$PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*28") ); // RMC & GGA only
      gpsSerial.println( F("$PMTK220,1000*1F") ); // 1Hz update rate

      waitForFix();
      printFix();
    }

    void loop()
    {
    }

    void waitForFix()
    {
      uint8_t fixes = 0;

      do {
        if (GPS.available( gpsSerial )) {
          fix = GPS.read();
          fixes++;
        }
      } while ((fixes < 2) && !fix.valid.location);

    } // waitForFix

    void printFix()
    {
      Serial.print( F("Time: ") );
      if (fix.valid.time) {
        if (fix.dateTime.hours < 10)
          Serial.print( '0' );
        Serial.print(fix.dateTime.hours);
        Serial.print(':');
        if (fix.dateTime.hours < 10)
          Serial.print( '0' );
        Serial.print(fix.dateTime.minutes);
        Serial.print(':');
        if (fix.dateTime.hours < 10)
          Serial.print( '0' );
        Serial.print(fix.dateTime.seconds);
        Serial.print('.');
        if (fix.dateTime_cs < 10)
          Serial.print( '0' );
        Serial.print(fix.dateTime_cs);
      }
      Serial.println();

      Serial.print( F("Date: ") );
      if (fix.valid.date) {
        Serial.print(fix.dateTime.day);
        Serial.print('/');
        Serial.print(fix.dateTime.month);
        Serial.print('/');
        Serial.print( fix.dateTime.full_year() );
      }
      Serial.println();

      Serial.print( F("Fix status: ") );
      if (fix.valid.status)
        Serial.print( (int) fix.status );
      Serial.println();

      if (fix.valid.location) {
        Serial.print( F("Location: ") );
        Serial.print( fix.latitude(), 4 );
        Serial.print( F(", ") );
        Serial.println(fix.longitude(), 4);
      }

      if (fix.valid.speed) {
        Serial.print("Speed (knots): ");
        Serial.println( fix.speed() );
      }

      if (fix.valid.heading) {
        Serial.print( F("Angle: ") );
        Serial.println( fix.heading() );
      }

      if (fix.valid.altitude) {
        Serial.print( F("Altitude: ") );
        Serial.println( fix.altitude() );
      }

      if (fix.valid.satellites) {
        Serial.print( F("Satellites: ") );
        Serial.println( fix.satellites );
      }
    }

The NeoGPS library waits for a complete batch of sentences, because the speed is in one sentence (RMC) and the altitude is in another sentence (see [this table](https://github.com/SlashDevin/NeoGPS/blob/master/extras/doc/Choosing.md)).  NeoGPS provides complete "fixes", as assembled from all the sentences your GPS device sends.  The fixes are available once per second, or whatever you have configured your device to provide.

You may also notice that I used another library I maintain, [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial).  `SoftwareSerial` is *very* inefficient because it disables interrupts for long periods of time.  This can interfere with other parts of your sketch or other libraries.

If you can put the GPS on pins 8 & 9, AltSoftSerial would be even better.  It only works on those two pins.

Your original sketch uses 12124 bytes of program space and 1031 bytes of RAM.

The NeoGPS version uses 10680 bytes of program space and 446 bytes of RAM.  A significant savings!