body:
> With open source electronics, what is the difference between a clone, and a counterfeit?

**Counterfeit**: the vendor says/implies that the Arduino board is produced by Arduino/Genuino, an "original", but it is not. The screen-print is the same, but looking closer at the components and PCB there are some differences. You think you can turn to Arduino/Genuino for product support but you cannot.

**Clone**: the vendor states that the board is a "compatible copy", uses all the open-source bill-of-material, schematics, etc, (or slightly changed for cheaper components) when produced, and it is obviously not produced by Arduino/Genuino. You know that you cannot turn to Arduino/Genuino for product support.

The punishment for selling and buying (!!) counterfeit fashion in Italy is very severe.

Counterfeiting is [a trademark violation issue][1].

Cheers!

  [1]: http://www.inta.org/TrademarkBasics/FactSheets/Pages/Counterfeiting.aspx


sender: user

message:
When I call the tone function on a Uno, why do I not have to declare the pinmode in setup?

Like so:

    // Simplest tone
    void setup() {
    }

    void loop() {
        tone (8,500); //on pin 8 output 500 Hz
    }

sender: assistant

body:
Because the `tone(hertz)` code initializes the pinmode, along with the timer/counter control registers to produce the appropriate frequency.

    void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)
    {
      uint8_t prescalarbits = 0b001;
      long toggle_count = 0;
      uint32_t ocr = 0;
      int8_t _timer;

      _timer = toneBegin(_pin);

      if (_timer >= 0)
      {
        // Set the pinMode as OUTPUT
        pinMode(_pin, OUTPUT);
       ...

See [Tone.cpp - line 255](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Tone.cpp#L255) for the source.


message:
Arduino development vs nRF51 development

Originally I had an idea to develop an Arduino-compatible project using an **ATmega328P**, some sensors and the **nRF51822** as the BLE radio. As I progressed, I realized that if I relaxed the Arduino-compatible requirement, I could actually do away with the ATmega328P and write the application directly on the nRF51822 as it is a more capable MCU (32-bit, more memory, faster, has SPI, I2C and TTL serial, etc.) I'm not familiar with writing native applications for the nRF51822 but it seems much more complicated.

For someone that has experience in both platforms, can you please list some of the tradeoffs of developing using an ATmega328P for application + nRF51822 for radio and using the nRF51822 for both application and radio?

body:
First, there are various ports of the Arduino environment to the NRF51822, but I'll leave that aside for the moment and address using Nordic's codebase or the mbed one.

Generally speaking, one of these paths will put you more in the current "real world" of professional level embedded development, in which the ARM cortex parts play a leading role.  You will have conventional multiple source file projects tied together by more ordinary means such as a Makefile or explicit IDE configuration, rather than the rather oddball way the Arduino IDE has evolved to do things.  The basic lower level APIs you will be writing against will be much more conventional - ie, your code will start in `main()` rather than `setup()` and `loop()`, you will generate debug messages with `printf()` or similarly styled member function on mbed, rather than Arduino type `print()`/`println()` (though of course you can use `printf()` on an Arduino with some setup).  This tends to make it a lot easier to port or share code between this and other embedded systems, or even between an embedded system and a phone or desktop communicating with or simulating it.  Of course you can treat an Arduino as a plain ATmega and do this with that as well, up to the limits of the CPU and its memories.

People tend to think of the mbed option as being an online "toy" for certain boards, but you can generally use others just by setting it for a board using the same MCU in a similar way.  And in most cases you can download a zipfile of a project with a Makefile in it that will drive arm-gcc or a few other compiler choices.  The NRF51822 does come in varieties with different onboard storage sizes, and this can sometimes require care and attention to the linker script - in a few cases a project that fits in the online build (apparently with the Keil compilation engine as its backed) will not build in the downloaded GCC configuration unless you adjust the linker script to reduce the stack size, or perhaps change compiler optimization levels.

Countering reasons you might end up keeping the ATmega would be if you need some of its I/O peripherals or its 5v I/O capability.  For example, the NRF51822 has limited hardware PWM capability compared to an ATmega so that must generally be done in software.

If you are really at home with "The Arduino Way" switching to anything more traditional may take some adjustment of thinking and habits.  On the other had, if you look at the benefits of Arduino being the variety of works-out-of-the-box, easily modified examples you can use to explore the possibility of a project, but often find yourself annoyed by the legacy of its countless quirks and atypical approaches in the longer run, then you'll probably find the adaptation to using the NRF51822 directly to have been worthwhile.


message:
Multiple Wireless Sensors to an Arduino

I am looking for ideas on how to connect 12 sensors to an Arduino wirelessly.  The sensors will be about 10ft from the Arduino.  They need to send one byte of data every 100ms-250ms to the Arduino in an organized manner.

 - I have investigated MQTT and pubsubclient, but have not found a way to make an Arduino a Broker, and have been told it is very inefficient for my application.
 - I have looked at NRF24L01, but it appears to be limited to just 6 pipes to receive data in an organized fashion.
 - I researched Xbee, but have been told that it cannot keep up with the data rate.

Other suggestions are appreciated...  Thank you.

body:
It might be easiest to send a UDP packet over WiFi.  There is no extra packet overhead for this "connectionless" protocol: no OPEN, no ACK/NAK, no CLOSE, etc.  The incremental cost for additional bytes is very small, so if you decide you need to send 2 bytes, or even 100 bytes, it won't affect the throughput very much.

If you can "batch" the bytes, that would be even better.  For example, could you send 8 bytes per node, once every 800ms-2000ms?  If not, WiFi speeds should allow the single-byte UDP packet to get through without much latency.  Do you know what latency the receiver can accommodate?  You might get lower *average* latency with batched packets, depending on the network access time (i.e., how long it takes to hop on to the air).

A roll-your own approach would be to use a raw RF transmitter/receiver with something like VirtualWire.  With proper synchronization from the "master", the slaves could each have their own time slot, avoiding collisions (which keeps the network access time low)


body:
I would recommend the nRF24L01.

You don't need one pipe per node - just one pipe.

Each pipe is effectively an address that a node responds to - having multiple pipes means you can have multiple addresses on one node (like aliases) - but of course you only need one address per node, and hence one pipe per node.

The range is more than adequate (with the antenna version I have managed to get hundreds of meters no problem) and the price is so low as to be negligible.


body:
Use nRF24L01. To avoid collisions you can query the sensors (as Chris suggested in comment).
The setup would be:
Each sensor would have unique address. Central unit would transmit request and sensor node would respond to it. Central unit would have different address and all sensors would transmit to that address. You can also use data in ack to pack response.

* Central node (Addr0) -> Sensor 1 (Addr1): Request
* Sensor 1 (Addr1) -> Central node (Addr0): Response, sensor data
* Central node (Addr0) -> Sensor 2 (Addr2): Request
* Sensor 2 (Addr2) -> Central node (Addr0): Response, sensor data
* Central node (Addr0) -> Sensor 3 (Addr3): Request
* Sensor 3 (Addr3) -> Central node (Addr0): Response, sensor data
* ...


message:
How do I change pin assignments for the LUFA AVRISPMkII?

I just managed to get Dean Camera's LUFA AVRISP clone working on my Arduino Pro Micro, when to my dismay I found that to use PDI for my XMega, I need to have PD5 exposed for the clock source! The Pro Micro has PD5 connected to an LED, so I am not easily able to use it.

   If worst comes to worst, I can desolder the LED and wire a jumper, but that would be a pain in the butt. So I am wondering if any of you know if I can change the clock pin assignment from PD5 to PD6 or some other accesible pin. Thank you in advance for your help!

--[[ EDITS ]]--
Sorry for my lack of clarity, I am using the Pro Micro as the programmer, and the AVRISP clone supports PDI to the XMEGA. The 32u4 is actually directly supported by the programmer firmware. Here is what I am doing:

--[[ EDITS II ]]--
There is a schematic.. umm.. draw-o? I don't know but anyway the cathodes of D1 and D3 are NOT connected. That wire is an error.
<!-- 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/y1XxH.png)

<!-- End schematic -->

--Cantos

body:
Can you give more details on your problem? Schematics or something like that?

As I see from [here][1], the Arduino Pro Micro uses ATmega32u4 chip, which is not part of XMega family, so I'm not sure if their internals are mutually compatible. In any case, if you configure PD5 as an input for your clock, it will work as an input, since it's a GPIO pin `(DDRD &= ~(1<<PIN5))`. You'll just additionally have the LED blinking :). You can also configure PD6 as an input in the same way `(DDRD  &= ~(1<<PIN6))`.

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


body: I found the answer searching through the Doxygen files. I had to go to AppConfig.h under Config in the project root directory, and edit AUX_LINE_MASK to change the pin. Thanks to everyone who helped!


body:
just in case anyone else is trying to use a Pro Micro as a makeshift PDI programmer with the AVRISPMKII firmware included in the LUFA library: contrary to what the OP claims to have accomplished by editing AppConfig.h, it is NOT possible to reassign the XCK pin on ATMEGA devices (at least not to my knowledge). I can only conjecture as to why he made that claim (perhaps he confused XMEGA/ATMEGA, and thus ISP/PDI). I do not wish to blame the OP, but his post had sent me and others down a dead end for a minute, too bad there is no easy fix like that. :(

The XCK function is hard-wired to the pin, in this (ATMEGA32U4) case PD5. The LUFA code utilizes the ATMEGA's USART transmitter configured for synchronous operation, hence a clock signal must be provided to transfer data to the target device. That's why XCK must be used and there is no other way, at least not with LUFA. The call that enables the PDI target has nothing to do with the AUX_LINE define in AppConfig.h

The only way a Pro Micro board can be used is by either soldering a wire to the XCK pin or by holding a wire against it (if you can hold it steady for a couple of seconds without slipping, that is). Thus, if you need a makeshift PDI programmer that will not require soldering, get a Teensy 2.0 or something else that breaks out PD5 as a GPIO pin.


message:
Mysterious RX pulses on UART connect on OS X Arduino Due

Arduino IDE 1.6.8, Arduino Due, Mac OS 10.11.3

I am seeing eight mysterious pulses on the RX line when I connect to the serial port using multiple client libraries (Python, JavaScript as well as the built-in Serial Monitor in the IDE). About 78-79us apiece, sampled at 1MS/s with a Logic Pro 16.

[![Mystery pulses][1]][1]

These eight pulses when interpreted at 57600 baud will jam the Firmata firmware. And they happen on every connection.

This is using a new install of the Arduino 1.6.8 IDE and with multiple sketches (the normal "Blink" sketch will reproduce this also).

Repro steps on my machine:

1. Install any sketch
2. Start a logic analyzer if you want to catch it
3. Go to Serial Monitor. I have mine configured for 57600 baud, Newline line ending, but it doesn't matter
4. If you want, close and repeat step 3
5. Note pulses each time you connect to the serial port

Any suggestions for diagnosing this? It sounds like it's serial driver-level in some way.

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

body:
Short:

Looking at the ATMEGA16U2 firmware (https://github.com/arduino/ArduinoCore-sam/blob/master/firmwares/atmega16u2/arduino-usbserial/Arduino-usbserial.c) I find that, when you configure/change settings of the USB emulated serial port, the USART is resetted. This happens even when you open the Arduino Serial Monitor (it must configure the serial speed, etc.). This causes your spike.

Long:

Look at function:

`void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo)`

There you'll see that after some lines, it resets the USART, by zeroing its registers:

    /* Must turn off USART before reconfiguring it, otherwise incorrect operation may occur */
     UCSR1B = 0;
     UCSR1A = 0;
     UCSR1C = 0;

At page 168, of the current ATMEGA16U2 datasheet, you'll find that, by setting  UCSR1B's bit 3 (TXEN1), you enable the transmitter,  overriding the normal port operation (i.e. it becomes output). Quoting the datasheet:

> Writing this bit to one enables the USART Transmitter. The Transmitter
> will override normal port operation for the TxDn pin when enabled. The
> disabling of the Transmitter (writing TXENn to zero) will not become
> effective until ongoing and pending transmissions are completed, i.e.,
> when the Transmit Shift Register and Transmit Buffer Register do not
> contain data to be transmitted. When disabled, the Transmitter will no
> longer override the TxDn port.

Therefore, by writing `UCSR1B = 0;` you no longer override the TXD1 pin, which will act as input.

The ATMEGA16U2 TXD is connected to the ATSAM3X8E's RX line. In normal operation, with the UART enabled, that line stays high if no data is being transmitted. If you disable the UART, that particular line is no more driver to 1. Since the initialization code does not set the pull-up on that pin (and neither it's configured as output), the pin becomes a floating input, and any leakage to GND or even the input impedance of your probe (which is between your pin and GND), will slowly bring the logic level to 0.

To override this, problem, you should either:
1) Modify ATMEGA16U2 firmware, by setting that PIN as OUTPUT, with value 1.
2) Modify ATMEGA16U2 firmware, by enabling the pull-up on that pin.
3) (suggested) Enable the pull-up on the RX line on the ATSAM3X8E.


message:
How to convert String to byte array

I have the code, it's purpose is to receive the string from a comport like:
```Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456```
and translate it into four byte arrays ` byte user1[16], user2[16], pass1[16], pass2[16]`. Here's the code:

    String inString = ""; // COM port incoming data buffer

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      Serial.println("Start");
    }

    void loop() {
      // put your main code here, to run repeatedly:
      // Receive data from com port
      while (Serial.available() > 0) {
        int inChar = Serial.read();

        if (inChar != '\n') {
          inString += (char)inChar;
        } else {
          // New line
          String Action = inString.substring(0, 3);
          if (Action == "Set") {
            SetCard(inString);
          } else if (Action == "Get") {
            Serial.println("1");
          } else {
            Serial.println(Action);
          }
          inString = "";
        }
      }
    }

    void SetCard(String Data) {
      Serial.println(Data);
      // Data Set@user1@user2@pass1@pass2
      // Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
      byte user1[16], user2[16], pass1[16], pass2[16];

      String user1str = inString.substring(4, 20);
      String user2str = inString.substring(21, 37);
      String pass1str = inString.substring(38, 54);
      String pass2str = inString.substring(55, 71);

      Serial.println("Strings");
      Serial.println(user1str);
      Serial.println(user2str);
      Serial.println(pass1str);
      Serial.println(pass2str);

      Serial.println("Arrays");
      user1str.getBytes(user1, 16);
      user2str.getBytes(user2, 16);
      pass1str.getBytes(pass1, 16);
      pass2str.getBytes(pass2, 16);

      writeByteArray(user1, 16);
      writeByteArray(user2, 16);
      writeByteArray(pass1, 16);
      writeByteArray(pass2, 16);
    }

    void writeByteArray(byte array[], int arrlength)
    {
      for (int j = 0 ; j < arrlength ; j++) //print the block contents
      {
        Serial.write (array[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
      }
      Serial.println("");
    }

When I run this code and send my string through a com port I expect the output:

    Start
    Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
    Strings
    1234567890123456
    1234567890123456
    1234567890123456
    1234567890123456
    Arrays
    1234567890123456
    1234567890123456
    1234567890123456
    1234567890123456

And yet, I receive

    Start
    Set@1234567890123456@1234567890123456@1234567890123456@1234567890123456
    Strings
    1234567890123456
    1234567890123456
    1234567890123456
    1234567890123456
    Arrays
    123456789012345
    123456789012345
    123456789012345
    123456789012345

Why? And how do I receive desired output?
[getBytes docs][1]

  [1]: https://www.arduino.cc/en/Reference/StringGetBytes

body:
> Why? And how do I receive desired output? getBytes docs

The String member function [getBytes][1]() will null-terminate the string. You must add space for that.

      byte user1[17], user2[17], pass1[17], pass2[17];
      ...
      user1str.getBytes(user1, sizeof(user1));
      ...
      Serial.print((char*) user1);

That should do the trick.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WString.cpp#L547


body:
Using String.getBytes(buffer, len) to get bytes.

"len" is the length to copy, but usually need to add 1 for the end of string '\0'.

For example:

    String s = "123";
    int count = s.length();  // lenth() is 3
    s.getBytes(buffer, count);   // copied "12\0" => HEX(31 32 00)
    s.getBytes(buffer, count + 1);   // copied "123\0" => HEX(31 32 33 00)

The official document not mentioned those above, and it's not reasonable for the modern function design.

Misunderstanding in that and waste our life so much.


message:
ESP8266 blue led stays stays on

I have found a similar qustion to mine but there was no good response.

I've connected my ESP8266 to Arduino UNO.

Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).

I used AT+IPR=9600 command to change it.

After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor.

Note: I connected the esp8266 through a voltage regulator and a power source and both gave the same problem. My firmware is supposed to be updated so I don't think that it is the issue.

Could anyone please help me?

body: Did you change the firmware? I think Baud rate can be changed only if you flash it with newer version of the firmware.


message:
What does it mean in I2C, "NACK received"?

I am reading about I2C. On this site:

http://playground.arduino.cc/Main/WireLibraryDetailedReference#endTransmission

It says that `endTransmission()` can return one of the following status codes:

 * 0: Successful send.
 * 1: Send buffer too large for the twi buffer. This should not happen, as the TWI buffer length set in twi.h is equivalent to the send buffer length set in Wire.h.
 * 2: Address was sent and a NACK received. This is an issue, and the master should send a STOP condition.
 * 3: Data was sent and a NACK received. This means the slave has no more to send. The master can send a STOP condition, or a repeated START.
    4: Another twi error took place (eg, the master lost bus arbitration).

If I attach nothing to my Arduino (or with pull-up resistors to both SDA/SCL), I always get status 2. But how can a NACK (or anything) be received when there is nothing to communicate with? Does it mean something else?

Here is my example code

    #include "Wire.h"
    void setup() {
      Serial.begin(9600);
      Wire.begin();
    }
    void loop()  {
      Wire.beginTransmission(42);
      Wire.write(0);
      byte status = Wire.endTransmission();
      Serial.println(status); // always prints 2
    }

body:
A `NACK` is signaled by an acknowledgement slot in which `SDA` remains high while `SCL` cycles under control of the master.

Since high is the un-driven state of the pulled-up bus, in the absence of a peripheral at the selected address to positively acknowledge by pulling it down, a `NACK` condition will *passively* result.


message:
Sizing relays for audio circuit?

Non-technical person here, so please be gentle. I moved into a place that has ceiling speakers in each room (I tried, but they don't come apart, aren't marked other than manufacturer, and that is a company that went out of business 15+ years ago). So, let's assume they are 8 ohm speakers.

I have a media amplifier, and have successfully played music over all the speakers so I know that they work.

My wife would like the ability to select which speakers are on or off, so I'm thinking a quick Arduino project and relay board with 8-12 relays... but I'm not sure how to estimate the load, so I don't know how to appropriately size the relays.

Any suggestions on the best way to do this, or should I just get mains-rated relays and over-engineer the heck out of this?

body:
If you can estimate speaker power, it probably is reasonable to use the ordinary power formula P = I²R for estimating the current the relay needs to handle.  Typically, high-power speakers of a given kind are bigger than low-power speakers of the same kind.  But as you can see from pictures of
[5W](https://www.google.com/search?site=imghp&tbm=isch&source=hp&q=5w+speaker),
[10W](https://www.google.com/search?site=imghp&tbm=isch&source=hp&q=10w+speaker), and
[40W](https://www.google.com/search?site=imghp&tbm=isch&source=hp&q=40w+speaker) speakers, some 10W speakers are smaller than some 5W speakers, and some are bigger than 40W speakers, so power estimation based on speaker size can be difficult.

If you have access to the sound source (tuner or player or whatever, connected to an amplifier) you may find output power listed on the amplifier.

In any case, due to the I² term in the power formula, the range of current to plan for is relatively small.  For example, if 5W is going to an 8Ω speaker, 5/8 = I², and I =  0.79 A.  If it's 40W, then I = 2.24 A.  This range is likely to be handled ok by relays sold for ordinary use with Arduino systems.

*Note 1:* A relay's current rating ordinarily is derated significantly when the relay is used to switch DC or high-voltage AC.  Audio is low-voltage AC and relay derating probably isn't needed.  *Note 2:* The current a relay can safely switch in a live circuit may be much less than the unswitched current that closed contacts can carry.  This might not be a problem with low-voltage audio.  *Note 3:* Some commercial high-wattage audio distribution systems operate at higher voltages (see, eg, wikipedia's [high-voltage audio distribution systems](https://en.wikipedia.org/wiki/Constant-voltage_speaker_system) article, re 70.7 V etc systems); if you have one of those – as amplifier labeling might reveal – the example calculations shown above would need adapting.


message:
Comparison of a bit vs. setting a bit

Simple question really, I just want to be sure that I understand it correctly. I understand this isn't necessarily Arduino specific.

With regards to the ATmega2560 I'm doing 3 back-to-back A/D conversions - one immediately after the previous finishes. I'm accomplishing this by calling a Single Conversion each time.

I stumbled across this useful code to wait for the conversion to finish:

    while(ADCSRA & (1<<ADSC))

I understand that it is waiting for the conversion to finish and that when this is done the ADSC will be set to 0. (Conversely, I could wait for ADIF to be set to 1.) I'm not as clear on how exactly this line is interpreted.

Normally when I see something along the lines of `(1<<ADSC)` it means write a 1 to the ADSC bit.

But, in this instance, that isn't the case.

Why not just write:

    while(ADSC);

body:
You misunderstand the meaning of:

    1 << ADSC

That actually means *Bit-shift 1 left by the number of bits specified by the value ADSC*.

`ADSC` in this case is 6:

    #define ADSC    6

So if you did:

    while(ADSC);

you would actually be doing:

    while(6);

Which of course will never end, since 6 is not 0, so is true.

Instead you shift 1 left 6 times, which in binary would be:

    00000001
        << 6
    01000000

That, of course, is 64, or 0x40 in hexadecimal.  That is then ANDed with the value of the ADCSRA register to return the value of one single bit within that register.  It's then the result of that AND that you control the `while` with.  So it ends up as:

    while(ADCSRA & 0x40);

Which will either equate to:

    while(0x40);

if the 7th bit is set, or if it's not set:

    while(0x00);

And since 0x00 is 0 it will equate to false when the bit isn't set and the `while` will finish.


message:
Failed to read DHT22 sensor using Intel Galileo Gen2 board

Why do I end up with the display

> Failed to read from DHT sensor!

in the serial monitor in most cases when I run the code given below? When I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false. Any help would be highly appreciated.

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

    // Example testing sketch for various DHT humidity/temperature sensors
    // Written by ladyada, public domain

    #include "DHT.h"

    #define DHTPIN 2     // what pin we're connected to

    // Uncomment whatever type you're using!
    //#define DHTTYPE DHT11   // DHT 11
    #define DHTTYPE DHT22   // DHT 22  (AM2302)
    //#define DHTTYPE DHT21   // DHT 21 (AM2301)

    // Initialize DHT sensor for normal 16mhz Arduino
    DHT dht(DHTPIN, DHTTYPE);
    // NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
    // might need to increase the threshold for cycle counts considered a 1 or 0.
    // You can do this by passing a 3rd parameter for this threshold.  It's a bit
    // of fiddling to find the right value, but in general the faster the CPU the
    // higher the value.  The default for a 16mhz AVR is a value of 6.  For an
    // Arduino Due that runs at 84mhz a value of 30 works.
    // Example to initialize DHT sensor for Arduino Due:
    //DHT dht(DHTPIN, DHTTYPE, 30);

    void setup() {
      Serial.begin(9600);
      Serial.println("DHTxx test!");

      dht.begin();
    }

    void loop() {
      // Wait a few seconds between measurements.
      delay(2000);

      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit
      float f = dht.readTemperature(true);

      // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }

      // Compute heat index
      // Must send in temp in Fahrenheit!
      float hi = dht.computeHeatIndex(f, h);

      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print(f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(hi);
      Serial.println(" *F");
    }

body:
The [article][1] link by Nick is the same that I found, so it must be a well search problem.

What is described on the Intel forum is that the Galileo is not capable of direct communication with the sensor as it is a computer and not a microcontroller, so therefore lacks the ability for accurate timing required by the sensor and also the DHT* is considered a peripheral and would thus require a way to interface with the "PC".

What is described in the post is to use two pins to create the proper digital signal for the DHT.

The circuit makes use of a diode to protect the output pin.

The OP on the forum describes the connections like this:

>Pin 2 of Galileo is connected to the data pin of the DHT11.
>
> Cathode of the diode is connected to pin 3 of the Galileo.
>
> Anode of the diode is connected to the DHT11 data pin.

The diode would be a standard diode, possibly a fast switching signal diode as the 1N4143. The resistor would be the standard pull up resistor of 10K Ohms.

Here is the OPs schematic:

[![enter image description here][2]][2]
<sub>(source: [intel.com](https://communities.intel.com/servlet/JiveServlet/downloadImage/2-245223-237707/DHTGal.PNG))</sub>

You will also need to make use of the code linked to by the OP in the linked post as it was modified to work with the workaround.

  [1]: https://communities.intel.com/thread/53869?tstart=0
  [2]: https://i.stack.imgur.com/ZvYzB.png


message:
How can there be not enough current?

I am new to the Arduino world. I have a question regarding current that the Arduino outputs over its 5V port. Why is the current in the Arduino too weak for current hungry circuit when the only thing that changes in this equation `V=IR` is the current itself.

For instance, the voltage in an Arduino is restricted to 5 volts. Assuming that the resistance of the current stays the same, shouldn't the current also increase (following Ohm's law) over its 5V port? More specifically, I am talking about powering ESP8266 with an Arduino.

body:
The problem is not that "there is not enough current", but that you can't dissipate enough power.

Let's assume you are powering the board from an external 12V supply. Now, the 5V are obtained from 12V with a resistive regulator: this means that the regulator (see [this image][1] if you are interested in knowing what component it is) simply behaves like a variable resistor, dissipating the power in excess. Now, let's assume you want to draw 4A from the 5V rail, since you want to turn on a lot of LEDs and other stuff. Since P=VI, the regulator (that very little component) has to dissipate (12V-5V)*4A = almost 30W. This means that it becomes a little heater and.. Puff! it breaks.

Now, 4A is a really high current, but that regulator can withstand very little power dissipations. According to the datasheet, and estimating a 1cm x 2cm heatsing under it, we can estimate a 25 K/W thermal resistance, which means that each watt you dissipate raises the internal temperature by 25K (=25°C). You can't go beyond 150°C without damaging the component, which means that if your room is at 25°C you can dissipate AT MOST 5W. In practice, never go beyond 3W. Anyway even 5W mean that, at 12V, you can't get more than 5W/7V=0.7A.

By the way, the regulator is rated 0.8A, so you should never go beyond that value in any case.

Now, this was the external regulator. As for the usb, you can't get more than 500mA from that power supply. That's written in the specs. For this reason, a 500mA fuse is on that rail, so going beyond 500mA will blow that one, interrupting your power. Well, that's a self-healing fuse, so after some time (maybe hours?) it will operate again, but.. Don't try that.

In the end, the digital pin current. The atmega datasheet says that

 1. The absolute maximum current per I/O Pin is 40.0mA
 2. The absolute maximum current inside VCC and GND Pins is 200.0mA

This means that from each single pin you can get at most 40mA (but I suggest you never go beyond 20mA), and the sum of all the currents (and the internal peripherals) should never exceed 200mA. So if you need to power 2 leds, you can give each of them 20mA, if you need to power 15 of them you can't (you are limited to, let's say, 10mA). If you need more, use transistors to separate the current paths.

  [1]: http://3.bp.blogspot.com/-msRgadfnk34/UvaZ1EEyTXI/AAAAAAAAAuM/DvSoiyw2Mu8/s1600/Arduino+uno+w-circled+voltage+regulator.PNG


body:
A very simple answer:  The Arduino is limited to an absolute 40mA per pin, because within the controller chip (ATMega328 usually) the path the current follows is very small.  More current can destroy the tiny transistors in the chip.  Best case, you burn out that pin.

If you have a problem that requires more than 40mA (and really, as other posters point out, 20mA!) you should be using a transistor, mosfet or relay controlled by the Arduino, rather than directly power the end device.


message:
Arduino digital input fluctuates with neighbouring pins

I am using digital pins (2,3,4,5) to play midi notes on and off with 3pdt switches with pull down 10k resistor between input pin and ground.

However when I press button 2 randomly at different time interval it sometimes shows pin 3 high in the monitor. (after reading forums here I have realised that it might be due to big switches that I am using where the physical contact plates might be reason for this). I have even changed wires and isolated them from each other to rule out the noise from the wires.
I have checked all the connections and soldered the Arduino board pins with best possible skills that I have and tracks are all clear.

Same case occurs between other buttons as but its not always.
However after reading about Debounce I have made changes to the code as following, now I got the error only once after that I havent seen it. Can someone have look at the code and advice me if I have assigned Debounce function to multiple switches correctly and if not, what should it be as I am new with coding
Since I am using 3pdt switch I have added switch mode..

    #include <MIDI.h>

    int buttonPin[] = {2, 3, 4, 5};
    byte mode[] = {0, 0 , 0 ,0};
    boolean currentState = LOW;
    boolean lastState = LOW;
    int buttonPinM[] = {6, 7, 8, 9};
    byte mode1[] = {0, 0, 0, 0};

    boolean currentState1 = LOW;
    boolean lastState1 = LOW;

    long lastDebounceTime = 0;
    long debounceDelay = 50;

    void setup (){
     MIDI.begin(MIDI_CHANNEL_OMNI);

     int i;
     for (i = 0; i < 4; i++) {
      pinMode(buttonPin[i], INPUT);
     }
     int j;
     for (j = 0; j < 4; j++) {
      pinMode(buttonPinM[j], INPUT);
     }

     {
      int i;
      for (i = 0; i < 4; i++);
     }
     {
      int j;
      for (j = 0; j < 4; j++);
     }
    }

    // This will track which pin/mode we're using

    int j = 0;
    int i = 0;

    void loop () {
     {
      currentState = digitalRead(buttonPin[i]);

      if ( (millis() - lastDebounceTime) > debounceDelay) {
       switch (mode[i]) {
        case 0:
         if (currentState == HIGH) {
          MIDI.sendNoteOff (i+55, 0, 1);
          mode[i] = 1;
          lastDebounceTime = millis();
         }
         break;
        case 1:
         if (currentState == HIGH)
          mode[i] = 2;
         break;
        case 2:
         if (currentState == LOW) {
          MIDI.sendNoteOn (i+55, 127, 1);
          mode[i] = 3;
          lastDebounceTime = millis();
         }
         break;
        case 3:
         if (currentState == LOW)
          mode[i] = 0;
         break;
       }
      }
      lastState = currentState;
      if (++i > 3)
       i = 0;
     }
     {
      currentState1 = digitalRead(buttonPinM[j]);
      if ( (millis() - lastDebounceTime) > debounceDelay) {
       switch (mode1[j]) {
        case 0:
         if (currentState1 == HIGH ) {
          MIDI.sendNoteOn (j+61, 127, 1);
          mode1[j] = 1;
          lastDebounceTime = millis();
         }
         break;
        case 1:
         if (currentState1 == HIGH)
          mode1[j] = 2;
         break;
        case 2:
         if (currentState1 == LOW) {
          MIDI.sendNoteOff (j+61, 0, 1);
          mode1[j] = 3;
          lastDebounceTime = millis();
         }
         break;
        case 3:
         if (currentState1 == LOW)
          mode1[j] = 0;
        break;
       }
      }
      lastState1 = currentState1;
      if (++j > 3)
       j = 0;
     }
    }

body:
Posting here since it is quite long, but it's not a complete answer, just a few thoughts and a possible improvement.

Ok, so there are a couple of things in your code I don't understand:

**1: in the setup()**

 {
  int i;
  for (i = 0; i < 4; i++);
 }
 {
  int j;
  for (j = 0; j < 4; j++);
 }

What are these for?

**2: debouncing**

You are not implementing it correctly, at least not for me. You are reading the button every 50ms, without debouncing. Ok, you won't see "bounces", but there are better solutions (see later).

**3: modes 1 and 3**

They are quite useless. What are they for?

**4: pins 6,7,8,9**

What are they for?

**5: variable laststate**

What is it for? You never use it

**6: updating one button per loop**

Is it needed? I mean, you are just updating one button per loop instead of all of them for each loop.

**In the end**

Ok, now my suggestions, apart from learning to indent the code (otherwise it's impossible to read it): I always use the bounce2 class to debounce a button, since it contains everything inside and.. Well, it works well. It can also detect the rising and falling edges of the button, thing that you need if I interpreted correctly your code.

One more thing: debounce delay can be lowered (even to just 5ms):

    #include <MIDI.h>
    #include <Bounce2.h>

    int buttonPin[] = {2, 3, 4, 5};
    int buttonPinM[] = {6, 7, 8, 9};

    Bounce debouncers[4];
    Bounce debouncersM[4];

    int debounceDelay = 50; // Usually is lower - even 5ms is fine
    uint8_t i = 0;

    void setup ()
    {
     MIDI.begin(MIDI_CHANNEL_OMNI);

     for (i = 0; i < 4; i++)
     {
      pinMode(buttonPin[i], INPUT);
      debouncers[i].attach(buttonPin[i]);
      debouncers[i].interval(debounceDelay);

      pinMode(buttonPinM[i], INPUT);
      debouncersM[i].attach(buttonPinM[i]);
      debouncersM[i].interval(debounceDelay);
     }
    }

    void loop ()
    {
     for (i = 0; i < 4; i++)
     {
      debouncers[i].update();
      debouncersM[i].update();
     }

     for (i = 0; i < 4; i++)
     {
      if (debouncers[i].rose()) // button i switched from 0 to 1
       MIDI.sendNoteOff(i+55, 0, 1);
      if (debouncers[i].fell()) // button i switched from 1 to 0
       MIDI.sendNoteOn (i+55, 127, 1);
      if (debouncersM[i].rose()) // button i switched from 0 to 1
       MIDI.sendNoteOn (i+61, 127, 1);
      if (debouncersM[i].fell()) // button i switched from 1 to 0
       MIDI.sendNoteOff(i+61, 0, 1);
     }
    }


message:
Issues on Arduino, LiPO battery and two mottors setup

My main objective with this project was to control these two DC motors with an Arduino Nano (it is not a UNO), powered by a 3-Cell 750mAh LiPO battery (both the motors as the Arduino itself). So, I came up with something like this (it is a simplified version):

[![Simplified version of circuit.][1]][1]

If the load on the two mottors rise, could the Arduino be damaged by this current increase? Is the voltage too high for the Arduino handle? Is there any more issues that this setup can have?

When searching, I found that it would be wise to get a fuse between the power supply and the arduino (before reaching Vin). Is that necessary?

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

body:
> If the load on the two motors rise, could the Arduino be damaged by this current increase?

No, the motor current doesn't pass through the Arduino. It is completely separate.

> Is the voltage too high for the Arduino handle?

Borderline. The regulator (a lowly 7805) may well get very hot at that voltage (depending on the Arduino's current draw) and go into thermal shutdown.

> Is there any more issues that this setup can have?

Maybe add a small buck regulator to the 5V pin instead of using the on-board linear regulator. That will not overheat and will be far more efficient making your batteries last longer. Often marketed as "UBEC" (Universal Battery Elimination Circuit) and used throughout the model vehicle industry these are very easy to get hold of and are ideal for powering things like Arduinos from batteries like this.


message:
Water pressure an salinity sensor connected to arduino

I am trying to design a project that Arduino would have connected water and salinity sensor, would be packed in a special box be droped into ocean up to 500 meters. What sensors should I use and how should they be conencted. I assume that I would need professional equipment, not chineese stuff from ebay.
Hardware needs to be able to work under 50*C and up to 50bar

Update:

Budget is about up to 400 pounds for sensors.
Resolution of pressure 0 to 100 bar
Resolution of salinity doesnt matter so much. Few percents of mistake, just to measure it somehow

body:
I suggest that you look for a sensor from Honeywell. The problem is that the pressure is very high for a board mounted sensor and the atmospheric pressure is varying. The board mounted sensors measure a maximum of 10 bar.  It is not clear what accuracy you require. Is there a connection to the surface? If so you should measure differential pressure between the seabed and the surface.  Can you be content with a maximum depth of 100 m?

I don't think salinity varies much offshore so it might not be worth measuring.


message:
Arduino and DC Motor control board

I've this [PWM Module - 6V-90V 15A Pulse Width PWM DC Motor Speed Controller Switch][1] which I use to control a peristaltic pump (ordinary DC motor), now I want to replace the potentiometer with an Arduino in order to create a soft-start for the pump by pressing a button.
The control is a 0-5V input from the potentiometer, and the description says "_you can external drive_" and "_It could use of PLC controls speed of motor_", unfortunately I cannot provide datasheets or schematics.

Is it possible? Or I need a digital pot?

How should I wire it? The 3 cables from the board to the pot are: **ground, 0-5V and 5V**

  [1]: http://m.aliexpress.com/item/32584436489.html

body:
Functionally you can replace the potmeter with a digital potmeter.
If your arduino runs on 5 volt, you can simply connect the grounds and the wire connected to the middle of the pot to a pwm pin.
If the pwm pin does not work smoothly use a RC filter. That is a resis  tor and a capacitor.  As explained here [instructables][1]
If your arduino runs on 3.3 you can still use the rc filter but you need to add a bridge.

  [1]: http://www.instructables.com/id/Analog-Output-Convert-PWM-to-Voltage/


body:
Or you may exchange the whole controller with a power mosfet module connected to your arduino. And use pwm directly from your arduino.
http://store.arduino.cc/product/T010020


message:
Compare the new sample in a high sampling rate datalogger

I am using sdFat library the analog bin logger example,

[Github: SdFat/SdFat/examples/AnalogBinLogger/
][1]

The program is working fine and every thing but the thing is, this high speed datalogger uses interrupts and timers to make the ADC work at a pre-determined sampling frequency and it DOES NOT use the normal `analogRead ()`

What I want is, when the input of some analog pin is bellow a pre-determined value, I want to write HIGH or LOW to some digital pin,
my question is, how can I compare the new sample in the analog bin logger example as I simply want to compare the new sample as in:

    if ( analogRead() < 256 ) {// do something}

knowing that there is no analogRead() in the program because it uses timers and interrupts.

  [1]: https://github.com/greiman/SdFat/tree/master/SdFat/examples/AnalogBinLogger

body:
In the function

    ISR(ADC_vect) {

the variable `d` contains the current sample:

      // Read ADC data.
    #if RECORD_EIGHT_BITS
      uint8_t d = ADCH;
    #else  // RECORD_EIGHT_BITS
      // This will access ADCL first.
      uint16_t d = ADC;
    #endif  // RECORD_EIGHT_BITS

So you can just "do something" depending on what is in `d`.  Of course, since this is a timer interrupt you have limited time to do anything, so you need to make sure that whatever you do is fast and efficient - so really you want to be using direct port access instead of digitalWrite().


message:
Why perform bitwise operations here? (SPI FRAM read method)

See: https://github.com/adafruit/Adafruit_FRAM_SPI/blob/master/Adafruit_FRAM_SPI.cpp
The following method reads and converts the input to 8 bit. I have several questions concerning its function.

Using addr = 0xFFFF as an example, the method converts the variable to 0xFF. I understand that bits are removed from the end, but surely 65535 != 255. Perhaps relatively, to their max size, but how is this a useful conversion? I might be missing something about bitwise here..

    uint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)
    {
     digitalWrite(_cs, LOW);
     SPItransfer(OPCODE_READ); //read memory from fram array (2-byte)
     SPItransfer((uint8_t)(addr >> 8));
     SPItransfer((uint8_t)(addr & 0xFF));
     uint8_t x = SPItransfer(0);
     digitalWrite(_cs, HIGH);
     return x;
    }

Correct me if I'm wrong, the casting is to keep sign extension from occurring.

The masking I understand in theory, but do not at all understand its application here.

Finally, it always returns the same value x = 0, why?

I also see there's a write method but no read method. Only read8. Reasoning?

body:
Let's assume `addr` is `0xbeef`. Then, if we break down each operation:

    expression             │ value
    ───────────────────────┼───────
    addr                   │ 0xbeef
    addr >> 8              │ 0x00be
    (uint8_t)(addr >> 8)   │   0xbe
    addr & 0xFF            │ 0x00ef
    (uint8_t)(addr & 0xFF) │   0xef

So this is essentially breaking down the address into two 8-bit chunks,
and transmitting those chunks individually. It's done like this because
SPI only transmits bytes.

> the casting is to keep sign extension from occurring.

Non, sign extension cannot occur, since `addr` is an unsigned number.
The casting really serves no useful purpose, other than documenting the
code. It would be done implicitly simply because `SPItransfer()` takes
an `uint8_t` argument. The casting _could_ be useful if `SPItransfer()`
was overloaded with a 16-bit version.

> Finally, it always returns the same value x = 0, why?

No, it returns whatever the call to `SPItransfer(0);` returns, i.e. the
data sent by the FRAM module.


message:
Controlling HDMI Switch via RS232/UART

Problem:

I have an HDMI switch that is controllable via RS232

- Scenario 1:
    - Setup: PC connected to HDMI switch using USB -> serial adapter
    - Test: Opening PuTTY on COM port and sending command "sw i01" from my PC
    - Results: HDMI switch input changes to port 1 [Good]
- Scenario 2:
    - Setup: Arduino UART port connected to TTL->RS232 adapter connected to serial->USB adapter connected to PC with PuTTY program open on COM port
    - Test: Sending command "sw i01" from Arduino to PC using code below
    - Results: "sw i01" prints repeatedly on the Putty terminal [Good]
- Scenario 3:
    - Setup: Arduino UART port connected to TTL->RS232 adapter connected to HDMI switch serial port
    - Test: Sending "sw i01" from Arduino repeatedly to HDMI switch using code below
    - Results: HDMI port does not switch from port2 to port1 [Bad]

Hardware:

- Intel Galileo Gen 2
- SparkFunRS232/TTL Shifter connected to Galileo UART
- HDMI switch is IOGear GHSW8141

Code:

[Note: Galileo Gen 2 requires Serial1 for UART communication]

    void setup() {
        Serial1.begin(19200);
    }

    void loop() {
        Serial1.print("sw i01");
        Serial1.write(13);    // CR
        Serial1.write(10);    // LF
        delay(1000);
    }

Question:

It seems like Scenario 1 and 2 confirm that the Arduino->HDMI switch communication should work, but it doesn't. Am I missing something regarding physical connectivity? Does manually typing "sw i01" in PuTTY send different commands than I have in the Arduino code?

body:
Your HDMI switcher, and your USB to RS-232 converter speak RS-232.  The Arduino speaks TTL UART.

While the concept behind them, and the overall format of the data, is the same there are major differences:

* RS-232 uses a ±10V NRZ signalling method, TTL UART uses a 0-5V signalling method
* RS-232 uses inverse logic compared to TTL UART

That means that you need to convert the Arduino's TTL UART to ±10V NRZ with inverse logic in order to communicate with the IOGear.

Fortunately that's a simple enough task using a special interface chip. These are readily available and can be bought for tiny amounts as a breakout board or even a full shield if you like (such as [this one from Sparkfun](https://www.sparkfun.com/products/13029)).  The chip is known as a **MAX232** in its most common form, though other manufacturers may use different letters.

If you pop on eBay (or your favourite budget seller site) and search for "Arduino MAX232 DB9" (the DB9 is the type of plug on the board - the 9-pin D connector) you will get lots of hits to choose from.


body:
I found it is was related to the physical connection!

In Scenario 3, I originally had the Sparkfun TTL/RS232 adapter that had a female DB9 connector wired to the HDMI switch female DB9 connector using a male/male serial cable. The serial cable I bought was a straight through cable.

I swapped it out with a null modem cable and it worked right away.

Looking at the wiring diagram, I thought swapping the Tx/Rx pins on the Sparkfun adapter would have achieved the same result as the null modem cable, but apparently not.

If anybody can point out why the null modem cable made the difference, that would be something good to know for the future.


message:
Running Steppers with servo

I'm doing a project which is automatic box carrier. It will hold a box from a location and move it next to it. Kind of cnc work. Locations are fixed it just has to run the orders. I want to send an array of integers and manage them in the switch under main loop. for example

<!-- language: c -->

      orders[0]=2;
      orders[1]=2000;

      orders[2]=3;
      orders[3]=60;

      orders[4]=1;
      orders[5]=7000;

      orders[6]=2;
      orders[7]=2000;

      orders[8]=3;
      orders[9]=90;

      orders[10]=1;
      orders[11]=2000;
will be my orders array and here is the code i want to run. When I upload code to arduino steppers and servo doing fine until orders[8]. When came to that order; first servo goes to 30 degrees then goes to 0 and click sound starts. After that steppers are not doing remaining steps.

<!-- language: c -->

    #include <Servo.h>
    Servo myservo;

    int distance=0;
    int code =0;
    int orders[10]={};
    int thisStep=0;
    int thisVal=1;
    int pos = 0;
    int currpos=90;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);

      pinMode(2,OUTPUT);
      pinMode(3,OUTPUT);
      pinMode(4,OUTPUT);
      pinMode(5,OUTPUT);
      digitalWrite(2,LOW);
      digitalWrite(3,LOW);
      digitalWrite(4,LOW);
      digitalWrite(5,LOW);
      myservo.attach(9);

      orders[0]=2;
      orders[1]=7000;

      orders[2]=3;
      orders[3]=60;

      orders[4]=1;
      orders[5]=2000;

      orders[6]=2;
      orders[7]=2000;

      orders[8]=3;
      orders[9]=30;

      orders[10]=1;
      orders[11]=2000;

     /* orders[12]=2;
      orders[13]=5000;*/
    }

    void loop() {

      code = orders[thisStep];
      switch (code){
        case 1:

        go(orders[thisVal]);
        thisStep = thisStep + 2;
      thisVal = thisVal + 2;

        break;
        case 2:
         Serial.println(thisVal);
        goReverse(orders[thisVal]);
        thisStep = thisStep + 2;
        thisVal = thisVal + 2;

        break;

        case 3:
        goServo(orders[thisVal]);
        thisStep = thisStep + 2;
        thisVal = thisVal + 2;
        break;
      }

    }
    void go(int dist){
      digitalWrite(2,LOW);
      digitalWrite(4,LOW);
      do{
      digitalWrite(3,HIGH);
      digitalWrite(5,HIGH);
      delayMicroseconds(10);
      digitalWrite(3,LOW);
      digitalWrite(5,LOW);
      delayMicroseconds(10);
      distance = distance+1;
      Serial.println(distance);
      }while (dist>distance);
     distance=0;
     delay(500);
    }
    void goReverse(int dist){
      digitalWrite(2,HIGH);
      digitalWrite(4,HIGH);
      do{
      digitalWrite(3,HIGH);
      digitalWrite(5,HIGH);
      delayMicroseconds(300);
      digitalWrite(3,LOW);
      digitalWrite(5,LOW);
      delayMicroseconds(300);
      distance = distance+1;

      }while (dist>distance);
      distance=0;
      delay(500);
    }

    void goServo (int degree){
      myservo.attach(9);
      myservo.write(degree);

      delay(300);
       myservo.detach();
      /*if (currpos > degree)
      {
        for (pos = currpos; pos >= degree; pos -= 1) { // goes from 0 degrees to 180 degrees
          // in steps of 1 degree
           myservo.write(pos);              // tell servo to go to position in variable 'pos'
           delay(15);
           // waits 15ms for the servo to reach the position
          }
          delay(500);
      }
      else if (currpos < degree)
      {
        for (pos = currpos; pos <= degree; pos += 1) { // goes from 0 degrees to 180 degrees
          // in steps of 1 degree
           myservo.write(pos);              // tell servo to go to position in variable 'pos'
           delay(15);
           // waits 15ms for the servo to reach the position
          }

      }
      currpos=degree;

    */

    }

Thanks.

body:
Your problem here is that you have an array of 10 bytes, which works fine, only that in your loop you don't stop or check that you are within that array.

If this is supposed to run forever, you could add a line like this at the end of your loop:

    if (thisStep > sizeof(orders)-1) thisStep = 0;

(-1 because you have an array of 10, which are from 0-9, sizeof will return 10)

this will make it start from the beginning again.


message:
Uploading code to Arduino wirelessly

I have been working on a project watch which would work best if it is entirely sealed (to waterproof it). The watch may need future updates, but I will be unable to send code to it using a usb connector or isp programmer without opening the case. What is the best way to connect my PC with this watch wirelessly?

I gather that the serial ports are usually used to send code via the usb, and that most Bluetooth modules use serial coms to communicate with the Arduino.

The Arduino that I am using is an Arduino Pro Mini clone.

Any help will be greatly appreciated.

body:
You could use ESP8266 and [ESP-LINK][1] firmware to update the arduino firmware over the wire. Its also enables you to debug it wirelessly. What it does is provide a serial link but over wifi. Just like connecting it via cable.

  [1]: https://github.com/jeelabs/esp-link


message:
RFID detects the first card fine, but hangs on a second

I am writing a program that:

 1. Reads string (one line) from com port
 2. Waits for an RFID card to be present
 3. Reads a block from the card

Here's the code (it uses [this][1] MFRC522 library, also the code is based on makecourse.com  RFID tutorial):

<!-- language: c -->

    #include <SPI.h> //include the SPI bus library
    #include <MFRC522.h> //include the RFID reader library

    #define SS_PIN 10  //slave select pin
    #define RST_PIN 9  //reset pin
    MFRC522 mfrc522(SS_PIN, RST_PIN);        // instatiate a MFRC522 reader object.
    MFRC522::MIFARE_Key key; //create a MIFARE_Key struct named 'key', which will hold the card information

    byte readbackblock[18]; //This array is used for reading out a block. The MIFARE_Read method requires a buffer that is at least 18 bytes to hold the 16 bytes of a block.

    String inString = ""; // COM port incoming data buffer

    void setup() {
      Serial.begin(9600);        // Initialize serial communications with the PC
      SPI.begin();               // Init SPI bus
      mfrc522.PCD_Init();        // Init MFRC522 card (in case you wonder what PCD means: proximity coupling device)
      Serial.println("Scan a MIFARE Classic card");

      // Prepare the security key for the read and write functions - all six key bytes are set to 0xFF at chip delivery from the factory.
      // Since the cards in the kit are new and the keys were never defined, they are 0xFF
      // if we had a card that was programmed by someone else, we would need to know the key to be able to access it. This key would then need to be stored in 'key' instead.

      for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;//keyByte is defined in the "MIFARE_Key" 'struct' definition in the .h file of the library
      }

    }

    void loop() {
      while (Serial.available() > 0) {
        int inChar = Serial.read();

        if (inChar != '\n') {
          inString += (char)inChar;
        } else {
          // New line

          Serial.println("Start");
          while (!initcard()); // Detecting new card
          Serial.println("CardFound");
          readBlockToCom(2); // Reading a block
          Serial.println("Done");
          inString = "";
        }
      }
    }

    bool initcard()
    {
      // Look for new cards (in case you wonder what PICC means: proximity integrated circuit card)
      if ( ! mfrc522.PICC_IsNewCardPresent()) {//if PICC_IsNewCardPresent returns 1, a new card has been found and we continue
        return false; //if it did not find a new card is returns a '0' and we return to the start of the loop
      }

      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {//if PICC_ReadCardSerial returns 1, the "uid" struct (see MFRC522.h lines 238-45)) contains the ID of the read card.
        return false; //if it returns a '0' something went wrong and we return to the start of the loop
      }
      return true;
    }

    void readBlockToCom(int number)
    {
      readBlock(number, readbackblock);//read the block back
      Serial.print("read block: ");
      for (int j = 0 ; j < 16 ; j++) //print the block contents
      {
        Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
      }
      Serial.println("");
    }

    int readBlock(int blockNumber, byte arrayAddress[])
    {
      int largestModulo4Number=blockNumber/4*4;
      int trailerBlock=largestModulo4Number+3;//determine trailer block for the sector

      /*****************************************authentication of the desired block for access***********************************************************/
      byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
      //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
      //this method is used to authenticate a certain block for writing or reading
      //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A = 0x60 (=1100000),  // this command performs authentication with Key A
      //blockAddr is the number of the block from 0 to 15.
      //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
      //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
      if (status != MFRC522::STATUS_OK) {
             Serial.print("PCD_Authenticate() failed (read): ");
             Serial.println(mfrc522.GetStatusCodeName(status));
             return 3;//return "3" as error message
      }
      //it appears the authentication needs to be made before every block read/write within a specific sector.
      //If a different sector is being authenticated access to the previous one is lost.

      /*****************************************reading a block***********************************************************/

      byte buffersize = 18;//we need to define a variable with the read buffer size, since the MIFARE_Read method below needs a pointer to the variable that contains the size...
      status = mfrc522.MIFARE_Read(blockNumber, arrayAddress, &buffersize);//&buffersize is a pointer to the buffersize variable; MIFARE_Read requires a pointer instead of just a number
      if (status != MFRC522::STATUS_OK) {
              Serial.print("MIFARE_read() failed: ");
              Serial.println(mfrc522.GetStatusCodeName(status));
              return 4;//return "4" as error message
      }
      Serial.println("block was read");
    }

The problem I'm having is that

 1. I send first line via com port
 2. Apply a card to RFID-RC522
 3. The program reads the block alright
 4. But then I send the second line
 5. Arduino hangs on card detect

Here's the output I receive:

    Scan a MIFARE Classic card
    Start
    CardFound
    block was read
    read block: makecourse_____
    Done
    Start

 I tried removing card and applying it again or applying a different card, but it still freezes on card detect, sometimes after some time it works, though.

  [1]: https://github.com/miguelbalboa/rfid

body:
You should try adding this, at the end of `readBlock()`:

    // Halt PICC
    mfrc522.PICC_HaltA();
    // Stop encryption on PCD
    mfrc522.PCD_StopCrypto1();


message:
Instantiating bounce library inside a class

I am trying to get my head around how to instantiate objects from existing libaries inside a class object. Specifically I am trying to get the bounce2.h debouncer working.

At the moment my code compiles but i think the debounce function is not working as the button is filling my array with lots of random numbers (even from setup) whereas it works fine on a non-class based sketch, so I think that I am probably not instantiating the bounce object correctly. If anyone can help I would be very grateful!

My header:

    #ifndef CandleRack_h
    #define CandleRack_h

    class CandleRack
    {
      public:

        CandleRack(byte candleRackStatus);
        void begin();
        void pushButton();
        void selectRandomCandle();
        void turnOnCandle(byte candlePosition);
        void burnCandlesForMs();
        void fadeOutCandle(byte candlePosition);

      private:
        Bounce _debouncePushButton;
        byte _pushButtonPin;
        byte _candleRackStatus;
        byte _candlePosition;
        byte _candleStatus[];
        elapsedMillis _candleTimeElapsed;
        unsigned int _candleOnForMs;
    };
    #endif

My cpp

    #include "Arduino.h"
    #include <FastLED.h>
    #include <elapsedMillis.h>
    #include <Bounce2.h>
    #include "CandleRack.h"

    #define NUM_LEDS 50

    CandleRack::CandleRack(byte candleRackStatus)
    {
      _candleRackStatus = candleRackStatus;
    }

    void CandleRack::begin()
    {
      randomSeed(analogRead(0));

      _debouncePushButton = Bounce();
      _pushButtonPin = 3;
      _candleOnForMs = 20000;
      pinMode(_pushButtonPin, INPUT_PULLUP);
      _debouncePushButton.attach(_pushButtonPin);
      _debouncePushButton.interval(10);

      for (byte b = 0; b < NUM_LEDS; b++)
      {
        _candleStatus[_candlePosition] = 0;
      }

      Serial.println("Candle Array: ");       // Debug ************************
      for (byte b = 0; b < NUM_LEDS; b++)     // Debug ************************
      {                                       // Debug ************************
        Serial.print(_candleStatus[b]);       // Debug ************************
        Serial.print(", ");                   // Debug ************************
      }                                       // Debug ************************
      Serial.println("");                     // Debug ************************
      Serial.println("Begin Complete");       // Debug ************************
    }

    void CandleRack::pushButton()
    {
      // Look for a button push
      if (_debouncePushButton.update())
      {
        if (_debouncePushButton.fell())
        {
          selectRandomCandle();
        }
      }
    }

    void CandleRack::selectRandomCandle()
    {
      byte randomCandlePosition;
      do
      {
        randomCandlePosition = random(0, NUM_LEDS);
      }
      while (_candleStatus[randomCandlePosition] != 0);

      turnOnCandle(randomCandlePosition);
    }

    void CandleRack::turnOnCandle(byte _candlePosition)
    {
      // leds[_candlePosition] = CRGB::Red;
      _candleStatus[_candlePosition] = 1;

      Serial.println("Button Pushed: ");      // Debug ************************
      Serial.println(_candlePosition);        // Debug ************************
      Serial.println("Candle Array: ");       // Debug ************************
      for (byte b = 0; b < NUM_LEDS; b++)     // Debug ************************
      {                                       // Debug ************************
        Serial.print(_candleStatus[b]);       // Debug ************************
        Serial.print(", ");                   // Debug ************************
      }                                       // Debug ************************
      Serial.println("");                     // Debug ************************
    }

    void CandleRack::burnCandlesForMs()
    {
      // See if it is time to turn the candle off
      for (byte b = 0; b < NUM_LEDS; b++)
      {
        if (_candleTimeElapsed > _candleOnForMs && _candleStatus[b] == 1)
        {
          CandleRack::fadeOutCandle(b);
          _candleTimeElapsed = 0;
        }
      }
    }

    void CandleRack::fadeOutCandle(byte _candlePosition)
    {
      _candleStatus[_candlePosition] = 0;
    }

My sketch:

    #include "Arduino.h"
    #include <FastLED.h>
    #include <elapsedMillis.h>
    #include <Bounce2.h>
    #include "CandleRack.h"

    CandleRack MyCandleRack(0);

    void setup() {
      delay(3000); // sanity delay

      Serial.begin(9600);
      while (!Serial);

      Serial.println("Setup Starts");  // Debug ************************

      MyCandleRack.begin();

      Serial.println("Setup Complate");  // Debug ************************
    }

    void loop() {

      MyCandleRack.pushButton();
     // MyCandleRack.burnCandlesForMs();

      FastLED.show();
    }

edit - added the code from the original debounce example for a single sketch

    // Detect the falling edge

    // Include the Bounce2 library found here :
    // https://github.com/thomasfredericks/Bounce-Arduino-Wiring
    #include <Bounce2.h>

    #define BUTTON_PIN 2
    #define LED_PIN 13

    int ledState = LOW;

    // Instantiate a Bounce object :
    Bounce debouncer = Bounce();

    void setup() {

      // Setup the button with an internal pull-up :
      pinMode(BUTTON_PIN,INPUT_PULLUP);

      // After setting up the button, setup the Bounce instance :
      debouncer.attach(BUTTON_PIN);
      debouncer.interval(500);

      // Setup the LED :
      pinMode(LED_PIN,OUTPUT);
      digitalWrite(LED_PIN,ledState);

    }

    void loop() {

      // Update the Bounce instance :
       debouncer.update();

       // Call code if Bounce fell (transition from HIGH to LOW) :
       if ( debouncer.fell() ) {

         // Toggle LED state :
         ledState = !ledState;
         digitalWrite(LED_PIN,ledState);

       }
    }

body:
Your main issue (the cause of your symptoms) is the fact that you have no size for your `_candleStatus` array.  Without specifying a size you end up with no memory allocated to the array, and hence no valid content.

In your class definition the line:

    byte _candleStatus[];

should be modified to:

    byte _candleStatus[NUM_LEDS];

and `NUM_LEDS` should be defined in the header, not in the CPP file. (By specifying it in the header file, since the header file is included in the CPP file, the definition ends up in both files).

Aside from that this line doesn't do what you think it does:

    _debouncePushButton = Bounce();

You are copying the content of an anonymous bounce object created just for the occasion into a pre-existing Bounce object.  You don't want that line to exist since the Bounce object has already been instantiated by the construction of your `CandleRack` object.

However there is something you need to be aware of known as the *Static Initialization Order Fiasco* which can bite you on the rear end if you are not aware of it.  This is basically when you use objects in other objects and those objects haven't yet been properly created since you cannot predict the order in which objects are initialized. This may or may not be an issue in your system - it all depends on how the other classes you use behave.

One way around the issue, if you find it does become a problem (or if you just want to avoid the problem altogether) is to use pointers and what is known as *Construct On First Use*.  This is where you don't instantiate any objects in your constructor or the class definition - instead you just have pointers to them and use the `new` keyword to construct the object from within a member function (such as `begin()`).

For this you change your class definition object entries to be pointers, such as:

    Bounce *_debouncePushButton = NULL;

*(Note that not all versions of the compiler will support that assignment in the class definition. It's a modern addition to C++ and depending on your version of the Arduino software may or may not work. If it doesn't you can move the assignment into the constructor by removing the `= NULL` from the definition and adding `_debouncePushButton = NULL;` into the constructor.)*

Then construct a new object in the `begin()` function (if it hasn't already been created):

    if (_debouncePushButton == NULL) {
        _debouncePushButton = new Bounce();
    }

Now you have to access the `_debouncePushButton` as a pointer to an object not an object, so change all your accesses to use the pointer dereference operator `->`:

    _debouncePushButton->attach(_pushButtonPin);
    ... etc ...

In case the class should ever go *out of scope* or be used in a *dynamic* way you really should create a *destructor* to delete any objects that have been created:

    CandleRack::~CandleRack() {
        if (_debouncePushButton != NULL) {
            delete _debouncePushButton;
        }
    }

Note that you should only ever try and delete objects that have actually been created - hence the test to see if it's not null.

Excessive use of `new` and `delete` though is discouraged, so it is best to use objects in a static context if possible. Too much `new` and `delete` or `malloc` and `free` can cause *heap fragmentation* which can lead to you running out of memory and all the associated stability problems that come with it.

Of course, all this is optional and chances are it won't be needed if the other classes behave well.


message:
Options for communicating between Arduinos

I'm looking to communicate between ~5-10 Arduinos to send commands and data between them. By "Arduino" I mean the ATmega328 programmed using the Arduino programming framework.

Each of the devices would be on the same PCB.

I know I2C and SPI can communicate to some degree, but that they're really meant for peripherals devices connected to a micro controller rather than connecting multiple micro controllers to each other, and that they usually only send a few bytes of data at a time. On the other hand I know LCD displays can be driven using them, and I'd imagine there's a lot of data being transferred in those cases.

Is there a something like I2C (multi-master, multi-slave, single-ended, serial computer bus) for communicating between micro controllers? Allowing each device to send data to each other device unsolicited. For example, if a switch was pressed on device A, it would tell device B, without having device B ask A all the time if a switch was pressed. and vice versa.

**Edit**: I found some libraries that may do what I want with RS-485. Is this the only viable option for ~1k bps transmission between 5-10 devices? I would imagine TCP/IP over Ethernet would work as well, but that seems like too much. Are there any I2C libraries that allow sending that amount of data between only master devices?

- https://github.com/MichaelJonker/HardwareSerialRS485
- https://github.com/MajenkoLibraries/ICSC

body:
There are a number of concepts that can help you realize your dream. I can't, in the space of this answer, tell you exactly how to implement what you want, but I can show you the concepts that will help you to implement it.

First off there's the concept of the *bus master*.  This isn't necessarily the device that instantiates communication - instead this is the device that *owns* and *controls* the bus.

When a device that isn't the bus master wants to communicate on the bus it first asks permission from the bus master.  The old Z80 (well, I say "old", but they are still in use in many forms today) used this concept to allow other chips to use the data and address buses. It consists of two signals - BUSRQ and BUSACK.  A device first looks to see if either of BUSRQ or BUSACK are active, and if neither are it then activates BUSRQ. If the bus master is willing to give up the bus to the other device (it's not using it at that moment) it activates BUSACK and the other device then knows that it can use the bus.  Nothing else can use it until BUSRQ and BUSACK have both been released.  Nice and simple and elegant.

But not perfect. If two devices both decide to ask for the bus at the very same instant you get a *collision*.  This is a common problem amongst shared bus systems like this, and causes untold problems unless you know how to handle it properly.

Enter the concept of *listen-while-you-talk*.  This involves the device that is sending on the bus also listening to what is being sent on the bus through a separate receiver.  It then can know if what it sent on the bus is what actually ended up on the bus.  For instance if two devices talk at the same time and one sends `10011001` and the other sends `11001100` the result that appears on the bus might actually end up as something else, such as `11011101` or maybe `10001000` depending on how the bus signals are created.  So if you know what you sent got corrupted you can now do something about it.

Next concept: *backing off*.  This is where both the senders wait for a short period and try and send again. As long as they both delay for a different amount of time the first one to try will get the bus and be able to communicate. But how do you guarantee that they will both delay for different times?  You may think the answer is simple: use a random number, like `rand()` or `random()`.  But that is also problematic:

Another concept: *The **pseudo** random number generator*

The Arduino doesn't generate random numbers.  It just uses a complex mathematical formula to create a sequence of numbers that, to us, *look* random.  They aren't though.  Write a small program to print 10 random numbers through serial and run it multiple times (press the reset button).  You will find the same "random" numbers in the same order every time.  Try it on another Arduino and you get the same numbers again. Always the same.

So what to do?  The answer is called *seeding* the random number generator.  The next number generated by `rand()` et al depend on the number that had been generated last.  So change the *first* number and all the rest of the numbers will change.  However, you have a catch-22 situation. You need a random number to seed the random number generator to make it random to be able to generate a random number to seed the random number generator... ad infinitum.  You see where that's going? You can't seed from `rand()` since `rand()` isn't random until you have seeded from a random source. So you need to find a random source.

And that's not an easy task.  The best source of *entropy* as it's known is *white noise*. This can be generated in a number of ways with a number of different circuits - from the breakdown of a diode junction to very high gain amplification of the thermal fluctuations in a resistor.

All are quite complex for what you want really, but there is a simpler, if slightly less random, method - read an analog input that isn't connected to anything.  It won't have as much of a range as a proper entropy generator, but it should provide enough randomness to give a reasonable chance of each device getting a different seed.

Another useful concept is the interrupt.

This is good in a situation where you don't want the complexity of a multi-master bus with all the collisions etc. You have a single master that does all the work on the bus, and when a slave device has something important to say it nudges the master with an interrupt. The master then goes "Yes? What do you want?" to which the slave replies "Someone pressed my button".

That way the master isn't constantly polling the slave to see if the button has been pressed.  It is often used in bus arrangements like SPI and there are many chips, such as IO expander chips, that can assert an interrupt when one of their input pins changes state.

But if you have 20 devices does that mean you have 20 interrupt pins?  Not necessarily. New concept: *wired OR*.

It's perfectly possible to have multiple different slaves all using the same interrupt pin.  The pin is normally held HIGH with a resistor (it could be an internal pullup resistor) and each slave has an *open drain* output connected to that pin.  An open drain output, when "off", is not connected to anything - it's like the pin is in input mode (in fact it can be emulated on chips that don't have open drain by switching between input and output mode).  When the output is "on" it connects the pin to ground, pulling down the IO pin, just like a button would.

It's then up to the master to make its way round the slaves that it knows are attached to that interrupt to see who needs attention.  You can of course implement a number of different interrupt pins with different groups of slaves on each one - maybe a high priority one with just one device, and lower priority ones with multiple devices on each, for example.

The same concept of *wired OR* and *open drain* can be used for allowing multiple devices to all share the same physical wires.  That is exactly how I2C works - the two bus lines are pulled up by resistors and the devices on it use open drain outputs to pull the line low to release it back to high to create the different logic levels. If two devices both pull it low together it will just be low.  Without the open drain method if you had one device outputting a 1 and another outputting a 0 you would basically get a short circuit between the two and you would end up damaging chips.

And then of course you have the concept of synchronous versus asynchronous communication, but that is an entirely different kettle of fish. Simply said though, protocols with a clock, like SPI and I2C, which have a master generating that clock, are synchronous. Protocols like the UART and RS-232, RS-485, etc are asynchronous - they rely on both ends agreeing on how fast data is being sent (baud rate) so they know how to interpret the signals as they arrive.


body:
In addition to @Majenko's excellent answer, you need to have a think about what you are communicating.

It sounds like you want to communicate a single bit - perhaps you can get away with individual pins? If you have a master, and up to 13 slaves, you could have one pin on the master connected to one pin on each of the slaves (via a resistor). If slave A wanted to signal it's signal, it would raise the pin; the master would then be able to poll each pin in turn, to work out who said what.


body:
Another option is SPI.

SPI can be used with any number of devices, in a ring. It was explained to me as follows: any participant can toggle the clock line 8 times, to move the byte in it's own buffer, into the next device's buffer, in a ring; the device gets a byte from the previous device. If someone else toggles the clock 8 times, you get notified that the new byte is ready (this is done in hardware).

You need to think carefully about a protocol for this - an "address", "length", "command", and then any number of parameters. The sender sends the "address" byte, sets the "length" byte in the buffer, and holds the rest ready. The next device has received the "address" byte, and sees if it is the intended recipient. If it is not, it notes this down, and pushes the chain round, notes the length, and waits until someone ELSE has pushed that many bytes around. If it IS yours, read the rest of the data, pushing the data around, and blanking it as you go (to stop it coming back). A blank address (e.g. 0) would be reserved, meaning "don't do anything with this, wait for someone else to push it around, and read the next byte as the next address". All devices would need to initialize to 0 on startup.

If you need to set addresses dynamically, set a special byte "all stations", with a command which means "your device number is X, and tell the next device it's device number is X+1". Someone would need to initiate this, of course.

You also run the risk of collisions, if two devices start sending at the same time, or if something doesn't relay what it's supposed to (e.g. a chip is powered down). You need to think about how you're going to detect/recover from this.


body: Check out PJON - https://github.com/gioblu/PJON. It's a one-wire alternative.


message:
Power 4 leds with max7219 and LedControl.h

So this is my first arduino (or embedded for that matter) project. I am trying to power 4 leds with max7219. Max7219 seems easy to use, but for some reason after I upload the code, nothing happens. I've looked over my breadboard, and the connections seem right. My confusion arises from the fact that all the projects I have found on google use matrices for the leds. I am using 4 separate leds. Does this even matter?

Here is the code I use:

<!-- language: c -->

    #include "LedControl.h"

    LedControl ledControl = LedControl(12, 9, 10, 1);

    void setup()
    {
        //should be waking ledcontrol
        ledControl.shutdown(0, false);
        ledControl.setIntensity(0, 8);
    }

    void loop()
    {
        ledControl.setLed(0, 0, 0, true);
    }

body:
No it shouldn't matter that you are using separate LEDs, but you will have to connect them in a way that is acceptable to the 7219, they will have to share either a common anode or cathode (can't remember which of the top of my head).

I find its always best to check the basics (Based on personal experience)

 - Have you got the LEDs the correct way around?
 - Are you using the correct voltage for everything?
 - Do the LEDs work when controlled directly by the Arduino, try "Blink"?
 - Have you tried changing the intensity?
 - Have you got the required resistors in?
 - Try inverting the index of the LEDs, i.e. led(x=0,y=0) might be wired (x=7,y=7)?

You loop() is not pausing, so all it is going to be doing is calling that one statement repeatedly.  Now that might not be a problem or the second call may be blocking the first from completing.  So I suggest add a delay for a second or so and see if that changes anything.  Also to prove you are running you Loop() code flash the LED on the board (pin13?).

Hope that helps.


message:
What are ideal delay times between commands for RF24 lib

Am working on a WiFi based irrigation system that utilises the RF24 lib for comms.
Have got prototype of remote sensor up and running which has a standby current of 0.036mA and transmits data every hour using around a peak of 12mA.
While running the prototype I see various retry attempts which seem to vary with every transmission – despite the setup being under the same conditions all the time. I have coded a retry loop to limit this to 10 tries connecting to the master – don’t want the sensor to continuously be sending without getting a confirmation from the master

What I am trying to find is the ideal delay required between various RF24 commands to limit transmit times as much as possible to conserve power usage.
Any ideas??
(code snippets attached)

<!-- language: c -->

       pinMode(mostureSensorVCC, OUTPUT);
       digitalWrite (mostureSensorVCC, HIGH); //VCC to sensor
       pinMode(mostureSensor1, INPUT);      //moisture sensor on
       delay(10);
       int sensorValue1 = analogRead(mostureSensor1); // read the input on analog pin
       Serial.print("Current Value Sensor 1 is : "); // debugging
       Serial.println(sensorValue1); // print out the value you read:
       msg[0] = sensorValue1;
        digitalWrite(mostureSensor1, LOW);
        digitalWrite(mostureSensorVCC, LOW);
          while (message != sensorValue1)
            {

              Serial.print("sensorValue in while loop is "); // debugging
              Serial.println(sensorValue1);                   // debugging
              Serial.print("Message One is ");                // debugging
              Serial.println(message);                        // debugging
              radio.powerUp();
              delay(70);

              radio.stopListening();
              delay(50);
              radio.write(msg, 2);
              delay(40);
              radio.startListening();
              delay(50);

             Serial.println(d);               // debugging

              if (radio.available())
                {
                 Serial.println("Radio available");     // debugging
                  radio.read(msg, sizeof(msg));
                  message = msg[0];
                  Serial.print("Check Message received from master ");// debugging
                  Serial.println(message);

                }
                if(d>=10)
                {
                  Serial.println("Unable to send to master");
                  break;
                }
           d++;
      }

    delay(1000);
    radio.powerDown();
    message = 0;
    msg[0] = 0;

body:
Remove all delays except the one after startListening.

You could replace it with a "wait for radio.available to be true OR 50ms to have passed" piece of code. There is no need to wait for 50ms if the message was already received after e.g. 10ms.

Even better would be to use the ACK-package feature of the NRF. With this feature the master already prepares a package for the slave. Then when the slave sends it's message (every hour), the prepared package is included in the ACK (acknowledgement) packet.

As to optimizing it even further. It would be better to optimize the sleep code, then the send code. The sleep part will still use more power in an hour than the sending code, even if it takes 10 second to do so.

As to the lost packages. Try using a different channel. You also might want to get an NRF module with an real antenna, and maybe even an amplifier, for the master.

PS You can remove the serial.print in the deployed version.


message:
Using #define and multiple classes

I am using the FastLED library in my program and the basic usage is that the following lines go at the top of the main sketch:

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

You can see the documentation at https://github.com/FastLED/FastLED/wiki/Basic-usage

However, I am using the FastLED library in several different objects in my program and I would like to be able to reference NUM_LEDS in different header files for each object so that the number of LEDS can be controlled just by changing the value in the main sketch.

I am also intending that my own objects can be made into libraries for others to use, so they will then define the settings in their main sketch, that my libraries will then use.

body:
As the OP suggested, I'm posting a summing up of the comments under his question since the answer was found.

In order to make a common define for those parameters in different source files, the easiest solution is to make a shared header. To do this, just create a new file called `FastLedInclude.h` and, inside of that, write

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

Then in every source file you will just have to `#include "FastLedInclude.h"` to be able to use that library.

The FastLED library also requires the programmer to create a struct. Now, placing the definition of the struct (i.e. `struct CRGB leds[NUM_LEDS];`) into the header file leads to compilation errors, since the compiler writes the code to allocate it once for every object file.

The correct way to share this among different object files is to declare it `extern` in the header, then define it just once in one of the cpp or ino files:

 // into FastLedInclude.h
 extern struct CRGB leds[];

 // into any cpp or ino file (but just once)
 struct CRGB leds[NUM_LEDS];

This can also be done in the main ino sketch file, but personally I prefer to define it into another one (it depends, however, on how you choose to divide the program).

If you want to create a library, some other problems arise. The easiest solution is to ask the user to manually modify the header file which will be in the library folder. This solution is a bit uncomfortable, but it is the safest one.

Another solution is to force the user to create a header file into the sketch folder. Then the library should know the sketch folder path to back-include it. But.. This is a very discouraged option, since it will require the library to know the sketch location, thus violating the consistency principle at the base of a library-based approach.

The third solution is to modify the approach, from a compile-time static definition to a dynamic one. In order to do this, instead of defining `NUM_LEDS` and `DATA_PIN` at compile time you save them as variables in the library class.

For instance, in your library class definition you have

 class yourclass
 {
  public:
   yourclass(uint8_t data_pin, uint8_t num_leds);
   ~yourclass();
  private:
   uint8_t _data_pin;
   uint8_t _num_leds;
   struct CRGB *leds = NULL;
 };

And the implementation can be

 yourclass::yourclass(uint8_t data_pin, uint8_t num_leds)
 {
  _data_pin = data_pin;
  _num_leds = num_leds;

  // Dynamic allocation of the array
  leds = (struct CRGB *) malloc(num_leds * sizeof(struct CRGB));
 }

 yourclass::~yourclass()
 {
  // you should free the leds array when done
  free(leds);
 }

Then the user can write

 yourclass *obj = new yourclass(6, 60);

 // or, if he wants to define,
 #define NUM_LEDS 60
 #define DATA_PIN 6
 ...
 yourclass *obj = new yourclass(DATA_PIN, NUM_LEDS);

or, in the case of a statically allocated object,

 yourclass obj(6, 60);

 // or, if he wants to define,
 #define NUM_LEDS 60
 #define DATA_PIN 6
 ...
 yourclass obj(DATA_PIN, NUM_LEDS);


message:
Hardware network-infrastructure for a fully-arduino-based home-automation project

As already mentioned in [another question][1], I'm spending **LOT** of time planning the home-automation system for my new house (currently still in the "still building" phase).

Even if started only as a "lights/switch management project", things started getting bigger and bigger and, at the moment, in addition to original requirements, I **already** have:

 1. A [reed switch including cut-detection wires][2] (for a total of 4 wires)  installed on every single window (one switch for single-windows; two switches for dual-door windows);
 2. planned the location of a DHT22 sensor in each room.

In addition to the above, I'm currently evaluating the opportunity to add a single **RGB led to have visual-feedback for each push-button** (something like: GREEN=>LIGHT/OFF; RED=>LIGHT/ON). More specifically, I'm evaluating the opportunity to replace common/simple pushbuttons with these:

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

 Obviously, such a change will **heavily** impact the cabling, as:

 - original simple/pushbutton required **only two wires** for each pushbutton, with one wire potentially shareable among adiacent pushbuttons (I'll be using "internal pullups", so one wire will be GND)

 - RGB pushbuttons require **six** wires (GND and SIGNAL for pushbutton; R, G and B plus COMMON for LED), with only two wires potentially shareable among adjacent pushbuttons (GND and COMMON).

Adding to this that it will be easy to have wall-boxes hosting two, three or even four pushbuttons, and you easily understand that **LOTS** of cables are required!

Here below I'm attaching a rough schema of what I'm planning to build, in terms of hardware:

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

where you can see:

 - ROOM 1, with:
   - 2 x reed switch (up to 8 wires);
   - 1 x DHT22 (3 wires);
   - a wall box with two pushbuttons/wLED (up to 12 wires);
   - a wall box with one pushbutton/wLED (up to 6 wires)

 - ROOM 2, with:
   - 1 x reed switch (4 wires);
   - 1 x DHT22 (3 wires)
   - a wall box with two pushbuttons/wLED (up to 12 wires)

Also, as for "controlling" the whole system:

 - two POWER-BOXES, located externally to rooms, where I originally planned to host the "controller" (a MEGA2560) together with needed Relay-modules, and interconnected via an RS-485 bus.

(BTW: actually, I'll have three POWER-BOXES, and not only TWO. But this is a detail, as for the spirit of this question).

Please note that POWER-BOXES (PB1 and PB2) will be located (...as for the original plan) quite **FAR** from some rooms: up to 10/15 meters, in the worst case scenario. Also, please note that each power-boxes are far up to 10/15 meters from each-others.

Before the real question, let me add another couple of important points:

  - Even tough I know that some kind of wireless system and/or wireless segment could simplify my overall architecture, I'm a strongly believer that a "wired" system is more reliable than a "wireless" one, expecially in the long-term. As such, as I'm lucky enough to put down **lots** of "pipes" (to properly distribute cables all around the house), I really prefer a wholly wired system;

  - As for this question, I'm **not** interested in the "software" side of the system. This is really an accessory (again, as for this very question). My **really_big_problem** relates to the "hardware" infrastructure to put in place. That's why I'm posting this question here.

After the all of this, here is the question:

As for your experience and knowledge:

 1. should I stick to original plan, having an RS-485 multidrop-bus interconnecting only the MEGAs, with "signal" cables going directly from room-hardware (pushbuttons, reeds, DHT22, etc.) to the MEGA PINs ....

or

 2. should I add some other Arduinos (a Micro seems a really good candidates) in **each room**, terminating all the signal-room-cables coming from room-hardware, and speaking with MEGAs via the same RS-485 bus?

In the first case, I'll have a real simple RS-485 bus with a mess of cables; In the second case I'll have a _longer_and_more_complex_ RS-485 bus, with a much manageable network cabling/infrastructure.

Am I right? What are the PROs and the CONSs of above two scenarios? Should I investigate **other** approaches?

Are there some documentation that can help me picking the right solution?

**Thanks in advance to all of those who will spend some (precious) time helping me in this really difficult decision to take!**

-----

BTW: if you need further details, please don't hesitate to ask.

  [1]: https://arduino.stackexchange.com/questions/15834/how-to-interconnect-multiple-arduinos-with-a-rpi-to-control-home-lights-switches
  [2]: https://arduino.stackexchange.com/questions/20666/tamper-circuit-of-a-reed-switch-can-i-connect-the-two-wires-to-an-input-and-a
  [3]: https://i.stack.imgur.com/Hw62i.jpg
  [4]: https://i.stack.imgur.com/UHzVq.jpg

body:
1. short wires are generally better than long ones
2. I agree, that wired is better in your situation
3. Maybe you distinguish between two different areas: sensor/actor to controller and controller to controller communication
4. In many cases you can not chose the sensor/actor to controller communication, because it is given by the device (DHT-22, reed, led push button etc.). Therefore, keep these lines short
5. RS-485 is good, but is it necessary? It adds drivers to each device. Maybe, I2C could do it,to. You can still use twisted pair cables.


body:
Here my additional thoughts in short:

1. 20 meters is, compared with the distance to the moon, quite short ;-). Maximum length of RS-485 is reported to be kilometers with small transmission rates (google: rs485 cable length).

2. Noise can either be avoided (hardware) or corrected by software (fault tolerant codes, checksums etc.) Generally, software is cheaper.

3. Short wires does not mean no wires at all. Short wires would e.g. result if you have a controller per room and connect the sensors to it.

4. There are also small packages of Arduino compatible chips available (ATTiny84/85). And without RS485 you save the space of the controllers...

5. I2C bus length should work inside a house, if yous is not bigger than the one of Bill Gates...
http://www.esacademy.com/en/library/technical-articles-and-documents/miscellaneous/i2c-bus/frequently-asked-questions/i2c-faq.html

6. I would not use serial for communication. It is not extensible. Serial is ok for debugging.