message:
Atmega328P - SCK pin

I am using Atmega328p with arduino bootloader in a project. There happens to be an LED connected on SCK pin. During Start (or restarts), the LED appears to flicker a couple of times (3 times to be exact). I don't want this to happen. I can change the connections but I would prefer a software solution because hardware change means a PCB modification.

I probed the SCK pin and I got some expected waveforms. There were two different cases:

1) When I powered the arduino using USB to serial programmer i.e. Tx Rx connected to a PC:

[![with UART connected][1]][1]

2) When I powered the arduino with an external power source (the case with my project):

[![Without UART][2]][2]

This is what I think:

1) [As mentioned in this thread](http://forum.arduino.cc/index.php?topic=204369.0), the bootloader has a piece of code which makes it act that way.
The bootloader code has a pin definition file which declares SCK pin as a LED and blinks it a couple of times to indicate that it has entered the bootloader. [I found the code here](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/optiboot/pin_defs.h):

    #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) || defined(__AVR_ATmega88) || defined(__AVR_ATmega8__) || defined(__AVR_ATmega88__)
    /* Onboard LED is connected to pin PB5 in Arduino NG, Diecimila, and Duemilanove */
    #define LED_DDR     DDRB
    #define LED_PORT    PORTB
    #define LED_PIN     PINB
    #define LED         PINB5

[Other relevant piece of code is here.](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/optiboot/optiboot.c)

In this case, changing the LED definition to PINB4 and burning the bootloader and program again should take care of the issue. However this didn't work out for me. This is what I did exactly:

a) Opened the file D:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\optiboot\pin_defs.h

b) Modified the PINB5 to PINB4 on line 6.

c) Saved the file, burnt the bootloader and then program.

d) Powered up the chip and tested whether I am getting those 3 pulses. I got those 3 pulses.

(Even though it didn't work, I am still going to try it a few more times just in case I might have made an error.) :(

2) This brings me to second thought that since atmega328 accepts code through SPI by default, it checks for incoming data by clocking the SCK pins 3 times during startup. In this case, a software fix won't do anything.

What do you guys suggest? Should I go for the PCB modification or is there still some hope left?

Ignacio pointed out that I can disable bootloader to get rid of the issue. I want to program the chip using arduino IDE (preferably via UART) but I can consider SPI as well in case everything else fails.

Note: I am not sure whether this post is more suited for EE or Arduino. In case you guys(mods) think I'd get better suggestions there, feel free to move my post to Arduino.

  [1]: https://i.stack.imgur.com/bU1DZ.jpg
  [2]: https://i.stack.imgur.com/JHWZC.png

body:
There is nothing in the default megaAVR initialization that causes SCK to behave in this manner; it is all caused by the bootloader.

Fortunately all you have to do to solve this is disable the bootloader. Unprogramming the `BOOTRST` fuse (ext:0) will cause execution to start at address 0 instead of the beginning of the bootloader on reset.


sender: user

sender: assistant

body:
I compiled Optiboot a while back using the shell script below. This is for Linux, you may need to adapt slightly for other operating systems.

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

    BIN_LOCATION='/home/nick/Development/arduino-1.6.5-r5/hardware/tools/avr/bin'

    $BIN_LOCATION/avr-gcc -mmcu=atmega328p \
        -D__AVR_ATmega328P__ \
        -DF_CPU=16000000L \
        -DBOOTLOADER_ADDRESS=7E00\
        -DBAUD_RATE=115200 \
        -DLED_START_FLASHES=0 \
        -DOPTIBOOT_FIX=1 \
        -Os \
        -gdwarf-2 \
        -fno-inline-small-functions \
        -fno-split-wide-types \
        -fno-tree-scev-cprop  \
        -fno-exceptions -ffunction-sections -fdata-sections \
        -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -fno-jump-tables  \
        -fno-keep-inline-functions -fno-common \
        -std=gnu99 \
        -Wl,--section-start=.text=7E00 \
        -Wl,--relax -nostartfiles \
        -Wl,--gc-sections \
        -ooptiboot.elf optiboot.c

    rm -f optiboot.hex

    $BIN_LOCATION/avr-objcopy -O ihex --set-section-flags=.eeprom=alloc,load \
        --no-change-warnings \
        --change-section-lma \
        .eeprom=0 \
        -R .eeprom optiboot.elf optiboot.hex

    $BIN_LOCATION/avr-objdump -j .sec1 -d -m avr5 optiboot.hex > optiboot.lst

You will need to find where your copy of avr-gcc and insert that into the first line above.

Notice I have changed the define for `LED_START_FLASHES` to be zero above. That should fix the issue.

To save you the trouble of doing that, I have made a "no blink" version for the Atmega328 and put it here:

<http://gammon.com.au/Arduino/optiboot_no_blink_atmega328.hex>

**Warning** - the script above compiled the "no blink" version OK, but using the latest version of the Optiboot.c code, and the latest compiler, makes a .hex file that is four bytes too long, for reasons I can't work out. However it compiles fine if you omit the blinks, because there is less code there.

---

Note re the LED on D13. Because the LED is driven by an op-amp (on the Uno), it will flash even with the above code. However that is because the op-amp has a high-impedance input. If you use a pull-down resistor on D13 it won't flash.

---

Now that I look at the download, it is so short I may as well include it here:

    :107E0000112482E08093C00088E18093C10086E065
    :107E10008093C20080E18093C40084B714BE81FFC8
    :107E2000C8D088E1809360008DE080936000259A3F
    :107E300018E108E033E0F32EEE24EA94DD24D39435
    :107E400045E0C42E51E1B52EA7D0813429F481E05C
    :107E5000BED083E09AD096C0823419F484E1B7D0C2
    :107E600091C0853419F485E0B2D08CC0853599F481
    :107E700093D0C82FD0E0D0930102C09300028CD0E1
    :107E80009E01382BC901880F991F9093010280939E
    :107E9000000297D077C0863529F484E098D080E03E
    :107EA00074D070C0843609F042C07ED0E0910002E8
    :107EB000F0910102F0925700E895C0E0D1E002C0D5
    :107EC0006BD089938C2F90910202C917C8F38C1B39
    :107ED00001C0E9929C2F980F9034D8F372D007B666
    :107EE00000FCFDCF40910002509101029A01A0E0F8
    :107EF000B1E08C911296FD013197608190E0962B54
    :107F0000F9010C01D0925700E89511242E5F3F4FE4
    :107F1000A038F1E0BF0769F7FA01C0925700E89571
    :107F200007B600FCFDCFB0925700E8952BC0843710
    :107F3000B1F43AD046D0E0910002F0910102CF01B5
    :107F40000196909301028093000284911ED080914B
    :107F500002028150809302028111EDCF13C0853758
    :107F600041F42FD08EE111D085E90FD08FE00DD0F4
    :107F700009C0813531F4109360000093600021D076
    :107F800001C01FD080E101D05FCF9091C00095FF6C
    :107F9000FCCF8093C6000895A8958091C00087FF0C
    :107FA000FCCF8091C6000895F7DFF6DF80930202D0
    :107FB000F3CFE0E6F0E088E180831082EE27FF2730
    :107FC0000994EADF803209F0F4DF84E1DECFCF9359
    :0C7FD000C82FE2DFC150E9F7CF91F3CFDA
    :0400000300007E007B
    :00000001FF

Just save that as optiboot.hex.


message:
I’m having a tough time trying to program 2 fsr sensors

[![This is how everything is connected][1]][1]Can anyone help me please?
I’m having a tough time trying to program 2 fsr sensors.                                                                                The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed?                     I have got only one to work by using this code:

    /* FSR simple testing sketch.

    Connect one end of FSR to power, the other end to Analog 0.
    Then connect one end of a 10K resistor from Analog 0 to ground

    For more information see www.ladyada.net/learn/sensors/fsr.html */

    int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
    int fsrReading;     // the analog reading from the FSR resistor divider

    void setup(void) {
      // We'll send debugging information via the Serial monitor
      Serial.begin(9600);
    }

    void loop(void) {
      fsrReading = analogRead(fsrPin);

      Serial.print("Analog reading = ");
      Serial.print(fsrReading);     // the raw analog reading

      // We'll have a few threshholds, qualitatively determined
      if (fsrReading < 10) {
        Serial.println(" - No pressure");
      } else if (fsrReading < 200) {
        Serial.println(" - Light touch");
      } else if (fsrReading < 500) {
        Serial.println(" - Light squeeze");
      } else if (fsrReading < 800) {
        Serial.println(" - Medium squeeze");
      } else {
        Serial.println(" - Big squeeze");
      }
      delay(1000);
    }

So what would be the correct code in order to get two sensors to work at the same time?

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

body:
Call your second FSR "fsr2" connect it to analog pin A1 and add to your existing code. Sort of like this:

    int fsrPin = 0, fsr2Pin = 1;     // the FSR and 10K pulldown are   connected to a0
    int fsrReading, fsr2Reading;     // the analog reading from the FSR resistor divider

    void setup(void) {
      // We'll send debugging information via the Serial monitor
      Serial.begin(9600);
    }

    void loop(void) {
      fsrReading = analogRead(fsrPin);
      delay(5);
      fsr2Reading = analogRead(fsr2Pin);

      Serial.print("Analog reading = ");
      Serial.print(fsrReading);     // the raw analog reading
      Serial.print("\t");
      Serial.print(fsr2Reading);


message:
Value of joystick reduces when I send it over serial

I've got two arduino cards and two bluetooth bluesmirfs. I am currently trying to read value from a joystick and send it over to the other arduino card and use that value to control my servo motor.

Here's my code.

           //Master Code
    void loop()
    {
        yVal = analogRead(yAxis);   (value between 0 and 1023)
      if(bluetooth.available())
      {

        bluetooth.print(yVal);
      }
      else if(Serial.available())
      {

        Serial.print(yVal);
      }
      delay(100);
    }

    //Slave code
    void loop(){
      while(Serial.available())
      {

        int c = Serial.read();
        Serial.print("Joystick value: ");
        Serial.println(c);
        int val = map(c, 0, 1023, 0, 255);
        Serial.print("Map value: ");
        Serial.println(val);

          myServo.write(val);
        }
      }

Am I doing something wrong? Instead of getting something between 0 and 1023 I get something below 50.

body:
A fundamental lack of understanding of how serial communications works is what you have.

Serial sends bytes. You are attempting to read an int. The two don't match. Not only that, but you are sending the value as text, not a number, so you're interpreting it as gibberish.

My suggestion: do the `map` on the master not the slave, and send a raw byte between 0 and 255 not a string of text between "0" and "1023".

    bluetooth.write(map(yVal, 0, 1023, 0, 255));


message:
Using an Arduino to drive a digital RGB LED strip

I recently purchased a 5M strip of digital RGB LEDs, that is compatible with the "Adafruit_NeoPixel.h" library.

Is maintaining the original order of the LEDs important?  Could I cut the strip in say four sections, and then reconnect those sections out of their original order?

Just to be clear these are digital 3-pin(+5V,DI,GRN) strips, not analog 4-pin(+12V, R, G, B) strips.

I'm just not finding good info regarding if the individual LEDs are pre-assigned an ID by the manufacturer, or if they somehow use a serial-timing way to assign IDs at startup.

Before digging through the Adafruit_NeoPixel.h, I wanted to see if I could get a quicker answer here.

THANKS!

body:
I can not find detailed information regarding the 5M LED strips you bought.

I have used [Adafruit addressable LED strips][1].  What Adafruit publishes on their web site helped a great deal when I cut my strips into smaller sizes.

Here is an Adafruit image which may help you:

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

I would think the order does not matter.  But you do need to connect the data such that "outs" go to "ins".  And you need to connect them in a row.  That is you need to connect them in one loop.

Added later...

Assuming we are using the [WS2812][3]:

[![enter image description here][4]][4]

We know from the specifications that the RGB data is encoded as 3 8 bit NZR (Non Zero Return) pulses.  8 bits for each color: red, green & blue.  That there is 1 such "word" of 24 bits for each pixel.  That the beginning of a set of "words" is marked by a 50us or grater interval where DI is zero.  And that each pixel strips off the first 24 bit "word" before passing the balance of the data on.

In other words, it doesn't matter what order WS2812 are assembled in.  Also that WS2812 have no idea where they are in the sequence.  All that matters is that each succeeding WS2812 gets its data from the previous WS2812.

One last note. The necessary timing is really fast and really tight. Can't be more than 150 billionths of a second off. No way can a multitasking platform like a PC, Mac or RaspberryPi pull this off.  When sending off a set of "words" to a string of pixels, the embedded processor will likely not be doing anything else!

  [1]: https://www.adafruit.com/products/1460
  [2]: https://i.stack.imgur.com/3iuFt.jpg
  [3]: https://cdn-shop.adafruit.com/datasheets/WS2812.pdf
  [4]: https://i.stack.imgur.com/XnVKD.jpg


message:
Do I need 3 voltage dividers to control ESP8266

I am buying an ESP8266 and the plan is to control it serially from an Arduino. I am going to use a voltage divider(Using a voltage divider is temporary and I know the cons of using voltage dividers).

I calculated out the values of the voltage divider and I am going to use 220 ohm and 440 ohm value resistors to get 3.3 volts and 250 ma from the Arduino 5v pin so I can power vcc and ch_pd on the ESP8266.

**The question** is do I need to use a separate voltage divider to connect Arduino TX to ESP8266 RX and Arduino RX to ESP8266 TX. Or will it be safe to connect RX and TX directly to Arduino RX and TX.

Honestly I am extremely new to this and I don't even know if I am going at this right. If I am tell me.

body:
The RX pin is 5V tolerant (at least it is on all of my boards!) and almost certainly your arduino will recognize 3V as logic high for the TX pin. So you don't really need any level conversions there (no other pin is 5V tolerant).

Are you sure your ESP8266 board doesn't already have a 5V to 3V3 regulator? I've never seen one!


body:
For **ESP 3.3V power supply**, I'd recommend a distinct 3.3V regulated supply.

Of course, the Arduino UNO already has a 3.3V output but it may not supply enough current to the ESP (current consumption can go up to almost 200mA): UNO 3.3V pin is limited to 50mA. So do not use it or you may roast your UNO.

Using resistors to output 3.3V from Arduino 5V might be possible (the UNO 5V pin can provide ~400mA) but it would be a big waste of energy because you'd have to use low resistor values to be able to supply 200mA for instance.

You might possibly use a 7833 regulator with additional caps to provide 3.3V from Arduino 5V pin (or `Vin` directly if your UNO is powered through the DC power jack, not USB)

For **ESP RX** a voltage divider is foreseeable but it may trigger issues due its switching response time, which may be too slow when transmitting data at high baud rates. I recommend using a [MOSFET based level shifter][1]:

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

The advantages of this circuit are:

- it has the fastest switching response time
- it can work in both directions (3.3V -> 5V and 5V -> 3.3V)

You can also buy some cheap [ready-made breakouts][3] using this circuit and offering several level shifters.

For **ESP TX**, I'd also recommend the same level shifter circuit as for RX (if you can make one, you can make two).

  [1]: http://www.hobbytronics.co.uk/mosfet-voltage-level-converter
  [2]: https://i.stack.imgur.com/DDKpm.jpg
  [3]: https://www.sparkfun.com/products/12009


message:
Is it safe to place a capacitor across vin and gnd?

I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

The ATX is gated by a relay on its DC side and seems to cause enough of a current drain that it causes the Arduino to reset.

I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

Standard?

EDIT:
Here's a very basic sketch..

[![12V Transformer powers arduino on VIN/GND pins, other pins a 5V, GND and control for relay][1]][1]

12V Transformer powers arduino on VIN/GND pins, other pins are 5V, GND and control for relay

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

body:
> I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

I don't entirely follow that wording. Please draw a picture.

> I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

470µF is fine. In this situation the bigger the better. If 470µF fixes it then 470µF is fine. Don't be afraid of going higher though. I have 3,300µF capacitors here that are commonly used for similar purposes.

What you have implemented is called a *reservoir* capacitor and is a common use for large value capacitors like that.


message:
IR sensor does not work well on carpets

I have facing a problem since long and cannot solve it. I built Arduino car and place 2 IR sensors shown in image, to check down distance to avoid falling from stairs. One is at back and other at front. On hard surface they work well but on carpet always give wrong reading like no object there which translates unsafe to move and my car stops. How can we solve this problem? I also tried Ultrasonic but it has same problem on carpets or fabric.

I tested this that on carpet it was giving a big distance reading but when I place a white paper, suddenly it was fixed and detected surface.

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

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

body:
You may have noticed that this product is no longer available from well known parts distributors like adafruit.com, sparkfun.com or trossenrobotics.com. I would recommend using a Sharp distance sensor designed for the distances you are interested in:
[![enter image description here][1]][1]
It is about 10 times the price, but produces a variable voltage that you can read with the Arduino's ADC.  Then you can compensate for floor irregularities in your code.

If you care to experiment, I obsurved that the better distance measurement devices angle the emitter and sensor to light up & observe the same spot at the desired operating distance:
[![enter image description here][2]][2]

You might try this with your current sensor.  However, it does not appear the manufacture left you enough lead length to make such an adjustment.

  [1]: https://i.stack.imgur.com/hZaWg.jpg
  [2]: https://i.stack.imgur.com/AOunj.jpg


message:
How do I pass an Int Array into void for a foreach loop?

I know its probably an odd question...but I found a workaround for a foreach loop in C. I have a whole bunch of int arrays that I would like to be able to pass into a void, which has that foreach loop in it. This is my code right now:

    int example[] = {1, 2, 3, 4, 5};

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

        #define foreach(item, array) \
            for(int keep = 1, \
                count = 0,\
                size = sizeof (array) / sizeof *(array); \
                keep && count != size; \
                keep = !keep, count++) \
            for(item = (array) + count; keep; keep = !keep)
        }
    }

    void Words (int w[]) {
        foreach(int *v, w) {
            Serial.println(*v);
            delay(500);
        }
    }

    void loop () {
        Words (example);
    }

However when I run it, it only returns the first number of the array, I need all 5 of them. I know theres all sorts of additional things that could be it, like the * or & symbol but I really don't understand what they do. Any ideas as to how to get that to work?

body:
What you want will not work the way you think: in C++ (just like in C), arrays and pointers are almost the same, and the compiler won't be able to make a distinction between

    void f(int* array)

and

    void f(int array[])

In particular, inside `f()` the compiler won't be able to know the actual size of `array`: for the compiler `sizeof array` will always be the same as `sizeof(int*)`, i.e. just the size of a pointer, always 2 bytes on Arduino UNO, whatever type it points to.

If you want your `foreach` macro to work correctly, you have to pass it the actual array count of items as an additional argument:

    #define foreach(item, array, size) \
        for(int keep = 1, \
            count = 0;\
            keep && count != size; \
            keep = !keep, count++) \
        for(item = (array) + count; keep; keep = !keep)

And also pass the count of items in `Words`:

    void Words(int w[], size_t size) {
        foreach(int *v, w, size) {
            Serial.println(*v);
            delay(500);
        }
    }

In `loop()` you can use `sizeof example`, because the compiler knows what its size is, from its initialization (an array of 5 integers, i.e. 10 bytes):

    void loop() {
        Words(example, sizeof example / sizeof example[0]);
    }

You could even define a macro to compute the count of items in an array:

    #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

It will work **as long as you use it with an argument that is completely known by the compiler**:

    void loop() {
        Words(example, ARRAY_SIZE(example));
    }

Important comments on your original code
========================================

You mentioned that you want to "*save space*", but defining a macro will not help in this regard, as a macro is **NOT** a function, hence **its *binary code* will be repeated everywhere it is used**. It can just help make your *source code* shorter and possibly clearer.

The way you defined your macro seems weird and overly complex to me: why use 2 `for` loops when you need only one?
It would have been possible to define it in a simpler way, for example:

    #define foreach(type, var, array, size) \
        for(type* var = array; var != array + size; var++)

It would be used as follows:

    void Words(int w[], size_t size) {
        foreach(int, v, w, size) {
            Serial.println(*v);
            delay(500);
        }
    }

Using C++ templates may probably help too, but this is an advanced topic. I'd recommend reading first some good book about C++ before digging into templates.


body:
Adding to the reasons why it's a bad idea to define that macro:

- If you want to keep your code readable, inventing syntactic sugar and implementing it with macros is the wrong way of going about it. If the language designers did not do provide a construct, there is probably a reason. This is particularly true if you are not a complete master of the language.

- Premature optimization is *always* a bad idea. First, modern compilers are very good about optimizing stuff. Second, unless you have measured the performance of your code in great detail and deemed the performance unacceptable, you are wasting effort and making the code harder to maintain. Third, what you *think* may be an optimization may result in worse code in a future version of the compiler, or in a different hardware architecture. The list goes on.

- Never use preprocessor macros unless there is no other way of doing what you want to do (there usually is). There are countless articles detailing why you should not, but here is a short summary: macros pollute the global namespace, are hard to test and thus hard to debug, have no type checking, introduce subtle (and not-so-subtle) bugs, obscure calling semantics, and generally make the code unreadable. That we are having this discussion here is proof enough :)

- In this particular example, you are relying on the fact that the array `example[]` is *defined* (meaning: declared and storage is allocated, and in this case initialized, for it) in the same translation unit as your macro. Had this not been the case, `sizeof` would not have worked

- If you want to inline code, use inline functions. If you want to define constants, use `const`. And so on.

In your case, you are far better off declaring your arrays as `vector<int>` and using either iterators or the *range for* in combination with *auto* type declarations:

    #include <vector>
    std::vector<std::vector<int>> example = {
      {3, 1, 4, 1, 6},
      {2, 7, 1, 8, 2, 8, 1, 8},
      {5, 7, 7, 2}};

    ...

      for (auto v: example) {
        for (auto i: v) {
          // do something with i
        }
      }

Isn't this a lot more readable than your foreach macro?

Needless to say, you need to make sure that your tool chain supports C++11; the 1.6.7 version of the Arduino IDE running on Linux definitely does.

Obviously, there are occasional reasons to break the rules I mentioned above, but until you know *exactly* what you are doing, it's better not to.


message:
Code doesn't seem to work when trying to program 2 sensors

[![][1]][1]Can anyone help me with this issue

I'm trying to program two FSR sensors through typing this code but I've realized that one is working instead of two.

The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed. I have got only one to work by using this code.

The first sensor is connected to the A0 pin on the arduino and the second sensor is connected to the A1 pin

This is the code that I've written

    /* FSR simple testing sketch.

     Connect one end of FSR to power, the other end to Analog 0.
     Then connect one end of a 10K resistor from Analog 0 to ground
     For more information see www.ladyada.net/learn/sensors/fsr.html */

    int fsrPin = 0;
    int fsr2Pin = 1;   // the FSR and 10K pulldown are connected to a1
    int fsrReading ;
    int fsr2Reading;   // the analog reading from the FSR resistor divider

    void setup(void) {
        // We'll send debugging information via the Serial monitor
        Serial.begin(9600);
    }

    void loop(void) {
        fsrReading = analogRead(fsrPin);
        fsr2Reading = analogRead(fsr2Pin);

        Serial.print("Analog reading = ");
        Serial.print(fsrReading);
        Serial.print("\t");
        Serial.print(fsr2Reading);

        // We'll have a few threshholds, qualitatively determined
        if (fsrReading < 10) {
            Serial.println(" - Nothing");
        } else if (fsrReading < 200) {
            Serial.println(" - Light");
        } else if (fsrReading < 500) {
            Serial.println(" - Lightness");
        } else if (fsrReading < 800) {
            Serial.println(" - Medium");
        } else if (fsr2Reading < 1100) {
            Serial.println(" - No-Pressure");
        } else if (fsr2Reading < 1400) {
            Serial.println(" - Light-touch");
        } else if (fsr2Reading < 1700) {
            Serial.println(" - Light-squeeze");
        } else if (fsr2Reading < 2000) {
            Serial.println(" - Medium-squeeze");
        } else {
            Serial.println(" - Big-squeeze");
        }
        delay(1000);
    }

So could anyone tell how to edit this code correctly in order to get two sensors to work?

The one connected to the A0 pin is working but not the other
[![This how its physically connected][2]][2]

  [1]: https://i.stack.imgur.com/94ZrE.jpg
  [2]: https://i.stack.imgur.com/XnXzJ.jpg

body:
As JFPoilpret says you if logic is wrong.
It might make it easier if you took that whole if block out and made it into a function that accepted the value from the sensor as a parameter.

    void CheckReading(int reading)
    {
        if (reading < 10) {
            Serial.println(" - Nothing");
        } else if (reading < 200) {
            Serial.println(" - Light");
        } else if (reading < 500) {
            Serial.println(" - Lightness");
        } else if (reading < 800) {
            Serial.println(" - Medium");
        } else {
            Serial.println(" - Big-squeeze");
        }
    }

Notice that the values only go up to 800, going larger than 1023 won't work anyway.


body:
Try changing the pins to use A0 and A1, as pins 0 and 1 relate to the digital pins.

    int fsrPin = A0;
    int fsr2Pin = A1;   // the FSR and 10K pulldown are connected to a1

As has been mentioned by Matt, make sure you also only test for values between 0 and 1023.

You are also missing the pinMode, which sets the pins as input/output in the setup function

    void setup(void) {
        // We'll send debugging information via the Serial monitor
        Serial.begin(9600);
        pinMode(fsrPin, INPUT);
        pinMode(fsr2Pin, INPUT);
    }


body:
@Rich1234
I have taken your code, JFPoilpret's, Holmez's and my answers and put them altogether.  Hopefully this explains what we mean and will give you something to work from.  It does compile, but I don't know if it works, because I don't have two sensors to try it with.  The code is by no means perfect, but its a start.  If there are any problems, give us a shout.

    /* FSR simple testing sketch.
     Connect one end of FSR to power, the other end to Analog 0.
     Then connect one end of a 10K resistor from Analog 0 to ground
     For more information see www.ladyada.net/learn/sensors/fsr.html */

    const int fsrPin = A0;  // Change to A0 so it refers to the correct pin
    const int fsr2Pin = A1;    // Change to A0 so it refers to the correct pin
    // int fsrReading ;  // Change Not required
    // int fsr2Reading;    // Change Not required

    // Function  : Read the data from the pin and write a meaningful description to the serial output.
    // Parameters  : The analog pin to read from.
    // Returns   : The value read from the pin
    int checkReading(int pin)
    {
     const int reading = analogRead (pin);  // Get the reading from the pin. (const because it won't change within the scope (life) of this function)
     Serial.print(reading);
     Serial.print(" - ");
        if (reading < 10) {
            Serial.println("Nothing");
        } else if (reading < 200) {
            Serial.println("Light");
        } else if (reading < 500) {
            Serial.println("Lightness");
        } else if (reading < 800) {
            Serial.println("Medium");
        } else {
            Serial.println("Big-squeeze");
        }
     return reading;
    }

    void setup(void) {
        // We'll send debugging information via the Serial monitor
        Serial.begin(9600);
        pinMode(fsrPin, INPUT);  // Change to define the pin 'direction'
        pinMode(fsr2Pin, INPUT);
    }

    void loop(void) {

        Serial.print("Analog reading A0 = ");
        checkReading(fsrPin);
        Serial.print("Analog reading A1 = ");
        checkReading(fsr2Pin);

        delay(1000);
    }


message:
Is it possible to have an array of int arrays?

I have a huge number of arrays, each with a series of numbers each referring to an LED on a strip. I want to be able to address each one by a number, so the logical solution to that for me was to make the whole thing into an array. Can that be done, or is there a better work around that can be implemented?

body:
Yes you can have arrays inside arrays.

The array would be declared as:

    int arrayName [ x ][ y ];

where `x` is the number of rows and `y` is the number of columns.

The example below declares and initializes a 2D array with 3 rows and 10 columns:

    int myArray[3][10] = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 },
                           { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 },
                           { 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 } };

To access the value of 27 (and save it into myValue):

    myValue = myArray[2][6];


message:
How to import data from SDcard on Arduino to the computer using Arduino serial/COM port?

I have Arduino UNO with Adaruit wifi shield. I store some data on the sd card successfully and now I need to import that data on to the computer.

I am sending some token, say "1", to the UART port of Arduino (COM port), there is a code written on the Arduino which responds to that token and sends data (byte by byte) in the bulk amount on the serial of the Arduino. I have to accept bytes and store in a file on the local machine (computer) and upload to the server ultimately at the same time.

(It will be good if the process has the browser support i.e I will send request from web browser to API and that API will connect to serial port/ COMP port of my Computer and somehow the file will be created on the local machine and the data from the Arduino will be saved in that file; the file created will be uploaded to the server ultimately.)

What is the proper way to this, is there any API or software for it?

Please help me out.

Thanks in advance!

body:
There is an example for the ESP8266 (using the Arduino IDE) called SDWebServer which might give you some ideas, I would suggest you try it but I doubt the libraries would work on an Arduino.

If you are going to support a web API, I would suggest you implement a REST API on the Arduino, that is a commonly used API for these type of things.

 1. The client (PC) sends a HTTP GET request to the server (Arduino) with the token you want.
 2. The server responds with the data the token corresponds to.

You are using standard HTTP (you can do it through a browser), so it should go through firewalls without a problem.  Its a very common format, there are plenty of tools to debug it and tutorials for all sorts of platforms that you should be able learn from.

The problem is REST API isn't the best solution for Serial comms, I'm not saying its impossible you could send the network messages via serial, but it wouldn't be pretty.  I think you would be better keeping your custom interface for the serial and moving as much of the code into common functions so you can share it between the two interfaces.

Hope that helps


message:
Use of two external power sources for a power cell - charger

I have a [SparkFun Power Cell - LiPo Charger/Booster] and want to use the external 5V charge capability. Now my question:

Can I directly hook up a DC jack (for a 5V power supply) **and** an [inductive charging circuit] to the external charge pins of the Sparkfun Power Cell LiPo Charger Module or should I use a slide switch so that **either** the power supply via the dc jack **or** the inductive charging module can power the Sparkfun Power Cell LiPo Charger? I prefer the first option, but I have concerns that the inductive charging module is damaged when for example the power supply is hooked up...

Have anybody experience with an similar setup?<br>
Thank you in advance for your answers.

[SparkFun Power Cell - LiPo Charger/Booster]:https://www.sparkfun.com/products/11231

[inductive charging circuit]: https://www.adafruit.com/product/1407

body:
A switch would be the best way of preventing damage, but you could also use diodes to prevent power flowing back to the PSU or Inductive circuit.

I tried something similar once using transistors to prevent both circuits operating at the same time, but never managed to get it to work.  You could practice any solutions on a breadboard with some LEDs.


message:
Can I use Arduino Nano V3 to program another arduino (Pro Mini)?

I was planning to buy serial to USB converter (FT232RL) to be able to program Arduino Pro Mini.
But the shop nearby offers Arduino Nano V3 at almost the same price.
Could I use this Arduino instead (and gain new microcontroller platform for free ;-)?

body:
**Yes!**

Yes, you can substitute the Arduino Nano V3 for the Arduino Uno and follow the instructions [here][1], providing that the Arduino Pro Mini is a 5V version. (Otherwise, you will have to do some voltage conversion.)

Both boards have the same SPI pins as the Arduino Uno. The connections would be as follows:

Arduino Nano --> Arduino Pro Mini
5V  ------------------->  Vcc
GND  ---------------->  GND
D10  ----------------->  RESET (10uF between RESET & GND)
D11  ----------------->  D11
D12  ----------------->  D12
D13  ----------------->  D13

The process detailed in the link can be summarized as follows:

1. Load the `ArduinoISP` sketch into the Arduino that you will use as programmer. You find it under `Examples` > `11. ArduinoISP` > `ArduinoISP`.
2. Select the serial port of the Arduino Nano (target): `Tools` > `Port` > corresponding port number.
3. Wire up the two Arduinos as described.
4. In the `Tools` menu, set the programmer to the `Arduino as ISP`.
5. Select the target board: `Tools` > `Board` > `Arduino Pro Mini`.
6. Open the program to be loaded to the Arduino Pro Mini and program it by selecting `Sketch` > `Upload using programmer`

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP


message:
Arduino IDE menu doesn't display properly (missing letters)

I have just installed newest version of Arduino 1.7.10 from arduino.org.

It has this problem that its menu are not displaying properly - when I hover mouse over items in menu they either disappear completely or some of the letters are missing. Sometimes the whole menu (like 'tools' menu) won't even display. Dialog windows (like "Do you want to save your changes") also suffer from this problem.

I have Windows 7 and I just installed newest version of Java to see if this helps, but it doesn't.

Have any of you had such problem?

body:
I've never had this problem, but here are some things you might want to look at.

 - Did you install it from an administrator account and use "run as administrator"?  If not, uninstall and reinstall.
 - Its possible that you are missing a font, god knows which one.  Go and look at the Arduino source on GitHub(?) and find any TTF files and install them.
 - Does this version support Windows 7?
 - What version did you have previously? Did you uninstall it before installing this?
 - If you didn't have a version before this one, uninstall this version go and get 1.5 or 1.6 and install that, then install 1.7 over the top.

Good luck, and keep monitoring the Arduino.org forums because if it is a problem with the app then they will start screaming quite quickly.


message:
System Is not Functioning Error. Windows XP, Arduino Uno R3, C# Listen SerialPort

Can anyone help me with this issue.

We created an arduino project. We listen microswitch.
If switch click, Arduino send basic serial data.
And C# application read serial port.

This solution is working but after more times (3Hours, 5Hours,..) system stoped.
Error message is "a device attached to the system is not functioning"
Solution: Usb remove and retry plug system is going to running.

We are try putty.exe maybe problem C# project but don't working.

If microswitch click don't flash "TX" or "RX" led.

    const int button = 3;

    uint64_t bounceTime = 50;
    uint64_t holdTime = 250;
    uint64_t doubleTime = 500;

    uint64_t lastReading = LOW;
    uint64_t hold = 0;
    uint64_t single = 0;

    uint64_t onTime = 0;
    uint64_t lastSwitchTime = 0;

    void setup() {
     pinMode(button, INPUT_PULLUP);
     Serial.begin(9600);
    }

    void loop() {

     int reading = digitalRead(button);

     if (reading == HIGH && lastReading == LOW) {
       onTime = millis();
     }

     if (reading == HIGH && lastReading == HIGH) {
       if ((millis() - onTime) > holdTime) {
         hold = 1;
       }
     }

     if (reading == LOW && lastReading == HIGH) {
       if (((millis() - onTime) > bounceTime) && hold != 1) {
         onRelease();
       }
       if (hold == 1) {
          delay(5000);
          reading = digitalRead(button);
          if(reading==LOW){
                  Serial.println("B");
          }
         hold = 0;
       }
     }
     lastReading = reading;

     if (single == 1 && (millis() - lastSwitchTime) > doubleTime) {
       single = 0;
     }

    }

    void onRelease() {
     if ((millis() - lastSwitchTime) >= doubleTime) {
       single = 1;
       lastSwitchTime = millis();
       return;
     }

     if ((millis() - lastSwitchTime) < doubleTime) {
       single = 0;
       lastSwitchTime = millis();
     }

    }

body:
I assume that by "USB" you mean "USB-to-serial adaptor".

Try running the same code without any serial communications, just have an LED do the equivalent of printing, and power it from a good power supply. If it runs for more than five hours, the problem is with the USB adaptor and/or your PC (Windows XP? Really?), and hence not relevant to this forum.

If the code crashes, then maybe you have a marginal board, or there is some other environmental factor that's giving you trouble. The code looks OK on first glance.


message:
Networking multiple Arduino Megas and updating their programs from one master

Is it possible to link multiple Arduino Megas using RS485, for example, and update the program on client Megas from one master Mega, as well as for them to communicate with each other? Whilst I found multiple examples of networks, nothing comes up for programming the boards other than through a PC

Thanks for any pointers!

body:
In principle, yes, you can do it. It's what existing bootloaders do -- they take code over the serial port, or USB, load it to flash, and then branch to it. Not to mention OTA.

So yes, you can modify the bootloader to use different pins, talk rs485, come up with code-integrity checks, specify particular bit patterns to signal "reboot" or "now load new code", and so on. If you have enough flash, you can even keep two copies, a working and a new, like most OTA code does.

I am not aware of a ready-made library that does that. If I wanted to roll my own, I would start by studying the OTA code.


message:
Arduino Serial Monitor works but not on PySerial and PuTTY

I made simple custom arduino board using an atmega328p and the PL2303 serial to USB chip.

In my arduino program, I am in a loop that sends out a string continuously. I can read this in the Arduino serial monitor with a baudrate of 9600. However, in my python program using the pySerial library, the readline function doesn't return anything. I checked using PuTTY but it still doesn't do anything.

Now I tried messing with the serial settings and found out that these lines of code work (the readline returns the string) if I call it in the exact same order.
<!-- language-all: lang-cpp -->

    ser = serial.Serial(comm_port)
 ser.xonxoff = True
 ser.rtscts = True
 ser.dsrdtr = True
    ser.readline()

However, the code below doesn't work

    ser = serial.Serial(comm_port, xonxoff=True, rtscts=True, dsrdtr=True)
    ser.readline()

What could be causing this? My guess is somehow I've switched the datalines in my USB cable and that the arduino serial monitor handles this somehow.

Another thing to note is that I couldn't program the Arduino the normal way via USB. I always have to program it using the ICSP port and a USBasp programmer.

body:
I wrote a python application which communicated with an arduino and for some reason I had to insert a delay after opening the serial for it to work correctly, if I didn't the first data I sent would always get dropped. Perhaps that's what's occuring here? Setting the attributes of the serial connection like that is probably slower than doing it in initialisation.

For myself I found that a delay of 3 seconds was what I needed for it to work 100% correctly on all computers (on some a second was enough). You only had to wait after opening it once open it worked fine.

To do a delay import the time module and use the sleep function which takes an argument of seconds.

    import time

    time.sleep(3)

Also worth noting depending on your application it's worth setting a timeout value for the serial that's appropriate or just keeping it open with the timeout paramter.

     ser = serial.Serial(com, 115200, timeout=0)

If you do this make sure to close it when you finished with it though (I personally used a try finally block which makes sure its always closed).

    try:
      ser = serial.Serial(com, 115200, timeout=0)
      #go nuts with whatever communicating your doing
    finally:
      ser.close()

I'm afraid I can't really tell you what caused the issue though. I also realise that this question is quite old so I hope my answer is still helpful, if not to you then to someone else who stumbles across it. To note for future the people on the official Arduino forum may be of more help for arduino related questions in general.


message:
Send information (such as a string) over digital pins

I wan't to send information from my arduino digital pins to another arduino's digital pins like a string, or a char. Can I do this without something like Software Serial?

The reason I am asking is because I am wanting to send information from several serial devices to my raspberry pi from an arduino. Thing is, that Raspberry pi only has one set of UART pins, so I was thinking because I have extra arduino uno's, why not send then information to the arduino and have it write the received information to the raspberry pi's digital pins..

Now that I am writing this, I think I will connect the 2 arduinos via a serial connection, and use software serial to write out to the raspberry pi, in three different stages, to get the information to the pi.

The reason I am using the PI is I want to display this information on a large screen with many different options, in short the GPU capabilities are what I am using the PI for, that and Processing.

**Question still stands though, can you send information over digital pins?**

body:
The RaspberryPi is a fairly complete linux computer.  As such it can be a USB Host to many USB Devices.  If you need more serial ports simply buy [FTDI equipped USB to serial cables][1], plug them into a USB hub and plug that into the RaspberryPi.
[![enter image description here][2]][2]

  [1]: https://www.adafruit.com/products/954
  [2]: https://i.stack.imgur.com/ykCtt.jpg


body:
There are many different ways of communicating.

In addition to serial you can use a protocol like SPI or I²C. If the Arduino are in close proximity I²C enables many devices to communicate on a common bus.


body:
Yes, you can send information to/from your arduino digital pins using a method called Bit Banging. [Wikipedia][1] (lots more on Google!)

You can use the Arduino to output as an ad hoc serial port or parallel port. The serial could be asynchronous (UART/RS232/I2C) or synchronous (such as SPI).

The down side is you will have to write a fair bit more software to send/interpret the data.

From your description I gather that data is only going one way - from the Arduino to the Pi. I personally would bit bang SPI as I think this would be the easiest and would not require exact timing.

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


message:
Power supply change change gps readings?

I was powering a GPS Sensor from the 3v3 pin of a raspberry pi and my reading for my GPS sensor had some strange symbols in the mix, but when i switched to the 3v3 on the arduino, my reading came back to normal. This wasted several hours of my time.

Any idea why i would get weird readings when using a different power source?? (even though it is the same voltage)

Note: Both the raspberry pi and the arduino are getting their power form the USB that is connected to my PC.

body:
The Pi can only supply ~50mA from 3.3V. This is unlikely to be enough to run GPS.

In addition USB can only supply 500mA. This is marginal at best, and below the recommended minimum for Pi.


message:
My Arduino UNO turns LED ON forever when I connect it to my Laptop

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

My Arduino UNO Board keeps the LED light turned on forever whenever I connect it to my PC. And, when I try to upload even a sample sketch, it says `avrdude: stk500_recv(): programmer is not responding`.

How can I fix this error?

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

body:
When you connect the device, if you hear the Windows "found device" sound, then you need to check your COM port driver, as it's very likely that the COM port number may have changed. On your Desktop or in File Manager, right click "This PC" or "My Computer", and select "Manage" from the submenu.  That will bring up the Computer Management console. On the left, select "Device Manager".  That will bring up your list of devices. In the list look for "Ports (COM & LPT)".

[![Device Manager - Ports][1]][1]

If you don't see, "Ports", then click "View" and check "Show hidden devices".  If this is the only Arduino that you've ever used, you should only see one listing. Make note of the COM Port Number the driver is using. *It's possible that the port number may have changed since you first used the device. Plug-n-play will do this if you plug the cable into a different USB port that may be using a different USB controller, etc.*

Then in your Arduino IDE, click "Tools", then expand "Boards" and select "Arduino/Genuino UNO" board, then re-click "Tools", and hover over "Port", and select the port number that is assigned to the Port that you found in Device Manager.

If that doesn't work, then you may have a problem with your driver.  Some of the "cheap chinese board" use a different FTDI chipset, so the plug-n-play windows driver may not work. In that case, the manufacturer should point you to the correct driver. Download their provided driver, then you can update the driver in Device Manager.

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


message:
error: invalid conversion from 'char' to 'char*' [-fpermissive]

I have written a simple code to read data from capacitive keypad and display it on LCD.

I am getting the data from keypad in following data structure.

    char phoneNumber[PHONE_DIGITS];

 and then displaying the data on LCD as

       LcdString(phoneNumber[i]);

where my LCD string function is

    void LcdString(char *characters)
    {
      while (*characters)
      {
        LcdCharacter(*characters++);
      }
    }

There is a type cast error

>  error: invalid conversion from 'char' to 'char*' [-fpermissive]

How can I debug it?

body:
You're calling your function with a single char, specified by phoneNumber[i], but your function is expecting an array.

If you change your call to:

    LcdString(phonenumber)

then that will pass the entire array.

Are you trying to say that you're storing multiple phone numbers?  i.e. a two dimensional array?  Check out the String reference for more details: https://www.arduino.cc/en/Reference/String


message:
Bluetooth sending values from two joysticks

Is there any good way of sending values from two joysticks from arduino A to arduino B? I tried sending using if statements, so if the Y- or X-axis' value changed then it would send that, but the servo motor on Arduino B went a little bit crazy.

Here's what I've done so far:

    //Master Code
    void loop()
    {
          yVal = analogRead(yAxis);   // read the value of the Right Joystick (value between 0 and 1023)
          yMap = map(yVal, 0, 1023, 0, 255);
          xVal = analogRead(xAxis);     // read the value of the left Joystick (value between 0 and 1023)
          xMap = map(xVal, 0, 1023, 0, 110);

      if(Serial.available() && !(xVal > 505 && xVal < 510)){
          Serial.print('X');
          delay(10);
          Serial.write(xMap);
          }
      if(Serial.available() && !(yVal > 500 && yVal < 520)){
          Serial.print('Y');
          delay(10);
          Serial.write(yMap);

        }
        delay(10);
    }

And the Slave code:

    //Slave code
    void loop(){
      while(Serial.available())
      {
        c = Serial.read();
        delay(5);
        val = Serial.read();
        if(c == 'X'){
            digitalWrite(13, LOW);
            myServo.write(val);
        }else if(c == 'Y'){
            digitalWrite(13, HIGH);
        }
        }

    }

Edit: I was thinking that maybe I should do something like a start and stop bit for X and Y?

Edit2: I wrote an if statement in Arduino B because it was reading the value -1, I don't know why, but after the if statement the servo motor hasn't been going crazy and the program works now. I still would like to know if I can do this in a better way. Thanks in advance!

body:
When using the ADC to control servos I get much better results when I process the ADC values through an [exponential smoothing][1] function:

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

There is less jitter.  However there is more lag.  You can tune the function by changing alpha between 1 (no history, effectively no smoothing at all) to 0 (no new data is averaged in, effectively not changing).  Pick 0.5 to start with.  If there is too much jitter pick smaller numbers until the jitter is reduced and the lag is still tolerable.

  [1]: https://en.wikipedia.org/wiki/Exponential_smoothing
  [2]: https://i.stack.imgur.com/YsqRL.png


body:
#Arduino A
You can read the values from two joysticks as normal and send it like this. This method ensures of no data loss. Ensure that you read the values and store them in appropriate variables and then send it over serial.

    // Setting Sensor pins
    const int potPin = A0;
    const int pot1Pin = A1;

    // Creating variables
    uint8_t pot;
    uint8_t pot1;

    void setup() {
    // Declearing the pinModes' for sensors
      pinMode(potPin, INPUT);
      pinMode(pot1Pin, INPUT);
    // Begining Serial Communication
      Serial.begin(9600);

    }

    void loop() {
    // reading from the sensors
      pot = map(analogRead(potPin),0 ,1023, 0, 255);
      pot1 = map(analogRead(pot1Pin),0 ,1023, 0, 255);

    //Packing the Serial message
      Serial.print("U*"); //A header
      Serial.print("A");  //a token to indicate the message payload
      Serial.print(pot);
      Serial.println("");

      Serial.print("U*"); //A header
      Serial.print("B");  //a token to indicate the message payload
      Serial.print(pot1);
      Serial.println("");

    }

#Arduino B
After the data are packed and sent over the serial. You need to unpack it with the other Arduino/device

The code will look like this:

    String data; //Store each line of Serial communication
    String pot1String = "0", pot2String = "0";
    float pot1, pot2;
    void setup()
    {
      //initialize Serial communication
      Serial.begin(9600);
      //read first package
      if (Serial.available() > 0)
      {
        data = Serial.readStringUntil('\n');
      }
      //Disregard the first reading
      data = "0";
    }

    void loop() {
      //start reading from serial
      if (Serial.available() > 0)
      {
        data = Serial.readStringUntil('\n');
      }
      String payload = "";
      if (data != "0")
      {
        int offset = data.indexOf("U*"); //This is the header (0x552A)
        if (offset >= 0)
        {
          payload = data.substring(offset + 3, data.indexOf('\n'));
          char value = data.charAt (offset + 2);
          switch (value)
          {
            case 'A':
              pot1String = payload;
              break;
            case 'B':
              pot2String = payload;
              break;
          //Add more case as the project grow
          }
        }
      }
      //convert strings to float
      pot1 = pot1String.toFloat();
      pot2 = pot2String.toFloat();

    // Continue with the rest of your project

    }

- Make sure to use the same baud rate in both sketches

Hope this helped. Ask me if you have farther questions


message:
How do you extend the wires from the arduino board to both fsr sensors to be placed on both chairs (one for each)

I’m trying to figure out how to extend the wires for both force sensitive resistors so that it could be place on each chair, one sensor on one chair and the other sensor on the other chair

This is how this was originally connected

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

So what would be the best way to extend both cables to place both sensors on each chair

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

body:
In ADC sampling there will always be noise.  Longer cables may increase that noise.  Sensors with lower resistance tend have less noise.  For these reasons it would be better to start from a schematic, part numbers and / or specifications rather than a picture.

There are a number of ways to reduce noise.  Hardware solutions include twisted pair and shielded cables.  Software solutions include averaging multiple samples and removing outliers.

If all you are asking is if you can use longer cables, the answer is yes as long as you can tolerate the or compensate for additional noise if any.


body:
In order to extend the wires you will need:

- [Crimp Connector Housing][1]
- [Female Crimp Pins][2]
- [Male Crimp Pins ][3]
- [Stranded Wire: 30 AWG][4]

and if you want to do a better job than bread board then you can use a [Strip board][5] to solder your resistors on and some [headers][6] to connect your wires.

You should not get any noise in ideal situation.

I don't know where you from so I just posted the links to the store I usually buy from. you can find these items on ebay or similar. Plus you will need a [crimping tool][7] as well.

  [1]: http://core-electronics.com.au/0-1-2-54mm-crimp-connector-housing-1x1-pin-25-pack.html
  [2]: http://core-electronics.com.au/female-crimp-pins-for-0-1-housings-100-pack.html
  [3]: http://core-electronics.com.au/male-crimp-pins-for-0-1-housings-100-pack.html
  [4]: http://core-electronics.com.au/stranded-wire-red-30-awg-100-feet.html
  [5]: http://www.ebay.com.au/itm/5Pcs-Double-Side-5x7cm-Printed-Circuit-PCB-Vero-Prototyping-Track-Strip-Board-SY-/252324587520?hash=item3abfb7a800:g:9EIAAOSwHgVW7ENM
  [6]: http://core-electronics.com.au/10-pcs-40-pin-headers-straight.html
  [7]: http://core-electronics.com.au/crimping-tool-0-08-0-5-mm-capacity-20-28-awg.html


message:
How to calculate the needed voltage and current to supply for Arduino

I have Arduino MEGA and I'm connecting to it 5 servomotors.

    { 3 TowerPro M995
    Basic Information

    Modulation:  Digital
    Torque:  4.8V: 130.5 oz-in (9.40 kg-cm)
    6.0V: 152.8 oz-in (11.00 kg-cm)

    Speed:  4.8V: 0.20 sec/60°
    6.0V: 0.16 sec/60°

    Weight:  1.94 oz (55.0 g)
    Dimensions:
    Length:
    1.60 in (40.7 mm)

    Width:
    0.78 in (19.7 mm)

    Height:
    1.69 in (42.9 mm)
    Motor Type:  3-pole
    Gear Type:  Metal

    2 Towerpro M996R

    Basic Information

    Modulation:  Digital
    Torque:  4.8V: 130.5 oz-in (9.40 kg-cm)
    6.0V: 152.8 oz-in (11.00 kg-cm)

    Speed:  4.8V: 0.19 sec/60°
    6.0V: 0.15 sec/60°

    Weight:  1.94 oz (55.0 g)
    Dimensions:
    Length:
    1.60 in (40.7 mm)

    Width:
    0.78 in (19.7 mm)

    Height:
    1.69 in (42.9 mm)
    Motor Type:  3-pole

    }

So how can I calculate the voltage and current needed to supply this Arduino?

body:
Voltage is simple - a device has a requirement and that is what you have to provide. In the case of the servos that is a range of voltages that it can use. So 5V is a good voltage.  The Arduino can take 5V if you feed it in to the 5V pin or the USB port, or 7-12V if you feed it in to the barrel jack.

The current you cannot calculate. You haven't provided enough information. The calculation, when you have the information, is quite simple: for all the devices on the same power supply add the currents requirements together. The supply has to be able to provide *at least* that amount of current.


body:
Drive all your components simultaneously from an external supply at appropriate voltage. Measure current draw in series (set your multimeter's red cable on the 10A port and set it to 10A, and connect red to VOUT, black to ground). Don't hold the wires in your hands, use clip-ons. Let it run for a while, and pay attention to current fluctuations. Read the current requirements on the display. A power supply with a bit more amperage than necessary is a Good Thing(tm).

Edit: remember to get both normal load and stall measurements. It is wise to add some way of turning stalling motors off, since stalling is motor death. And sometimes power supply death - those segway-for-kids things come to mind (and make me snicker ... WHEN I WAS A CHILD WE HAD OUR FEET FOR TRANSPORTATION, AND SHOES, IF WE WERE LUCKY!).


message:
TFT screen to change sketches

I have an Uno + WiFi 101 thermometer and I'd like to be able to take it places and easily change WiFi network SSIDs and passwords.  Can I use a TFT screen to make these changes to a sktech or am I stuck using a PC and IDE for this kind of thing?

Can someone provide a sample sketch of what this might look like?  I want to know it's something that's possible before I spend the money on a TFT.

It's possible (let's face it, LIKELY) that I fundamentally misunderstand the capabilities and limitations of the TFT screen.  Sorry for the noobish question.

body:
A TFT screen is just a screen. You can't modify SSIDs and passwords with it, any more than you can by poking your PC monitor (unless perhaps you have a touch-screen*). To modify things you would need:

* An input device (eg. a keypad)
* A method of displaying what you are entering (this is where the screen would be handy)
* A method of storing the new information. You could store things like passwords in EEPROM.
* Code to make all that work.

\* Some distributors sell touch-screen interfaces designed to go on top of screens - this might conceivably be what you are thinking of. However you still need the touch-screen, and code to make the touch-screen, **and** the TFT screen, work.


message:
How to request data via I2C?

How do you program an Arduino Uno to request data over I2C, sending parameters defining the request?

I'm trying to program Arduino A to read a sensor value from another Arduino B, and it first needs to tell B which sensor to report, but I can't find any easy way to do this with Arduino's Wire library. There doesn't seem to be anything like `Wire.requestFrom(addr, 1235, 2)` which would then call a handler on the slave the looks like `onRequest(sensor_id)`.

I found [this page][1] on how to push data one way to a slave, and I found [this page][2] on how to request data from a slave without specifying any input, but I can't find anything in between.

Is the solution to use the first method to set the parameters, and then the second to get the data? If so, that seems very circuitous. Is there a more direct method?

  [1]: https://www.arduino.cc/en/Tutorial/MasterWriter
  [2]: https://www.arduino.cc/en/Tutorial/MasterReader

body:
Its the way the protocol is designed. From the very first byte that is sent, you already indicate if you want to read or write data. You can't do both. The protocol is a lot more straightforward this way, one transaction at a time. Plus it gives the feel of a data frame, with START and STOP bits delimiting the frame (not regarding repeated STARTs).

But even for a full-duplex protocol like SPI, you've already said that the master must first send certain parameters to the slave. Nothing can be sent by the slave until it has received these parameters and processed them, full-duplex comms or not. Only after this, can it reply with the requested data.

The Wire methods are designed to send data in one direction at a time, as it should be. You could, of course, create a function like the one in your question, but it would inevitably involve the same process of first writing to the slave and then reading.


message:
Burn new bootloader without crystal

I am considering purchasing these ATmega328 s from
[3 pack ATmega328P][1].

The company says they come with the Arduino UNO bootloader.
I do NOT have any 16 MHz crystals, and I would like to make the chips run on the 8 MHz internal crystal.

I have an Arduino Duemilanove.

Is it possible to burn the minimal setup bootloader [from here][2] onto the bootloaded chips without using a crystal?

  [1]: http://www.amazon.com/3-pack-Atmega328p-pu-Chip-Arduino-Bootloader/dp/B018ZR3F7O/ref=sr_1_1?s=electronics&ie=UTF8&qid=1462677434&sr=1-1&keywords=atmega328p&refinements=p_85:2470955011
  [2]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

body:
I've done just that on a Arduino Pro Mini of mine.

You need to change the fuses to have the chip use the Internal Oscillator, instead of a crystal. After that you just program the 8-MHz version of the bootloader. Like the one used in the `Arduino Pro Mini 3.3V`.

The only problem is that **you need to connect a crystal, to change the fuses to not use the crystal**. Though it doesn't need to be 16Mhz. Anything between 1 and 16MHz will do.

But since you need to change both the fuses and the bootloader, there is no advantage to buy chips with the bootloader preinstalled.

I'd just buy some bare chips without the bootloader.

PS $4.66 is on the high side for an ATMega328P-PU.


message:
Multiplying Arrays

I have an issuing multiplying two one dimension arrays together. Each array is an unsigned long that is storing values of factorials. The last row is completely off. My code is below also with a screenshot of the output.

    void setup() {
    //----------------------------- start serial monitor
 Serial.begin(9600);

 Serial.println("Factorial Table");
    //----------------------------- declare variables
 unsigned long fact = 1;
 unsigned long r[5];
 unsigned long c[5];
 unsigned long product[6][6];
    //----------------------------- load facotirals into array(s)
 for (unsigned long d = 1; d <= 5; d++)
 {
  fact = fact * d;
  r[d] = fact;
  c[d] = fact;
 }
    //----------------------------- multiply factorials
    //                              and load into new array

 for (int row = 1; row <= 5; row++)
 {
  for (int col = 1; col <= 5; col++)
  {
   product[row][col] = r[row] * c[col];
  }
 }

    //----------------------------- print factorials

 for (int prow = 1; prow <= 5; prow++)
 {
  for (int pcol = 1; pcol <= 5; pcol++)
  {
   Serial.print(product[prow][pcol]);
   Serial.print(" ");
  }

  Serial.println(" ");
 }

}

<img src="https://i667.photobucket.com/albums/vv38/Michael_Niebauer/output_zpsekxefuuw.jpg">

body:
In C and its progeny, array indices start at 0. `unsigned long r[5]` declares an array of five longs; the array elements are `r[0]` through `r[4]`. Your loop, however, varies the array index from 1 though 5. `r[5]` is accessing whatever happens to lie in memory beyond `r[4]`

Here is a much better version of your code. Note, among other things, the coding style. Remember that you write programs for other *humans* to read!

    const int kSize = 5;
    void setup() {
      unsigned long r[kSize];
      unsigned long product[kSize][kSize];
      unsigned long fact = 1;
      for (int d = 0; d < 5; ++d) {
        fact *= d + 1;
        r[d] = fact;
      }
      for (int row = 0; row < 5; ++row) {
        for (int col = 0; col < 5; ++col) {
          product[row][col] = r[row] * r[col];
        }
      }

      Serial.begin(9600);
      Serial.println("Factorial Table");
      for (int row = 0; row < 5; ++row) {
        for (int col = 0; col < 5; ++col) {
          Serial.print(product[row][col]);
        }
        Serial.println();
      }
    }

See the difference? Style points to note:

 - no unnecessary comments. In fact, the code is readable enough that no comments are necessary.
 - No unnecessary space.
 - The array size is used in several places; it's better to define it as a constant. There is also no reason to specify anything other than `int`; a good optimizer will detect that you are never using values of more than 5, and will optimize the code accordingly.
 - You don't really need two separate arrays, since they have the same values.
 - You obviously don't need to first store and then print, but I assume you are doing this to learn.
 - I didn't initialize the Serial port and didn't print the header until i was ready to print. Group logically-related statements together. (OTOH, you might have been thinking that at some point you might want to insert print statements before there, so putting Serial.begin first thing in your code might have been better.

While there are lots of styles around, https://google.github.io/styleguide/cppguide.html is good enough for Google, so it's good enough for me :)

Here is a better way to initialize the array of factorials:

      r[0] = 1;
      for (int d = 1; d < kSize; ++d) {
        r[d] = r[d - 1] * (d + 1);
      }


message:
EBay "Development Programmer Board for ATtiny"

Has anyone tried these? Does the ATtiny have a bootloader? What software is used to program the chip? Arduino compatible?

Looks a lot more convenient than programming the ATtiny via an Uno.

http://m.ebay.com/itm/201536595756

/Ola

[![Image of the product in hand][1]][1]

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

body:
If you don't have experience working with AVRs at a low level then stay away from that. It doesn't provide any connection for a programmer and relies on the Micronucleus bootloader already being in place.

If you really want to experiment with ATtiny development then go with either an Adafruit Trinket or a Digistump Digispark (both of which already have Micronucleus loaded), or get an AVR programmer and (optionally) a ATtiny13/25/45/85 development board that includes a 6- or 10-pin programming header


body:
I don't see than much usefulness in these boards.

Negatives:

 - The USB port is only for power. Not for programming.
 - You have to buy an ATTiny chip to put into the socket. It's **not** included.
 - There is no way to put this into a breadboard.
 - There isn't even a way to get to the output pins. So you have to put the chip into this programmer, program it, remove it from the programmer, and place it back into the circuit.
 - It seems to use an 8-pin header to break out the 8 pins on the ATtiny. You'd have to use some female jumper wires to connect to them.

Positives:

 - There is a voltage regulator, so you can connect a higher voltage to the VIN pin
 - There is an 8-pin ISP header, so you can easily connect a ISP programmer, like an [USB-ASP](http://www.ebay.com/itm/51-AVR-Atmega-Programmer-ISP-Downloader-USB-ASP-Downloader-/201066541625?hash=item2ed07ff239)

So in conclusion, some minor plus sides, and some major downsides.

Just place the 8-pin DIP ATtiny in a breadboard.


body:
TL;DR: **It's basically a bigger digispark with a socket and different header.**

Just for completeness:

It depends on the product description, recently I ordered two of your link and some of [these][2]. Those seem to be the same board as you asked for, but in your link the "Package includes" only mentions the board without MCU, which would render the question pointless.

Like Ignacio already said correctly, without proper equipment you wont get this to work with the Arduino IDE. Once you have a bootloader (e.g. micronucleus) on it (the MCU), you can use it like a digispark.

In fact the USB connection works just like on the digispark and ist **not only for power**.

The mounted ATtiny85 was preflashed with micronucleus v1.6 and registered as vendor=16d0, product=0753, which means you could even start with it right away, with Arduino IDE and the [digistump board manager][3].

Personally I use these for prototyping small projects with those tinies on the go where you often don't need a programmer. Once you're done or want to do more you can always remove the bootloader and continue with a real programmer. Or you want to reflash while using the reset pin for I/O, also handy.

  [2]: https://www.amazon.de/gp/product/B073WT3L2S/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1
  [3]: https://digistump.com/wiki/digispark/tutorials/connecting


body: This board supports Attiny25/45/85 MCUs. It is possible to use bootloader with this board. It can be a low speed (1.5MBps) USB device. More info can be found in this article: https://makbit.com/web/firmware/breathing-life-into-digispark-clone-with-attiny-mcu/


body:
The socket is important. One of the huge benefits of using these 8 pin packages is the ability to plug and pull over and over again. Sadly there are few development boards not obsessed with USB. Thankfully this one's is a power header and can be removed easily enough. The Digi/Ada offerings and their clones are not socketed. They are also simple enough to do your own boards.

You can program the x5's with the SparkFun Tiny AVR programmer, based on a design by D.A.Mellis using leads, or by transplanting the mcu. And you can do it from an Arduino, either way you are making up or sourcing a lead, as squid style flying leads are tedious.

Otherwise there is a 2k or so bootloader that can be used, which would be most useful for the 85. Without serial support from USB or FTDI this will be hard.

**Software**

 1. Arduino with core from [https://github.com/SpenceKonde/ATTinyCore][1]
 2. avra and avrdude from the command line for assembler, you could also compile C/C++ from the command line but this is not common.
 3. AVR plugin for Eclipse.
 4. Sloeber stand alone Eclipse based Arduino IDE, some quirks.
 5. Atmel Studio 7 based on Visual Studio, requires Windows, requires genuine "Microchip" programmer. Note this is free and includes an emulator.
 6. There is some effort to get this possible with C-Lion by JetBrains.

.

  [1]: https://github.com/SpenceKonde/ATTinyCore


body:
I just used one of those boards in conjunction with a cheap tinyISP board to program a DIP8 attiny85 using ISP from Arduino IDE.

The pinout matches if you put the IDC cable the right way around. I used a 10-pin IDC cable - I think you'd have to use at least an 8-pin IDC because a 6-pin wouldn't fit with the extra pins on the programmer board, unless you only soldered on the 6 header pins that you need for ISP.

[![tinyISP][1]][1]

If you program the digistump bootloader onto the attiny85 then you should be able to use the USB socket on that board to reprogram it. But if it's a blank attiny85 then you have to use ISP to program it in the first place.

Here's how I hooked them up:

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

You can see from the silkscreen that the pins are clearly designed to match up to the Arduino ISP pinout:

[![enter image description here][5]][5]

  [1]: https://i.stack.imgur.com/qOzhv.png
  [2]: https://i.stack.imgur.com/bixgy.jpg
  [3]: https://i.stack.imgur.com/KUK01.jpg
  [4]: https://i.stack.imgur.com/jOUrM.jpg
  [5]: https://i.stack.imgur.com/niDyN.jpg


message:
How to connect an LED to Arduino LilyPad Mp3

can anyone help me with connecting LED to Arduino LilyPad Mp3  in a way, that each switch (1 of 5) light up a different LED?

I tried connecting an LED between the switch and the board, then the LED light up, but the speaker does not play the audio file.

I also tried connecting an LED directly to the speaker, then LED lights up and the speaker plays the sound file, but the problem is that all of the LED´s light up at the same time....

body:
You might try connecting the anode side of your LEDs through a current limiting resistor to the positive side of the supply.  Then connecting the cathode side of the LED to the switched pin on the Arduino LilyPad Mp3.  So, in this diagram:

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

...that would be the pads where the switches are connected.

The current limiting resistor depends on the specifications of the LED.  Check the voltage and current required to light the LED.  Subtract the voltage needed from your supply voltage.  Then use the V=IR equation and solve for R.  That is, V = the voltage difference between your supply and what is needed by the LED and I is the current (probably in milliamps, so watch your math!) that the LED needs to light up properly.  You will probably need small current limiting resistors somewhere around between 100 and 800 ohms.

Added later...

Thanks to @Gerben we have a diagram of what I was describing:

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

In Gerben's diagram he has used the regulated 3 volt output of the Arduino LilyPad Mp3.  We can double check all the pin labels using a diagram from Sparkfun:

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

You should be able to repeat this circuit for each switch.  Sparkfun has an LED tutorial [here][4].  But I'm not very happy with their guess approach when picking out a current limiting resistor.  Ah, [this tutorial][5] is much more to the point.

So, if we assume the LEDs you are using need 3mA @ 3V (remember to use values for YOUR LEDs!) and use this equation (Vs = supply voltage and Vf = LED voltage):

[![enter image description here][6]][6]

...then we set it up like (3 - 3) / (0.03) which is zero.  That's because I was using LEDs that work at 3 volts.  But if I used LEDs that worked at 3mA at 1.8V then I need... (3 - 1.8) / (0.03) = 40 ohm resistors.  Or there about. As most resistor values are on a log scale I suspect there should be a 47 ohm available.

  [1]: https://i.stack.imgur.com/xoTnl.png
  [2]: https://i.stack.imgur.com/KCUlD.png
  [3]: https://i.stack.imgur.com/qHGAr.png
  [4]: https://learn.sparkfun.com/tutorials/light-emitting-diodes-leds?_ga=1.1888825.965782605.1436615638
  [5]: https://www.sparkfun.com/tutorials/219
  [6]: https://i.stack.imgur.com/5uPYa.jpg


message:
How to use web data from GSM Sim900 to be used as input for Arduino?

I have a GSM Sim900 connected to an Arduino Uno. I'm successfully able to use HTTP READ commands to show data from the web on the Arduino's serial monitor. It is showing complete HTML from that URL on the serial monitor.

Now, how should I filter data from the web? I mean I just want to display selected numbers in the serial monitor and not the complete HTML.

And secondly, how should I store these numbers into a variable so I could use them as input data for Arduino?

Thank you.

body:
What about RapidXml? RapidXML is a very fast and small XML DOM parser written in C++. It is aimed primarily at embedded environments so might work here. Boost software license means source is freely available. http://rapidxml.sourceforge.net.

The other way to go is just parsing out the numbers with string manipulation.


body:
You should read the manual.
More specifically the "Sim900 AT reference".
I've found it on a russian server (https://www.google.nl/url?sa=t&source=web&rct=j&url=http://wiki.amperka.ru/_media/%D0%BF%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D1%8B:gprs_shield:gprs-shield_sim900_at_commands.pdf&ved=0ahUKEwinze2Tp7fQAhWBMSYKHQFkBh0QFghEMA0&usg=AFQjCNGKd5Uohe7CmcJcIc1Am-SKdRsWXg&sig2=XIsvvkLWHs60sTo7FZ7tWw) but you may want to try and get it directly from the manufacturer.

In the datasheet, it will explained what values are allowed with the "at+httpread" command. You can actually specify which part you want to read. This is usefull when your Arduino can't parse the complete page.

If you have control over the page, you may also generate a device-friendly page consisting of key-value pairs, instead of it being a whole HTML page.

![enter image description here](https://i.stack.imgur.com/g4cBg.png)


message:
Arduino nano to esp8266 level shifting needed?

I want to connect an Esp8266 Wifi module to an Arduino nano. I am wondering if I need to implement level-shifting for the Arduino TX line to Esp RX line?

I find different schema's on the net. Some with, some without level-shifting:

With:
http://community.blynk.cc/t/robot-with-esp8266-shield-and-arduino-nano/3316/8

Without:
https://arduino.stackexchange.com/questions/17590/arduino-nano-v3-0-with-esp8266

Some use a capacitor between GND and Esp CH_PD pin, others use a 10K resister between the 3.3V and the CH_PD pin (https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/)...

What is the most basic but required setup for a Arduino Nano and a Esp8266?
(I have Esp8266-12e modules)

Thanks!

body:
The **arduino nano v3**'s logic is 5v, and the ESP8266's logic is 3.3V, so you need to do level shifting between both.
Using a voltage divider drains more current (guess not an issue in this case) and it's ok only when going from 5V to 3.3V (when the signal must be shifted from 3.3V to 5V in the links you provide, it looks like it's based on that 3.3V is still considered "HIGH" on a TTL signal).

I personally prefer using a level shifter, it just complicates a bit the Bill Of Materials, but you won't have to debug the level shifting part.

And better than that, using an arduino mini pro @3.3v working directly at 3.3V gets rid of this hassle.


body:
You could use a simple diode, between the Arduino TX and ESP RX. That's what the [Adafruit Huzzah uses](https://cdn-learn.adafruit.com/assets/assets/000/024/745/original/adafruit_products_schem.png?1429900999).

It takes advantage of the internal pull-up on the RX pin of the ESP. The diode will allow a LOW, to pull the signal low, through the diode. But it will block a HIGH 5 Volt signal from going into the ESP.


message:
Running Arduino IDE in terminal?

Is there any way to use Arduino in the terminal? I have a USB 802.15.4 board that works with Arduino, but I don't want to use the IDE with it, I want to use the terminal.

body:
1.) You can configure the arduino ide to use an "external editor". This means the arduino ide runs als usual but reloads the opened file for compiling and uploading. This is when you want to keep the original arduino ide.

2.) You can use the [ino projekt][1] which gives you a cli interface to manage your arduino projects. The [quickstart][2] guide gives a good overview of the project.

    ino init -t blink
    ino build
    ino upload
    ino serial

You can of course make all needed modifcations for differend boards and communication. I think the second option is what you are looking for ;)

  [1]: http://inotool.org/
  [2]: http://inotool.org/quickstart


body:
The most popular method these days is to use [arduino-builder](https://github.com/arduino/arduino-builder).

This seems to be the official Arduino command line interface now, and can do most things the IDE can do short of actually editing your code for you.

It is a set of GO scripts, so you will need GO installed.


message:
How to sleep a whole circuit?

I have just completed my first project, a clone of the Simon game of the eighties. The main parts of the circuit are an ATMega328, a 1602 2x16 LCD, and a small joystick.
It is powered directly from 3x1.5V batteries with solder bridges connecting all power pins on each part directly to the batteries. Therefore, if I sleep the ATMega, it won't change a thing comsumption-wise, as the LCD will still be powered.

What are (my first project, I am very unknowledgeable) the possible strategies to sleep the whole circuit?

I thought of using an ATMega pin as a positive lead for the joystick and LCD. Is that feasible?

Another strategy would be to interface some component (a relay?) between the battery and LCD, and command that component from an ATMega pin. Does someone know the right part for the job (I have a 220V relay in my parts, but it seems overkill)?

Lastly, even though it seems unlikely, is there a possible strategy without using any ATMega pins, as I currently use every single one (4 buttons, 4 leds, joystick x, y, and button, 1 buzzer, and 6 pins for the LCD, for a total of 18) except Rx and Tx?

body:
The first and most smart solution is to use a switch between the batteries and everything else. This way, you slide the switch in the off position and the whole circuit is completely detached from the batteries: power consumption: 0.

If you can't (because, for instance, you want it to automatically power off after a while) you can use a transistor (PMOS, for instance) instead of the switch. you have then to put a complementary transistor (NMOS) on its gate, then a button in parallel to it. Just another passve component is required: a resistor (value e.g. can be 100k). When you press the button, the circuits becomes momentarily powered on. You will have to pull the nmos gate to a logic 1 with the atmega to keep the circuit powered. When you want to turn everything off, pull the pin to a logic 0 and your circuit will immediately shut down.

If, third solution, you want to give the atmega complete control over the powering, it needs to be always on. You can then omit the complementary transistor and use a reverse logic on the pin (so 0 = on, 1 = off) and then you can do whatever you want with the power (turn on and off whenever you want).
**edit**: as a comment suggests, it can be better to put a resistor to set the appropriate voltage on the gate at power up. Even if the commenter told to put a pull-down, I suggest you to put a pull-up (pull-down = normally on, pull-up = normally off). **edit 2** as Paul suggested, there could be cases in which you need to be able to turn on and off automatically the circuit, and then store it for longer times without consuming battery. In this case it could be a good idea to put something (a mechanical switch, a jumper, a detachable wire) to completely detach the battery even from the arduino (even if, in this case, you can just remove the batteries from the housing).

Here is a small paint-made sketch to show the solutions. If you have any questions just ask ;)

[![Circuits for pouzzler][2]][2]

EDIT: If you want to let the atmega control the power, you'll have to give him a way to do so. Which means.. You should use a pin. If you want you can use safely the RX and TX pins, as long as you don't enable the serial interface. If you need more pins, you can try to optimize your pins usage (for instance using a 4:1 multiplexer for the buttons you will have 2 control pins and 1 input, for a total of 3 pins, instead of 4), even if I think that the best solution is to use a port expander. for instance in the past I used the MCP23017, which has a I2C interface, or the MCP23S17, with a SPI interface. You will have to use the serial interface you choose (I2C: 2 pins - SCL and SDA, SPI: 4 pins - MISO, MOSI, SCK, SS, but they are the same pins used for programming), and then you will have 16 more pins for your uC

EDIT BY foivaras:

The same result can be achieved utilizing an NMOS instead of a PMOS.This would have an advantage over PMOS solution if power line was >5v and arduino was powered by a dc to dc converter. On this scenario, PMOS solution would need one more transistor to work.
Notice that the NMOS has to be placed on the low side of the power line and it will cutoff the power to joystick and lcd with 0v  and enable the power with 5v on its gate.(See 4th image)

[![NMOSPOWERCONTROL][1]][1]

COMMENT BY fra87

This solution is not a valid alternative in my opinion. Usually interrupting ground is a bad idea, because usually the rest position of the I/O pins is ground: if you interrupt the ground for the LCD, for instance, you will have +5V on the VCC pin, and a floating ground, but you will have 0V on all the I/O pins, possibly damaging the internal circuits. Moreover having a floating ground is bad in terms of noise protection.

The only advantage COULD be in the particular case explained by the editor, which is a DC/DC converter powering the arduino but not the LCD and the Joystick. This is a strange setup, though, and the proposed solution is better at a first glance (requires one less transistor), but is wrong. For instance, let's suppose the joystick is powered at 12V. If you detach the ground, the joystick will "shut down", which means that all its pins will float up to 12V. This means that on the arduino pin you will see 12V: you can damage it.

So, in the end, I discourage this solution. The only case when you can need it is when you are in a hurry and do not have any feasable PMOS: even in this case, however, I suggest you to replace the NMOS with a PMOS as soon as possible.

Just one more note: edits to the posts, in my opinion, should be done to improve the quality of the answer, by better formatting the content, removing orthographic errors and so on. If someone needs to add some comments or other solutions, it's better to use the comments or add another answer to the thread

  [1]: https://i.stack.imgur.com/AoK9p.png
  [2]: https://i.stack.imgur.com/rNuc3.png


message:
ESP8266 reset problem

I am trying some AT commands with ESP8266 but it resets continously when it stop resetting, i can't get any response from ESP8266.

Example :

    AT

    OK
    AT+CWMODE=1

    OK
    AT+CIPMODE=0

    OK
    AT+CIPMUX=1

    OK
    AT+CWJAP="..",".."

     ets Jan  8 2013,rst cause:4, boot mode:(3,1)

    wdt reset
    load 0x40100000, len 612, room 16
    tail 4
    chksum 0x12
    load 0x3ffe8000, len 788, room 4
    tail 0
    chksum 0x50
    load 0x3ffe8314, len 264, room 8
    tail 0
    chksum 0x4a
    csum 0x4a

    2nd boot version : 1.1
      SPI Speed      : 40MHz
      SPI Mode       : QIO
      SPI Flash Size : 4Mbit
    jump to run user1

    sd
    ready

     ets Jan  8 2013,rst cause:4, boot mode:(3,1)

    wdt reset
    load 0x40100000, len 612, room 16
    tail 4
    chksum 0x12
    load 0x3ffe8000, len 788, room 4
    tail 0
    chksum 0x50
    load 0x3ffe8314, len 264, room 8
    tail 0
    chksum 0x4a
    csum 0x4a

    2nd boot version : 1.1
      SPI Speed      : 40MHz
      SPI Mode       : QIO
      SPI Flash Size : 4Mbit
    jump to run user1

    sd
    ready

I have upgraded my firmware and I tried GPIO0 and GPIO2 are active but it still does not response fine. It worked yesterday but today it is working like crazy..

body: Arduino can not provide enough current for ESP8266 operations. Use external 3.3V power supply, I would recommend 500ma. Also don't forget to put a small cap between vcc and ground. 100uf should do it.


body:
I had the same problem. My esp8266 is powered by FTDI USB to serial module. Since this module can provide a limited amount of current to 3.3V. I use to get frequent reset.

I resolved it by adding a 1000ufd electrolyte capacitor near the power connection of the esp8266 module. And issue resolved like never been there.

I am sure that can also be done by a smaller capacitor. Try with 470 or 220ufd.

enjoy

Rauf


message:
reading pwm signal doesn't work correctly

my goal is to read a pwm signal from a rc receiver. For that i tried to use an arduino.

i ran this code on the arduino:

    #define Pin 3

    int pwm_value;

    void setup() {
      pinMode(Pin, INPUT);
      Serial.begin(9700);
    }

    void loop() {
      pwm_value = pulseIn(Pin, HIGH);
      Serial.println(pwm_value);
    }

Now i connected the 3rd pin with the output of the receiver. But instead of printing the correct pwm values they get printed completely crazy. Sometimes they are under 10 and sometimes they are over 10000. The receiver outputs the correct signal.

I also noticed that if i just touch the pin with my finger or if i only connect a single jumper cable without anything at the end, the arduino will read a pwm signal.

I have realy no idea to solve that. Can you please help me?

Thank you!

body:
check if the problem is the fact you have set `9700` baud rate on your sketch while the commonly used `9600` is supported from arduino IDE.

---

I slightly modified your code and it works for me. Check if this works for you:

 #define Pin 3
 #define Source 5
 unsigned long  pwm_value;

 void setup() {
  pinMode(Source,OUTPUT);
  pinMode(Pin, INPUT);
  Serial.begin(9600);
  analogWrite(Source,500);
 }

 void loop() {
  pwm_value = pulseIn(Pin, HIGH);
  Serial.println(pwm_value);

 }

when you connect pin3 with pin 5 you should get a consistent value on Serial(=967).

### About getting signal on floating pins
Getting a signal on a floating pin is normal.
When you have a cable attached it acts like an antenna. When you touch it, you are the antenna!


message:
Proper use of * and & when passing objects in methods

Coming from C#, pointers are somewhat foreign although I am grasping the concept.
Is it proper to construct methods in the following manner and passing the object (as a parameter) constructed by reference? If not, then please answer how to do this properly.

Initialize the object

    Adafruit_VS1053_FilePlayer musicPlayer =
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

Method: (use the * for pointer?)

    boolean initializeMusicPlayer(Adafruit_VS1053_FilePlayer *mp, uint16_t baudRate) {

     musicPlayerSerialPort.begin(baudRate);
     // initialise the music player
     if (!mp->begin()) { // initialise the music player
      Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
      return false;
      //while (1);
     }
     Serial.println(F("VS1053 found"));

     mp->sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working

     if (!SD.begin(CARDCS)) {
      Serial.println(F("SD failed, or not present"));
      return false;
      //while (1);  // don't do anything more
     }
     Serial.println("SD OK!");
     // Set volume for left, right channels. lower numbers == louder volume!
     mp->setVolume(20, 20);

     if (!mp->useInterrupt(VS1053_FILEPLAYER_PIN_INT)) {
      Serial.println(F("DREQ pin is not an interrupt pin"));
      return false;
     }
     return true;
    }

Call the method (Use the ampersand to pass the currently created one by reference?)

    if(initializeMusicPlayer(&musicPlayer, 9600) == true) {
  tempString = tempString + "MusicPlayer initialized!";
  Serial.println(tempString);
  //when adding lcd, print the above to lcd and remove the serial print
 }

body:
The method you have implemented, *passing by pointer*, is one of the two normal methods, yes. The other is *passing by reference* and is specific to C++, not C.

Under the hood the end result is the same between the two methods, by the syntactic "sugar" is very different and the latter can be preferable for that reason alone.

Your method:

    void function(whatever *ob) {
        ob->method();
    }

    function(&myObject);

The *pass by reference* method:

    void function(whatever &ob) {
        ob.method();
    }

    function(myObject);

As you can see the need to convert the object into a pointer with `&` is now gone. That makes it much easier for people lacking in programming skills to use it since it hides the whole pointer mechanism from them.

Also, internally your function now treats `ob` as just another object using `.`, rather than a pointer to an object and needing to use `->`.  Note that you can only use the reference operator in a function prototype, not a variable or anything like that - it's purely for passing objects and variables to functions.  If you want to then go and store the pointer in a variable you still then have to get the address:

    void function(whatever &ob) {
        myObjectPointer = &ob;
    }

As you see it gets confusing with the two different uses of `&`. Basically though: if it's in a function prototype, it's the `pass by reference` operator. If it's anywhere else, it's the `get the address of` operator (or a logical AND of course).

Storing the pointer can be useful if you want to then do other things later on with the same object, especially if you are yourself working with a class.  For instance, I often write code similar to the following:

    class foo {
        private:
            bar *ob; // Pointer to other object of type "bar"
        public:
            foo(bar *inob) : ob(inob) {}
            foo(bar &inob) : ob(&inob) {}

            void something() {
                ob->doSomething();
            }

            void somethingElse() {
                ob->doSomethingElse();
                ob->evenMoreThings();
            }
    };

You then have a choice of constructors:

    bar myBar;
    foo myFoo(myBar);

    // ... later ...
    myFoo.something();

or

    bar myBar;
    foo myFoo(&myBar);

    // ... later ...
    myFoo.something();

and the user doesn't have to remember which they need to use - whichever they try will work.


message:
Voltage divider producing unexpected voltage

I'm trying to run a neopixel strip and an arduino from the same power supply using a voltage divider to get 5V to the strip.

Here are the values for my voltage divider:

  R1 = 1500 Ω

  R2 = 1000 Ω

  Vin = 12 V

resulting in:

  Vout = Vin*(R2/(R1+R2)) = 12*(1000/(1500+1000)) = 12*(1000/2500) = 12*0.4 = 4.8

When the divider is connected at its inputs but not at its outputs, I measure the expected 4.8V across R2. But as soon as I connect the neopixels, I only get about 1.6V.

Could anybody explain this || Suggest a possible solution?

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

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

body:
Since you are connecting your pixel strip in parallel with R2, the
correct formula is

    Vout = Vin × (R2∥Rp) / (R1 + (R2∥Rp))

Where Rp is the resistance of the pixel strip and

    R2∥Rp = R2 × Rp / (R2 + Rp)

is the combination of R2 and Rp in parallel. From this you can see that
an output voltage of 1.6 V is consistent with a strip resistance of
300 Ω.

This is, however, somewhat oversimplified, as the I(V) characteristic of
the LED strip is probably non-linear, thus not really equivalent to a
resistor.


message:
How to set float to variable with 7 digits after the decimal point in arduino?

Example:

    float x = 3154681.124 / 100000; //x = 31.54;

I want x to be:

    x = 31.5468112;

body:
    float x = 3154681.124 / 100000; //x = 31.54;

`x` is now `31.5468112` (or close to).

    Serial.println(x);

Output: `31.54`

Why? Because `Serial.println` defaults to 2 decimal places for floats.

> Syntax
>
> `Serial.println(val)`
>
> `Serial.println(val, format)`
>
> Parameters
>
> `val`: the value to print - any data type
>
> `format`: specifies the number base (for integral data types) **or number of decimal places (for floating point types)**

So the solution: specift 7 decimal places when you print:

    Serial.println(x, 7);