message:
String class summation disappears the right operand

I intend to create a function to jsify sensors' content and save it on a SD-card or send through a http client. Except for the `Serial.println`'s, the function is transcripted below.

    String jsonificar(vector<vector<String>> sujeito){
      String json_txt = String(""), chave, valor;
      String chave_str, valor_str;

      json_txt+=String("{");
      for(unsigned int i = 0; i<sujeito.size(); i++){
        if(sujeito[i].size() != 2){
            Serial.println("Cada conteudo deve conter 2 textos!");
        }
        else{
            chave = sujeito[i][0];
            valor = sujeito[i][1];
            Serial.println(chave);
            Serial.println(valor);
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += chave;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += ":";
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += valor;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);

            if(i != sujeito.size() - 1){
              json_txt += String(",");
            }
        }
      }

      json_txt+="}";
      Serial.println(json_txt);

      return json_txt;
    }

The output on serial follows:

    Output:

    Chave1
    Valor1
    {
    {\"
    {\"Chave1
    {\"Chave1\"
    {\"Chave1\":
    {\"Chave1\":\"
    {\"Chave1\":\"Valor1
    {\"Chave1\":\"Valor1\"
    Chave2
    Valor2
    {\"Chave1\":\"Valor1\",
    {\"Chave1\":\"Valor1\",\"
    {\"Chave1\":\"Valor1\",\"    <===
    {\"Chave1\":\"Valor1\",\"\"
    {\"Chave1\":\"Valor1\",\"\": <===
    {\"Chave1\":\"Valor1\",\"\": <===
    {\"Chave1\":\"Valor1\",\"\": <===
    {\"Chave1\":\"Valor1\",\"\": <===
    {\"Chave1\":\"Valor1\",\"\":}

The arrows show the spots where the logs are different from expected: the keys and values provided are "Chave1", "Valor1", "Chave2", "Valor2". So, the key-value should be "Chave2":"Valor2". Would you have a grasp of this behaviour? I look forward for the answer!

body:
Your "disappearing string" has the following cause: Out-of-Memory.

You are constructing lots of `String` objects in your code and are concatinating to one. That uses memory on the heap for each `String` (and `realloc()` when the String memory must be expanded).

Consider the following test sketch which includes your code but also adds a memory leak by 150 bytes in each iteration:

<!--language:lang-cpp-->

    #include <Arduino.h>
    #include <ArduinoSTL.h>
    using namespace std;

    extern unsigned int __heap_start;
    extern void *__brkval;

    /*
     * The free list structure as maintained by the
     * avr-libc memory allocation routines.
     */
    struct __freelist {
     size_t sz;
     struct __freelist *nx;
    };

    /* The head of the free list structure */
    extern struct __freelist *__flp;

    /* Calculates the size of the free list */
    int freeListSize() {
     struct __freelist* current;
     int total = 0;
     for (current = __flp; current; current = current->nx) {
      total += 2; /* Add two bytes for the memory block's header  */
      total += (int) current->sz;
     }
     return total;
    }

    int freeMemory() {
     int free_memory;
     if ((int) __brkval == 0) {
      free_memory = ((int) &free_memory) - ((int) &__heap_start);
     } else {
      free_memory = ((int) &free_memory) - ((int) __brkval);
      free_memory += freeListSize();
     }
     return free_memory;
    }

    String jsonificar(vector<vector<String>> sujeito) {
     String json_txt = String(""), chave, valor;
     String chave_str, valor_str;

     json_txt += String("{");
     for (unsigned int i = 0; i < sujeito.size(); i++) {
      if (sujeito[i].size() != 2) {
       Serial.println("Cada conteudo deve conter 2 textos!");
      } else {
       chave = sujeito[i][0];
       valor = sujeito[i][1];
       Serial.println(chave);
       Serial.println(valor);
       Serial.println(json_txt);
       json_txt += "\\\"";
       Serial.println(json_txt);
       json_txt += chave;
       Serial.println(json_txt);
       json_txt += "\\\"";
       Serial.println(json_txt);
       json_txt += ":";
       Serial.println(json_txt);
       json_txt += "\\\"";
       Serial.println(json_txt);
       json_txt += valor;
       Serial.println(json_txt);
       json_txt += "\\\"";
       Serial.println(json_txt);

       if (i != sujeito.size() - 1) {
        json_txt += String(",");
       }
      }
     }

     json_txt += "}";
     Serial.println(json_txt);

     return json_txt;
    }

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

    String myStr = "";

    void loop(void) {

     Serial.print(F("Free Memory:"));
     Serial.println(freeMemory());

     //force a memory leak by allocating appending to a global String
     myStr +=
       "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
       "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

     vector<vector<String>> v =
       { { "Chave1", "Valor1" }, { "Chave2", "Valor2" }, };

     jsonificar(v);
     delay(1000);
    }

From the output we can see the exact point where we have enough memory and the result is correct, and where we don't have enough memory and the string just "disappears" because there was not enough memory to allocate it:

    Free Memory:911
    Chave1
    Valor1
    {
    {\"
    {\"Chave1
    {\"Chave1\"
    {\"Chave1\":
    {\"Chave1\":\"
    {\"Chave1\":\"Valor1
    {\"Chave1\":\"Valor1\"
    Chave2
    Valor2
    {\"Chave1\":\"Valor1\",
    {\"Chave1\":\"Valor1\",\"
    {\"Chave1\":\"Valor1\",\"Chave2
    {\"Chave1\":\"Valor1\",\"Chave2\"
    {\"Chave1\":\"Valor1\",\"Chave2\":
    {\"Chave1\":\"Valor1\",\"Chave2\":\"
    {\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2
    {\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"
    {\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"}
    Free Memory:761
    Chave1
    Valor1
    {
    {\"
    {\"Chave1
    {\"Chave1\"
    {\"Chave1\":
    {\"Chave1\":\"
    {\"Chave1\":\"Valor1
    {\"Chave1\":\"Valor1\"
    Chave2
    Valor2
    {\"Chave1\":\"Valor1\",
    {\"Chave1\":\"Valor1\",\"
    {\"Chave1\":\"Valor1\",\"Chave2
    {\"Chave1\":\"Valor1\",\"Chave2\"
    {\"Chave1\":\"Valor1\",\"Chave2\":
    {\"Chave1\":\"Valor1\",\"Chave2\":\"
    {\"Chave1\":\"Valor1\",\"Chave2\":\"
    {\"Chave1\":\"Valor1\",\"Chave2\":\"
    {\"Chave1\":\"Valor1\",\"Chave2\":\"


sender: user

message:
ESP8266 communication issue

I have an issue communicating with ESP8266 via Arduino Uno's serial ports.

I can connect to it using
`python -m serial.tools.miniterm /dev/ttyUSB0 115200`
command but when trying to send an `AT` command, it looks like this:

    �tC�

    ERROR
    �v[�
    ERROR
    at

    OK

So, sometimes I'm able to properly send a command, but usually what I type turns to gibberish. I've tried other baud values, but only `115200` works.

I'm powering Arduino via USB from my laptop. I've seen some mentions that this behavior may be caused by low voltage but unfortunately, I'm currently unable to verify it whether that's a case here.

My schematic looks like this:
[![Schematic][1]][1]

I'm new to this, so if there is any crucial information I've missed, then please let me know and I'll do my best to provide it.

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

sender: assistant

body:
The issue, as Maximilian Gergardt suggested in comments, was with Arduino's TX/RX sending 5V signal. Adding voltage dividers on RX line solved the issue. Refer to diagram below for details:
[![enter image description here][1]][1]

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


message:
How can I upload .hex files to a Pro Micro using Linux?

I have a hand-wired keyboard that uses a Pro Micro board, with an ATmega32u4 chip. I can't seem to flash firmware on it. The commands I've been trying are variations of:

    avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

The errors I've been getting begin:

    Writing | #######avrdude: error: programmer did not respond to command: set addr
    ####avrdude: error: programmer did not respond to command: set addr
    avrdude: error: programmer did not respond to command: write block
     ***failed;
     ***failed;
     ***failed;
     ***failed;

And end:

    #avrdude: error: programmer did not respond to command: set addr
    avrdude: error: programmer did not respond to command: set addr
    avrdude: error: programmer did not respond to command: set addr
    #avrdude: error: programmer did not respond to command: set addr
    avrdude: error: programmer did not respond to command: set addr
    avrdude: error: programmer did not respond to command: set addr
    # | 100% 0.16s

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x0000
             0x0d != 0x0c
    avrdude: verification error; content mismatch
    avrdude: error: programmer did not respond to command: leave prog mode
    avrdude: error: programmer did not respond to command: exit bootloader

I'm on Arch Linux. Any ideas?

body:
There's two stages to uploading a hex file to a USB-based Arduino - and you're only doing the second stage.

The first stage is to reset the board into the bootloader so it can accept the instructions from the second stage.  The IDE normally does that manually for you when you hit the UPLOAD button.

The way these boards are reset is to first open the CDC/ACM port and set the baud rate to 1200, then close the port again. That triggers the code to reset the board into the bootloader.

You can probably do it using the `stty` tool in Linux:

    $ stty -F /dev/ttyACM0 speed 1200
    $ stty -F /dev/ttyACM0 speed 115200
    $ avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

The second `stty` may not actually be needed, but it's good to reset the baud rate to a normal value ready for uploading. I don't have a board to hand right now to test it though.


body:
I had the same issue, and it was caused by udev, I found the answer [here][1]

[It's some obscure bug][2]

Tweaking udev rules solved the problem for me, now all is good, here is the procedure: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

  [1]: https://learn.adafruit.com/adafruit-feather-32u4-adalogger/using-with-arduino-ide
  [2]: https://bugs.launchpad.net/ubuntu/+source/modemmanager/+bug/1473246


message:
Arduino OTA port not updating in Arduino IDE

The OTA (from the [ArduinoOTA][2] library) on my ESP8266 does not show up in the programming ports on the Arduino IDE unless I restart the IDE.   Even when I plug in a usb cable and the ports list updates to show that device, it does not show the network port without a restart.   Does anyone know why this would happen or how to solve it?

I downloaded the newest version of the IDE and this is still the case.

  [1]: https://github.com/PaulStoffregen/Encoder
  [2]: https://github.com/esp8266/Arduino/tree/master/libraries/ArduinoOTA

body:
For some reason you have to close and reopen the Arduino IDE for it to discover all available OTA ports.   Not sure why this is -- if anyone knows I would be glad to learn.

EDIT: keeping this answer just for comments -- it's not a real answer.


body:
I found an workaround for Windows:

 - disable IPv6 from Network Configuration
 - disable/enable network interface
 - restart Arduino IDE

You should see your OTA device in port list, in Arduino IDE.


body: I have the exact problem on various flavours of Linux with last Arduino IDE and rebooting the router seems to be the only thing I've found that can make the IP address port appear.


message:
How to make my servo slow down in it´s movement

I want to make my servo react on the data that my light sensor tells him by the amount of light that it is catching. I want the servo to go fast to the left when there is shadow/darkness and then I want it to go slowly back to the right when the light is back.

This is the code I´m now using for my 180 degrees servo.
I also want this to work on my 360 degrees servo but because I am a beginner, I can´t figure it out...

    #include <Servo.h>

    Servo s;

    void setup() {
      // put your setup code here, to run once:
      //pinMode(9,OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);
      s.attach(9);
    }

    void loop() {
       float l = analogRead(A0);
       Serial.print(l);
       Serial.print(" ");
       int v = map(l,0,1024,0,179);
       s.write(v);
       Serial.println(v);

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

  [1]: https://i.stack.imgur.com/jnQlm.jpg
  [2]: https://i.stack.imgur.com/CXWAM.jpg

body:
The servo's rotation speed is controlled by its internal circuitry. Once you send it a new target position, it drives at it's maximum speed toward that position and decelerates as it approaches.

The best you can do to slow it down is to change its target stepwise, until you reach the target position, instead of setting the final target all at once. If you move it in several large steps, the motion will be jerky; if you send smaller steps at shorter intervals (so the total travel time will be same), the motion will get smoother.

If your application needs the smoothest motion possible, send it many tiny steps rapidly, again, observing your required total travel time. You should be able keep the servo constantly at (or closer to) it's approach speed.


message:
How to avoid calling multiple times Wire.begin() in libraries?

it's all in the title ; I'm developping a library and use *TwoWire pointers in this library ; but I am using an external library that calls Wire.begin(). I've seen something about TWCR register in arduino but I don't know what it is exaclty.

Thanks in advance :)

body:
What you are interested in is this bit of the Wire library:

    TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

The important bit is the `TWEN` bit - TwoWire ENable.

If that bit is set in the TWCR register than Wire.begin() has been called already and you don't need to call it again:

    if (TWCR & _BV(TWEN) == 0) {
        Wire.begin();
    }

However, it really doesn't matter if you call it multiple times.


message:
Library to send large amount of data over 433 MHz

I am trying to communicate between two Arduinos using two RF 433 MHz modules (transmitter receiver). I found that the library `Wildewire.h` allows a maximum of 77 bytes so is there any another library that allows to send a more than that?

body:
Radio modules send packets of data (and for very good reasons) so, if the total size of the data you want to send is greater than the packet limit, you have to engineer a higher level system (called a protocol) that can split your bigger message up into chunks that can be handled by the .h file.

I'm not saying one isn't available and indeed you may find one but, if you don't find one, you are facing the design of a protocol to handle bigger messages. It's not too difficult - imagine splitting the data you wish to send into 64 byte chunks and appending a single byte at the start of the data that describes the packet payload: -

 - As being a full message
 - As being a start of message (message overruns 64 bytes)
 - As being a mid message
 - As being an end of message (i.e. the last few bytes of data in the message)

This is enough information for your receiver code to reconstruct the original message but make sure you do good error checking if there isn't sufficient in the .h code. And also make sure your receiver "acknowledges" each packet received as being error free.

You might also wish to embed an address that makes your transmission and reception more robust or even add a packet count to the mid message marker byte. You have a maximum of 77 bytes for the payload so you have a few bytes spare for improving integrity but, the minimum payload system is 1 byte header and 76 bytes of payload (which may include other checks like CRC).


message:
Why does Arduino Tone example with 8 ohm speaker make USB port fail?

I'm using an Arduino Nano and attempting to run the basic sample program at:
[https://www.arduino.cc/en/Tutorial/toneMelody][1]

When I build the circuit they way they show (extremely simple) using an 8 Ohm speaker and connect the power to USB the Nano begins to power (never fully powers up) and then the USB port fails (I believe as a protection mechanism).

[![sample fritzing circuit][2]][2]

Is the schematic provided with that sample incorrect?
They say it can be used with an 8 Ohm speaker but they show it hooked up with e piezo.
Here are the comments from the Sketch:

[![sketch comments][3]][3]

Is it possibly overdrawing current with the 8 Ohm speaker?
Is the circuit incorrect in some way?
**NOTE:** Without the speaker connected the Nano powers up with no problem. I am also building other circuits with the Nano and they work fine.

  [1]: https://www.arduino.cc/en/Tutorial/toneMelody
  [2]: https://i.stack.imgur.com/6uxpn.png
  [3]: https://i.stack.imgur.com/ZgjQX.png

body: The USB +5v opens to protect your computers from the connected device trying to draw too much current. The pin driver may have burned out, or it may, in fact, have delivered an excessive current (even if not the full 625 mA) but have been saved from failure by the USB supply having opened soon enough.


body:
As already mentioned in your question, in the Arduino tutorial "Melody" under "Hardware Required" is stated "piezo buzzer or a speaker" and in the comment that heads the sketch is stated: "8 ohm speaker on digital pin 8". But the pictures under "Circuit" and "Schematic" show a piezo sound transducer.

In any case the word "buzzer" is wrong. A buzzer usually has a built-in oscillating circuit or mechanism and, when energized, produces sound at a more or less fixed frequency. Better would have been: a piezo speaker and a 'normal' (moving coil) speaker.

There is a big difference between a piezo and a speaker: under a dc-voltage the piezeo wil have a near infinitive resistance and the 8 Ohm speaker roughly 4 Ohms. At 400 Hz the piezo has an impedance of roughly 2000 Ohm (there is a huge range of piezo's with varying characteristics), while the impedance of the normal speaker will be roughly 10 Ohm.

One side of the buzzer/speaker is connected to Ground, therefore current is only flowing when the side connected to pin 8 is HIGH (pin 8, has to source the current and not to sink it).

The datasheet of the Atmega328P states at page 299 that the absolute maximum ratings (which is not the same as maximum allowable operational ratings) are 40 mA for an I/O-pin is 40.0 mA and 200 mA for Vcc and Ground pins.<br />
The datasheet shows a graph (fig. 35-24 at page 600) showing "I/O Pin Output Voltage vs. Source Current (VCC = 5 V)". From this graph an internal resistance of about 26 Ohm can be derived. The graph does'n show what happens at pin-currents larger than 20 mA, but let's guess the internal resistance stays about the same 26 Ohm.

When pin 8 is constantly HIGH (5 V at 0 Hz) the current through the speaker would be about 5/(26+4) = 167 mA. This is far above the 40 mA maximum rating for the pin current, but not enough to trip the USB-fuse (trips at 500 mA). When this situation lasts the pin-driver will be destroyed. This could cause an internal open circuit (with no further consequences) or an internal short circuit which might cause a supply current higher than 500 mA which would trip the USB-fuse. In this case pin 8 would be permanently destroyed which is easy to establish. If pin 8 keeps working, this scenario doesn't happen.

Normally the sketch "Melody" would not output a dc-signal (0 Hz). At 400 Hz the pin current would be 5/(26+8)= 147 mA. This is still far above the maximum rating for the pin current and the scenario is the same as above.

So the only way the USB-fuse could be tripped is when the pin driver burns out and causes a short-circuit from Vcc to ground. Reading between the lines, my impression is that Raddevus tried this out more than once, which means that pin 8 keeps working. Also I don't think that it is likely that an burn-out of a (few) transistor(s) of an IC causes a short-circuit. Therefore the cause for tripping the USB-fuse must lie elsewhere.

A last consideration is that Raddevus mentions (in his comment of June 18 at 15:34) three input buttons which are not in the 'schematic' shown with his question. He also seems to use a dodgy board ("missed ground hole on bboard, hit 5v"). So may be we don't see all the factors involved.


message:
How does an LED in an LED-strip like WS2811 know when it should be on or off

I was experimenting with an Arduino board and an LEDstrip WS2811
it works all perfect, but I do not understand how a particular led knows when it is called or adressed. Does every led have a unique address?

body:
The WS2811 is the driver chip, that is embedded into the strip. In principle it is some kind of shift register, that outputs PWM values, and on the strip they are daisy-chained (data output of one is connected to data input of the next). With the Arduino you shift out a stream of bytes, when using a RGB strip 3 bytes per LED (1 byte per color). The first WS2811 reads these 3 bytes, sets it's outputs (PWM) according to them and outputs the rest of the datastream to another pin, so that it can reach the next WS2811. The LEDs on the strip are connected to the WS2811's outputs.

So all in all the WS2811 chip saves the current desired state of it's LED, which it got through the data stream from the Arduino. The chips don't have a direct address, but can be identified by their position in the strip. So you cannot only write to the 5th LED without also writing values to the LEDs before it. But, if you don't want to set the whole strip, you can output less data, than the strip as LEDs, effectively ignoring the LEDs at the end.

---

EDIT:

> but How does it recognize the first led?

The strip has somewhat like a data line. When you look at the markings for this line on both ends of the strip, you normally should see something like "DI" and "DO", which means Data In and Data Out, each at one end of the strip. Each LED has it's own Data In and Data Out, which are chained to the next and the previous LED. The first and last LED expose their Data In or Data Out (respectively) to the outside of the strip. You feed the data into Data In of the first LED driver, which outputs the rest of the data at it's Data Out pin, where the data can go to the next driver. So the direction, in which the data flows through the strip is already defined and hardwired. You cannot send data in the other direction through the strip. So the first LED is that one, that is directly attached to the Data In line of the strip and will be connected to the Arduino.

Keep in mind, that this is not an address. You can cut the strip at an appropriate place (so that you don't destroy the circuit. Most strips have these pieces regularly after every or every third LED) and get a new first LED, if you now connect the Data In, where you cut the strip, to the Arduino. An LED strip with WS2811's is not an array or a matrix of LEDs, it is a chain of LEDs. This difference is important in how you control them.


body:
The LED units don't have any unique addresses of their own, instead they are indexed by their position in the string of LEDs. When you feed data into the first LED, you put the entire sequence of color values into the first one. It will then set its own color to the first one in the sequence, and then output all the rest to the next LED in the series.

None of the LEDs actually "know" where in the strip they are located, they only take the first value that comes in and set their own color to that value, and then output the rest of the values to the next LED in the series.


message:
How to track a pressure sensor from analog inputs?

I am a beginner with arduino. I have been researching pressure sensors composed of 2 conductors that sandwich a layer of velostat. My understanding is the velostat when compressed creates resistance between the conductive plates meaning when stepped on the charge decreases. I wanted to inquire about a wiring scheme for connecting these sensors to my analog inputs of a arduino nano with ideally 8 sensors connected to the 8 analog inputs. What is the wiring scheme? I would like to detect a gradation in sensitivity as best as possible for tracking someone applying pressure to that sensor. I have not built the sensors yet so that aspect of the project is open ended. Thanks for your attention in the matter. I am new to the world of electronics so please explain in elementary terms.

body:
It is not really clear, what exactly is your question here.

You are correct: The resistance of the velostat goes down, as pressure is applied to it. You have to build a voltage divider with the sensor and a normal resistor. The best value for that resistor highly depends on the sensor you build, because the way and the size you build it will control it's resistance. Then you can feed the middle pin of that voltage divider to an analog input.

The precision depends on many factors, including the sensor itself and the noise, that gets introduced into the analog input. Try and tweak your circuit, until it suits your needs.


message:
Read pc volume percentage?

is there a way to read the current pc volume? This is going to be a part of a project that I have in mind that is essentially reading curent pc volume value and giving it an RGB value (green=>30, yellow=<30>60, red=<60) and lighting up an RGB led accordingly.

body:
There is no way for any hardware device, Arduino or otherwise, to request information like that from a computer.

HID is a protocol which (when used as a keyboard) allows you to *send* keypresses, including "media keys", which tell the computer to change the volume (amongst other things). There is no provision, other than three status LEDs, for getting any data back from the computer.

You will have to write software for your computer to query that information using whatever API may be available for your operating system, and pass that information through whatever communication channel you choose to the Arduino (such as through serial).

Some pointers:

* [C# get master volume level/precent](https://stackoverflow.com/questions/4235246/c-sharp-get-master-volume-level-precent)
* [Windows 7 Master Volume](https://www.codeproject.com/Questions/440743/Windows-Master-Volume)
* [Arduino: Sending and Receiving Multi-Digit Integers](https://www.baldengineer.com/arduino-multi-digit-integers.html)


body:
There are external devices that show the volume, but you need a driver for that. I don't know if there is an open source driver which you could adapt to send the volume via a serial port to the Arduino.

The Windows PowerShell has the possibility to get the volume and transmit it to a serial port. You could do that a few times per second. In linux it might even be easier, a bash script with gawk with "amixer sget Master".

Another problem is to select the right serial port for the Arduino. I don't know how to automatically select the right port.


message:
What is a simple way to measure the ambient light?

I want to install some LED stripes on my motorcycle, i.e. as brake light and indicators. I use WS2812 LED stripes which can be very bright - especially with many LEDs on at the same time.

I want to measure the ambient light so that in the bright sun I can light the LEDs with, let's say, 100%. But in the night maybe just with 30% intensity. I want to detect the ambient light to change the intensity.

I don't need high resolution and I don't need high speed. If the ambient light is measured i.e. once per second with 4 bit resolution that would be already good enough.

Which ambient light sensor (or photo diode or whatever) makes sense for this little project and how to connect it?
Does it make sense to use more than one light sensor for a better average ambient light value (just in case one sensor is in the shadow, another in the sun)?

I found these sensors form a Chinese supplier:

https://www.banggood.com/CJMCU-9930-APDS-9930-Digital-Proximity-And-Ambient-Light-Sensor-For-Arduino-p-1103139.html

https://www.banggood.com/GY-49-MAX44009-Ambient-Light-Sensor-Module-For-Arduino-p-1196674.html

But an I2C interface seems to be overkill for my simple project.

Any suggestions?

body:
Perhaps a [LDR][1] and a 10k ohm resistor might work.

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

  [1]: https://www.aliexpress.com/item/20Pcs-Photo-Light-Sensitive-Resistor-Photoresistor-5528-GL5528/32651317086.html
  [2]: https://i.stack.imgur.com/i7xji.png

    #define LDRpin A0
    unsigned int LDRvalue = 0;

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

    void loop(){
      LDRvalue = analogRead(LDRpin);
      Serial.println(LDRvalue);
      delay(1000);
    }


body:
You can also use an LED. Connect the LED and its resistor between two port pins. Then, when you want to measure ambient light in your program, do this:

1. Make sure any pullups/pulldowns are disabled.
2. To discharge the LED, start with switching it on for a short moment (a clock cycle is enough) by setting the pins to output and setting anode high and cathode low.
3. [Reverse the polarity][1] by setting the anode pin low and the cathode pin high.
4. Set the cathode pin to input.
5. Using a timer and a pin change interrupt, measure the time it takes for the cathode pin to become low.

Since the capacity of the LED varies with light intensity, the time it takes for the LED to discharge through its resistor and the pin resistance is is an indication of light intensity.

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


message:
Need help with converting Celsius to Fahrenheit in the code

I'm new to Arduino and trying to figure out how to convert Celsius to Fahrenheit with the parameters listed below. Do I need to create a separate file for the calculations? If so, can someone help me on how I can go about doing that?

    #include <DHT.h>
    #include <DHT_U.h>

    int SENSOR = 2;
    int TEMPERATURE;
    int HUMIDITY;

    DHT dht(SENSOR, DHT11);

    void setup() {
      Serial.begin(9600);
      dht.begin();
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      TEMPERATURE = dht.readTemperature();
      HUMIDITY = dht.readHumidity();
      Serial.print("Temp: ");
      Serial.print(TEMPERATURE);
      Serial.println(" celsius ");
      Serial.println(" ");
      Serial.print("Humidity: ");
      Serial.println(HUMIDITY);
      delay(2000);

      //Built In LED
      digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on (HIGH is the voltage level)
      delay(250); // wait for a second
      digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
      delay(250);
    }

body:
You could add a function to your sketch.

    // Celsius to Fahrenheit conversion
    double Fahrenheit(double celsius){
      return 1.8 * celsius + 32;
    }

Then add this code to your loop().

    Serial.print("Temp: ");
    Serial.print(Fahrenheit(TEMPERATURE));
    Serial.println(" fahrenheit ");


body:
If you are using the Adafruit DHT sensor library, then you can get a
Fahrenheit reading by passing `true` as an argument to
`readTemperature()`. C.f. [the comment in the source code][source]. For
example:

<!-- language: lang-c++ -->

    Serial.print("Temp: ");
    Serial.print(dht.readTemperature(true));  // true -> Fahrenheit
    Serial.println(" deg. F");

Note that this library offers also the conversion functions
`convertCtoF()` and `convertFtoC()`.

[source]: https://github.com/adafruit/DHT-sensor-library/blob/1.3.0/DHT.cpp#L34


message:
Robot car speed issue

[![enter image description here][1]][1]
If I'm connecting it in this way I have no issue and I can control the speed.
[here is a video][2]
[![enter image description here][3]][3]

    const int speedMotorA = 9;
    const int speedMotorB = 3;
    const int motorPin1  = 4;
    const int motorPin2  = 7;
    const int motorPin3  = 12;
    const int motorPin4  = 13;

    void setup() {
      Serial.begin(9600);
      pinMode(speedMotorA, OUTPUT);
      pinMode(speedMotorB, OUTPUT);
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      pinMode(motorPin3, OUTPUT);
      pinMode(motorPin4, OUTPUT);
    }
    void loop(){
      TurnMotorA();
      TurnMotorB();
    }

    void TurnMotorA() {
      int Speed = analogRead(A2);
      Speed = Speed*0.24926686;
      Serial.println(Speed);
      analogWrite(speedMotorA,Speed);
      digitalWrite(motorPin1, HIGH);
      digitalWrite(motorPin2, LOW);
    }

    void TurnMotorB() {
      int Speed = analogRead(A2);
      Speed = Speed*0.24926686;
      analogWrite(speedMotorB,Speed);
      digitalWrite(motorPin3, HIGH);
      digitalWrite(motorPin4, LOW);
    }

now I'm trying to expand my mini-project with servo and ultrasonic sensor
with this code and wiring, I have tried many ways to control speed but it's not working properly while increasing speed motor A respond but motor B stay off till I reach maximum speed 255 motor B start working.
[here is a video][4]
[![enter image description here][5]][5]

    #include <NewPing.h>
    #include <Servo.h>

    #define TRIG_PIN A4
    #define ECHO_PIN A5
    #define MAX_DISTANCE 200
    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
    Servo myservo;

    const int laser = 8;
    int distance = 0;
    const int speedMotorA = 9;
    const int speedMotorB = 3;
    const int motorPin1  = 4;
    const int motorPin2  = 7;
    const int motorPin3  = 12;
    const int motorPin4  = 13;

    int hitlaser(){
      digitalWrite(laser, HIGH);
      delay(200);
      digitalWrite(laser, LOW);
    }

    void setup() {
      pinMode(laser, OUTPUT);
      pinMode(speedMotorA, OUTPUT);
      pinMode(speedMotorB, OUTPUT);
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      pinMode(motorPin3, OUTPUT);
      pinMode(motorPin4, OUTPUT);
      myservo.attach(5);
      myservo.write(65);
      delay(2000);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
    }

    void loop() {
     int distanceR = 0;
     int distanceL =  0;
     delay(40);
     digitalWrite(laser, HIGH);
     if(distance<=50)
     {
      moveStop();
      delay(100);
      moveBackward();
      delay(300);
      moveStop();
      delay(200);
      distanceR = lookRight();
      delay(200);
      distanceL = lookLeft();
      delay(200);

      if(distanceR>=distanceL)
      {
        turnRight();
        moveStop();
      }else
      {
        turnLeft();
        moveStop();
      }
     }else
     {
      moveForward();
     }
     distance = readPing();
    }

    int lookRight()
    {
        myservo.write(5);
        delay(500);
        int distance = readPing();
        delay(100);
        myservo.write(65);
        return distance;
    }

    int lookLeft()
    {
        myservo.write(150);
        delay(500);
        int distance = readPing();
        delay(100);
        myservo.write(65);
        return distance;
        delay(100);
    }

    int readPing() {
      delay(70);
      int cm = sonar.ping_cm();
      if(cm==0)
      {
        cm = 250;
      }
      return cm;
    }

    void moveStop() {
        analogWrite(speedMotorA, 0);
        analogWrite(speedMotorB, 0);
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, LOW);
        digitalWrite(motorPin3, LOW);
        digitalWrite(motorPin4, LOW);
      }

    void moveForward() {
        int Speed = analogRead(A2);
        Speed = Speed*0.24926686;
        Serial.println(Speed);
        analogWrite(speedMotorA,Speed);
        analogWrite(speedMotorB,Speed);
        digitalWrite(motorPin1, HIGH);
        digitalWrite(motorPin2, LOW);
        digitalWrite(motorPin3, HIGH);
        digitalWrite(motorPin4, LOW);
    }

    void moveBackward() {
        int Speed = analogRead(A2);
        Speed = Speed*0.24926686;
        Serial.println(Speed);
        analogWrite(speedMotorA,Speed);
        analogWrite(speedMotorB,Speed);
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, HIGH);
        digitalWrite(motorPin3, LOW);
        digitalWrite(motorPin4, HIGH);
    }

    void turnRight() {
      int Speed = analogRead(A2);
      Speed = Speed*0.24926686;
      Serial.println(Speed);
      analogWrite(speedMotorA,Speed);
      analogWrite(speedMotorB,Speed);
      digitalWrite(motorPin1, HIGH);
      digitalWrite(motorPin2, LOW);
      digitalWrite(motorPin3, LOW);
      digitalWrite(motorPin4, HIGH);
      delay(300);
      moveForward();
    }

    void turnLeft() {
      int Speed = analogRead(A2);
      Speed = Speed*0.24926686;
      Serial.println(Speed);
      analogWrite(speedMotorA,Speed);
      analogWrite(speedMotorB,Speed);
      digitalWrite(motorPin1, LOW);
      digitalWrite(motorPin2, HIGH);
      digitalWrite(motorPin3, HIGH);
      digitalWrite(motorPin4, LOW);
      delay(300);
      moveForward();
    }

update :

after removing servo from the project it seems working but how can i use servo with this project
Thanks to  [Majenko♦][6]
**update 2**
after attaching servo to pin 9 i can now controle speed but still some issues as when Robot car have obsticles it should make backword >> issue is >> one motor only go backword!.

    #include <NewPing.h>
    #include <Servo.h>

    #define TRIG_PIN A4
    #define ECHO_PIN A5
    #define MAX_DISTANCE 200
    NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);
    Servo myservo;

    const int laser = 8;
    int distance = 0;
    const int speedMotorA = 11;
    const int speedMotorB = 3;
    const int motorPin1  = 4;
    const int motorPin2  = 7;
    const int motorPin3  = 12;
    const int motorPin4  = 13;

    int hitlaser(){
      digitalWrite(laser, HIGH);
      delay(200);
      digitalWrite(laser, LOW);
    }

    void setup() {
      pinMode(laser, OUTPUT);
      pinMode(speedMotorA, OUTPUT);
      pinMode(speedMotorB, OUTPUT);
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      pinMode(motorPin3, OUTPUT);
      pinMode(motorPin4, OUTPUT);
      myservo.attach(9);
      myservo.write(65);
      delay(2000);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
    }

    void loop() {
     int distanceR = 0;
     int distanceL =  0;
     delay(40);
     digitalWrite(laser, HIGH);
     if(distance<=50)
     {
      moveStop();
      delay(100);
      moveBackward();
      delay(1000);
      moveStop();
      delay(200);
      distanceR = lookRight();
      delay(200);
      distanceL = lookLeft();
      delay(200);

      if(distanceR>=distanceL)
      {
        turnRight();
        moveStop();
      }else
      {
        turnLeft();
        moveStop();
      }
     }else
     {
      moveForward();
     }
     distance = readPing();
    }

    int lookRight()
    {
        myservo.write(5);
        delay(500);
        int distance = readPing();
        delay(100);
        myservo.write(65);
        return distance;
    }

    int lookLeft()
    {
        myservo.write(150);
        delay(500);
        int distance = readPing();
        delay(100);
        myservo.write(65);
        return distance;
        delay(100);
    }

    int readPing() {
      delay(70);
      int cm = sonar.ping_cm();
      if(cm==0)
      {
        cm = 250;
      }
      return cm;
    }

    void moveStop() {
        analogWrite(speedMotorA, 0);
        analogWrite(speedMotorB, 0);
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, LOW);
        digitalWrite(motorPin3, LOW);
        digitalWrite(motorPin4, LOW);
      }

    void moveForward() {
        int Speed = analogRead(A2);
        Speed = Speed*0.24926686;
        Serial.println(Speed);
        analogWrite(speedMotorA,Speed);
        analogWrite(speedMotorB,Speed);
        digitalWrite(motorPin1, HIGH);
        digitalWrite(motorPin2, LOW);
        digitalWrite(motorPin3, HIGH);
        digitalWrite(motorPin4, LOW);
    }

    void moveBackward() {
        int Speed = analogRead(A2);
        Speed = Speed*0.24926686;
        Serial.println(Speed);
        analogWrite(speedMotorA,Speed);
        analogWrite(speedMotorB,Speed);
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, HIGH);
        digitalWrite(motorPin3, LOW);
        digitalWrite(motorPin4, HIGH);
    }

    void turnRight() {
      int Speed = analogRead(A2);
      Speed = Speed*0.24926686;
      Serial.println(Speed);
      analogWrite(speedMotorA,Speed);
      analogWrite(speedMotorB,Speed);
      digitalWrite(motorPin1, HIGH);
      digitalWrite(motorPin2, LOW);
      digitalWrite(motorPin3, LOW);
      digitalWrite(motorPin4, HIGH);
      delay(300);
      moveForward();
    }

    void turnLeft() {
      int Speed = analogRead(A2);
      Speed = Speed*0.24926686;
      Serial.println(Speed);
      analogWrite(speedMotorA,Speed);
      analogWrite(speedMotorB,Speed);
      digitalWrite(motorPin1, LOW);
      digitalWrite(motorPin2, HIGH);
      digitalWrite(motorPin3, HIGH);
      digitalWrite(motorPin4, LOW);
      delay(300);
      moveForward();
    }

Appreciate your support

  [1]: https://i.stack.imgur.com/IiTeg.jpg
  [2]: https://youtu.be/gZLBvR8W2fY
  [3]: https://i.stack.imgur.com/fcTSs.jpg
  [4]: https://youtu.be/1Y35QM6gJuE
  [5]: https://i.stack.imgur.com/wLFWc.jpg
  [6]: https://arduino.stackexchange.com/users/4143/majenko

body:
The problem here is a conflict of resources.  Both the Servo library and the PWM for pin 9 require the same timer.

> The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

You should choose a different PWM pin (not pin 10) instead of pin 9.


message:
Waterlevel sensor disrupts PH reading

I have a [water level sensor][1] and a PH sensor connected to my nodemcu via an [ADS1115 ][2]. When I insert only the PH sensor into the water then everything works fine. But when I insert the waterlevel sensor into the same container the PH sensor seems to shortcircuit and I get 5V no matter the actual PH level. Is there anything im missing or a way to prevent that from happening?

  [1]: https://www.amazon.de/Sharplace-Wasser-Sensor-Modul-Arduino-Rot/dp/B075VHRGND/ref=sr_1_1?ie=UTF8&qid=1529326945&sr=8-1&keywords=water level sensor
  [2]: https://www.adafruit.com/product/1085

body:
That water level sensor uses bare metal which is in contact with the water. The PH sensors are sensitive for that kind of voltage in the water, even if it would be 0V.

There are isolated PH sensor amplifier modules. On forums are often discussions whether to ground an aquarium or not for a PH sensor. With a isolated PH sensor, you avoid most of those problems.

There are also non-contact water level sensors. For example capacitive sensor or even sensors that can be attached on the outside. Some sensors use the water pressure, but I don't know if this one is isolated: https://www.sparkfun.com/products/10221


message:
How many times can I upload a program or sketch to my Arduino Uno Clone Board?

I'm about to work on my very first project using arduino (I'm just about to buy one next week), and one of our professor says that we can only upload a program or sketch in an Arduino Uno Board for approximately 8 times. He also added that if we're using a clone version, it'll can only last for 2 sketch uploads. Is this true or is he bluffing? Thank you in advance.

body:
He's talking complete and utter gibberish.  To quote from the [ATMega328P datasheet][1]:

> * High Endurance Non-volatile Memory Segments
>   * 32KBytes of In-System Self-Programmable Flash program
Memory
>   * 1KBytes EEPROM
>   * 2KBytes Internal SRAM
>   * ***Write/Erase Cycles: 10,000 Flash***/100,000 EEPROM
>   * Data Retention: 20 years at 85°C/100 years at 25°C(1)
>   * Optional Boot Code Section with Independent Lock Bits
>      * In-System Programming by On-chip Boot Program
>      * True Read-While-Write Operation
>   * Programming Lock for Software Security

So you have at least 10,000 uses out of it before it starts to go flakey.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf


message:
Do I need a full Arduino board hardwired to a sensor to send data via Wi-Fi?

Basically I want to wire a Wheatstone bridge style load-cell into a moving trolley and transmit the data to a remote workstation so I can get real-time feedback about the loading conditions.

Do I need to have a full board riding on the trolley that is wired in between the Wi-Fi transmitter and the bridge amplifier or is there a way that the current variations from the bridge can be read directly by the Wi-Fi transmitter and relayed to the remote in some translatable format?

The trolley design is extremely streamlined and it would be a bummer to have to add more than minimal electronics to make this happen...

body: There are small packages out there with built in WiFi.  Node MCU is one of them, however its analog to digital conversion isn't up to the task of measuring bridges.  If you go that route you'll need to add a ADC to the Node MCU which will increase the total package size.


message:
Creating formatted String (including floats) in Arduino-compatible C++

I'm using a Mega2560 and a generic SSD1306 OLED display with the Adafruit_SSD1306 (and by extension, Adafruit_gfx) library.

I need to print a bunch of float values (ranging between 30.0 and 99.9) to the display with exactly one decimal place of precision. The catch is, the Adafruit library doesn't have a printf() method, only one that takes a single ready-to-print string.

Here's an (obviously non-Arduino) Java-like example of what I'm trying to accomplish:

    String foo = String.format("%.1f, %.1f\%", temp1, hum1);
    // "display" is my instance of Adafruit_SSD1306
    display.print(foo);

So... how can I do something similar in Arduino-compatible C(++)?

Note: for this specific program, I have (relatively speaking) RAM to burn, so I really don't care if whatever library I use to generate formatted Strings is particularly efficient (as long as it isn't leaking). If it wants to use 4k of RAM and 80k of flash to format a 20-character String, so be it.

body:
The `Adafruit_GFX` class has two methods named `print()` and
`println()`. These behave exactly like `Serial.print()` and
`Serial.println()`. Specifically, when printing a float, you can provide
a second argument telling it the number of decimal places you want after
the decimal point:

    display.print(temp1, 1);  // 1 digit after the decimal point
    display.print(", ");
    display.print(hum1, 1);  // ditto
    display.print("%");

**Background**: the reason these methods behave like the ones of
`Serial` is that both `Adafruit_GFX` and `HardwareSerial` inherit them
from the [`Print` virtual class][Print].

[Print]: https://github.com/arduino/Arduino/blob/1.8.5/hardware/arduino/avr/cores/arduino/Print.h


body:
Normally for formatting strings I'd suggest the venerable `snprintf` and similar functions. However, on an 8-bit Arduino when you're using floats that's not an option: the function that does all the formatting for this family if functions has had floating point support surgically removed from it. This is to make the function a fraction of the size so it's not as bloaty in small microcontrollers.

I believe there is a float-capable version somewhere on the internet that could be somehow installed, though I have never looked into doing that.

Instead you need to do the formatting of floats manually.  Everything else can be done with `snprintf`, but the floats need to be done separately.

Fortunately there's a function specifically for formatting a float into a character array (C-string), called `dtostrf` and is used thus:

    float myVal = 23.49173783;
    char *buffer[10]; // Enough room for the digits you want and more to be safe
    dtostrf(myVal, 9, 1, buffer);

The first number in the parameter list is how many characters you want to have in your output, including the `.` and any leading `-`. Any extra characters are padded with space.  The second number is how many decimal places.  If the first number is negative the value is left-aligned. If it's positive it's right-aligned.  So the code above would give you:

    〿〿〿〿〿23.5␀

(Note: I am using `〿` to denote a space character.) If you used `-9` you'd get:

    23.5〿〿〿〿〿␀

You can, of course, feed that created string into another string using `snprintf` and the `%s` placeholder.

    char buf2[32];
    snprintf(buf2, 32, "The temperature is: %s\r\n", buffer);

    buf2 ⇒ "The temperature is: 23.5〿〿〿〿〿"

If you want to trim the string down to just contain the number portion and lose the spaces it's best to left-align it with a negative width, then change the first space to a `␀`:

    char *space = strchr(buffer, ' ');
    if (space != NULL) {
        *space = '\0';
    }


body:
One can use the `String()` type initialization to convert any number, including float to String. For example to convert `3.14159` simply type ⤵

```cpp
float num = 3.14159
String str1 = String(num, 1) // 3.1
String str2 = String(num, 2) // 3.14
String str3 = String(num, 3) // 3.141
```
To the right of the comma is the number of decimal places one wants the string result to have. It has a lot of functionality but that's one of the overloads. You can see them [all here!][1]

To see this code working on a .ino sketch check out this GitHub repo
https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries

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


message:
warning: variable 'b' set but not used

I got the following error:

`warning: variable 'b' set but not used`.

I think I do a really small thing wrong but I can't figure out what it is.

    #define array_size(array) ((int)(sizeof(array) / sizeof((array)[0])))

    typedef struct Boid {
      unsigned long start_animate_time;
    } Boid;

    Boid boids[4];

    Boid create_boid() {
      unsigned long start_animate_time = 0L;
      Boid b = {start_animate_time};
      return b;
    }

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

      boids[0] = create_boid();
      boids[1] = create_boid();
      boids[2] = create_boid();
      boids[3] = create_boid();

      for (int i = 0; i < array_size(boids); i++) {
        Boid b = boids[i]; // <<<<<<<<<<<<< this line!
        b.start_animate_time = 456;
      }

      for (int i = 0; i < array_size(boids); i++) {
        Boid b = boids[i];
        Serial.println(b.start_animate_time); // BUG always 0
      }
    }

    void loop() {

    }

> flock_01_ino_debug.ino:28:10: warning: variable 'b' set but not used
> [-Wunused-but-set-variable]
>      Boid b = boids[i];
>           ^

body:
C++ is not Java. You can't just assign structs like that - it copies them (if anything).

    Boid b = boids[I]; // <<<<<<<<<<<<< this line!
    b.start_animate_time = 456;

Instead just access the array slice directly:

    boids[i].start_animate_time = 456;

And later on as well:

    Serial.println(boids[i].start_animate_time);

Basically, you create a "Boid" variable called "b", copy the content of `boids[i]` to it, set a value in that variable, and then throw it away. Hence the "not used". If you want to reference a specific array slice as a separate variable either get a pointer to it:

    Boid *b = &boids[i];
    b->start_animate_time = 456;

Or use a reference:

    Boid &b = boids[i];
    b.start_animate_time = 456;

Of the two I prefer using a pointer, but I come from a C background and understand pointers, but it took me many years of trial and error to get to that point...


message:
Output voltage of PIR sensor

![enter image description here](https://i.stack.imgur.com/vtjUa.jpg)![enter image description here](https://i.stack.imgur.com/1aKYL.jpg)

Case 1
I am measuring output voltage of PIR sensor, I am getting 3.3v

Case 2
I have connected a resistor and a led to output of PIR sensor. Now when I measure voltage at the output pin of the sensor, I am getting 2.04v only.

In case 2 as the output voltage is dropped, it is not able to trigger a high state to arduino pin.

Where am I going wrong? What shall I change?

body:
The PIR can’t provide enough current to drive the led. The maximum current for the BIS0001 is 10mA.

Either increase the resistor value, and accept that the led is less bright.

Or use a transistor to drive the led.

Or connect the led to an Arduino pin and turn the led on by code, based on the input pin connected to the PIR


message:
Background "static" on side of TFT screen?

I recently bought an XC4629 128x128 TFT screen and noticed that failing to initialise a background for the screen produced this RBG static.

A red line drawn on the screen without a background:
[![enter image description here][1]][1]

The problem, however, is that when I did initialise a background, the "static" remained on 3-4 pixels down the side of the screen:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/vdmkU.jpg
  [2]: https://i.stack.imgur.com/aYH7B.jpg

Here is the code I used:

     #include <TFT.h>
     #include <SPI.h>

     #define CS   10
     #define DC   9
     #define RESET  8

     TFT myScreen = TFT(CS, DC, RESET);

     void setup(){
       myScreen.begin();
       myScreen.background(0,0,0);
     }

     void loop(){
       myScreen.stroke(255, 0, 0);
       myScreen.line(0, 128, 128, 10);
     }

Is this a problem with the screen itself? I have searched around the internet and have found no similar issues. Due to the behaviour it seems like an code issue but I have made it as simple as possible and experimented and only found it goes away if I remove the signal and just have the screen on backlight only. I also double checked that the wiring was all in the correct slots (both referencing the code and the datasheet for the screen).

Many thanks in advance.

body:
It will be a problem with the library you are using. Not all screens that use the same CoG are wired in quite the same way. Often a CoG that supports a larger number of columns is used with a screen that doesn't have that many columns (132 in this case), and the actual screen is placed at an offset within the available columns, and it's up to the manufacturer of the screen where that offset is.

So the library has to initialize the CoG with where the screen actually is within its physical column range, and your screen is different to what the library is expecting.  Looking at the TFT library bundled with the IDE most screen configurations appear to impose a couple of pixels offset in the columns, which you don't want.

I would suggest investigating other TFT libraries, such as UTFT, which may give better control over screen parameters.


message:
HEF4094 with 12v Vcc

Using old [NXP HEF4094BP][1] shift register chips, for the reason of fixing some old hardware. These chips were popular in the 90's because they could accept 3-15V VCC and directly drive series+parallel LED chains. Think: gas station price signs, etc.

I'm green. Using [this post][2] and the [4094 datasheet][1], I've successfully modeled your typical shift register count-to-100 binary, with an LED on each SR out. Powered by 5V, works great. This was phase 1 for me.

For phase 2, I powered the Arduino via 12V (via p30, Vin). Still supplying 5V to the 4094 (Nano pin 27 output), works great.

Phase 3, I need help. I remove the 5V jumper that was from Nano pin 27 going into 4094's VCC pin. In it's place, I run 12V directly from the (regulated) PS and I get NO LED output.  I know I haven't burned anything out because at 12V I get brief "flashes" when I'm "plugging" in the 12V power supply. I can revert to 5V VCC input and it works fine as before.

I've read the datasheet 3X and it's not clear how the chip's output pin voltage is managed when you alter the VCC to be higher (is it limiting current or voltage on the outputs?)

  [1]: https://assets.nexperia.com/documents/data-sheet/HEF4094B.pdf
  [2]: http://forum.arduino.cc/index.php?topic=211583.0

body:
The part of the datasheet you need to understand is this bit:

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

That's the input logic levels, and as you can see they vary depending on the supply voltage.

At 10V you need to supply at least 7V to get a HIGH registered. At 15V you need 11V or more. So at 12V you can expect that level to be around 9V and upwards.

The Arduino outputs 5V. That's nowhere near 9V, so the chip completely ignores it.

These chips are not designed to be level translators. They are designed to work with other chips that also run at the same voltage. To use it at a higher voltage that the chip that's driving it you will need to employ some form of 5V to 12V level translation.

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


message:
Is it possible to print a custom object by passing it to Serial.print()?

I googled about it, but can't find the answer. As I would guess I would have to inherit from the Print class and somehow pass to its print methods the part of my object I would like to be printed. But I am not sure how to go about it or if it is even possible.

body:
There is a class called `Printable`. If you inherit from that, and implement the `size_t printTo(Print& p)` function, your object can then be passed to the print functions:

    class myClass : public Printable {
        private:
            int _val1;
            int _val2;

        public:
            myClass(int v1, v2) : _val1(v1), _val2(v2) {}
            size_t printTo(Print& p) const {
                 size_t r = 0;

                 r += p.print("One: ");
                 r += p.print(_val1);
                 r += p.print(" Two: ");
                 r += p.print(_val2);
                 return r;
           }
    };

Then:

    myClass ob(4, 5);

    Serial.println(ob);
    => One: 4 Two: 5


message:
Arduino Wifi Works one way but not the other? (ESP32) (Possible Variable Type Problem)

I am working on a code that accepts input from serial monitor and connects to Wifi, and have been getting issues.

my SSID for my wifi is "SamF" but for some reason arduino only likes it when I initialize at the top, not when I accept it from serial monitor even though they are the same..

Example The below code works:

    #include <WiFi.h>

    char ssid[] = "SamF"; //OR const char* = "SamF"
    char pass[] = "secretPassword";
    void setup()
    {
    WiFi.begin(ssid, pass);
    }
    void loop () {}

The Code Below Does not work..

    #include <WiFi.h>
    char pass[] = "secretPassword";
    void setup()
    {
    ssidSerial = my code that receives Serial input and converts to char

    for(int k=0;k<=3;k++){
    ssidPlaceHolder[k]=ssidSerial[k];
    }
    const char* ssid = ssidPlaceHolder;
    WiFi.begin(ssid, pass);
    }
    void loop () {}

Everything compiles fine, I debugged by using Serial.print and they are both displaying "SamF" and sizeof(ssid) for both is 4... so I am not sure why one works and the other doesn't? any ideas?

Thanks in advance for any help, and if anyone needs the code after I am done I will be more than glad to share it on git!

body:
Basic string in C is an array of characters terminated by a 0. All functions taking char* or const char* use this 0 to determine the end of the string, because there is no other information about the length of that string.

In your question you copy characters from one characters buffer to other, but you do not set the terminating 0, so the function `begin` takes the data after the `pass` pointer until some random memory location with 0.


message:
Is there any problem in running Arduino logic to 12V LEDs?

I want to run a strip of 300 12V LEDs (Adafruit Neopixels with WS2811), with my Arduino. Is it safe to connect a follows, or is there some "separation" between voltage levels needed?

- 5V voltage/out and ground (from converter 1) to Arduino Voltage-in and ground.
- 12V voltage-out (from converter 2) to LED strip voltage-in.
- 12V ground (from converter 2) to Arduino ground and LED strip ground.
- Arduino data pin to LED strip data pin.

body:
The signalling of those LEDs is 5V and the power supply 12V. Basically you have a 5V-powered chip with constant current sinks driving LED chains that are powered from 12V. The 5V power for the chip is created from the 12V power for the LEDs. So, you need to:

* Provide +12V and GND to the chain of LEDs from a 12V power supply
* Connect the data line to an Arduino
* Connect the GND connection to the Arduino as well.

Nothing more is needed.


message:
What is this? Looks like a sensor

I got an Arduino kit from my dad.
But inside this box is a thing, maybe a sensor. But I can't find what it is.
Anyone recognize this 'thing' on the picture?

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

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

body:
Appears to be a touch sensor that can be found on various on-line retail web pages:

[http://www.satistronics.com/][1]

[https://www.arduiner.com/][2]

Also, the back may have a URL as this one does:

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

...however, the URL appears not to function.

  [1]: http://www.satistronics.com/k1208043-diy-touch-sensor-switch-module-for-arduino-works-with-official-arduino-boards_p4096.html
  [2]: https://www.arduiner.com/en/tilt-touch-vibration/85-touch-sensor-touch-switch-module-smart-car-arduino-3809200620547.html
  [3]: https://i.stack.imgur.com/ipqvw.jpg


message:
Interfacing Figaro KE25 Oxygen Gas Sensor with Arduino Uno

I have been trying to interface the **Figaro KE25 2 lead fuel cell type oxygen gas sensor** with **Arduino Uno**. I am not getting the required output on the Serial Monitor for regular air (Oxygen concentration of 19%).

I have attached the **sketch** I have typed out, the **output I have obtained on the Serial Monitor**, the **output(mV) vs Oxygen concentration (%) graph** of the Figaro KE25 sensor I have obtained from the datasheet, the **chemical reactions governing the working of the sensor**,the **circuit diagram** I have used, and the **construction of the sensor**.

In this question; I will explain the sensor first, then my circuit, then my sketch, and lastly the problem I have with my output.

In **electronics**, the **Anode is the positive electrode** and the **cathode is the negative** electrode. In ***electrochemistry***, the ***Anode is the Negative electrode*** and the ***Cathode is the positive electrode***. Do check the image of the construction of the sensor I have provided obtained from the datasheet.[![image of the construction of the sensor][1]][1] [Full Technical Datasheet][2]

The **Cathode**, that is, **the positive electrode** is the **sensing electrode** (Oxygen gets consumed here and an electric current is generated). Since a current is being generated by the sensor (fuel cell), **no power supply needs to be given to the sensor**. Check the image of the chemical reactions provided (obtained from the full technical datasheet of the sensor). [![Chemical Reactions][3]][3][Technical Datasheet][4]

The sensor in question is an analog voltage type sensor. Keeping this and everything I have mentioned above in mind, I have constructed the following circuit with Arduino Uno. Refer the picture I have put up. I have connected the **Cathode (the sensing positive electrode, red in colour) to the Arduino's analog A0 pin** and **the Anode (negative electrode) to the Arduino's ground**. [![Circuit][5]][5]

The sketch I have used is as follows:

     /*the analog pin of the alcohol sensor goes into analog pin A0 of the
     Arduino*/

     void setup()
     {
         Serial.begin(9600); //sets the baud rate
     }

     void loop()
     {
         float v1;
         float oxy = 0.0;
         float v2 = 0.0;
         pinMode(A0,INPUT_PULLUP);

         /*To make sure that reading is zero when the circuit is open*/

         v1 = analogRead(A0);

         /*reads the analog value from the Oxygen gas sensor and this value can
         be anywhere from 0 to 1023 (10 bit ADC used in Arduino Uno)*/

         if(v1>900) //To make sure that reading is zero when the circuit is open
         {
             v1=0;
         }
         v2 = (v1*3000)/992;

         /*The above line calculates the output of the sensor in mV using the
         fact that a HIGH reading in an input pin of an Arduino Uno board is
         equivalent to a voltage of 3V or higher. When I displayed just 'v1',
         the lowest of the high values I got was 992. So I equated it to 3V
         (3000mV) and used the unitary method to find out what a non-HIGH v1
         value would be in terms of mV.*/

         oxy = v2/0.6;

         /*The above line calculates the Oxygen concentration from the mV output
         of the sensor using the output(mV) vs concentration(%) graph from the
         sensor's datasheet. The graph is a straight line passing through (0,0)
         and hence the governing equation is of the form y = m * x. Where 'y' is
         'v2' and 'x' is Oxygen conc. in %.*/

         Serial.print("Oxygen value: ");
         Serial.print(v1);
         Serial.print("    ");
         Serial.print(v2);
         Serial.print("mV    ");
         Serial.print(oxy);//prints the Oxygen value
         Serial.println("%");

         delay(1000);
     }

he output(mV) vs Oxygen concentration(%) graph provided in the datasheet is shown below. The straight line labeled as 'KE25' is to be considered. [![O/P(mV) vs. O2 conc.(%)][6]][6] [Product information (datasheet)][7]

he output I have obtained on the serial monitor is as follows:
[![SerialMonitor][8]][8]

Such a high voltage from the sensor is not possible. My output reading is not possible at all. Where have I made a mistake and how do I correct it?

>**Update 1 :** I changed the line `pinMode(A0,INPUT_PULLUP)` to `pinMode(A0,INPUT)`. Now I am getting sensible values on my Serial Monitor. However, I am also getting many '0' outputs **(many)**. I am also getting many random values **(many)**. I need more information on how to interface a fuel cell type Oxygen sensor using Arduino Uno in terms of how to get a proper voltage reading across such a sensor. I have found no question on electrochemical, fuel cell type Oxygen gas sensor interfacing. All questions asked are regarding sensors that require a power supply. In case of fuel cell type Oxygen gas sensors, current is generated when Oxygen is sensed and hence, no power supply is required. Also, if anyone is into electrochemistry, how do I check the voltage output of a fuel cell type Oxygen gas sensor using a voltmeter? Do I use a DC voltmeter or an AC voltmeter?

> **Update 2:** I've made changes to the code based on @EdgarB's suggestions. The output I am getting now is better but still wrong. I checked if the sensors I am using are functional using a multimeter (I confirmed if the method I am using is right, and it is), and they are. The Oxygen values I am getting now are still really low: 6-8%. I should be getting: 19-21%. I used a reference voltage of 600 mV and modified the code.

> Modified code:

     void setup()

     {

         Serial.begin(9600);//sets the baud rate
         analogReference(INTERNAL);
     }

     void loop()
     {
         const float A_REF = 0.6e3;
         const float Scalc = (1/0.6);

         float v1;
         float oxy = 0.0;
         float v2 = 0.0;
         pinMode(A0, INPUT);
         v1 = analogRead(A0);
         v2 = (v1 * A_REF) / 1024;
         oxy = v2 * Scalc;
         Serial.print("Oxygen value: ");
         Serial.print(v1);
         Serial.print("    ");
         Serial.print(v2,4);
         Serial.print("mV    ");
         Serial.print(oxy,4);//prints the Oxygen value
         Serial.println("%");
         delay(1000);
     }

> Output:
[![Output][9]][9]

  [2]: http://www.meditronik.com.pl/doc/b0-b9999/ke25.pdf
  [3]: https://i.stack.imgur.com/3uZsB.jpg
  [4]: http://www.figarosensor.com/products/entry/ke-25.html#ti
  [5]: https://i.stack.imgur.com/HaJQd.jpg
  [6]: https://i.stack.imgur.com/qUd6u.jpg
  [7]: http://www.figarosensor.com/products/docs/KE Prod Info (1014).pdf
  [8]: https://i.stack.imgur.com/1IdtW.jpg
  [9]: https://i.stack.imgur.com/yw9Hm.jpg

body:
You calculation of v2 is incorrect.

    v2 = (v1 * 3000) / 992;

The maximum value v1 will have is 1023 and this equates to 5v (not 3v).  So to calculate the voltage v2 I think you should be doing:

    v2 = (v1 / 1023) * 5000;

But this will make your calculations even further out!


body:
Your problem stems from having the internal pullup resistor for A0 turned on.

The sensor is a current generator with a load resistor (plus thermistor) built in to convert the current into a voltage. By adding a pullup resistor you turn it into a voltage divider across 5V with a small current being injected into the central node:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/zCEPV.png)

<!-- End schematic -->

Since the datasheet doesn't specify the load resistance nor the source current I have made up some values to demonstrate.

If we take just the current source and load resistance RL+RT and calculate the voltage drop across that we get:

    V=R×I = 5000 × 0.00001 = 50mV

Which is a reasonable value. It's a lot of oxygen, but that's because these are made-up values.

Now what would be the voltage with the pullup resistor added? Well, this is where it gets a little more complex. At times like this it's easier to just simulate the circuit in something like the [falstad simulator](http://tinyurl.com/yalptakx) and I can tell you it's **757.1mV** (If you want to learn how to do this kind of circuit analysis manually you should learn [superposition theory](https://www.allaboutcircuits.com/textbook/direct-current/chpt-10/superposition-theorem/)).

A massive change.

Obviously you're not seeing a change *that* big - and that's because the pullup resistor is *more* than just a simple resistor. There's many more factors that influence the reading, including the output impedance of the network, as well as the rest of the internal ADC circuitry.

Suffice it to say, though, adding a pullup resistor is a bad idea when using the ADC.

But you want to keep the pullup resistor so you can know if the sensor is connected or not. That's not a problem. Just turn it on and off at will:

    pinMode(A0, INPUT_PULLUP);
    delay(1);
    bool connected = analogRead(A0) < 900;
    if (connected) {
        pinMode(A0, INPUT);
        delay(1);
        v1 = analogRead(A0);
    }

It's recommended to wait a moment after changing the pullup resistor state before reading from the ADC to reduce electrical noise picked up by the ADC - hence the `delay(1)` calls.


body:
You have three different issues here:

1. improper use of the pullup resistor
2. incorrect interpretation of the analog reading
3. too small input signal

## Pullup resistor

Majenko already covered the first issue, with very good advice.

## Interpretation of the analog reading

Code Gorilla already explained the second issue. However, since you do
not seem to understand, I will add my take here.

The formula to convert an analog reading to an actual voltage is

voltage = reading × analog\_reference ÷ 1024.

Yes, it's 1024 rather the often seen (but erroneous) 1023. See [the
manufacturer's datasheet][datasheet], which is the _only_ authoritative
reference. Doesn't make much of a difference anyway. The main issue is
the analog reference voltage which, in the default configuration, is the
same as the voltage powering the Arduino, i.e. 5 V.

In a comment, you wrote:

> if a pin is configured as INPUT, then the voltage at the pin is 3V or
> higher

This is complete nonsense. The voltage on an input pin is whatever
voltage is provided by the circuit connected to that pin. If you
actually mean the _threshold voltage_ for the pin reading `HIGH`, well,
that threshold is typically 2.6 V (see the “typical
characteristics” in the datasheet), but the exact value is not
guaranteed. The number you quote is “the lowest value where the pin is
guaranteed to be read as high”. In other words, the voltage threshold
can be lower than 3 V, but not higher.

And all this is completely irrelevant to you. The input thresholds are a
feature of the digital input circuitry attached to the pin. This circuit
is responsible for deciding whether the pin is `LOW` or `HIGH` when you
`digitalRead()` it. But you don't care about the digital value: you are
using the pin as an analog input. The ADC converter is a different
circuitry that has _absolutely nothing to do_ with the digital input.
You can even disable the digital input of the pin and still use the ADC.

## Low signal

According to the graph you provide, the sensor should output
12.6 mV in normal air (21% O2). That's about
2.58 ADC steps. Thus you expect the reading to fluctuate between
the digital values 2 and 3. This is really quite low for your ADC.

A simple way to mitigate this problem is to change the analog reference.
The default is 5 V, but [you can switch it to an internal
1.1 V reference][analogReference] that will significantly increase
your resolution: in `setup()`, call

    analogReference(INTERNAL);

Then you can compute the oxygen level as follows:

    const float A_REF = 1.1e3;         // analog reference = 1,100 mV
    const float SENSOR_CAL = 1 / 0.6;  // calibration: %(O2) / mV

    void loop()
    {
        int reading = analogRead(A0);
        float voltage = reading * (A_REF / 1024);
        float oxygen = voltage * SENSOR_CAL;
        // ...
    }

Another way to mitigate the signal weakness is to average multiple
readings. This can make your effective resolution better than the raw
ADC resolution.

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf
[analogReference]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

## ADC offset

The formula

voltage = reading × analog\_reference ÷ 1024

applies only to an ideal ADC. In practice, any ADC has some offset error
and gain error. Taking them into account, the formula becomes:

voltage = (reading + offset\_error) × analog\_reference ÷ (1024 + gain\_error)

In many cases these errors are too small to care about. However, since
you are working near the resolution limit of your ADC, the offset error
can be an important concern. The gain error is no issue here, so you can
forget about it.

If you have a voltmeter, you can easily determine the offset error:
measure a low voltage, like the one from your sensor, with both the
voltmeter and the ADC. Ideally, you would average many ADC readings to
get a better resolution. From the voltmeter measurement, you compute the
average reading you would expect from your ADC, then you get

offset\_error = expected\_ADC\_reading − actual\_ADC\_reading

Then you use this measured offset to correct your readings:

    const float offset_error = ...;  // measured with the voltmeter

    void loop()
    {
        int reading = analogRead(A0);
        float voltage = (reading + offset_error) * (A_REF / 1024);
        // ...
    }


message:
Run Time Error in arduino

I am trying to communicate multiple clients to a server, all using nodeMCUs. I am getting a weird run time error at the Server Serial Monitor of Arduino IDE when I upload the code.

Here's my server code:

    #include <ESP8266WiFi.h>
    #define Max_Clients 5

    WiFiServer server(80);
    WiFiClient *clients[Max_Clients] = {NULL};
    String inputs [Max_Clients] = {""};                           //Initializing to store the string received from clients

    void setup() {
      pinMode(D1,OUTPUT);                                         //Intializing pins for showing output and input
      pinMode(D2,OUTPUT);
      pinMode(D3,OUTPUT);
      pinMode(A0,INPUT);

      Serial.begin(9600);                                         //Start communication between the ESP8266-12E and the monitor window

      WiFi.mode(WIFI_AP);                                         //This ESP8266-12E is an AccessPoint
      WiFi.softAP("NodeMCU_js", "12345678");                      //Provide the (SSID, password)

      IPAddress myIP = WiFi.softAPIP();                           //Obtain the IP of the Server
      Serial.println("Server IP is: ");                           //Print the IP to the monitor window
      Serial.println(myIP);
      server.begin();                                             //Start the HTTP Server
    }

    void loop() {
      WiFiClient client = server.available();                     //Check if a new Client has connected to the server

    if (client) {
    Serial.println("A new Client has connected :)");

    for (int i=0 ; i<Max_Clients ; ++i){              //Acknowledges and sets up new clients
      if (NULL == clients[i]){
        clients[i] = new WiFiClient(client);          //nothing in clients[i] means it is a new client
        break;
        }
      }
    }

    for(int i=0 ; i<Max_Clients ; ++i){                           //For available clients
      if (NULL != clients[i] && clients[i]->available()){
        String request = clients[i]->readStringUntil('\r');
        Serial.println("The string of client "+String(i+1));    //Print client's message
        inputs[i] = request;
        Serial.println(inputs[i]);

        int duty[4];
        duty[i] = inputs[i].toInt();

        if (i == 0){
          analogWrite(D1, duty[i]);
          clients[i]->println("To client 1.\r");
        }
        if (i == 1){
          analogWrite(D2, duty[i]);
          clients[i]->println("To client 2.\r");
        }
        if (i == 2){
          analogWrite(D3, duty[i]);
          clients[i]->println("To client 3.\r");
        }

        clients[i]->flush();                                    //Waiting for transmission to complete
        clients[i]->stop();
       }
      }
     }                                                                 //void loop closure

Here's my client code (which will be same for all clients):

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    char ssid[] = "NodeMCU_js";
    char password[] = "12345678";

    WiFiClient client;                // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()

    IPAddress server(192,168,4,1);

    void setup() {
      pinMode(A0,INPUT);
      pinMode(D6,OUTPUT);

      WiFi.persistent(false);
      WiFi.mode(WIFI_STA);

      Serial.begin(9600);                 //Serial connection
      WiFi.begin(ssid,password);          //WiFi connection

      while (WiFi.status() != WL_CONNECTED) {         //Wait for the WiFI connection completion
        delay(500);
        Serial.println("Connecting...");
      }
      Serial.println("Connected.");
      client.connect(server, 80);   // Connection to the server
      }

    void loop() {

      if(WiFi.status() == WL_CONNECTED){   //Check WiFi connection status

        int sense = 200;
        client.println(sense+"\r");  //Client's message to the server
        String answer = client.readStringUntil('\r');         //Reading response from the server
        Serial.println("from server: " + answer);             //Printing the response
        client.flush();

        delay(3600000);
        }
      else{
        Serial.println("Error in WiFi connection");
        }
      }

On uploading this code, the Serial Monitor at the server shows:

>A new Client has connected :)
>The string of client 1
>nt8_t* BufferedStreamDataSource<TStream>::get_buffer(size_t) [with TStream = >ProgmemStream; uint8_t = unsigned char; size_t = unsigned int]
>The string of client 1

While the Serial Monitor at the client shows:

>Connecting...
>Connecting...
>Connecting...
>Connecting...
>Connecting...
>Connecting...
>Connecting...
>Connected.
>from server: To client 1.

I have no clue of the source of this error. Any help is appreciated.

Thanks in advance.

body:
I suspect the problem stems from the client side.  This line:

    client.println(sense+"\r");  //Client's message to the server

doesn't do what you think it does.

`sense` is a number (200).  `"\r"` is a string constant located at an address in memory.  When you add the two together you are not concatenating two strings, but you are adding 200 to the address of the string constant - and then sending whatever it finds at that location.

The "\r" is actually redundant anyway, since you are using `println` which adds `\r\n` to the end of a print. However if you do want to do it manually you just need to split it into two prints:

    client.print(sense);
    clienr.print("\r");


message:
I cannot upload any code to my arduino uno

I am using ardunio uno on a windows 10 machine.

I have never been able to upload any code whatsoever.

Every time i get different errors, sometimes it's about com port, sometimes about memory, baud rate and what not.

This time I am getting the following error.

What should I do next?

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Jayesh Patel\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982 -warnings=none -build-cache C:\Users\JAYESH~1\AppData\Local\Temp\arduino_cache_625197 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jayesh Patel\Documents\Arduino\sketch_jun21a\sketch_jun21a.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Jayesh Patel\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982 -warnings=none -build-cache C:\Users\JAYESH~1\AppData\Local\Temp\arduino_cache_625197 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Jayesh Patel\Documents\Arduino\sketch_jun21a\sketch_jun21a.ino
    Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Detecting libraries used...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "nul"
    Generating function prototypes...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\preproc\ctags_target_for_gcc_minus_e.cpp"
    "C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\preproc\ctags_target_for_gcc_minus_e.cpp"
    Compiling sketch...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp" -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp.o"
    Compiling libraries...
    Compiling core...
    Using precompiled core
    Linking everything together...
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982\sketch\sketch_jun21a.ino.cpp.o" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/..\arduino_cache_625197\core\core_arduino_avr_uno_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982" -lm
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.eep"
    "C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.elf" "C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.hex"
    Sketch uses 1030 bytes (3%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\JAYESH~1\AppData\Local\Temp\arduino_build_163982/sketch_jun21a.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: ser_open(): can't open device "\\.\COM5": The semaphore timeout period has expired.

    avrdude done.  Thank you.

    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

body: If you have arduino with ch340 you need to install driver for board.


message:
Averaging input from multiple input over a fixed amount of time (estimated)

I am trying to average input values for a number of inputs and have it then store those averages into a string to write to a txt doc on a sd card.

I am using:

<!-- language: lang-c++ -->

    // read 6 sensors and append to the string:
    for (int analogPin = 0; analogPin < 6; analogPin++) {
      int sensor = analogRead(analogPin);
      dataString += String(sensor);
      if (analogPin < 6) {
        dataString += ",";
      }
    }

to read the pins at the moment, but I want to change the analogRead(analogPin) to an average value and then use the averages to create the string.

but when I try to average the data I run into errors, or I get output that is 0 for something that should be higher (3.3V).

I am doing this to stabilize my values a bit better and remove jitter.

Any suggestions?

body:
This function will average readings on an analog pin, include it and use it in place of analogRead(...) and it should do what you want.

    int aveAnalogRead(int pin, int ave=10, int delayms = 0)
    {
        int tot = 0;
        for(int i=0; i<ave; i++)
        {
            tot += analogRead(pin);
            if(delayms) delay(delayms);
        }
        return tot/ave;
    }

in your loop():

    for (int analogPin = 0; analogPin < 6; analogPin++)
    {
       int sensor = aveAnalogRead(analogPin);
         <<do your work here>>
    }


message:
Cannot load anything from library

So I installed libraries through the Arduino interface (`Sketch` > `Include Library` > `Manage Library`). Then I check: `C:\Users\username\OneDrive\Documents\Arduino\Libraries`, and I confirm the new libraries are there.

However, when I compile I always get the error that Arduino cannot find the library, no matter which one I try to import.

I'm on Arduino 1.8.5, Windows. What am I missing?

body:
This was a problem with using your OneDrive folder.

[duskwuff wrote][1]:
> [This is a known incompatibility between the Arduino IDE and Microsoft OneDrive](https://github.com/arduino/arduino-builder/issues/254). A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.

The issue with OneDrive folders has been resolved as of version 1.8.6.

[https://www.arduino.cc/en/Main/ReleaseNotes][2]

> ARDUINO 1.8.6 2018.08.23
>
> [ide]
>
> * Updated arduino-builder to 1.4.0:
>  - parallel build (improve compile speed)
>  - better reuse of already compiled files
>  - **Windows: fixed build for sketch stored under OneDrive cloud folders**

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.

  [1]: https://arduino.stackexchange.com/a/53951/19409
  [2]: https://www.arduino.cc/en/Main/ReleaseNotes

  [1]: https://arduino.stackexchange.com/a/53951/19409


message:
Too many amps for Step motor

I have an adafruit motor shield and attached the Nema 17 stepmotor. Now the big problem is trying to power it without it overheating. I was originally using a 12v 6a power supply but quickly switched to a 12v 2a and then a 12v 1a. All of them still make the Nema stepper motor very hot.

I'm using the accelstepper and adafruit modules on the arduino to control the stepper motor. I noted that the magnets are all always on in my code which might explain why it gets hot but I need to maintain some form of torque for the system I'm developing.

I will attach code as that might be the problem. Is there a second device I need to attach to the adafruit motor sheild and the nema stepper motor.

    #include <AccelStepper.h>
    #include <MultiStepper.h>
    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_MS_PWMServoDriver.h"

    int ComControlValue = -1;

    /* Define pins for motor and define step motor function */
    const int SlowStepPerRev = 400;                              // Define slow speed constant
    const int MotorB = 2;
    int rpm = 60;                                                // Rotation per minute
    int acelspeed = 40;                                          // Acceleration speed
    int distrot = 200;
    int destinationunknown = 0;                                  // Destination of plate 1

    /* Initialize the stepper library on the motor shield */
    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_StepperMotor *myMotorB = AFMS.getStepper(SlowStepPerRev, MotorB);

    /* you can change these to SINGLE or DOUBLE or INTERLEAVE or MICROSTEP! */
    // wrappers for the motor!
    void forwardstepB() {
       myMotorB->onestep(FORWARD, INTERLEAVE);
    }
    void backwardstepB() {
       myMotorB->onestep(BACKWARD, INTERLEAVE);
    }

    AccelStepper stepperB(forwardstepB, backwardstepB);

    void setup() {
       Serial.begin(115200);                                     // Establish Serial connection to computer
       Wire.begin();                                             // join i2c bus as master
       AFMS.begin();                                             // Begin useage of conveyorbelt motor

       stepperB.setMaxSpeed(rpm);                                // Initialize max speed
       stepperB.setAcceleration(acelspeed);                      // Initialize and set speed of acceleration for spinning
    }

    void loop() {
       switch(ComControlValue){
            case -1: //wait
                Serial.println("Waiting for Command");
                Serial.println(stepperB.currentPosition());
                while (Serial.available()==0){}
                ComControlValue=Serial.parseInt();               // Pull value from serial port
                break;                                           // break loop & return to start
            /* 1 : Move plates into the system */
            case 1:
    // Arduino using accelmotor, move to position X
            if (plateNum < platelimit){
                   plateNum++;
                   ComControlValue= 11;                          // After establishing plate num & location, move to case 11 to start stepmotor movement
                   destinationunknown = destinationunknown + 200;
            }
            else {
                   ComControlValue = -1;                         // To many plates, cancel move command
            }
            stepperB.moveTo(destinationunknown);
            break;

            /* 2 : Move plate out of system */
            case 2:
            // Arduino using accelmotor, move to position Y
            if (plateNum > 0){
                   plateNum = plateNum--;
                   ComControlValue= 11;                         // After establishing plate num & location, move to case 11 to start stepmotor movement
                   destinationunknown = destinationunknown - 200;
            }
            else {
                   ComControlValue = -1;
            }
            stepperB.moveTo(destinationunknown);
            break;

            /* 1 : Run Stepmotor to completion */
            case 11:
            // Step motor requires an uninterrupted while loop to move to completion
            // code setup will utilize while loop and allow for movement
            stepperB.run();                                     // run stepmotor
            if (stepperB.distanceToGo() == 0 ){
                    ComControlValue = -1;                       // Completed movement, go back to case -1
            }
            break;
       }
    }

body:
Stepper motors get hot. It's a fact of life. More so when they are held stationary.

A [typical 12V Nema 17 stepper motor](https://www.ebay.co.uk/itm/Nema-17-Bipolar-40Ncm-12V-0-4A-Stepper-Motor-42x42x40mm-Reprap-CNC-Arduino-/121786531059) has a coil resistance of 30Ω per phase. With 12V across a single phase it will consume 0.4A.  That is the equivalent of about 4.8W of power. That comes out in the form of heat.

Reducing the current capacity of your power supply will not "fix" the problem. All that will happen is that as you go to lower and lower current supplies the supply will get hotter and eventually break.

You can test the coil resistance of your motors with a DMM set to the Ohms range, then calculate the power dissipation using:

    Current = V ÷ R = 12 ÷ <measured resistance>

and:

    Power = V² ÷ R = 144 ÷ <measured resistance>


body:
I think you will have a better chance reducing the heat by lowering the supply voltage (which will reduce the current as a consequence). You won't get the nominal torque if you go below 12V, but this is a compromise and there's no free cheese there.

Limiting the available current only works in a predictable manner with power supplies which can work as current sources. If your power supply is only a voltage source, then trying to draw more current than it can provide will eventually result in the power supply going into self-protection (not delivering any voltage) or breaking down. With voltage sources, maximum current is a limit **you have to respect**, not a limit the power supply will impose.


message:
fatal error: avr\wdt.h: No such file or directory in arduino due

I am using Arduino DUE for vehicle tracking gps/gprs device. Before using Arduino DUE I used Arduino UNO. When I am trying to load my code in Arduino DUE It shows me "fatal error: avr\wdt.h: No such file or directory". I can't delete watchdog from my code as it is so important for my device.
Now how can I solve this problem ?

body:
The Due is a very different board than the Uno. It uses a completely different architecture (ARM vs AVR). You can't use AVR-specific  code on an ARM chip, and the Watchdog code is AVR-specific.

You will have to find (or write) the equivalent ARM code using the Due's register set instead.