message:
Generate 2 PWM signals Vc and Vh from Arduino Uno

I want to generate two PWM signals VC and VH to give input to the gas sensor  with the duty cycle mentioned below. I also want to take the reading from the same sensor at the same time using Arduino Uno.

[![Waveform1]][1][![Circuit][2]][2]

I am confused how to proceed with the code in Arduino Uno.

  [1]: https://i.stack.imgur.com/bY2dK.png
  [2]: https://i.stack.imgur.com/8UGU5.png

body:
You can use the `millis()` function to see how much time has passed and use this to create your waveform while still being able to perform other tasks. You will check in which part of the wave you are in each iteration of `loop()` and adjust your outputs accordingly.

E.g:

    long vhtime;
    uint8_t vhpin = 9;   // the VH output pin
    uint8_t vcpin = 10;  // the VC output pin

    long period = 250;   // the period of your pwm signal in ms
    long vhduty = 14;    // amount of ms vh should be high
    long vcdelay = 2;    // amount of ms we wait for vc to go high after vh has gone high
    long vcduty = 5;     // amount of ms vc should be high

    long curtime;        // this will hold our current position in one period of the waveform

    void setup() {
      pinMode(vhpin, OUT);
      pinMode(vcpin, OUT);
      digitalWrite(vcpin, LOW);
      digitalWrite(vhpin, HIGH);
      vhtime = millis();
    }

    void loop() {
      curtime = millis() - vhtime;
      if (curtime > vhduty)        // we are in the last 236ms of the wave, vh should be low
        digitalWrite(vhpin, LOW);
      else                         // we are in the first 14ms of the wave, vh should be high
        digitalWrite(vhpin, HIGH);
      if (curtime > vcdelay && curtime < vcduty + vcdelay) // vc should be high during this time
        digitalWrite(vcpin, HIGH);
      else
        digitalWrite(vcpin, LOW);
      if (curtime > period) {
        // we should start a new period
        digitalWrite(vhpin, HIGH);
        vhtime = millis();
      }
      // do your other calculations here
    }


sender: user

message:
Suggestions for a program for drawing simple schematics

I'm wondering if there are free programs or web sites that let you draw simple schematics similar to this example:

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

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

sender: assistant

body:
A compilation of possibilities mentioned the comments. I'll add to this as I try out the suggestions.

From @Gerben, "kind of in order of complexity":

* [circuitlab.com](https://www.circuitlab.com) - online schematic capture and simulator (analog, digital, and mixed signal). Licensed for professional, student/educator, and hobbyist (free) usage. Officially runs in Chrome and Firefox, and they report users having success with Safari and Opera which are not officially supported.

* [Fritzing](http://fritzing.org/home) - cross-platform (Mac, Windows, Linux). Has Breadboard View mode with built in Arduino support that allows you to create diagrams like this one:

 [![LCD Rise and Shine Clock from http://barkengmad.com/2013/10/led-clock-circuit-design-on-fritzing/][1]][1]

 From there you can click on the Schematic view to route wires and convert the breadboard into a traditional schematic.

* [CircuitMaker](http://www.circuitmaker.com) - Windows only, requires creating an account.

* [Eagle](http://www.cadsoftusa.com) - cross-platform (Mac, Windows, Linux), paid and free versions.

 Component library collections (thanks to Marko Mackic for the idea):

 - [Adafruit](https://github.com/adafruit/Adafruit-Eagle-Library)
 - [Element14 Arduino library](http://www.element14.com/community/docs/DOC-64069/l/the-element14-arduino-cadsoft-library) - requires registration, lots of other libraries as well
 - [Sparkfun](https://github.com/sparkfun/SparkFun-Eagle-Libraries)

* [KiCad](http://kicad-pcb.org) - cross-platform (Mac, Linux (with packages for several distributions), Windows, and source code), [open source][2] and also on [GitHub][3].

Found [Autodesk's 123D Circuits](https://123d.circuits.io) in a question on [Arduino Simulators (and emulators)][4].

  [1]: https://i.stack.imgur.com/UvWA9.jpg
  [2]: http://kicad-pcb.org/download/source
  [3]: https://github.com/KiCad/kicad-source-mirror
  [4]: https://arduino.stackexchange.com/questions/61/can-i-program-for-arduino-without-having-a-real-board


body:
I've been using ExpressSCH (Express Schematic) from: <http://www.expresspcb.com/>

That is a free install for Windows and is pretty easy to use.

Example of its output:

[![ExpressSCH example][1]][1]

It comes with quite a few symbols defined, and you can easily make your own extra ones (like the Uno I did in the schematic above).

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


body: Myself, I prefer to use Eagle, and download Sparkfun and Adafruit libraries for components based around Arduino. There you can create schematics, and create PCB layouts too.


body:
There are many cicuit drawing softwares available on the internet.
Besides the softwares mentioned above, I would like to recommend EasyEDA editor.

It’s a free, web-based EDA suite, you can use it without installing anything.

Mac, Linux, Windows and Android,All platforms supported.

EasyEDA has simple but powerful drawing capabilities, it’s part library is quite massive and there is plenty of parts to pick from. Users can create their own symbols and footprints either by copying existing ones into My Parts then editing and saving them or by drawing them from scratch.

For example, here is a [simple 555 circuit][1].

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

  [1]: https://easyeda.com/editor#id=aa349bf359274c668ef3bb40140432cf
  [2]: http://www.circuitstoday.com/electronics-circuit-drawing-softwares
  [3]: https://i.stack.imgur.com/g7gvj.png


message:
Arduino Uno R3 (with Atmega 16u2) and MAC OSX 10.11 (El capitan) not working

I have Chinese copy of arduino which uses ATmega16u2 (at least that's what is written on the chip itself). When connected, it is visible in system information under USB section:

> Communication Device:
>
> Product ID: 0x0043
> Vendor ID: 0x2341
> Version: 0.01
> Serial Number: 75237333636351600270
> Speed: Up to 12 Mb/sec
> Manufacturer: Arduino (www.arduino.cc)
> Location ID: 0x1a140000 / 6
> Current Available (mA): 1000
> Current Required (mA): 100
> Extra Operating Current (mA): 0
> Built-In: Yes

But it doesn't show up in arduino program ports.

I've searched a lot, and it seems that people mostly had problems with arduinos on CH340 chips. I also have one such arduino, but it works properly after installing signed drivers as [described here][1].

Are there any solutions for atmega 16u2 chips?

My system:

 - OS X El Capitan 10.11.2 (15C50) (hackintosh if it changes anything).
 - Arduino Uno R3 (chinese copy)
 - Arduino soft version 1.6.7

Additional info:
I've tried connecting Arduino Mega 2560 with Atmega16u2 chip and it also doesn't work

  [1]: http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

Info I've got using Nick's awesome program:

    Atmega chip detector.
    Written by Nick Gammon.
    Version 1.17
    Compiled on Jan  8 2016 at 21:35:08 with Arduino IDE 10607.
    Attempting to enter ICSP programming mode ...
    Entered programming mode OK.
    Signature = 0x1E 0x94 0x89
    Processor = ATmega16U2
    Flash memory size = 16384 bytes.
    LFuse = 0xFF
    HFuse = 0xD9
    EFuse = 0xF4
    Lock byte = 0xFF
    Clock calibration = 0x56
    Bootloader in use: No
    EEPROM preserved through erase: No
    Watchdog timer always on: No
    Bootloader is 4096 bytes starting at 3000

    Bootloader:

    3000: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    3010: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    3020: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    ...

    MD5 sum of bootloader = 0x6A 0xE5 0x9E 0x64 0x85 0x03 0x77 0xEE 0x54 0x70 0xC8 0x54 0x76 0x15 0x51 0xEA
    No bootloader (all 0xFF)

    First 256 bytes of program memory:

    0: 0x90 0xC0 0x00 0x00 0xA9 0xC0 0x00 0x00 0xA7 0xC0 0x00 0x00 0xA5 0xC0 0x00 0x00
    10: 0xA3 0xC0 0x00 0x00 0xA1 0xC0 0x00 0x00 0x9F 0xC0 0x00 0x00 0x9D 0xC0 0x00 0x00
    20: 0x9B 0xC0 0x00 0x00 0x99 0xC0 0x00 0x00 0x97 0xC0 0x00 0x00 0x48 0xC4 0x00 0x00
    30: 0x0C 0xC4 0x00 0x00 0x91 0xC0 0x00 0x00 0x8F 0xC0 0x00 0x00 0x8D 0xC0 0x00 0x00
    40: 0x8B 0xC0 0x00 0x00 0x89 0xC0 0x00 0x00 0x87 0xC0 0x00 0x00 0x85 0xC0 0x00 0x00
    50: 0x83 0xC0 0x00 0x00 0x81 0xC0 0x00 0x00 0x7F 0xC0 0x00 0x00 0x02 0xC1 0x00 0x00
    60: 0x7B 0xC0 0x00 0x00 0x79 0xC0 0x00 0x00 0x77 0xC0 0x00 0x00 0x75 0xC0 0x00 0x00
    70: 0x73 0xC0 0x00 0x00 0x71 0xC0 0x00 0x00 0x6F 0xC0 0x00 0x00 0x6D 0xC0 0x00 0x00
    80: 0x6B 0xC0 0x00 0x00 0x69 0xC0 0x00 0x00 0x67 0xC0 0x00 0x00 0x65 0xC0 0x00 0x00
    90: 0x63 0xC0 0x00 0x00 0x61 0xC0 0x00 0x00 0x12 0x01 0x10 0x01 0x02 0x00 0x00 0x08
    A0: 0x41 0x23 0x43 0x00 0x01 0x00 0x01 0x02 0xDC 0x01 0x09 0x02 0x3E 0x00 0x02 0x01
    B0: 0x00 0xC0 0x32 0x09 0x04 0x00 0x00 0x01 0x02 0x02 0x01 0x00 0x05 0x24 0x00 0x01
    C0: 0x10 0x04 0x24 0x02 0x06 0x05 0x24 0x06 0x00 0x01 0x07 0x05 0x82 0x03 0x08 0x00
    D0: 0xFF 0x09 0x04 0x01 0x00 0x02 0x0A 0x00 0x00 0x00 0x07 0x05 0x04 0x02 0x40 0x00
    E0: 0x01 0x07 0x05 0x83 0x02 0x40 0x00 0x01 0x04 0x03 0x09 0x04 0x32 0x03 0x41 0x00
    F0: 0x72 0x00 0x64 0x00 0x75 0x00 0x69 0x00 0x6E 0x00 0x6F 0x00 0x20 0x00 0x28 0x00

    Programming mode off.

Fuses info:

    Atmega fuse calculator.
    Written by Nick Gammon.
    Version 1.10
    Compiled on Jan  8 2016 at 22:19:34 with Arduino IDE 10607.
    Attempting to enter programming mode ...
    Entered programming mode OK.
    Signature = 0x1E 0x94 0x89
    Processor = ATmega16U2
    Flash memory size = 16384
    LFuse = 0xFF
    HFuse = 0xD9
    EFuse = 0xF4
    Lock byte = 0xFF
    Clock calibration = 0x56
    Hardare Boot Enable..................... [X]
    Debug Wire Enable....................... [ ]
    External Reset Disable.................. [ ]
    Enable Serial (ICSP) Programming........ [X]
    Watchdog Timer Always On................ [ ]
    Preserve EEPROM through chip erase...... [ ]
    Boot into bootloader.................... [ ]
    Divide clock by 8....................... [ ]
    Clock output............................ [ ]
    Bootloader size: 4096 bytes.
    Start-up time: SUT0: [ ]  SUT1: [ ] (see datasheet)
    Clock source: low-power crystal.
    Brownout detection at: 3.0V.

body:
You can use my [Chip detector sketch](http://www.gammon.com.au/forum/?id=11633) to confirm (using another Arduino to run the sketch) if the target chip is a Atmega16u2 or not, and if so, what fuses etc. are set.

Wiring would be like this:

[![Connecting to Atmega16u2][1]][1]

Close-up:

[![Wiring close-up][2]][2]

ICSP header (from above):

[![ICSP header][3]][3]

You should see something like this:

    Atmega chip detector.
    Written by Nick Gammon.
    Version 1.17
    Compiled on Jan  3 2016 at 07:34:08 with Arduino IDE 10605.
    Attempting to enter ICSP programming mode ...
    Entered programming mode OK.
    Signature = 0x1E 0x94 0x89
    Processor = ATmega16U2
    Flash memory size = 16384 bytes.
    LFuse = 0xEF
    HFuse = 0xD9
    EFuse = 0xF4
    Lock byte = 0xCF
    Clock calibration = 0x96
    Bootloader in use: No
    EEPROM preserved through erase: No
    Watchdog timer always on: No
    Bootloader is 4096 bytes starting at 3000

    Bootloader:

    3000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
    3010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
    3020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xEE 0xC4 0x00 0x00

    ...

    MD5 sum of bootloader = 0xD8 0x8C 0x70 0x6D 0xFE 0x1F 0xDC 0x38 0x82 0x1E 0xCE 0xAE 0x23 0xB2 0xE6 0xE7
    Bootloader name: Arduino-dfu-usbserial-atmega16u2-Uno-Rev3

    First 256 bytes of program memory:

    0: 0x90 0xC0 0x00 0x00 0xA9 0xC0 0x00 0x00 0xA7 0xC0 0x00 0x00 0xA5 0xC0 0x00 0x00
    10: 0xA3 0xC0 0x00 0x00 0xA1 0xC0 0x00 0x00 0x9F 0xC0 0x00 0x00 0x9D 0xC0 0x00 0x00
    20: 0x9B 0xC0 0x00 0x00 0x99 0xC0 0x00 0x00 0x97 0xC0 0x00 0x00 0x48 0xC4 0x00 0x00
    30: 0x0C 0xC4 0x00 0x00 0x91 0xC0 0x00 0x00 0x8F 0xC0 0x00 0x00 0x8D 0xC0 0x00 0x00
    40: 0x8B 0xC0 0x00 0x00 0x89 0xC0 0x00 0x00 0x87 0xC0 0x00 0x00 0x85 0xC0 0x00 0x00
    50: 0x83 0xC0 0x00 0x00 0x81 0xC0 0x00 0x00 0x7F 0xC0 0x00 0x00 0x02 0xC1 0x00 0x00
    60: 0x7B 0xC0 0x00 0x00 0x79 0xC0 0x00 0x00 0x77 0xC0 0x00 0x00 0x75 0xC0 0x00 0x00
    70: 0x73 0xC0 0x00 0x00 0x71 0xC0 0x00 0x00 0x6F 0xC0 0x00 0x00 0x6D 0xC0 0x00 0x00
    80: 0x6B 0xC0 0x00 0x00 0x69 0xC0 0x00 0x00 0x67 0xC0 0x00 0x00 0x65 0xC0 0x00 0x00
    90: 0x63 0xC0 0x00 0x00 0x61 0xC0 0x00 0x00 0x12 0x01 0x10 0x01 0x02 0x00 0x00 0x08
    A0: 0x41 0x23 0x43 0x00 0x01 0x00 0x01 0x02 0xDC 0x01 0x09 0x02 0x3E 0x00 0x02 0x01
    B0: 0x00 0xC0 0x32 0x09 0x04 0x00 0x00 0x01 0x02 0x02 0x01 0x00 0x05 0x24 0x00 0x01
    C0: 0x10 0x04 0x24 0x02 0x06 0x05 0x24 0x06 0x00 0x01 0x07 0x05 0x82 0x03 0x08 0x00
    D0: 0xFF 0x09 0x04 0x01 0x00 0x02 0x0A 0x00 0x00 0x00 0x07 0x05 0x04 0x02 0x40 0x00
    E0: 0x01 0x07 0x05 0x83 0x02 0x40 0x00 0x01 0x04 0x03 0x09 0x04 0x32 0x03 0x41 0x00
    F0: 0x72 0x00 0x64 0x00 0x75 0x00 0x69 0x00 0x6E 0x00 0x6F 0x00 0x20 0x00 0x28 0x00

    Programming mode off.

---

On my genuine Uno I get these settings from OS/X:

      Product ID: 0x0043
      Vendor ID: 0x2341
      Version:  0.01
      Serial Number: 74134373733351300000
      Speed: Up to 12 Mb/sec
      Manufacturer: Arduino (www.arduino.cc)
      Location ID: 0xfd130000 / 8
      Current Available (mA): 500
      Current Required (mA): 100

I haven't had any problems using the Uno with OS/X however I don't remember whether or not I had to install a device driver for it.

---

> Info I've got using Nick's awesome program:

    ...
    Signature = 0x1E 0x94 0x89
    Processor = ATmega16U2
    Flash memory size = 16384 bytes.
    LFuse = 0xFF
    HFuse = 0xD9
    EFuse = 0xF4
    ...
    Bootloader:

    3000: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    ....

    MD5 sum of bootloader = 0x6A 0xE5 0x9E 0x64 0x85 0x03 0x77 0xEE 0x54 0x70 0xC8 0x54 0x76 0x15 0x51 0xEA
    No bootloader (all 0xFF)

It is interesting that they are shipping without a bootloader on the ATmega16U2. Whilst that chip doesn't need one (and it is disabled by the fuses in mine) clearly there are *some* differences. I checked the "first 256 bytes" of the code between your board and mine and they are the same, so possibly the main code is identical.

I would try to plug your Arduino into another Mac, if possible. It may be that your "hackintosh" has enough differences in its loaded software that it doesn't recognize that USB interface.

  [1]: https://i.stack.imgur.com/mvkwF.jpg
  [2]: https://i.stack.imgur.com/gVjGX.jpg
  [3]: https://i.stack.imgur.com/02lMq.png


body:
After two months I finally found a solution. The problem was with USB drivers for my hackintosh. Few days ago new [Multibeast 8.1][1] was released with new USB drivers. After installing El Capitan 10.11.4 update and then installing USB drivers from Multibeast my Arduinos magically starter working again!

  [1]: http://www.tonymacx86.com/downloads.php?do=file&id=313


body:
There is complete documentation on Arduino website, I followed the steps and I was able to install driver

https://support.arduino.cc/hc/en-us/articles/4408887452434-Flash-USB-to-serial-firmware-in-DFU-mode


message:
Interfacing Gammon's RS485 with computer

I'm using the non-blocking RS485 Gammon's library for Arduino (as shown at http://www.gammon.com.au/forum/?id=11428) to handle the communication between some arduinos.
Now I'm having trouble to add a Raspberry Pi (or otherwise a non-arduino platform) to the network.

How can I integrate the Gammon's protocol in a python or processing software?

body:
Open-source and Web-search is just great. [This][1] might be what you are looking for.

Cheers!

  [1]: https://github.com/Sthing/Nick-Gammon-RS485


message:
Decision maker loop problem

Today, I've started a decision maker, using a Arduino UNO R3, a button and a RGB led.
This project makes a decision for you (yes, no, or maybe) when you don't know your own decision about something.

The code I used in the project is the following one (written by me):

    #define out OUTPUT
    #define in INPUT
    #define H HIGH
    #define L LOW

    int red = 2;
    int green = 3;
    int blue = 4;

    int randomValue = 0;

    int button = 5;
    int buttonState = 0;

    void setup(){
        pinMode(red, out);
        pinMode(green, out);
        pinMode(blue, out);

        pinMode(button, in);
    }

    void loop(){
        buttonState = digitalRead(button);
        if(buttonState == H){
            randomValue = random(0,4);
            if(randomValue == 1){
                digitalWrite(red, H);
                delay(200);
                digitalWrite(red, L);
                clear();
            }
            if(randomValue == 2){
                digitalWrite(green, H);
                delay(200);
                digitalWrite(green, L);
                clear();
            }
            if(randomValue == 3) {
                digitalWrite(blue, H);
                delay(200);
                digitalWrite(blue, L);
                clear();
            }

        }
    }

The connections are correct, and the code also. The problem is: when I push the button, the LED starts showing random colors, and what I want is for the LED to show one color per push.

What can I do?

body:
There is one basic concept that you are lacking.  At the moment you are looking to see *if* the button is pressed, not *when* the button has been pressed.

Instead of just looking to see if it is HIGH you need to look if it *was* LOW but is *now* HIGH. It's that transition from LOW to HIGH that you need to use as your trigger for when to set the LED colour, and that means remembering the state of the button the last time you went through the loop.

    buttonState = digitalRead(button);
    if (buttonState != oldButtonState) {
        oldButtonState = buttonState;
        if(buttonState == H) {
            // Do your stuff
        }
    }

`oldButtonState` is defined the same as `buttonState`.


message:
Low Cost Motorized Valve

I'm looking for a low cost motorized water valve.  I've done a number of searches and have found nothing compelling.  Has anyone here used a motorized water valve with Arduino?  What would you recommend?

A fail-open solenoid might also work but I'd like to try my hand at a motorized valve.

The valves I found start at US$50.  I'm looking for something cheaper.  The purpose is tinkering and I'd like to make an "if water detected - then close valve" sketch.  Ir's simple, just more expensive than I expected.

body:
You can get sprinkler valves, that use solenoids, for under $20 that fit on plastic PVC pipe and are designed for water, such as these at [SprinklerWarehouse][1].  They typically use pipe sizes of about 1 inch.

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


message:
android app to control arduino using usb

I am trying to figure out how i could make an android app like this one, https://www.youtube.com/watch?v=cVj0jqOlGXo but instead of transmitting through bluetooth it would transmit it through a usb cable that plugs from my phone directly into my arduino.

body:
I think you may want to look *USB Serial port communication in android*. Some googling will help
 here's a nice example of such work, described in detail:

http://felhr85.net/2015/01/09/a-dirty-and-quick-example-of-serial-port-communication-in-android/

And in case the codes/that source gets lost, here is the
GitHub link of the developer: https://github.com/felHR85/SerialPortExample


message:
Access denied when Uploading

I went to upload my sketch to my Uno (r3), but unusually, the Upload Console returned this error:

    avrdude: ser_open(): can't open device "\\.\COM4": Access is denied.

Just started seeing this, cannot upload.

body: You have selected the wrong COM port. Go to Tools -> Port -> Select the right port. If you do not know the port number disconnect the Arduino, open the same menu again and look what is listed there, write down if you can't remember, now plug your Arduino back in and select the option that wasn't there before.


body:
There might be another device has already connected to that port. It could even be a terminal emulator which is left connected from last debugging session.

Otherwise, make sure that your UNO is really presented on COM4 by checking with "Device Manager". if not, change the port where it is available.


body: I'm using a windows 10 and had this happen randomly. I closed several other applications and it started working again.


message:
In UART, what mechanism sets the "new data received" flag back to 0?

I was reading [documentation on UART on AVR][1] and it looks simple: when a flag (bit `RXC0` of register `UCSR0A`) is set to 1, it means the micro controller has new data for you, and you read this from register `UDR0`.

But something boggles my mind: How does the micro controller know that we have read the data? Or, in other words, after it received the first byte on UART, the flag is set to 1, but when is it set back to 0?

  [1]: http://www.embedds.com/programming-avr-usart-with-avr-gcc-part-1/

body:
The ATmega328p data-sheet describes the setting of RXCn:

### Bit 7 – RXCn: USART Receive Complete

> This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXCn bit will become zero. The RXCn Flag can be used to generate a Receive Complete interrupt (see description of the RXCIEn bit).

The hardware seems to keep a register the size of the receive buffer. Incremented when received and decremented when read. It is only one level so the size is 0..1, i.e. one bit.

Actually there is two registers; one for possible incoming data and one for the latest data until read.

Cheers!

More details in [ATmega328p data-sheet, chap. 19 USART0][1]

  [1]: http://www.atmel.com/images/doc8161.pdf


message:
How does the PID controller actually work?

Preferably PID functions on an Arduino uno or any other examples. I have been researching but many of the the websites really do not explain it.

**P.S is there an algorithm for a PID? Thanks**

body:
How a PID controller works depends on the particular implementation.

There is a algorithm/library for PID on the Arduino: http://playground.arduino.cc/Code/PIDLibrary and an excellent explanation of the all of functions within it at http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/

Over on stackoverflow and electronics, there are some good questions and explanations that might help:

*  https://electronics.stackexchange.com/questions/190606/understanding-a-pid-controller

*  https://stackoverflow.com/questions/14614124/how-do-i-use-a-pid-controller?rq=1

* https://stackoverflow.com/questions/21516143/pid-control-value-of-process-parameter-based-on-pid-result?rq=1

* https://stackoverflow.com/questions/13542447/i-dont-understand-integral-part-of-pid-controller?rq=1

* https://stackoverflow.com/questions/21534996/pid-controller-intuition-for-when-error-0?rq=1


body:
I, also, didn't get the idea behind PID from just reading Wikipedia. After some videos/tutorials, I believe the best way to explain it is:

**What is PID**

PID is an algorithm. It involves three factors which can be adjusted to tune a signal.

It is often used in servo's (and things like thermostates, basic signal controllers)

**Imagine this**

The servo will be used in the practical examples.

A servo has:
- a current position (signal)
- the position you want the servo to be in (goal signal)
- a speed (PID output signal)

The PID output signal/algorithm makes sure that the servo reaches it's goal.

**In short:**

PID is an algorithm that can adjust a signal towards an setpoint. Or correct it for that matter.
It regulates how much you have to adjust the signal, without getting serious overshoot, or oscillation around the setpoint.

**Detail:**

P stands for proportional.

Which means that the further the servo is from it's setpoint, the more speed we want to/can give it. So that we're faster towards the set point.
This also means that we slow down as we near the set point.
Of course you can multiply each of these rules with a factor, to achieve a better balance.

I stands for integrating.

It basically comes down to the fact that it constantly keeps adding to the signal, depending on how long there is a difference between the current point and set point. This is so that if P is still a little slow, it adds some speed over time.

D stands for differentiating

It's less commonly used. (Wikipedia)
The D factor reacts on the speed of the change in value. Or speed of change in setpoint (Dutch wikipedia is not 100%, comment if neccesary :) )

These factors / the algorithm provides a smooth regulation of various systems, hence that's why it is so adjustable.

It can be used for balancing quadcopters or making your house comfortably warm (without sudden changes, or too slow changes)

**Why?**

How would you balance a quadcopter?
If it shifts to one side, you don't want to fully reverse the throttle.
It'll make it wobble, since you get a lot of overshoot.
Controlling things can be hard, PID is an known working algorithm for those cases. But you have to adjust the factors right to adjust it to your specific system. (They all react differently, or have to react differently).


message:
Audio Visualizer (not working properly)

**Parts**

 - Arduino Uno R3 (Atmega328 - assembled)
 - Adafruit Bicolor LED Square Pixel Matrix with I2C
   Backpack
 - Electret Microphone Amplifier - MAX4466 with Adjustable Gain
 - Half-size Breadboard
 - Breadboarding wires

**Description**
I have been following the build guide for the "Piccolo Music Visualizer" on the Adafruit website (https://learn.adafruit.com/piccolo?view=all), using all of the same components and code (following the guide exactly as shown). I first tested the 8x8 matrix to see if it was working properly, and it works beautifully. The problems started when I wired up the electret microphone...

In regard to how I wired this to the breadboard, I followed the example for the R3 on the Adafruit guide (since that's my current version):

**Note**
The files (code) used for this project are found here: (https://github.com/adafruit/piccolo). The ffft file is supposed to be saved to the library (this worked for me). The Piccolo file is supposed to be saved to the Sketchbook (this did not work for me - kept giving error messages when trying to reference it). I instead copied the code found in the Piccolo file, and saved it as a new sketchbook file. Let me know if this might be the cause of the problem. This is my first arduino project, so I am still trying to figure out how the IDE works.

**Problem**
The electret microphone is supposed to pick up audio and the LED matrix should display a waveform based on the loudness and frequency of the audio. Instead, I only have 2 bars on the bottom left lighting up (the effect is static - wont respond to volume or frequency changes). Oddly, when pulling out the microphone from the breadboard, the waveform begins displaying as it should, but in a glitchy/unstable form. I figured the problem was with the adjustable gain on the microphone, but no matter how much I adjust the screw only the 2 bars are affected and still static (when adjusted to the left only green LED, in middle is green and orange, to the right is red/orange/green on the matrix).

A little confused as to what the problem could be... is the microphone broken, code malfunctioning, wiring incorrect, etc.

**Pictures to reference** (DropBox link)**:**
- ***See comment below for link*** (must have *10 rep* to use more than *2 links* in post)
(zip file contains **3** pictures: "*wiring*", "*when_on*", "*pulling_out_mic*")
Photos are over 2MB so I couldnt upload here.

body:
It sounds like a dry joint; the fact that the LED matrix seems to work 'better' when you're fiddling with the microphone board makes me think that the problem lies entirely with that little board.

Try adding more solder; the more the merrier.


message:
Can I use a GPS from old Garmin with an Arduino?

I'm working on an Arduino project, and I'd like to add GPS functionality. I could buy a GPS module, but those are expensive. I had an old Garmin Forerunner 305 lying around, so I took it apart and took a peek inside. There are two PCBs - one connected to a screen and one to the GPS. In addition, there was a battery and a small part for charging.

I'd like to know if it is possible to connect this GPS to my Arduino, and if so, how?

Edited:
To make my question more precise,

-I see the pins in the top right of the picture. How do I connect those to my Arduino? Is there any specific kind of wire? Because the pins are too small for standard wires.

-Once I connect it, how do I figure out the voltage requirements and pin layout? I tried googling the  GPS model, but nothing helpful came up. What kind of scope should I put on it?

The two pictures below show only the GPS part of the inside of the watch.
[![The GPS PCB][3]][3]

[![The other side of the GPS][4]][4]

  [3]: https://i.stack.imgur.com/CMrCK.jpg
  [4]: https://i.stack.imgur.com/VsdzK.jpg

body:
The short answer is **NO**, unless you have solid experience with microelectronics.

Finding documentation for a module you take out of a commercial device is hard to impossible. Chances are, that module is specific to Garmin, and even if it isn't, it's certainly [EOL][1] by now, with no support whatsoever.

Even if you do find the spec, there is a high chance that you'll have to write a software library to support it on Arduino. Don't expect the supplier to share the code they gave to Garmin.

Finally, to put together and debug this project, you will need quite some equipment:

- oscilloscope to debug the electrical interface
- soldering station to solder small pins properly

Like people said in comments, this equipment alone will cost much more than a brand-new GPS receiver.

  [1]: https://en.wikipedia.org/wiki/End-of-life_(product)


body:
Yes, interfacing with arduino, PC, ESP8266, whatever, easy peasy.  Simple to breakout the serial comms off the Garmin, and whether or not you want to use a logic level shifter (Depending on your RS-232 logic requirements), easy too implement.

I've got a whole bunch of old Garmins (and some new ones) interfaced with some cheapy ESP8266's so I can share the GPS output (All of it.  Not just the x,y,z position data), with multiple devices.

I'd be willing to share the code, wiring if you wish.


message:
Using Arduino Uno as ISP to program Mega 2560

I'm trying to use Arduino Uno as ISP to program Arduino Mega 2560 using this Pin connections (Uno->Mega):

slave reset: 10:       ->        RESET on target

MOSI:        11:      ->           51

MISO:        12:      ->         50

SCK:         13:      ->        52

It runs perfectly when I "Burn Bootloader" from Arduino IDE and LED starts blinking on target. So I assume my pin connections are correct.

However, when I open the Blink example and perform "Upload Using Programmer" in Sketch tab after choosing "Arduino as ISP" in Tools>Programmer it uploads the code but LED on Mega doesn't blink.

I'm afraid that I have problem in my Mega Bootloader hex file and think it's not configuring Pin 13 as a LED pin. But in this case I shouldn't have seen the led blinking after burning the bootloader.

What am I missing here? I appreciate your help.
-Bex

body:
Find the file called "boards.txt" located in your Arduino installation directory. In my case, the path is "arduino-1.6.5/hardware/arduino/avr/boards.txt". Open it with your favourite text editor and locate the ATMEGA2560 section. (not in notepad, it breaks the file format, notepad++ my choice)

in boards.txt

* back-up the file incase you break it,
* find the line :
mega.menu.cpu.atmega2560.bootloader.high_fuses=0xD8
* and change it with :
mega.menu.cpu.atmega2560.bootloader.high_fuses=0xD9

Source : http://soc.ninja/documentation/programming-atmega2560-with-arduino-uno-or-mega/#rating-74


message:
How to send data from ThingSpeak to ESP-8266 (Arduino) using ThingHTTP?

I have made an Arduino kit that acts as a weather station. It sends sensors data (DHT11 & LDR) to the ThingSpeak web server.

Now I want to perform some actions based on the data on the ThingSpeak server (like if temperature exceeds a limit turn on the fan, etc).

I've searched and I found that there's a React app on ThingSpeak, which will trigger events if data exceeds some values.

The problem where I got stuck is that I want to send a signal from the ThingSpeak web server to my ESP8266 (Arduino) to turn on/off the device connected to a relay on Arduino.

I've figured out that there's also a ThingHTTP feature which sends HTTP requests. But I don't know how to send requests/signals to my kit to perform some actions.

I've already spent 2 months building this project, and now I'm stuck in the last part. Please give your valuable suggestions and solutions.

body:
For sending information to/from Arduino best option is MQTT. It's lightweight and very simple to use.

While your Arduinos are using MQTT to send info and receive commands (like changing thresholds), your Web server has access to the same information in real time. You can format it and present it in any way you like, without any Arduino participation.


message:
Sending 5 Led pixel values to arduino , is this a good way?

I wanted to install a 5 LED strip underneath my PC's front panel. I want to send color over PC so it can change when i open different apps, with temperature or etc!

So all I think the best way to do this is to just use Arduino to set the LED Values!

But I have had some troubles creating a good communication protocol for this, I've been just simply sending 45 digits (15 3 digit numbers) to my Arduino with serial. here's code:
Arduino :

    #include "Adafruit_NeoPixel.h"
    #include "WS2812_Definitions.h"

    #define PIN 4
    #define LED_COUNT 5

    struct pixel {
      int R = 0;
      int B = 0;
      int G = 0;
    };

    Adafruit_NeoPixel leds = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_GRB + NEO_KHZ800);

    char count = 1;
    int pixelNumber = 0;
    struct pixel tempPixel;
    //struct pixel Pixels[LED_COUNT];

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Init");
      leds.begin();  // Call this to start up the LED strip.
      clearLEDs();   // This function, defined below, turns all LEDs off...
      leds.show();   // ...but the LEDs don't actually update until you call this.
    }

    void loop() {
      if(Serial.available() > 0) {
        if(count == 1) {
          tempPixel.R = PC_Receive();
        } else if (count == 2) {
          tempPixel.G = PC_Receive();
        } else if (count == 3) {
          tempPixel.B = PC_Receive();
          count = 0;

          setPixelColor(pixelNumber, tempPixel);
          Serial.println(pixelNumber);
          leds.show();
    //      Pixels[pixelNumber] = tempPixel;
          if(++pixelNumber >= LED_COUNT) {
            pixelNumber = 0;
          }
        }
        count++;
      }

    //  if(pixelNumber == 0) {
    //    for(int i = 0; i < LED_COUNT; i++ ) {
    //       setPixelColor(i, Pixels[i]);
    //    }
    //
    //    leds.show();
    //  }
    }

    void setPixelColor(int a, struct pixel P)
    {
      leds.setPixelColor(a, P.R, P.G, P.B);
    }

    char PC_Receive() {
      int result = 0;

      while(Serial.available() == 0);
      result += ((int)Serial.read() - '0') * 100;

      while(Serial.available() == 0);
      result += ((int)Serial.read() - '0') * 10;

      while(Serial.available() == 0);
      result += ((int)Serial.read() - '0');

      Serial.println(result);
      return result;
    }

    void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) {
      for(int i = 0; i < LED_COUNT; i++) {
        leds.setPixelColor(i, red, green, blue);
      }
      leds.show();
     }

And here's PC's dirty code in python:

    import serial
    import time
    import random

    class Pixel:

     def __init__(self, R, G, B):
      self.R = R
      self.G = G
      self.B = B

    def clearAll():
     for i in range(0,5):
      ser.write("000000000")

    def sendPixel(pixels):
     for i in range(0,5):
      ser.write(str(pixels[i].R).zfill(3))
      ser.write(str(pixels[i].B).zfill(3))
      ser.write(str(pixels[i].G).zfill(3))

    ser = serial.Serial('/dev/ttyACM2', 9600)

    little = [0,0,0,0,0]

    for i in range(0,5):
     little[i] = Pixel(0,255,50)
    sendPixel(little)

    time.sleep(0.5)
    clearAll()

the problem is it isn't stable, i think i should just use an \n at end or send back OK or something to confirm it, but that would make it slow if i did it for each value! (and checking only once after all 5 leds are send would mean sending more values until i receive the ok and clearing and sending them again!)

Can you recommend me a better way?

Thanks!

EDIT: Just wanted to say! it's almost done! It does change color when i open chrome, and i think at 115200 baud rate it's fast enough to not notice a delay (although at 9600 i felt like it's slower then my (xxx/xxx/xxx....) protocol but it's better and works at 115200

i will add some basic functions to my python side and add a rainbow effect
I will also add GPU temperature and etc... it's not going to be really hard on linux but windows, im not sure :D

body:
I'd recommend adding digits to a digit register, setting the an R,B,G register with R,B,G and setting values of led a-e to the RBG registers when you get an a-e, ignoring whitespace, and clearing the register otherwise.  So:

     ser.write("xRBGabcde\n")  # clear all the LEDs
     ser.write("x127RBb")       # make led b half-purple, relying on prior state
     ser.write("x255Gc")        # make led c greenish-white


body:
I would recommend a similar solution as DaveX with a small modofication.

If you bitmask your LEDS, and leave room for a possible additional 3, you can mask any combination of them in the space of 00-FF. then you could send to the arduino a single string of 0xFFFFFFFF  FF(LED bitmask),FF(Red value), FF(Green Value), FF(Blue Value).

so
LED 1 {`00000001` =`01`} all red {`FF0000`} would be `0x01FF0000`

LED 2 and  4 {`00001010` =`0A`} all green {`00FF00`} would be `0x0A00FF00`

LED 5 and 1 {`00010001` =`11`} all blue {`0000FF`} would be `0x110000FF`

ALL LEDS off would be `0xFF000000`

All LEDS onn full white would be `0xFFFFFFFF`


message:
WiFi repeater using ESP8266

I have a [ESP8266][1] and I wonder if it is possible to create a Wi-Fi signal repeater using this module.

- I can create a network so that devices connect it.
- I can connect to an existing network.

But I can not connect the network created with the network that I connected

Does anyone know how to do this? or you have any examples?

  [1]: https://alselectro.files.wordpress.com/2015/05/esp1.png

body:
You can't have a single ESP8266 be both an access point and a client, at least not using the exposed API (recall that the Arduino libaries do not implement much functionality themselves, all they do is call the underlying RTOS API).

Also, a signal repeater is not a radio-only device. It would have to understand the low-level 802.11* protocols and packet types so you don't end up with forwarding loops. You can't do it just by connecting a pair of 8266s back-to-back over SPI and blindly forward packets; there is a lot of networking code that would have to be written.


message:
Print string and integer LCD

How do I print a string and integer on an LCD? Here is what I have tried:

    int number = 2;
    int result = (number + number);
    lcd.print(number, DEC + " plus " + number, DEC + " equals " + result, DEC);
And the result is an error.  When I try:

    lcd.print(number + "look");
or

    lcd.print("1234 " + number);

Then the result on the LCD is "34 ", as it deleted the first two numbers!

I want it to print:

1234 2

Please help!  Thanks!

body:
The `lcd.print()` method takes a string or a number as an argument, but not both at once. Using the + operator for concatenation is not native to C strings. C strings are basically stored as pointers to the first character of the string. So when you tried `lcd.print("1234 " + number)` and got `"34 "`, what most likely happened is that you advanced the pointer, pointing to the first character of `"1234 "`(i.e. '1') by `number` (i.e. 2), thus making the pointer point to the **3rd** character in the string and thus making `lcd.print()` display `"34 "`.
In order to print something that contains both strings and integers, the most straightforward way is to convert each piece to an Arduino string and then concatenate them, using the + operator like you did earlier.

        lcd.print(String("1234 ") + String(number));
        lcd.print(String(number) + String(" plus ") + String(number) + String(" equals ") + String(result));

These are some examples. You could also use create a sufficiently large `char` buffer and use `sprintf()` from `stdio.h` to build a string made up of integers and strings. Look up a textbook on C/C++ for more details.


body:
What is wrong with this:

    lcd.print(number, DEC + " plus " + number, DEC + " equals " + result, DEC);

It is the number of parameters and the assumption that plus will concatenate string literals.

    lcd.print("1234 " + number);

This gives "34 " when number is 2. Why? This is because that is the result of adding 2 to the string literal pointer, i.e. the string starting at the character "3". Please use separate print statements instead:

    lcd.print("1234 ");
    lcd.print(number);

Do not use String to concatenate strings. That is a waste of SRAM, processing and has a risk of heap fragmentation. Simply a bad idea in small scale embedded systems such as AVR.

To understand these errors you should go back and read about strings and string literals in C/C++ (compared to Java :).

Cheers!


body:
I got the same problem and I printed the string and the integer on the same line by moving the cursor like this :

       lcd.setCursor(0, 0);    <----------Column 0 , Line 1
       lcd.print("This code failed");
       lcd.setCursor(0, 1);    <----------Column 0 , Line 2
       lcd.print("Error Code = ");
       lcd.setCursor(13, 1); <-change the cursor for the INT. Column 13 , Line 2
       lcd.print(int);


body:
    int a=0;
    float b=10.01;

    char str[16];

    sprintf(str,"a=%d, b=%.2f, c=%d", a, b, 2); // use sprintf() to compose the string str

    lcd.print(str);

The output will be 'a=0, b=10.01, c=2'


message:
panstamp device signature is random

I Have 2[panstamp][1]. I can program the first but not the second with the arduino program.

When I upload the sketch (a simple blink) on the second, I got this

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x004e22
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check.

avrdude done.  Thank you.

And if I retry, I got this.

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x81f014
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check.

avrdude done.  Thank you.

The device signature is not the same anymore ...
I've changed the wire and re-open arduino program. But it don't change, the device signature change (often 0xE1E1E1). I've check the connection between the ATmega and the wire and everything is ok.

Is the Panstamp broken ? or should I do a kind of factory reset?

  [1]: http://panstamp.com

body:
> Is the Panstamp broken ?

Sounds like it. If one works, and the other does not, using the same wiring, it looks like you have a faulty one.

> or should I do a kind of factory reset?

You can't really "factory reset" a chip like that. Possibly there is a problem with the fuses. You may be able to explore further here:

<https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board>


message:
>> << and -> Syntax in arduino

I was trying to follow [this][1] tutorial and came across `>>`. What exactly does this do?

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

body:
`>>` is right shift a value by a certain number of bits.
`<<` is left shift a value by a certain number of bits.
`->` is accessing a member of a class or struct that is referenced by a pointer.

# Right Shift and Left Shift

If you have a binary number `0b00010000` and right shift it two bits you get `0b00000100`. The C notation for that is `val >> 2`.  The same for left shift - `val << 2` would result in `0b01000000`.

# Pointers and members

Normally when you access a member of a class or struct you use `.`, such as `Serial.println()`.  However it is possible to make a *pointer* to a class instance, and when you do you need to access the members with `->` instead of `.` - such as `mySerial->println()`.
This arrow notation serves as syntactic sugar: `mySerial->println()` is interpreted as `(*mySerial).println()`. The parentheses are necessary because the dereferencing operator `*` has a lower order of precedence compared to the dot `.` operator.


message:
Plug/socket between thermocouple wires and the amplifier

I am building a temperature monitoring system that has 24 thermocouples. Managing all the wires is a hassle, and I'd like to connect all 48 wires to a few plug and socket connectors. Maybe 6 of these [lead wire harnesses][1] from eBay (see below).

The point of this would be to allow me to quickly disconnect all the thermocouples from their amplifiers when I need reposition the arduino, and then reconnect them afterwards without tracking each individual cable.

I don't know if this will have a negative impact on the function of the thermocouples. Is it ok to have a 'joint' (i.e., the socket) in the thermocouple cables, or do they need to remain intact from the end all the way to the amplifier?

Alternatively, would having a few inches of regular copper wire inserted between the thermocouple wires and the amplifier be ok? That is, having two copper wires attached to the amplifier, joining 8 of these wires together in a socket, and attaching the plug to the actual thermocouple (alumel/chromel) wires? The thermocouple wires are several feet long.

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

  [1]: http://www.ebay.ca/itm/1pc-Small-8pin-terminal-lead-wire-harness-Jack-and-Plug-8-Pin-Wire-Socket-/181880935288?hash=item2a58f2d378:g:tx8AAOSwQTVWA1NM
  [2]: https://i.stack.imgur.com/Rz8Er.jpg

body:
I do not know the accuracy that you will require in your temperature measurements.

Your idea of using copper wire and connector sockets is reasonably ok as long as you are aware of the following :

Where you make a connection from thermocouple wire to copper, that creates another thermocouple in itself. This isn't a great problem since the temperature of the "undesired" thermocouple is likely to be at room temperature (constant?)

No matter what you do, you always end up with undesired thermocouples (example when you connect your thermocouple directly to your circuit board copper, darn it.)

[Thermocouple Selection and use](https://www.picotech.com/library/application-note/thermocouple-application-note) is a page you can go to for more information.  Especially the *Cold junction compensation* (CJC) section.

EDIT added : You should twist your extention leads together to reduce electrical noise from the environment. Twist each pair, do not twist the bundle all together.


message:
Arduino nokia 5110 lcd screen problem

Hello I have a nokia 5110 lcd display connected to my Arduino. I have looked at so many tutorials and none of them work for me. I am trying to get a bitmap displayed in the screen but only the lights light up and nothing else happens.
I have the lcd connected to the following Arduino pins:

 - vcc -- 3.3v
 - gnd -- gnd
 - sce -- pin 7
 - rst -- pin 6
 - d/c -- pin 5
 - DN -- pin 4
 - sclk -- pin 8
 - led -- 100ohm resistor --pin 11

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

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

Nothing will display on the screen could someone please help me here is my code:

     #include "U8glib.h"
     #include "dht.h"

     #define dht_apin A1
     #define backlight_pin 11

     dht DHT;

     U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6);  // CLK=8, DIN=4, CE=7, DC=5, RST=6

     const uint8_t brainy_bitmap[] PROGMEM = {
      0x00, 0x00, 0x03, 0xB0, 0x00, 0x00, 0x00, 0x00,
      0x07, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x46,
      0x00, 0x00, 0x00, 0x00, 0xFC, 0x47, 0xC0, 0x00,
      0x00, 0x01, 0xCE, 0x4C, 0x60, 0x00, 0x00, 0x03,
      0x02, 0x58, 0x30, 0x00, 0x00, 0x03, 0x02, 0x58,
      0x10, 0x00, 0x00, 0x02, 0x02, 0x58, 0x18, 0x00,
      0x00, 0x03, 0x06, 0x4C, 0x18, 0x00, 0x00, 0x07,
      0x04, 0x44, 0x18, 0x00, 0x00, 0x0D, 0x80, 0x40,
      0x3C, 0x00, 0x00, 0x09, 0xC0, 0x40, 0xE6, 0x00,
      0x00, 0x18, 0x78, 0x47, 0xC2, 0x00, 0x00, 0x18,
      0x0C, 0x4E, 0x02, 0x00, 0x00, 0x1F, 0x86, 0x4C,
      0x7E, 0x00, 0x00, 0x0E, 0xC6, 0xE8, 0xEE, 0x00,
      0x00, 0x18, 0x43, 0xF8, 0x82, 0x00, 0x00, 0x10,
      0x06, 0x4C, 0x03, 0x00, 0x00, 0x30, 0x0C, 0x46,
      0x01, 0x00, 0x00, 0x30, 0x18, 0x46, 0x01, 0x00,
      0x00, 0x10, 0x18, 0x43, 0x03, 0x00, 0x00, 0x18,
      0x10, 0x43, 0x03, 0x00, 0x00, 0x1C, 0x70, 0x41,
      0x86, 0x00, 0x00, 0x0F, 0xE0, 0x40, 0xFE, 0x00,
      0x00, 0x09, 0x1E, 0x4F, 0x06, 0x00, 0x00, 0x08,
      0x30, 0x43, 0x86, 0x00, 0x00, 0x0C, 0x20, 0x41,
      0x86, 0x00, 0x00, 0x06, 0x60, 0x40, 0x8C, 0x00,
      0x00, 0x07, 0x60, 0x40, 0xB8, 0x00, 0x00, 0x01,
      0xE0, 0x41, 0xF0, 0x00, 0x00, 0x00, 0x38, 0xE3,
      0x00, 0x00, 0x00, 0x00, 0x0F, 0xBE, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xCF,
      0x82, 0x0C, 0x86, 0x46, 0x1F, 0xEF, 0xC3, 0x0C,
      0xC6, 0xEE, 0x1C, 0xEC, 0xC7, 0x0C, 0xE6, 0x7C,
      0x1C, 0xED, 0x8D, 0x8C, 0xFE, 0x38, 0x1C, 0xED,
      0x8D, 0xCC, 0xDE, 0x38, 0x1D, 0xCD, 0xDF, 0xCC,
      0xCE, 0x38, 0x1F, 0x8C, 0xF8, 0xEC, 0xC6, 0x38,
      0x1F, 0xEC, 0x08, 0x0C, 0xC2, 0x18, 0x1C, 0xEC,
      0x00, 0xC0, 0x00, 0x00, 0x1C, 0xFD, 0xFB, 0xC0,
      0x00, 0x00, 0x1C, 0xFC, 0x63, 0x00, 0x00, 0x00,
      0x1C, 0xEC, 0x63, 0xC0, 0x00, 0x00, 0x1F, 0xEC,
      0x60, 0xC0, 0x00, 0x00, 0x1F, 0xCC, 0x63, 0xC0,
      0x00, 0x00, 0x1F, 0x0C, 0x63, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x28, 0x2B, 0x4F, 0x67,
      0x42, 0x38, 0x7B, 0xEA, 0x86, 0xB2, 0x28, 0xC7,
     };

     void draw(void) {
       u8g.drawBitmapP( 0, 0, 6, 50, brainy_bitmap);  // put bitmap
       u8g.drawStr(10, 10, "% ");

     void loop(void) {

       u8g.firstPage();
       do {
         draw();
       } while( u8g.nextPage() );

         delay(5000);  // Delay of 5sec before accessing DHT11 (min - 2sec)
       }

body:
There are several possibilities.

Arduino GPIO pins drive outputs to ground or 5V.

The pins on the Nokia 5110 LCDs boards I have are not 5V tolerant. So you might have damaged them when the Arduino's GPIO connected to 5V.

A simple fix is to put a 10k ohm resistor in each signal path, i.e.

 - sce -- pin 7
 - rst -- pin 6
 - d/c -- pin 5
 - DN -- pin 4
 - sclk -- pin 8

You could get a level-shift chip, or build a circuit, but resistors are quick, cheap and easy.

I would strongly recommend using a very simple Arduino library to get the display working. Then, once everything is working, continue with your current approach. All you need is a simple test; something which turns pixels on and off to check that it works.

I have had good results with the Arduino Playground [Philips PCD8544 (Nokia 3310) driver][1]

I have several Nokia 5110's. A few needed the values loaded at initialisation to be tweaked, to make the display visible.

Specifically in void LcdInitialise(void):

      LcdWrite(LCD_C, 0x21 );  // LCD Extended Commands.
      LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast).
      LcdWrite(LCD_C, 0x04 );  // Set Temp coefficent. //0x04
      LcdWrite(LCD_C, 0x14 );  // LCD bias mode 1:48. //0x13
      LcdWrite(LCD_C, 0x20 );  // LCD Basic Commands
      LcdWrite(LCD_C, 0x0C );  // LCD in normal mode.

I have had to tweak *Set Temp coefficent*, *LCD bias mode 1:48* and *Set LCD Vop (Contrast)* to get make the display clear, without looking washed-out, or all-dark. Using a very simple library like the [Philips PCD8544 (Nokia 3310) driver][1] should make it easy to adjust this until things work well.

  [1]: http://playground.arduino.cc/Code/PCD8544


body:
Assuming you got your code from this site: https://brainy-bits.com/tutorials/how-to-use-the-nokia-5110/, it seems you edited the code from there to display only the bitmap, but you didn't get rid of everything. You have no DHT temperature sensors, so get rid of all DHT references in your code, including the 5 seconds delay at the bottom of `loop()`. If you intend to use the code from that site, then use it this way:

    void draw(void) {
      u8g.drawBitmapP( 37, 0, 6, 50, brainy_bitmap);  // put bitmap
    }

    void setup(void) {
      analogWrite(backlight_pin, 50);  /* Set the Backlight intensity */
    }

    void loop(void) {
      u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );

    }

Make sure to get rid of the #define, #include and constructor referring to DHT.


body:
Change your pinouts. HW SPI needs 13 and 11, not 8 and 4. Try this short bit of code:
#

    include <U8glib.h>

    #define RST 6
    #define CE  7
    #define DC  5        //  D high is data, C low is command.
    #define DIN 11
    #define CLK 13
    #define Backlight 9  // Don't forget the 330 ohm resistor.

    //Declare the display and assign the pins.
      U8GLIB_PCD8544 u8g(13, 11, 7, 5, 6);  // CLK=13, DIN=11, CE=7, DC=5, RST=6

    void draw() {
      u8g.setFont(u8g_font_profont11);      // Select font
      u8g.drawStr(0, 15, "Nokia 5110...");  // Put string of display at position X, Y.
      u8g.drawStr(29, 35, "HELLO!!!");
    }

    void setup() {
        analogWrite(Backlight, 80);  // Set Backlight Intensity, 0 is fully bright, 255 is off.
    }

    void loop() {                    // Enter the U8Glib Picture Loop
     u8g.firstPage();
      do {
        draw();
      } while( u8g.nextPage() );
    }


message:
Push-Pull tone code

I wanted to use a piezo sounder to sound an alarm in an application. Testing indicated that `tone()` was not very loud.

I could use some external circuitry to swing the pins ±5V but as I have plenty of spare pins, it seemed feasible to use 2 pins driven in anti-phase to increase the power by 4.

I looked at the source `Tone.cpp` but the code is somewhat intimidating. Before I start to modify it I was wondering if anyone else has already done something like this.

body:
Yes, Tim Eckel has already published a library "toneAC" on the Arduino website at http://playground.arduino.cc/Code/ToneAC

All of the syntax is there too.


message:
constant current or constant voltage power supply to use with RGB shield with high power LEDs

So, I got an arduino uno and a [RGB shield from velleman][1] for christmas because I mentioned I might want to do a project with high power LEDs - a neat surprise, but now I have to use it (:
The shield can do PWM on an external power supply and this can be wired through to the high power LEDs itself. I aim to power about 10W of LED light in total, with different colors in order to make good use of the board. Can I go for Option 1? If not, what would you advise?

**Option 1**

As [high power LEDs][2] need a constant current, I am inclined to connect a [constant current supply][3] as the external supply of the board (assuming all channels' LEDs need the same current).

*Update*: I talked to an electrician and a constant current supply typically works on a PWM basis; putting this in series with the PWM of the shield is not smart.

**Option 2**

Alternatively I could connect a standard constant voltage supply and make sure that the current is within limits:

* One option would be to use *resistors*; but, with 12V DC and 350mA I would need like 33 Ohm resistance dissipating 4 Watts of power, which is inefficient.
* Alternatively there are [DC voltage to constant current LED drivers][4] which will take care of the constant current for me; I could put those at the exits of the shield for the LEDs. They supposedly have a better conversion efficiency than the resistors, but I do have any knowledge about their performance with PWM as input; but I have serious doubts they would like that type of input. Furthermore, these drivers also often have PWM capabilities. This kind of module would render the shield functionality largely useless.

  [1]: https://www.reichelt.de/Erweiterungsboards/ARDUINO-SHD-RGB/3/index.html?ACTION=3&GROUPID=6669&ARTICLE=148933&OFFSET=16&
  [2]: http://www.ebay.com/itm/1W-3W-High-Power-cool-warm-white-3000k-4000k-10000k-30000k-LED-20mm-star-pcb-/321471559197?var=&hash=item4ad932b61d:m:m9FF_32EUKYGAQ_1yJ7jQFA "for example..."
  [3]: http://www.ebay.com/itm/High-Power-350mA-10W-LED-Driver-Board-DC-Boost-5-32V-Wide-Input/161047962520?_trksid=p2047675.c100005.m1851&_trkparms=aid=222007&algo=SIC.MBE&ao=1&asc=20131003132420&meid=095402a042fa472d9944387cbdd4ee36&pid=100005&rk=3&rkt=6&sd=141700678280 "for example"
  [4]: http://www.ebay.com/itm/350-MA-Constant-current-LED-driver-with-PWM-control-up-to-10-off-1W-led-/311494471358?hash=item4886846ebe:g:E6EAAOSwwE5WWP1A "for example"

body:
Your thinking and reasoning is pretty much spot on.

The board you have is basically a trio of high current low side switches. So yes, you need *something* to limit the current, and as you have noted resistors are not going to be very efficient.

The best way to drive high power LEDs is, as you know, with constant current. However, you need a constant current source *per LED channel*, not one single one for the whole board. That means three individual constant current sources, each providing the right current for the LEDs you are driving on that channel.

It's possible to roll your own cheap constant current sources using LM317T linear voltage regulators (http://diyaudioprojects.com/Technical/Current-Regulator/). It's a cheap option, though pretty much as in-efficient as using resistors, just easier to deal with the heat sinking.  Note that on the LM317T the tab is live, so you must use three separate heat sinks for each channel.

My personal preference though is to use PWM capable constant current sinks. My favourite is the [CAT4101](http://www.onsemi.com/PowerSolutions/product.do?id=CAT4101) which can deal with up to 1A per channel (more if you parallel them) and uses a single resistor to set the current. It has a PWM input that you can drive direct from an Arduino's PWM pin. Of course, as you note, that then makes your nice shield redundant.


message:
Making AC current with pin 11

I'm trying to make AC current (50Hz) with an Arduino Uno. It seems to be not working (or wrong code).

    int up;
    int down;
    int out = 11;
    void setup() {
      pinMode(out, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      for (up = 0; up <= 255; up++) {
        analogWrite(out, up);
        delay(1);
      }
      for (down = 255; down >= 0; down--) {
        analogWrite(out, down);
        delay(1);
      }
    }

**Update:**

1. Now the code above is giving output voltage of 0-5V (getting increased from 0 to 5 and then decreased) not giving a negative cycle (-5V).

2. After setting the minimum delay of 1, the output wave is still half wave rectifier with frequency 2Hz.

3. Without delay LED is blinking so fast I don't know what's its frequency.

How do I make make 50Hz AC current a with negative cycle?

body:
I ran your sketch and this is the output signal:

[![square wave][1]][1]

`analogWrite` produce a square wave.

As Majenko said, you have to add a low pass filter to get that sine wave.

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


body: If you are not critical on the waveform you can use a transformer where the secondary has a center tap. The primary should have one as well. Tie the input center tap to +12 or whatever is available but DO NOT use the arduino 5 volt pin. Then using two avalanche protected N channel MOSFETs you them to drive the remaining two input leads.  The output will be a pseudo sine wave, far from perfect but it will have the negative excursion you want.This type of circuirity can be found in Switch Mode Power Supplies (SMPS). Note the transformer winding ratio will determine your output voltage. You will need a little dead time between turning one MOSFET off and the Other on.  A single mosfet would work but there would only be two connections to the transformer primary not 3 and the wave form will be a lousy.


message:
Arduino TMP36 sensor

I am following the tutorial [Tiny WiFi Temperature Sensor with Arduino][1]. everthing works fine, but I have a little problem.

When the serial monitor is opened the sensor is reading fine like 23.20, 20.25 etc.,  but when I closed the serial monitor window I got wrong values, for example, 289.34, 289.90.

What does the serial monitor do?

I am stuck with this problem for last two days. Please give me a hand.

  [1]: https://www.openhomeautomation.net/tiny-wifi-temperature-arduino/

---

 - The baud rate is as you can see 115200 and i have changed it various time but it doesn't do anything.

 - I haven't test commenting out the Serial.println() lines

 - The values i can see at my server (see the function send_request).

 - The problem is when i am testing the program opening the serial monitor windows everything works fine for example: 29.20, 30.12, 28.12 but when i close the windows i start getting wrong values for exmaple: 289.45, 289.89 , etc... .

Here is my code.
--

    #include <Adafruit_CC3000.h>
    #include <Adafruit_CC3000_Server.h>
    #include <ccspi.h>

    /*
       Tiny WiFi temperature sensor with Arduino, the TMP36 sensor & the CC3000 chip
       Writtent by Marco Schwartz for Open Home Automation
    */

    // Include required libraries

    #include <SPI.h>
    #include <string.h>
    #include "utility/debug.h"
    #include<stdlib.h>

    // Define CC3000 chip pins
    #define ADAFRUIT_CC3000_IRQ   2
    #define ADAFRUIT_CC3000_VBAT  A3
    #define ADAFRUIT_CC3000_CS    8

    // WiFi network (change with your settings !)
    #define WLAN_SSID       "ssid"        // cannot be longer than 32 characters!
    #define WLAN_PASS       "password"
    #define WLAN_SECURITY   WLAN_SEC_WPA2 // This can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2

    // Create CC3000 instance
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                             SPI_CLOCK_DIV2);

    // Local server IP, port, and repository (change with your settings !)
    uint32_t ip = cc3000.IP2U32(10,0,129,108);
    int port = 8080;
    String repository = "/tiny-wifi-temperature/";

    void setup(void)
    {

      Serial.begin(115200);
      Serial.println("Start setup");

      // Initialise the CC3000 module
      if (!cc3000.begin())
      {
        Serial.println("Impossible to start");
        while (1);
      }

      Serial.println(F("\nDeleting old connection profiles"));
      if (!cc3000.deleteProfiles()) {
        Serial.println(F("Failed!"));
        while(1);
      }

      listSSIDResults();
      connectNetwork();
      displayConnectionDetails();
      /*
      while(!displayConnectionDetails())
      {
        connectNetwork();
      }*/

    }

    void connectNetwork(void)
    {
      Serial.println(F("Trying to connect wifi ")); Serial.println(WLAN_SSID) ;

      /*
      uint32_t ipAddress = cc3000.IP2U32(10, 0, 130, 200);
      uint32_t netMask = cc3000.IP2U32(255, 255, 0, 0);
      uint32_t defaultGateway = cc3000.IP2U32(10, 0, 1, 1);
      uint32_t dns = cc3000.IP2U32(10, 0, 1, 1);
      if (!cc3000.setStaticIPAddress(ipAddress, netMask, defaultGateway, dns)) {
        Serial.println(F("Failed to set static IP!"));
        while(1);
      }
      */

      /*
      if (!cc3000.setDHCP()) {
        Serial.println(F("Failed to set DHCP!"));
        while(1);
      }*/

      // Connect to  WiFi network
      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }
      Serial.println("Connected to WiFi network!");

      // Check DHCP
      Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP())
      {
        delay(100);
      }

    }

    void loop(void)
    {

      // Measure the temperature
      int sensorValue = analogRead(A4);
      float milliVoltsValue = sensorValue * 5000. / 1024.;
      float temperature = (milliVoltsValue - 500.) / 10.;

      // Print the result
      Serial.println(temperature);

      // Transform to string
      char temp[5];
      dtostrf(temperature, 5, 2, temp);

      // Send request
      String request = "GET " + repository + "sensor.php?temp=" + String(temp) + " HTTP/1.0";
      send_request(request);

      // Update every second
      delay(1000);
    }

    // Function to send a TCP request and get the result as a string
    void send_request (String request) {

      // Connect
      Serial.println("Starting connection to server...");
      Adafruit_CC3000_Client client = cc3000.connectTCP(ip, port);

      // Send request
      if (client.connected()) {
        client.println(request);
        client.println(F(""));
        Serial.println("Connected & Data sent");
      }
      else {
        Serial.println(F("Connection failed"));
      }

      while (client.connected()) {
        while (client.available()) {

          // Read answer
          char c = client.read();
        }
      }
      Serial.println("Closing connection");
      Serial.println("");
      client.close();
    }

    void listSSIDResults(void)
    {
      uint32_t index ;
      uint8_t valid , rssi, sec ;
      char ssidname[33];

      if (!cc3000.startSSIDscan(&index)) {
        Serial.println(F("SSID scan failed!"));
        return;
      }

      Serial.print(F("Networks found: ")); Serial.println(index);
      Serial.println(F("================================================"));

      while (index) {
        index--;

        valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

        Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
        Serial.println();
        Serial.print(F("RSSI         : "));
        Serial.println(rssi);
        Serial.print(F("Security Mode: "));
        Serial.println(sec);
        Serial.println();
      }
      Serial.println(F("================================================"));

      cc3000.stopSSIDscan();
    }

    bool displayConnectionDetails(void)
    {
      uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

      if (!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
      {
        Serial.println(F("Unable to retrieve the IP Address!\r\n"));
        return false;
      }
      else
      {
        Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
        Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
        Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
        Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
        Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
        Serial.println();
        return true;
      }
    }

body:
The serial monitor gives you a way to "talk" relatively directly with the Arduino – in this case it give you a way to easily confirm that the basic circuit is working and that you are getting sensible temperatures. That's a foundation on which you can build.

It is unlikely – I think – that the serial monitor is causing the problem. But before you believe me, there is one thing you should consider. The serial monitor runs relatively slowly, so outputting the temperature via the serial monitor introduces a delay in your code. That could explain the difference.

So your next step is to trace your bad value. So, first more questions:

 - What baud rate are you running the serial monitor at? Does changing the baud rate affect the result? That would point to a timing related issue.
 - Is there any code that writes to the serial monitor (e.g., a call to Serial.println())? If there is what happens when you comment it out?
 - Where are you seeing the two values (the correct and incorrect values)? I assume that both are at the web server, but I want to confirm this.
 - Can you explain more clearly the process to demonstrate the problem? In the tutorial that you link to I don't think that the code pathway is the same to see the value on the serial monitor as it is on the server, so I'm wondering if an error was made as you changed the code.


message:
Arduino compiler uploading last saved version of sketch, not current

Is this an issue or a defined behavior? I am using Arduino IDE 1.6.6

Sometimes I made changes in code, and immediately upload them to the Arduino board. And many times issues already fixed are persisting, leaving me that feeling of "the uploaded code has not the changes I have just made". Then I save my sketch, compile and upload again and the issue vanishes. As long as the issue get someway fixed, I tend to forgot about it.

As software engineer, most of the times I assume the code I am compiling and uploading / publishing to any platform is always the latest, not the latest saved. I believe this is not the behavior of the Arduino IDE. It uploads the last saved version of code, not the last modified.

**In summary: I believe the Arduino IDE uploads to the board the last saved version of the sketch, not the current one being modified.** Can anyone confirm this?

Thanks in advance.

body:
I haven't tried it but it would be an easy experiment to make on some throw-away code.

However, do note that saving before compiling or uploading is *optional* in the Arduino IDE. That may very well be the key to what you observed. I keep mine enabled, i.e., to save before any compile or upload. The option is in the Preferences dialog accessed from the menus, not in the manually-edited `preferences.txt` file. That might be the key to what you observed.

Update:
In that case, including the pre-defined macros `__DATE__` and `__TIME__` (of the pre-processor run) and `__TIMESTAMP__` (of the file's last modification) in a "Hello" string can help debug this.

These pages list the [standard][1], and [common][1] predefined macros implemented in gcc's pre-processor.
  [1]: https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html#Standard-Predefined-Macros

Note also that most version control systems offer similar macros that get replaced at checkout to embed a revision number and other version-control information.


message:
Nothing is working even though every thing is right & it is new?

I have bought a new 'SunFounder Arduino uno R3' and started learning, the first lesson was 'Blinking LED' of course.

I have done it all, connected Jumper-Wires and the Sensor and the LED light, I wrote the code:

    const int ledPin = 9;
    void setup()
    {
       pinMode(ledPin,OUTPUT);
    }
    void loop()
    {
       digitalWrite(ledPin,HIGH);
       delay(500);
       digitalWrite(ledPin,LOW);
       delay(500);
    }

BUT NOTHING HAPPENS !!!, I checked out every thing over and over, it just does not work ???
Every thing is well about the board and the UNO R3 it is new.
I have checked the code and the connections and checked the Device Manager to know that the serial port of the arduino is 'COM3'...
I dont know what is wrong with it ?!!

body:
In these cases it helps to break down the problem in pieces.

If the internal LED on pin 13 blinks with your code it means that the software side is OK so far (code, Arduino type, compiling, uploading etc), so I suggest looking at the physical side of things.

Do you have a multimeter available? If so, connect it between pin 13 and ground and it should show you if the output works.

Finally, is the LED working? When you connect it between 5V and GND (with a resistor!) it should light up.


message:
Programing in Assembly for the Digispark

I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

body: There seems to be some specific attiny flag required but by the gcc in order to make the genereated hex file work with digispark. Take a look here https://github.com/pda/digispark-asm.


body:
> I've been given a digispark and am looking to write straight assembly code for it. Anyone know how to get started with this? I've been successful in getting the Arduino IDE set-up but would really like to avoid writing assembly in-line...

The Arduino IDE build support assembly files (.S). Nerd Ralph has written a  [blog][1] on the subject. There you will find all the details and how to write both inline and pure assembly files. He is really god at digging out all the details and sharing his findings.

  [1]: http://nerdralph.blogspot.se/2013/12/writing-avr-assembler-code-with-arduino.html


body:
In 2021, I use VSC + Platformio.

I create a main.asm file in which I put the code from https://github.com/pda/digispark-asm.

In the "platformio.ini" file I define the digispark as :

[platformio]

default_envs = digispark-tiny

[env:digispark-tiny]

platform = atmelavr

board = digispark-tiny

I run the code, upload it to a digispark and this works amazingly well.


message:
Arduino raise the error "variable-sized object 'my2dArray' may not be initialized" while trying to change the elements of 2d array

I' m trying to change 1 to 0 in two-dimensional (5x5 matrix) for specific servo positions.First, i tried to program forward movement of my robot.  My code is like this:

<!-- language: c -->

    #include <Servo.h>
    #define x 5
    #define y 5

    Servo myServo;
    Servo myServo2;

    int pos = 0;

    int counter1;
    int counter2;
    int integer;

    void setup() {
      Serial.begin(9600);
      myServo.attach(9);
      myServo2.attach(10);
    }

    void loop() {

      int my2dArray[x][y]= {
      {1,1,1,1,1},
      {1,1,1,1,1},
      {1,1,0,1,1},
      {1,1,1,1,1},
      {1,1,1,1,1},
      };

      int robot = my2dArray[2][2];

       if (counter1 > 0){
         for (integer = 0;  integer <2; integer +=1){
          int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

         }
     }
    }

      int moveForward(){
      for (pos = 0; pos <= 360; pos += 1) {
        myServo.write(pos);
        myServo2.write(pos);
        delay(15);
        if (pos == 360){
        counter1 += 1;
        }
        return counter1;
    }
    }

    int moveBackward(){
      for (pos = 360; pos <=0; pos -= 1) {
        myServo.write(pos);
        myServo2.write(pos);
        delay(15);
        if (pos == 360){
        counter2 += 1;
        }
        return counter2;
    }
    }

But i can' t change the [3][2] and [4][2] elements from 1 to 0. I get an error:

     error: variable-sized object 'my2dArray' may not be initialized

Can you help me?
Thanks.

body:
The error is in this line:

      int my2dArray[2 + integer][2] = robot * my2dArray[2 + integer][2];

The presence of the word `int` there tells it to try and make a new variable. You don't want to do that, since it's an error.  Lose the `int` and it might work.


message:
Trouble when avoiding delays

I am new to Arduino and I am learning how to avoid using delay.

I have written some code to move my servo by 20° using delays, but can only move the servo once with my current code. In `setup()`, I assign the servo 150. The next value the servo receives is 15, which it performs. It does not iterate through the following values though. I have been using this guide, [BlinkWithoutDelay][1], with no luck.

Here is my code:

    #include <Servo.h>
    Servo myservo;
    unsigned long previousMillis = 0;
    const long interval = 1000;

        void setup() {
           myservo.attach(9);
           myservo.write(150);
        }

       void loop() {
           unsigned long currentMillis = millis();

           if (currentMillis - previousMillis >= interval) {
                previousMillis = currentMillis;
                myservo.write(15);
           }
           if (currentMillis - previousMillis >= interval) {
                previousMillis = currentMillis;
                myservo.write(35);
           }
           if (currentMillis - previousMillis >= interval) {
                previousMillis = currentMillis;
                myservo.write(65);
       }

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

body:
You are resetting the timer on the first phase [`write(15)`] instead of *after* the last phase [after `write(65)`]! The `previousMillis = currentMillis` should be only after the last phase, before the loop repeats. Not only that, but the time at which each phase executes needs to be different. Currently every `if()` statement is set to run after *interval* has elapsed. If, for example, you wanted *interval* to be the delay between each phase, you could use *interval\*1* on the first phase, *interval\*2* on the second, and *interval\*3* on the third. For example:

       if (currentMillis - previousMillis <= interval * 1) {
            // Runs from interval*0 to interval*1;
            myservo.write(15);
       }
       else if (currentMillis - previousMillis <= interval * 2) {
            // Runs from interval*1 to interval*2;
            myservo.write(35);
       }
       else if (currentMillis - previousMillis <= interval * 3) {
            // Runs from interval*2 to interval*3;
            myservo.write(65);
       }
       else {
            // Runs once after interval*3;
            // *or* runs on first iteration when previousMillis is zero;
            previousMillis = currentMillis;// Reset the loop;
       }

To put the above logic in English:

1. `write(15)` while time is between 0 and 1 intervals;
2. `write(35)` while time is between 1 and 2 intervals;
3. `write(65)` while time is between 2 and 3 intervals;
4. reset the loop once time reaches 3+ intervals.

Note the use of `else if` instead of simply `if` on consecutive statements. This prevents more than one code block from running on the same iteration of the `loop()`.

Edit: I highly recommend having a small delay (like 1ms) somewhere in the `loop()`, such as at the end. It would be a bad idea to constantly run the `write()` function when the value is the same as on the last call.

On the other hand, if your starting value is indeed 150 and the loop should start only after interval*1, you may want to iterate from interval*2 through interval*4:

       if (currentMillis - previousMillis <= interval * 1) {
            // Runs from interval*0 to interval*1;
            // Do nothing; servo is set to either 150 or 65 during this time;
       }
       else if (currentMillis - previousMillis <= interval * 2) {
            // Runs from interval*1 to interval*2;
            myservo.write(15);
       }
       else if (currentMillis - previousMillis <= interval * 3) {
            // Runs from interval*2 to interval*3;
            myservo.write(35);
       }
       else if (currentMillis - previousMillis <= interval * 4) {
            // Runs from interval*3 to interval*4;
            myservo.write(65);
       }
       else {
            // Runs once after interval*4;
            // *or* runs on first iteration when previousMillis is zero;
            previousMillis = currentMillis;// Reset the loop;
       }


body:
If you want to change the servo every second, try to use a conditional expression in the timing structure. If you want to use more parallel structure with multiple intervals use different counters (example see: [here]).

Here is an example of the every second version:

<!-- language: c -->

    #include <Servo.h>
    Servo myservo;
    unsigned long previousMillis = 0;
    const long interval = 1000;
    int angle = 150;

    void setup() {
       myservo.attach(9);
       myservo.write(angle);
    }

    void loop() {
        unsigned long currentMillis = millis();

        if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;

            switch (angle) {
                case 150:
                case 65:
                  angle = 15;
                  myservo.write(angle);
                  break;
                case 15:
                  angle = 35;
                  myservo.write(angle);
                  break;
                case 35:
                  angle = 65;
                  myservo.write(angle);
                  break;
            }
        }
    }

**EDIT:** Add variable assignment `angle` in conditional expression.

[here]:https://stackoverflow.com/questions/32037217/how-can-i-replace-delay-by-millis/32043899#32043899


message:
Menu system without libraries

I was wondering if there are a way to do a menu system for arduino UNO using buttons and without libraries.

I tried to do it by myself but the code was too long and heavy.

I don't want full code, just a pseudo-code idea and how does it works.

I know there are libraries that to this, but I want to practise C++.

Thanks!

body:
Interactive menus are certainly not a "simple" task. That is why people use libraries.

Whatever you try you will end up with complex code - either long winded with lots of duplication, or somewhat cryptic with lots of pointers, arrays, and structures. Not an easy task for a beginner in C++.

How I would set about it would involve the following things:

1. A structure that defines a menu entry, including pointers to one of: sub-menu array, numeric variable (including max/min limits), option array, function to execute.
2. Arrays of the above structure to define each menu
3. Array or linked list of "breadcrumbs" through the menu to track where you are and go back up properly
4. Functions to display and navigate the menu arrays on an LCD.

All of that uses fairly advanced C coding techniques, especially when it comes to managing all the pointers, etc.

The "simpler", though more long winded way, would be to write individual functions for each menu and sub-menu, but that would make your program incredibly long and prone to have errors when duplicating (copy/paste) code.


message:
Which Bluetooth Module can I use with Arduino Micro/Mini?

I need to use a Bluetooth module with an Arduino Micro/Mini.

Please suggest which one would be the best, HC 05/06, or any other?

body:
Do you require slaves or masters?

Both modules are actually the same, it is just the firmware that is different, and in turn that changes how they use the pins. HC05 can be both Master and Slave, and has a full set of AT commands, whereas HC06 can only be a slave, and has a more limited set of AT commands at its disposal.

Otherwise, for low power projects, then BLE modules, such as HC-10 or HC-11 might be worth considering.

Really, it all depends on what you want to do with them, what is the overall project? You could get away with one HC-05 and one HC-06, but it is really task dependant. It is probably worth you having a read up of some articles on the web, and looking at some example projects to see other people's configurations. This will hopefully help you to see what you actually require for your project.

FWIW, I looked into this a few months back and wrote a short blog, [BlueMoon][1], on it, which contains some example projects and links to video tutorials - this may help give you an insight...

  [1]: https://gr33nonline.wordpress.com/2015/08/13/blue-moon/


body:
I have had good results using the [Bluefruit LE UART Friend][1] module from Adafruit with a 32u4 micro Arduino type module, there are only a few pins to connect up to get things going (do remember to follow the instructions to pull the CTS pin to ground).

As per the previous answer it really does depend on what you want to do with it - but this module does Low Energy, can be configured as a "Beacon" and there is a companion App for Android/iOS.

  [1]: https://www.adafruit.com/products/2479


message:
Explanation for micros function

I was trying to understand the working of micros() function internally and I had a look at the function in Arduino.h

This is the code:

    unsigned long micros() {
        unsigned long m;
        uint8_t oldSREG = SREG, t;

        cli();
        m = timer0_overflow_count;
     #if defined(TCNT0)
        t = TCNT0;
     #elif defined(TCNT0L)
        t = TCNT0L;
    #else
        #error TIMER 0 not defined
    #endif

    #ifdef TIFR0
            if ((TIFR0 & _BV(TOV0)) && (t & 255))
            m++;
    #else
            if ((TIFR & _BV(TOV0)) && (t & 255))
            m++;
    #endif

        SREG = oldSREG;

        return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
    }
Can someone please explain me what this line is doing :

      if ((TIFR0 & _BV(TOV0)) && (t & 255))
       m++;

body:
If the timer 0 has overflowed (`TIFR0 & _BV(TOV0)`) and there is at least a count of 1 in the timer count register (`t & 255`) then increment the local copy of the overflow count.

That overflow count is used later on to add an upper 8 bits to what is basically an 8 bit counter to turn it into a 16 bit one (`(m << 8) + t`).


body: Since at the start of this function interrupts have been disabled by the `cli()` function it is possible that the timer `TCNT0` has overflowed yet this *event* has not been processed and included in the value of `timer0_overflow_count` that has been read into `m`. Therefore the line that you are asking about is checking for this condition and incrementing the local copy `m` if necessary before using it to calculate the number of microseconds since startup.


message:
LCD does not work with if condition

#include <LiquidCrystal.h>
    #include <Wire.h>

    LiquidCrystal lcd(2, 3, 4, 5, 11, 12);// initialize the library with the numbers of the interface pins

    int pirPin = 7; //Variable that will receive the digital signal from the sensor
    int LEDgreen = 6; //LED addressed to the digital pin 6
    int speaker = 8; //speaker addressed to the digital pin 7
    int buttonPin = 9; // the pin that the pushbutton is attached to

    void setup(){
      pinMode(buttonPin, INPUT);// Initialize the button pin as an input:
      pinMode(pirPin, INPUT);  // declares variable pirPin as an input
      pinMode(LEDgreen, OUTPUT); // declares variable LEDgreen as an output
      pinMode(speaker, OUTPUT); // declares variable speaker as an output
      lcd.begin(16, 2);
      // turn on the cursor:
      lcd.cursor();
      Serial.begin(9600);
    }

    void loop(){
      int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
      int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
      if(buttonState == LOW){
        if(digitalRead(pirPin) == LOW){
          /*The LED Blinks once with the command digitalWrite
          the LED keeps turned on after blink during the motion cycle*/
          digitalWrite(LEDgreen, HIGH);
          delay(1000);
          digitalWrite(LEDgreen, LOW);
          delay(500);
          digitalWrite(LEDgreen, HIGH);
          /*speaker plays frequency, the number 7 is the digital pin,
          the second number is the frequency played and the third number is the sound duration
          we repeated this command with different frequency and varying the time in order to create a
          pleasant sound */
          tone(4,261,300);
          delay(200);
          tone(4,329,300);
          delay(200);
          tone(4,392,600);
          delay(200);
          tone(4,329,300);
          delay(200);
          tone(4,392,300);
          delay(200);
          tone(4,493,600);
          delay(200);
          tone(4,392,300);
          delay(200);
          tone(4,493,300);
          delay(200);
          tone(4,294,600);
          delay(200);
          lcd.setCursor(0,0);
          lcd.print("  Motion  ");  // Print a message to the LCD.
          lcd.setCursor(0,1);
          lcd.print(" Detected ");
        } else if(digitalRead(pirPin) ==  HIGH) {
           digitalWrite(LEDgreen, LOW); // Turn off the LED in the case where no motion is detected
           lcd.setCursor(0,0);
           lcd.print("No Motion  ");
           lcd.setCursor(0,1);
           lcd.print(" Detected ");
         }
       } else if(buttonState == HIGH) {
         if(digitalRead(pirPin) == LOW) {
           digitalWrite(LEDgreen, HIGH);
           delay(1000);
           digitalWrite(LEDgreen, LOW);
           delay(500);
           digitalWrite(LEDgreen, HIGH);
           tone(4,261,300);
           delay(200);
           tone(4,329,300);
           delay(200);
           tone(4,392,600);
           delay(200);
           tone(4,329,300);
           delay(200);
           tone(4,392,300);
           delay(200);
           tone(4,493,600);
           delay(200);
           tone(4,392,300);
           lcd.setCursor(0,0);
           lcd.print("  Motion  ");
           lcd.setCursor(0,1);
           lcd.print(" Detected & door ");
         } else if(digitalRead(pirPin) ==  HIGH) {
           digitalWrite(LEDgreen, LOW);
           // Turn off the LED in the case where no motion is detected
           tone(4,329,300);
           delay(200);
           tone(4,392,300);
           delay(200);
           tone(4,493,600);
           delay(200);
           tone(4,392,300);
           lcd.setCursor(0,0);
           lcd.print("No Motion  ");
           lcd.setCursor(0,1);
           lcd.print(" Detected but door ");
         }
       }
       delay(2000); // wait for 1 seconds before compare again
     }

body:
This is a summary of your basic loop logic:

    void loop() {
      int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
      int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
      if (buttonState == LOW) {
        if (digitalRead(pirPin) == LOW) {
            // buttonState is LOW
            // pirPin is recently read as LOW
            // ... Motion Detected ...
        }
        else if (digitalRead(pirPin) ==  HIGH) {
            // buttonState is LOW
            // pirPin is recently read as HIGH
            // ... No Motion Detected ...
        }
      }
      else if (buttonState == HIGH) {
        if (digitalRead(pirPin) == LOW) {
            // buttonState is HIGH
            // pirPin is recently read as LOW
            // ... Motion Detected & Door ...
        }
        else if (digitalRead(pirPin) ==  HIGH) {
            // buttonState is HIGH
            // pirPin is recently read as HIGH
            // ... No Motion Detected but Door ...
        }
      }
      delay(2000); // wait for 1 seconds before compare again
    }

However, this is bad code:

    if (digitalRead(pirPin) == LOW) {
        // ... Motion Detected ...
    }
    else if (digitalRead(pirPin) ==  HIGH) {
        // ... No Motion Detected ...
    }

because each time the digitalRead(..) function is called, it can give a different value. So even though your intention is clear, this code won't work the way you expect. Consider what happens if the first digitalRead(pirPin) is high, so digitalRead(pirPin)==LOW is false, but then the second digitalRead(pirPin) is low, so digitalRead(pirPin)==HIGH is also false. Then neither block of code runs. Instead, use:

    if (digitalRead(pirPin) == LOW) {
        // ... Motion Detected ...
    }
    else {
        // ... No Motion Detected ...
    }

Or since you already sampled it at the start of the loop with `int pirVal = digitalRead(pirPin);`, simplify the logic as:

    void loop() {
      int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
      int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal

      if (buttonState == LOW) {
        if (pirVal == LOW) {
            // buttonState is LOW
            // pirPin is LOW
            // ... Motion Detected ...
        }
        else {
            // buttonState is LOW
            // pirPin is HIGH
            // ... No Motion Detected ...
        }
      }
      else {
        // buttonState is HIGH
        if (pirVal == LOW) {
            // buttonState is HIGH
            // pirPin is LOW
            // ... Motion Detected & Door ...
        }
        else {
            // buttonState is HIGH
            // pirPin is HIGH
            // ... No Motion Detected but Door ...
        }
      }
      delay(2000); // wait for 1 seconds before compare again
    }

By the way, if you're using the Arduino IDE, you can easily clean up the indentation to make these control structures easier to see, by using Tools | Auto Format.


message:
What is the memory expense of creating a String from a char array?

I'm writing a little API for processing email messages in Arduinos. Obviously, I need to keep memory use down, but I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

My logic uses char arrays (so that memory is statically allocated). If my end user converts a char array to a String (so that they can easily see if an email subject startsWith() a particular word) will this result in doubling the character memory used? .. or will the String class simply include a pointer to the original char array (and just add some cruft)?

What would be the best-practice in this kind of situation?

body:
> What would be the best-practice in this kind of situation?

To not use `String`.

> I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

There's nothing wrong with providing an `indexOf` function in your API.  But you don't have to use `String` to implement that function when called.  You can just use the `strstr` function on char arrays (reference [here](http://www.cplusplus.com/reference/cstring/strstr/)).

I should also point out that most Arduinos do not have enough RAM for storing an email.

### UPDATE 07-01-2016:
To answer the titular question, the fixed cost of using `String` is at least 1600 bytes of program space, more if you use more than a few methods.  The linker can throw out methods you don't use.

Then for each `String` variable you declare, the recurring cost is 8 bytes for the variable itself, plus the variable-size memory chunk for your character data.  This chunk is allocated from the heap, and is the size of your string plus 4 more bytes to manage the chunk within the heap.  That's a total of 12 extra bytes per `String` instance.

However, I did not originally answer that question because you explicitly asked about the *memory* expense.  This ignores other expenses that should not be ignored:

* execution time - Allocating memory from the heap is really a search for a chunk of the requested size.  At the beginning it can be quick, but as the heap gets fragmented (small chunks build up) it takes longer to find a chunk.  And when the `String` is emptied or destroyed, the memory chunk gets put back into the heap and (possibly) merged with adjacent chunks.  Reducing the size of a `String` does not free up any memory.  The `String` maintains its maximum size until it is emptied or destroyed.
* long-term stability - Embedded Systems are supposed run *forever*.  A primary characteristic of a system that can run forever is "deterministic."  For whatever inputs it receives, it has a predictable response and end state.  When you use the heap via `String`, the heap gets fragmented according to the data it handles.  This is not predictable, and it may get into a state where no memory chunk of the requested size is available.  Choke.
* maintenance - because the heap state depends on the processed `String` data, finding the cause of the failure can be difficult.  It can fail at different times because the input data is different, and it can fail at different places in the program.

Because of *these* expenses, `String` is rarely used by an experienced developer.  Unfortunately, `String` is tempting to the beginner because it is easy to understand.  What is difficult to understand is the complicated, non-deterministic behaviour under the hood that **inevitably** leads to system failure, rending of garments and gnashing of teeth.


body:
[I'm a year late but this or a related question gets asked often enough, I think it's worth another answer.]

With a Mega, there's enough memory to *consider* doing what you propose ***if*** we make some assumptions and modifications:

1. We know or can accept a maximum size of a string, above which, memory allocation will fail, detectably (the allocator returns a NULL pointer and the object handles the failure gracefully);

2. We use a non-fragmenting allocation method - statically allocated buffer pools of one or more fixed sizes - that are allocated and returned intact. No splitting or merging will take place. A given request will be filled with a buffer of the requested size or larger, if one is available.

3. Either the String object is modified to only use the new allocator or the system '_new()_' is replaced by it.

The obvious disadvantages are:

 - The entire heap will not be eaten up by a fragmented memory pool. ("Heap" is that space between the statically allocated memory and dynamically growing and shrinking stack. When the stack and heap meet, your application fails).
 - You'll need to know something about your application's memory needs to plan the buffer pools.
 - You'll have to plan to prevent or handle allocation failure.

In exchange, you get:

 - The allocator won't crash your system.
 - The String object's programming advantages become available.
 - You'll write better code since you had to think about and plan for its needs rather than let a dumb and fragmenting allocator blindly consume the heap.


message:
Arduino Yún shield password reset

I'm using a Yún shield from Dragino with an Arduino Uno, but the default wifi password for the shield (which should be "dragino") isn't working.

I tried the wifi reset (holding down the reset button for 5 seconds) and a factory reset (holding down the reset button for 30 seconds) but the password still seems to be incorrect.

Is there any way I can reset the password?

body:
Try connecting via ethernet to 192.168.255.1 with root/root

The SSH access for Dragrove is:
IP: 192.168.255.1 on LAN port. If you want to connect to the Dragrove via WiFi, the IP should be 192.168.1.108.
Username: root
Password: root

http://www.seeedstudio.com/wiki/Dragrove_-_Generic_gateway_for_internet_of_things