message:
Running Pro Mini Continuous on 12v w/o Damaging Regulator

A Pro Mini needs to be placed in a 100mmx50mmx25mm, no holes but not air tight ABS plastic enclosure, with a 12v power supply connected to the raw input. It will be consuming max 40mA, ambient temperature 30-32C, and needs to be run 24/7. Upon prototyping in open air, I tried to touch the regulator MIC5205, after 30 seconds upon powering on with my bare fingers and it was too hot to touch. The rest of the components were cool to touch. I would use a buck converter to step down to 5v, however there isn't space for it in the current setup.

I used to run a Mega 24/7 on 12v, consuming much more current about 700mA, the onboard regulator malfunctioned after 1 year of use, which I believe was due to the excessive heat, as the PCB around the regulator turned a little brownish.

Despite being hot to touch, I understand that electronics run in heat all the time like computers, routers, etc for 24/7. Therefore, I would like to know if 12vx0.04A=0.48w will be too much heat/feasible to run in the above mentioned setup, without damaging the regulator in the long run?

body:
**Summary:**

**Simple, effective, low cost solution - choose any 3:**
A series resistor in the regulator input, of properly designed resistance and wattage will greatly reduce regulator temperature and increase overall reliability. Reason and design details given below.

**Detail:**

Assuming a 5V processor dissiaption in the regulator is
(Vsupply - Vregulator_out) x Current
= (12-5)x 0.040 = 280 mW - usefully less than the 480 mW if you are dissipating all the power in the regulator.
For a 3V3 processor dissipation is (12-3.3)* 0.040 ~= 350 mW

"Too hot to touch" is a minimum of 55C and probably hotter - say 70C for now.
At 30C ambient delta T = (70-30) = 40 C.
Thermal resistanc = dT/Watts =40/0.280 = 140 C/W or 114 C/W at 3V3.

Both of those thermal resistances are very high. You do not describe what heatsinking is on the regulator but that suggests PCB copper only and not much of it. Even adding a very rudimentary heat sink should help immensely. If there is no obvious way to add a formal heat sink then adding a 'flag' of copper or brass by soldering should be doable.

Using Mark William's 220C/Watt figure (see datasheet for conditions).
Say 300 mW (see above).
Delta t = 220 C/W  x 0.3 W = 66 C rise.
Ambient is 30-32 so allow 35 for very minor safety factor.
66 C rise + 35 C ~= 101C - water boils.
And temperature inbox will rise mildly from energy dissipated so hotter again.
BUIT a series resistor inside the box or external  will make an immense difference.

**An easy and effective solution:**

The regulator needs some "headroom" - some voltage above the Vout value to allow some dropacross the internal switch. Check the data sheet, but a modern LDO probably allows as little as 1V headroom. So, for 5V out you need 6V in. The extra 6v from 12V to 6V is not "needed" by the regulator. So, it can be dissipated in a low cost high reliability resistor.
Determine

 - Vsupply_minimum - the absolute lowest value supply will assume.

 - Vreg_in_minimum  I'll use 6V to start.

 - I_load_maximum - you said 40 ma. This must be abs_max or if of very short duration must be able to be supported by capacitors.

Then

Rmax = V/I = (V_supply_min-Vregin_nax) / Imax
= (12 - 6 )/.040 = 150 Ohm.
This is the absolute maximum resistor that meets the specification. A slightly smaller value will be safer. Say 120 R in this case.
Then
Pmax in R = I^2R = .04^2 x 120 = 192 mW.
A 500 mW resistor would be "safe enough" and a 1 watt one very safe.
Pregulator max = (6-5) x 0.040 = 40 mW, 14% of the 280 mW initially.
A  W resistor with adequate cooling will be very safe. Safest is probably a purpose built air cooled wire wound.

Note that the dissipated energy will raise internal ambient. A resistor is still an effective solution.

Place a suitable decoupling capacitor at the regulator input. Even if not normally used here it is needed due to the series input resistor raising the supply resistance.

._______________________________________

**Temperature rise inside box due to heat dissipation.**

**Summary:** Using pessimistic assumptions for box thickness, available area and power dissipation an internal temperature rise of under 15 degrees C can be expected. As the regulator is now dissipating under 15% of the original dissipation due to the series resistor it will have a far longer operating lifetime.

Notes:

Temperature rise (assuming no air transfer occurs) is limited by heat transfer through the plastic. This is controlled by the thermal conductivity of th e plastic, its thickness and its area.  Obviously:
 - Thicker plastic leads to higher temperature rise.

 - More surface area leads to lower temperature rise.

 - Higher thermal conductivity of the plastic leads to lower temperature rise

So given Thermal conductivity = Ktc

 - **Delta T = Watts x thickness / (Ktc x area)**

So Ktc = Watts x thickness /(Delta_Tx area)
So units of Ktc must be Watts/metre/degree_C
Which is indeed how Ktc is usually expressed.

This table of [**Thermal properties of plastic materials**](http://www.professionalplastics.com/professionalplastics/ThermalPropertiesofPlasticMaterials.pdf) lists Ktc for ABS as 0.17 W/m/K
This means that 170 mW will cause a 1 degree K (or C) rise when plastic ratio of thickness to area is 1.

Assume thickness of box = 5mm = much higher than is likely.
Box area for a box L x W x D = 2 x (LW + WD + DL)
Here  = L D W = 100mm x  50mm  25 mm or 0.1 x 0.05 x 0.025m
Area = 0.0175 m^2.
Use a smaller more pessimistic area of 0.01 m^2
Use a pessimistic heat dissipation of 0.5 Watts

Using the formula - **Delta T = Watts x thickness / (Ktc x area)**  from above

**Temperature rise = 0.5 x 0.05 / (0.17 x 0.01) ~= 15 degrees C (or K)**
This is based on a thicker than likely box, smaller than actual area, and higher than expected energy dissipation. A 15C rise is bearable and actual is lower, and as the regulator now dissipates under 20% of original it will survive very well.


sender: user

message:
Overview of compiled code size

When I compile my code, the Arduino IDE returns the binary sketch size in byte.

Is there a good way to find out (approximately) what function or what part of my code takes up how much memory in flash, so that I get a feeling what feature takes most of precious flash memory or where I may be wasting flash and should start optimizing?

sender: assistant

body:
One approach is to look at the assembly listing of the program.

1. After compiling the program (via the Verify or Download button) locate the directory where the .cpp, .hex, and .elf files for the program have been stored.  (If you have trouble finding them, briefly turn on verbose compile options in the arduino IDE and look at the directory names in the output.)

2. In that directory, run `avr-objdump -S ` *fn.cpp.elf* `> listing.txt` where *fn.cpp.elf* is the name of your sketch with `.ino` taken off and `.cpp.elf` added on at the end.  For example, with sketch `serialecho.ino`:

    avr-objdump -S serialecho.cpp.elf > listing.txt

3. View the `listing.txt` file, and subtract each function's starting address from its ending address, using hex arithmetic.  For example, with `setup` code

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

in the listing we will see

    00000144 <setup>:
    ...(6 lines snipped)...
     144:   26 e0           ldi     r18, 0x06       ; 6
     146:   40 e8           ldi     r20, 0x80       ; 128
     148:   55 e2           ldi     r21, 0x25       ; 37
     14a:   60 e0           ldi     r22, 0x00       ; 0
     14c:   70 e0           ldi     r23, 0x00       ; 0
     14e:   80 e1           ldi     r24, 0x10       ; 16
     150:   92 e0           ldi     r25, 0x02       ; 2
     152:   db c1           rjmp    .+950           ; 0x50a <_ZN14HardwareSerial5beginEmh>

    00000154 <loop>:

The calculation 0x154–0x144 = 0x10 shows this portion of `setup` is 16 bytes long.

These examples were generated on a linux system.  I think the approach is the same on a MSWindows system except you may need to say `avr-objdump.exe` instead of `avr-objdump`, and may need to specify its path.  See, eg, the [Assemler results, where?](http://forum.arduino.cc/index.php/topic,3537.0.html) thread at forum.arduino.cc.


message:
Improve sampling speed while using a multiplexer

I currently connected 5 sensor via a multiplexer (I must connect them to a multiplexer because they are I2C devices but they cannot been allocate more then 2 addresses so I use a multiplexer to solve the addressing problem).

However the sample rate is a shame , it is about 6.5Hz . I wish I could improve the sample rate by using some tricks.
In my loop() function, multiplexer will loop through channel 0-4 , and read each of these channel's sensor value and print it by using Serial.print()

Is there any tricks I could use to improve my sampling rate faster ? Thanks...

Here is my multiplexer class :

    class MUX {
    public:
    //mux control pins:
    int s0 = 22;
    int s1 = 24;
    int s2 = 26;
    int s3 = 28;

    //SIG pin (not necessary WHEN sig is connect to 5V)
    //int SIG_pin = 0;

    //array to store channel :: muxChannel[channel numbers ][4 digit channel representation]
    int muxChannel[16][4] = {
      {0, 0, 0, 0}, //channel 0
      {1, 0, 0, 0}, //channel 1
      {0, 1, 0, 0}, //channel 2
      {1, 1, 0, 0}, //channel 3
      {0, 0, 1, 0}, //channel 4
      {1, 0, 1, 0}, //channel 5
      {0, 1, 1, 0}, //channel 6
      {1, 1, 1, 0}, //channel 7
      {0, 0, 0, 1}, //channel 8
      {1, 0, 0, 1}, //channel 9
      {0, 1, 0, 1}, //channel 10
      {1, 1, 0, 1}, //channel 11
      {0, 0, 1, 1}, //channel 12
      {1, 0, 1, 1}, //channel 13
      {0, 1, 1, 1}, //channel 14
      {1, 1, 1, 1} //channel 15
    };

    void setupMux() {
      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);

      digitalWrite(s0, LOW);
      digitalWrite(s1, LOW);
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);
      Serial.println(F("Multiplexer initialized"));
    }

    void selectChannel(int channel) {
      int controlPin[] = {s0, s1, s2, s3};
      for (int i = 0; i < 4; i++) {
        digitalWrite(controlPin[i], muxChannel[channel][i]);
      }
    }

body:
It's hard to offer much more than speculation without knowing more about the sensors and your current code, but here is one possibility:

If the bulk of your loop time is the sum of the conversion times, is it possible to cycle through the sensors twice, once to start each conversion (so they will convert nearly simultaneously), wait one conversion-time (or for the first sensor to complete), then cycle through them again to read back each converted value?

    for each sensor,
      setup mux;
      send start conversion command;
    end

    for each sensor,
      setup mux;
      while conversion not done,
        ;  // wait
      read and store value;
    end

For 16 sensors and assuming the conversion time the majority of the time spent, that could speed your sample rate to ~100Hz. Expect maybe half of that, since mux-setup and communication times are probably not negligible.


body:
The technique suggested by @JRobert (starting all the conversions in one loop, then running another loop to wait for completions and read results) looks reasonable.

Here are a couple of ways to shorten the code shown in the question:

First, instead of four `int` declarations to set the value of `s0 ... s3`, use an `enum`.  An `enum` is used to declare integer constants.

    enum { s0 = 22, s1 = 24, s2 = 26, s3 = 28};

Second, don't bother with the lengthy, tedious, and unnecessary `muxChannel` array.  Delete the declaration of `muxChannel` and replace `selectChannel` with the following:

    void selectChannel(int channel) {
      int controlPin[] = {s0, s1, s2, s3};
      for (int i = 0; i < 4; i++) {
        digitalWrite(controlPin[i], channel & 1);
        channel /= 2;
      }
    }

The expression `channel & 1` picks off the least-significant-bit of `channel`.  The statement `channel /= 2;` divides `channel` by 2, which moves the next bit of `channel` into place for output.  You could instead say `channel >>= 1;` or `channel = channel/2;`, etc. if you prefer.

You might also look closely at your sensor boards to see if there is any way to add jumpers to get another bit or two of I2C device addressing, allowing you to avoid multiplexing.


message:
Big endian or little endian?

I need to pass a 16-bit long address (for an external EEPROM) to a function (`twi_writeTo`) in a buffer.
I am currently doing this

    byte buffer[2];
    buffer[0] = (byte)(eeaddress >> 8);
    buffer[1] = (byte)(eeaddress & 0xFF);
where `eeaddress` is an `unsigned int` with the address.

I then do

    int8_t ret = twi_writeTo(eeprom_i2c_addr, buffer, 2, 1);

Before I tried

    int8_t ret = twi_writeTo(eeprom_i2c_addr, (uint8_t*)&eeaddress, 2, 1);

but that returns garbage. Probably the byte order is swapped. Is that the case?
And if so, is there a better way than copying the two bytes to a buffer?

body:
If it's the byte order that causes a problem that's likely compiler specific and I don't think one can change it. Even if it were possible, changing the global endianness might break libraries that depend on it, so you likely can't escape using a function to swap the variable.

If you know you only need one value at a time you could write something like the following code, with a global buffer (untested but in principle should work (and I know global variables are evil, but should work for an Arduino project)):

    byte buf[2];

    byte* reverse(int val) {
        buf[0] = (byte)(val >> 8);
        but[1] = (byte)val;
        return buf;
    }

So you could use it like:

    int8_t ret = twi_writeTo(eeprom_i2c_addr, reverse(eeaddress), 2, 1);


message:
Alternatives to Wire library for I2C

I am looking for (reasonably easy to use and well tested) alternatives to the `Wire` library. `Wire` works very well, but: I only need the Arduino to act as I2C master and the `Wire` library seems to be a real waste of resources:

My goal is to send out data en bloc (e.g. 32 or 64 bytes). This data is already sitting in an array in SRAM. Now when you use the `Wire` library, you call the `TwoWire::write` function which copies your data into a 2nd buffer. Afterwards, `Wire` makes use of the `TWI` library where `twi_writeTo` copies the data again into a 3rd buffer. That's a bit clunky, isn't it?

I have seen the [DSSCircuits / I2C-Master-Library][1] but I am not sure how mature it is because there hasn't been any commit after the initial commit which is 3 years old now.

  [1]: https://github.com/DSSCircuits/I2C-Master-Library

body:
I don't see any objection to using [DSS Circuits I2C Master Library](http://dsscircuits.com/articles/arduino-i2c-master-library).

It may not have been updated for a couple of years, but if it works it doesn't need to be. It's not as if libraries for micro-controllers have to support new printer drivers, video drivers, etc.

If it works, it works.

The chip hasn't changed, and the only real reason for updates these days is if the IDE changes (or the compiler changes) in such a way that it introduces compile errors. Such things have happened fairly recently with things like PROGMEM having tighter rules, for example.


body:
[Cosa][1] [TWI][2] class is a very different approach to I2C device driver support. It does not use any extra SRAM for buffers at all. If a device driver is non-blocking it must handle the necessary buffering. Also the Cosa TWI class supports typical interaction with I2C devices such as master/slave, "write register-read data"-patterns, and transactions when using multi-threading.

A software and hardware [Arduino-TWI][3] library is available. It uses the Arduino-GPIO library and can be used on AVR and SAM based boards.

Some examples: [TWI Scanner][4], [DS3231 Real-Time Clock/Calender][5], [I2C LCD Adapter with PCF8574][6].

  [1]: https://github.com/mikaelpatel/Cosa
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/TWI.hh
  [3]: https://github.com/mikaelpatel/Arduino-TWI
  [4]: https://github.com/mikaelpatel/Cosa/blob/master/examples/Tools/CosaTWIscanner/CosaTWIscanner.ino
  [5]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/DS3231/DS3231.hh
  [6]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/DFRobot_IIC_LCD_Module/DFRobot_IIC_LCD_Module.hh


body:
Also [Procyon AVR library][1] worth be checking. It is a bit old now but very professional and kinda minimalistic. Not much dependencies, should be fine to use just I2C module only. There is hardly anything new in AVR I2C part since.

  [1]: http://www.procyonengineering.com/embedded/avr/avrlib/


body:
I made 2 libs myself for easier use and consistant calls:

one for AVR targets:
[cI2C](https://github.com/SMFSW/cI2C)

another using the same functions for all other targets (which basically is a wrapper for Wire library):
[WireWrapper](https://github.com/SMFSW/WireWrapper)

Both are available within the IDE library manager.
They both work as master without using interrupt and are tested on different targets with different slaves:
- UNO, Nano for cI2C
- Zero, Due & ESP8266 for WireWrapper


body:
You can use completely different approach to the top question. Asking for alternatives you have given reason to this: getting rid of unused code in the binary. You can achieve removal of unused code without actually using alternative library. Please keep in mind, that you can instruct the compiler and linker to exclude unused code from the compiled binary. Just use compilation flags:

    CFLAGS += -Wl,-static
    CFLAGS += -ffunction-sections
    CFLAGS += -Wl,--gc-sections

Rach function will be in its own section.

    LDFLAGS += -Wl,-gc-sections

This tells GCC to send the -gc-sections flag to the linker which will remove
unused sections. And voilla! Unused sections are removed.


message:
Multiple GSM shields on one Arduino

I am looking for a way to listen for received text messages on multiple numbers. When I came across the Arduino and its shields, I thought to myself this might be the perfect way to do just that.

One of the modules / shields I found on the internet by watching a youtube video is the TC 35 GSM.

I have been reading multiple questions here regarding the "stacking" of shields, and the usual reply is "check what pins / if they are using the same pins". Though these questions were not GSM module specific, and did not include stacking the **same** shields.

So I am very curious if this is possible. Let's say I want to listen to 10 SIM cards at once for received messages, will this be possible by stacking the modules on one Arduino?

Thanks!

body:
The [data sheet for the Siemens TC35](http://www.robotshop.com/media/files/pdf/datasheet-gsm-tc35.pdf) says *"The  data  interface  is  implemented  as  a  serial  asynchronous  transmitter  and  receiver conforming  to  ITU-T  RS-232  Interchange  Circuits  DCE.  It  operates  at  CMOS  level  (2.65V).
All RS-232 signals on the ZIF connector are low active."*

this is actually a low-voltage  equivalent of "RS232" serial. Real RS232 uses -12V and +12V signalling for binary 0 and 1 but most modern devices work with logic levels, often inverted (e.g. 0V and ~3.3V).

Most Arduinos support in hardware only a single logic-level serial interface. A few Arduinos, like the Arduino Mega, will support up to four logic-level RS232 interfaces.

Using a software library, you can emulate a serial port over the digital IO pins but the Arduino will quickly run out of processing power if you try to emulate several RS232 interfaces.

> **will this be possible by stacking the modules on one arduino?**

Almost certainly not. I doubt the daughterboard ("shield") designers made provision for that. At the least you'd have to re-route the serial interface to nonstandard pins and check that the power requirements don't exceed what the Arduino can supply.

If you can find a module that communicates over I2C or SPI there might be a better chance of getting it to work.


body:
Not directly stacking, no. You could do a dirty trick where you bend the serial pins out sideways, letting the stack handle all the power and ground and wakeup pins and stuff. Then handle the serial communications with each module separately.

The Uno and similar only have a single UART (serial port) each, but you can emulate more with "software serial", aka "bit-bang" techniques. These are full of caveats and I wouldn't wish them on a newbie.

The Mega2560 has four UARTs, so you're getting closer. You'd need to use wires coming off those sideways-bent pins to bring the signals down to the different tx/rx pins per UART, but I could see it working.

You can also add UARTs over SPI/I2C, but that's getting into a good bit of program complexity. Look at the SC16IS750 or the MAX3100 for starters.

(There's also a horrible, horrible hack emerging in my mind: Connect a single transmit line to a demux chip, so you can pick a single TC35 to talk to at any given moment. Bus all the receive lines together with resistors/diodes. Hope you never end up in a situation where two are talking at once.)


body:
The short answer is, no, you can't just stack them, but yes, it is possible (though not trivial) to connect ten or more of these to a single Arduino board and have it monitor all of them.

Note that the following explanation is simplified, possibly over-simplified, in the interests of brevity and giving you a general idea of what you're in for if you try this. Many of the details (as I mention below) could easily be one or several questions of their own.

You didn't give the [datasheet](https://en.wikipedia.org/wiki/Datasheet) for the board you're considering, so I'll work from the description of a similar board (though not an Arduino shield) using the same chip, the [Cytron Technologies TC35 GSM Development Board](https://docs.google.com/document/d/1Nmkcos20_gqYwU-mR7i0QlRpGSKiNO6yEP1d-Kf2b2o/edit).

Arduino shields connect various pins of their chips to pins on the Arduino board. In many (perhaps most) cases you can't have two different devices connected to the same Arduino pin, so if you were just going to plop another board on it would have to have special support for changing the pins it's using (often via [jumpers](https://en.wikipedia.org/wiki/Jumper_(computing))) or being able to have several boards communicating on the same pins. The GSM chip you're considering uses two dedicated pins for [serial communication](https://en.wikipedia.org/wiki/Serial_communication) transmit and receive; these are the pins you'll need to rewire if you're going to use multiple boards on a single Arduino.

What kind of rewiring you'll need to do depends on how many you really want. The Arduino Uno has 14 digital I/O pins, two of which are usually used for the USB serial interface to the computer, giving you six devices if you dedicate a pair of pins to each device. Since the communication rate with the boards is quite slow (9600 [bps](https://en.wikipedia.org/wiki/Data_rate_units), see below) you could multiplex many of these on one pair of Arduino pins via a number of different techniques (such as using shift registers); this alone is complex enough that a different question could be devoted just to considering the possible choices, with further questions on the details of implementing each choice. You should consider, if you're interfacing with a PC, using multiple Arduino microcontrollers each with only one or a few GSM chips talking to them, talking to a PC via USB, and doing further processing on the PC.

If you're using a lot of boards you'll need to make sure you can supply enough power to them; you may need to use a power source outside the Arduino board itself. An Arduino powered from its USB interface can pull no more than 500 milliamps (because that's the USB limit). If you're using a separate power supply and the Arduino's on-board regulator, the limitation will be based on the electrical and thermal limitations of that regulator; [this blog post](http://www.electricrcaircraftguy.com/2014/02/arduino-power-current-and-voltage.html) is one detailed discussion of that.

There's also the issue of level shifting; Arduino boards usually do digital I/O at 5 volts or 3.3 V; this chip looks like it talks at 2.65 V and you or the board you're using will need to handle that. If the board you're using doesn't do appropriate level conversion there are other questions (such as [this](https://arduino.stackexchange.com/questions/17734/can-i-safely-integrate-3-3v-sensor-with-5v-arduino-uno-how/17739#17739)) that discuss the details of particular level-conversion solutions.

Once you have pins connected to the devices you'll need to talk to them; this involves the lower level "framing" parts of the serial protocol and the higher-level command set.

For framing the GSM chip appears to use the [low-speed serial protocol framing](https://en.wikipedia.org/wiki/Serial_port#Settings) that's standard in the computer world; aside from the voltage level difference it's the same as used in RS-232 communications between a computer and a modem or other "serial" device. The setting from the data sheet I used is "9600bps, 8-1-N, No Flow Control" which is slow enough that the microcontroller itself can easily communicate with quite a number of these without any extra hardware using [bit banging](https://en.wikipedia.org/wiki/Bit_banging). A 16 MHz Arduino executes something approaching 16 million instructions per second (most instructions are one clock cycle), giving you over 1500 instructions per bit-time to read a bit from every attached device, do the processing to turn the bits into bytes, and process the resulting messages. If you're careful with your programming, and depending on what you're doing, it shouldn't be too hard to deal with even up to a couple of dozen GSM chips, though this is almost certainly not a trivial programming job that you're going to do with standard Arduino libraries.

The higher level command set is also pretty much the same as old-fashioned computer-modem comunication; the GSM chip (and thus pretty much any board that uses it) talks standard PC-style serial protocol at 9600 bps using the [AT command](https://en.wikipedia.org/w/index.php?title=AT_Commands) set. You'll see messages such as

    +CMGR: "REC READ","+60125651453",,"12/07/31,10:0702+32"
    Hello

when you receive an SMS and similar ones when you send an SMS.


message:
Why doesn't my code work in a function, yet works inline?

I'm trying to write a faster `shiftOut` function, which does not use the slow `digitalWrite`. In my code I have the original `shiftOut`, the new shiftOutFast, and the same as shiftOutFast, but inline. The three blocks are separated by delays to tell them apart on my scope. Here's the code:

    #define CLR(x,y) (x &= (~(1 << y)) )
    #define SET(x,y) (x |= (1 << y) )

    void shiftOutFast(uint8_t dataPort, uint8_t dataBit, uint8_t clkPort,
                      uint8_t clkBit, uint8_t bitOrder, uint8_t val) {
      for (uint8_t i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST) {
          if (val & 0x01) {
            SET(dataPort, dataBit);
          } else {
            CLR(dataPort, dataBit);
          }
          val >>= 1;
        } else {
          if (val & 0x80) {
            SET(dataPort, dataBit);
          } else {
            CLR(dataPort, dataBit);
          }
          val <<= 1;
        }

        CLR(clkPort, clkBit);
        SET(clkPort, clkBit);
      }
    }

    #define dataPin 4
    #define clockPin 5
    #define dataPort PORTD
    #define dataBit PORTD4
    #define clockPort PORTD
    #define clockBit PORTD5

    void setup() {
      pinMode(dataPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
    }

    void loop() {
      shiftOut(dataPin, clockPin, LSBFIRST, 0x55);
      delay(1);

      shiftOutFast(dataPort, dataBit, clockPort, clockBit, LSBFIRST, 0x5C);
      delay(1);

      bool bitOrder = LSBFIRST;
      uint8_t val = 0x5C;

      for (uint8_t i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST) {
          if (val & 0x01) {
            SET(dataPort, dataBit);
          } else {
            CLR(dataPort, dataBit);
          }
          val >>= 1;
        } else {
          if (val & 0x80) {
            SET(dataPort, dataBit);
          } else {
            CLR(dataPort, dataBit);
          }
          val <<= 1;
        }

        CLR(clockPort, clockBit);
        SET(clockPort, clockBit);
      }
      delay(1);
    }

The problem is that calling `shiftOutFast` doesn't do zilch. Absolutely nothing. It doesn't seem to be the logic, because when I do the same inline it works. Any ideas?

body: You should declare `volatile` the port parameters of your function. Otherwise, to the compiler, their write accesses seem useless, and they get optimized out.


body:
The problem is that you are passing the value of the ports to the function, not the address of the ports.

You need to either pass "by reference" or as a pointer, so that modifying the port variable modifies the *actual* port variable not the copy of the value that you pass.

The simplest way is to modify your function to be:

    void shiftOutFast(volatile uint8_t &dataPort, uint8_t dataBit,
                      volatile uint8_t &clkPort, uint8_t clkBit,
                      uint8_t bitOrder, uint8_t val) {
    ....
    }

That way, instead of passing whatever is in the port at the time to the function (pass by value) it instead creates a new variable which is located at the same address as the variable that you are passing (pass by reference) so modifications of one variable modifies the other.

Note that only the "port" variables need to be passed by reference, all the others remain as pass by value.  Also they should be, as Edgar says, flagged as *volatile*.


message:
OTA updates for Arduino using nRF24L01+

Is it possible to send OTA updates to Arduino via nRF24L01+ module?

Here are my findings:

[Here](http://www.instructables.com/id/Wireless-upload-program-to-Arduino-without-USB-cab/) is an instructable explaining how to program Arduino wirelessly but this thing uses a BT module which shows up on PC as a COM port.

[Here](http://www.instructables.com/id/Arduino-Wireless-Programming-with-XBee-Series-1-or/?ALLSTEPS) is something similar using Xbees.

However, these use another arduino attached to a PC on the other end. In my case, I am planning to use rPi hooked to another nRF24L01+ rather than PC.

This is an excerpt from the datasheet of Atmega chip:

> In ATmega88A/88PA/168A/168PA/328/328P the Boot LoaderSupport provides
> a real Read-While-Write SelfProgramming mechanism for downloading and
> uploading program code by the MCU itself. This feature allows flexible
> application software updates controlled by the MCU using a
> Flash-resident Boot Loader program. The Boot Loader program can use
> any available data interface and associated protocol to read code and
> write (program) that code into the Flash memory, or readthe code from
> the program memory.

Here is what I planned as a strategy.

Master programmer = Raspberry Pi + nRF module.

Slave arduino = Arduino + nRF24L01 + external EEPROM

Once I have to upload a new code, I can transmit the compiled code to the arduino (I can do that, right?) and Arduino will save it in the external EEPROM for the time being.

When the transfer is complete, I will send a signal which will make the arduino reset and copy the code from EEPROM to its flash memory.

My questions:

Is the strategy correct and feasible?

How should I proceed to achieve it?

Any other suggestions which you might have are welcome.

body:
Your best strategy would be to write your own bootloader.

The existing bootloader receives data through the serial port and writes it, a page at a time, to the flash.  Your custom bootloader, instead, would receive the data through the nRF module and write it to flash, a page at a time.

You could use the source code for the existing bootloader (maybe use optiboot?) as a starting point and remove the UART code, replacing it with nRF code.

Of course, you still need a way to enter the bootloader when you want to program it - the easiest way is to ensure that is added into any sketch you upload so you can send an instruction to that sketch to enter the bootloader.

You would also need to create a program on the Pi to do the programming over the air - or modify an existing one like avrdude.

It may, in the long run, be simpler to have a pair of other Arduinos (maybe something small like an ATTiny based board) to act as bridges between UART and the nRF modules so they become a transparent wireless serial link.


body:
It's definitely feasible and it's been done. Look at [Low Power Labs site](http://lowpowerlab.com/blog/category/moteino/wireless-programming/) where Felix did the same thing, but with a RF69 radio and an external flash chip. You do need a modified bootloader as he uses, one that would detect the new sketch in the external flash and will upload it to the Arduino on reset. Radio difference aside this should work well for your purposes.

Given the flaky nature of the radio communication I think it's a good idea to store the program separately rather than create a highly modified bootloader which will read the radio stream - it might be that for programming you need a constant stream of bytes which the radio can't always provide (though I'm not 100% sure about this); another reason being that the extra code you would need to access the radio will make for a larger bootloader.


body:
If you're working with remote sensor nodes, perhaps consider the MySensors library.

It's got support for two methods of delivering OTA updates - one using a node.js controller running on a rPi; and another third-party solution with a .NET front-end.

Failing that, you could borrow the bootloader code from the library and customise to your own needs.


body:
There is an [Arduino optiboot fork][1] for this now, which seems to handle what you want.

You would use a PC, RPi or whatever that could run `avrdude` to send the update to an Arduino acting as the update server, which transmits the code to the client.

The instructions on the page seem quite comprehensive.

  [1]: https://github.com/balrog-kun/optiboot


body:
As per @Majenko and @Kurt suggestions:

Please check out me blog post, it is exactly about that!

https://www.2bitornot2bit.com/blog/arduino-bootloader-with-ota-over-the-air-support-over-nrf24l01

I have made a complete tutorial about this issue and also modified the suggested code above so debugging will be easier.

The basic idea is to have a local station which forwards the new sketch from the **computer->uart->spi->rf24** to a remote Arduino running a custom bootloader which listens on the **rf24->spi** instead of the UART. This bootloader does everything as usual (expecting protocol commands as part of the stk500 protocol and so on) but, instead of getting them over UART the packets arrive from the RF24 module through SPI.

During boot, the bootloader will have to initialize the RF module registers and then parse the incoming bytes if any; after a timeout, it will quit and run the sketch currently there in a loog as usual

In [my blog][1] you will see some notes about the Hardware configuration for the local station: you need a 10uF capacitor between the **RESET** and **GND** pins to avoid flashing the local station while trying to flash the remote station.

That post also incldues the commands needed to use AVRdude to flash the bootloader and then to flash the remote station (which has the new bootlaoder) through the local station running the "flasher" sketch (station with the capacitor).

Basic commands are:

    avrdude -C "C:\Users\Ben\Downloads\avrdude\etc\avrdude.conf" -b 19200 -c usbtiny -p m328p -v -e -U efuse:w:0xFD:m -U hfuse:w:0xDA:m -U lfuse:w:0xFF:m -F
    avrdude -C "C:\Users\Ben\Downloads\avrdude\etc\avrdude.conf" -b 19200 -c usbtiny -p m328p -v -e -U flash:w:optiboot_atmega328_new_bootlader.hex -U lock:w:0x0F:m

You can find the code on my blog and links to other sources and tools needed
(such as an AVR programmer).

  [1]: https://www.2bitornot2bit.com/home/arduino-bootloader-with-ota-over-the-air-support-over-rf24


message:
Get JSON data from Arduino with AJAX

I have an Arduino with Ethernet Shield. I'm trying to get data from Arduino, using AJAX call.
At the moment I have the following code on Arduino:

>     #include <SPI.h>
>     #include <Ethernet.h>
>
>     byte mac[] = {
>       0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
>     };
>     IPAddress ip(192, 168, 1, 177);
>
>     EthernetServer server(80);
>
>     void setup() {
>       Serial.begin(9600);
>       while (!Serial) {
>         ;
>       }
>
>       Ethernet.begin(mac, ip);
>       server.begin();
>       Serial.print("server is at ");
>       Serial.println(Ethernet.localIP());
>     }
>
>
>     void loop() {
>       float temperatureIndoor;
>       float temperatureOutdoor;
>       EthernetClient client = server.available();
>       if (client) {
>         Serial.println("new client");
>         boolean currentLineIsBlank = true;
>         while (client.connected()) {
>           if (client.available()) {
>             char c = client.read();
>             Serial.write(c);
>             if (c == '\n' && currentLineIsBlank) {
>               client.println("HTTP/1.1 200 OK");
>               client.println("Content-Type: application/json;charset=utf-8");
>               client.println("Server: Arduino");
>               client.println("Connnection: close");
>               client.println();
>
>               temperatureIndoor = 22.77;
>               temperatureOutdoor = 15.55;
>               client.print("{\"0\":{\"TemperaturaInterior\":\"");
>               client.print(temperatureIndoor);
>               client.print("\",\"TemperaturaExterior\":\"");
>               client.print(temperatureOutdoor);
>
>               client.print("\"}}");
>               client.println();
>               break;
>             }
>
>           }
>         }
>         delay(1);
>         client.stop();
>         Serial.println("client disconnected");
>       }
>     }
>

I'm trying to get values with the following ajax call:

        $.ajax({
         url: 'http://192.168.1.177/',
         type: 'post',
          data: { tag: 'getData'},
          dataType: 'json',
                      async: false,
             success: function (data) {

    $('#TemperaturaInterior').val(data.TemperaturaInterior).show();
    $('#TemperaturaExterior').val(data.TemperaturaExterior).show();

              }
             });

If I access directly from the browser to Arduino (192.168.1.177) I get the correct JSON reply from arduino:
{"0":{"TemperaturaInterior":"22.77","TemperaturaExterior":"15.55"}}

I'm not getting the values.
Any idea?
Thanks

NOTE:

This what I get when ask to arduino to give me the values:

![enter image description here][1]

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

body: Ouch man you are getting burned by CORS. This stack overflow box isn't big enough for me to explain how much of a pain CORS is and how much trouble it will cause you. That being said there is a really good recourse that will help explain how to get this working with a couple of http headers http://enable-cors.org/. Good luck


body:
This is more of a Stack Overflow question, but I'll help you a bit. The problem has nothing to do with your Arduino per-say. It has more to do with your PHP/Ajax.

Your code is suited for a completely local setup, but pulls from a remote site, which violates some security protocols build into your browser and jQuery. You need to change your code to this:

    $.ajax({
        url: 'http://192.168.1.177/',
        type: 'post',
        data: { tag: 'getData'},
        dataType: 'jsonp',
        async: false,
        success: function (data) {
            $('#TemperaturaInterior').val(data.TemperaturaInterior).show();
            $('#TemperaturaExterior').val(data.TemperaturaExterior).show();
            }
        });
    (may need slight modifications since you didn't include all PHP/html code)

For more information, see the [jQuery documentation][1], particularly look at data types and what it says about cross-domain json vs jsonp.

[Here][2] is a relevant SO question.

  [1]: http://api.jquery.com/jquery.ajax/ "jQuery Documentation
  [2]: https://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain


message:
How to write RFID data using the RFID-RC522 chip

I have got this library+code example from a friend, to read RFID numbers using the RFID-RC522 chip:

RFID.ino

    #include <RFID.h>
    #include <SPI.h>

    /**
    * RFID pins
    * MOSI: Pin 11 / ICSP-4
    * MISO: Pin 12 / ICSP-1
    * SCK: Pin 13 / ISCP-3
    * SS: Pin 10
    * RST: Pin 9
    */

    RFID rfid(10, 9);
    unsigned char prevNum[] = {0,0,0,0,0};

    void setup()
    {
      Serial.begin(9600);
      SPI.begin();
      rfid.init();
    }

    void loop() {
        if (rfid.isCard()){
            if (rfid.readCardSerial() && (
                rfid.serNum[0] != prevNum[0]
             or rfid.serNum[1] != prevNum[1]
             or rfid.serNum[2] != prevNum[2]
             or rfid.serNum[3] != prevNum[3]
             or rfid.serNum[4] != prevNum[4]
            )){
              Serial.println(rfid.serNum[0]);
              Serial.println(rfid.serNum[1]);
              Serial.println(rfid.serNum[2]);
              Serial.println(rfid.serNum[3]);
              Serial.println(rfid.serNum[4]);

              prevNum[0] = rfid.serNum[0];
              prevNum[1] = rfid.serNum[1];
              prevNum[2] = rfid.serNum[2];
              prevNum[3] = rfid.serNum[3];
              prevNum[4] = rfid.serNum[4];
            }
        }
    }

RFID.h

    /* RFID.h - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
     * Based on code Dr.Leong   ( WWW.B2CQSHOP.COM )
     * Created by Miguel Balboa (circuitito.com), Jan, 2012.
     */
    #ifndef RFID_h
    #define RFID_h

    #include <Arduino.h>
    #include <SPI.h>

    /******************************************************************************
     * Definitions
     ******************************************************************************/
    #define MAX_LEN 16   // Largo m�ximo de la matriz

    //MF522 comando palabra
    #define PCD_IDLE              0x00               // NO action; Y cancelar el comando
    #define PCD_AUTHENT           0x0E               // autenticaci�n de clave
    #define PCD_RECEIVE           0x08               // recepci�n de datos
    #define PCD_TRANSMIT          0x04               // Enviar datos
    #define PCD_TRANSCEIVE        0x0C               // Enviar y recibir datos
    #define PCD_RESETPHASE        0x0F               // reajustar
    #define PCD_CALCCRC           0x03               // CRC calcular

    //Mifare_One  Tarjeta Mifare_One comando palabra
    #define PICC_REQIDL           0x26               // �rea de la antena no est� tratando de entrar en el estado de reposo
    #define PICC_REQALL           0x52               // Todas las cartas para encontrar el �rea de la antena
    #define PICC_ANTICOLL         0x93               // anti-colisi�n
    #define PICC_SElECTTAG        0x93               // elecci�n de tarjeta
    #define PICC_AUTHENT1A        0x60               // verificaci�n key A
    #define PICC_AUTHENT1B        0x61               // verificaci�n Key B
    #define PICC_READ             0x30               // leer bloque
    #define PICC_WRITE            0xA0               // Escribir en el bloque
    #define PICC_DECREMENT        0xC0               // cargo
    #define PICC_INCREMENT        0xC1               // recargar
    #define PICC_RESTORE          0xC2               // Transferencia de datos de bloque de buffer
    #define PICC_TRANSFER         0xB0               // Guardar los datos en el b�fer
    #define PICC_HALT             0x50               // inactividad

    //MF522 C�digo de error de comunicaci�n cuando regres�
    #define MI_OK                 0
    #define MI_NOTAGERR           1
    #define MI_ERR                2

    //------------------ MFRC522 registro---------------
    //Page 0:Command and Status
    #define     Reserved00            0x00
    #define     CommandReg            0x01
    #define     CommIEnReg            0x02
    #define     DivlEnReg             0x03
    #define     CommIrqReg            0x04
    #define     DivIrqReg             0x05
    #define     ErrorReg              0x06
    #define     Status1Reg            0x07
    #define     Status2Reg            0x08
    #define     FIFODataReg           0x09
    #define     FIFOLevelReg          0x0A
    #define     WaterLevelReg         0x0B
    #define     ControlReg            0x0C
    #define     BitFramingReg         0x0D
    #define     CollReg               0x0E
    #define     Reserved01            0x0F
    //Page 1:Command
    #define     Reserved10            0x10
    #define     ModeReg               0x11
    #define     TxModeReg             0x12
    #define     RxModeReg             0x13
    #define     TxControlReg          0x14
    #define     TxAutoReg             0x15
    #define     TxSelReg              0x16
    #define     RxSelReg              0x17
    #define     RxThresholdReg        0x18
    #define     DemodReg              0x19
    #define     Reserved11            0x1A
    #define     Reserved12            0x1B
    #define     MifareReg             0x1C
    #define     Reserved13            0x1D
    #define     Reserved14            0x1E
    #define     SerialSpeedReg        0x1F
    //Page 2:CFG
    #define     Reserved20            0x20
    #define     CRCResultRegM         0x21
    #define     CRCResultRegL         0x22
    #define     Reserved21            0x23
    #define     ModWidthReg           0x24
    #define     Reserved22            0x25
    #define     RFCfgReg              0x26
    #define     GsNReg                0x27
    #define     CWGsPReg           0x28
    #define     ModGsPReg             0x29
    #define     TModeReg              0x2A
    #define     TPrescalerReg         0x2B
    #define     TReloadRegH           0x2C
    #define     TReloadRegL           0x2D
    #define     TCounterValueRegH     0x2E
    #define     TCounterValueRegL     0x2F
    //Page 3:TestRegister
    #define     Reserved30            0x30
    #define     TestSel1Reg           0x31
    #define     TestSel2Reg           0x32
    #define     TestPinEnReg          0x33
    #define     TestPinValueReg       0x34
    #define     TestBusReg            0x35
    #define     AutoTestReg           0x36
    #define     VersionReg            0x37
    #define     AnalogTestReg         0x38
    #define     TestDAC1Reg           0x39
    #define     TestDAC2Reg           0x3A
    #define     TestADCReg            0x3B
    #define     Reserved31            0x3C
    #define     Reserved32            0x3D
    #define     Reserved33            0x3E
    #define     Reserved34         0x3F
    //-----------------------------------------------

    class RFID
    {
      public:
        RFID(int chipSelectPin, int NRSTPD);

     bool isCard();
     bool readCardSerial();

        void init();
     void reset();
     void writeMFRC522(unsigned char addr, unsigned char val);
     void antennaOn(void);
     unsigned char readMFRC522(unsigned char addr);
     void setBitMask(unsigned char reg, unsigned char mask);
     void clearBitMask(unsigned char reg, unsigned char mask);
     void calculateCRC(unsigned char *pIndata, unsigned char len, unsigned char *pOutData);
     unsigned char MFRC522Request(unsigned char reqMode, unsigned char *TagType);
     unsigned char MFRC522ToCard(unsigned char command, unsigned char *sendData, unsigned char sendLen, unsigned char *backData, unsigned int *backLen);
     unsigned char anticoll(unsigned char *serNum);
     unsigned char auth(unsigned char authMode, unsigned char BlockAddr, unsigned char *Sectorkey, unsigned char *serNum);
     unsigned char read(unsigned char blockAddr, unsigned char *recvData);
     unsigned char write(unsigned char blockAddr, unsigned char *writeData);
     void halt();

     unsigned char serNum[5];       // Constante para guardar el numero de serie leido.
     unsigned char AserNum[5];      // Constante para guardar el numero d serie de la secion actual.

      private:
        int _chipSelectPin;
     int _NRSTPD;

    };

    #endif

Using the code I have now I can read RFID data, and read them via the Serial monitor.
Now, if I want to write RFID numbers to a card, can I do this with this library, or what other library should I use that is capable of writing?

body:
The library you refer to is called [RFID][1] by Miguel Balboa.
It is equipped with several examples showing you how to read and write data. Check them out.

If you are looking for some more background information on what happens when you write data on a tag, check out the [first video of of the MakeCourse][2] of the University of South Florida.

At 21:30 it explains how to write data.

  [1]: https://github.com/miguelbalboa/rfid
  [2]: http://makecourse.weebly.com/week10segment1.html


message:
Why is SoftwareSerial causing arduino to reboot?

I'm trying to design an RC controller using an Arduino and an XBee Series 2 Pro. I have the hardware serial running for debug information and I want the XBee to be connected to a soft serial on pins 8 and 9.

My arduino keeps restarting, or at least the setup function keeps looping, every time I try to send data through the XBee. If I modify the code so the XBee runs on the hard serial, the program works, but I would rather not have that setup because then to load new code onto the arduino I have to open the controller and disconnect the XBee.

I tried changing the pins that the soft serial runs on and that makes no difference, nor does unplugging the power to the XBee but leaving the serial connections in. I also tried to write another pin high to make sure there's enough current, and that didn't cause a restart.

My arduino is connected to the XBee, 4 potentiometers, and 1 switch.

    #include <XBee.h>
    #include <SoftwareSerial.h>

    #define NOTE_A3  220
    #define NOTE_B3  247
    #define NOTE_C4  262
    #define NOTE_D4  294
    #define NOTE_E4  330

    #define THR_JOYSTICK A0
    #define YAW_JOYSTICK A1
    #define RL_JOYSTICK A2
    #define FB_JOYSTICK A3
    #define POT A4
    #define TOGGLE 4
    #define SPEAKER_PIN 3
    //#define WAKE_PIN 10

    #define YAW_MIN 0
    #define YAW_OFFSET 386
    #define YAW_MAX 815

    #define RL_MIN 0
    #define RL_OFFSET 359
    #define RL_MAX 800

    #define FB_MIN 0
    #define FB_OFFSET 355
    #define FB_MAX 795

    #define THR_MIN 0
    #define THR_OFFSET 0
    #define THR_MAX 754

    const int ESC_MIN = 764;
    const int ESC_OFFSET = 1500;
    const int ESC_MAX = 2000;

    XBee xbee = XBee();
    SoftwareSerial nss(13,12);
    uint8_t payload[10];
    // SH + SL Address of receiving XBee
    XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40c67584);
    ZBTxRequest packet = ZBTxRequest(addr64, payload, sizeof(payload));
    ZBTxStatusResponse txStatus = ZBTxStatusResponse();

    void setup() {
      //start serials
      Serial.begin(9600);
      nss.begin(9600);
      xbee.setSerial(nss);

      //pin modes
      pinMode(THR_JOYSTICK,INPUT);
      pinMode(YAW_JOYSTICK,INPUT);
      pinMode(RL_JOYSTICK,INPUT);
      pinMode(FB_JOYSTICK,INPUT);
      pinMode(POT,INPUT);
      pinMode(TOGGLE,INPUT);
      pinMode(SPEAKER_PIN,OUTPUT);

      //delay to allow inputs to settle
      delay(1000);

      //the speaker will need a total resistance of at least 125 Ohm
      //so if it's an 8 Ohm speaker, an additional 117 is needed etc...

       //calibrate THR
      int first = millis();
      tone(SPEAKER_PIN,NOTE_A3);
      int reading = analogRead(THR_JOYSTICK);
      while(reading > THR_OFFSET + 5 || reading < THR_OFFSET - 5) {
        delay(20);
        reading = analogRead(THR_JOYSTICK);
      }
      int dif = 200 - millis() + first;
      if(dif <= 200 && dif >= 0) {
        delay(dif);
      }

      //calibrate YAW
      first = millis();
      tone(SPEAKER_PIN,NOTE_B3);
      reading = analogRead(YAW_JOYSTICK);
      while(reading > YAW_OFFSET + 5 || reading < YAW_OFFSET - 5) {
        delay(20);
        reading = analogRead(YAW_JOYSTICK);
      }
      dif = 200 - millis() + first;
      if(dif <= 200 && dif >= 0) {
        delay(dif);
      }

      //calibrate FB
      first = millis();
      tone(SPEAKER_PIN,NOTE_C4);
      reading = analogRead(FB_JOYSTICK);
      while(reading > FB_OFFSET + 5 || reading < FB_OFFSET - 5) {
        delay(20);
        reading = analogRead(FB_JOYSTICK);
      }
      dif = 200 - millis() + first;
      if(dif <= 200 && dif >= 0) {
        delay(dif);
      }

      //calibrate RL
      first = millis();
      tone(SPEAKER_PIN,NOTE_D4);
      reading = analogRead(RL_JOYSTICK);
      while(reading > RL_OFFSET + 5 || reading < RL_OFFSET - 5) {
        delay(20);
        reading = analogRead(RL_JOYSTICK);
      }
      dif = 200 - millis() + first;
      if(dif <= 200 && dif >= 0) {
        delay(dif);
      }

      //done
      tone(SPEAKER_PIN,NOTE_E4);
      delay(200);
      noTone(SPEAKER_PIN);
      delay(15);
      tone(SPEAKER_PIN,NOTE_E4);
      delay(200);
      noTone(SPEAKER_PIN);
      delay(15);
      tone(SPEAKER_PIN,NOTE_E4);
      delay(350);
      noTone(SPEAKER_PIN);
    }

    void loop() {
      int POTReading = analogRead(POT);
      int toggle = digitalRead(TOGGLE);

      int throttleValue = mapLimit(analogRead(THR_JOYSTICK) - THR_OFFSET,THR_MIN,THR_MAX - THR_OFFSET,0,ESC_OFFSET);
      int yawValue = mapLimit(analogRead(YAW_JOYSTICK),YAW_MIN,YAW_MAX,ESC_OFFSET-ESC_MAX,ESC_MAX - ESC_OFFSET);
      int rightLeftValue = mapLimit(analogRead(RL_JOYSTICK) - RL_OFFSET,RL_MIN,RL_MAX - RL_OFFSET,0,ESC_MAX - ESC_OFFSET);
      int frontBackValue = mapLimit(analogRead(FB_JOYSTICK) - FB_OFFSET,FB_MIN,FB_MAX - FB_OFFSET,0,ESC_MAX - ESC_OFFSET);
      int potValue = analogRead(POT);
      int toggleValue = digitalRead(toggle);

      //throttle
      payload[0] = throttleValue >> 8 & 0xff;
      payload[1] = throttleValue & 0xff;
      //yaw
      payload[2] = yawValue >> 8 & 0xff;
      payload[3] = yawValue & 0xff;
      //RL
      payload[4] = rightLeftValue >> 8 & 0xff;
      payload[5] = rightLeftValue & 0xff;
      //FB
      payload[6] = frontBackValue >> 8 & 0xff;
      payload[7] = frontBackValue & 0xff;
      //Pot
      payload[8] = potValue >> 8 & 0xff;
      payload[9] = potValue & 0xff;
      //toggle
      payload[10] = (byte) toggleValue;

      //wake XBee
      //digitalWrite(WAKE_PIN,LOW);
      xbee.send(packet);
       if(xbee.readPacket(500)) {
         if(xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
           xbee.getResponse().getZBTxStatusResponse(txStatus);
           if(txStatus.getDeliveryStatus() != SUCCESS) {
             //the remote XBee didn't ACK
             tone(SPEAKER_PIN,NOTE_C4,100);
           }
         }
       } else {
         //error or something
         tone(SPEAKER_PIN,NOTE_E4);
         noTone(SPEAKER_PIN);
         tone(SPEAKER_PIN,NOTE_E4,50);
       }

        //sleep XBee
        //digitalWrite(WAKE_PIN,HIGH);
        delay(100);
    }

    int mapLimit(int val, int fromLow, int fromHigh, int toLow, int toHigh) {
      int result = map(val,fromLow,fromHigh,toLow,toHigh);
      if(result > toHigh) {
        result = toHigh;
      } else if(result < -toHigh) {
        result = -toHigh;
      }
      return result;
    }

body:
Just a guess, but maybe your Arduino power supply isn't juicy enough. I had the same problem running 2 modules + LCD on a Arduino powered via USB.
Try to find a power supply somewhere between 9 and 12V (from an old router, modem or cellphone you don't need anymore), and use it to power your Arduino instead of relying on the the USB port alone.

http://playground.arduino.cc/Learning/WhatAdapter


body: 10 bytes in `payload` were being used, but `payload` was declared using `int payload[10]` when it should have been `int payload[11]`.


message:
Arduino clock needed to print the time a button is pressed while continuing to count the time?

I'm making a clock using an arduino uno and a compatible freetronics screen. So far it can count the time in a 24 hour loop after which it repeats and counts again. The screen had a number of buttons built onto it and I want to get it so that when one of the buttons on the screen is pressed it prints the time that it was pressed on the top line of the screen while continuing to count and print the time on the second line of the screen.

How can I edit my code below to do this when a button is pressed? What sort of command do I need to add?

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

    #define MILLIS_OVERFLOW 34359738

    /**
    * Clock Variables
    */
    unsigned long currentMillis, previousMillis, elapsedMillis;
    int seconds = 0, minutes = 0, hours = 8;

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    void setup()
    {
      Serial.begin(9600);
        lcd.begin( 16, 2 );

    }

    void loop()
    {
    setClock();

    /**
     * After set clock now you have 3 int variables with the current time
     */
     //seconds
     //minutes
     //hours
     lcd.setCursor ( 0, 1);
     lcd.print(hours);
     lcd.print(":");
     lcd.print(minutes);
     lcd.print(":");
     lcd.print(seconds);
     lcd.print(":");
     lcd.print(elapsedMillis);

    }

    void setClock()
    {
    currentMillis = millis();
    /**
     * The only moment when currentMillis will be smaller than previousMillis
     * will be when millis() oveflows
     */
    if (currentMillis < previousMillis){
        elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
    } else {
        elapsedMillis += currentMillis - previousMillis;
    }

    /**
     * If we use equals 1000 its possible that because of the mentioned loop limitation
     * you check the difference when its value is (999) and on the next loop its value is (1001)
     */
    if (elapsedMillis > 999){
        seconds++;
        elapsedMillis = elapsedMillis - 1000;
    }

    if (seconds == 60){
        minutes++;
        seconds = 0;
    }
    if (minutes == 60){
        hours++;
        minutes = 0;
    }
    if (hours == 24){
        hours = 0;
    }

    previousMillis = currentMillis;
    }

Any help will be greatly appreciated, thanks

body:
use a second variable called TNow and when the button is pressed pass it the value of currentMillis. parse  and use this as the value to display. or have misunderstood your question? wondering why you aren't using a time library. such as [this][1]
if you look on the site [here][2]  use the time library you can then use  *variable name* = now();

  [1]: http://www.pjrc.com/teensy/td_libs_Time.html
  [2]: http://playground.arduino.cc/code/time


body:
You probably want to read the button press on LCD using "read_LCD_buttons" function. See an example at: [Arduino LCD KeyPad Shield](http://www.dfrobot.com/wiki/index.php?title=Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)).

So your part of your code would probably be:

    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5
    int lcd_key     = 0;

    void loop()
    {
     setClock();

     /**
     * After set clock now you have 3 int variables with the current time
     */
     //seconds
     //minutes
     //hours
     printValueAtLine(0);

     lcd_key = read_LCD_buttons();  // read the buttons

     switch (lcd_key)
     {
       case btnSELECT:
       {
         printValueAtLine(1);
         break;
       }
       case btnRIGHT:
       {
         // code in case other buttons like  btnRIGHT, etc are pressed
         break;
       }
       case btnNONE:
       {
         //do nothing
         break;
       }
     }
    }

    void printValueAtLine(int line)
    {
     lcd.setCursor (1, line);
     lcd.print(hours);
     lcd.print(":");
     lcd.print(minutes);
     lcd.print(":");
     lcd.print(seconds);
     lcd.print(":");
     lcd.print(elapsedMillis);
    }

The code is untested and you may have to make minor corrections to it.

Also, rather than saving values in global variables, you might want to use local ones using libraries suggested by wobbler.


body:
Since you will have to deal with _two_ different times, I suggest
writing a small class for representing those times in broken-down form.
This is a reduced version of the classical `strcut tm`. Times are made
`Printable` so you can just `print()` them to the LCD. I included an
`increment()` method to add one second to this time.

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

    class BrokenDownTime : public Printable {
        uint8_t hours;
        uint8_t minutes;
        uint8_t seconds;
    public:
        void increment();
        size_t printTo(Print &p) const;
    };

    /* Increment the time by one second. */
    void BrokenDownTime::increment()
    {
        if (++seconds >= 60) {
            seconds = 0;
            if (++minutes >= 60) {
                minutes = 0;
                if (++hours >= 24)
                    hours = 0;
            }
        }
    }

    /*
     * Print to anything that inherits from the Print class (Serial,
     * LiquidCrystal, etc.). This makes times `Printable'.
     */
    size_t BrokenDownTime::printTo(Print &p) const
    {
        p.print(hours/10);
        p.print(hours);
        p.write(':');
        p.print(minutes/10);
        p.print(minutes);
        p.write(':');
        p.print(seconds/10);
        p.print(seconds);
        return 8;  // 8 bytes written
    }

The main program checks in `loop()` for the button being pressed. When
this happens, it saves the current time as `lastPress`. If the button
was ever pressed (variable `button_was_pressed`), the recorded time is
displayed on the first line:

    #include <LiquidCrystal.h>

    #define BUTTON_ADC_PIN A0

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
    BrokenDownTime now;

    /* Detect a press on `left', change the thresholds for other buttons. */
    bool buttonPressed()
    {
        int reading = analogRead(BUTTON_ADC_PIN);
        return reading > 405 && reading < 605;
    }

    /* Update `now'. */
    void updateTime()
    {
        static unsigned long last;
        if (millis() - last >= 1000) {
            now.increment();
            last += 1000;
        }
    }

    void setup()
    {
        lcd.begin(16, 2);
    }

    void loop()
    {
        static BrokenDownTime lastPress;
        static bool button_was_pressed;

        updateTime();

        /* Record the time of the button press. */
        if (buttonPressed()) {
            lastPress = now;
            button_was_pressed = true;
        }

        /* Display the recorded time on the first line. */
        if (button_was_pressed) {
            lcd.setCursor(0, 0);
            lcd.print(lastPress);
        }

        /* Display the current time on the second line. */
        lcd.setCursor(0, 1);
        lcd.print(now);
    }

I did not test the program, but I hope you get the idea.


message:
Does data coming in on Arduino serial port store for some time?

I am using Arduino Uno and my question is when data is coming on Rx pin and at that time our program is not checking Serial.available()

Then after some time the program will check Serial.available().
Can we read data? Does it get stored in memory?

If stored how to remove that?

Is the answer the same for Software.Serial()?

body: Yes.  The serial port uses a *ring buffer* (also known as a *circular buffer*) for storing the incoming data until you want it.  That buffer is 16 bytes in size on the smaller Arduinos and 64 bytes in size on the larger one.  A similar ring buffer is used to store transmitted data until the port is ready to transmit it in the background.


body:
Yes.  The receive ring buffer is 64 bytes and will discard anything past that until the program reads them out of the buffer.

>But be careful:  In serial monitor, any number of bytes more than 64 and ending with Enter will give you `Serial.available==63` at the Arduino - and no `\n` at the end.  This is important especially if you are using readline() in Python.
>
>However, when NOT in the serial monitor, you can actually get the result `Serial.available==64` and use Serial.read() to get them in sequence.  No `\n` is required.
>
>So be careful debugging in the serial monitor when it comes to buffer size and newlines.  It is subtly different when programs are talking vs the serial monitor.
>
>**Most important difference is that a program can send a single byte and continue.  Serial monitor will send a single character, but is blocked until you press newline to get it to transmit.  Yet serial monitor does not send the newline character.**

----------------------------------
Simple scenario:  You want the Arduino to respond to a single-byte command code send via the serial cable from a Raspbian system running a Python data logging program based on something the Arduino reads or by time of day.

You need to trigger the Arduino to take some action as a result.

So on the Arduino you want to first clear the receive buffer by simply reading it out like so:

Arduino code to read a single-character command:

    byte ch;
    void setup() {
      Serial.begin(9600));
      while (Serial.available>1) ch = ser.read();
    }
    void loop {
      if (Serial.Available==1 && Serial.read()=='X') {
         .....respond to the X command....
      }
      else
         ....etc...
      delay(60000);
    }

>Note that when a Rpi Python program is sitting there waiting for linein=ser.readline() the Arduino transmit buffer size is not relevant.  Python collects each byte as it comes in until the `\n` then returns the string to linein.  The line can be very long.  I have tested it to 100 bytes.

----------------------------------------------
Software.Serial acts exactly the same way.


message:
Arduino Start en Stop

Is there a way to set a time for instance 8.00 PM to make the arduino-uno start or stop at that time?

body:
Really stop Arduino is possible, it's called sleep mode, but the UNO is designed so badly with respect to power consumption that you may as well keep it running.

To have it done something at a specific time you could connect a real time clock (RTC) breakout board (SparkFun has a couple). Use a 1 second timer interrupt to read the clock and compare it with (a table of) times where you want things done. A table could hold the time, an output (e.g. for a relay) and the new status (on or off). If you have just a couple of those you can store them in the RTC's battery-backed up RAM.

**edit**
You can use your PC's time, all the hardware you need is the USB cable. On the PC you run a program that sends the current time to the Arduino. (There are [Processing examples](https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing) of how to communicate with the Arduino on the Net.)

Note that without an RTC your PC will have to be on all the time and connected to the Arduino. You could use the PC just to sync the Arduino's clock and keep time yourself, but the clock of the Arduino is not very accurate.

Getting the time from the Internet is also possible, but then you'll need a Wifi or Ethernet shield to make the connection.


message:
Passing VAL(0-179) to OLED

I´m using Spark Fun Micro Pro board 5V: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro

and to that i´ve hooked a true color OLED from digole: http://www.digole.com/index.php?productID=859

I manage to get my VAL from my potentiometer on screen. But when I exceeds val "10", and then go back to lets say "9", the zero from "10" is still there. It looks like:  "90" instead of "9". The problem is of course that the second (and third) number don't go away.. Im sure there is a simple way of doing this but I can't get my head around it..
I´ve tried using clearScreen but that function makes the OLED blink in a unpleasant way every time it clears... Hope you get my question, english isn't my native language, as u maybe can tell =)
Thanks

    void loop()
    {
      val = analogRead(potpin);        // reads the value of the     potentiometer (value between 0 and 1023)
      val = map(val, 0, 1023, 0, 179);  // scale it to use it with the servo (value between 0 and 180)
      myservo.write(val)  sets the servo position according to the scaled     value
      mydisp.clearScreen();
      mydisp.setPrintPos(9, 6);
      mydisp.print(val);

      delay(200);  // waits for the servo to get there
     // mydisp.clearScreen();

    }

body:
Instead of printing "10" or "9" etc, print "10 " or "9 ".  Add an extra space at the end of what you print which overwrites the character that was there before.

    mydisp.print(val);
    mydisp.print("  ");

I used 2 spaces there, in case you go from 3 digits straight to 1.

Another method is to "format" the number using sprintf:

    char temp[4];
    sprintf(temp, "=", val);
    mydisp.print(temp);


message:
Serial device file no longer shows up in /dev/ after working fine for months

I am using an Arduino MEGA connected to my Linux workstation via USB. I have been using this setup for several months with no issues.

A few days ago, **the usual serial device file (`/dev/ttyACM0`) stopped showing up when I plug in the device**)

 * Haven't re-flashed recently.
 * Unable to reflash.
 * Removing the devices only shield does not do anything.
 * Have not changed my physical setup recently.
 * Connector cable is confirmed working with a different device.

Is this a case of bad hardware, or is there a possible fix other than buying a new device?

**`dmesg` results**: None (cleared buffer and re-ran dmesg after plugging / unplugging device)
**usb-devices**:

    T:  Bus=01 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
    D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
    P:  Vendor=1d6b ProdID=0002 Rev=03.13
    S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
    S:  Product=EHCI Host Controller
    S:  SerialNumber=0000:00:1a.0
    C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

    T:  Bus=01 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
    D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
    P:  Vendor=8087 ProdID=0024 Rev=00.00
    C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

    T:  Bus=02 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
    D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
    P:  Vendor=1d6b ProdID=0002 Rev=03.13
    S:  Manufacturer=Linux 3.13.0-37-generic ehci_hcd
    S:  Product=EHCI Host Controller
    S:  SerialNumber=0000:00:1d.0
    C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

    T:  Bus=02 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=480 MxCh= 6
    D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
    P:  Vendor=8087 ProdID=0024 Rev=00.00
    C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

    T:  Bus=02 Lev=02 Prnt=02 Port=03 Cnt=01 Dev#=  3 Spd=480 MxCh= 0
    D:  Ver= 2.00 Cls=ef(misc ) Sub=02 Prot=01 MxPS=64 #Cfgs=  1
    P:  Vendor=1bcf ProdID=2805 Rev=20.15
    S:  Manufacturer=6047B0021601A0218M7NB
    S:  Product=HP HD Webcam [Fixed]
    C:  #Ifs= 2 Cfg#= 1 Atr=80 MxPwr=500mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=0e(video) Sub=01 Prot=00 Driver=uvcvideo
    I:  If#= 1 Alt= 0 #EPs= 0 Cls=0e(video) Sub=02 Prot=00 Driver=uvcvideo

    T:  Bus=02 Lev=02 Prnt=02 Port=05 Cnt=02 Dev#=  4 Spd=12  MxCh= 0
    D:  Ver= 2.00 Cls=e0(wlcon) Sub=01 Prot=01 MxPS=64 #Cfgs=  1
    P:  Vendor=0bda ProdID=0001 Rev=68.17
    S:  Product=CSR BS8510
    C:  #Ifs= 2 Cfg#= 1 Atr=e0 MxPwr=0mA
    I:  If#= 0 Alt= 0 #EPs= 3 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
    I:  If#= 1 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb

    T:  Bus=03 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=480 MxCh= 2
    D:  Ver= 2.00 Cls=09(hub  ) Sub=00 Prot=01 MxPS=64 #Cfgs=  1
    P:  Vendor=1d6b ProdID=0002 Rev=03.13
    S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
    S:  Product=xHCI Host Controller
    S:  SerialNumber=0000:26:00.0
    C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

    T:  Bus=04 Lev=00 Prnt=00 Port=00 Cnt=00 Dev#=  1 Spd=5000 MxCh= 2
    D:  Ver= 3.00 Cls=09(hub  ) Sub=00 Prot=03 MxPS= 9 #Cfgs=  1
    P:  Vendor=1d6b ProdID=0003 Rev=03.13
    S:  Manufacturer=Linux 3.13.0-37-generic xhci_hcd
    S:  Product=xHCI Host Controller
    S:  SerialNumber=0000:26:00.0
    C:  #Ifs= 1 Cfg#= 1 Atr=e0 MxPwr=0mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=09(hub  ) Sub=00 Prot=00 Driver=hub

**ls-usb**:

    Bus 002 Device 004: ID 0bda:0001 Realtek Semiconductor Corp.
    Bus 002 Device 003: ID 1bcf:2805 Sunplus Innovation Technology Inc.
    Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

body:
The fact that `dmesg` gives you nothing at all is the most telling fact.  The there was a communication problem, or the firmware had messed up on the USB interface chip, then you'd expect something to show up - even if it was something along the lines of "device not accepting address 8: -71"

We can ignore the main ATMega2560 chip since that has no bearing on the USB interface.  Instead we're interested in the ATMega16U2 (or whatever is on your board version).

So some things you need to confirm by probing around on the board with a multimeter, or better still, an oscilloscope:

1. Check that there is power to the board through the USB.
2. Check that there is power both sides of the green (or brown-ish if you have a clone) poly-fuse near the USB socket
3. If you have an oscilloscope, switch the probe to 10x and look for oscillations on the crystal's pins.
4. Grab the datasheet for your ATMega*xx*U2 chip and get the pinout.  Check that there is power on the pins there should be power on.
5. Check that the RESET pin of the ATMega*xx*U2 chip is HIGH.

If you have a hardware programmer, or another Arduino you can use as a hardware programmer, connect it to the 2x3 header (you may need to populate it first) and try get it to identify the chip ID.  Try to re-flash the USB interface firmware.

Another thing to check is the USB socket itself.  Those big chunky USB sockets look strong, but they're actually quite flimsy inside.  The metal leaves that the plug presses against can bend with time and not make a good contact.  Using a fine needle try lifting them up slightly so they make better contact with the cable.  I think Arduino are the only people that still use them in an active product these days ;)


message:
Using Arduino command line on windows

I have an nmake file;

      srcpath = ..\pilot
      cmdline =  "C:\Program Files (x86)\Arduino\arduino.exe"
      cmdflags = --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files
      prefs = --pref sketchbook.path=$(srcpath) --pref build.path=build
      deps = $(srcpath)\pilot.ino $(srcpath)\commands.h $(srcpath)\publish.h $(srcpath)\motor.h

      pilot.hex :$(deps)
     type $(srcpath)\pilot.ino
     $(cmdline) $(cmdflags) $(prefs) $(srcpath)\pilot.ino

The file types out fine, but Arduino returns an error;

"failed to open sketch ..\pilot\pilot.ino"

I am setting --pref sketchbook.path=$(srcpath), but I have tried with and without (and many variations of both) and get the same error.

This is the command that is currently being invoked, and looks correct to me;

    "C:\Program Files (x86)\Arduino\arduino.exe" --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files --pref sketchbook.path=..\pilot --pref build.path=build ..\pilot\pilot.ino

Any ideas?

body:
    srcPath = C:\Users\mikep\Documents\MWPRobotics\Pilot\Pilot
    bldPath = $(srcPath)\build
    arduinoCmd = "C:\Program Files (x86)\Arduino\arduino.exe"
    arduinoFlags = --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files --preferences-file $(bldPath)\pilotPrefs.txt
    prefs = --pref sketchbook.path=$(srcPath) --pref build.path=$(bldPath)

    deps = $(srcPath)\Pilot.ino $(srcPath)\commands.h $(srcPath)\publish.h  $(srcPath)\motor.h

    pilot.hex : $(deps)
    # type $(srcPath)\Pilot.ino
     $(arduinoCmd) $(arduinoFlags) $(prefs) $(srcPath)\Pilot.ino

Apparently it is really picky about absolute full paths (contrary to the comments that say it is relative)


message:
DHT11 with Mysql

I need help to record databаse from dht11 sensor to mysql server.
this is my code:

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

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // RESERVED MAC ADDRESS
    EthernetClient client;

    IPAddress server(192,168,0,102); // IP Adres (or name) of server to dump data to

    #define DHTPIN 2 // SENSOR PIN
    #define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
    DHT dht(DHTPIN, DHTTYPE);

    long previousMillis = 0;
    unsigned long currentMillis = 0;
    long interval = 250000; // READING INTERVAL

    float temperature = 0; // TEMPERATURE VAR
    float humidity = 0; // HUMIDITY VAR
    String data;

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

     if (Ethernet.begin(mac) == 0) {
      Serial.println("Failed to configure Ethernet using DHCP");
     }

     dht.begin();
     delay(10000); // GIVE THE SENSOR SOME TIME TO START

           temperature = (float) dht.readTemperature();
           humidity = (float) dht.readHumidity();

    }

    void loop(){

     currentMillis = millis();
     if(currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
      previousMillis = currentMillis;
      temperature = (float) dht.readTemperature();
                    humidity = (float) dht.readHumidity();
     }

     if (client.connect(server, 3306)) {
              Serial.print("temperature=" );
              Serial.println( temperature );
              Serial.print("humidity=" );
              Serial.println( humidity );
              Serial.println("-> Connected");
                if(client.connected()){
                // Make a HTTP request:
                client.print( "GET /add_data.php?");
                client.print("temperature=");
                client.print( temperature);
                client.print("humidity=");
                client.print( humidity);
                client.println( " HTTP/1.1");
                client.println( "Host: 192.168.0.102" );
                //client.println(server);
                client.println( "Connection: close" );
                client.println();
                client.println();
                client.stop();
              }
            }
     if (client.connected()) {
      client.stop(); // DISCONNECT FROM THE SERVER
     }

     delay(30000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
    }

I connected to database but can't make records. this is output on serial monitor:
temperature=21.00
humidity=73.00
-> Connected

this is my php:add_data.php

    <?php
        // Connect to MySQL
        include("dbconnect.php");

        // Prepare the SQL statement
        $SQL = "INSERT INTO test.test.temperature (temperature ,humidity) VALUES ('".$_GET["temperature"]."', '".$_GET["humidity="]."')";

        // Execute SQL statement
        mysql_query($SQL);

        // Go to the review_data.php (optional)
        header("Location: review_data.php");
    ?>

dbconnect.php=>

    <?php
    $MyUsername = "root";  // enter your username for mysql
    $MyPassword = "fifa2005";  // enter your password for mysql
    $MyHostname = "localhost";      // this is usually "localhost" unless your database resides on a different server

    $dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
    $selected = mysql_select_db("test",$dbh);
    ?>

review_data.php=>

<?php
// Start MySQL Connection
include('dbconnect.php');
?>

        <title>Arduino Temperature Log</title>

Arduino Temperature Log

            ID
            Date and Time
            Temperature
            Humidity

        <?php
        // Retrieve all records and display them
        $result = mysql_query("SELECT * FROM temperature ORDER BY id ASC");

        // Used for row color toggle
        $oddrow = true;

        // process every record
        while( $row = mysql_fetch_array($result) )
        {
            if ($oddrow)
            {
                $css_class=' class="table_cells_odd"';
            }
            else
            {
                $css_class=' class="table_cells_even"';
            }

            $oddrow = !$oddrow;

            echo '
';
            echo '   '.$row["id"].'	';
            echo '   '.$row["timestamp"].'	';
            echo '   '.$row["temperature"].'	';
            echo '   '.$row["humidity"].'	';
            echo '
';
        }
        ?>

body:
You can break down testing in steps.

Call your PHP page from the browser with some dummy parameters and see if it saves them in the DB.

If that part works use a network sniffer, like WireShark to sniff the TCP connection and make sure the correct data is sent to the PHP server from the Arduino.

Depending on which part is not working you can ask the question in the appropriate stack exchange.


body:
You have one problem in the construction of your HTTP GET request on Arduino side:

            // Make a HTTP request:
            client.print( "GET /add_data.php?");
            client.print("temperature=");
            client.print( temperature);
            client.print("humidity=");
            client.print( humidity);

You forgot to separate both request arguments with an ampersand. It should be:

            // Make a HTTP request:
            client.print( "GET /add_data.php?");
            client.print("temperature=");
            client.print( temperature);
            client.print("&humidity=");
            client.print( humidity);

Note the `"&humidity"` instead of just `"humidity"`.


body:
i'm not sure why my old code doesn't work, but this is my new one and it is working fine. Maybe it will help someone.

    #include <dht.h>
    #include <SPI.h>
    #include <Ethernet.h>
    EthernetClient client;
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    char server[] = "192.168.0.101";
    dht DHT;
    int interval = 5000; // Wait between dumps
    #define DHT11_PIN 2
    void setup()
    {
      Ethernet.begin(mac);
      Serial.begin(115200);

      //Serial.println("Humidity (%),\tTemperature (C)");
    }
    void loop()
    {
      Serial.print("Temperature2 = ");
        Serial.print(DHT.temperature);
        Serial.println(" *C");

        Serial.print("Humidity = ");
        Serial.print(DHT.humidity);
        Serial.println(" ");

      // READ DATA
      //Serial.print("DHT11, \t");
      int chk = DHT.read11(DHT11_PIN);

      if (client.connect(server, 80)) {

        client.print( "GET /diplomna/Arduino/add_data.php?");
        client.print("temperature=");;
        client.print( DHT.temperature );
        client.print("&&");
        client.print("humidity=");
        client.println( DHT.humidity );
        client.println( "HTTP/1.1");
        client.println( "Connection: close" );
        client.stop();
        Serial.println("CONNECTED");
      }
      else {
        // you didn’t get a connection to the server:
        Serial.println("–> connection failed/n");
      }
      delay(interval);
    }


message:
Sending sensor readings from Arduino to Raspberry Pi over 433 MHz

I'm building a garden monitor, so I got myself an Arduino Nano, a soil humidity sensor, an air humidity and temperature sensor as well as a luminosity sensor. Since I had not one but two Raspberry Pis laying around I thought I'll handle the receiving end with one of them. I also got a 433 MHz RF kit.

The trail of the information will look like this: Sensor(s) -> Arduino -> 433 MHz Transmitter - - - 433 MHz - - - 433 MHz Receiver -> Raspberry Pi

Now my question is, what libraries should I use? I checked [rc-switch][1] (it has libs for both Arduino as well as [RPi][2]) and managed to send some codes but it seems that I'll need to write my own protocol to use this to transmit even simple data as it wasn't developed for sending data, rather simple switch on / switch off signals to simulate remotes.

[VirtualWire][3] would seem as the ideal candidate but the problem is it doesn't have an RPi equivalent.

Any suggestions?

  [1]: https://github.com/sui77/rc-switch
  [2]: https://github.com/r10r/rcswitch-pi
  [3]: http://www.airspayce.com/mikem/arduino/VirtualWire/

body:
You could look into the [RadioHead](http://airspayce.com/mikem/arduino/RadioHead/) library - there might be a port for RPi, though I couldn't find one with a (very) quick google. This library works well, I use it actually with RFM69H 433 MHz radios (from Moteinos), a little more expensive than the simple 433 kits, but also supports encryption which might be important down the line. If you can't find a good library for RPi one solution could be to have a second Arduino acting as a receiver and sending data serially to RPi. This is what I use with a regular desktop PC which is my home server.

I also found a discussion about connecting a RFM69 to the RPi [here](http://homeautomation.proboards.com/thread/7/raspberry-rfm69-sensor-node-gateway) which might give you more information about the process in general, even if you won't use the same radio.


body: There is custom made library to solve this issue  here and i recomend you read this discussion.


body:
Presuming you want to get results quickly, I recommend you have a look at [openHab][1] This is a Java based home automation framework and server that has plugins for many existing protocols.

Once you get your protocol running it is just a matter of plugging it into openHab for charting and storage. I use for inside home measurements:
![enter image description here][2]

Also [this post][3] will help you further with connect 433 to RasPi and Arduino.

Specifically for temp and humidity sensors there is the reverse engineered Cresta protocol, that is also used in a lot of commercial sensors. See [this Github repo][4] for Arduino code. Also findable for Raspberry Pi.

  [1]: http://openhab.org/
  [2]: https://i.stack.imgur.com/5SM7e.png
  [3]: http://www.princetronics.com/how-to-read-433-mhz-codes-w-raspberry-pi-433-mhz-receiver/
  [4]: https://github.com/mysensors/Arduino/tree/master/libraries/RemoteSensor


body:
I am fairly new to Arduino but have had a basic experience with python on RPi (Model 2). I am trying to connect ultrasonic sensors (for distance measuring) on Arduino  and then send (RF transmission) the value to Raspberry Pi. I am not able to figure out how to write a code for receiving the transmitted code. I have to receive the code, decode it and then update it in my SQLITE database (on the same RPi).

I have already tried RFSniffer but I am unable to receive value other than "INT". RPi shows nothing if I send any "CHAR" or "STRING".

Please do suggest me how should I proceed.

Thanks in advance

Pradeep Verma


message:
connection between two ARDUINO with xbee

I have a setup where two XBEES modules are talking to each other, both using XBEE shields, one attached to an UNO ARDUINO and the other a MEGA ARDUINO. One XBEE sends the data and the other receives it and switch on or off a LED.
The problem is the receiver one don't work.
This is the sender code

    int led = 13;
    const int bouton = 2; String inputString;
    void setup() {
    pinMode(led, OUTPUT);
    Serial1.begin(9600);
    Serial.begin(9600);
    digitalWrite(led, LOW);
    }
    void loop() {
    while (Serial.available() ) {
    // get the new byte:
    delay(3);
    char inChar = Serial.read();
    // add it to the inputString:
    inputString += inChar;
    }
    if (inputString.length() >0) {
    Serial.println(inputString);
    Serial1.println(inputString);
    inputString="";
    }
    }

This the receiver one

    int led = 13;
    String inputString;
    void setup() {
    // put your setup code here, to run once:
    pinMode(led, OUTPUT);
    Serial.begin(9600);
    }
    void loop() {
    while (Serial.available() ) {
    // get the new byte:
    delay(3);
    char inChar = Serial.read();
    // add it to the inputString:
    inputString += inChar;
    }

    if (inputString.length() >0) {
    Serial.println(inputString);
    if (inputString == "on"){
    digitalWrite(led,HIGH);
    Serial.println("LED ON");
    }

    if (inputString == "off"){
    digitalWrite(led,LOW);
       Serial.println("LED OFF");
    }
    inputString="";
    }
    }

I get on the serial monitor of ARDUINO UNO what i wrote in the serial monitor of ARDUINO MEGA but the LED don't switch on or off :/

body: Probably you are getting a new character/carrier return (\n or \n\r) in your receivers' string, that is why it won't match exactly "on" or "off", it will be "on\n", "on\r\n" or similar.


message:
Conflict between OneWire and I2C?

I have two Arduino boards and I want to make them communicate via I2C. The first board (slave) should read a temperature value from a DS18B20 sensor (OneWire) and send it to the second board (master) via I2C.

So, I tried to merge some code from the standard examples (Wire/master_reader, Wire/slave_sender and dallas/simple).

When I use the two sketches bellow, the serial monitor of the master board is printing the "hello " message, but when I enable the request temperature lines (slave code)

<!-- language: c -->

    sensors.requestTemperatures();
    sensors.getTempCByIndex(0);

the serial monitor shows nothing.

I wander if there is a conflict between OneWire and I2C, or if I've made some serious mistakes in the code.

Any suggestions would be appreciated.

#Master

<!-- language: c -->

    #include <Wire.h>

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

    void loop(){
        Wire.requestFrom(2, 6);
        while(Wire.available()){
            char c = Wire.read();
            Serial.print(c);
            }
        delay(500);
       }

#Slave

<!-- language: c -->

    #include <Wire.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #define ONE_WIRE_BUS 2
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    void setup(){
        sensors.begin();
        Wire.begin(2);
        Wire.onRequest(requestEvent);
     }

    void loop(){
    }

    void requestEvent(){

        //sensors.requestTemperatures();
        //sensors.getTempCByIndex(0);

        Wire.write("hello "); // respond with message of 6 bytes
    }

body:
The OneWire stuff can be quite slow. I think I timed doing a temperature read at 12.5 mS which is a long time to be in an ISR. I think you will find that the master assumes it is going to get no response and times out, in that time.

[1-Wire Peripheral Interface - for Arduino ](http://www.gammon.com.au/forum/?id=10902)

What I suggest you do, is get the temperature in the slave, as often as you want, and then just return the temperature when requested. eg.

<!-- language-all: lang-C++ -->

    volatile float lastTemp;

    void loop(){
      sensors.requestTemperatures();
      float t = sensors.getTempCByIndex(0);
      // protect move of 4 bytes
      noInterrupts ();
      lastTemp = t;
      interrupts ();
    }

    void requestEvent(){
      Wire.write ((char *) lastTemp, sizeof lastTemp);
    }

Untested, but that is the general idea.

Documentation about interrrupts, and why I am turning off interrupts when moving the temperature to a global variable: <http://www.gammon.com.au/interrupts>


body:
If there is a conflict, could the slave switch between i2c and one wire?

I don't know how often your device needs to poll, but if you can get away with, say, once per minute, you could poll at regular intervals, and spend the rest of the time (99%) listening for the master. If it is not polled, the number read could be queued. When the master does manage to connect, it could collect the entire queue quickly.

The master, from it's side, could poll more frequently - say once every 53 seconds. About once or twice an hour, it would fail - it would need to handle that gracefully. No matter, it would get the data next time round. Even failing several times in a row wouldn't be a problem; the data would be queued at the slave for later transfer.


message:
Arduino UNO code ignores variables selectively

This is the first code I wrote for my UNO R3 just to feel out the functions and I've already got some jankiness. Throughout this description I am referring to the **first two if statements** one inside the other one.

I'm trying to increment `i` every time the signal is activated and then `j` is used to create a small space of time where the button being pressed will not increment `i`. My problem is my if statement involving `j` seem to be totally ignored. I've tried multiple configurations of the if statement structure to no avail.

Here is where things get interesting. So upon setting up the serial connection back to my PC to debug this irritating problem and printing out the actual value of `j` (to see why it was triggering my if statement prematurely) it magically fixed the problem. It's like until the program literally acknowledges `j`'s value in the print statement it doesn't exist but if it does it works. Any ideas on this?

Note: the serial monitor in both picture depicts consecutive iterations with the signal activated the entire time.

This picture shows the serial monitor after running with the button pressed but the print statement commented out

![This picture shows the serial monitor after running with the button pressed but the print statement commented out][1]

This picture shows the serial monitor at a space where the button was pressed and held (same time frame as image 1) but in this one it increments `i` to 3 and then continues incrementing `j`. How is this happening?

![This picture shows the serial monitor at a space where the button was pressed and held(same time frame as img 1) but in this one it incremements i to 3 and then continues incrementing j. How is this happening?][2]

  [1]: https://i.stack.imgur.com/adizC.jpg
  [2]: https://i.stack.imgur.com/KcVYF.jpg

body:
Its hard to see you code, but I think I can make a pretty good guess from your description what is going on.

It seems that you are using the time it takes to increment a value as a way to slow down your code. I think you are underestimating the speed of the arduino. The time it takes to count to 200 (if I'm reading your pictures right) is almost instant; However, you then start printing to with serial each time. Once the serial buffer is full, `Serial.print()` will wait until there is room in the buffer to place the new value. This time is still small, but making the code wait for it to pass 200 times will take much longer than just waiting for a number to increment to 200.

I think that having added a print statement is slowing down the code enough that your increment based delay is having a noticable effect. What you should do is use the [`void delay(unsigned long milliseconds);`][1] function to cause the code to stop for a bit after it first detects the button has been pressed, and then see if its still pressed afterward. You can also use [`delayMicroseconds(unsigned int)`][2] for shorter but more precise timing. Or better yet, use the [`unsigned long millis();`][3] function to grab and store the time when the button was activated, and continue polling the current time until the desired delay has been acheived. That way is more code, It allows the code to do something productive while it waits or keep looping.

  [1]: http://www.arduino.cc/en/Reference/Delay
  [2]: http://www.arduino.cc/en/Reference/delayMicroseconds
  [3]: http://www.arduino.cc/en/Reference/Millis


body:
Yes, and I do appreciate the original answer as it is effective(something just bugs me about losing sensory capability for any amount of time), I just was not really looking for a work around but rather the engineer in me was simply interested in why the code would be responding the way it was. Anyways though I got around to writing my tester and now it's working like a charm. Maybe I was being sloppy before? Obviously I just need to do a bit more testing. I'll post the code just in case anyone is interested in seeing it(also will keep in mind the preference to actual code rather than screen shot in the future) . Thanks for the support!![enter image description here][1]

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


message:
Can the Arduino Due be used as a serial to USB converter?

The Arduino due exclusively runs on 3.3V, so I am wondering if this can be used as a USB to serial converter just like the Arduino Uno could, or do you need to do level shifting?? Will I ruin the board if I just hook up RX and TX to a 5v device?

body:
Yes it will work as a USB to serial device, however the serial will be at 3.3V not 5V. It'll still be serial though.

For it to send data to a 5V device, depending on the device, it might work.  3.3V is often around the "high" threshold for an input pin on a 5V device, but check the datasheet for the 5V device to be sure.

For receiving data the 5V will be above the 3.3V supply voltage of the main SAM3X chip, so should be avoided. As with most Atmel datasheets, actually finding the information you want is almost impossible, and I haven't found if there is a maximum "over voltage input current" or not, so to be on the safe side a full level shifting voltage divider should be used on the RX pin.


message:
What is the function of the XBee / USB switch on an XBee shield?

I recently bought an XBee shield ([this][1]). The shield has a switch that seems to switch between USB/XBee. However, there is no USB port. What exactly is the switch supposed to do?

  [1]: http://www.ebay.com/itm/New-For-Arduino-ZigBee-XBee-Bluetooth-Bee-V03-Shield-Module-Wireless-Control-Hot/301457628487?_trksid=p2047675.c100005.m1851&_trkparms=aid=222007&algo=SIC.MBE&ao=1&asc=30543&meid=6648f5c1a8f54e9e92e799f4092616ce&pid=100005&rk=3&rkt=6&sd=221568487830&rt=nc

body: Better to check connection with tester. I think it switches connection to bluetooth module directly to your PC (with usb serial converter which is on arduino board)  or with arduino microcontroller.


body: I imagine that the switch has the same functionality as the "serial select" switch on the official Arduino Wireless Shield for XBee modules. Therefore the explanations on the switch settings given there (http://www.arduino.cc/en/Main/ArduinoWirelessShield) probably apply also to your board.