message:
WS2812 - First are white and then they turn red/yellow/orange near the end

I'm trying to power about 150 WS2812 LEDs from my ESP8266 NodeMCU board (running NeoPixel Arduino code). The first few LEDs are white, but about half way down, the LEDs turn yellow, then they turn orange, and at the end they're basically red.

Could this be caused because of the power draw? The strip itself is currently drawing about 900 mAh, and I am powering the ESP8266 with a 1.5A 5v supply. The LEDs are running off 3.3v directly from the ESP8266.

Also, after like 2 minutes, the LEDs turn off completely. The board never disconnects from my WiFi. They just turn off. I can turn them on again right after.

body:
See [Powering NeoPixels](https://learn.adafruit.com/adafruit-neopixel-uberguide/power).

> Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).
>
> ...
>
To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps. Or use 60 (instead of 20) if you want to guarantee an absolute margin of safety for all situations. For example:

So you need at least 3 amps or even **9 amps** for absolute safety.

>  The LEDs are running off 3.3v directly from the ESP8266.

I doubt it is designed for that. The internal traces won't be designed to handle maybe 5 amps.

---

To avoid colour degradation through the strip you could use multiple power supplies (to avoid the voltage dropping due to the resistance over the strip). You would connect the grounds (and connect the data wires of course) but break the +5V line in the middle and insert another power supply.

However one (fairly powerful) supply **directly connected to the NeoPixels** might do the trick. That is, not through the ESP8266.

Also see [NeoPixels Revealed: How to (not need to) generate precisely timed signals](https://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/).

On that page:

> **Q**: In the video, when the entire strip is lit full white, it looks like the far end has a orange tint to it. Is this an artifact of the camera or something?
>
> **A**: Wow, you are very perceptive! Yes, the string did start to get orange at the end at full power. I actually didn’t just run out of apartment when making this long string – I also ran out of power supplies. I had 3 supplies, each 10amps. This is almost enough, but not when every single LED is full brightness white. When that happens, the voltage at the very end of the strip starts to get too low and the LEDs start looking pallid. Why orange? Because blue LEDs need the highest voltage drop to light so when the voltage sags they are the first to go followed by the greens – leaving yellows to oranges and ultimately red.

(He had 1000 pixels). So this guy used 3 separate 10 amp power supplies!


sender: user

sender: assistant

body:
From the Adafruit Uberguide.
[https://learn.adafruit.com/adafruit-neopixel-uberguide/power][1]

I am experiencing the same issue.  This is the solution I found.

> Distributing Power The longer a wire is, the more resistance it has.
> The more resistance, the more voltage drops along its length. If
> voltage drops too far, the color of NeoPixels can be affected.
>
> Consider a full 4 meter reel of NeoPixels. With 5V applied at one end
> of the strip, for those pixels closest to this end, power traverses
> only a few inches of copper. But at the far end of the strip, power
> traverses 8 meters of copper — 4 meters out on the +5V line, 4 meters
> back on the ground line. Those furthest pixels will be tinted brown
> due to the voltage drop (blue and green LEDs require higher voltage
> than red).
>
>leds_brownout.jpg
>
> Pro Tip: NeoPixels don’t care what end they receive power from. Though
> data moves in only one direction, electricity can go either way. You
> can connect power at the head, the tail, in the middle, or ideally
> distribute it to several points. For best color consistency, aim for 1
> meter or less distance from any pixel to a power connection. With
> larger NeoPixel setups, think of power distribution as branches of a
> tree rather than one continuous line.
>
>leds_nobrown.jpg

  [1]: https://learn.adafruit.com/adafruit-neopixel-uberguide/power


message:
How to measure ultrasonic sensor without pulsein method?

I am a front-end developer so I don't really know Arduino. Anyway, my teacher gave me a project.

In short, I have to measure distance with HC-SR04. But the problem is that the teacher wants me to use a timer. But I can't understand how can I do that.

Thank you for helping.

body:
Rather than give you the straight answer in code form, consider this approach. If you learn how the unit works, you will be better prepared to answer questions presented to you.

The background of an ultrasonic distance measuring device is that it sends out a signal, in the form of sound you cannot hear. The device then listens for any echoes (bounce-back) of that pulse within a certain time period. This time period represents the distance range that the device can register. If the electronics are of poor quality, the minimum distance will be larger than if the device was of higher quality, as the amount of time for the pulse to bounce from a close-in object is going to be very short. The electronics have to be very fast to read such a short period of time.

There are libraries for ultrasonic devices such as the one you note, but that's the "easy way" to use it. If you perform appropriate searches, you will find there are references how to use direct timing for this device, which will satisfy the requirement you have been given.

I could perform the search and provide you a link, but that's half the work. Consider to use terms including your device identifier along with code and timing and you may find useful links. It is also very possible that you will find someone's pre-written code using the timing method.


body:
The solution is, You need to implement custome pulse in funtion

    unsigned long rdPulseIn(int pin, int value, int timeout) { // the following comments assume that we're passing HIGH as value. timeout is in milliseconds

        unsigned long now = micros();
        while(digitalRead(pin) == value) { // wait if pin is already HIGH when the function is called, but timeout if it never goes LOW
            if (micros() - now > (timeout*1000)) {
                return 0;
            }
        }

        now = micros(); // could delete this line if you want only one timeout period from the start until the actual pulse width timing starts
        while (digitalRead(pin) != value) { // pin is LOW, wait for it to go HIGH befor we start timing, but timeout if it never goes HIGH within the timeout period
            if (micros() - now > (timeout*1000)) {
                return 0;
            }
        }

        now = micros();
        while (digitalRead(pin) == value) { // start timing the HIGH pulse width, but time out if over timeout milliseconds
            if (micros() - now > (timeout*1000)) {
                return 0;
            }
        }
        return micros() - now;
    }

You can read distance

    long mm = rdPulseIn(echoPin, HIGH, 37)/5.82; // distance in mm


message:
How to store a string in an object and retrieve it safely later?

I'm writing a program where I will be able to toggle between multiple banks, and each bank has 4 presets on it. Right now, I'm trying to give each preset a name that is assigned on creation.

I have an object I called `StoredDataManager`, which will handle all the banks. In its constructor, I do this:

    for (byte i = 0; i < NUMBER_OF_BANKS; i++) {
      Bank bank;
      _banks[i] = &bank;
    }

`_banks` is declared like this: `Bank* _banks[NUMBER_OF_BANKS];` in the `.h`file of `StoredDataManager`.

A bank has 4 presets, like this:

    Preset* _A;
    Preset* _B;
    Preset* _C;
    Preset* _D;

Which I initialize as this:

    Preset preset(presetName, presetData);
    ...
    _A = &preset; ...

Where `presetName` is `"CHR"`, and `presetData` doesn't matter, because I'm just trying to get the name to work.

In the preset, the name is saved like this: `char _presetName[4];`.
It is returned like this:

    char* Preset::getPresetName() {
      return _presetName;
    }

I try to print a preset's name like this:

    Serial.println(_banks[0]->getPreset('A')->getPresetName());

But, right now it simply returns `C§`.

Why is that? I suspect it has to do with the memory being erased or overwritten.

EDIT:
Here is the code of `getPreset`:

    Preset* Bank::getPreset(char presetLocation) {
      switch (presetLocation) {
        case PRESET_LOCATION_1:
          return _A;
        case PRESET_LOCATION_2:
          return _B;
        case PRESET_LOCATION_3:
          return _C;
        case PRESET_LOCATION_4:
          return _D;
        default:
          return NULL;
      }
    }

I think now that I'll turn this into 4 separate functions, like `getA`, `getB` and so on, but this what it is the moment. `PRESET_LOCATION_1` is just a `#define PRESET_LOCATION_1 'A'`.

EDIT 2:
I start in the main arduino `.ino` file with this:

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

This triggers this constructor:

    StoredDataManager::StoredDataManager() {
      for (byte i = 0; i < NUMBER_OF_BANKS; i++) {
        Bank bank;
        _banks[i] = &bank;
      }
      _currentBankIndex = 0;
      Serial.println(_banks[0]->getPreset('A')->getPresetName());
    }

This is `_banks`: `Bank* _banks[NUMBER_OF_BANKS];`.
The initializing of the `bank` object runs this constructor: (PRESET_LOCATION_1, 2, 3, and 4 just being `'A', 'B', 'C', 'D'`)

    Bank::Bank() {
      addPreset("CHR", "Some data", PRESET_LOCATION_1);
      addPreset("CHR", "Some data", PRESET_LOCATION_2);
      addPreset("CHR", "Some data", PRESET_LOCATION_3);
      addPreset("CHR", "Some data", PRESET_LOCATION_4);
    }

Which calls this function:

    void Bank::addPreset(const char* presetName, String presetData, char presetLocaton) {
      Preset preset(presetName, presetData);
      switch (presetLocaton) {
        case PRESET_LOCATION_1:
          _A = &preset; break;
        case PRESET_LOCATION_2:
          _B = &preset; break;
        case PRESET_LOCATION_3:
          _C = &preset; break;
        case PRESET_LOCATION_4:
          _D = &preset; break;
      }
    }

Then, above in the `StoredDataManage`s constructor, this line is hit:

    Serial.println(_banks[0]->getPreset('A')->getPresetName());

And that's where I try to log out the preset name.

body:
    void Bank::addPreset(const char* presetName, String presetData, char presetLocaton)
    {
      Preset preset(presetName, presetData);

      switch (presetLocaton)
      {
        case PRESET_LOCATION_1:
          _A = &preset; break;
        case PRESET_LOCATION_2:
          _B = &preset; break;
        case PRESET_LOCATION_3:
          _C = &preset; break;
        case PRESET_LOCATION_4:
          _D = &preset; break;
      }
    }

I can't see how this is going to work because you are storing somewhere outside a function a pointer to a local variable *inside* the function. As soon as `addPreset` exits the variable `preset` will go out of scope, and a pointer to it will be undefined.

---

You should probably do a `new` to make a new instance of `Preset` which it is then valid to store outside the scope of the function.


message:
How to fix compilation error for tone() using same timer as other function

I am trying to integrate tone() with the open source program for the Amped heart rate monitor. The error:
>Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
>
>(.text+0x0): multiple definition of `__vector_7'
>
>sketch\PulseSensorAmped_Arduino_1dot4.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

The program comes in three files. PulseSensorAmped_Arduino_1dot4.cpp I don't think references any timers but references a function in another file with this code:

      // Initializes Timer2 to throw an interrupt every 2mS.
      TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
      TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
      OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
      TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
      sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED

This uses timer 2; but isn't the error for timer 1? The tone() reference page says that tone interferes with pins 3 and 11. Is there any way to fix this?

references:

https://www.arduino.cc/en/Reference/Tone

https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino

body:
It looks like the Tone library uses Timer 2, and it looks like your other code also uses Timer 2, hence the error message. Vector 7 would be the TIMER2_COMPA_vect (Timer 2 compare "a").

Pins 3 and 11 are from Timer 2.

I wrote a small library that generates tones using the hardware PWM and not interrupts. You can read about it [here](http://www.gammon.com.au/forum/?id=11504&reply=11#reply11).

Example code:

    #include <TonePlayer.h>

    TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

    void setup()
      {
      pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

      tone1.tone (220);  // 220 Hz
      delay (500);
      tone1.noTone ();

      tone1.tone (440);
      delay (500);
      tone1.noTone ();

      tone1.tone (880);
      delay (500);
      tone1.noTone ();
      }

    void loop() { }

Library can be downloaded from <http://www.gammon.com.au/Arduino/TonePlayer.zip>

This uses Timer 1 (so that won't interfere with Timer 2) and no interrupts.


message:
Volatile variable not updating from timer ISR

I know this is a problem that has come up many times but I can't seem to get this code fragment to update the count variable on an ATMEGA328P. I am using an Arduino Uno as a development board, with the LED on pin 13 set to flash for debugging. I have confirmed the timer and LED part work by toggling port B pin 5 in the ISR routine.

    #include <avr/io.h>
    #include <avr/interrupt.h>

    volatile uint8_t count;

    void init_100us_tick(void) {
     TCCR0A = _BV(WGM01) | _BV(WGM00);  // WGM mode 7 with OCRA as top
     TCCR0B = _BV(WGM02) | _BV(CS01);  // CLK / 8 prescaler
     TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);  // Interrupt enabled on OCR0A
     OCR0A = 200;       // 16 MHz / 8 / 200 = 100 us
     sei();         // Enable interrupts
    }

    ISR(TIMER0_COMPB_vect) {
     count++;
 }

    int main(void) {
     DDRB |= _BV(DDB5);      // PB5 output
     init_100us_tick();      // Initialise 100 us tick
     count = 0;        // In case of micro reset

        for (;;) {
         if (count >= 100) {     // Every 10 ms
          count = 0;
          PORTB ^= _BV(DDB5);    // Toggle PB5
         }
       }
       return 0;
    }

This is being compiled and burned to an Arduino Uno with the following:

    avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o test.o test.c
    avr-gcc -mmcu=atmega328p test.o -o test
    avr-objcopy -O ihex -R .eeprom test test.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:test.hex

I have tried disabling the optimisation with no effect. AVR-GCC is version 4.9.2

body:
You want CTC mode for that to work. As in:

    #include <avr/io.h>
    #include <avr/interrupt.h>

    volatile uint8_t count;

    void init_100us_tick(void) {
        TCCR0A = _BV(WGM01);       // CTC mode 2 with OCRA as top
        TCCR0B = _BV(CS01);        // CLK / 8 prescaler
        TIMSK0 = _BV(OCIE0B) | _BV(TOIE0);      // Interrupt enabled on OCR0B
        OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
        sei();                                  // Enable interrupts
    }

    ISR(TIMER0_COMPB_vect) {
        count++;
    }

    int main(void) {
        DDRB |= _BV(DDB5);                      // PB5 output
        init_100us_tick();                      // Initialise 100 us tick
        count = 0;                              // In case of micro reset

        for (;;) {
            if (count >= 100) {                 // Every 10 ms
                count = 0;
                PORTB ^= _BV(PORTB5);             // Toggle PB5
            }
       }
       return 0;
    }

That toggles every 10 ms.

---

**(Edited to add)**

The PWM mode you chose will work providing you enable the correct interrupt. This also outputs 10 ms pulses:

    #include <avr/io.h>
    #include <avr/interrupt.h>

    volatile uint8_t count;

    void init_100us_tick(void) {
        TCCR0A = _BV(WGM01) | _BV(WGM00);       // Fast PWM mode 7 with OCRA as top
        TCCR0B = _BV(WGM02) | _BV(CS01);        // CLK / 8 prescaler
        TIMSK0 = _BV(OCIE0A);                   // Interrupt enabled on OCR0A  ***
        OCR0A = 200;                            // 16 MHz / 8 / 200 = 100 us
        sei();                                  // Enable interrupts
    }

    ISR(TIMER0_COMPA_vect) {                    // Compare A vector ***
        count++;
    }

    int main(void) {
        DDRB |= _BV(DDB5);                      // PB5 output
        init_100us_tick();                      // Initialise 100 us tick
        count = 0;                              // In case of micro reset

        for (;;) {
            if (count >= 100) {                 // Every 10 ms
                count = 0;
                PORTB ^= _BV(PORTB5);           // Toggle PB5  ***
            }
       }
       return 0;
    }

Changed lines indicated by `***`

Note that you should **not** have enabled `_BV(TOIE0)` because you have no interrupt handler for Timer 0 overflow. Without an interrupt handler the compiler probably generated code to jump to the reset vector.

The interrupt occurs when the timer matches the **Compare A** amount (not Compare B) so you need an interrupt on the A side.


message:
Reading Infrared raw data

I'm trying to understand a few things about this code.

1. Why is `digitalRead()` slower than `IRpin_PIN & (1 << IRpin)`?
2. What does `IRpin_PIN & (1 << IRpin)` mean? I translated it to numbers and I figured out it's actually `PIND & (0b100)`. What does PIND translate to and why is bitwise-and with `0b100` performed on it?
3. Why is the 20-microsecond delay (`RESOLUTION`) necessary?
4. What does `_BV` in `while (! (IRpin_PIN & _BV(IRpin)))` mean?

---

    /* Raw IR decoder sketch!

     This sketch/program uses the Arduno and a PNA4602 to
     decode IR received. This can be used to make a IR receiver
     (by looking for a particular code)
     or transmitter (by pulsing an IR LED at ~38KHz for the
     durations detected

     Code is public domain, check out www.ladyada.net and adafruit.com
     for more tutorials!
     */

    // We need to use the 'raw' pin reading methods
    // because timing is very important here and the digitalRead()
    // procedure is slower!
    //uint8_t IRpin = 2;
    // Digital pin #2 is the same as Pin D2 see
    // http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
    #define IRpin_PIN      PIND
    #define IRpin          2

    // the maximum pulse we'll listen for - 65 milliseconds is a long time
    #define MAXPULSE 65000

    // what our timing resolution should be, larger is better
    // as its more 'precise' - but too large and you wont get
    // accurate timing
    #define RESOLUTION 20

    // we will store up to 100 pulse pairs (this is -a lot-)
    uint16_t pulses[100][2];  // pair is high and low pulse
    uint8_t currentpulse = 0; // index for pulses we're storing

    void setup(void) {
      Serial.begin(9600);
      Serial.println("Ready to decode IR!");
    }

    void loop(void) {
      uint16_t highpulse, lowpulse;  // temporary storage timing
      highpulse = lowpulse = 0; // start out with no pulse length
    //  while (digitalRead(IRpin)) { // this is too slow!
        while (IRpin_PIN & (1 << IRpin)) {
         // pin is still HIGH
         // count off another few microseconds
         highpulse++;
         delayMicroseconds(RESOLUTION);
         // If the pulse is too long, we 'timed out' - either nothing
         // was received or the code is finished, so print what
         // we've grabbed so far, and then reset
         if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
           printpulses();
           currentpulse=0;
           return;
         }
      }
      // we didn't time out so let's stash the reading
      pulses[currentpulse][0] = highpulse;
      // same as above
      while (! (IRpin_PIN & _BV(IRpin))) {
         // pin is still LOW
         lowpulse++;
         delayMicroseconds(RESOLUTION);
         if ((lowpulse >= MAXPULSE)  && (currentpulse != 0)) {
           printpulses();
           currentpulse=0;
           return;
         }
      }
      pulses[currentpulse][1] = lowpulse;
      // we read one high-low pulse successfully, continue!
      currentpulse++;
    }

    void printpulses(void) {
      Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
      for (uint8_t i = 0; i < currentpulse; i++) {
        Serial.print(pulses[i][0] * RESOLUTION, DEC);
        Serial.print(" usec, ");
        Serial.print(pulses[i][1] * RESOLUTION, DEC);
        Serial.println(" usec");
      }
      // print it in a 'array' format
      Serial.println("int IRsignal[] = {");
      Serial.println("// ON, OFF ");
      for (uint8_t i = 0; i < currentpulse-1; i++) {
        //Serial.print("\t"); // tab
        Serial.print("pulseIR(");
        Serial.print(pulses[i][1] * RESOLUTION , DEC);
        Serial.print(");");
        Serial.println("");
        //Serial.print("\t");
        Serial.print("delayMicroseconds(");
        Serial.print(pulses[i+1][0] * RESOLUTION , DEC);
        Serial.println(");");
      }
      //Serial.print("\t"); // tab
      Serial.print("pulseIR(");
      Serial.print(pulses[currentpulse-1][1] * RESOLUTION, DEC);
      Serial.print(");");
    }

body:
    int digitalRead(uint8_t pin)
    {
     uint8_t timer = digitalPinToTimer(pin);
     uint8_t bit = digitalPinToBitMask(pin);
     uint8_t port = digitalPinToPort(pin);

     if (port == NOT_A_PIN) return LOW;

     // If the pin that support PWM output, we need to turn it off
     // before getting a digital reading.
     if (timer != NOT_ON_TIMER) turnOffPWM(timer);

     if (*portInputRegister(port) & bit) return HIGH;
     return LOW;
    }

1) so it

 - calls function `digitalRead()` (puts value on stack, jumps, prepare function frame - each cost some time)
 - calls 3 other functions (with all the same problems)
 - check for sanity of value
 - check for PWN (and eventually calls another function)
 - does the `PIND & (0b100)`
 - returns from function (so read stack, clear the frame, jumps, set the result)

just to obtain the same functionality

 - typical for library functions, that each call makes sure the environment is sane and expected each and every time it is called - in close loop you can check it onece before and then just do not broke it
 - translates parameter from `nice arduino numbers` to `real addresses and bits` each and every time again

2) it access the PORT D (see AVR (the processor) internal construction) and reads value of its 3. bit (which maps to the relevant pin of the chip/Arduino board

3) see following comment - it is expected length of the pulse (maybe with some safety limit)

4) _BV is for BitValue - shift 1 to position given by arg (that is macro doind 1 << IRpin) maybe more nice/readable version, compiles to the same. (the `!` is ofcourse negaition)


message:
Arduino due - SAM-BA bootloader is it there even if you replace the original chip

On this page http://playground.arduino.cc/Bootloader/DueBootloaderExplained it mentions the sam-ba bootloader is permanently burned into the rom of the chip.

Does this mean even if I buy a new chip from Farnell, it will still have the bootloader in or is just ones that are specifically made for the arduino due?

That is different from say the mega328, with the mega328 I have to burn the bootloader on manually using isp programmer/ buy it preprogrammed.

body:
Yes, for the Due, but No, for a Zero or Adafruit Feather M0.
----------

The Due uses the [Atmel SAM3X8E][1] featuring:

> 16 Kbytes ROM with embedded bootloader routines

As a ROM the contents are fixed during manufacture, so would be there in a new chip.

However it is worth noting that many SAM devices including this one have the NVM bits that are much like the fuse bits on an ATmega.  Here GPNVM bit 1 defaults to 0, enabling the bootloader, but if set to 1 the bootloader will be skipped.   Hence it may well be possible to get one into a state where the bootloader is not available.  They also have an "erase" pin which if driven high during startup will restore the default state (bootloader invoked) of this NVM bit (and erase whatever you put in flash).

----------
In contrast, the Arduino Zero and the Adafruit Feather M0 also use Atmel "SAM" chips with "SAM-BA", however, they use the SAMD21, where the situation [is a bit different][2]:

> Unlike
existing SAM products, ROM monitor is not available in SAM D21 and SAM-BA will
be loaded in Flash memory.

> SAM-BA bootloader is not factory programmed on SAM D21 devices and has to be programmed using an
external programmer.

----------

Incidentally, congratulations on being willing to step beyond the ATmega DIP packages - more people need to learn that surface mounts part (or at least the TSSOP and LQFP varieties) are something that can be worked with by hand.  If you do not have hot air tools, make sure to only solder one corner, check alignment, solder the opposite and recheck, etc.  But hot air will save you so many headaches and a solder station with it is now in the $60-70 range.

Finally, while you do have the bootloader available in the SAM, to really take advantage of all of its capabilities you will want to get an SWD interface - in addition to programming without reliance on the bootloader, this exposes things like breakpoint debugging, which while almost never "necessary" can still be quite convenient and useful.   Atmel used to offer a great deal on the PCB of the SAM-ICE pod less cables kit and housing, unfortunately there was a massive price increase after the Microchip acquisition.

SWD programming is effectively vendor-unique software operations performed on top of a standard signalling scheme, so you do have options for programmers from other sources - you can make a functional if quite slow CMSIS-DAP from an MBED board (or [apparently an Arduino Pro Micro][3]) that will work for debugging but be slow at flashing, you can probably use a Raspberry pi, or the more advanced FTDI devices with the MPSSE engine such as FT232H/FT2232H/FT4232H (but not the everyday FT232RL).  With alternate programmers you will probably need to use something like openocd for the host software - Atmel Studio likely only supports their own and perhaps a few pricey alternatives.

  [1]: http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf
  [2]: http://www.atmel.com/images/atmel-42366-sam-ba-bootloader-for-sam-d21_applicationnote_at07175.pdf
  [3]: https://github.com/myelin/arduino-cmsis-dap


message:
How to calculate the time it takes before the water valve stops dispensing water in an Automatic Water level controller?

I am making a project about an automated water level controller using ultrasonic, potentiometer and Arduino board. I need a mathematical calculation on how it works. So here's a simple scenario:

I have an open top cylindrical container with a radius of 7cm. The ultrasonic sensed that the half height of the container, which is 15cm, is filled with water. At the bottom part of it, a tube with a radius of 1cm is connected alongside with the water valve. How can I calculate the time needed for the water valve to stop dispensing water if I set the potentiometer to keep the level of water at 9cm only? Can you give me a mathematical formula??

I really need a help, please. Any answer will be highly appreciated. Thank you in advance.

body:
The concept you have is more complicated than you can imagine. But to answer your question (which is not so arduino-based), the mathematical formula you looking for is [Torricelli's Law][1].

My suggestion for you is design a system which use a feedback concept instead
[![enter image description here][2]][2]

  [1]: https://en.wikipedia.org/wiki/Torricelli's_law
  [2]: https://i.stack.imgur.com/Mhc03.png


body:
Sounds like it's the valve's time to close (t_vc) + half (statistically) the measurement interval (t_interval) + the software reaction time (t_sw). So

Add whatever measurement interval the software uses, if any, and the valve's time to close, once activated, and the software's time to react (from decision to actually making the valve-close signal) and you should have it. So:

T = t_sw + t_vc + 0.5*t_interval

Any software reaction time should be negilgible for practical purposes, so we're down to:

T = t_vc + 0.5*t_interval

If the software doesn't include sleeps or delays but loops continuously, measuring and deciding, then the half-interval reduces to negligibility leaving just the valve closure time:

T = t_vc


message:
How to delete first voltage reading?

I'm trying out a new ADC, ADS1262, below is the code. I want to discard the first voltage reading.
-----------------------------------------------------------------
    */
    #include <SPI.h>
    #include <SoftwareSerial.h>
    #include <math.h>
    #include <ads1262.h>

    #define PGA 1                     // Programmable Gain = 1
    #define VREF 2.50                 // Internal reference of 2.048V
    #define VFSR VREF/PGA
    #define FSR (((long int)1<<23)-1)

    ads1262 PC_ADS1262;                     // class

    float volt_V=0;
    float volt_mV=0;
    volatile int i;
    volatile char SPI_RX_Buff[10];
    volatile long ads1262_rx_Data[10];
    volatile static int SPI_RX_Buff_Count = 0;
    volatile char *SPI_RX_Buff_Ptr;
    volatile int Responsebyte = false;
    volatile signed long sads1262Count = 0;
    volatile signed long uads1262Count=0;
    double resolution;

    void setup()
    {
      // initalize the  data ready and chip select pins:
      pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
      pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
      pinMode(ADS1262_START_PIN, OUTPUT);               // start
      pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

      Serial.begin(9600);
      //initalize ADS1292 slave
      PC_ADS1262.ads1262_Init();                      // initialise ads1262
      Serial.println("ads1262 Initialised successfully....");

     }

    void loop()
    {
      volatile int i,data;

     if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data   ready(DRDY pin)
      {
        SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
        Responsebyte = true ;
      }

      if(Responsebyte == true)
      {
        for(i = 0; i <5; i++)
        {
          SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
        }
        Responsebyte = false;
      }

      if(SPI_RX_Buff_Count >= 5)
      {

        ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
        ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
        ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
        ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

         uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|      ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
         sads1262Count = (signed long) (uads1262Count);      // get signed value
         resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
    // Serial.print(resolution,15);
         volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
         Serial.print(volt_V,8);

       }

      SPI_RX_Buff_Count = 0;

    }

    float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
    {
      return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    }

body:
Simplest way is to have a flag to specify whether you've read the first reading or not.  Default to zero:

    int read_first = 0;

Then you can say:

    if (read_first ) {
        volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
        Serial.print(volt_V,8);
    }
    else {
       // discarded first result, now we've read the first one
       read_first = 1;
    }


body:
Here is what the code shown in the other answer will do.

    int read_first = 0;

That allocates `read_first` and sets it to zero.

    if (read_first ) {
        volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
        Serial.print(volt_V,8);
    }
    else {
       // discarded first result, now we've read the first one
       read_first = 1;
    }

First time in, `read_first` evaluates false, so the `else` branch will be taken, and `read_first` set to 1.  Note that no reading has been taken yet, so the  “// discarded first result, now we've read the first one” comment is incorrect and irrelevant.  Second and later times in, `read_first` evaluates  true, so `volt_V` readings will be taken and printed.

To correct the problems with that code, use an approach like the following.

    int useReading = 0;
    ...
    volt_V = resolution*(float)sads1262Count;
    if (useReading ) {
        Serial.print(volt_V,8);
        // and otherwise use the reading as desired
    }
    useReading = 1;

After this takes a first reading, it doesn't use that reading because `useReading` evaluates false.  Subsequent readings get used because `useReading` is turned on after the first reading.


message:
"port" is greyed out in 1.6.13, running win 10 for an Uno R3

I am new to this, and my kid got an Elegoo smart robot car kit v2.0 for Christmas. We assembled the car, but after downloading the software, the program always states:

> Arduino: 1.6.13 (Windows Store 1.6.13.0) (Windows 10), Board: "Arduino/Genuino Uno"
>
> Sketch uses 2,242 bytes (6%) of program storage space. Maximum is 32,256 bytes.

>Global variables use 210 bytes (10%) of dynamic memory, leaving 1,838 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

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

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

I don't know what other information is important. Can somebody please help me?

Thank you.

body:
When the port is greyed out its not available (I know you had worked that out) so you have a problem with you serial to USB drivers.

Looking at the kit I think you are connecting the UNO to a USB port on your PC/laptop using a blue cable.
 1. Please can you check that the cable is connected properly.
 2. Can you try a different USB port on the PC (don't use a USB hub - some don't work).
 3. Does Windows recognise a device has been plugged?
 4. Are you running it as administrator, you will need to be to install the drivers.
 5. Can you try connecting it to a different PC?

If these don't fix it then, please comment and well go through looking at the device manager.

Hope it works, it looks like fun.


message:
NodeMCU sensor values to web page

I post NodeMCU sensor values to a web page. But how can I pass those values to a database using PHP?

Here is the code to post sensor values to a web page:

    #include <ESP8266WiFi.h>

    const char* ssid = "CDS_ARDUINO";
    const char* password = "arduinotest@wifi";

    WiFiServer server(80);

    void setup() {
      Serial.begin(115200);
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("WiFi connected");
      // Start the server
      server.begin();
      Serial.println("Server started");
      // Print the IP address
      Serial.print("Use this URL : ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");
    }

    void loop() {
      WiFiClient client = server.available();
      if (!client) {
        return;
      }
      // Wait until the client sends some data
      Serial.println("new client");
      while(!client.available()){
        delay(1);
      }
      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println("Connnection: close");
      client.println();
      client.println("<!DOCTYPE HTML>");
      client.println("");
      client.println("<meta http-equiv=\"refresh\" content=\"3\">");
      client.println("
Getting NodeMCU Analog values
");
      int sensorReading = Serial.read();
      client.println("");
      client.println("");
      client.println("
");
      client.println("");
      client.println("");
      client.print("
");
      client.println("");
      client.print("&nbsp &nbsp &nbsp &nbsp &nbsp");
      client.print(" Analog input value is ");
      client.println("");
      client.print(sensorReading);
      client.print("
");
      client.println("");
      delay(100);
      Serial.println("Client disconnected");
    }

body:
Before your question gets closed, since it's only merely related to Arduino, I'd like to post this answer to give you more of an clue on how to set up the system.

 1. Connect PHP and the database of your choice.
 2. Connect the Arduino to PHP (probably with TCP/IP or HTTP), to send the values to the database.
 3. Use PHP (+ webserver) to generate and serve webpages.

Only point 2 is somewhat related to Arduino.SE, so I'll try to give you some "handles" to get started.

https://www.arduino.cc/en/Tutorial/WebClient

https://www.arduino.cc/en/Tutorial/HttpClient

You can issue a GET request with variables to a webpage using Arduino.
In PHP you can [read out these variables][1].
And using PHP you can [connect][2] and [send][3] variables to your database.

*You shouldn't connect the Arduino directly to the database, because exposing your database to the world wide web is a security risk.*

After this, it will be relatively easy to generate a page with the contents from your database.

  [1]: http://php.net/manual/en/reserved.variables.get.php
  [2]: http://www.w3schools.com/php/php_mysql_connect.asp
  [3]: http://www.w3schools.com/php/php_mysql_insert.asp


message:
Creating linear motion using motor

I am trying to make a smart lock for bicycles. This lock can be controlled with the help of smartphones. For the purpose, I am using an Arduino interfaced with HC-05 Bluetooth Module which receive commands from an Android smartphone.

The overall project is almost over, except the actual lock. I want to create a lock with a pin which can be slide between the spokes of the wheel to cease the motion of the wheels. I can't find any product in the Indian market. Can you please suggest any product available or how to make one myself?

> I've seen the solenoid locks but their stroke is too small to make a meaningful lock out of it.

Your help will be well appreciated.

body:
The pin that slides between the spokes should be just a metal bar that accepts your "small" pins in the ends to hold it in place.  Try looking at it from a different perspective and I think you will find a lot more suitable products.

You could use a worm gear, but this would be susceptible to bruit force attacks (literally) and would be easier to break.

Have you considered what happens when the power fails?  Does the lock lock or unlock?  If it unlocks on a power fail then it will be quite easy to open.  If it remains locked on a power fail then its not very user friendly, you would have to carry spare batteries and changing tools with you.

Sorry, but it is easy to poke holes in other peoples designs.


message:
Vary the length of square waveform

[![Inverted Square waveform][1]][1]

Here in figure,  we can see two waveforms.

Below one is waveform of raw RPM signal. I want to find square waveform which based on that LOW INTERVAL of RPM signal and length must vary according our requirement. So for that purpose, I just made inverter circuit using 74HC14 and Low pass filter(for removing noise).

As a result of that circuit, I got Upper one waveform means square wave signal. Now, you can see it has also one spike beside square wave(I don't want that). And I can't vary length because inverter circuit gives only perfect inverting signal.

Is it possible to make square wave like this and also vary the length of that square wave with help of Arduino?

Here, I want to use Arduino because I have to vary the length of square wave with help of programming.  For example, if I want 10ms square wave then just enter value 10 in programming then generate 10ms square waveform. Rising edge must be same. And right now, I have no clue or idea how to do this.

If possible then please give me some suggestion how to do this.

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

body: The most steightforward decision is to use this spike to trigger interrupt in Arduino. The interrupt procedure starts one of the counters and sets 1 at one of the pins. After N milliseconds by counter or by inner timer the Arduino outputs 0 to the same pin, so you will have needed length of the positive pulse. This will work while pulse length will be less then time between successive spikes. Do not forget to make standard spike amplitude enough to start interrupt, but not too big not to damage Arduino. Of course you can work without interrupts, just testing the input in main cycle, but it will be less presise. You will need a decision, how to conveniently control the pulse length by some tool. It can be infrared pult or some other tool and you must see the set time value, so you will need to use some indicator. May be LCD  1602 keypad shield will be enough for this.


message:
Regarding PGA bypass in ADS1262

I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.

I have taken the reference of example given in [this][1] library.

I have interfaced [protocentral-ads1262-32-bit-precision-adc-breakout-board][2] with Arduino Ethernet Board.

In the example, I have put `#define VREF 5` but it shows the double the input voltage in serial window and when I put `VREF 2.5`, it shows regular input voltage.

For input voltage range 0 to 5V (single signal), I need to bypass the PGA but I dont know how to do it.

When the input signal is more than 2.5V then it always give the 2.5V only. If the input signal is, say 4.86V then it should give 4.86V but its gives 2.5V.

  [1]: https://github.com/Protocentral/ProtoCentral_ads1262
  [2]: https://www.protocentral.com/analog-adc-boards/1005-protocentral-ads1262-32-bit-precision-adc-breakout-board-0642078949630.html

body:
You don't want to bypass the PGA.

By default the chip uses the 2.5v internal reference. You need to switch that to using AVDD/AVSS as the voltage reference. If the library doesn't allow that you will have to do it manually referring to the datasheet.


body:
> I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.

Look at the register map. it should allow you to by pass the pga.

> In the example, I have put #define VREF 5 but it shows the double the input voltage in serial window and when I put VREF 2.5, it shows regular input voltage.

Simple solution: divide the library's output by 2.

Right solution: the library likely doesn't support bipolar output. So re-write  your own.


message:
Arduino Uno with PWM driven motor and 433 MHz wireless receiver don't work

I am fairly new to the Arduino topic and I'm trying to get a few things to work together.

At the moment I'm using an Arduino Uno board, but planning to use an Arduino Nano for this.

First I tried setting up a DC motor that can be controlled via PWM, which works perfectly when used standalone. I can start/stop the motor and change speed depending on the value I send to the PWM pin.

Next, I tried to use an RF-5V wireless receiver to work with a remote control from remote switched power outlets. For this one I followed the instructions on [how to build a 433 MHz sniffer][1]. This all by itself works as well. I can receive different codes depending on which keys on the remote I am pressing.

Now the fun part started: I wanted to integrate both projects into one, so I could use the remote to start/stop the motor. So I came up with the following circuit:

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

(The sketch is updated so it shows the right pins matching the code)

And the following code (which is partly from the instructions mentioned above):

    #include <RCSwitch.h>

    // init 433MHz lib
    RCSwitch mySwitch = RCSwitch();
    unsigned long lOldValue=0;  // to check for consecutive reads on 433MHz
    int motorPin = 5; // PWM-Pin to use for motor

    void setup() {
      pinMode(motorPin, OUTPUT);
      Serial.begin(9600);
      // set-up rf receiver
      mySwitch.enableReceive(0);
      // 433MHz Receiver on interrupt 0 => that is pin #2
    }

    void loop() {
      if (mySwitch.available()) {
        int value = mySwitch.getReceivedValue();
        // only react, if at least two times same value received
        if (value == lOldValue) {
          if (value == 0) {
            Serial.print("Unknown encoding");
          } else {
            Serial.print("Received ");
            Serial.print( mySwitch.getReceivedValue() );
            Serial.print(" / ");
            Serial.print( mySwitch.getReceivedBitlength() );
            Serial.print("bit ");
            Serial.print("Protocol: ");
            Serial.println( mySwitch.getReceivedProtocol() );
            // One of the keys on the remote
            if (value == 274393) {
              Serial.println("got start code, starting motor");
              analogWrite(motorPin, 100); // start the motor
            }
            // another key on the remote
            if (value == 270384) {
              Serial.println("got stop code, stopping motor");
              analogWrite(motorPin, 0); // stop the motor
            }
          }
        }
        lOldValue = value;
        mySwitch.resetAvailable();
      }
    }

When I run the code and click on the remote, I get different values shown depending on the key I press. So the wireless receiver works as expected.

When I receive the right value for starting the motor, the motor really begins to turn, so this works as well.

And here the fun part starts:

As soon as I use the `analogWrite` function to send data to the PWM port the motor is connected to, the wireless receiver stops working (or at least I do not get any more values when pressing a key on the remote).

I found a few similar posts/problem descriptions on the net which said to try the following:

- Use another pin for PWM (due to possible interrupt conflicts). I tried that as well, same behaviour.
- Use external power supply instead of USB-Cable, which helped somebody resolve this issue. Not here. Does not work either.

**So the question is:**

Does anybody know how to combine those two things together so I can use the wireless receiver to get commands and switch on/off the motor with it on an Arduino Uno?

And would this solution probably work with an Arduino Nano as well?

**Update:**

I changed the motor against a LED, same behaviour. So its not related to the motor itself.

I found out that when i use some timers to set the motor pwm to 0 with the analogWrite function, that the wireless receiver starts working again.
So it really looks like there is no way to use PWM and the wireless receiver together.

I also changed the pin for the receiver from 2 to 3 (and of course changed the code to use the right pin) and used other PWM pins for using with the motor. But still to no success.

Does anyone have an idea on how to bring both the wireless receiver and PWM driven things to work together? Might this be an hardware issue (due to interrupts) or a library issue for the rcswitch?

  [1]: https://blog.thesen.eu/433mhz-und-rfid-sniffer-auf-arduino-basis/
  [2]: https://i.stack.imgur.com/yK81R.png

body: You are asking too much from the Arduino if you expect it to drive a motor with only the on-board 5V regulator AND the radio. Eliminate at least the motor connection to the 5V and use a MOSFET to drive the motor with a stand-alone power source like an alkaline battery pack of at least 6V - You need current to drive a motor and the UNO is limited to 500mA. Once you PWM the MOSFET, it should handle the motor with ease. A IR510 is good for this use. You will need a 10K pull-down resistor to the Gate Pin to keep it LOW when no signal is present.  This should get you going in the right direction. 0.01 ceramic filter capacitors to the - and + leads to ground around the motor is also helpful. Look up on-line how others do this.


message:
Detecting I2C transfer with LED

I am going to do a project with a lot of Arduinos connected via I2C, where like of them can became master for a moment to announce an event. So I would like to see how much is the bus used. As there will be a central point, I thought about putting a LED there, from +5V to clock line, so it would shine when the transfer occurs and be black when the line is free. And so I would be able to guess the utilisation level of the bus. (The clock is effectively PWM going to zero often while in transfer, while being plain +5V when no transfer is active).

Of course direct connection is not the best idea, as it would disrupt the pull-ups and mess with the protocol (as it would drain a lot of power to clock each time it went down), there should be some separator/amplifier.

The question is - does anybody know a simple setting, where the LED would be driven by a small current to zero (that is inverting amplifier as simple as possible with high enough input impedance to not disturb I2C communication)?

Thanks for all hints :)

body:
It can be done with two N-channel MOSFETs or one P-channel MOSFET (depending on what you have locally / can get / is in your bits box):

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

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

<!-- End schematic -->

In the left schematic the first MOSFET acts like a NOT gate, and the second is a simple low-side switch. The pair together make an active-low low-side switch.

The right hand schematic, which is somewhat simpler, uses a single P channel MOSFET as a high-side switch. This is normally driven with an N-channel MOSFET to invert the logic, since it is naturally active-low. You don't want that, so you can just connect direct to the gate.

Note that all MOSFETs are "logic level" with a threshold voltage below 3V (or -3V in the case of the P-channel).


message:
Arduino Nano 3.0 dimensions without the pins

I think the title of this question is quite clear. I am looking for the exact dimensions of the Arduino Nano 3.0, with the electronic components and the USB mini port on the IC (the Atmega328 one), without the external pins.

body:
Mini-USB-B is around 4mm tall.

Most PCBs are around 1.6mm.

The FT232RL on the bottom is 2mm (max) according to the datasheet. (voltage regulator is 1.8mm). (I'm sure about this tantalum capacitors)

So that's something around 7.6mm total height


body: I have a nano so let me get a ruler, ok. The usb port takes up most of the room so 4mms, the board itself is 1mm and a tiny chip adds 2mms as well. So 7mms! Hope this helped!


message:
Touch-screen, 3 H-bridges and 3 sensors on Arduino Nano 3.0

I am using an Arduino Nanao andI am wondering if there is a way to connect an 2 inch touchscreen, 3 H-bridges (it takes 3digital pins to power one of them and 1 additional to control the voltage) and have 3 analog pins left for sensors?

body:
I think, that there is at least one I2C touchscreen (eg. https://www.adafruit.com/product/1947 )(I2C need 2 pins - SCL(A5)+DATA(A4) - given by HW) and if you need 3x3=9 digital pins for setting direction, you can use also I2C multiplexer on the same 2 pins (http://playground.arduino.cc/Code/I2CPortExpander8574). So you are left with need for 3 PWM pins from (D3,D5,D6,D9,D10,D11).

So there is a way for sure.


message:
Unspecified running error while programing WeMos D1 in wireless mode

I've tried to program `WeMos D1` directly by wireless connection. I've test my `D1` so it had no problem. after setting `SSID` and `Password` I've programed it for wireless using. It ran well. as I want to programing thought wireless there was an Unspecified error for running `python.exe` !

    java.io.IOException: Cannot run program "python.exe": CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
        at processing.app.helpers.ProcessUtils.exec(ProcessUtils.java:26)
        at cc.arduino.packages.Uploader.executeUploadCommand(Uploader.java:129)
        at cc.arduino.packages.uploaders.GenericNetworkUploader.uploadUsingPreferences(GenericNetworkUploader.java:99)
        at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
        at processing.app.SketchController.upload(SketchController.java:709)
        at processing.app.SketchController.exportApplet(SketchController.java:682)
        at processing.app.Editor$DefaultExportHandler.run(Editor.java:2190)
        at java.lang.Thread.run(Thread.java:745)
    Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
        at java.lang.ProcessImpl.start(ProcessImpl.java:137)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
        ... 8 more
    An error occurred while uploading the sketch

I've python on my PC  and it works. to clear my problem I've attached  the following `gif`

[![the gif][1]][1]

any help would be appreciated.

  [1]: https://i.stack.imgur.com/YWEyP.gif

body:
You might have Python installed, but can you run it?

Open a command window on you PC.  (Windows button R then CMD)
Then in that type python.

If python starts up then it should be working, but I suspect you will get an error saying:

`'python' is not recognized as an internal or external command, operable program or batch file.`

To fix this you need to edit you path and restart the IDE.  (How you edit you path depends on your version of Windows so you would be best searching for `edit environment path` and your version of windows and that should come back with an answer quickly.

Of course if its Linux/mac then it could still be the same issue.


message:
avrdude: stk500_recv(): programmer is not responding after serial

I have searched but have not found any solution to my problem so I am asking it here.  I make a program in python that makes serial communication with the Arduino. I started to upload my Arduino code but I forgot that my python program was open in the terminal (I use Ubuntu). So, I think the Arduino code and python output went to the same port which the Arduino is on. After that I couldn't upload any code into the Arduino.

Every time it prints the following error:

> avrdude: stk500_recv(): programmer is not responding
> avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

and then makes more 9 attempts.
Any help?

body:
Likely all you really need to do is exit/kill every process trying to use the Arduino, un-plug it from the USB port, and plug it back in.

This is in part because Linux doesn't really block multiple programs from trying to use the serial device at the same time, unless they take particularly efforts to claim it exclusively, but the attempted sharing may result in serial traffic that doesn't make any sense.

Another issue can be that if a still-running program was using a device that vanished, when that device is reconnected it will not be assigned to the in-use port number, but to a free one.


message:
Arduino Uno as keyboard

I am trying to make Arduino Uno to act as a keyboard. I have successfully flashed the USB-HID firmware in it using [this link][1] also and programmed it like this.

    uint8_t buf[8] = {
     0
    };

    int inpin1 = 7;
    int inpin2 = 8;
    int val1 = 0;
    int val2 = 0;

    void setup() {
      Serial.begin(9600);
      delay(200);
      pinMode(inpin1, INPUT);
      pinMode(inpin2, INPUT);
    }

    void loop() {
      val1 = digitalRead(inpin1);
      if(val1 != HIGH) {
       buf[2] = 80; // Left Arrow
       Serial.write(buf, 8);
       releaseKey();
      }
      val2 = digitalRead(inpin2);
      if(val2 != HIGH) {
        buf[2] = 79; // Right Arrow
        Serial.write(buf, 8);
        releaseKey();
      }
    }

    void releaseKey() {
      buf[0] = 0;
      buf[2] = 0;
      Serial.write(buf, 8);
    }

The above code works fine but the problem is that when I tried to play a game, which uses right arrow and left arrow, and to control a car I was using the push button, which I connected to Arduino as left and right arrow keys. But suppose I want to turn a car. I have to press the key and then release the key to move it a very little to the right or left. So, if I want to turn the car either left or right, I have to press and release so many times that it becomes impossible to play the game. Do you anyone know how to resolve this problem?

  [1]: http://mitchtech.net/arduino-usb-hid-keyboard/

body:
You should just not call the `releaseKey` function, until the button is released.

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

    int oldVal1 = 0;
    int oldVal2 = 0;

    void loop()
    {
        val1 = digitalRead(inpin1);
        if( val1!=oldVal1 )
        {
            oldVal1 = val1;
            if(val1 != HIGH)
            {
                buf[2] = 80; // Left Arrow
                Serial.write(buf, 8);
            }
            else
            {
                releaseKey();
            }
        }

        val2 = digitalRead(inpin2);
        if( val2!=oldVal2 )
        {
            oldVal2 = val2;
            if(val2 != HIGH)
            {
                buf[2] = 79; // Right Arrow
                Serial.write(buf, 8);
            }
            else
            {
                releaseKey();
            }
        }

    }


message:
Arduino Starter Kit - firmly wiring longer parts

I am getting started with project 01 on the Arduino starter kit. I'm facing an issue when wiring parts with long ends e.g. led & resistor. To make the simple circuit with led, resistor & switch work, I have to hold down the resistor & led, and then press the button. The parts don't connect well to the wires underneath the breadboard.

I want ask if someone could suggest how to better deal with such parts. On searching, I found people cut their parts short, but are there other approaches ?
Thanks.

body:
Cutting them short is proven solution, but there is sometimes still problem with legs too thin to fit good.

Other, even more reliable, is to solder them to pinheader https://commons.wikimedia.org/wiki/File:16_Pin_Header.jpg (just break away 2 or 3 pins depending on how many legs you need). Works even for SMD resistors and diodes https://divnoblog.files.wordpress.com/2015/10/005-odpor_1.jpg

Also you can use small piece of universal stripboard https://en.wikipedia.org/wiki/Stripboard / perfboard https://en.wikipedia.org/wiki/Perfboard, to solder anything on that and solder the pinheader under it. Works perfectly for switches etc.

(of course you can buy "modules" from any suplier, where is the part, maybe accompanied by one or two resistors or such, but the price is higher, than is you do it manually at home and there is not such wide range, as is in normal analog/digital parts, which you can solder to fit your needs)

The problem with https://en.wikipedia.org/wiki/Breadboard is, that usually the holes are good just for the pinheader-sized legs (a lot of IC have the right dimensions too), while nearly any pasive/simple parts are much thinner and do not fit reliably. But for some fast playing with and non-critical application it is usually usable enough.


message:
DHT sensors with RGB LED

I have a DHT11 that outputs temperature and humidity values to my serial monitor. I'm trying to serial the **COLOUR** of the light based on the temperature conditions. So far I only get `1`'s and `0`'s. How can I change these integer values to output string say `RED`, `GREEN` or `BLUE`?

**Code**

    #include <dht.h>

    dht DHT;
    #define DHT11_PIN A5
    int redPin = 10; // Red LED,  connected to digital pin 10
    int grnPin = 9; // Green LED, connected to digital pin 9
    int bluPin = 8;  // Blue LED, connected to digital pin 8

    void setup() {
      Serial.begin(9600);
      // Sets the pins as output for RGB LED
      pinMode(redPin, OUTPUT);
      pinMode(grnPin, OUTPUT);
      pinMode(bluPin, OUTPUT);
    }

    void loop() {
      int chk = DHT.read11(DHT11_PIN);
      int t = DHT.temperature;
      int h = DHT.humidity;
      Serial.print("Temperature = ");
      Serial.print(t);
      Serial.print( "," );
      Serial.print("Humidity = ");
      Serial.print(h);
      Serial.print("\n");
      delay(60000);
      if((DHT.temperature < 26) && (DHT.temperature >= 23.2)) {
        // Writing the LED colour pins HIGH or LOW to set colours
        digitalWrite(redPin, HIGH); // yellow
        digitalWrite(grnPin, HIGH);
        delay(100);
        digitalWrite(bluPin, LOW);
      }
      if((DHT.temperature < 23) && (DHT.temperature > 20.2)) {
        digitalWrite(grnPin, HIGH); // green
        delay(100);
        digitalWrite(redPin, LOW);
        digitalWrite(bluPin, LOW);
      }
      if((DHT.temperature < 20) && (DHT.temperature > 17.2)) {
        digitalWrite(grnPin, HIGH); // aqua
        digitalWrite(bluPin, HIGH);
        delay(100);
        digitalWrite(redPin, LOW);
      }
      if(DHT.temperature <= 17) {
        digitalWrite(bluPin, HIGH); // blue
        delay(100);
        digitalWrite(grnPin, LOW);
        digitalWrite(redPin, LOW);
      }
      delay(1000);
      // Sensor shouldn't be read too frequently so delay of 1s
    }

I will be grateful if I can get some help. Thanks!

body:
You need to use `analogWrite()`. You use this with a digital pin and it does Pulse Width Modulation (PWM) which will give you are larger range of colours. Have a look at the Reference page for the function.

You might even be able to use the `map` function (something like that) to 'map' the temperature to the colour values without all the if statements.


body:
> So far I only get 1's and 0's

Before moving into the LED parts, you have to make sure that your system can correctly read the DHT sensor. There are debugging example from [arduino-info.wikispaces.com][1]

>  How can I change these integer values to output string say RED, GREEN or BLUE?

You can do it by simple `if-else` statement. This would be better than your original code, because there are multiple `if`'s without any `else` which is (although not so significant) less optimal.

So, if put together, you can try:

    void loop()
    {
      int t,h,chk = DHT.read11(DHT11_PIN);

      switch (chk)
      {
        case DHTLIB_OK:
                    Serial.print("OK,\t");
                    break;
        case DHTLIB_ERROR_CHECKSUM:
                    Serial.print("Checksum error,\t");
                    break;
        case DHTLIB_ERROR_TIMEOUT:
                    Serial.print("Time out error,\t");
                    break;
        case DHTLIB_ERROR_CONNECT:
            Serial.print("Connect error,\t");
            break;
        case DHTLIB_ERROR_ACK_L:
            Serial.print("Ack Low error,\t");
            break;
        case DHTLIB_ERROR_ACK_H:
            Serial.print("Ack High error,\t");
            break;
        default:
                    Serial.print("Unknown error,\t");
                    break;
      }
      //moving on into next parts only if you get "OK" from serial reply, which means you successfully read the DHT11
      t = DHT.temperature;
      h = DHT.humidity;
      Serial.print(DHT.humidity, 1);
      Serial.print(",\t");
      Serial.println(DHT.temperature, 1);

      //----end of sensor reading and debugging

      if (t<=17)
      { //blue
       digitalWrite(bluPin, HIGH);
       digitalWrite(grnPin, LOW);
       digitalWrite(redPin, LOW);
       delay(100);
      } else
       if (t<20)
       {
        digitalWrite(grnPin, HIGH);  // aqua
        digitalWrite(bluPin, HIGH);
         digitalWrite(redPin, LOW);
        delay(100);
       } else
       if (t<23)
       {
      //....
       }
       //....
       //and goes on

     delay(1000);
    }

And yes, as @Matt suggest, it would be better if you use PWM to control the RGB led which will give you (mathematically) 255*255*255 colour possibilities instead of 8 combinations from `digitalWrite()`. For example:

    //....
    //....
      if (t<20)
      { //aqua
       new_t = map(t,DHT11_min_temperature_reading,DHT11_max_temperature_reading,0,255);
       //you can do self research about DHT11 maximum and minimum temperature reading
       //parameters 0 and 255 is the minimum value of PWM(0) and the maximum value(255)
       AnalogWrite(bluPWMPin, new_t);
       AnalogWrite(grnPWMPin, 255-new_t);
       AnalogWrite(redPWMPin, 0);
       delay(100);
      }
    //....
    //....

Hope it helps :D

  [1]: https://arduino-info.wikispaces.com/DHT11-Humidity-TempSensor


message:
Timer3 Arduino maximum period

At the moment I'm trying to learn microcontrollers with Arduino, and have a problem with the timer.

Arduino works at 16MHz clock, and the best prescaler is 1024, which means the timer increments the value every 64 us. Timer 3 is a 16 bit timer, which gives us a maximum time of 64*65535= 4194240, ca. 4s

But what if I want to do a job every 8 seconds? Any idea?

Here's my code:

    TCCR3A = 0;
    TCCR3B = 0;
    TCCR3B |= (1<<WGM32); //CTC
    TCCR3B |= (1 << CS32);
    TCCR3B |= (1 << CS30);// 1024 prescaler
    TIMSK3 |= (1<<OCIE3A);
    sei();

body:
You can't - not directly. Instead you do a job at a higher frequency which just counts. When it has counted enough you do your other job.

For instance, you might trigger your interrupt once a second. That interrupt just adds 1 to a count and returns. Unless that count just hit 8, when you reset the count to 0 and run your 8 second routine.


body:
You know that the inbuilt function `millis()` would let you achieve that goal?

For example:

    unsigned long startTime;

    void loop ()
      {
      if (millis () - startTime >= 8000)
        {
        startTime = millis ();  // reset start time to now
        // do something that needs doing every 8 seconds
        }

      // do other stuff

      }  // end of loop


body: If the 5% error (~4.2 sec vs. 4.0 sec) isn't a problem, 2 counter overflows will give 8 seconds with the same 5% error, or ~8.4 sec. If you need higher accuracy, either start the timer with a slightly smaller initial counter value, (62500 * 64 = 4000000 uSec), choose a divider value that naturally overflow at convenient sub-multiples of the intervals your program will need, and again count N overlows of the timer before your code responds.


message:
Understanding SevSeg

I need to write a library for a display I created with eight segments. So, I decided to try to use SevSeg (https://github.com/DeanIsMe/SevSeg) as a starting off point. It can't be *that* different, right?

Well, I think I have hit a roadblock that indicates I must basically do everything from scratch. Here is how the information on what segments correspond to letters are stored in SevSeg:

     // The codes below indicate which segments must be
    //illuminated to display each number.

    static const byte digitCodeMap[] = {
      //     GFEDCBA  Segments      7-segment map:
      B00111111, // 0   "0"          AAA
      B00000110, // 1   "1"         F   B
      B01011011, // 2   "2"         F   B
      B01001111, // 3   "3"          GGG
      B01100110, // 4   "4"         E   C
      B01101101, // 5   "5"         E   C
      B01111101, // 6   "6"          DDD
      B00000111, // 7   "7"
      B01111111, // 8   "8"
      B01101111, // 9   "9"
      B01110111, // 65  'A'
      B01111100, // 66  'b'
      B00111001, // 67  'C'
      B01011110, // 68  'd'
      B01111001, // 69  'E'
      B01110001, // 70  'F'
      B00111101, // 71  'G'
      B01110110, // 72  'H'
      B00000110, // 73  'I'
      B00001110, // 74  'J'
      B01110110, // 75  'K'  Same as 'H'
      B00111000, // 76  'L'
      B00000000, // 77  'M'  NO DISPLAY
      B01010100, // 78  'n'
      B00111111, // 79  'O'
      B01110011, // 80  'P'
      B01100111, // 81  'q'
      B01010000, // 82  'r'
      B01101101, // 83  'S'
      B01111000, // 84  't'
      B00111110, // 85  'U'
      B00111110, // 86  'V'  Same as 'U'
      B00000000, // 87  'W'  NO DISPLAY
      B01110110, // 88  'X'  Same as 'H'
      B01101110, // 89  'y'
      B01011011, // 90  'Z'  Same as '2'
      B00000000, // 32  ' '  BLANK
      B01000000, // 45  '-'  DASH
    };

As you can see this is a one dimensional array of 8-byte binaries that encode the segment. I don't understand the purpose of the B0 at the beginning of each byte. Could I use the 0 column to encode my eighth segment?

Am I right to assume this will change everything about the code and maybe I should start from scratch with a 2-D array?

This is roughly what I want:

    //  ABCDEFGH  Segments      8-segment map:
      11000011, // 0   "0"       A BBBBB H
      10000000, // 1   "1"       A C   D H
      01011010, // 2   "2"       A C   D H
      11101010, // 3   "3"       A  C D  H
      00110101, // 4   "4"       A  E F  H
      01011010, // 5   "5"       A E   F H
      11101110, // 6   "6"       A E   F H
      01011000, // 7   "7"       A GGGGG H
      01111110, // 8   "8"
      01100101, // 9   "9"
      11111101, // 10  "A"
      10001110, // 11  "b"
      11000010, // 12  "C"
      00001111, // 13  "d"

What data type should I use for the array? Would byte work since I'm not using the B0?

Thanks.

body:
> I don't understand the purpose of the B0 at the beginning of each byte.

That's just Arduino's rather weird way of doing binary constants. For example, in the file binary.h are lines and lines of stuff like this:

    #define B1011 11
    #define B01011 11
    #define B001011 11
    #define B0001011 11
    #define B00001011 11
    #define B1100 12
    #define B01100 12
    #define B001100 12
    #define B0001100 12
    #define B00001100 12

A better way is to use standard C++ constants, eg.

    0b00001100

instead of:

    B00001100

---

> Could I use the 0 column to encode my eighth segment?

Yes, they are just bytes, so you can use all 8 bits.


message:
Can't power mg2639 cellular shield with battery

I have a SparkFun MG2639 cellular shield attached to an Arduino Uno R3.  I have had both the cell modem and the GPS unit working when the shield is powered from the Uno.  I followed the [instructions on SparkFun's site][1] to switch the shield to be powered by battery (cut SJ2, short SJ3) and connected a fully charged Li-ion battery.  I measure over 4.1 volts at the battery connection pads on the shield but the power LED isn't on and the shield isn't responding.  It looks as though it's not getting any power.  I also powered it from my bench supply with 5V and it shows no current draw.

Did I miss something in the conversion instructions?

  [1]: https://learn.sparkfun.com/tutorials/mg2639-cellular-shield-hookup-guide/supplying-power

body: Turns out the soldered short of SJ3 was not complete.  After resoldering the shield powers up as expected.


message:
Why does static member std::map reset ESP8266 when outside the .ino file?

Here's an example of a class which crashes the ESP8266-03 causing it to reset:

Test.hpp file:

    #include <map>

    class Test {
    public:
        int data() const;

        Test(int x);
        ~Test();
    protected:
        int _data;

        static std::map<int, Test const *>thing;

        static void _Reserve(Test const * const t);
    };

Test.cpp file:

    std::map<int, Test const *> Test::thing;

    int Test::data() const
    {
        return this->_data;
    }

    void Test::_Reserve(Test const * const t) {
        Test::thing[t->data()] = t; // Works fine if this line is removed.
    }

    Test::Test(int x): _data(x)
    {
        Test::_Reserve(this);
    }

    Test::~Test() {};

Project.ino:

    #include "ESP8266WiFi.h"
    #include "Test.hpp"

    Test test(2);

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

    void loop() {
        Serial.print("Timer: ");
        Serial.println(millis());
     delay(1000);
    }

The following **does NOT** crash the ESP8266-03 and prints the time as it should:

    #include "ESP8266WiFi.h"
    #include <map>

    class Test {
    public:
        int data() const
        {
            return this->_data;
        }

        Test(int x): _data(x)
        {
            Test::_Reserve(this);
        }
        ~Test() {};
    protected:
        int _data;

        static std::map<int, Test const *>thing;

        static bool _Reserve(Test const * const t) {
            Test::thing[t->data()] = t;
        }
    };

    std::map<int, Test const *> Test::thing;

    Test test(2);

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

    void loop() {
        Serial.print("Timer: ");
        Serial.println(millis());
     delay(1000);
    }

When the first version is uploaded to the board, I get the following in the serial monitor:

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

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

    wdt reset

When I reset it and boot it regularly, no upload mode, the following repeats every ~1 second:

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

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v09f0c112
    ~ld

body:
> Why does static member std::map reset ESP8266 when outside the .ino file?

What happens if the Test() constructor is run before the map constructor? This is the problem: you are assuming order of execution.

Use a Singleton pattern or init() member function to force the ordering that is required.

Cheers!


message:
why leonardo bootloader is bigger than UNO?

Apparently leonardo and UNO are very similar boards.

However, despite that both have the same flash memory size, Leonardo bootloader is considerably bigger than UNO bootloader (4KB vs 0.5KB).

what would be the reason? it is there any way to use smaller bootloader in leonardo?

Uno specs: [https://www.arduino.cc/en/Main/ArduinoBoardUno][1]

Leonardo specs: [https://www.arduino.cc/en/Main/ArduinoBoardLeonardo][2]

Thanks!

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardUno
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

body:
> Apparently leonardo and UNO are very similar boards.

No, they are very, very different.

The Uno uses an external USB-UART bridge. This means that the bootloader code only has to read from the UART in order to program the device.

The Leonardo has USB support built into the MCU. This means that the bootloader must contain an entire USB Device stack in order to process the USB packets and then pass the payload to the programming routines.


message:
Find the time between HIGH state & LOW state of push button(switch)

I want to find the timing between HIGH state and LOW state of push button. For that, I made a program. You can see my program below. In my program, I made logic like that when switch is pressed then one variable "currentMillis" store the value of millis() and it store value until button pressed. But whenever I pressed button again then it also add previous value. For example, if button pressed for first time then suppose we got 200ms, now suppose if button pressed second time then we got 500ms and if button pressed third time then we got 1000ms. That mean every time value added. No doubt I made a logic which seem to be perfect but I can't figure out what is problem. Please give me some suggestions.

    const int  buttonPin = 2;

    unsigned long currentMillis = 0;
    unsigned long previousMillis = 0;
    unsigned long finalMillis = 0;

    int buttonPushCounter = 0;

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

       pinMode(buttonPin, INPUT);
       digitalWrite(buttonPin, HIGH);
    }

    void loop()
    {
      if (digitalRead(buttonPin) == LOW)
      {
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(buttonPushCounter);

        while(digitalRead(buttonPin) == LOW)
        {
          currentMillis = millis();
        }

        finalMillis = currentMillis - previousMillis;
        Serial.println(finalMillis);

        previousMillis = finalMillis;
        //finalMillis = 0;
      }
    }

Here, it is my serial monitor output.

    on
    number of button pushes:  1
    0
    on
    number of button pushes:  2
    775
    on
    number of button pushes:  3
    873
    on
    number of button pushes:  4
    1425
    on
    number of button pushes:  5
    1496
    on
    number of button pushes:  6
    2073
    on
    number of button pushes:  7
    2010
    on
    number of button pushes:  8
    2643
    on
    number of button pushes:  9
    3052
    on
    number of button pushes:  10
    3195
    on
    number of button pushes:  11
    3396
    on
    number of button pushes:  12
    3575
    on
    number of button pushes:  13
    3737

body:
You wrote

    previousMillis = finalMillis;

This means that you store the duration of the pulse, not the last time it was pressed.

Change it with

    previousMillis = currentMillis;

and you will be able to detect the high + low time.

By the way, constantly reading the millis function is useless. You can change your code to

    while(digitalRead(buttonPin) == LOW);
    currentMillis = millis();

which reads only once.


body:
First of all, frarugi87 is right.
Second, why not use this:

    finalMillis = millis() - previousMillis;
    previousMillis = millis();

Instead of what you wrote.

    if (digitalRead(buttonPin) == LOW) {
        buttonPushCounter++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(buttonPushCounter);
        finalMillis = millis() - previousMillis;
        previousMillis = millis();
        Serial.println(finalMillis);
        while(digitalRead(buttonPin) == LOW){}
      }

It works great.

Hope it helps.

Yoav


body:
While the previously given answers should work for you, they share a
couple of problems with your original code:

* they do not debounce the button
* they block while waiting for the button to be released

Blocking the program is not a big deal if you do not have to do anything
else. However, chances are you are showing us only a fraction of what
will ultimately be a larger program. In this case, doing a busy wait
(like `while (digitalRead(buttonPin) == LOW) ;`) will block the _whole
program_, not only this particular feature. Then, I suggest you get
immediately in the habit of writing non blocking code:

* when the button is pressed, record that fact and the current time
* when the button is released, report to the user

The important notion is that you never _wait_ for anything. Instead, you
check whether something has to be done _right now_ and, if so, you do
it.

Here is a non-blocking version of your program, with some debounce
added:

    const uint8_t button_pin = 2;

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

    void loop()
    {
        static int last_button_state = HIGH;
        static unsigned int push_count;
        static unsigned long last_press_time;
        int button_state = digitalRead(button_pin);
        unsigned long now = millis();

        // Record when the button is pressed.
        if (last_button_state == HIGH && button_state == LOW) {
            push_count++;
            last_press_time = now;
        }

        // Report when the button is released.
        if (last_button_state == LOW && button_state == HIGH) {
            unsigned long push_duration = now - last_press_time;
            if (push_duration < 10) {  // discard bounce
                push_count--;
            }
            else {
                Serial.print(F("pushes: "));
                Serial.print(push_count);
                Serial.print(F(", duration: "));
                Serial.print(push_duration);
                Serial.println(F(" ms"));
            }
        }

        last_button_state = button_state;
    }


message:
Is the A6 module broken?

Hi recently I've could send some messages with the [A6 GSM module][1], which uses **AT commands**. To switch on the board, you need to press the power button about 4 seconds or connecting the VCC pin to the PWR pin to avoid manual switching on. In this [Andreas Spiess' video][2] (minute 2:21), he recommends reset the device to give to the board a defined state. I had not done this until the device didn't work properly with some scripts. To reset it, he advises to reset the modoule. Its RST pin needs 0.70 mA and works at low level. In addition, the Arduino can not provide that current with a single pin so he uses a N-channel MOSFET (3055) to reset the board.

In my case I used a transistor (I don't know if it's NPN or PNP) and I connected the circuit like in his video. It worked! But it given **strange results** to the serial monitor  (yes, I set the baud rate correctly). After reset the board it switched on automatically because it was connected the PWR pin and VCC pin. The mistery occured when I unplugged the board (even its current) and then I reconnected it again. Since that moment it doesn't work, it doesn't switch on its LED to show you that the board is working. So, can anyone explain me **why** the 3055 it's neccesary to reset the board? Can it be done using **Ohm's Law**, a digital pin and a big resistance to give to the board the 70 mA?

Thanks!

  [1]: http://www.electrodragon.com/w/GSM_GPRS_A6_Module#A6_Pin_Definitions
  [2]: https://youtu.be/qtzrVj66IOA?t=2m21s

body:
I come across this problem too..based on what you said, i think it works like this:

The parameter you are looking for is power rating.. Arduino digital pin can only tolerate some amount of current, and im guessing it is less than 70mA..if you still do that, it is possible to damage that pin..since you want a LOW level for trigger, you can connect that RST manually to GND.. GND is also 0V just like the DIGITAL LOW, but it has no internal circuitry as of digital pin - meaning that you can sink a lot more current to GND..
If you want to be on the safe side, connect a limiting resistor(use ohm law for value), and also take note on the resistor power rating..


message:
MPU6050 safe to use with glue?

My current project involves embedding an MPU6050 accelerometer into straps, one of which goes below the knee, the other above the knee.

I need to fit the sensor into the strap and currently i have 6-core multi-threaded wire soldered directly into the board. This doesn't facilitate the greatest of long term stability, as too much strain and the wires will just pull out and break.

What I am wondering is if it is OK to:

 1. cover the wire side of the board in glue from a hot glue gun?
                     Would this have any possible conductivity issues or risk damaging the wires or board itself?
 2. If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance. This would leave me with a really solid sensor for embedding if so!

Any answers to the above questions would be greatly appreciated and I would be extremely grateful for any alternative options as well. I would like to keep the wires soldered into the board as it is extremely tidy and makes for easier embedding than if I were to use another connector.

body:
> Would this have any possible conductivity issues

Nope.

> or risk damaging the wires or board itself?

Nope.

> If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance.

Sure.

This is known as "potting". You can get special potting compounds, but hot glue is just as good.


body:
1) I do not see any problem here - I myself used hot glue to fix and isolate power source of robot from the copper side. It does not leak any (measurable by my tools) current, does not show any sign of detorations and works well both electrical and mechanical way. I used it only on copper side, where was risk of shortcuts and where were no heat dissipators (as it isolate also heat). But I think, that the MPU does not generate so much heat, to be worry about - body proximity and weather on summer would affect it more.

2) Hot glue is not as hot as soldering lead/tin so short contact with the MCU should not harm it. (You can shortly touch hot glue to manipulate it and not get burned, so it is not so hot). Anyway I would apply it as fast as possible and would leave it cool down before swithing it on (the working and the storing temperatures are different case). Be carefull with the wires, as the isolator can be melted, if heated by hot glue and moved at the same time. Also take in mind, that the hot glue should be little around the whole, to isolate from humidity. And that it would be complicated to solder anything after the glue is applied - so have all contacts (you may possibly need access) somehow lead out of the glue. And try the construction before applying the glue, to be extra sure, that nothing is missing and everything works.

I personally would place the MCU on some kind of PCB and solder the wires to the PCB organized the way the wires would continue to form "cable" and to have extra sure there is no force on the connection of MCU pins. Also I would fixed the whole cable to the PCB with something, so the solder itself is not under any force, as it is the most probabely place to broke there. An I would ensure, that the cable goes smoothly away from the PBC, as it would be bad, if it would be bent ower sharp edge at the place where it leave its glue support.


message:
Mapping PPM Signals to Servo Values

This question is an extension of this question.

https://arduino.stackexchange.com/questions/33088/accessing-values-from-array-within-a-library

The answer provided by Mark showed me how to read and print a single value from a particular array by using the index number to print to the serial console.

The second part of this question is how to get these values from the array to map to 0-180 for values that are useful to the servo.

The below code is my attempt that is not working. I used the servo sweep example from the Arduino examples which worked fine with a potentiometer but not with the ppm input. What am I doing wrong here? This won't compile. (I am using TinyServo.h library since this is for an attiny85. Works with with the pot mapping just fine.)

 #include <TinyServo.h>
 #include <TinyPinChange.h>
 #include <TinyPpmReader.h>
 #include <Rcul.h>

 int PPM_INPUT_PIN = TinyPpmReader.width_us(3); //<------- Doesn't work

 //int potpin0 = 3;    <---------          // This worked
 int val0;                     // integer to store value

 const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
 const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
             // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

 #define PANSERVO 0
 #define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

 void setup()
 {
   setupServos();
 }

 void loop()
 {
   val0 = analogRead(PPM_INPUT_PIN);  <---------          //Doesnt work// reads the value of the       potentiometer (value between 0 and 1023)            // reads the value of the 2nd potentiometer (value between 0 and 1023)
   val0= map(val0, 1000, 2000, 0, 180);
  // scale it to use it with the servo (value between 0 and 180)
     // scale it to use it with the servo (value between 0 and 180)

 moveServo(PANSERVO, val0);

   delay(5);                           // waits for the servo to get there
 }

For some background, the ppm library outputs like this to the serial monitor:

Ch4=**1560** us

These values move from ~1000 - 2000 depending on the ppm signal input. (The input is from a RC remote control receiver)

This example below prints only channel 4 (Ch4=1560 us)from  a total of 8 channels. Now, I want to map this to the values of 0-180:

 #include <TinyPinChange.h>
 #include <TinyPpmReader.h>
 #include <Rcul.h>

 #define PPM_INPUT_PIN  2

 void setup()
 {
   Serial.begin(38400);//attiny tx - rx uno does not work at 9600 baud. Set to 38400 @ attiny 1mhz and uno serial console to 38400 baud
   TinyPpmReader.attach(PPM_INPUT_PIN); /* Attach TinyPpmReader to PPM_INPUT_PIN pin */
 }

 void loop()
 {

 Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us"));

  display results */
   delay(500);
 }

What am I doing wrong?

body:
    int PPM_INPUT_PIN = TinyPpmReader.width_us(3);
will save the result into variable `PPM_INPUT_PIN`, while

    val0 = analogRead(PPM_INPUT_PIN);
will save an analog reading results from `PPM_INPUT_PIN` channel into variable `val0`. This is (one of) your problem.
To map the PPM value, you can do:

    #include <TinyServo.h>
    #include <TinyPinChange.h>
    #include <TinyPpmReader.h>
    #include <Rcul.h>

    int val0,                     // integer to store value
     mappedval0;      // integer to store mapped value;

    const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
    const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                           // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

    #define PANSERVO 0
    #define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

    const int PPM_max_value = xxxxx; //put the max value of PPM reading result
    const int PPM_min_value = yyyyy; //put the min value of PPM reading result

    void setup()
    {
      setupServos();
    }

    void loop()
    {
      val0 = TinyPpmReader.width_us(4);   //get PPM reading result from index 4
      mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
        // scale it to use it with the servo (value between 0 and 180)

      moveServo(PANSERVO, mappedval0);
      delay(5);                           // waits for the servo to get there
    }


message:
Accelerometer readings on a moving object

I hope this stack is the right place for this question.
I have an accelerometer mounted securely on a swaying object -lets say a stick or pole-
this object is swinging back and forth in small angles (+- 20) with a frequency of about 2-3 times a second.
Im using the accelerometer output to calculate the tilt of the object, however since the frequency of the swings is relatively high the accelerometer readings are very high as well, and not reliable for calculating the tilt.

from my research i have seen that accelerometers work best in a stable environment.
Is there any way to improve the reliability of my accelerometer output in this setup?

body:
A few things to consider.

First. An accelerometer isn't that great here. Low output frequency is one issue. Noise is another. A pot or an optical encoder would be better.

Secondly. Even if output frequency isn't an issue. You will need some sophisticated math to reconstruct the instantaneous tilt, as the measurements are essentially a sine function, but with an acceleration away from the center of the rotation.  Getting to the max tilt is easier mathematically.

Just for starters.


message:
Arduino Problem with using SoftwareSerial and SPI

I am using an external ADC (via SPI) and also a GPS receiver (Software Serial). I tried each one of them and it's working fine. Now, when I try to integrate both of them in one sketch, I can only make the ADC work, the GPS is not receiving something.

    void setup()
    {
      pinMode(ADS1220_CS_PIN, OUTPUT);
      pinMode(ADS1220_DRDY_PIN, INPUT);

      Serial.begin(115200);
      ss.begin(9600);

      //while(!Serial);
      //SPI.begin();                           // wake up the SPI bus.
      //SPI.setBitOrder(MSBFIRST);
      //SPI.setDataMode(SPI_MODE1);

      //ADS1220.begin();
      Wire.begin();
      delay(1000);  // Give things time to "warm-up"

      delay(1000);
      pre_time = millis(); //store current time to be used as "previous" time
    }
I found out that in the setup(), when I comment out all those SPI functions, the GPS returns something. What seems to be wrong with this? thank you so much for any help

body:
SoftwareSerial is **very** inefficient.  AltSoftSerial is best.  See [this answer](https://arduino.stackexchange.com/questions/26240#26277) for a complete list of alternatives.

You may want to look at my [NeoGPS library.](https://github.com/SlashDevin/NeoGPS)  It is smaller, faster and more accurate than all other libraries.  The examples are structured better.  You don't show your whole sketch -_-, but the loop structure could be your real problem.  Be sure to read the Troubleshooting page for more suggestions.


body: I managed to solve this just by changing the Rx pin to digital pin 4 from digital pin 10, I don't know what causes the problem but it did the job for me


message:
Reading updated serial data from ESP8266

I have connected my ESP8266 to my Arduino Uno on pin 2 & pin 3 as RX & TX. I adjusted the baud rates and I have no issue receiving the data from the ESP8266.

The ESP8266 gets connected as a client to a server and grabs the likes count of a Facebook page. The data on the ESP8266 serial port is updated correctly every time the ESP sends a get request to the server to get the updated likes count of a particular Facebook page.

Unfortunately I'm not receiving this updated likes count on my Arduino serial port. I'm always receiving the same likes count. I have to close the serial window and open it again to receive the new count. Or reset the Arduino itself to receive the new likes count.

So why isn't it posting the latest likes count sent from the ESP to the Arduino instantly without having to reset the Arduino? Maybe I have an issue in the `void loop()`.

Because I display this data on an external display and I need it to be updated without me needing to reset the Arduino every time to receive the latest count.

    void loop() {
      char c;
      while (esp8266.available() && c != '\n') {
        c = esp8266.read();
        response += c;
      }
      //If end of line
      if (c == '\n') {
        //Getting the likes string only
        if(likes = response.substring(response.indexOf("Likes:")+6, response.indexOf("::"))) {
          //Filtering some unneeded strings
          if((strstr(likes.c_str(), "URL")) == NULL) {
            currentLikes = atol(likes.c_str());
            Serial.print(currentLikes);
            //Printing likes count on serial port
          }
          Serial.println();
        }
      }
    }

body:
Thank you everyone I had to just clear the response string every time.

I have just added `response = "";` after the `Serial.print(currentLikes);`


message:
Arduino Leonardo clone voltage question

I'm planning my first Arduino project which involves a MPU-6050 accelerometer(3.3V) and a RGB led(5V). I've found this [Arduino Clone][1] but i'm not sure if it has 3.3V and 5V outputs that I can use. The pins do exist on the original Leonardo board but i'm not sure if the clone contains them as well.

  [1]: https://www.amazon.de/gp/product/B01HAZ2M8A/

body:
That has a 5V pin (Vcc) but no 3.3V. Also the 5V pin can't provide more than a few hundred mA.

Better specifications are here: https://www.sparkfun.com/products/12640


message:
Wearable GPS Antenna

I am using the Adafruit Fona 808 to make a wearable device. One of the main features is GPS but I cannot seem to find a suitable antenna for wearables. My question is: What is a good GPS antenna for a wearable project and should it be active or passive?
Thanks

body:
I too thought whats wrong with a normal Antenna, but the answer is the problem is the human body.

There are manufacturers that make "fabric" antennas, but these tend to be Mil-Spec so are going to cost a fortune.  (http://www.pharad.com/gps-wearable-antenna.html)

I found this site that explains what the effect of the body is, and seems to make their own antenna.  http://www.pharad.com/gps-wearable-antenna.html

I think you might be better off looking for a high gain antenna and the choice of active or passive will probably be based on the interference you get from the body.


message:
Digital Band pass filter on Arduino

I am working with sensors on Arduino and would like to filter the sensor's output to a certain band of frequencies.

I found many examples online on how to implement simple digital low-pass filters in Arduino code, but not for band pass filters.

Is it even possible to achieve this in the scope of an Arduino program?
If anyone can share some tutorial for this, that would be much appreciated.

body:
A band pass filter simply means that it a filter between a certain interval of frequencies thus it can be made from a high pass filter and a low pass filter

e.g. this fact is mentioned here http://www.electronics-tutorials.ws/filter/filter_4.html

as well as lots of other web pages which a search by you can find.
So yes a band pass filter can be implemented on arduino if you can implement the corresponding high pass and low pass filter too.