body:
Hello Arduino comunity!

I am working on a circuit that uses an Arduino Mini to read values from certain points of a boost/buck converter circuit to determine things like input state, output state, overheat and so on. The circuit is working all right, and the only part left to do is to connect the digital pins of the Arduino to the different points in the boost/buck regulator.

The problem is however that I need to read from a range of voltages between 1 and 31 volts with the Arduino, which isn't possible, because not only will it damage the controller if the voltage exceeds 5V, but values below 3V will be regarded as false.

I thought of putting some potential dividers, which would obviously not do the trick, and I also thought of using a WS78L05 voltage regulator per input pin (because each pin might have a different voltage from the rest) but that isn't dealing with voltages <=5V and 31V exceeds its rating as well.

Lastly I thought of using transistors, which seemed like a good idea, but I would require 2 transistors per input wired as follows:

<!-- 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/rGhw8.png)

<!-- End schematic -->

But it is impractical to do for 4 inputs and there is limited space available on the PCB too :(

Is there any IC that encapsulates the circuit above, or is there any other way to achieve what I want to do?

Thanks very much :)

title: Digital read on voltages between 1 and 31 volts?

Answers: 3

body:
Using a simple voltage divider (51K / 10K as you have worked out already) fed directly into an ADC input will give you a reading of 32 on the ADC at 1V input. That should be enough to give a reliable threshold detection.

If you want to have higher sensitivity at lower voltages you can increase the output of your voltage divider to more than 5V and then clip it with a zenner diode. For instance if you reduce the 51K to 33K you get 7.2V out of the voltage divider. A 5V zenner diode can then clip it to 5V. Your 1V input (which would be 0.233V on the output of the divider) would now read 47 on the ADC. Anything over 21V would then read 1023.

<!-- 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/UepZW.png)
<!-- End schematic -->

Theoretically you could get away with not having the voltage divider at all and just using the zenner and one resistor to clip the incoming voltage to 5.1V. That would give you the greatest sensitivity, but also the greatest current flow through the zenner.

<!-- 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/Ff2TO.png)

<!-- End schematic -->

Size R1 to limit the current at your maximum voltage to within the rating of the zenner.

body: Use two quad lm339 voltage comparator chips to make an analog to digital convertor-you will need 2 to read 31 volts accurately. Its a standard ADC circuit, with this common lm339 is,  so a search will find circuit-it may need a simple modification to combine the two circuit.

body:
The junction of a 51KΩ, 10KΩ voltage divider will feed an Arduino ADC input 5.08 V at 31 V input, and 0.16 V at 1 V input.  With a 5 V reference, I think the first of those will give 1023 counts, and the latter, 33 counts.  This is from 1023*(1/5)*10/(10+51) ≃ 33.54.  That may be enough counts for reliable detection, depending on how noisy the environment is.

For more sensitivity at lower voltages, if the first reading is less than 225 counts, one can switch to the 1.1 V internal ADC reference and take another reading.  (1023*1.1/5 ≃ 225.06.)  With a 1.1 V reference, a 1 V input to the divider produces 152 counts, and a 6.7 V input produces about 1023 counts.  (1023*(1/1.1)*10/(10+51) ≃ 152.46 and 1.1/(10/61) ≃ 6.7.)

To change the ADC  reference voltage, say `analogReference(DEFAULT)` for Vcc reference, or `analogReference(INTERNAL)` for 1.1 V reference.


body:
I am using a BLE device (https://www.adafruit.com/product/1697) that I use to print data to an app. I can successfully connect the BLE to the app and receive the data but the result however gets chopped up.

What I am sending is a lat, lng value (that I gather with a library called TinyGPS++ http://arduiniana.org/libraries/tinygpsplus/) and the code looks like this:

    BTLEserial.Print::print(gps.location.lat(), 8);
    BTLEserial.print (", ");
    BTLEserial.Print::print(gps.location.lng(), 8);

So for example if the latitude is: `32.12345678`, it comes like this to the app: `3`, new row, `2`, new row etc.

So my question is, how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

title: How can I adjust my code so that the value that I print with my BLE device does not get chopped up when I receive it on an app?

Answers: 1

body:
> how can I adjust my code to make sure it does not send the result chopped up but instead sends it's complete value?

The BLE device uses a package approach and the print member functions only support strings (char vectors and Arduino String). Construct the message as a String:

    double lat = gps.location.lat();
    double lng = gps.location.lng();
    String msg = String(lat, 8) + String(", ") + String(lng, 8);
    BTLEserial.print(msg);

Cheers!


body:
I got problems with the code and I have used most of today, trying to find a solution and it's starting to drive my crazy. I hope one of you guys will be able to help me out.

I need the code to check a specific page every 10 seconds, single character.

This is what I have now, working code:
Where should I start?

    #include <Ethernet.h>
    #include <SPI.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = { 192, 168, 1, 104 };
    char server[] = "billigefittings.dk";

    EthernetClient client;

    void setup()
    {
      Ethernet.begin(mac, ip);
      Serial.begin(9600);

      delay(1000);

      Serial.println(Ethernet.localIP());
      Serial.println();

      Serial.println("connecting ...");

      if (client.connect(server, 80)) {
        Serial.println("connected");
        client.println("GET /lan.php");
        client.println();
      } else {
        Serial.println("connection failed");
      }
    }

    void loop()
    {
      if(client.available() > 0) {

        char c = client.read();

        Serial.print("page value:");
        Serial.println(c);

        if(c == '1') {
            digitalWrite(8, HIGH);
            Serial.println("8 HIGH ...");
            delay(5000);
            digitalWrite(8, LOW);
            Serial.println("8 LOW ...");
        }else{
            Serial.println("page value does not match '1' !");
        }

        // The code above should run even 10 seconds

      }

      if(!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
        for(;;);
      }

    }

Update: Edit the loop like the example below does not work either, it stops after the first loop (8 LOW):

    void loop()
    {
      if(client.available() > 0) {

        char c = client.read();

        Serial.print("page value:");
        Serial.println(c);

        if(c == '1') {
            digitalWrite(8, HIGH);
            Serial.println("8 HIGH ...");
            delay(5000);
            digitalWrite(8, LOW);
            Serial.println("8 LOW ...");
        }else{
            Serial.println("page value does not match '1' !");
        }

        delay(5000);

        // The code above should run even 10 seconds

      }

    }

title: How can I make this code read a page every 10 seconds?

Answers: 1

body:
As discussed in the comments, you need to connect to the client *each time*, not just once.

Here's my modified version of your code, which I hope will work -- I'm not set up to test it.

    #include <Ethernet.h>
    #include <SPI.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = { 192, 168, 1, 104 };
    char server[] = "billigefittings.dk";

    void setup()
    {
      Ethernet.begin(mac, ip);
      Serial.begin(9600);

      delay(1000);

      Serial.println(Ethernet.localIP());
      Serial.println();
    }

    void loop()
    {
      // Connect to the server
      Serial.println("connecting ...");

      EthernetClient client;
      if (client.connect(server, 80)) {
        Serial.println("connected");
        client.println("GET /lan.php");
        client.println();
      } else {
        Serial.println("connection failed");
      }

      // Wait a moment for data to arrive
      // Note: This is NOT a reliable way of doing it!
      delay(1000);

      if(client.available() > 0) {
        char c = client.read();

        Serial.print("page value:");
        Serial.println(c);

        if(c == '1') {
            digitalWrite(8, HIGH);
            Serial.println("8 HIGH ...");
            delay(5000);
            digitalWrite(8, LOW);
            Serial.println("8 LOW ...");
        }else{
            Serial.println("page value does not match '1' !");
        }
      }

      // Disconnect the client
      if(client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
      }

      // Wait another 9s, which will give us a delay of roughly 10s
      delay(9000);
    }


body:
Sorry if this is too basic, but I am very new to arduino and electronics. I come from programming, I am trying to start a project where I can control an RGB led strip, I want to be able to control the light intensity and color of the light strip (something like [this][1]), using a microphone.

My goal is for frequency to control de color of the rgb light and the dB (Volume) to control the light intensity. I have found several microphones such as [this ones][2]. Can I get both frequency and dB input from this microphones?

Would I need some extra controllers for this project? Again I am very new with this, sorry by the basic questions.

  [1]: https://www.amazon.com/ALITOVE-Similar-Individually-Addressable-Flexible/dp/B01HXFKMV6/ref=sr_1_2?ie=UTF8&qid=1483806695&sr=8-2&keywords=rgb led strip arduino
  [2]: http://www.amazon.com/Detection-Intelligent-Compatible-Atomic-Market/dp/B00TM7R21W/ref=sr_1_7?ie=UTF8&qid=1483803448&sr=8-7&keywords=arduino microphone sensor

title: Control RGB led using microphones, getting the right components

Answers: 1

body:
It would be worth checking out the [ColorChord][1] project.  It runs on an ESP8266, not an Arduino, but it ought to get you going.

  [1]: https://github.com/cnlohr/colorchord


body:
I am isolating the ATMega328P from the Arduino Uno. I have used it for many other projects, so it does work as intended. Also, I have used my ESP8266-01 for other projects and works great (including serial communication).

I am trying to get the ESP8266-01 to make the ATMega328P pin 13 blink an LED. That is all.

When the ESP8266 is hooked to the TX/RX of the arduino board, the program works exactly as intended. I hook it up the exact same way to the ATMega328P and it doesn't work.

I am using baud rate of 9600 for the communication and using a 16MHz crystal for the ATMega328P.

<!-- 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/TWCDi.png)

<!-- End schematic -->

The controller is getting 3.3v from the supply as well. And pin 13 is supposed to turn on/off depending on the serial value. Below is the code for the ESP8266:

    #include <ESP8266WiFi.h>

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

    void loop() {
      delay(10000);
      Serial.write("LED ON");
      delay(10000);
      Serial.write("LED OFF");
    }

And below is the code for the ATMega328P:

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2,3);

    void setup()
    {
      Serial.begin(9600);
      esp8266.begin(9600);
      pinMode(13, OUTPUT);
    }

    void loop()
    {
      if(esp8266.available())
      {
        String command = "";
        while(esp8266.available())
        {
          command += (char)esp8266.read();
        }

        if(command == "LED ON") {
          digitalWrite(13, HIGH);
        }

        if(command == "LED OFF") {
          digitalWrite(13, LOW);
        }
      }

      delay(500);
    }

As stated, they work great separately, but when I try serial communication with them together, it doesn't work.

P.S. I usually set my ESP8266 baud rate to 115200, but the ATMega328P, I believe, needs to run at 9600 because of the 16MHz clock frequency. Not sure about this part, though.

EDIT:

<!-- 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/NWGap.png)

<!-- End schematic -->

title: ESP8266 Serial Communication with ATMega328P

Answers: 1

body:
Generally, try to debug the problem.  Evidently either you're not getting data from your `esp8266.available()` and/or `esp8266.read()`, or it's not the right data.  Put traces (`Serial.println(...)`) in, print things out, and find out what's going wrong.

---

Specifically, I suspect the issue here is that you are relying on all the data being available *immediately*: you check `esp8266.available()` which will tell you whether one or more bytes is available.  Then you `esp8266.read()` until there are no more bytes available.  What if there's a 1ms delay between bytes arriving?  You'll get,perhaps `LED O`, `esp8266.available()` will tell you there's no more data (there's not, *yet*!) and you stop reading.

You could probably get it working by putting a small `delay()` in:

    while(esp8266.available())
    {
      command += (char)esp8266.read();
      delay(100);
    }

That's a solution (probably) but not a *good* one.  A better solution would be to make your commands `LED_ON\n` and `LED_OFF\n` - and read until you get a `\n`.


body:
I am experimenting with an ATmega328P bootloader, and I created an Intel HEX (.hex) file with a program with an infinite loop in the beginning and with Optiboot code at the end of the hex file. (Code loaded into the chip is here: http://relliks.php5.cz/stackexchange/DUMP.bin.)

Then I disabled the `BOOTRST` fuse and pressed the restart button on Arduino Uno R3, but the bootloader still blinks with the LED on digital port 13.

How is it possible, that the bootloader is executed after chip restart and `BOOTRST` is disabled? My fuse settings are: Only `SPIEN` and `BODLEVEL0` are set.

I found that when I disable the `BODLEVEL0` fuse, the bootloader turns off.
`BODLEVEL0` is used to set the brown-out voltage and shouldn't affect bootloader start. Where is the issue?

title: The BOOTRST fuse was disabled, but bootloader code is still running after chip reset

Answers: 2

body:
You don't seem to have filled in all the interrupt vectors. I get this from your .bin file:

    00000000 <.sec1>:
           0:       00 c0           rjmp    .+0             ;  0x2
           2:       00 00           nop
           4:       00 00           nop
           6:       00 00           nop
           8:       fc cf           rjmp    .-8             ;  0x2
           a:       fb cf           rjmp    .-10            ;  0x2
           c:       fa cf           rjmp    .-12            ;  0x2
           e:       f9 cf           rjmp    .-14            ;  0x2
          10:       f8 cf           rjmp    .-16            ;  0x2
          12:       f7 cf           rjmp    .-18            ;  0x2
          14:       f6 cf           rjmp    .-20            ;  0x2
          16:       f5 cf           rjmp    .-22            ;  0x2
          18:       ff ff           .word   0xffff  ; ????
          1a:       ff ff           .word   0xffff  ; ????
          1c:       ff ff           .word   0xffff  ; ????
          1e:       ff ff           .word   0xffff  ; ????
          20:       ff ff           .word   0xffff  ; ????
          22:       ff ff           .word   0xffff  ; ????
          24:       ff ff           .word   0xffff  ; ????
    ...
        7dfc:       ff ff           .word   0xffff  ; ????
        7dfe:       ff ff           .word   0xffff  ; ????
        7e00:       11 24           eor     r1, r1           <--- bootloader
        7e02:       94 b7           in      r25, 0x34       ; 52
        7e04:       14 be           out     0x34, r1        ; 52
        7e06:       89 2f           mov     r24, r25
        7e08:       8d 70           andi    r24, 0x0D       ; 13
        7e0a:       11 f0           breq    .+4             ;  0x7e10
        7e0c:       89 2f           mov     r24, r25
        7e0e:       de d0           rcall   .+444           ;  0x7fcc
        7e10:       85 e0           ldi     r24, 0x05       ; 5

Now I can't quite see the relationship between the brown-out and those higher interrupts, but if one of them happened to fire I think it would waddle its way past all those 0xFF instructions and hit the bootloader.

The Atmega328P has 26 interrupt vectors (including Reset).

body:
Thank you very much!

I found that when I set fuses using program PONYPROG2000 and native RS232 programmer (http://3.bp.blogspot.com/-2D_0B7...) then I read fuses again using another program (eXtreme Burner) and another programmer(USBASP 2.0), there was difference. **The PONYPROG2000 probably sets the fuses incorrectly**.
Now the Atmega328P works correctly yet.


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

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

Answers: 3

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!

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

body:
Just incase anyone else has the problem,

You need to connect the strip as a ring by returning the tail end to the psu,

Electricity basics !!!!


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

title: How to measure ultrasonic sensor without pulsein method?

Answers: 2

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


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

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

Answers: 1

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.


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

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

Answers: 1

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.


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

title: Volatile variable not updating from timer ISR

Answers: 1

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.


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

title: Reading Infrared raw data

Answers: 1

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)


body:
EDIT: Changed the title to better express what I'm after.

I've been dabbling in connecting two Arduino Nano 3's with the RFM69HCW breakout for the past 5 days.. but got nowhere.

I've followed the official [hookup guide][1] at first, after that didn't work, I've tried the code samples from a Adafruit post, and still nothing.

By 'nothing', I mean that I compiled and uploaded the code to two separate Arduinos that are literally 5cm apart, tried sending messages, broadcasting messages.. etc. but without any success.

Here they are - on two breadboards, but the layout and connections are symmetrical:

[![Layout picture][3]][3]
Yeah, the bottom one is quite confusing to look at because of the wires, but I lent most of them to friends - so I had to improvise.

To clarify the picture, I connected the Arduino as follows:

 - D2 -> INT(Interrupt)
 - D10 -> SS
 - D11 -> MISO
 - D12 -> MOSI
 - D13 -> C(Clock)

One of the codes that I tried: (This is from the official guide, but modified slightly)
<!-- language-all: lang-cpp -->

    #include <RFM69.h>
    #include <SPI.h>

    #define NETWORKID     0
    #define MYNODEID      1 //2 For the other Arduino
    #define TONODEID      255

    #define FREQUENCY     RF69_915MHZ

    #define ENCRYPT       false // Set to "true" to use encryption
    #define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes

    #define USEACK        true // Request ACKs or not

    RFM69 radio;

    void setup()
    {
      Serial.begin(9600);
      Serial.print("Node ");
      Serial.print(MYNODEID,DEC);
      Serial.println(" ready");

      radio.initialize(FREQUENCY, MYNODEID, NETWORKID);
      radio.setHighPower();
    }

    void loop()
    {
      static char sendbuffer[62];
      static int sendlength = 0;

      if (Serial.available() > 0)
      {
        char input = Serial.read();

        if (input != '\r')
        {
          sendbuffer[sendlength] = input;
          sendlength++;
        }

        if ((input == '\r') || (sendlength == 61))
        {
          Serial.print("sending to node ");
          Serial.print(TONODEID, DEC);
          Serial.print(", message [");
          for (byte i = 0; i < sendlength; i++)
            Serial.print(sendbuffer[i]);
          Serial.println("]");

          if (radio.sendWithRetry(TONODEID, sendbuffer, sendlength))
            Serial.println("ACK received!");
          else
            Serial.println("no ACK received");

          sendlength = 0;
        }
      }

      if (radio.receiveDone())
      {
        Serial.print("received from node ");
        Serial.print(radio.SENDERID, DEC);
        Serial.print(", message [");

        for (byte i = 0; i < radio.DATALEN; i++)
          Serial.print((char)radio.DATA[i]);

        Serial.print("], RSSI ");
        Serial.println(radio.RSSI);

        if (radio.ACKRequested())
        {
          radio.sendACK();
          Serial.println("ACK sent");
        }
      }
    }

Notes:
Everything is powered by a 5V 2A brick - the RFM69 modules are receiving a stepped down 3.3V from those small thingies connecting two separate breadboard power rails.

Also... I don't have any 915MHz antennas, so I used some 433MHz ones that I had laying around - I'm going to get correct ones later, but right now, for testing them 5cm apart it should be good enough..?

P.S.: I HATE when stuff doesn't have status LEDs, I could really use some on the radio modules.

  [1]: https://learn.sparkfun.com/tutorials/rfm69hcw-hookup-guide
  [3]: https://i.stack.imgur.com/XQsCa.jpg

title: How do you debug SPI connected devices?

Answers: 0


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

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

Answers: 1

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


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

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

Answers: 2

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


body:
I am using the Accelstepper library to control a stepper motor, according to commands input via Serial.
It works as expected for the first time when I start Serial Monitor and send command.

When left idle for some seconds (> 10 seconds), the motor makes clicking sounds for the first few commands(without moving) and then it starts working again as expected. The longer I leave it, the more commands it misses.

It gets resolved if I restart Serial Monitor on UNO.

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

    #include <Arduino.h>
    #include "AccelStepper.h"

    #define STEPPER_X_STEP_PIN 2
    #define STEPPER_X_DIR_PIN 3

    enum Direction { FORWARD, BACKWORD } direction;

    String inputString = "";         // a string to hold incoming data
    boolean stringComplete = false;  // whether the string is complete

    void blockingRunSpeedToPosition();

    AccelStepper stepper(AccelStepper::DRIVER, STEPPER_X_STEP_PIN, STEPPER_X_DIR_PIN);

    void setup()
    {
      Serial.begin(9600);
      stepper.setMaxSpeed(200.0);
      stepper.setAcceleration(50);
    }

    void loop()
    {
      // print the string when a newline arrives:
      if (stringComplete) {
          // clear the string:
          inputString.trim();
          if(inputString == "x") {
              direction = FORWARD;
              blockingRunSpeedToPosition();
          }
          inputString = "";
          stringComplete = false;
        }
    }

    void serialEvent() {
        while (Serial.available()) {
            char inChar = (char)Serial.read();
            inputString += inChar;
            if (inChar == '\n') {
              stringComplete = true;
            }
        }
    }

    void blockingRunSpeedToPosition()
    {
        int steps = 400;
        stepper.setCurrentPosition(0);
        stepper.move(steps);
        while (stepper.distanceToGo() != 0) {
               stepper.run();
        }
    }

I think there is no issue with the code or my Arduino connection since the motor runs fine in the beginning.

I tried the above code on Arduino MEGA, UNO, different motors with different drivers. The problem persists.

I think it is something to do with motor excitation (energized coils).
Please give me some hints and pointer to debug the issue, since I don't know where to look. I am an intermediate programmer and robotics hobbyist.

Here is the [video demo of the issue](https://youtu.be/tjey4Y7v_P4).

I am using:

- Arduino MEGA - ATmega2560
- NEMA 23.
- Rino stepper motor.
- Arduino Pin 2 is Step and 3 is Direction.
- Driver Vcc is connected to 5V pin.
- 48 volt, 5 Amps SMPS.
- Ubuntu 16.
- [Accelstepper library](http://www.airspayce.com/mikem/arduino/AccelStepper/)

title: Stepper motor moves initially but after idle time, clicks and doesn't move for a while

Answers: 0


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

title: How to delete first voltage reading?

Answers: 2

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.


body: Recently I stumbled myself on a fairly old blood sugar test strips canisters. Inside them, I found this what they called "Code Card" which inside, an EEPROM `Microchip 93LC46B` a `1K Microwire compatible serial EEPROM`. I want to salvage them for my Arduino project. Is possible to read/write data to them? and how to determine the capacity? I only see `16 bit word size` on the datasheet and `1K` on the title.

title: Reading/Writing salvaged EEPROM

Answers: 0


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

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

Answers: 1

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.


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

title: NodeMCU sensor values to web page

Answers: 1

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


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

title: Creating linear motion using motor

Answers: 1

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.


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

title: Vary the length of square waveform

Answers: 1

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.


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

title: Regarding PGA bypass in ADS1262

Answers: 2

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.


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

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

Answers: 1

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.


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

title: Detecting I2C transfer with LED

Answers: 1

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).


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

title: Arduino Nano 3.0 dimensions without the pins

Answers: 2

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!


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

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

Answers: 1

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.


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

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

Answers: 1

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.


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

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

Answers: 1

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.


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

title: Arduino Uno as keyboard

Answers: 1

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();
            }
        }

    }


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

title: Arduino Starter Kit - firmly wiring longer parts

Answers: 1

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.


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

title: DHT sensors with RGB LED

Answers: 2

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


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

title: Timer3 Arduino maximum period

Answers: 3

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.


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

title: Understanding SevSeg

Answers: 1

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.


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

title: Can't power mg2639 cellular shield with battery

Answers: 1

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