message:
Linking Arduino Nano with ESP8266 Wifi module

I recently started playing around with Arduinos to connect a few sensors up. I used an Arduino Nano to measure temperature, humidity, air pressure and light level.

To store the data in a database, I used another Arduino that I connected to a Raspberry Pi, and let the two Arduinos talk wirelessly to each other via 433 MHz.

That all works pretty well, but the 433 MHz communication is not exactly the most reliable (I often miss a transmission). When I stumbled upon the ESP8266 module, it seemed like the optimal solution for communication. How cool would it be if I could just pull out the information via an HTTP call from the Raspberry Pi?

After toying around for many hours, uploading many different firmwares, getting more and more frustrated because I could not get it to do anything, I finally have it working through an FTDI module connected up like this:

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

I use an MB102 power module to provide the 3.3v required by the ESP8266. I turns out you need to connect the ground from the MB102 to the ground of the FTDI module to get any proper response. After doing that I was able to send AT commands and get the proper responses. I could even connect it to my home Wifi.

The next thing I want to do is connect it to the Arduino. I found a very simple schema for that (http://blog.huntgang.com/2015/01/20/arduino-esp8266-tutorial-web-server-monitor-example/), where you connect RX to TX and TX to RX. Using the MB102 I connected it like this:

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

Apparently I should now be able to upload a blank sketch to the Arduino, and then use the serial monitor again to sens AT command, exactly the same way I did it when using the FTDI module.

The problem is that I get nothing at all this way. I don't even see my own AT commands in the console. I do see the ESP8266 flashing every time I send a command (I even see it it still connected to my router, probably it remembered the info I send through the FTDI...?)

The question is, what am I going wrong? I read some posts about the TX from the Arduino also being 5v and that you need to do something to bring it back to 3.3v, but there are also many tutorials that say it's not required.

  [1]: https://i.stack.imgur.com/9mjhX.png
  [2]: https://i.stack.imgur.com/aLzdG.png

body:
There might be an issue with the baudrate from the Nano FTDI chip to the RX/TX and the ESP8266. Did you disconnect when uploading the sketch?

How about trying [this][1] instead?

Cheers!

  [1]: http://blog.huntgang.com/2015/01/20/arduino-esp8266-tutorial-web-server-monitor-example/


sender: user

sender: assistant

body:
Stumbled on good tutorial here, tried and it does the job:
https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/


body:
Yes, if you are using different power sources the grounds always have to be connected, otherwise the boards don't know what zero volts is.

The TX of the Arduino is 5v, you need a level shifter to convert 5v to 3.3v, something like this (https://shop.pimoroni.com/products/adafruit-4-channel-i2c-safe-bi-directional-logic-level-converter?utm_medium=cpc&utm_source=googlepla&variant=302017581&gclid=CPqujsPxlc0CFcYcGwodb8YIoA)

The TX of the ESP8266 is 3.3v and the RX of the Arduino is 5V and you will need a level shifter to handle this.  You can use the same one as listed above, because it can convert 4 high (5v) signals into 4 low (3.3v) signals.

People say you can so it with resistors, but I have also read that they don't perform well enough to handle fast switching digital signals (so 300 Baud on your serial might be OK, but not 115000 :) )

People also say you don't need level convertors.  That's true things _might_ work for a while without them, but sooner or later something will go pop.  Increasing the voltage will speed up the process so you can imagine what will happen if you connected a 230v supply directly to a USB device.

One final point, do you know the ESP8266 is a 80/160MHz processor with 256KB of RAM, when you compare that to you Arduino its like programming you PC via your phone.  What you could try is connecting the ESP8266 via a FTDI module and program it via the Arduino IDE in Arduino C.  Its a lot easier than all this connection stuff.


body:
The easiest way to work with these devuces is to connect them to a spare pair of Arduino pins and use SoftwareSerial for communicating (unless you're using one of the Arduinos with more than one UART). SoftwareSerial work up to 9600 baud on 16MHz devices, 4800 on 8MHz devices, so you'll need to set the ESP8266 to accommodate that. They currently ship at 115200 baud. You can use the hardware UART on pins (0, 1) but then re-programming the Arduino means disconnecting & reconnecting the ESP temporarily each time, and gets old pretty quickly.

Here's what I do with new ESPs (If you've re-flashed your ESP, you'll need to download the AT instruction-set emulator and re-flash it with that, first):

    # To configure a new ESP module:
    # Connect the ESP and the FTDI as in your top diagram, set your
    # terminal-emulator to 115200 baud, and enter the following:

    AT                             # ESP should respond "OK"
    AT+RST                         # Resets the ESP
    AT+UART_DEF=9600,8,1,0,0       # Sets ESP UART: 9600,N,8,1,no flow ctl

    # Now change the terminal emulator baud rate to 9600

    AT+CWMODE=1                    # Set ESP to station mode (client)
    ATE0                           # Set ESP's echo off
    AT+CWLAP                       # List access points - after a short pause
                                   # the ESP returns a list of WiFi access points

For future reference, here is a link to the [ESP8266 AT Instruction Set][1].

Update June 2020: The above link was broken, now fixed. You can also find documentation at [Espressif's github account][2] (online readable, but not pdf, as of this date).

  [1]: https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf
  [2]: https://github.com/espressif/esp-at/tree/master/docs


message:
How to learn electronics/programming with Arduino?

I want to learn core and mechanics of microcontrollers with Arduino, and I don't really know where to find good source of knowledge.

Every Arduino related tutorial is about very basic stuff like connecting the LCD display without explaining what every pin does. When it comes to programming tutorials only explain what functions are needed and do not explain what happens inside the hardware.

For example i know what delay() function does, and I know that I can find definition in the source files:

    void delay(unsigned long ms)
    {
     uint16_t start = (uint16_t)micros();

     while (ms > 0) {
      yield();
      if (((uint16_t)micros() - start) >= 1000) {
       ms--;
       start += 1000;
      }
     }
    }

But what I really want to know what that code does, and how to write own functions. I would appreciate if you could provide me with any starting point. Should I just follow the source files until I get it or is there any better reference?

I have Arduino Leonardo, and experience in programming in C/C++.

body:
There are two main topics there: Digital Electronics, and C++ programming, and the Arduino happens to bridge the gap between the two.

That's why it's hard to find tutorials in the style you want.  So instead of looking for Arduino tutorials that do what you want you need to split the topics apart and deal with them separately.

Search for C++ programming tutorials. That should help you understand the structure and syntax of a program better. Search for digital electronics tutorials. Good keywords are things like *logic gates*, *combinational logic* or *digital interfacing* and just *digital electronics*. That should help you understand things like logic levels, logical functions, inputs and outputs, and such like.

Once you have basic understanding in both fields you can begin to see how the two relate together. One of the most important skills any engineer has is understanding and interpreting datasheets. From datasheets you can find how the hardware operates and what you would need your program to do to make the hardware do what you want.


body:
For information about the “core and mechanics of microcontrollers with Arduino”, there are numerous articles with lots of details on the [arduino.cc](http://forum.arduino.cc/) forum.  However, most of the code posted there sucks, as does most of the code posted here on [Arduino Stackexchange](http://arduino.stackexchange.com).  That's a natural consequence of people posting code that doesn't work and they wonder why.

For a reasonably organized and accurate body of information about Arduino hardware and software, see [Nick Gammon's Arduino pages](http://www.gammon.com.au/forum/index.php?bbtopic_id=123).  Also see [arduino.land](https://arduino.land/FAQ/showcat.html) pages.  For better understanding of Arduino software internals, see [garretlab's “Internal Structure of Arduino Software”](http://garretlab.web.fc2.com/en/arduino/inside/index.html) pages, which are well organized and quite informative about the subjects they cover.

Regarding the specific `delay()` code shown in the question, first consider this slightly simpler version, from Arduino 1.6.3:

    void delay(unsigned long ms) {
        uint16_t start = (uint16_t)micros();
        while (ms > 0) {
            if (((uint16_t)micros() - start) >= 1000) {
                ms--;
                start += 1000;
            }
        }
    }

Ignoring data type constraints, it's evident that the `while` loop counts down `ms` from its original value to zero.  The burden of the `if` executes about once per millisecond, because `start` advances 1000 microseconds each time within the `if`.

The casts of `micros()` – ie, where `uint16_t` appears in parentheses before `micros()` – tell the compiler to throw away the upper two bytes of `micros()` [which is actually an unsigned long, or [`uint32_t`](http://www.cplusplus.com/reference/cstdint/)] and treat it as an unsigned 16-bit integer.  The low two bytes of `micros()` overflow every 65536 microseconds, on which occasions within a millisecond it will come to pass that although `(uint16_t)micros()` is less than `start`, due to use of unsigned arithmetic `((uint16_t)micros() - start) >= 1000`.

The code you included has one more statement in the `while` loop:

        yield();

For most models of Arduino, `yield()` is an empty function, a do-nothing if compiled at all.  On the Due, with [`Scheduler.h`](https://www.arduino.cc/en/Reference/Scheduler) in use to support cooperative (non-preemptive) multitasking using multiple stacks, `yield()` gives the scheduler an opportunity to schedule another task, if one is ready to run.  Note that if a  “cooperative” but malignant task always takes just under 65536 microseconds to do its work, it can happen that `delay()` as shown never returns.


message:
nRF24L01 Problem

I'm trying to code a simple transmitter - Receiver program with nRF24L01

Very simple code. Compiles. But when I try to test it using serial monitor. But only the first character is printed on the screen just once.

<!-- language: c -->

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    #define CE_PIN 9
    #define CSN_PIN 10

    const uint64_t pipe = 0xE8E8F0F0E1LL;

    RF24 radio(CE_PIN, CSN_PIN);

    int smth[1];  // the transmitter data
    int x=0;  // the copy of the receiver data
    char rec[1]; //the receiver data

    int ledPin = 3; // choose the pin for the LED
    int inPin = 7;   // choose the input pin (for a pushbutton)
    int val = 0;     // variable for reading the pin status

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  // declare LED as output
      pinMode(inPin, INPUT);    // declare pushbutton as input

      radio.begin();
      radio.openWritingPipe(pipe);  //originally transmitter
    }

    void loop(){
      val = digitalRead(inPin);  // read input value
      if (val==HIGH) {         // check if the input is HIGH (button released)
        digitalWrite(ledPin, HIGH);  // turn LED OFF
        Serial.println('1');
        smth[0] = '1';
        radio.write(smth, sizeof(smth));
      } else {
        digitalWrite(ledPin, LOW);  // turn LED ON
        Serial.println('0');
        smth[0] = '0';
        radio.write(smth, sizeof(smth));
      }
    }

----------

Serial Monitor :

0

----------

Instead of printing a zeros for infinite time till I change the mode of the switch, even though if I change the mode of the switch from low to high, nothing is printed on the screen.

I'm using Library for instance [http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01][1]

Any help?

  [1]: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01

body: A quick look at the library header files shows you should call `radio.stopListening()` before calling `radio.write()` for the module to switch to transmit mode. This could be what is blocking the `radio.write` in the else block. I also recommend you try a `byte` array first, to get things working, just in case `int`s are the issue.


body:
Completing TisteAndii reply I suggest to have a look at init. According to the RF24 classe list, it seems radio.begin(); and radio.openWritingPipe(pipe); are "void" function.
I personnaly use NRFLite from Dave Parson and his lib send a return value for his _radio.init function.
That's interesting because a lot of lib have a "send feature" which don't return until the receiver replied. So if you turn on your nRF and send data while the receiver is OFF, you're blocked. With a test at init, you can check that and loop until the receiver is available.

Note: I let my answer, but that's not the good one. As indicate in the coment, the init function dont tell if the receiver is avaible, but only if the nRF is connected (your nRF, so not the other one).


message:
ATTINYx5 usi for uart?

Can the ATTINYx5 use its universal serial interface for a better UART than the Sofware Serial library alone? If so, is there a library or tutorial for this?

body: AVR307 describes implementation of a half duplex UART implementation using the USI. Note that full duplex is not possible due to the synchronous design of the USI.


message:
ESP8266 Returns 'invalid' - Cause 4

I have tried to get the Ai-Thinker ESP8266 working at all. If you hook it up to an Uno you have garbage returned no matter what the baud rate is. Tried softwareSerial on D3 and D4 (switching pins doesn't help) and over D0 and D1 with no sketch (to send AT commands directly to the device because softwareSerial wasn't working).

I'm using a logic converter from 5v to 3.3v to handle the voltage correctly.

I also know for a fact you can do that. I've done it a bunch with Bluetooth. HC-05.

NOTE: Pins in the wrong order won't return anything, in order to get garbage it needs to be wired correctly.

I also have a FTDI module that functions as another passthrough unit for this. It has a jumper for 3.3v to 5v and will stay on 3.3v as these units are unable to handle 5v.

I used PuTTY in order to view the boot information of this chip. On boot it returns this information.

So here's my issue.

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

    wdt reset
    load 0x40100000, len 816, room 16
    tail 0
    chksum 0x8d
    load 0x3ffe8000, len 788, room 8
    tail 12
    chksum 0xcf
    ho 0 tail 12 room 4
    load 0x3ffe8314, len 288, room 12
    tail 4
    chksum 0xcf
    csum 0xcf

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

    sd▒C▒
    Ai-Thinker Technology Co. Ltd.

    invalid

At the end of the day this invalid line means that the wifi information (from what I understand) is corrupted. It also refreshes this information over and over and WILL NOT accept AT commands so I can't seem to chase it down.

I am afraid that by attempting to update it if this kind of issue happens it will be bricked.

Both of these modules are opened today and I have tested another 8266 with similar results.

Any help would be appreciated.

body:
Alright so I figured it out. Thanks to user Butters for pointing me in the right direction.

The Arduino Uno DOES NOT have enough power to handle the ESP8266 itself. It needs a power source using a 5v to 3v stepdown chip. The 3v3 rail doesn't handle it by itself.


message:
How to prevent inclusion of unnecessary libraries?

How do you save space by preventing the inclusion of unnecessary binaries?

When I compiled the [ROS Blink](http://wiki.ros.org/rosserial_arduino/Tutorials/Blink) example, I received the warning:

    Global variables use 1,951 bytes (76%) of dynamic memory,
    leaving 609 bytes for local variables. Maxiumum is 2,560 bytes.
    Low memory available, stability problems may occur.

Considering the example uses almost no libraries, I was surprised by this, but sure enough, the compiler pulls in a ton of libraries that are never used:

    Scanning dependencies of src
    Scanning dependencies of arduino
    Scanning dependencies of ros_lib
    src/main.cpp
    arduino/wiring.c
    arduino/wiring_shift.c
    arduino/wiring_digital.c
    arduino/wiring_pulse.c
    arduino/WInterrupts.c
    arduino/hooks.c
    arduino/wiring_analog.c
    arduino/USBCore.cpp
    arduino/new.cpp
    arduino/Tone.cpp
    arduino/WString.cpp
    arduino/HardwareSerial1.cpp
    arduino/Stream.cpp
    arduino/HardwareSerial3.cpp
    arduino/HardwareSerial0.cpp
    arduino/CDC.cpp
    arduino/HardwareSerial2.cpp
    arduino/main.cpp
    arduino/HID.cpp
    arduino/HardwareSerial.cpp
    arduino/IPAddress.cpp
    arduino/Print.cpp
    arduino/WMath.cpp
    arduino/abi.cpp
    Linking libarduino.a
    ros_lib/duration.cpp
    ros_lib/time.cpp
    Linking libros_lib.a
    Linking firmware.elf
    Converting to firmware.hex

Why are so many files being included in the compilation, and how do I filter them out?

body:
The [Arduino IDE build][1] script will actually copy all core source code file to the tmp directory, compile and generate an archive file. The sketch is compiled and linked with this library. Only the referenced (used) functions and data are [linked in the binary][2].

The size (both program and data) of this blink is somewhat larger than the "standard" blink example but this is due to the publisher-subscriber run-time.

Cheers!

PS: If you google you can find commands to listing what is actually in the generated binary. [Here][3] is a starting point.

  [1]: https://www.arduino.cc/en/Hacking/BuildProcess
  [2]: http://openhardwareplatform.blogspot.se/2011/03/inside-arduino-build-process.html
  [3]: http://forum.arduino.cc/index.php?topic=155142.0


body:
Part of the compilation process is what is known as *garbage collection*, which is controlled by the compilation flag `-Wl,--gc-sections`

This process goes through the compiled program and works out which sections (functions, blocks of read-only data, etc, each in its own *section* controlled by `-ffunction-sections` and `-fdata-sections` IIRC) and works out which are not needed in your compiled program.  It then deletes them.

The problem you have though is not with code or read-only data size, but with static RAM allocation size.  This is global variables and local static variables - things used for stiring data, maybe as serial buffers, etc.  Most of that is probably part of the underlying RTOS that you have elected to use. Which is the problem of using an RTOS to just blink an LED. It could be seen as a task that is beneath the RTOS and is complete overkill. Of course, since you're just testing, that is pretty irrelevant, however, as you add more functionality you will most likely find that the memory footprint doesn't increase much since it's the "background" stuff that of the RTOS that will always be there regardless of what tasks you are performing.


message:
Problem in RS485 Communication between Arduino and PC

I'm trying to sending and receiving data via RS485 communication. Interfacing Arduino and PC(laptop)
using SN75176 RS485. I wrote a program to send a string "Hello" from arduino via Tx pin. My intention is to receive
the "Hello" string in my PC's hyperterminal. After uploading the program im receiving junk data. The baud rate i've mentioned in
my program and i gave in hyperterminal are same. I've checked the wire connection, it is ok. Then, what is the problem?

Code:

<!-- language: c -->

 #include <SoftwareSerial.h>
 int Txpin = 1;
 int ditpin = 5;  //for 1st rs485
 int ditpin1 = 2; //for 2nd rs485
 void setup()
   {
     // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(Txpin,OUTPUT);
  digitalWrite(ditpin, HIGH); //For transmit data from arduino
  digitalWrite(ditpin1, LOW); //For receive data to hyperterminal
   }

 void loop()
   {
  Serial.println("Hello\r\n");
  delay(1000);
   }

Wire connection:

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

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

body:
You cannot connect from Arduino serial input/output with RS485 circuit and then to the PC RS232 port. You need a TTL to RS232 adapter. For instance an adapter based on [MAX3222][1].

[![MAX3232 circuit diagram][2]][2]

Cheers!

  [1]: http://pdfserv.maximintegrated.com/en/ds/MAX3222-MAX3241.pdf
  [2]: https://i.stack.imgur.com/TPUVf.gif


message:
Convert Long to binary - least signifant bit first

I have found an Arduino function which converts a 2-bytes-`long`-value to a binary value.

e.g. I call `sendCommand(0x05)` And it gives me an output:

`00000101`

    void sendCommand(unsigned long command){
      for (unsigned long  mask = 1UL << (7);  mask;  mask >>= 1) {

        if (command & mask) {

        Serial.print( "1" );
        } else {

        Serial.print( "0" );
        }
      }
    }

my Problem is, that I want to have the Least significant bit first. How do I have to adjust this function to achieve this?

e.g.
`sendCommand(0x05)`
shall give an output:

`10100000`

body:
    void sendCommand(unsigned long command){
      for (unsigned long  mask = 1UL; mask<256UL;  mask <<= 1) {

        if (command & mask) {

        Serial.print( "1" );
        } else {

        Serial.print( "0" );
        }
      }
    }

PS a long is actually 4 bytes long. But your code only uses 1 byte of it.


message:
powering RF on GPIO

I have been running a simple RF link between 2 arduini uno recently and everything went faily well. I am now trying a new project with an arduino mini pro (5V/16MHz) and the seeeduino RF link (@315MHz), and I see very odd results : when the transmitter is on USB cable, the link runs ok, but when on a 9V battery (as raw voltage input), I get very very limiter range (a few inches).

Because the setup works on USB, I'm assuming that the current limitation on the GPIO that powers the RF transmitter is not the issue here. It therefore has to be the battery itself or the regulator.

Somehow I need to use a GPIO to shut down the radio during power saving phases. My current design is very basic, I should probably add a transistor to enable power on the RF. I was also thinking maybe the RD oscilliator needs to settle down a bit, I may need to add some delays before starting to send data. I can see on the oscilloscope that the data and power PINs seem to behave correctly, although I have noticed a voltage drop on the power pin which is similar in pattern to the data transmitted (but again this is no issue unless using the 9V battery).

body:
As established in the comments, the issues here are powering the module directly from a GPIO pin, which are limited to 20 mA, and potentially the limited current of a 9V battery.

Personally I avoid using 9V batteries in projects, as they are comparatively expensive for the lifetime they provide. There are various boost/step-up converters that make a steady 5V supply from two AA batteries.


message:
Is it possible to create a standalone exe which can burn the code into a Teensy 3.1?

So here's the scenario.

I have sent my teensy 3.1 circuit to a client of mine
And now I need to update the code burned onto teensy without providing client access to the code

So is it possible to create an exe or an installer of a kind which on execution simply upload the new code onto the teensy?

Since the code is finally a hex file uploaded onto the controller I hope this must be possible
But on doing a quick google search i was not able to find any valid resource which would guide me how to go about it.

body:
Yes, it is perfectly possible.

You will need three things:

1. The HEX file you want to program
2. The programming utility for your chosen board (would be in the IDE folder somewhere - not sure what Teensy uses off hand)
3. A text editor.

Then, using the text editor, you create a `.BAT` file which executes the programming utility with the right parameters to program the board.

It can help to do an upload in the IDE in verbose mode so you can see exactly what command and parameters are being executed.


body:
Yes.  Teensy has a command line loader available at https://www.pjrc.com/teensy/loader_cli.html or https://github.com/PaulStoffregen/teensy_loader_cli

Given the hex file, the teensy_cli client could upload it without giving your client the source code.  For non-teensy devices, avrdude could be used similarly.

Alternately, one could fork the cli code, modify it to use an embedded copy of your hex file data in a hard-coded or encrypted constant, and then deliver that modified single-purpose executable file to your client.


body:
The simplest solution is to ask you client to install the TeensyLoader application. https://www.pjrc.com/teensy/loader.html

Send the new HEX file to the client. The client should then connect the board to the computer. Run the TeensyLoader and upload the HEX file. The TeensyLoader will recognize the board when the reset button is pushed. The HEX file will need to be located on disk (after download or mail attachment).

Cheers!


message:
Arduino IDE Based Data Logger - Stops Running

I have created a data logger that writes to a MicroSD on a user defined interval.  The data logger also has the ability to use an xBee unit to transmit the data received to a base station.

This is a [link to the code and pictures of the data logger][1].

I use Arduino IDE for prototyping and coding.  After compiling the code, I use the temp HEX file and upload it to the boards using AVR Studio 4.

The problem I am experiencing is the data loggers will stop running after a random number of recordings.  This can be days or weeks of running before the problem is experienced. This issue rarely occurs when the logger is running in local mode, but occurs often when running with an XBee unit.

A temporary fix I have found for the problem is to add `delay(10);` before and after the SD card writes.  I do not know why this fixes the problem and would like to find a more appropriate solution.

  [1]: https://drive.google.com/folderview?id=0B8g6J3lNxKRDa3U5aC02VVppQ3M&usp=sharing

body:
This use of String is dangerous.  You are growing and shrinking the String in a loop and hoping the memory manager prevents any holes from forming:

    void clockResetcheck() {

      char clkset[] = "CLKSET.TXT";
      if  (myFile.open(clkset, O_READ)) {

        uint16_t newYr;
        uint8_t  newDay;
        uint8_t  newMo;
        uint8_t  newHr;
        uint8_t  newMin;
        uint8_t  newSec;
        char data;
        String temp;
        int place = 0;

        while ((data = myFile.read()) > 0) {

        if (data == '/' || data == ':' || data == ',') {
          if (place == 0) {
            newDay = temp.toInt();
            temp = "";
          }
          if (place == 1) {
          newMo = temp.toInt();
          temp = "";
          }
          if (place == 2) {
            newYr = temp.toInt();
            temp = "";
          }
          if (place == 3) {
            newHr = temp.toInt();
            temp = "";
          }
          if (place == 4) {
            newMin = temp.toInt();
            temp = "";
          }
          if (place == 5) {
            newSec = temp.toInt();
            temp = "";
          }
          place++;
          if (place == 6) {
            myFile.close();
            break;
          }
        }
        else {
          temp = temp + data;
        }
      }
    ...

The line

    temp = temp + data

is a danger flag.  This sort of concatenation is going to reallocate the buffer used by String to make it fit the result.  The reallocate will leave behind a hole with the previous smaller string.

String has logic to reuse the buffer if possible.  So if you start big, it should not have to reallocate.  Something like:

    String temp("12345678");  // allocates the buffer at largest needed size
    temp = ""; // clear out

That is a less likely to fragment memory.  You have a few other concatenates in code that are similar danger.

The best advice to long running programs I ever received:

> Stay off the heap.

You are using String inside functions.  That means that buffers are allocated and freed again and again.

A better pattern is to remove **all** the local String's in functions.  Instead use one global String as a temp buffer.

    String g_temp("                        ");
    void function1() {
       g_temp = "";
       g_temp += char
    }
    void functionB() {
       g_temp = "";
       // do stuff with g_temp
    }

With this pattern, the allocate happens once when the program starts.  If the size is setup large enough, if will **never** need to reallocate.  This means your high water mark for memory use is established at the time the program starts.  You don't have to monitor for a week to see if some corner case will run out of memory.


message:
Set an arduino software clock

Me and my friend are having some trouble setting up an software clock to our arduino uno.

It's for a school project and we´ve never done any programming before. thanks!

body:
There is a Time library which you can import.

Here are things that I found on the Arduino website.

    hour();            // The hour now  (0-23)
    minute();          // The minute now (0-59)
    second();          // The second now (0-59)
    day();             // The day now (1-31)
    weekday();         // Day of the week, Sunday is day 1
    month();           // The month now (1-12)
    year();            // The full four digit year: (2009,
                    //  2010 etc)
    setTime(t);              // Set the system time to the
                          //  give time t
    setTime(hr,min,sec,day,month,yr); // Another way to set
                                   //  the time
    adjustTime(adjustment); // Adjust system time by adding
                         //  the adjustment value

    timeStatus();   // Indicates if time has been set and
                 //  recently synchronized
                 //  returns one of the following
                 //  enumerations:
    * timeNotSet    // The time has never been set,
                 //  the clock started at Jan 1 1970
    * timeNeedsSync // The time had been set but a sync
                 //  attempt did not succeed
    * timeSet       // The time is set and is synced
                 //  Time and Date values are not valid if
                 //  the status is timeNotSet. Otherwise
                 //  values can be used but the returned
                 //  time may have drifted if the status is
                 //  timeNeedsSync.

    setSyncProvider(getTimeFunction);// Set the external time
                                  //  provider
    setSyncInterval(interval);    // Set the number of
                               //  seconds between re-sync

And obviously,

    #include<Time.h>

Tell me in the comments if you need more help.


message:
Converting ASCII value to String

I have this code.

    String incoming;   // for incoming serial data

    void setup() {
        Serial.begin(9600);  // opens serial port, sets data rate to 9600 bps
    }

    void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incoming = Serial.read();
                String mysrr = String(incoming);
                // say what you got:
                Serial.print("I received: ");
                Serial.println(mysrr);
        }
    }

A few of you will recognise this as an Arduino example.

However, when I run it ( I sent it the message "hi"), I get this in the serial:

    I received: 104
    I received: 105

Why is this happening?

body:
Serial.read() returns an int not a String. https://www.arduino.cc/en/Serial/Read

Use an int for incoming (as the example). Or even better use a char and skip all the strings.

Cheers!


message:
Light leds on this board one at a time

I am playing around with this Tinycircuits [16 LED board][1] and I can figure out how to persistently light two LEDs at the same time. The page comes with an example that i can modify but I can only do 1 at a time

**How do I light more than one LED at a time?**

    /*
    TinyDuino Edge LED Demo

    April 9 2014, by Ben Rose

    This example code is in the public domain.

    http://www.tiny-circuits.com

    */

    void setup()
    {
      LedOn(0);//Pass a zero to turn all LEDs off
    }

    void loop()
    {
      for(int i=1;i<16;i++){
        LedOn(i);
        delay(20);
      };
      for(int i=16;i>1;i--){
        LedOn(i);
        delay(20);
      };
    }

    void LedOn(int ledNum)
    {
      for(int i=5;i<10;i++){
        pinMode(i, INPUT);
        digitalWrite(i, LOW);
      };
      if(ledNum<1 || ledNum>16) return;
      char highpin[16]={5,6,5,7,6,7,6,8,5,8,8,7,9,7,9,8};
      char lowpin[16]= {6,5,7,5,7,6,8,6,8,5,7,8,7,9,8,9};
      ledNum--;
      digitalWrite(highpin[ledNum],HIGH);
      digitalWrite(lowpin[ledNum],LOW);
      pinMode(highpin[ledNum],OUTPUT);
      pinMode(lowpin[ledNum],OUTPUT);
    }

  [1]: https://www.tiny-circuits.com/tiny-shield-16-edge-led.html

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

This is your circuit.

I think you can take it from here by looking at the diagram, but please note that e.g. 1 0 0 0 0 will light up 3 and 1, so be careful.

To show more than one, turn on multiple LEDs in rapid succession. It will give the effect that more than one are on. This is known as multiplexing.

**Update:**

After Googling around, I understood it better. I also wrote this code.

    int IO1 = 50;
    int IO2 = 48;
    int IO3 = 46;
    int IO4 = 44;
    int IO5 = 41;
    int del = 1000;

    void setup() {

      pinMode(IO1, INPUT);
      pinMode(IO2, INPUT);
      pinMode(IO3, INPUT);
      pinMode(IO4, INPUT);
      pinMode(IO5, INPUT);
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
        displayLED(1);
        delay(del);
        displayLED(2);
        delay(del);
        displayLED(3);
        delay(del);
        displayLED(4);
        delay(del);
        displayLED(5);
        delay(del);
        displayLED(6);
        delay(del);
        displayLED(7);
        delay(del);
        displayLED(8);
        delay(del);
        displayLED(9);
        delay(del);
        displayLED(10);
        delay(del);
        displayLED(11);
        delay(del);
        displayLED(12);
        delay(del);
        displayLED(13);
        delay(del);
        displayLED(14);
        delay(del);
        displayLED(15);
        delay(del);
        displayLED(16);
        delay(del);// light up LEDS 1, 2 and 3.
    }

    void displayLED(int a){
        clear();
        if (a == 1){o(1); o(2); h(1); l(2); Serial.println('1');}
        if (a == 2){o(1); o(2); l(1); h(2); Serial.println('2');}
        if (a == 3){o(1); o(3); h(1); l(3); Serial.println('3');}
        if (a == 4){o(1); o(3); l(1); h(3); Serial.println('4');}
        if (a == 5){o(2); o(3); h(2); l(3); Serial.println('5');}
        if (a == 6){o(2); o(3); l(2); h(3); Serial.println('6');}
        if (a == 7){o(2); o(4); h(2); l(4); Serial.println('7');}
        if (a == 8){o(2); o(4); l(2); h(4); Serial.println('8');}
        if (a == 9){o(1); o(4); h(1); l(4); Serial.println('9');}
        if (a == 10){o(1); o(4); l(1); h(4); Serial.println(10);}
        if (a == 11){o(3); o(4); l(3); h(4); Serial.println(11);}
        if (a == 12){o(3); o(4); h(3); l(4); Serial.println(a);}
        if (a == 13){o(3); o(5); l(3); h(5); Serial.println(a);}
        if (a == 14){o(3); o(5); h(3); l(5); Serial.println(a);}
        if (a == 15){o(4); o(5); l(4); h(5); Serial.println(a);}
        if (a == 16){o(4); o(5); h(4); l(5); Serial.println(a);}

    }

    void clear(){pinMode(IO1, INPUT);
      pinMode(IO2, INPUT);
      pinMode(IO3, INPUT);
      pinMode(IO4, INPUT);
      pinMode(IO5, INPUT);}

    void o(int o){
        if (o == 1){pinMode(IO1, OUTPUT);}
        if (o == 2){pinMode(IO2, OUTPUT);}
        if (o == 3){pinMode(IO3, OUTPUT);}
        if (o == 4){pinMode(IO4, OUTPUT);}
        if (o == 5){pinMode(IO5, OUTPUT);}
    }

    void h(int l){
        if (l == 1){digitalWrite(IO1, HIGH);}
        if (l == 2){digitalWrite(IO2, HIGH);}
        if (l == 3){digitalWrite(IO3, HIGH);}
        if (l == 4){digitalWrite(IO4, HIGH);}
        if (l == 5){digitalWrite(IO5, HIGH);}
    }

    void l(int h){
        if (h == 1){digitalWrite(IO1, LOW);}
        if (h == 2){digitalWrite(IO2, LOW);}
        if (h == 3){digitalWrite(IO3, LOW);}
        if (h == 4){digitalWrite(IO4, LOW);}
        if (h == 5){digitalWrite(IO5, LOW);}
    }

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


body:
That is an interesting challenge. You should include the circuit diagram for this. It really helps understand the code.

[![Charleplex Circuit][1]][1].

There is excellent information on this technique to reduce number of pins [here][2].

Cheers!

  [1]: https://i.stack.imgur.com/J3WQz.png
  [2]: http://playground.arduino.cc/Code/Charlieplex


message:
TCP or HTTP connection between web server and arduino

If arduino works as a client and tries to connect to web server (the server is mine), should I connect to it via TCP or HTTP connection? Data will be simple strings (20 chars at max) so TCP connection should probably be enough?

The connection has to work in both ways - web server sending data to arduino and arduino sending data back to server.

body:
It's time you learned the [OSI 7 layer model: PDNTSPA](https://en.wikipedia.org/wiki/OSI_model).

HTTP is a *P*resentation (protocol) that runs over a TCP *S*ession.  If you are interacting with a web server then you will be opening a TCP socket and sending HTTP requests.

There is no other way of talking to a web server. It only speaks HTTP, and you can only connect to it through TCP.


message:
Arduino / BitVoicer Sending IR code on loop

I was designing a voice automated kitchen lighting system. I have led strips under the cabinets which are remote controlled by an IR remote, so I captured the IR codes and got an IR led to turn them on. Now I introduced BitVoicer so that I could use voice commands to control the LED. I have ran into the issue that the IR led keeps turning the lights on and off, but my IR codes worked prior to using BitVoicer.

Here is my arduino code:

    #include <BitVoicer11.h>

    int IRledPin = 13;

    BitVoicerSerial bvSerial = BitVoicerSerial();

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

    void loop()
    {
      bvSerial.getData();

      if(bvSerial.strData == "")
      {
        return;
      }

      if(bvSerial.strData == "wake")
      {
       LightOnCode();
      }
    }

      void pulseIR(long microsecs)
       {
         cli();

         while (microsecs > 0)
          {
            digitalWrite(IRledPin, HIGH);
            delayMicroseconds(10);
            digitalWrite(IRledPin, LOW);
            delayMicroseconds(10);

            microsecs -= 26;
          }
         sei();
        }
       void LightOnCode()
    {
      pulseIR(8940);
      delayMicroseconds(4380);
      pulseIR(520);
      delayMicroseconds(600);
      pulseIR(520);
      delayMicroseconds(560);
      pulseIR(560);
      delayMicroseconds(560);
      pulseIR(520);
      delayMicroseconds(580);
      pulseIR(520);
      delayMicroseconds(560);
      pulseIR(540);
      delayMicroseconds(580);
      pulseIR(520);
      delayMicroseconds(580);
      pulseIR(520);
      delayMicroseconds(580);
      pulseIR(540);
            delayMicroseconds(1660);
      pulseIR(520);
      delayMicroseconds(1680);
      pulseIR(520);
      delayMicroseconds(1660);
      pulseIR(540);
      delayMicroseconds(1680);
      pulseIR(520);
      delayMicroseconds(1680);
      pulseIR(500);
      delayMicroseconds(1680);
      pulseIR(540);
      delayMicroseconds(1680);
      pulseIR(520);
      delayMicroseconds(1660);
      pulseIR(540);
      delayMicroseconds(580);
      pulseIR(520);
      delayMicroseconds(560);
      pulseIR(560);
      delayMicroseconds(560);
      pulseIR(520);
      delayMicroseconds(600);
      pulseIR(500);
      delayMicroseconds(580);
      pulseIR(540);
      delayMicroseconds(560);
      pulseIR(520);
      delayMicroseconds(1680);
      pulseIR(540);
      delayMicroseconds(560);
      pulseIR(520);
      delayMicroseconds(1680);
      pulseIR(540);
      delayMicroseconds(1660);
      pulseIR(520);
      delayMicroseconds(1680);
      pulseIR(520);
      delayMicroseconds(1640);
      pulseIR(580);
      delayMicroseconds(1660);
      pulseIR(520);
      delayMicroseconds(1660);
      pulseIR(560);
      delayMicroseconds(560);
      pulseIR(520);
      delayMicroseconds(1680);
      pulseIR(520);

    }

If anyone could answer my question as to why the led keeps sending extra signals I would appreciate it! If you have any questions don't hesitate to ask!

body:
Taking a quick look at the [Documentation](http://www.bitsophia.com/BitVoicer/v12/BitVoicerManual_v12_en.pdf) on page 22, it looks like you need to use your `bvSerial.strData` calls within a function called `void serialEvent()` rather than inside of your loop.  I would recommend trying out their tutorial on that page just to make sure you get BitVoicer to work properly before scaling it for your application.

Hope that helps!


message:
Light up multiple LEDs with standard Arduino Uno

I am trying to find out if it is possible to light up multiple LEDs with a standard Arduino Uno. Say I have 500 LEDs and logically I give each one of them a number from 1 to 500. In my test scenario I'd like to say something like "LED No 275 On" and as a result only have this single LED turning on while all others remain off.

Is there a way to do that at all? Or will I have to use many different Arduino Unos for that?

body:
Probably the simple answer is to use 63 8-bit shift registers, with a LED and resistor attached to each shift register output pin. There are many good examples of using shift registers to add output ports on the internet.

The shift register solution will let you turn on just one LED at a time, or if your power supply can stand it, all 500 at once.

This question shows how to go about the expansion https://arduino.stackexchange.com/questions/117/is-there-a-way-to-have-more-than-14-output-pins-on-arduino
It also gives some other valid options.


body: Rectangular matrices and strips of dozens or hundreds of LEDs are available from places like Adafruit and Sparkfun, with added circuitry to allow you to address and manipulate single LEDs easily. Some are single color, some are RGB. Adafruit in particular has many products like this and many tutorials on how to use them.


message:
Connect ethernet cable wires directly to pins

Is it possible to uncrimp a RJ45 plug and connect the wires directly to the Arduino pins? I guess I'd have to decrypt the ethernet signal then on my Arduino which might not have enough processing power at command for such a task.

I don't want to do it with an Ethernet shield, so please don't link any in the answers.

body:
I am by no means an expert on this, this answer is ~20 minutes of me googling things, but I would say that *in theory* it is probably possible to do this with an arduino, at least at the lower transfer rates anyway, and certainly from a "will it kersplode my board" point of view - probably not since ethernet [runs at +/- 2v](https://en.wikipedia.org/wiki/Ethernet_over_twisted_pair) (ish) and [~10mA](https://electronics.stackexchange.com/questions/36725/current-over-ethernet) (ish). *However*:

The ethernet protocol is [exceedingly complex](http://ww1.microchip.com/downloads/en/AppNotes/01120a.pdf), with many layers needed to actually communicate with anything useful, all of which you would have to implement from scratch (there won't be a library to just drop in) and I'm not completely convinced that an entirely software-based implementation of the stack would fit on the arduino (but I could definitely be wrong there - and actually, on further thought, this probably is wrong, but I reckon *I* couldn't write it so it fit, but I'm a reasonably average human being).

Arduino is all about hacking and re-inventing wheels just for the fun of it but I am absolutely certain that there is no fun to be had re-engineering Ethernet and TCP/IP and all of the stuff in betweeen from scratch (obviously my opinion, I enjoy all sorts of things others don't, so YMMV).

My suggestion would be - if you don't like ethernet shields, look into getting a 'raw' ethernet controller chip (like the one soldered onto an ethernet shield) and build it directly into whatever device you're trying to make *first*, that'll give you plenty of exposure to how ethernet works at that level, then you can decide if you're still up for re-inventing the brain that invented the wheel. Good luck!


body:
Electrically, you don't have to worry about anything, as the previous answer stated, but Ethernet (Even 100Mbps FastEthernet, much less Gigabit) is way too fast for the Arduino to read.  `digitalRead()` is roughly 100x too slow, [it takes roughly 4 microseconds][1], and even doing direct port reads is 5x too slow.  This doesn't take into account another operations, much less the fact that the clocks on the Arduino's don't run that fast.

100Mbps FastEtherent runs at roughly 31MHz, or 31,000,000 Hz.  That is FAST compared to our Arduino's, which have a clock speed of only 16MHz.

To answer your question in a word, no, it is not possible to do what you ask.

  [1]: http://jeelabs.org/2010/01/06/pin-io-performance/


body:
As others have stated, it's not physically possible for an Arduino to encode or decode standard Ethernet protocol messages over CAT5 cable with wires at one end connected directly to the Arduino pins, and the other plugged into a standard Ethernet device.
Standard Ethernet runs at least 10 Mbit/s for [10BASE-T, each bit Manchester encoded][1], so effectively 20 Mbit/s. See ["TCP/IPv4 and Ethernet 10BASE-T/
100BASE-TX Debugging"][2] for a lot of photos of what the standard Ethernet protocol looks like on an oscilloscope screen.
An Arduino running at 16 MHz can't sample a pin at 20 Mbit/s.

However, Arduinos can easily transmit and receive messages using a variety of other, slower [communication protocols][3].
Devices that use such protocols can often be wired directly to the Arduino pins, with the Arduino programmed appropriately with that protocol.

Occasionally people use CAT5 cable (commonly called "ethernet cable") to carry those non-Ethernet messages from one device to another.

Sometimes people wire a RJ45 socket (also called a 8p8c socket) directly to an Arduino and corresponding RJ45 socket wired directly to the other device (often with a big "THIS IS NOT ETHERNET" warning on both sockets), and use standard off-the-shelf CAT5 patch cables with standard [RJ25 plugs (also called 8p8c plugs)][4] to carry those non-Ethernet messages between the sockets.
(For example, the connection between the Arduino-compatible "[Motherboard 1.2 Generation 3][5]" and the "[Stepper Motor Driver 2.3 Generation 3][6]" used in some early RepRaps; the [TechZone Thermocouple A-D converter][7] and other [1-wire devices that use the 1WRJ45 standard][8]; etc.
As far as I can tell, none of the many CAT5 cables Nate connected to various Arduinos in ["Lessons from Rebuilding Illumitune"][9] actually carry any Ethernet messages.)

Sometimes people cut and strip the ends of CAT5 cable, using them as a convenient bundle of wires that can be used pretty much like any wire.

Hooking wires directly between two Arduinos (or an Arduino and some other device using some non-Ethernet protocol) often seems to work when both are plugged into the same power supply and connected by a short cable. The "extra hardware" people use to interface between an Arduino and a Ethernet network or CANbus or RS485 bus or MIDI or etc. helps avoid a variety of problems that happen when two devices are plugged into different power supplies or have long cable runs between them or both.

  [1]: http://www.fpga4fun.com/10BASE-T3.html
  [2]: http://www.testequity.com/documents/pdf/ethernet-debugging.pdf
  [3]: http://en.wikibooks.org/wiki/Embedded_Systems/Common_Protocols
  [4]: http://cp.literature.agilent.com/litweb/pdf/5989-7528EN.pdf
  [5]: http://reprap.org/wiki/Motherboard_1_2
  [6]: http://reprap.org/wiki/Stepper_Motor_Driver_2.3
  [7]: http://reprap.org/wiki/TechZone_Tip_Assembly#Thermocouple_A-D_converter_with_OneWire
  [8]: http://www.opencircuits.com/1-wire
  [9]: https://www.sparkfun.com/tutorials/282


message:
Arduino countdown timer for repeating actions

I have tried to find simple library for triggering timer after some time.
The idea is to retry network connection (RF24 network library).

I have following code now

    while(!mesh.write(message, headerType, memSize)) {

    }

This code will try to send packet until success

But I need to give up after for instance 10 seconds

I wanna to have something like this

    bool timerTriggered = false;
    Timer myTimer = new Timer(10000);
    myTimer.setCallback(countedDown);

    void countedDown() {
       timerTriggered = true;
    }

And start timer before network request

    myTimer.start();

    while(!mesh.write(message, headerType, memSize) || !timerTriggered) {

    }

Please suggest the best way to implement this.

Thanks.

**EDIT**

I have found problem as far as delay(); uses timer internally it conflicts with libraries or simple timer.

The solution is to use `  Alarm.delay(400); ` instead.

Maybe someone knows better solution ?

body:
Something like this would work as a non-blocking, general purpose timer:

    unsigned long startTimestamp;
    unsigned long timestamp;
    const unsigned long timer_length = 10000; //10 seconds

    startTimestamp = millis();
    timestamp = startTimestamp;

    while ( (timestamp - startTimestamp) < timer_length)
    {
        // keep doing thing

        timestamp = millis();
    }

    // stop doing thing now


body:
To expand on the other answer and combine it better with your situation:

Just check the current time in your while loop:

    unsigned long startTime = millis();
    while((!mesh.write(message, headerType, memSize)) && ()millis() - startTime) < 10000)) {
    }

That is, while it's not transmitted properly, and the difference between now and when you started transmitting is less that 10 seconds, keep trying.

There is no need for any special libraries or asynchronous timers - it can all be done by examining `millis()`.


message:
Negative voltage output Or Controling negative voltage

I've got an RGB led strip I'm trying to control. It's a 12v, 4 pin strip.
Pin layout seems rather odd to me as 1 pin takes 12v of power and 3 pins (that go to ground) control the colors. In other words, **the LED colors are controlled by limiting outgoing voltage**.

[![Led Strip][1]][1]

 - **White**- +12v
 - **Green**- Green in negative voltage
 - **Red** - Red in negative voltage
 - **Blue** - Blue in negative voltage

I've already made a similar setup that uses n-channel MOSFETS (or at least I think that's what they are) between the colored cables and the ground and Arduino power the MOSFET gates as necessary.

**So my question is:** is it possible to hook these LEDs up directly to arduino and control the negative voltage without aditional electronics?

As a slightly off topic question: Is there a specific name for elements that are controlled with negative voltages.

----------------------

By the way, I'm using Arduino nano, although I don't think it is relevant at this point and I've got Mega and Uno aswell if needed.

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

body:
No, it's not possible, since the voltages and currents involved (12V) are too high.  It will damage your board.

Your arrangement with N-channel MOSFETs is the correct arrangement.

By the way, you are not working with "negative" voltages at all - it's all positive - you just happen to be between the "load" and ground.

This is called a **Low Side Switch** since it is on the "low" (i.e., between the load and ground) side of the circuit.

The LEDs you have are in an arrangement called **Common Anode** in that the anodes (+ pins) of the LEDs are all tied together (common) and you control the cathode (- pins) of the LEDs.  It means you can use cheap N-channel MOSFETs that are (as you have seen) easy to control with a microcontroller.  The other arrangement, *Common Cathode*, where all the cathodes (- pins) are tied together and you switch the power to the anodes (+ pins) requires P-channel MOSFETs *and* N-channel MOSFETs to switch the P-channel MOSFETs, which increases costs.


message:
Infrared distance sensor picks up distances that are not there

I have connected an [Infrared sensor][1] to my Arduino Uno and I've set this code up to blink whenever a distance of less than 50 cm is picked up. If there is an object less than 50 cm away, it does pick it up. However, with nothing in front of it it still blinks at random intervals. The sensor is new. Where do you think the problem is?

    int sensorPin = 0;
    int ledPin = 13;

    void setup() {
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      float distance = 12343.85 * pow(analogRead(sensorPin),-1.15);
      if(distance < 50){
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
      }
      delay(50);
    }

  [1]: https://www.sparkfun.com/products/242

body:
I see one problem with your code and how it relates to this device.

The output from the sensor is not the monotomic function you describe; not over its entire range.  Your conversion function describes only a section of the response.  The device is only intended to be used when an object is in range 10-80 cm.

You should check that the voltage at the analog input is valid before performing the math:

    int v;

    v = analogRead(sensorPin);
    // sensor is valid in range 0.4 to 2.5 V
    if((82 < v) && (v < 512)) {
      // voltage is in usable range, can convert
      distance = 12343.85 * pow(v,-1.15);
      if(distance < 50) {
        digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
      }
    }
    else {
      // no valid reading - probably just skip and try again on next loop
    }

With that the false triggers may be eliminated.


body:
Looks to me like there could be a signficant figures issue. Arduino can really only handle 7 digits of precision. You hit that right at your first constant in your distance variable, then you multiply by an integer to a power of -1.15. It's likely there are errors there that trip to less than 50, which would give you false positives.

As for the Sharp IR sensors, just buy an IR photodiode and LED for less than $1 USD and build and calibrate your own IR detector. You can calibrate it to a range of about 1 m. That's my recommendation. I did something similar after being frustrated by the cost of the Sharp IR Detectors. Wrote about it on my blog, if you're interested:

https://engineersportal.com/blog/2018/1/17/infrared-obstacle-detector-for-less-than-1


message:
exit(0) function shows up an error

So I have been trying to write a code where I use the `millis()` function to print the milliseconds of on-time of the board using `Serial`. But the condition is I want to stop printing the value once it reaches 10 seconds (10000ms).

I have been trying to use the `exit()` function but I get no output then.

    #include<stdlib.h>

    void setup()
    {

      Serial.begin(9600);          //  setup serial

    }

    void loop()

    {

    unsigned long timer1;

    while(timer1000!=0)

    {

    timer1=millis();

    Serial.println(timer1);

    }

        exit(1);

    }

body:
The AVR library documentation for [exit()][1] is great help. It explains that the interrupts are turned off and an infinite loop is entered. As the interrupts get turned off the last characters in the Serial buffer are not transmitted.

You can use [Serial.flush()][2] to wait for the transmission to complete before calling exit().

Cheers!

  [1]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga137096a48cc0c731052cadfb69c39b34.html
  [2]: https://www.arduino.cc/en/Serial/Flush


message:
Counting loops or if..else

What I would like to do is,
 step 1:

    led1 fades from black(off) to green (max-on 255)
    led2 fades from black(off) to red (max-on 255)

this happens at the same time.
If the max value is reached, then both leds fade out (to black, off)
so step 2:

    led1 fades from green to black
    led2 fades from red to black

Then step 3, almost same as step 1 but opposite colours:

    led1 fades from black(off) to red(max-on 255)
    led2 fades from black(off) to green(max-on 255)

And step 4, both fade to black

    led1 fades from green to black
    led2 fades from red to black

This is the code that fades led 1/3/5 from red to black and back to red
and led 2/4/6 from green to black, and back.

    #include <FastLED.h>
        #define NUM_LEDS 6
        #define DATA_PIN 3

            CRGB leds[NUM_LEDS];

               void setup() {
                   Serial.begin(9600);
           FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
       }

           void loop()
    {

      int x = 1;
       for (int i = 1; i > -1; i = i + x){

         leds[0] = CRGB(i,0,0);
         leds[1] = CRGB(0,i,0);
         leds[2] = CRGB(i,0,0);
         leds[3] = CRGB(0,i,0);
          Serial.println(i);
          FastLED.show();
          if (i == 55) x = -1;             // switch direction at peak
          delay(100);

       }
    }

****Original question****
> I am trying to fade a led (WS2812B) from black to green or red, and
> back to black. (that is working)  But now I want the same led fading
> to blue.
>
> How could I do that? I was trying a if..else but can't figure it out
> Or should I count the for loops?
>
> This is the starting code I am using
>
>
>
> maybe something like
>
>         if (i==0)
>     {
>                  leds[0] = CRGB(i,0,0);
>                  leds[1] = CRGB(0,i,0);
>                  leds[2] = CRGB(i,0,0);
>                  leds[3] = CRGB(0,i,0);
>     }
>         else
>     {
>                  leds[0] = CRGB(0,0,i);
>                  leds[1] = CRGB(0,0,i);
>                  leds[2] = CRGB(0,0,i);
>                  leds[3] = CRGB(0,0,i);
>     }
>                   FastLED.show();
>                   if (i == 100) x = -1;
>                   delay(100);
>
> But that is not working. Any suggestions?

body:
I would do that based on the clock. This lets you run each one independently.

On the off-chance that your project runs that long, the clock rolls over (resets) every 50 days.

I'm going to assume the 55 in your code should read 255.

I would do something like this (this is a code snippet, but should get you started):

    const int phase_milliseconds=2500; // each phase lasts 2.5 seconds.
    const phase_progress_length=256;   // each phase goes from 0 to 255
    const phases=4;                    // numbered from 0 to 3, will repeat forever.

    // This is the time since your Arduino turned on
    unsigned long time=millis();
    // how far we are through the current phase?
    int progress= time%phase_milliseconds)*phase_progress_length/phase_milliseconds;

    // which phase are we in?
    int phase=(time/phase_milliseconds)%phases;

    if (phase==0) { // first step
             leds[0] = CRGB(progress,0,0);
             leds[1] = CRGB(0,progress,0);
    } else if (phase==1) { // second step
             leds[0] = CRGB(255-progress,0,0);
             leds[1] = CRGB(0,255-progress,0);
    } else if (phase==2) { // third step step
             leds[0] = CRGB(0,progress,0);
             leds[1] = CRGB(progress,0,0);
    } else if (phase==3) { // fourth step
             leds[0] = CRGB(0,255-progress,0);
             leds[1] = CRGB(255-progress,0,0);
    }

Since this is time based, it doesn't matter much how often it runs, you don't need a delay (you can still put one in if you like). You can extend this to more steps.

Also note that I rattled this off, off the top of my head, so there may be errors.


message:
Seeking help - Using CJMCU 8*8 LED matrix with arduino

The CJMCU 8*8 LED board is a grid of 64 W2812 (addressable) LEDs. The board is configured as if it was one long LED strand (just a single  DIN, 5v and GND). For some flipping hair pulling reason, my code works fine on 2812 LED strands, but I get nothing on the board. Just random flickering when I jostle the 5V wire. Any ideas? Am I completely missing something here? Pretty sure the board is fine, just can't seem to take any input...

(Here's a link to the board: http://www.aliexpress.com/store/product/CJMCU-64Bit-WS2812-5050-RGB-LED-Development-Board-Built-in-RGB-Driver-White-SKU-11481/933826_32249197598.html)

body:
I just received 2 of these from 2 different suppliers on EBAY.
None work using the pins called [GND +5V DIN]. As it turns out the DIN is actually NOT DIN. The other connector area [GND +5V DOUT] is the DIN. Ugh!

These boards are marked CJMCU-8*8 on the back side and on the front they say "WS2812B-64 RGB LEDS". Which is another issue. They are using the 6 pin WS2812, not the 4 pin WS2812B.

So if this is what your board looks like then perhaps try the pin marked DOUT for your DIN. Or try to psych out the traces to make sure first.


body:
Unbelievably, as I've just discovered, this has been a known issue with these boards for at least a year and a half, yet they are still shipping them. The silk screening process of labeling the board is the problem. Just poor quality control. The front (LED) side of these low quality CMJCU-8*8 boards are incorrectly marked "SM2812B RGB LEDS". (The actual LEDs are 6 pin SM2812's, not 4 pin SM2812B's), but the real problem is with the back side of the board. The manufacturer printed the boards upside down, so that the input and output labels are reversed (DIN is really DOUT and vise versa).

I just purchased one of these defectively printed boards on line and received it a few days ago. Took me awhile to figure out why I couldn't get it to work, but I finally did. When hooked up backwards, the CMJCU-8*8 will do nothing at all (no LEDs will come on), because of the built in reverse polarity protection, but if you run your thumb hard (it's just +5V) over the other pins (the ones that include the erroneously marked DOUT) while the board is powered up, one or more of the SM2812 LEDs will magically come on. This is because your thumb makes an intermittent connection between the real DIN and the +5v rail, providing a forward bias to a few random LEDs. Once lit, these LED's will actually stay on until you cut power to the board, so if you keep ding it, you can get quite a few of the SM2812s to come on.

![CMJCU-64 Printing Error](https://s11.postimg.org/fhuzis29v/cjmcu_64_Printing_Error.jpg)


body: Literally spent hours painstakingly chasing same problem. Complained bitterly to supplier that board refused to respond or operate when received. They responded by trying to tell me I had no clue about how to connect, but eventually agreed to send replacement after I proved had connected correctly, while waiting for replacement came across this post, went and found original board and reconnected, 5V to DIN side, and DIN to DOUT (Instant operation) because the reverse polarity protection does not prevent being energized this way. if supplier comes good, will have another board to compensate my trouble.


message:
What's wrong with my IR sensor

I bought some 'lucky dip' IR sensors from China, no idea what they are, but they appeared to get lost in the post so instead I [bought some of these](http://uk.rs-online.com/web/p/ir-receivers/7085086/) from a reputable place in the UK that come with a [datasheet](http://docs-europe.electrocomponents.com/webdocs/0e56/0900766b80e56a95.pdf).

The next day, both items arrived together!

I'm trying to build a very simple proximity sensor for a robot, I built the following circuit:

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

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

<!-- End schematic -->

and stole this code to test it out:

    #define IRledPin 8
    #define D13ledPin 13
    #define IRsensorPin 9

    void IR38Write() {
      for(int i = 0; i <= 384; i++) {
        digitalWrite(IRledPin, HIGH);
        delayMicroseconds(13);
        digitalWrite(IRledPin, LOW);
        delayMicroseconds(13);
      }
    }

    void setup(){
      pinMode(IRledPin, OUTPUT);
      digitalWrite(IRledPin, LOW);
      pinMode(D13ledPin, OUTPUT);
      digitalWrite(D13ledPin, LOW);
    }

    void loop(){
      IR38Write();
      if (digitalRead(IRsensorPin)==LOW){
        digitalWrite(D13ledPin, HIGH);
      } else {
        digitalWrite(D13ledPin, LOW);
      }
    }

If I hold my hand in front of it, nothing happens (LED on-board arduino should light up), *however* if I point a TV remote at it and press a button, the LED lights up. I tested 2 of the 'fancy' sensors that I got and both behaved the same.

Then I tried one of the 'lucky dip' sensors, swapped it straight in and the whole thing works perfectly - point a TV remote and the LED lights, hold my hand ~10cm in front of it and the LED lights!

So, where have I gone wrong?

body:
See page 5 of your datasheet - that 'fancy' sensor suppresses "• Continuous signals at any frequency".

So you'll need to pulse your 38.4kHz signal for the sensor to produce an output.


body:
The answer I've accepted is the correct answer, but I wanted to add this extra bit for completeness. I reworked my code to use non-blocking delays for the IR LED so the sensor actually gets a chance to see it before it stops transmitting and it works! Range is quite a bit shorter than the 'lucky dip' sensor (~ 2cm).

    #define IR_LED 8
    #define LED 13
    #define SENSOR 9

    unsigned long burst_timer;
    unsigned long gap_timer;

    unsigned long timestamp;

    char led_state;
    char burst_count;

    const char BURST_MAX = 20;

    void setup()
    {
      pinMode(IR_LED, OUTPUT);
      led_state = LOW;
      burst_count = 0;
      digitalWrite(IR_LED, led_state);

      pinMode(LED, OUTPUT);
      digitalWrite(LED, LOW);

      pinMode(SENSOR, INPUT);

      timestamp = micros();
      burst_timer = timestamp;
      gap_timer = timestamp;
    }

    void toggle_led()
    {
      if (led_state == LOW)
      {
        led_state = HIGH;
      }
      else
      {
        led_state = LOW;
        burst_count++;
      }

      digitalWrite(IR_LED, led_state);
    }

    void loop()
    {
      timestamp = micros();
      if (timestamp - burst_timer > 13 && burst_count < BURST_MAX)
      {
        toggle_led();
        burst_timer = timestamp;
        gap_timer = timestamp;
      }

      if (burst_count >= BURST_MAX && timestamp - gap_timer > (13*2*BURST_MAX) )
      {
        burst_count = 0;
        burst_timer = timestamp;
        gap_timer = timestamp;
      }

      if (digitalRead(SENSOR) == LOW)
      {
        digitalWrite(LED, HIGH);
      }
      else
      {
        digitalWrite(LED, LOW);
      }
    }

Every time I use `delay()` (or `delayMicroseconds()`) I find a new reason not to!


message:
Nokia32/RCMM IR decoding issues

I am trying to decode the IR signals from a remote. I'm using an Arduino Pro Micro, and a TSOP38238 IR receiver.

I found out that the remote uses the Nokia32(RCMM) protocol, and I have been able to partially decode it using cyborg5/IRLib (specifically this one: [rcmm.ino][1]). I tweaked the values of the example using the LIRC file corresponding to my remote, mainly the absolute error tolerance ([Freebox_V5.lircd.conf][2]).

Compared to other remotes I tried (with different protocols) the RCMM algorithm doesn't manage to decode the signal every time. Around 40% of the time when I press a button I got an "Unknown type received" output from the decoder.

The following is three outputs (for the same button) of the algorithm for a successful decoding and below two other outputs corresponding to two failures. Could anyone tell me what could be done to increase the success of the decoding algorithm?

**Successful**
---

    Decoded RCMM: Value:2400A601 (32 bits)
    Raw samples(36): Gap:63264
      Head: m410  s290
    0:m160 s290 1:m160 s590   2:m210 s390 3:m210 s240
    4:m210 s240 5:m210 s240   6:m210 s240 7:m210 s240
    8:m210 s540 9:m210 s590   10:m210 s390 11:m210 s590
    12:m160 s290 13:m160 s290   14:m160 s240 15:m210 s440

    16:m160
    Extent=9810
    Mark  min:160  max:210
    Space min:240  max:590

**Failure 1**
---

    Unknown type received. Ignoring.
    Decoded Unknown(0): Value:0 (0 bits)
    Raw samples(36): Gap:3148
      Head: m410  s290
    0:m160 s240 1:m210 s590   2:m210 s390 3:m210 s240
    4:m210 s240 5:m210 s240   6:m160 s290 7:m160 s290
    8:m160 s590 9:m210 s590   10:m160 s440 11:m210 s590
    12:m160 s240 13:m210 s240   14:m210 s240 15:m210 s390

    16:m210
    Extent=9810
    Mark  min:160  max:210
    Space min:240  max:590

**Failure 2**
----

    Unknown type received. Ignoring.
    Decoded Unknown(0): Value:0 (0 bits)
    Raw samples(32): Gap:27904
      Head: m410  s290
    0:m160 s290 1:m160 s590   2:m160 s490 3:m160 s240
    4:m210 s240 5:m160 s290   6:m160 s290 7:m160 s290
    8:m160 s290 9:m160 s590   10:m160 s490 11:m160 s590
    12:m160 s1190 13:m160 s440   14:m160
    Extent=9460
    Mark  min:160  max:210
    Space min:240  max:1190

  [1]: https://github.com/cyborg5/IRLib/blob/master/examples/rcmm/rcmm.ino
  [2]: http://sourceforge.net/p/lirc-remotes/code/ci/master/tree/remotes/free/Freebox_V5.lircd.conf

body:
I'm unable to provide a complete answer yet but my research so far into a similar quest to use a similar remote can at least answer why you are getting two values for the same button on the remote. This is by design: the Nokia-32 RCMM protocol of this remote uses toggling codes that flip between one value and another on alternating presses of the same button.

My quest and the challenges of decoding this remote are documented in this thread: https://github.com/bengtmartensson/harctoolboxbundle/issues/97 where I discover that my IR remote uses Nokia 32 protocol but with mark and space timings slightly different from what most Arduino libraries are programmed for requiring a tweak to the signal in order to enable other libraries to decode it successfully.

Further information here: http://www.avsforum.com/forum/93-remote-control-area/1517341-theater-master-mx-500-remote-won-t-learn-bell-fibe-remote-any-help.html#post24345872 where we learn:
> it is different from most IR signals, because it has 4 different off durations, denoting zero, one, two , or three, while traditionally IR protocols have used just two off durations signifying zero or one.


message:
How to properly use volatile variables in Arduino?

I was doing a small project with an Arduino Uno. It involved interrupts as I am using encoders to measure how much the differential wheel system moves forward. My robot moves only forward. So I use only a single channel from each encoder. Here are my two interrupt routines:

    ISR (INT0_vect){

          encoderRPos = encoderRPos + 1;

    }

    ISR (INT1_vect){

      encoderLPos = encoderLPos + 1;

    }

 The variables `encoderRPos` and `encoderLPos` are of type `volatile int`. I understand that the variables which undergoes change in any interrupt routine need to be of type volatile. This is to warn other parts of the code that use these variables that it may change anytime.

But what happened in my code was a bit strange and I could not explain it. Here is how I compute the distance moved by the left wheel:

      #define distancePerCount 0.056196868
      float SR = distancePerCount * (encoderRPos - encoderRPosPrev);
      float SL = distancePerCount * (encoderLPos - encoderLPosPrev);

      encoderRPosPrev = encoderRPos;
      encoderLPosPrev = encoderLPos;

But when I print the following on my serial monitor, I notice an anomaly:

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

If you look at the third column, (SL) it's value is too high just for some time. This is upsetting all my calculations.

The only clue I can get it, if I take the value of SL that I got (3682), which is always a constant, and calculate back `(encodeLPos - encoderLPosPrev)`, I will get 65519.66, which is close to the max value of `unsigned int`. Which means `(encoderLPos - encoderLPosPrev)` is causing an overflow while both the values whose difference is taken is somewhere around 5000 only!

And I managed to solve it. It was by luck. This is how I modified the code:

      static int encoderRPosPrev = 0;
      static int encoderLPosPrev = 0;

      int diffL = (encoderLPos - encoderLPosPrev);
      int diffR = (encoderRPos - encoderRPosPrev);

      float SR = distancePerCount * diffR;
      float SL = distancePerCount * diffL;

      encoderRPosPrev = encoderRPos;
      encoderLPosPrev = encoderLPos;

  I can't comprehend what has happened. Is there something about volatile variables that I should have known about?

**Update:** [Here][2] is the entire code if you ever want to take a look. And it's working very well after changing it to what was suggested in the accepted answer.

  [1]: https://i.stack.imgur.com/DMDlf.png
  [2]: http://paste.ubuntu.com/14085127/

body:
You need to learn about *critical sections*.

What is probably happening is that the variables are being changed by the interrupt routines mid-way through the calculations. Your 'fix' reduces the time spent doing the calculation with the volatile variables thus making it less likely that there is a collision.

What you should do is copy the volatile variables to local variables with interrupts disabled for that brief period.

    cli();
    int l = encoderLpos;
    int r = encoderRpos;
    sei();

Because the Arduino is an 8 bit CPU it takes multiple assembly instructions to perform mathematical operations on 16 bit values. Floating point is even worse using many many instructions for a simple addition. Division and multiplication use considerably more. An interrupt has plenty of opportunity to fire during that list of instructions. By doing an assignment like that and then using the new local variables in your calculations the instructions needed to deal with the volatile variables is kept to an absolute minimum.  By turning off interrupts during the assignment you guarantee that the variables can't ever be changed while you are using them. This snippet of code is called a *critical section*.


message:
Arduino Mega 2560 not showing up in Serial Port in IDE

I recently purchased an Arduino Mega 2560. As soon as I connected it for the first time with my macbook pro the led was blinking (default blink program). To stop the blinking, I uploaded an empty sketch to Arduino. Now the arduino is not showing up in serial port in any operating system. The LED is constantly on and not blinking. Please help

body:
Did you try:-

 - Unplugging and reconnecting the board?

or

 - Holding down the reset button (on the board) during compile and then letting go when the Ide says "Uploading to ..."? (Make sure the sketch has a setup(){} and loop(){} so is not entirely empty)

If that doesn't work then ...

 - The pin13 on all the time with an empty sketch might indicate a hardware problem. Is anything connected to the board apart from the usb cable? Green LED simply means the board has power unless you are talking about the tx/rx Led's?

for windows users ...

 - Look in "Control Panel>Device Manager" to see if there is an exclamation mark against any devices, or "Unknown/Other" devices? If you can see the board but it has an error against it look at the properties to see if you can see what the error is. Re-installing the arduino ide will attempt to install the usb drivers again but they can also be found in the \drivers sub folder below the Arduino Ide.

 - If you can see an entry in control panel but it is not showing in the Arduino Ide try changing the port to a different COM number (right click>properties)

 - If you can't see anything in Control Panel try a different usb port on your computer.

 - Is the board connected directly to the pc via usb or via a usb hub? Make sure direct connect. If power externally make sure enough power.


message:
Adafruit TLC5947 breakout board is not working with my Arduino Uno

I am trying to use [this][1] board (setup tutorial on left hand nav) with my Arduino Uno.  I have tried using their example code, as well as my own simplified code, to turn on a single blue LED.

The simplified code I "wrote" is as follows:

<!-- language: c -->

    #include "Adafruit_TLC5947.h"

    #define NUM_TLC5974 1

    #define data   3
    #define clock   5
    #define latch   6

    Adafruit_TLC5947 tlc = Adafruit_TLC5947(NUM_TLC5974, clock, data, latch);

    void setup() {
      tlc.begin();
    }

    void loop() {
      tlc.setPWM(0, 4095);
      tlc.write();
    }

> [Scroll to the bottom for reference. (TLC5947)][2]

This compiles and uploads successfully.  I have DIN connected to 3, CLK to 5, and LAT to 6.  V+ is connected to the Arduino 5V pin, and GND to Arduino ground.

Using this setup, the LED does not turn on when connected to channel 0 on the board.  Using a multimeter, I have verified that the voltage between common ground and the channel 0 pin is ~0V.  Checking voltage on the board between GND and V+, I see 4.8V, which looks good.  Connecting the LED directly to the V+ line lights it up, but obviously isn't switchable.

I have no clue why I'm not seeing anything on channel 0's output when I directly write it to 100% duty cycle.

Why is this not working?

  [1]: https://learn.adafruit.com/tlc5947-tlc59711-pwm-led-driver-breakout/overview
  [2]: https://learn.adafruit.com/tlc5947-tlc59711-pwm-led-driver-breakout/programming

body:
> ... the LED does not turn on when connected to channel 0 on the board. [...] Connecting the LED directly to the v+ line lights it up, but obviously isn't switchable.

From this I suspect that you have connected the LED between pin 0 and ground. The problem with doing this is that the TLC594x LED driver outputs are current ***sinks***, and connect the output to ground when on. The LEDs must connect between V+ and the output as shown in the datasheet.


message:
DHT11 and DHT22 unused pin

The DHT11 and DHT22 is a 4 pin temperature and humidity sensor, where one of the pins is labelled as NC (not connected).

I'm curious what the unused pin is used for.
Factory calibration?

body:
in this datasheet both 3. and 4. pins are marked GND :
https://www.adafruit.com/datasheets/Digital humidity and temperature sensor AM2302.pdf


body:
On the DHT11 it's connected to pin 6 of the SOIC14 inside. So it's at least connected to something. But who knows what it's for.

It has a (internal) pull-up resistor to VCC of around 100kOhm on this pin.

I connected my logic analyzer to it, there is no signal, even while reading the sensor. Also connecting the arduino's signal wire to this (incorrect) pin does nothing.

Factory calibration or testing would be my guess too, but who knows.


message:
Arduino clone with ch340G and correct w7 x64 driver cannot connect to IDE

I have an Uno R3 with CH340G which works perfectly at my home w7 x64 notebook.
It worked properly right away with the CH341s64.sys driver. I tried revs from 2009, 2011 and 2014 and it is working with either one.
On my w7 x64 desktop though the drivers somehow do not communicate properly.
If I plug in the device, windows recognized it and a new port (port 8 in my case) shows up in device manager.

When I try to transfer a sketch to the device it fails with error message
avrdude: stk500_recv(): programmer is not responding.
I have tried CH341s64.sys rev 3.3.2011.11  and 3.4.2014.8 without success.
I have no clue how I can troubleshoot this as windows shows the port properly and there are no signs of error on the driver. There are no entries in the event logs.
Is there possibly a log file from the IDE which could shine a light?
I already tried with firewall disabled but no change.
My IDE is the latest 1.6.6 on both systems.

body:
Solved:
The issue was due to an USB Hub which I have at my desktop.
After I connecting the arduino directly to an USB port at my desktop everything was fine.
Unfortunately there is no hint about this in the arduino troubleshooting guide. A hub is only mentioned in conjunction with a MAC.


message:
A good water flow meter to monitor home usage with Arduino

I'm searching for a good water flow meter to add to my home controller project with Arduino. I have been searching in several pages and I only found some devices that work for low flow.  I need to control the water usage in my home and I thought to add a flow meter at the point where the water enters my home, and view the data with Arduino.

Do you have experience with any flow meter with good quality?

body:
I've used an arduino with an [irrigation flow meter][1].

I think I'm getting accurate results, but I haven't checked against a bill. It can handle high flow, and the sensors will attach to any size pvc line. The sensor are a bit expensive, however. $150 for the sensor and $35 for the T junction that it plugs into.

However, as you are living in an apartment, you'll probably need a non-invasive sensor. Perhaps an acoustic one.

  [1]: http://mostlyhighperformance.blogspot.com/p/irrigation.html?m=1


message:
433mhz range optimization

I would like to get the **best range possible** from my **433MHz modules**. After A LOT of searching and reading, I'm convinced I should be able to cover **10m indoors with free line of sight**.

**[update]**
After some tips in the comments I changed a few things. It looks like with an Arduino receiving in stead of a Pi, I get an extra meter, 1,5m now so still terrible. And 'as a bang on the fire arrow' as we say in Dutch, I now use two whip antenna's parallel to each other.
Before moving to fix the reception on my Pi, I now first try to maximize the reception on the receiving Arduino. This makes it much more simple to investigate.

**[update 2]**
After some more tests I got to about 6 meters range. When the transmitter is behind 1cm of wood, this goes back to 30cm.
My current 433MHz modules are going into the garbage bin, I thank you all for your time. I will look for a more stable alternative and maybe try some other/better433MHz modules like these: http://www.ebay.com/itm/433MHz-Superheterodyne-RF-Link-kits-3400-ARM-MCU-Transmitter-and-Reveiver-/281169560721?hash=item4177030491:g:SUcAAOxyaTxTRKJn

**[update 3]**
The new modules made an enormous change. I can now send my data from across my house with no problems at all. No ground plane (will try that TwoD!) yet. Still on 5V transmitter voltage!

I've asked a question before about my 433MHz setup so for full disclosure:
https://arduino.stackexchange.com/questions/17733/433mhz-sending-not-receiving

My current range is about 40/50cm, this is not much since I use a straight antenna ~17cm at the receiver and a coil antenna at the transmitter:
http://www.instructables.com/id/433-MHz-Coil-loaded-antenna/

These are the modules I use:
http://www.ebay.com/itm/-/221524421949?roken=cUgayN&soutkn=xKBBUo

And just FYI, I use these awesome working pumps:
http://www.ebay.com/itm/-/321779742264?roken=cUgayN&soutkn=hk1lrB

I have tried many antenna combinations and also upping the transmitter voltage to 12V but it doesn't help much. My aim is to reach 10m line of sight at the least.

 - I notice that my Pi outputs 4.77V to the receiver.
 - The 4 penlites now output around 5V so transmitter power is low.
 - What I also like to test is adding 10uF caps to the V and GND of the transmitter but I have to wait for them to get delivered.
 - I have the 10mw version of the transmitter, they may be just useless.
 - The receiver stands in front of a speaker and a subwoofer, I turn those off when I test.
 - The 433MHz modules came in pairs. I did not respect this and use any receiver with any transmitter, wonder if this is a problem. My end-goal is 3 transmitters on one receiver.
 - Since I have multiple Tx/Rx modules, I swapped them to exclude DOA modules.
 - Also tried these Helical antenna's, only made range worse; http://www.ebay.com/itm/-/171271811976?roken=cUgayN&soutkn=TmOnpH

My Arduino usses VirtualWire to send with 1000 baud to my Raspberry Pi, on the Pi side I use PIGPIO and the following code:

    if __name__ == "__main__":

       import time
       import datetime
       import pigpio
       import vw
       import json
       import requests
       from requests.auth import HTTPDigestAuth

       # Setup receiving 433MHz port
       RX=27

       # Setup Baud rate 433MHz
       BPS=1000

       # Connect to local Pi.
       pi = pigpio.pi()

       # Specify Pi, rx gpio, and baud.
       rx = vw.rx(pi, RX, BPS)

       # Empty message
       msg = 0

       # Save the time
       start = time.time()

       # Run for 3 seconds
       while (time.time()-start) < 36000:

          # Count msg per cycle
          msg += 1

          # Sleep for .4 second
          time.sleep(0.4)

          # Run while receiver is ready
          while rx.ready():

             # String join received characters into message
             message = ("".join(chr (c) for c in rx.get()))

             # Print the received message to screen
             print(message)

             # Create data dictionary
             data = {}
             data['meting']    = message[8:11]
             data['bericht']   = message[4:7]
             data['plant']     = message[1:3]
             data['timestamp'] = str(datetime.datetime.utcnow().isoformat())

             # Print the data to the screen
             print(data)

             # Setup filename for local data backup
             filename = str('data/' + data['plant'] + data['bericht'] + data['meting'] + '.json')

             # Write JSON data file to disk
             with open(filename, 'w') as outfile:
                json.dump(data, outfile)

             # Sending data
             url = 'http://server:8000/v1/documents?database=plantjes&extension=json'

             # Setup headers
             headers = {
                'Content-Type': 'application/json'
             }

             # Execute request
             r = requests.post(url, json = data, auth=HTTPDigestAuth('plantje', 'password'))

             # Print request response
             print r

       # Cancel the receiving of data
       rx.cancel()

       # Stop PIGPIO listening on pins
       pi.stop()

This script sends the measurement of the Hygro sensor to a database in JSON. This works like a charm.

The Arduino uses this code:

    #include <VirtualWire.h>
    #include <Sleep_n0m1.h>

    String pid = "p02";
    const int led_pin = 11;
    const int transmit_pin = 12;
    const int hygroSensor = 0;
    int hygroPower = 8;
    const int pump_pin = 5;
    int watering_level = 900;

    int count = 0;
    Sleep sleep;
    unsigned long sleepTime;

    void setup()
    {
      // serial console setup
      Serial.begin(9600);
      Serial.println("setting up");

      // cycle sleep time in ms
      sleepTime = 10000;

      // virtualwire setup
      vw_set_tx_pin(transmit_pin);

      // setting of pin modes
      pinMode(hygroPower, OUTPUT);
      pinMode(led_pin, OUTPUT);
      pinMode(pump_pin, OUTPUT);

      // Bits per sec
      vw_setup(1000);
    }

    void loop()
    {
      // delay to allow serial output to be ready after wake up
      delay(100);

      // cycle counter
      count++;

      // turn on hygro sensor module
      digitalWrite(hygroPower, HIGH);

      // wait a bit for hygro sensor to start
      delay(1000);

      // read the input on analog pin 0:
      int measure = analogRead(hygroSensor);

      // Start light to show transmitting
      digitalWrite(led_pin, HIGH);

      // log moment of sending
      Serial.println("Sending: " + String(measure));

      // create & send random message id
      String mid = "m" + String(random(100, 999));

      // Sending data
      String hygrodata = "d" + String(measure);
      dataSend(pid + mid + hygrodata);

      // Stop light to show transmitting
      digitalWrite(led_pin, LOW);

      // Wait a second
      delay(1000);

      // sleep code
      if(count >= 3)
      {
        // reset counter
        count = 0;

        // run pump routine
        //waterpump(measure, mid, pid);

        // log sleeping to serial console
        Serial.print("Going to sleep now..");

        // set sleep mode
        sleep.pwrDownMode();

        // turn off hygro module power
        digitalWrite(hygroPower, LOW);

        // sleep for: sleepTime
        sleep.sleepDelay(sleepTime);
      }
    }

    // Data sending funtion
    int dataSend(String data) {
      // declare int for length of message
      int msglen;

      // set length of message +1
      msglen = data.length() + 1;

      // declare array of characters
      char envelope[msglen];

      // put string in array
      data.toCharArray(envelope, msglen);

      // log data to serial monitor
      Serial.println(data);

      // send data
      vw_send((uint8_t *)envelope, sizeof(envelope));

      // wait for sending to finish
      vw_wait_tx();

      // return 1 for succes
      return 1;
    }

    // Pump function
    int waterpump(int measure, String mid, String pid) {
        // Log measure
        Serial.println(measure);

        // Water when needed
        if (measure > watering_level) {
          // Turn on pump 2 seconds
          digitalWrite(pump_pin, HIGH);
          delay(3000);
          digitalWrite(pump_pin, LOW);
          // Send pump data
          dataSend(pid + mid + "pump");
        }
    }

This controls the sensing of the messages and also the water pump I use to water my plant automagically when needed. This also works like a charm.

[![Arduino Hygo meter 433MHz setup][1]][1]
[![Raspberry Pi 433MHz receiver][2]][2]

  [1]: https://i.stack.imgur.com/CFJ3x.jpg
  [2]: https://i.stack.imgur.com/QIJ9k.jpg

body: Have you ever tried the Nordic nRF24L01 based modules? They are available on eBay for very low cost, and operate in the 2.4 GHz band.  They should offer a range of at least tens of meters indoors.  I have had good success with these, and they are very easy to interface to Arduino.


body:
I have the same TX/RX modules and two Arduinos and can get pretty good transmission reliability all throughout my house but it took some experimenting to figure out the largest factors in play (for me).

Module pairs should not matter, I got my 5 pairs jumbled up in a plastic bag, think only one was DOA. I use them together with Nexa wireless electric outlets and remotes since they operate on the same frequency and give me a decent reference point.

One thing I've noticed about the [receiver] modules is that they tend to auto-adjust to the signal strength. Blast at them with a transmitter at close range for a while and they will become worse at picking out the signs, from the noise at long range for some time. This appears to be true of the 433Mhz Nexa devices too.
When starting to transmit from further away, it may take longer before the receiver figures out it's found a signal.
Remember, these modules output only 1 or 0, not an analog signal, so they have to decide which level of noise to accept as 0 and when there is a 1.

My first mistake was not using a well attached antenna. A simple piece of strong wire is good enough in itself, but only if it makes good contact with the module. Good soldering skills always  recommended.

My second mistake was not giving the transmitter enough power. It can handle 12V, so give it 12V (not on the data pin!). Only go lower after you got it to work at the needed distance.

Try with a large ground plane for both transmitter and receiver (no contact with the device itself!). I got a very good range with my receiver on my computer case and the transmitter on my fridge!

I could even get a reliable reading from a temp sensor from inside the garage 10m away from the house when getting about 2m off the ground, using 17cm plain straight wires as antennas with good ground planes. (Monopoles antennas need ground planes to bounce the signal off.)

Try visualizing the signal on the receiving side with an oscilloscope. If you gave an analog receiver it's probably easier to tell apart noise and real data. But if all you got is the RX module, hooking up the data pin to some kind of logged visualization will at least let you see how difficult it is to spot the data patterns.

Try increasing the length of your preamble before the actual data. It'll let the receiver adjust before it gets to the interesting bits.

Repeat your transmitted data. Include a piece of id data which changes with each message, but not with each repetition, and store the last received id for comparison before relaying it to wherever.


body: The 433mhz modules can be sensible on the power lines, place a cap on the power input. Also a straight antenna works most of the times, but if you want some more distance, look into making a dipole antenna, there is a coil loaded diy antenna you can make that helps a little bit up from straight wire.


body:
I've had the same problem, couldn't get past 2 meters range.
Until i noticed that the TX-Frequency was off by about 150kHz.
I adjusted the RX Frequency (the module has a trimmer) and now 40-50m is possible with a wall in between.


body:
On the transmitting side (with cheap AC switches as receiver), I've actually had good results with the cheap green squares, and the equally cheap 5 for a dollar 'Helical antenna 433MHz' you find everywhere on ebay :)
I can reach all three levels of our house with that, and that's with only 5v supply on the green square, and it just sitting on a breadboard.

On request, picture of the antenna, soldered onto one of the cheap green  transmitters, this one works well for me on 5V:

[![Picture of antenna][1]][1]

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

This antenna was bought as a set of 5 from:
http://www.ebay.com/itm/171271811976

There's about 21 windings, with 5mm diameter, so that makes roughly 5mm * 3.14(=Pi) * 21 = 33 cm of wire in the coil.