message:
Arduino Mega with nRF24L01+ module

I am having trouble getting this module to work using the tmrh20 lib. I am using these modules with two arduino mega and a 3.3V external power supply. I also placed 10 uF in parallel with the modules power pin. I would really appreciate any comments or suggustions.

In the code below all I am trying to do is turn on a led.
Here are my pin assignment for both arduinos
CE -> 7
CSN -> 8
SCK -> 52
MOSI -> 51
MISO -> 50
IRQ -> unconnected

**Transmitter**

<!-- language: c -->

    //#include <DigitalIO.h>
    #include <SPI.h>
    #include "RF24.h"
    #include <printf.h>
    RF24 radio(7,8);
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    unsigned long msg = 375983;

    void setup() {
        Serial.begin(115200);
        printf_begin();
        Serial.println("Transmitter");
        pinMode(9, INPUT);
        radio.begin();
        radio.setChannel(108);
        radio.openWritingPipe(pipe);
        radio.startListening();
        radio.printDetails();
    }

    void loop() {
      radio.stopListening();
      if (digitalRead(9) == HIGH)
      {
        while (!radio.write(&msg, sizeof(msg))){
          radio.write(&msg, sizeof(msg));
    }
      Serial.println("Sending.....");
      }
      else {
        Serial.println("Awaiting Input....");
      }
      delay(500);

    }

print detail report

    STATUS = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
    RX_ADDR_P0-1 = 0xffffffffff 0xffffffffff
    RX_ADDR_P2-5 = 0x7f 0xff 0x7f 0xff
    TX_ADDR = 0x0000000000
    RX_PW_P0-6 = 0xff 0x7f 0xff 0x7f 0xff 0xff
    EN_AA = 0xff
    EN_RXADDR = 0xff
    RF_CH = 0xff
    RF_SETUP = 0xff
    CONFIG = 0xff
    DYNPD/FEATURE = 0x7f 0xff
    Data Rate = 1MBPS
    Model = nRF24L01
    CRC Length = Disabled
    PA Power = PA_MAX

**Receiver**

<!-- language: c -->

    //#include <DigitalIO.h>
    #include <SPI.h>
    #include "RF24.h"
    #include <printf.h>
    RF24 radio(7,8);
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    unsigned long msg;

    void setup() {
        Serial.begin(115200);
        printf_begin();
        Serial.println("Receiver");
        pinMode(9, OUTPUT);
        radio.begin();
        radio.setChannel(108);
        radio.openReadingPipe(0,pipe);
        radio.printDetails();

    }

    void loop() {
       radio.startListening();
       digitalWrite(9, LOW);
      if(radio.available()){
        while(radio.available())
        {
        radio.read(&msg, sizeof(msg));
        Serial.println("Incoming...");
        delay(500);
        Serial.println(msg);
        }
      }
      else{
        Serial.println("No Msg");
      }
      radio.stopListening();
      Serial.println(msg);
      if (msg == 375983){
        digitalWrite(9, HIGH);
        Serial.println(msg);
      }
      delay(500);
    }

print detail report

    STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
    RX_ADDR_P0-1 = 0x0000000000 0x0000000000
    RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
    TX_ADDR = 0x0000000000
    RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
    EN_AA = 0x00
    EN_RXADDR = 0x00
    RF_CH = 0x00
    RF_SETUP = 0x00
    CONFIG = 0x00
    DYNPD/FEATURE = 0x00 0x00
    Data Rate = 1MBPS
    Model = nRF24L01
    CRC Length = Disabled
    PA Power = PA_MIN

UPDATE:
Transmitter PrintDetail

    STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
    RX_ADDR_P0-1  = 0x00000000e1 0xc2c2c2c2c2
    RX_ADDR_P2-5  = 0xc3 0xc4 0xc5 0xc6
    TX_ADDR   = 0x00000000e1
    RX_PW_P0-6  = 0x20 0x00 0x00 0x00 0x00 0x00
    EN_AA   = 0x3f
    EN_RXADDR  = 0x02
    RF_CH   = 0x6c
    RF_SETUP  = 0x07
    CONFIG   = 0x0f
    DYNPD/FEATURE  = 0x00 0x00
    Data Rate  = 1MBPS
    Model   = nRF24L01+
    CRC Length  = 16 bits
    PA Power  = PA_MAX

Results form tmrh20 Getting Started Example

First Arduino

    Sent 8340224, Got response 0, Round-trip delay 547172 microseconds
    Now sending
    Sent 9889124, Got response 0, Round-trip delay 511072 microseconds
    Now sending
    Sent 11401920, Got response 0, Round-trip delay 43348 microseconds
    Now sending
    Sent 12446992, Got response 0, Round-trip delay 635580 microseconds
    Now sending
    Sent 14084352, Got response 0, Round-trip delay 1620788 microseconds
    Now sending
    Sent 16706968, Got response 0, Round-trip delay 1227548 microseconds
    Now sending
    Sent 18936340, Got response 0, Round-trip delay 145372 microseconds

Second Arduino

    *** PRESS 'T' to begin transmitting to the other node
The second arduino is not printing anything on the serial monitor, no matter what I enter.

body:
Try these:

- Set pin 9 on the TX side as a pulled-up input i.e. `pinMode(9, INPUT_PULLUP);`
Connect one end of the switch to GND and the other to pin 9. Then in your code, test for a button press like this: `if (digitalRead(9) == LOW){...}`
- Use a byte array for holding the address instead of the 64-bit int you're using.
- Remove the `stopListening()` call in your RX loop(); there is no need for it since all its doing is receiving.
- Remove the 500 ms delays in the RX loop() just in the unlikely case that its causing you to lose bytes


sender: user

sender: assistant

body:
(not enough point to comment, so here's a potential answer)
I had enormous troubles getting these things to work reliably.  I tried all kinds of caps over the power supply. In the end I went for a 1$ piggy back board that takes 5v input and regulates to 3.3V. It also has the right pin female header to fit the nfr nicely. Since then I've had no issues. I also did a bit of experimentation and found that the RX side was the side giving problems.


message:
How to program arduino due without arduino ide

Is it possible to program the Arduino Due without the Arduino IDE? Is there a standalone program that can be downloaded, and be used to upload a .bin file (which has already been generated from the arduino IDE) to the Due? Any guidance appreciated.

I read about SAM-BA programmer, downloaded it but double clicking the .exe file does nothing. Something seems to open but it disappers.

body:
The standalone program for most arduinos is avrdude: http://www.nongnu.org/avrdude/

However, for the Due, it is [BOSSA][1]:

> Unlike other Arduino boards which use avrdude for uploading, the Due
> relies on [bossac][2].
>  -- [Arduino Due Overview][3]

  [1]: https://sourceforge.net/projects/b-o-s-s-a/
  [2]: http://sourceforge.net/projects/b-o-s-s-a/
  [3]: https://www.arduino.cc/en/Main/ArduinoBoardDue


body:
Usually when on opening a program you get a console that pops on, it means that this program is meant for commandline usage and not CLI.

You should open a terminal, `cd` in the downloaded .exe directory, and then type that tool's name. You might want to try adding `--help` after the program's name to learn how to use it.

Another good idea is to look at what Arduino does by clicking on the verbose option in the preferences. Then you'll be able to copy/paste the command call and modify it to upload the firmware blob you want.

Finally, if you look up "AVR SAMX upload tool windows" on google you might find a GUI wrapper for the command line tool.


message:
Can a KCPI-3101 be replaced with an Arduino?

I'm planning to use a KPCI-3101 Keithley with a computer to creat a DAS with a sensor to show the data on computer

can i replace the Card and computer with an Arduino?

body:
You can't replace the [KPCI-3101 Keithley's][1] 16 channels of 12 bit 225kS/s with an Arduino.

  [1]: http://www.testequipmentdepot.com/keithley/multifunction-boards/kpci-3101a.htm


body:
An Arduino's ADC cannot sample fast enough to sustain 225ksps over 16 channels. That equates to a total of 3.6Msps.  The Arduino can manage something like 120ksps in total.

That's not to say there aren't microcontrollers that can't do that kind of speed - there are.  The PIC32MZ, for instance, can run at 15Msps (although it's somewhat buggy still) and there are many other microcontrollers.

The main bottleneck though is in the communication between the microcontroller and the computer.  Regardless of the sampling speed of an Arduino the serial interface is too slow for high speed sampling. Even at its practical maximum of around 2Mbps it gives you 200000 bytes per second, which with 2 bytes per sample would be 100ksps maximum throughput, not taking into account any protocol overheads.

So that's where having a PCI card is a big advantage. A 32-bit (or even 64-bit on PCI64) 66MHz direct channel to the CPU means you can shift considerably more data. And having the computer perform DMA access means that smooth data transfers without the CPU needing to be involved can be performed.


message:
Can I connect an Arduino GSM Shield directly to a PC?

Is it possible to communicate with and use the GSM shield directly from the computer, without using an arduino board?

body:
You can connect a https://www.arduino.cc/en/Main/ArduinoGSMShield to your computer with a USB-TTL serial cable, but you need to make sure you supply enough 700-1000ma to drive the GSM when it is transmitting.

> Power
It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use.


message:
What variables to declare for controlling a motor with high power motor controller

I was getting started with programming a motor controller with the Arduino Uno, in this case it's a mega motor shield ([the motor driver shield I'm using][1]).
  [1]: http://www.robotshop.com/en/arduino-compatible-mega-motor-shield-1a-5-28v.html#Useful Links
The problem I have doing this is that I'm not sure what variables to use for the motor which is connected to two outputs labeled MA and MB.  I used motorValue to set the speed previously and used motorPin for writing the speed with the Arduino and a breadboard, but I'm not sure what to use in place of that for the motor being connected to the driver shield outputs.

body:
Variables are just names assigned to numbers. The names, as far as your program is concerned, are completely meaningless.

It's the numbers you assign to the variables and, more importantly, what you *do* with those variables that is important.

Your shield seems to have jumpers to select what I/O pins perform which function, so you just need to write the software to control the chosen I/O pins in the right way.


message:
Read ISO/IEC 14443B (NFC Type B) with PN532

I bought a [PN532 from Elechouse][1] ([documentation here][2]) because I need to read IDs from `Type B` NFC cards.

My problem is that even if they say the hardware supports `Type B`, the official libraries an examples they provide are not made to.

I have not problem reading `Type A` cards, but nothing happends when I tap `Type B` cards.

After long searchs on internet I found that absolutely every `PN532` sellers have chosen to support only `Type A` cards in their libraries because according to them, a librari supporting both types would have taken too much space in Arduino's memory.

So today my problem is as simple as that: **how to read Type B NFC cards using PN532 on an Arduino UNO?**

I'm a bit new in Arduino so after many hours of searching and trying I couldn't figure out how to do it.

  [1]: http://www.elechouse.com/elechouse/index.php?main_page=product_info&cPath=90_93&products_id=2242
  [2]: http://www.elechouse.com/elechouse/images/product/PN532_module_V3/PN532_ Manual_V3.pdf

body:
I dont have an exact reply but

1) are you certain the other tags are type b?

2) hace you tried connecting the reader using a UART USB cable? You could use libnfc, to check if the reader works.
And going forward [at commands FOR the reader][1] are a good way to debbug.

  [1]: http://www.nxp.com/documents/user_manual/141520.pdf


message:
Arduino millis() won't work

This is my program. The LED should turn off after four seconds.

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

    int vraag = 7;
    int gloeikaars = 5;
    unsigned long previousMillis3;
    boolean gloeistate = true;

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

    void loop() {
        int x = digitalRead(vraag);
        if (x == 0) {
            digitalWrite(gloeikaars, !LOW);
        } else {
            Gloeikaars();
        }
    }

    // *********************************************************************
    // Gloeikaars aansturing
    // *********************************************************************
    void Gloeikaars() {
        unsigned long huidig = millis();
        digitalWrite(gloeikaars, !HIGH);
        if ((gloeistate == true) && (huidig - previousMillis3 >= 4000)) {
            huidig = previousMillis3;
            digitalWrite(gloeikaars, !LOW);
            gloeistate = false;
        }
    }

Can someone help me because it won't work?

body:
Your `previousMillis` variable is never set.  Two changes:

In setup:

    ...
    previousMillis3 = millis();
    ...

In loop:

    ...
    previousMillis3 = huidig;
    ...


message:
In Linux how do I start up Atmel Studio

I am using Linux Fedora 20. In order to compile C programs for the Arduino, as described in the book "C Programming with Arduino" by Warwick A Smith, pub by Elektor, I have downloaded and untarred/unzipped "avr8-gnu-toolchain-3.5.1.1671-linux.any.x86.tar.gz". That's as far as I can get. Please how do I proceed from this point? Is there anything else I need or should have done?

body:
https://mil.ufl.edu/374/docs/Install_Atmel_Studio_7.0.pdf :

Note for Mac and Linux Computer Users

If you have a Mac (i.e., a Macintosh computer from Apple) or if you use Linux, you will need an alternate Windows installation
or you will need to install a Windows virtual machine in order to then install and run Atmel Studio.

We suggest that you install
Boot Camp (free and the best); Parallels (not free) or possibly VMware (not free) may also work. UF offers free copies of
Windows 10 Software.

We do not recommend Virtual Box. Wine is another alternative, but this has not been verified to work.
(Note: My best students use Boot Camp!)


message:
ILI9163C screen not working properly

I've just tried out my new TFT_ILI9163C display with [TFT_ILI9163C][1] library but I'm having an issue with it. The graphics has moved down (the "hello world" should be in the top left) and the leftover space looks like there was no signal. Can be seen in the photo.
What could be wrong?

[![looks kind of no signal][2]][2]

  [1]: https://github.com/sumotoy/TFT_ILI9163C
  [2]: https://i.stack.imgur.com/TdGMl.jpg

body:
I wrote my own driver for DisplayCore for that very same board a while back and found the exact same problem.

The issue is just the setting for the offset of the GRAM which it looks like there is a setting for in the library you are using.  Get that value right and you will have a proper display.


body:
I had the same board and problem as you, what fixed is was changing the board setting to black even though it is phyiscally red.

Inside

    Arduino\libraries\TFT_ILI9163C\_settings\TFT_ILI9163C_settings.h

Change

    //  ---> SELECT HERE <----
    #define __144_RED_PCB__//128x128
    //#define __144_BLACK_PCB__//128x128
    //#define __22_RED_PCB__//240x320

to

    //  ---> SELECT HERE <----
    //#define __144_RED_PCB__//128x128
    #define __144_BLACK_PCB__//128x128
    //#define __22_RED_PCB__//240x320


body:
1. Open the file

  `{sketchbook folder}/libraries/TFT_ILI9163C/_settings/TFT_ILI9163C_settings.h`

 in a text editor. You can find the location of the sketchbook folder in the Arduino IDE at **File > Preferences > Sketchbook location**.
1. Change:

        #define __OFFSET      32

 to:

        #define __OFFSET      0
1. Save the file.
1. Upload the sketch to the Arduino board again.


message:
How do you control the amount of times the void loop loops per second?

int firstAnalogPin = 0;
    int secondAnalogPin = 5;
    int firstVal = 0;
    int secondVal = 0;
    void setup(){

      Serial.begin(9600);          //  setup serial

    }

    void loop(){

    firstVal = analogRead(firstAnalogPin);
       // read the input pin

    secondVal = analogRead(secondAnalogPin);
       // read the input pin

    Serial.print(firstVal);

    Serial.print("\t");

    Serial.println(secondVal);

    }

Basically, I want to know how to convert from the baud rate to the number of times `loop()` runs per second. How do I control the number of `loop()`s per second?

body: If your goal is to control how often the sensor is polled and printed to SD card, I would suggest you check out Blink Without Delay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay it would be a much cleaner way than trying to slow down the loop to a specified time.


body:
The number of times `loop()` runs every second depends on the time taken for the execution of the instructions *within* `loop()`. For instance, in your code, the time taken for one `loop()` is roughly equal to the time taken for the MCU to execute all the statements in `loop()` (more specifically, the time taken for each operation or function from call to return): in your case, the time taken for the `Serial.print()`s + the time taken for the `analogRead()`s (not considering any interrupts between statements).

That said, you generally don't want to control the interval between `loop()`s; I assume you actually want to control the interval between the execution of certain operations within your `loop()`. Say, you want to set the time between executions of `analogRead(0)` to 500 ms. This can be done like this:

    #define INTERVAL 500   // time between reads
    unsigned long lastRead = 0;

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

    void loop(){
      //....your other code....

      if (millis() - lastRead >= INTERVAL){  // if INTERVAL has passed
        val = analogRead(0);
        lastRead = millis();
        Serial.println(val);
        //...anything else
      }

      //...your other code...
    }

With this code, you now have about 2 `analogRead` samples every second. Of course, this is only useful if `loop()` runs faster than your chosen interval. If there are function calls, or any operations otherwise, in `loop()` (within or outside the IF block) that always take more time than your interval, then this code would serve no purpose.


body:
Marcello Romani's [SimpleTimer library][1] was made for this kind of problem. You let `loop()` run as fast as possible but only maintain the timers and do other _short_ tasks. The timer library runs your periodic tasks when necessary:

    #include <SimpleTimer.h>
    SimpleTimer timer;         // creates a set of timers

    // A timer call-back function - there can be more than one
    void onTimer(void){
       ;   // do stuff here, keep it short
    }

    void setup(void){
       ;   // Serial.begin() and other setup

       timer.setInterval(1000L, onTimer); // set a 1-sec repeating timer
    }

    void loop(void){
       timer.run();   // updates timers, maybe calls a callback func
       ;              // whatever other loop code
    }

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


message:
Stuck on uploading sketch via USB 6 pin

I'm just got a Galileo Gen2 and wanted to try a simple blinking-led. The firmware have been updated to 1.0.4. My problem is whenever I try to upload the code I get this error:

    Sketch uses 83,775 bytes (0%) of program storage space. Maximum is 10,000,000 bytes.
    ...
    echo "Sending Command String to move to download if not already in download mode"
    echo "~sketch downloadGalileo" > $tty_port_id

    Deleting existing sketch on target
    #Move the existing sketch on target.
    echo "Deleting existing sketch on target"
    "$fixed_path/lsz.exe" --escape -c "mv -f /sketch/sketch.elf /sketch/sketch.elf.old" <> $tty_port_id 1>&0
    Login timed out after 60 secondsPoky 9.0.2 (Yocto Project 1.4 Reference Distro) 1.4.2 clanton /dev/ttyS1clanton login:`

body: The answer was simply that 6-pin are not designed for uploading sketches. Instead use the micro-USB port to upload sketches.


message:
Arduino Timer Button

I am wandering how I would make it so the arduino uno will start a timer when button a is pressed and send "Start" or "Begin" or something like that to the console window. after the timer has started when button b is pressed it will mark the time from start of the timer and put it in the console window. After the timer has started when button c is pressed it will mark the time from start of the timer and put it in the console window. So on and so forth until button e, when button e is pressed i need the time to get logged in the console and they say "End" or "Stop" or something and then pause the sequence until I restart the board. This is for a school project and my only issue really is how to log the times On a timer loop persay.

body:
Ordinarily, posters are expected to say what they've tried so far, and to show the code they've written.  However, with a problem as difficult as this one, it seems reasonable to illustrate a complete program.

Note, this program assumes that one side of each button goes to Ground and the other side goes to a digital pin with its input pullup turned on.  (If you connect one side to +5V instead of to ground, you will need additional circuitry to sense button presses.)  The digital pins that are used are selected by changing the values swA, swB, and so forth, in the third line of the program.

<!-- language: lang-py -->

    //  jw - 8 Mar 2016 - Program for buttons demo
    // Ref: http://arduino.stackexchange.com/questions/21590/arduino-timer-button
    enum { swA=8, swB=9, swC=10, swD=11, swE=12}; // Switchbutton lines
    enum { nSwitches=5 };
    byte buttonPins[nSwitches]={swA, swB, swC, swD, swE};
    byte buttonBusy[nSwitches]={  0,   0,   0,   0,   0};
    unsigned long startTime;
    //--------------------------------------------------------
    void setup() {
      for (int i=0; i<nSwitches; ++i)
      // Note, this code assumes one side of button goes to Ground
      // and other side to a digital pin with its input pullup turned on
        pinMode(buttonPins[i], INPUT_PULLUP);
      Serial.begin(115200);
      Serial.println("Program begins");
    }
    //--------------------------------------------------------
    void doButton(byte b) {
      char *blabels[] = {"A, Start", "B", "C", "D", "E, End"};
      if (digitalRead(buttonPins[b]) && !buttonBusy[b]) {
        // The b'th button has freshly turned on.
        unsigned long now = millis();
        if (b>0 && !buttonBusy[0]) // To ignore B-E if A isn't on
          return;
        buttonBusy[b] = 1;
        if (b==0) startTime = now; // Button A resets timer
        Serial.print("Button ");
        Serial.print(blabels[b]);
        Serial.print(" at time ");
        Serial.println(now-startTime);
        if (b==nSwitches-1) { // Last Button ends timing, restarts cycle
          for (byte k=0; k<nSwitches; ++k)
            buttonBusy[b] = 0; // Clear all the busy-flags
        }
      }
    }
    //--------------------------------------------------------
    void loop() {
      for (int b=0; b<nSwitches; ++b)
        doButton(b);
    }

*Edit:* Note that triggering messages on button-release instead of button-press would be relatively easy if buttons didn't bounce.

Before explaining that, let's look at why the above code should work.  Assume the cycle (buttons A and later E getting pressed, and possibly some of B, C, D too) lasts at least a couple of seconds.  Assume we have ordinary button hardware, and that contacts can bounce for several milliseconds at each make or break.  When you press a button the Arduino sees a lot of pin-turning-on events, eventually settling at pin-is-on.  When you release a button the Arduino sees a lot of pin-turning-off events, eventually settling at pin-is-off.  And finally, assume each button press is long enough that at least one `digitalRead()` happens while contacts are closed.

Under those assumptions, the very first time in each cycle that we see a given button closed, we know that button has just been pressed.  Also, we can plausibly expect closure of button A to register before closures of other buttons, and can expect the closure of E to register after that of other buttons.  So we can ignore bounce.

On the other hand, with on-release triggering we need to distinguish whether a pin-turning-off event is due to contact bounce of a button just pressed, or is actually part of a button-release bounce sequence.

Here's a method worth considering if you want to implement trigger-on-release:
 • First, add a `delay(1)` call, in `loop()`.  This will make the code timing less processor-dependent, so it can run on a 48- or 72-MHz system as well as on 16-MHz Unos.
• Each time you detect that button b is on, execute `buttonBusy[b] = 40` to start (or restart) a 40-ms timeout.  That is, while a button is held down, we keep setting its timeout to 40.  (40 ms may be overly conservative.  20 ms should work ok with most switches, and 10 is ok with a lot of them.)
• When you detect that button b is off,
`  ` • if `buttonBusy[b]` is zero, do nothing.
`  ` • if `buttonBusy[b] > 0`, then decrement `buttonBusy[b]` and test if it now is equal to 1.  When it's equal to 1, regard b as released, so do its action.


message:
why does it use A0 to define analog pin 0 in some case and why use 0 directly?

https://www.arduino.cc/en/Tutorial/AnalogInput

https://www.arduino.cc/en/Tutorial/Knob

For first line of both examples(not in comments), it define the same pin, analog pin 0, but they use different values. why and can use A1, A2, etc. to define other analog pins?

body:
You can use 0 to 5 for `analogRead` of pins A0 to A5. However if you want to do `digitalRead` or `digitalWrite` on those pins then you have to use `A0` through to `A5` in order to avoid confusing them with the digital pins 0 to 5 (on the other side of the board).

> can use A1, A2, etc. to define other analog pins?

Yes.


body:
The answer is in the source code. Keep in mind that for this answer, I'm assuming you have a standard Arduino Uno. For other Arduino platforms the values are different but the situation is the same.

If you look at the analog pin definitions in `hardware/arduino/avr/variants/standard/pins_arduino.h`, you'll find these lines:

    static const uint8_t A0 = 14;
    static const uint8_t A1 = 15;
    static const uint8_t A2 = 16;
    ...

Which tells you that if you call `analogRead(A0)`, it is equivalent to calling `analogRead(14)`. So, really, the question is "How can calling `analogRead(0)` work?"

The answer to that is in `hardware/arduino/avr/cores/arduino/wiring_analog.c`. If you wade through the defines, you'll see that at the top of `analogRead`, there is the following code:

    if (pin >= 14) pin -= 14; // allow for channel or pin numbers

The result is that passing either `0` or `A0` results in `0` being used in the `analogRead` code.


message:
IOt application example Error

I have downloaded code from below link[Link of code][1]. I am trying test code from below. I am getting warning for below code.I couldnot able to find how to sort out

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

    /* ------------------ */
    /* SKETCH CREDENTIALS */
    /* ------------------ */

    const char *deviceId     = "<D56debb6351d9d4e74e000015>";             // * set your device id (will be the MQTT client username)
    const char *deviceSecret = "<Y4h+R1NRAxrhFciRhtHLj66ERSv8RExu>";         // * set your device secret (will be the MQTT client password)
    const char *outTopic     = "devices/<D56debb6351d9d4e74e000015>/set"; // * MQTT channel where physical updates are published
    const char *inTopic      = "devices/<D56debb6351d9d4e74e000015>/get"; // * MQTT channel where lelylan updates are received
    const char *clientId     = "<CLIENT-ID>";             // * set a random string (max 23 chars, will be the MQTT client id)

    /* ------------ */
    /* SKETCH LOGIC */
    /* ------------ */

    /* Server settings */
    byte server[] = { 178, 62, 108, 47 }; // MQTT server address

    /* Sample payload published to lelylan */
    /* The id is the status property id of the basic light /*
      /* http://lelylan.github.io/types-dashboard-ng/#/types/518be107ef539711af000001/ */
    const char *payloadOn  = "{\"properties\":[{\"id\":\"56debb6351d9d4e74e000015\",\"value\":\"on\"}]}";
    const char *payloadOff = "{\"properties\":[{\"id\":\"56debb6351d9d4e74e000015\",\"value\":\"off\"}]}";

    /* Ethernet configuration */
    byte mac[] = { 0xA0, 0xA0, 0xBA, 0xAC, 0xAE, 0x12 };
    EthernetClient ethClient;

    /* MQTT communication */
    void callback(char* topic, byte* payload, unsigned int length); // subscription callback
    PubSubClient client(server, 1883, callback, ethClient);         // mqtt client

    /* Pins configuration */
    int inPin = 2; // button
    int outPin = 4; // led

    /* Button and led logics */
    int state = HIGH;     // current state of the output pin
    int reading;          // current reading from the input pin
    int previous = LOW;   // previous reading from the input pin
    long time = 0;        // the last time the output pin was toggled
    long debounce = 200;  // the debounce time, increase if the output flickers

    /* arduino setup */
    void setup() {
      Serial.begin(9600);
      delay(500);

      Ethernet.begin(mac);
      Serial.print("Connected with IP: ");
      Serial.println(Ethernet.localIP());

      lelylanConnection();      // MQTT server connection
      pinMode(inPin, INPUT);    // button pin setup
      pinMode(outPin, OUTPUT);  // led pin setup
    }

    /* arduino loop */
    void loop() {
      lelylanConnection();

      const char *value;
      reading = digitalRead(inPin);  // read the button state

      // if the input just went from LOW and HIGH and we've waited long enough to ignore
      // any noise on the circuit, toggle the output pin and remember the time
      if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        if (state == LOW) {
          Serial.println("[PHYSICAL] Led turned on");
          lelylanPublish("on");
          state = HIGH;
        } else {
          Serial.println("[PHYSICAL] Led turned off");
          lelylanPublish("off");
          state = LOW;
        }

        time = millis();
      }

      // effectively update the light status
      digitalWrite(outPin, state);
      previous = reading;
    }

    /* MQTT server connection */
    void lelylanConnection() {
      // add reconnection logics
      if (!client.connected()) {
        // connection to MQTT server
        if (client.connect(clientId, deviceId, deviceSecret)) {
          Serial.println("[PHYSICAL] Successfully connected with MQTT");
          lelylanSubscribe(); // topic subscription
        }
      }
      client.loop();
    }

    /* MQTT publish */
    void lelylanPublish(char *value) {
      if (value == "on")
        client.publish(outTopic, payloadOn); // light on
      else
        client.publish(outTopic, payloadOff); // light off
    }

    /* MQTT subscribe */
    void lelylanSubscribe() {
      client.subscribe(inTopic);
    }

    /* Receive Lelylan message and confirm the physical change */
    void callback(char* topic, byte* payload, unsigned int length) {
      // copu the payload content into a char*
      const char *json;
      json = (char *) malloc(length + 1);
      memcpy(json, payload, length);
      json[length] = "\0";

      // update the physical status and confirm the executed update
      if (String(payloadOn) == String(json)) {
        Serial.println("[LELYLAN] Led turned on");
        lelylanPublish("on");
        state = HIGH;
      } else {
        Serial.println("[LELYLAN] Led turned off");
        lelylanPublish("off");
        state = LOW;
      }

      digitalWrite(outPin, state);
      free(json);
    }

  [1]: http://lelylan.github.io/lab-projects/arduino-ethernet-light/

> Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"
>
> C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino: In function 'void
> loop()':
>
> C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:77:26: warning:
> deprecated conversion from string constant to 'char*'
> [-Wwrite-strings]
>
>        lelylanPublish("on");
>
>                           ^
>
> C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:81:27: warning:
> deprecated conversion from string constant to 'char*'
> [-Wwrite-strings]
>
>        lelylanPublish("off");
>
>                            ^
>
> C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino: In function 'void
> callback(char*, byte*, unsigned int)':
>
> IOT_Testcode:124: error: invalid conversion from 'const void*' to
> 'void*' [-fpermissive]
>
>    memcpy(json, payload, length);
>
>                                ^
>
> In file included from C:\Program Files
> (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:25:0,
>
>                  from sketch\IOT_Testcode.ino.cpp:1:
>
> c:\program files
> (x86)\arduino\hardware\tools\avr\avr\include\string.h:117:14: error:
> initializing argument 1 of 'void* memcpy(void*, const void*, size_t)'
> [-fpermissive]
>
>  extern void *memcpy(void *, const void *, size_t);
>
>               ^
>
> IOT_Testcode:125: error: assignment of read-only location '*(json +
> ((sizetype)length))'
>
>    json[length] = "\0";
>
>                 ^
>
> IOT_Testcode:125: error: invalid conversion from 'const char*' to
> 'char' [-fpermissive]
>
> C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:130:24: warning:
> deprecated conversion from string constant to 'char*'
> [-Wwrite-strings]
>
>      lelylanPublish("on");
>
>                         ^
>
> C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:134:25: warning:
> deprecated conversion from string constant to 'char*'
> [-Wwrite-strings]
>
>      lelylanPublish("off");
>
>                          ^
>
> IOT_Testcode:139: error: invalid conversion from 'const void*' to
> 'void*' [-fpermissive]
>
>    free(json);
>
>             ^
>
> In file included from C:\Program Files
> (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:23:0,
>
>                  from sketch\IOT_Testcode.ino.cpp:1:
>
> c:\program files
> (x86)\arduino\hardware\tools\avr\avr\include\stdlib.h:305:13: error:
> initializing argument 1 of 'void free(void*)' [-fpermissive]
>
>  extern void free(void *__ptr);
>
>              ^
>
> exit status 1 invalid conversion from 'const void*' to 'void*'
> [-fpermissive]
>
>   This report would have more information with   "Show verbose output
> during compilation"   enabled in File > Preferences.

Kindly let me know how to resolve these warning

body:
This code was written and tested using an earlier Arduino IDE version, the author's upload of the source files happened over a year ago.

Within the Arduino 1.6.x branch the preprocessor and compiler behaviour have changed (among other things).

Older libraries will require an earlier Arduino IDE version (i.e. the 1.5.x branch) from https://www.arduino.cc/en/Main/OldSoftwareReleases#previous.

Additionally, we have to keep in mind that there are differences between Arduino.cc and Arduino.org. Those two projects split apart, their IDEs aren't equivalent any more.


message:
Brand new to Arduino, and can't even make an LED blink

So I'm going through Getting Started With Arduino. I skipped to making a LED blink when you press a button.

First I wrote the code, then I copied it directly from the .pdf I have, neither has worked.

The code is here:

    // Example 02: Turn on LED while the button is pressed
    const int LED = 13;   // the pin for the LED
    const int BUTTON = 7; // the input pin where the
                          // pushbutton is connected
    int val = 0;          // val will be used to store the state
                          // of the input pin
    void setup() {
      pinMode(LED, OUTPUT);   // tell Arduino LED is an output
      pinMode(BUTTON, INPUT); // and BUTTON is an input
    }
    void loop(){
      val = digitalRead(BUTTON); // read input value and store it
      // check whether the input is HIGH (button pressed)
      if (val == HIGH) {
        digitalWrite(LED, HIGH); // turn LED ON
      } else {
        digitalWrite(LED, LOW);
      }
    }

![enter image description here][1]

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

body:
Other than what what Nick Gammon said that you need the resistor from the board to led, as that will cause your microcontroller pins to get damaged.

The other possible problem is the two breadboards you have put together, the power rails have not been bridged between the two boards. This means that the switch is not providing any logical state to the microcontroller.

Also the only reason why the led is show in the book as a separate thing is that it is meant as an educational exercise to make you build something, the `L` led will do the same thing.


message:
How do I statements for the various conditions of this function?

I am still new to Aduino and I am trying to use a library's example sketch but I don't understand the following part of the code. I want to trigger an led when the "Pressed" condition is fulfilled. Pardon my ignorance.

    if (b != ClickEncoder::Open) {
    Serial.print("Button: ");
    #define VERBOSECASE(label) case label: Serial.println(#label); break;
    switch (b) {
      VERBOSECASE(ClickEncoder::Pressed);
      VERBOSECASE(ClickEncoder::Held)
      VERBOSECASE(ClickEncoder::Released)
      VERBOSECASE(ClickEncoder::Clicked)

      case ClickEncoder::DoubleClicked:
          Serial.println("ClickEncoder::DoubleClicked");
          encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
          Serial.print("  Acceleration is ");
          Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
          setMode = true;
           value = 0;
        break;
    }
  }

body:
You will have to explicitely expand the case `ClickEncoder::Pressed`. So instead of

    VERBOSECASE(ClickEncoder::Pressed);

you should write something like

    case ClickEncoder::Pressed:
        Serial.println("ClickEncoder::Pressed");
        digitalWrite(ledpin, HIGH);
        break;

Of course then you'll have to turn it off then, but.. Well, that's another problem


message:
Mounting Arduino in an enclosure

I've decided to use Sparkfun's Pro Mini boards to make my project into a semi-professional product.

My first thought turned to enclosures - of which the entire internet seems to be bereft. If I ever DO see an enclosure, it's for the Uno sized board and costs about twice the price of the board, which seems incredible to me.

No matter, I have found a way to make quite good enclosures for the Pro Mini pretty easily and cheaply.

HOWEVER, the next problem is mounting the board inside the box. I would like to be able to mount it firmly to the base but in a way which allows it to be removed if necessary. Obviously, there's not a lot of scope for putting screws through the board. It occurs to me that anything which holds it would need to do so by gripping the edges or the corners. Is there such a thing?

If there's nothing that fits the bill, would the board be OK if I were to HOT GLUE it to the base of the enclosure?

body:
What type of box?
Howmany times/how easily do you want to remove the Arduino Mini?

**Hot glue**

Hot glue is the way to go in many occasions.

 - It does not conduct electricity, so is pretty safe. (Please check your specific hot glue first)
 - It sticks quite well, for quite a time. You should also check if it's water resistant or fit for your target environment though.

But, it may have some side-effects:

 - It can get quite messy (which does not look really professional)
 - It's not that easily removable and has to be "re-glued" when you want to stick it back.
 - It might be too sticky (in a carboard box, you won't be able to just rip out the Arduino, withouth damaging the box).

*You could use double sided tape, which might actually work fine. Or atleast better/neater as the hot glue.*

**Sticky velcro**

A neat solution would be sticky velcro. You can easily attach, detach and re-attach the arduino to the velcro. It looks quite fancy and should hold well.

Again, you should check the specific velcro, it might not last 1000+ times of re-attaching (become loose or smh). But will be a good option overall.

[![sticky velcro][1]][1]

**Extra**

You can use mint-boxes as an enclosure. But they're usually made of tin or another conductive material. Please take care and cover the back of your arduino (or box) with electrical tape, to avoid shorts.

Extra-extra, you should (for "replacability") add connectors or headers to your Arduino. Since soldering the leads directly will still give the need to un-solder or resolder your Arduino when replacing.

**Note on making your Arduino project a consumer item**

You might save yourself quite some money by using a barebones arduino. Or actually, an ATmega 328P chip. Which is around 3€.
These will be a little more difficult to program, but might also look more professional.

You can also enable "program protection" fuse bits, so that others can't download the code from your arduino/microcontroller.

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


message:
How to read data from Arduino with Raspberry Pi via I2C?

I have connected a Raspberry Pi 2 model B to an Arduino Uno via Bi-Directional Level shifter, from this [BLOG][1]:

    Raspberry pi    GND    ----------   GND     Arduino
                    3.3v   ----------   5v
                    SCL    ----------   A5
                    SDA    ----------   A4

I hope my I2C connection is correct.

And my Arduino is connected to an 8-Channel relay board.

Now I have written code in which I can control the relay board with the Raspberry Pi. For example, if I Press '1', relay 1 goes high.

Now I want to send data back from the Arduino to the Raspberry Pi in order to cross-check if relay 1 is high or not. If relay 1 is high then it should send some data back to the Raspberry Pi.

My Raspberry Pi code is:

    import smbus
    import time
    # for RPI version 1, use "bus = smbus.SMBus(0)"
    bus = smbus.SMBus(1)

    # This is the address we setup in the Arduino Program
    address = 0x04

    def writeNumber(value):
        bus.write_byte(address, value)
        # bus.write_byte_data(address, 0, value)
        return -1

    def readNumber():
        number = bus.read_byte(address)
        # number = bus.read_byte_data(address, 1)
        return number

    while True:
        var = input("")
        if not var:
            continue
        writeNumber(var)
        number = readNumber()

My Arduino code:

    #include <Wire.h>

    #define SLAVE_ADDRESS 0x04
    #define RELAY1 9

    int number = 0;
    int state = 0;

    void setup() {
        pinMode(RELAY1, OUTPUT);
        Serial.begin(9600); // start serial for output
        // initialize i2c as slave
        Wire.begin(SLAVE_ADDRESS);
        // define callbacks for i2c communication
        Wire.onReceive(receiveData);
        Wire.onRequest(sendData);
        Serial.println("Ready!");
    }

    void loop() {
        delay(100);
    }

    // callback for received data
    void receiveData(int byteCount){
        while(Wire.available()) {
           number = Wire.read();
           Serial.print("data received: ");
           Serial.println(number);
            if (number == 1) {
                if (state == 0){
                    digitalWrite(RELAY1, HIGH); // set the LED on
                    state = 1;
                } else {
                    digitalWrite(RELAY1, LOW); // set the LED off
                    state = 0;
                }
            }
        }
    }

    // callback for sending data
    void sendData(){
        Wire.write(number);
    }

Now if I type 1, and due to some loose connection relay 1 doesn't go high, I want the Arduino to take data from the relay board and send it to the Raspberry Pi every time.

It will be great if someone can explain also that how it works.

Hope I was able to explain the problem. I have done lots of research but was not able to find some answer.

I am a beginner in Python so please help me.

Thanks in advance.

  [1]: http://blog.oscarliang.net/raspberry-pi-arduino-connected-i2c/

body:
You might want to graduate to the pigpio library for the Pi side of this.

[Here is where you can find examples of how it works.][1]

here is a fun one that is like Wireshark - will show you the I2C traffic:

https://github.com/joan2937/pigpio/tree/master/EXAMPLES/C/I2C_SNIFFER

Here is the [FAQ about I2C][2]

  [1]: http://abyz.co.uk/rpi/pigpio/examples.html
  [2]: http://abyz.co.uk/rpi/pigpio/faq.html#What_is_I2C


body: *Character '1' is not number 1. Try "number == '1'. – Mikael Patel Mar 9 '16 at 11:34*


message:
How to use a common anode 7-segment, 4-digit display?

Please take this question as an example to (my own) answer below.

I've got an 7 segment, 4 digit LED display, but I don't have any idea on how to wire it.

I don't understand the difference between common anode/cathode, and I don't have 2 pins per LED, which is strange.
Quite recently, a question on a "7 segment 4 digit common anode" got deleted.
At that very moment I was typing an answer.

Though, I still want to share my answer with you, or the person who asked it.
Please verify/update my answer with more information.
Specifically, could someone add working code, I can't at the moment.

body:
I'll try and take you through the complete basics of LED's etc.
As 4-digit 7-segment displays are a combination of multiple "LED techniques".

**Wiring LED's**

LED's, or Light Emitting Diodes, are one of the fun things of Arduino.

Essentially, they're easy to use, power them up and they'll light up.

They can be annoying, because they have some kind of polarity, meaning that they will only work when you wire them right. If you reverse positive and negative voltage, they won't light up at all.

Annoying as it is, it's also quite usefull.

**Cathode vs Anode**

On a traditional LED, the long lead is the (+), Anode.
The other lead being the (-) Cathode.

"Or, if someone’s trimmed the legs, try finding the flat edge on the LED’s outer casing. The pin nearest the flat edge will be the negative, cathode pin." - Sparkfun

Source: https://learn.sparkfun.com/tutorials/polarity/diode-and-led-polarity

[![Sparkfun][1]][1]

**Basic wiring**

I'm not sure if this is correct, since I ripped the image from the internet.

[![Basic LED wiring][2]][2]

Wiring an LED is quite easy, the Anode (+) connects to positive voltage, preferably through a current limiting resistor.
The Cathode (-) connects to ground (with a current limiting resistor, if you didn't have one on the positive side).

The current limiting resistor will avoid the LED from shorting out, damaging the LED or Microcontroller/Arduino.

**Multiple LEDs, matrices, RGB leds**

With multiple LED's you often have them with the positive side connected (+), "common Anode" or all connected to the (-) "common Cathode".

Basically it'll come down to this.

[![RGB common cathode/anode][3]][3]

For a common cathode, you supply current to the pins that you want to have on.

For a common anode, you sink the current through the LED.

**Multiplexing (multiple digit, 7-segments)**

You should check out the tutorial of parallax: http://learn.parallax.com/4-digit-7-segment-led-display-arduino-demo

[![Parallax 4digit7seg][4]][4]

When you've got a lot of LED's, it's often smart to "multiplex" them. Usually you go through "groups" of LED's rapidly, so that it looks like they're all on at the same time.

Usually you sink current from a column of LED's and supply current to individual LED's of a row.

Or, you supply current to a column of LED's and sink current from individual LED's of a row.

So that you can choose which column to activate, and which LED's of that column to light up. Changing these columns/rows rapidly will enable you to control multiple LED's with a lot less pins.

There even are display controllers for this, if you don't want to take care of the switching in your software.

**So when you have a 4 digit, multiplexed 7 segment, common anode**

The diagram will be more like this:

[![enter image description here][5]][5]

http://www.mytutorialcafe.com/Microcontroller Application C 7segmen.htm

  [1]: https://i.stack.imgur.com/PLjNd.png
  [2]: https://i.stack.imgur.com/tiPJk.gif
  [3]: https://i.stack.imgur.com/egSqx.png
  [4]: https://i.stack.imgur.com/UH0ut.png
  [5]: https://i.stack.imgur.com/YUpEy.gif


body:
Just as a complement to Paul's answer, I wrote a short program to show
how to drive the 7-segment 4-digit display of his figure:

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

This is actually a common cathode display, so the program assumes that,
as well as the particular wiring of the figure. The interesting part is
the `refresh_display()` function, which should be called periodically.
The algorithm is as follows:

* drive the 7 anodes with the appropriate signals for one of the digits
  we want to show
* set `HIGH` the output that controls that digit's cathode through the
  NPN transistor
* wait for 2.5 ms (for a refresh rate of 100 Hz)
* set `LOW` the cathode-controlling output
* move to the next digit.

It should be noted that the waiting is done without blocking the CPU, by
using the technique described in the [Blink Without
Delay](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay) Arduino
tutorial. Here is the program:

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

    const int NB_DIGITS     = 4;  // 4-digit display
    const int FIRST_ANODE   = 2;  // anodes a..g on pins 2..8
    const int FIRST_CATHODE = 9;  // cathodes, right to left, on pins 9..12

    // Digits to display, from right to left.
    uint8_t digits[NB_DIGITS];

    // Set all the used pins as outputs.
    void init_display()
    {
        for (int i = 0; i < 7; i++)
            pinMode(FIRST_ANODE + i, OUTPUT);
        for (int i = 0; i < NB_DIGITS; i++)
            pinMode(FIRST_CATHODE + i, OUTPUT);
    }

    // This should be called periodically.
    void refresh_display()
    {
        // Our 7-segment "font".
        static const uint8_t font[10] = {
            //abcdefg
            0b1111110, // 0
            0b0110000, // 1
            0b1101101, // 2
            0b1111001, // 3
            0b0110011, // 4
            0b1011011, // 5
            0b1011111, // 6
            0b1110000, // 7
            0b1111111, // 8
            0b1111011  // 9
        };

        // Wait for 2.5 ms before switching digits.
        static uint32_t last_switch;
        uint32_t now = micros();
        if (now - last_switch < 2500) return;
        last_switch = now;

        // Switch off the current digit.
        static uint8_t pos;
        digitalWrite(FIRST_CATHODE + pos, LOW);

        // Set the anodes for the next digit.
        pos = (pos + 1) % NB_DIGITS;
        uint8_t glyph = font[digits[pos]];
        for (int i = 0; i < 7; i++)
            digitalWrite(FIRST_ANODE + i, glyph & 1 << (6-i));

        // Switch digit on.
        digitalWrite(FIRST_CATHODE + pos, HIGH);
    }

    /***********************************************************************
     * Example usage.
     */

    void setup()
    {
        init_display();
    }

    void loop()
    {
        uint32_t now = millis();

        // Change the number displayed every second.
        static uint32_t last_change;
        if (now - last_change >= 1000) {
            digits[3] = digits[2];
            digits[2] = digits[1];
            digits[1] = digits[0];
            digits[0] = (digits[0] + 1) % 10;
            last_change = now;
        }

        refresh_display();
    }

Paul provided a link to a [tutorial on
Parallax](http://learn.parallax.com/4-digit-7-segment-led-display-arduino-demo)
that suggests using the
[Multiplex7Seg](https://github.com/jhartshorn/Arduino/tree/master/libraries/Multiplex7Seg)
Arduino library. That library is more general than the example code
above, as it does not make assumptions about the pins used. But the big
difference between the library and this code is in the way the timings
are managed:

* The library is driven by the Timer 2 overflow interrupt. This should
  provide a very steady timing, at the cost of having one timer
  dedicated to this job.
* The code above relies on the user calling `refresh_display()` often
  enough. It doesn't require dedicated hardware resources, but it
  doesn't play well with programs that take too long to `loop()`: it
  won't like you calling `delay()`.


message:
RF24 + High speed pwd

I'm using the arduino to generate a 100kHz pwd using timer 1

    void setup() {
      // put your setup code here, to run once:

       // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
       // And 7.32 bits 0-159 PWM on OC1B at 100kHz
       // Output on OC1B
       // Set at TOP, Clear at OCR1B
       // WGM =15 0b1111

       DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

       TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
       TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
       OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                              // or 16000000/(PreScaler *Ftimer)
       OCR1B  = 10;           // 10/160 duty cycle
       TCNT1 = 0 ;
    }

    void loop() {
      // put your main code here, to run repeatedly:
      OCR1B = 160/4 -1 ; // 25% duty cycle.
    }

I used this to test the modules:

    Receiver
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    int msg[1];
    RF24 radio(9,10);
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    int LED1 = 3;

    void setup(void){
     Serial.begin(9600);
     radio.begin();
     radio.openReadingPipe(1,pipe);
     radio.startListening();
     pinMode(LED1, OUTPUT);}

    void loop(void){
     if (radio.available()){
       bool done = false;
       while (!done){
         done = radio.read(msg, 1);
         Serial.println(msg[0]);
         if (msg[0] == 111){delay(10);digitalWrite(LED1, HIGH);}
         else {digitalWrite(LED1, LOW);}
         delay(100);}}
     else{Serial.println("No radio available");}}

Transmitter

    #include  <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    int msg[1];
    RF24 radio(9,10);
    const uint64_t pipe = 0xE8E8F0F0E1LL;
    int SW1 = 7;

    void setup(void){
     Serial.begin(9600);
     radio.begin();
     radio.openWritingPipe(pipe);}

    void loop(void){
     if (digitalRead(SW1) == HIGH){
     msg[0] = 111;
     radio.write(msg, 1);}}

I'm using this library
https://github.com/TMRh20/RF24

And it works ok, now first issue is that both, RF24 and the pwm
are using the pin 10 but the library allows you  to change it, so now I'm using pin 7 instead. I tested it again and still works fine.

But when I add the lines at the setup to use the pwd  the communication doesn't work

       DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A

       TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
       TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
       OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                              // or 16000000/(PreScaler *Ftimer)
       OCR1B  = 10;           // 10/160 duty cycle
       TCNT1 = 0 ;

I try line by line and the issue is here:

   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler

When setting the prescaler at 1.

Which is the dependency of the RF24 on this timer? and which options to I have to make it work

EDIT.

Now I'm using pins 6 and 7 for CE and CS
Also removed  "| bit(COM1A0) " form the register  setting

Still doesn't work

I've this

    void setup(void)
    {

      /// RF settings

      Serial.begin(9600);
     radio.begin();
     //radio.openReadingPipe(1,pipe);
     //radio.startListening();
     pinMode(LED1, OUTPUT);

     /// end RF settings

      //// pwd settings
     DDRB |= bit(DDB1) | bit(DDB2);
       OCR1A  = max_count;       // 16000000/(PreScaler *Ftimer)
       OCR1B  = 10;
       TCCR1A =  bit(WGM11) | bit(WGM10) |  bit(COM1B1); // bit(COM1A0) | Toggle OC1A, Clear on OC1B
       TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
       TCNT1 = 0 ;

      ////
     }

If I put the settings for the PWM before the settings for the RF24 then the PWM doesn't work, the RF settings at first the the communications doesn't work.

 radio.begin() must be overwriting the registers but I haven't found how.

body:
Maybe doing 100kHz PWM with timer2 instead of timer1 would be good.  The registers look similar to timer1, but they are only 8 bit, so you can't go bigger than 255 in the compare and count registers. The prescaler would be the same, and the timer controlled pins would be D11 and D3:

      //// pwm settings for 100kHz on Timer 2
      //// Toggle OC2A/D11/PB3 at 50kHz, PWM OC2B/D3/PD3 at 100kHz:
       DDRB |= bit(DDB3); //Enable output
       DDRD |= bit(DDD3); //Enable output
       // WGM2x=0b111 for fast PWM with TOP=OCR2A
       // COM2Ax=0b01 for toggle OC2A at OCR2A
       // COM2Bx=0b10 for set@bottom-clear@match_OCR2B PWM
       TCCR2A =   bit(WGM21)  | bit(WGM20)
                | bit(COM2B1)  // PWM on OC2B
                | bit(COM2A0); // Toggle OC2A
       TCCR2B =   bit(WGM22) | bit(CS20);  // Set /1 prescaler
       OCR2A  = 159;       // 16000000/(PreScaler *Ftimer)-1
       OCR2B  = 10;        // 6.25% PWM
       TCNT2 = 0 ;

I haven't tested this on an Uno/Atmega328P, but it looks reasonable per the [datasheet (p153-157)] [1].

If you don't want both the 50kHz toggle and 100kHz PWM outputs, (as in your posted code,) you could disable one or the other and adjust the frequency as needed.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


message:
How to write modular code for arduino?

I would like to create a program with separated modules, is this this possible using Arduino IDE?

body:
Arduino sketches can include Libraries (see https://www.arduino.cc/en/Guide/Libraries).

In order to work with the Arduino IDE, such a library is required to adhere to a certain folder structure and naming convention (as described in the above guide).

Other than that, it's similar to modularized code in any other language. The canonical language in Arduino libraries is C++.

Since a regular Arduino IDE installation already comes preinstalled with a multitude of libraries, you can take a look and go from there.

I recommend that you look through the example sketches (from the "Examples" menu option). Whenever you see an #include statement at the top of the sketch, you have a hint where to look next in order to gain a better understanding about the inner works.


body:
While you can create your own libraries for the Arduino, a simple way to make reusable code is to create a header (.h) file that contains the code you would like to make reusable.

Specifically, in the Arduino IDE [create a new tab](https://www.arduino.cc/en/Guide/Environment#toc8) with some name `foo.h`, and in your main tab, add `#include "foo.h"` at the top of your code. What this does is essentially copy paste the code from `foo.h` into your code during the [build process](https://www.arduino.cc/en/Hacking/BuildProcess). While simple in execution, it really helps organize more complex code, and in your case, helps with reusing code.

You can alternativly use "Normal Arduino code files (no visible extension), C files (.c extension), C++ files (.cpp), or header files (.h)."

And one extra note to help you - the header files do not have access to some of the typical Arduino commands and functionality, such as `delay()` or `Serial` unless you add `#include "Arduino.h"`. However, for IDE versions less than 1.0, use `#include "WProgram.h"`. This will give you access to those functions.


body:
The sketch code can be easily split into several files by creating a **new tab** (file) **without file name extension or .ino** ([source][1]). No need for `#include`s as the Arduino IDE combines these files for the build process.

For proper modularisation make a Library or see the link above for further information on using .h/.c/.cpp as modules.

  [1]: http://forum.arduino.cc/index.php?topic=41039.msg299095#msg299095


body:
> I would like to create a program with separated modules, is this this possible using Arduino IDE?

the answer depends on your code.

writing modular code is mostly a thought process:

1) you have to design your code to a logic model: rather than setting an led on pin 2, you design your code to set a pin, use that code to set a pin specified as LED_PIN, and then define LED_PIN to be pin 2. With this approach, you can simply redefine LED_PIN in your new project to use the same code.

2) you have to design your code top-down: rather than start writing your code right away, break it down to logic blocks, design the input and output of each block so that they work together cohesively. this is the toughest part of writing modular code.

after that, breaking the code down to .c/.h files is a piece of cake.


body:
Well.... The answers are interessting but depend on what JuanV is thinking about when he say "separated modules"...
For me, as an "old timer software dev", "separated modules" mean I build a central bloc of code (a nutshell) and the user download module which are automaticly "plugged" to the nutshell, expanding the feature.
A bit like a printer driver you add to your system, and which add feature for all software.
When I look at my past dev using this, I must admit I've some problems thinking of that on Arduino.
If you are looking for that you must think about various problems:

1) how to update? Maybe with an Android App getting the code from the Web and sending these data to the Arduino via Bluetooth. You can also think of adding a Wifi interface on the Arduino

2) where to store the new piece of code... It's seem you can write on flash "on the fly" but seems to be complicated

Due to this second point, maybe the easiest way would be to create a nutshell which will "interpret" data (so which read a kind of small script) and then you'll have just to send the data.
I suggest to have a look at the CNC made with Arduino. In most cases they use a  GCode interpreter. GCode is a descriptif langage for CNC machine. So the interpreter read the code and according to the code, send "orders" to the machine.
Maybe such a thing would be a good starting point.

On the other way, if what you call "modular approach" is just the way of building lib and re-use them, Lord Gonk answer is the way :)


message:
Arduino minimal power usage

I know there is a lot on this subject on the net but i cant seem to be able to join the dots together.
I am trying to make sensor system than can run for as long as possible if not indefinitely using an Arduino, and also to do so very cheaply. I have a £1 Arduino Nano clone that is running with sensor and alarm fine, but currently its runs off USB power from PC.

I have followed this guide to minimize power usage code side: https://www.openhomeautomation.net/arduino-battery/

And I have read that the Vin pin needs at least 7 volts to work properly, so 2 volts would be wasted in heat making a 5V level.

I have a 3.7V lithium cell 4300mAh so I thought I would need a step up boost module.

But it looks like the Nano can run using 3V. But the 3.3V rail is apparently made for external sensors, assuming I want a mixture of cheap/simple and high efficiency. Can i just hook a 3.7 lipo into the 5V rail of the Nano and a 5V solar panel (with diode) up to same point? Will this kill my Nano?
If not, is it worth stepping the 3.7V down to the minimum the Nano can run with?

Underclocking is not an issue, it essentially wakes up every hour reads 5 sensors and if all is well (99% of the time) goes back to sleep for an hour.
Linear voltage regulators seem to burn the excess voltage as heat. And then what will happen when the battery dies off and is no longer 3.7 volts? And if my solar panel is around 5V in good light, if its partly shaded and only has 3.5 volts for example it would not charge my lipo to 100% capacity. Should I step up DC/DC boost the panel voltage to charge my cell.

Guidance please.

body:
Arduinos are for rapidly getting something going without having to know much about the underlying electronics and microcontroller.  As a result, some design tradeoffs were made for you, generally optimized for development simplicity.

You now have a different primary concern, which is low power consumption.  If that is truly important, then you have to design the system with that goal up front.  This means starting with the bare microcontroller, designing the electronics around it carefully to minimize power, and designing the firmware architecture to minimize high-power cycles and maximize sleep time.

You are asking where to strap the big engine on a Honda Civic to make a high performance racing car.  You can make a Civic higher performance, but to get really high performance you have to start with that goal from the beginning.


body:
I have a [project along those lines](http://www.gammon.com.au/forum/?id=12106). I am reading temperature, humidity, and light level and logging it, with a timestamp, to an SD card.

Schematic (click for larger image):

[![Temperature sensor][1]][1]

Photo:

[![Temperature sensor photo][2]][2]

It was designed with low power in mind. It runs from 3 x AA batteries which I think I have only changed once since I made it (in August 2013).

Also see my [page about power saving](http://www.gammon.com.au/power).

I don't see any problem with running it directly from 3.7V - you would need to slow the processor down to 8 MHz (which I did anyway in that project).

The code (available [here](http://gammon.com.au/Arduino/Temperature_Monitor.ino)) compiles under the Arduino IDE.

  [1]: https://i.stack.imgur.com/krOrb.png
  [2]: https://i.stack.imgur.com/ZrGW4.png


body:
I have to agree with @Olin Lathrop about the fact that Arduinos are not really tuned for your goals.

I am doing microcontroller projects for like 20 years, and I found the nanowatt PIC microcontrollers offering the best price/performance/tricks ratio if you need to have something running on batteries for a seriously long time (and has not too much to calculate). There we're talking about nanoamperes in sleep, and there are a lot more tricks you can consider.

You have chosen Arduino for a valid set of good reasons. But which Arduino please? They come with different CPUs and hardware!

If you go with Uno:

* power your board directly by batteries, e.g. 3xAA batteries at the 5V pin to bypass power loss on the 5 V regulator (you can also give a try to feed power via the USB socket if you feel that more convenient)
* remove the 3.3 V regulator (assume you don't need 3.3 V)
* sleep a lot and sleep well, listen to @Nick Gammon and check his page about power saving

Then comes the minor tricks:

* do not let any pin float. Before going to sleep, put all inputs to output. I.e. if you have a button input, change port direction to output and set to 0. (assuming that you don't need the button in sleep)
* turn off not only all internal peripherals, but also external ones. For example, things like I2C temperature sensors may have remarkable 0.5 mA sleep current. The easiest thing is to power those from a port pin, and set the port to 0 before going to sleep.
* turn off all pullups (and all inputs to outputs), don't forget the I2C as well. Although the bus will be idle, there is a serious leakage current (serious means microamperes, and you wanna go to the nanoampere range, right?)

Then if you want to go really to the hard parts:

* throw away all hardware you don't need. The power checking comparators (I am referring to this schematics http://brittonkerin.com/annotateduino/arduino_uno_rev3_schematic.png), the USB interface chip altogether
* throw away u1 (the 5 V regulator) - also has some leakage current

And the final steps:

* I would check the electrolytic capacitors on the power rails, e.g. C2. These also have a leakage.
* Although Arduino does not have suppressor diodes to protect anything from any voltage spikes, I have to emphasize that single high capacity unipolar and bipolar suppressor diodes may have a leakage current of 1 uA.

Note about underclocking: this is not necessarily a wise thing to do. It is true that on slower speed the CPU consumes less. However at slower speed the CPU has to stay awake much longer to perform the same tasks.

 * I found that if you need to perform some complex calculations (not just reading some sensors) it may make sense to switch to a higher CPU speed, and do the calculation in less time and go back to sleep more efficient.
 * On the other hand, if your CPU is awake just to wait for some sensor readings and just burning cycles while waiting, a slower CPU speed is more beneficial.


message:
Detect when RFID card is absent

I am trying to build a mobile device that turns itself on when removed from its usual location. I am attempting to do this with an Adafruit PN532 RFID reader and a MiFare card. Using the sample code I can detect when the card is present

    success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
    Serial.println("Scanning");
    if (success){
      Serial.println("FOUND");
    }

 However, when I try to detect the absence of the card using the following code it will tell me "Present" over and over (since its in the Loop) while the RFID card is present but when it is removed it stops printing "Present" but never prints "Card Gone"

    success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
        Serial.println("Present");
        if (!success){
          Serial.println("Card Gone");
        }

Is this a function of how Im using ! or is there something else at play here? I have found very few suggestions regarding detecting the absence of an RFID card and none of them seem to provide any useful answer. Most suggest some other hardware methodology as the solution. That is not the type of answer Im interested in for the moment. I would simply like to figure out why my code is incorrect.

body:
First, your code isn't structured properly. It should be:

    success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

    if (success)
      Serial.println("Present");
    else
      Serial.println("Card Gone");

From what I could find in the library, the reason you aren't getting either the 'Card Gone' or 'Present' message when there is no card is because `nfc.readPassiveTargetID()` is a blocking function. It will wait forever until a tag is detected, at which point it returns to the caller. When you bring a card within the reader's range, the function returns quickly and `loop()` runs smoothly, giving you the 'Present' message over and over again. When you remove the card however, on the next call of `nfc.readPassiveTargetID()`, the function tries to locate a card but finds none and then it keeps trying and does not return. So `loop()` never gets past that point, until you bring a card within range again.

To detect the presence or absence of something, an observer must observe for some *pre-determined period of time* before making a decision. So, I suggest you get the [latest version][1] of this library which gives you the option of adding a milliseconds `timeout` argument to `nfc.readPassiveTargetID()`. That way, you can specify how long you want the function to try detecting a card before concluding there is no card and returning.

Alternatively, you could use your existing function as is but in `setup()` you need to set the maximum number of re-tries before the `nfc.readPassiveTargetID()` returns. This is done with `setPassiveActivationRetries()`. Any argument from 0x00 to 0xFE indicates a finite number of tries, while 0xFF is to wait forever:

    nfc.setPassiveActivationRetries(0x9A); // for example
    nfc.SAMConfig();  // this comes next

Good luck.

  [1]: https://github.com/adafruit/Adafruit_NFCShield_I2C


body: You can edit the .cpp file and add a timeout. I did this to remove the blocking scan. Search for TIMEOUT in the Adafruit_PN532 source code.


message:
Simple Arduino Serial Arithmetic

I'm developing a program to calculate static margin of an aircraft through the calculations of mass,moment and arm. Essentially dealing with large numbers.

I'm having difficulty in setting up my code in the way so that the arithmetic is applied correctly to larger numbers. What I have so far works but only when the input is 0-9. The arithmetic fails to calculate digits beyond.

I understand that I'm breaking the digits into separate variables as to convert them from ASCII format to their intended value. The problem is in putting those digits back together.

I know this is probably very simple but I'm picking up arduino again after a long break and I'm very rusty.

Here's my code thus far:

    long batterymoment,num1,num2,answer;
    int batterymass = 720;
    int batteryposition;
    boolean mySwitch = false;

    void setup() {
      Serial.begin(9600);
      num1=0;
      num2=0;
      Serial.println("Enter battery position");
    }

    void loop() {
      while (Serial.available()){
       batteryposition = Serial.read();

       if(batteryposition>47 && batteryposition<58){
         if(!mySwitch){
           num1=(num1*10)+(batteryposition-48);
         }else{
           num2=(num2*10)+(batteryposition-48);
         }
       }

       answer=num1+num2;
       batterymoment=answer*batterymass;
       Serial.print("Battery moment is: ");
       Serial.println(batterymoment);
       num1=0;
       num1=0;
       mySwitch=false;
      }
    }

Thanks.

body:
Do you mean to repeat num1=0; in loop()?

It is only reading one character per loop() because loop() happens much faster than Serial.available() and Serial.read().

Do the reporting and clearing when you receive some sort of separator/non-digit character.


message:
How do I upload the sensor data from arduino into a database?

I have just connected a Libelium shield to connect many sensors to Arduino UNO, that measure water ph level, temperature,...etc. I really couldn't figure out how do I upload the sensor data into a database(MySQL). I have the code for database connectivity, but still couldn't figure out how(Querying) to upload the sensor data into the database.

The main problem here is how do I make the arduino recognize the sensor data to upload it into database or send to to another Arduino or Raspberry pi through XBee.

Code for database connectivity:

    void sendData(){

              Serial.println("Connecting...");
              if (my_conn.mysql_connect(server_addr, 3306, user, password)){
                delay(500);
                Serial.println("Starting SQL!");
                Serial.println(INSERT_SQL);
                my_conn.cmd_query(INSERT_SQL);
                Serial.println("Query Success!");
                my_conn.disconnect();
                Serial.println("\n");
              }
              else {
                Serial.println("Connection failed!");
              }
    }

body:
First you have to create the table in your MySQL database, like:

    CREATE TABLE IF NOT EXISTS `table_log` (
      `log_id` int(11) NOT NULL AUTO_INCREMENT,
      `log_date` date NOT NULL,
      `log_time` time NOT NULL,
      `log_t1` float NOT NULL,
      `log_t2` float NOT NULL,
      `log_t3` float NOT NULL,
      `log_t4` float NOT NULL,
      `log_vbatt` float NOT NULL,
      PRIMARY KEY (`log_id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1;

You can execute it in your phpmyadmin page (or create the table manually there). Above we have columns for auto-increment id ('log_id' - necessary), date & time, 4 temperature values and voltage value (modify these according your requirements).

Than the query to create a new record would be like this:

    INSERT INTO `table_log` (`log_id`, `log_date`, `log_time`, `log_t1`, `log_t2`, `log_t3`, `log_t4`, `log_vbatt`) VALUES
        (0, '2016-03-04', '01:53:30', 1.0, 2.0, 3.0, 4.0, 3.0);

You need to create this string dynamically (with real values) and use instead of INSERT_SQL.


message:
nrf24l01+ with antenna problem

I just got 4 nrf24l01+ modules with the external antennas, but I'm not able to make them work.

I'm using arduino nanos and MySensors to create a gateway and a sensor.

The funny thing is that when I put a antenna nrf as the gateway and a pcb nrf as sensor, they work just fine, but the other way doesn't.

I also tried two nrfs as gateway and sensor, but the behavior does not look good.

What could it be? Wifi router interference? Channel? Baud rate? Data rate?

body:
It's likely an issue related to the modules'  electric supply. The effects can be packet loss (even down to zero bps) or loss of communication with the module.

Two things have to be covered with the nRF modules for them to work:

 - current draw (i.e. power),
 - decoupling/filtering (i.e. bypass capacitors).

Since you don't mention specific devices, I'm assuming you refer to an 'antenna' module with SMA (or RP-SMA) connector.

The Nordic Semiconductor nRF24l01+ that is typically used in these modules has a maximum power consumption well below 100mW.

A module with power amplifier (PA) draws significantly more power than the nRF chip alone, the total power consumption will be larger than 100mW.

An Arduino can only supply power according to it's onboard regulator capabilities.
The Minis (and Micros) feature a smaller regulator that cannot drive both the Atmel AVR microcontroller and the PA.

Solution:

 - provide a separate 3.3V regulator for the nRF module(s),
 - place a capacitor directly at the modules' connector's supply pins.

Link:

 - https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo#PP


message:
Why can't most servos rotate more than around 180°

I was looking how a servomotor works. I realized that a standard servo can only turn up to 180°, but I didn't understand why. Is it because of the potentiometer?

body:
Fundamentally, because the systems they were designed for convert rotary motion to linear, typically with a range substantially less than 180 degrees (probably more like 120 degrees).

Next, because the control scheme of PWM *position* pulses is not able to convey requests over an arbitrary range - the mapping of pulse width to position must be limited, and it is sensibly set up to map to something related to the useful range.

Because these limitations in task, a fairly ordinary rotary potentiometer of less than 360 degree range can be employed for position sensing.

Given that the useful range is limited, and the potentiometer relatively easy to damage by over rotation, the gearbox is typically constructed with a mechanical rotation stop somewhere outside the normal range of self rotation.


message:
Machine installed with arduino suddenly turns on when usb is unplugged

Why is my machine suddenly turns ON when I unplugged the USB on my computer? Does it have connection on the auto reset feature of my arduino board?

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

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

    String input = "";

    void setup(){

      Serial.begin(9600); // Sets up communication with the serial port

      pinMode(6,OUTPUT);
      pinMode(7,OUTPUT);
      pinMode(8,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(10,OUTPUT);
      pinMode(11,OUTPUT); // for start of program operation

      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,HIGH);

      digitalWrite(11,LOW);

    }

    void loop(){

      int recipe;
      //Serial.print("Enter recipe number: ");

      while(Serial.available()==0){    // Waits for data from serial port
      }

      while(Serial.available() > 0){
        int data = Serial.read();
          // convert the incoming byte to a char
          // and add it to the string
        input += (char)data;

        recipe = input.toInt()+'0';    //recipe=0 if not a digit
        if(recipe == '0')
          recipe = data;

        if(data == '\n'){
          //Serial.print("Recipe: ");
          //Serial.println(recipe);
          //Serial.print("String: ");
          //Serial.println(input);
          input = "";
        }
      }

      if(recipe == 's'){
        digitalWrite(11,HIGH);
        delay(1000);
        digitalWrite(11,LOW);

        digitalWrite(6,LOW);
        digitalWrite(7,LOW);
        digitalWrite(8,LOW);
        digitalWrite(9,LOW);
        digitalWrite(10,LOW);
      }

      else if(recipe>'0' && recipe<'32'){

        recipe = recipe-'0';
        char binary[7] = {0}; // This is where the binary representation will be stored
        recipe += 32; // Adding 32 so that there will always be 6 digits in the string
        itoa(recipe,binary,2); // Convert recipe to a string of base 2 and save it in array 'binary'
        char* signals = binary + 1; // Get rid of the most significant digit to get the 5 bits

      //Serial.print(signals); // Print out the signals in binary

        int i;
        for(i=0; i<5; i++){
          if(signals[i] == '0')
            signals[i] = '1';
          else
            signals[i] = '0';
          digitalWrite(i+6, signals[i]-'0'); // write to pin; converts the bit of the string to HIGH or LOW
          //Serial.print(signals[i]);
        }

      }
      else
        loop();

    }

body:
Do not call `loop` from `loop`. You will quickly run out of RAM and the sketch will crash:

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

    void loop(){

      int recipe;
      //Serial.print("Enter recipe number: ");

      while(Serial.available()==0){    // Waits for data from serial port
      }

      while(Serial.available() > 0){
    ...

      }
      else
        loop();

    }

---

For the pins that are supposed to be high, I suggest pull-up resistors:

      pinMode(6,OUTPUT);
      pinMode(7,OUTPUT);
      pinMode(8,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(10,OUTPUT);
      pinMode(11,OUTPUT);   // for start of program operation

      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,HIGH);

When the Arduino powers up it enters the bootloader for a second or so. Those pins won't be set high yet. A pull-up resistor would make sure they are high until such time as you want to drive them low.

---

If you are saying that the machine powers up when you **disconnect** the power to the Arduino, that is still a good reason for using pull-up resistors, to make sure that it does not operated until commanded to do so.

---

> where will i connect the pull up resistors and how?

Typically pull-up resistors will be around 10k, and are connected from the pin to +5V. Of course, if the Arduino is not powered, then you need another source of the +5V.

---

> please to clarify the "do not call from loop to loop"

Remove these two lines:

    else
        loop();

When `loop` exits, is it immediately re-called. You don't need to do it that way, in fact it is a Bad Idea.


body:
It looks like the this line in your setup:

      digitalWrite(11,LOW);

... would trigger contact input 211, and do "Start of Program Operation when D11 switches from off to on" every time the sketch starts.

If the arduino resets, it will pull this line low.  Autoreset would initiate this.

By changing the line to the following, the code will wait until it gets an 's' before pulling the line low.

      digitalWrite(11,HIGH);

I don't have an Arduino, but perhaps http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection may help in managing the Auto-Reset issue.


message:
Opto Isolator question

I'm building a CANBUS network based on an arduino to go into an offroad racing truck. The vehicle has two separate battery systems, and I would like to monitor the voltage while still electrically isolating them from the arduino itself. For the voltage monitoring itself, I assume I can use a simple voltage divider into an Analog pin. To electrically isolate the arduino, would an Opto Isolator work? I found this one: https://www.sparkfun.com/products/9118 But it appears that it's designed for low voltage to control high voltage, as opposed to the other way around.

body:
An optoisolator is good for digital signals, but won't transfer an analog signal accurately.

Instead, you could put ADCs on the different circuits and optoisolate their communication with a master Arduino.


body:
1) using current sensors based on Hall effect: [https://www.sparkfun.com/products/8882][1]. Their sensing circuit/leads and analog parts are electrically isolated.

The drawbacks are: to calculate the voltage, need to wire some load resistor with known value to batteries, but you can switch on the load circuit by relay during measurement; susceptible to magnetic field, some shielding might be needed.

2) to use [isolation amplifiers][2]: please see [http://www.analog.com/en/products/amplifiers/isolation-amplifiers.html][3]

  [1]: https://www.sparkfun.com/products/8882
  [2]: https://electronics.stackexchange.com/questions/51116/measuring-voltage-while-maintaining-isolation
  [3]: http://www.analog.com/en/products/amplifiers/isolation-amplifiers.html


message:
Bluetooth Arduino control (was Speech recognition arduino control)

How to I control arduino with voice. I got an Android app but it works only with Internet connectivity. So I was an Android app with works offline when I connect to my Bluetooth HC-05. Please suggest me some ideas

body:
You might find your answer with someone else who has done the same thing on Instructables:

[Arduino Voice recognition Via Bluetooth HC-05 - http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/][1]

Hope this helps!

  [1]: http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/


message:
Problem running WiFiWebClient example

I'm running the WiFiWebClient example which comes preloaded with Arduino IDE 1.6.7. I'm using Arduino Uno board with WiFi Shield Model R3.

    /*
      Web client

     This sketch connects to a website (http://www.google.com)
     using a WiFi shield.

     This example is written for a network using WPA encryption. For
     WEP or WPA, change the Wifi.begin() call accordingly.

     This example is written for a network using WPA encryption. For
     WEP or WPA, change the Wifi.begin() call accordingly.

     Circuit:
     * WiFi shield attached

     created 13 July 2010
     by dlf (Metodo2 srl)
     modified 31 May 2012
     by Tom Igoe
     */

<!-- language: c -->

    #include <SPI.h>
    #include <WiFi.h>
    #include <WiFiClient.h>

    char ssid[] = "Vanilla Sky"; //  your network SSID (name)
    char pass[] = "mypass";    // your network password (use for WPA, or use as key for WEP)
    int keyIndex = 0;            // your network key Index number (needed only for WEP)

    int status = WL_IDLE_STATUS;
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    //IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
    char server[] = "www.google.com";    // name address for Google (using DNS)

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    WiFiClient client;

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue:
        while (true);
      }

      String fv = WiFi.firmwareVersion();
      if (fv != "1.1.0") {
        Serial.println("Please upgrade the firmware");
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        status = WiFi.begin(ssid, pass);

        // wait 10 seconds for connection:
        delay(10000);
      }
      Serial.println("Connected to wifi");
      printWifiStatus();

      Serial.println("\nStarting connection to server...");
      // if you get a connection, report back via serial:
      if (client.connect(server, 80) == 0) {
        Serial.println("connected to server");
        // Make a HTTP request:
        client.println("GET /search?q=arduino HTTP/1.1");
        client.println("Host: www.google.com");
        client.println("Connection: keep-alive");
        client.println();
      }
    }

    void loop() {
      // if there are incoming bytes available
      // from the server, read them and print them:
      while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting from server.");
        client.stop();

        // do nothing forevermore:
        while (true);
      }
    }

    void printWifiStatus() {
      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your WiFi shield's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      // print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

It gets my WiFi shield connected to `Vanilla Sky` but doesn't fetch the HTTP request (see image below). What is getting wrong here?

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

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

body:
Let's break it down :)

> Please upgrade the firmware

Visit here to upgrade the firmware of your board. Your original post doesn't show the fw version, but could have outdated library references and has been noted many times that outdated fw will not work.

[https://www.arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading][1]

  [1]: https://www.arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading

Also add this to your project to help us determine your firmware:

      Serial.print("Firmware version: ");
      Serial.println(WiFi.firmwareVersion());

My guess is that it is less than 1.1.0. If the Arduino IDE is out of date, and the board is newer,  the NOT EQUAL TO(!=) may suggest that the firmware is newer than the library which could also be an issue.

Just b/c it connects to your router, doesn't mean that it can still communicate correctly.

One last side note, some versions of Arduino IDE have proven to be problematic with uploading a sketch to a wifi shield. A quick search with your Arduino version followed by the Wifi Shield not connecting could point you in the right direction. eg- Arduino x.xx wifi shield not connecting

Hope this helps!


message:
Why does the Arduino UNO have a separate power port if USB also powers it?

Can you power the Arduino off a USB cable alone, without using the regular power connection? If so, what's the point of the additional power connection: to provide extra power?
Also Why not just have two usb ports one for power one for connecting to the computer, or a micro usb.

body:
Arduino, in its very esence, is an embedded system and can be used as a standalone device. The USB port is provided for:

 1. To power up the device.
 2. To **program** it through a computer i.e. dump the sketch on it which one can program in the Arduino IDE.

Once you have dumped the program on it, it will stay on it forever unless you change/erase it and hence you can use the Arduino anywhere without actually bringing a computer (USB port) along.


body:
As Hyperbola pointed out, the USB port function is primarily to allow for programming the board. Now, since the USB port has the power cables too, it is convenient to power the device from the USB port.

The main drawback of USB port powering, however, is that it can supply a limited current: usually the USB2 ports can deliver up to 500mA before shutting down. In order for the arduino board to be compliant with this, consequently, a 500mA fuse was put on the board just after the 5V usb input.

Now, what if your final circuit requires more than 500mA? Will you have to change board? Of course not! you can just use the external power input to power the arduino board and all the other circuitry without worrying about the 500mA limitation. Of course the onboard regulator has limits too, but you have more flexibility.

Moreover portable applications run on batteries. No battery can supply exactly 5V (usually alkaline ones deliver 1.5V per battery, while lithium have usually 3.7V/cell, but this varies over time). Consequently they put an onboard regulator for providing 5V from any 6.5V+ source.

Summarizing: the USB power is convenient, since you will usually power it from the PC when programming. An external connector, however, is very important because it gives you more flexibility when choosing the power supply. You don't have to use both: you can just choose the most suitable for your needs.


body:
> Can you power the Arduino off a USB cable alone, without using the
> regular power connection?

You can use the USB cable alone to power the board.

> If so, what's the point of the additional power connection: to provide
> extra power?

You can use either to power the board. By using just the power plug you can make your Arduino portable by using a [battery box][1] or power it via a [wall plug][2].

> Also Why not just have two usb ports one for power one for connecting
> to the computer, or a micro usb.

Only ONE USB is needed to power and program.

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

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

[![enter image description here][5]][5]

  [1]: http://www.aliexpress.com/item/Battery-Case-with-Clip-for-4pcs-AA-battery-Arduino-Storage-Holder-Box-Case-Lead-FZ0975/32371855864.html?spm=2114.01010208.3.20.FsRn6V&ws_ab_test=searchweb201556_9,searchweb201602_2_505_506_503_504_10032_10020_502_10001_10002_10017_10005_10006_10003_10021_10004_10022_10018_10019,searchweb201603_9&btsid=5dfc0189-3cc3-4582-846c-0eb45294bea7
  [2]: http://www.aliexpress.com/item/9V-1A-AC-DC-Power-Suppy-Adapter-WALL-WART-PLUG-Arduino/32614338731.html?spm=2114.01010208.3.2.LTo710&ws_ab_test=searchweb201556_9,searchweb201602_2_505_506_503_504_10032_10020_502_10001_10002_10017_10005_10006_10003_10021_10004_10022_10018_10019,searchweb201603_9&btsid=2d7049b6-4056-45c3-aeba-8d9667ab7e8a
  [3]: https://i.stack.imgur.com/nQQUn.png
  [4]: https://i.stack.imgur.com/i1TAB.jpg
  [5]: https://i.stack.imgur.com/kc9QH.png


message:
Combining 2 State Machines?

I want to gain from recent advice from this forum by re-doing my project using 'state machine' logic if possible, in an effort to reduce wasted processor time and variables usage.

I'm starting from Nick Gammons '*state machine to process input from the serial port*' example http://www.gammon.com.au/statemachine, which shows all the different possible combinations for all the special control character 'events' against all the possible machine states - essentially a 2-dimensional grid.

I've refined my goal to the processing of serial input in a format of "**command  [parameters]  [options]**", similar to a DOS command-line format, eg:  **DIR  "c:\program files"  /w /s**. This would free me from needing large Buffer[] and Header[] string, and avoides any parsing,

Therefore my event control characters are space, comma, single-quote, double-quote, forward-slash, Carraige Return, and my 'states' are **NULL, COMMAND, PARAMETER, OPTIONS**

The OPTIONS state adds characters to a temporary option[] string until a comma or space delimiter or Carraige Return causes that option to be processed as appropriate, perhaps saving its value to a recognised variable.

The COMMAND and PARAMETER 'states' add characters to their corresponding command[] and parameters[] strings, including the special control characters if they are contained within either single or double quotes (thereby allowing quotes as part of a string if used within a pair of the other type).

So there appears to be a second state machine needed for **NoQuotes, SingleQuotes and DoubleQuotes** to modify the operation of the COMMAND, PARAMETER and OPTIONS states.

This is where I run out of neurons, because all I see is an impossibly complex 2-machine-state 3-dimensional grid with too many possible permutations.

But I suspect there must be a very practical way to implement this, because it lies at the heart of almost all command-line utilities dating back to a time when processor power and memory availability were scarcer than hens teeth, and those old DOS command-line utilities needed to be as mimimal as was possible, including their command-line parsing.

So can anybody suggest a feasible model (machine-state or otherwise) for getting command-line type format from input?

UPDATE

Oh dear... I've just seen another complication I hadn't spotted before, which is that '/' options are not necessarily always at the end, which means that except if the options state changes by carraige-return, options state change by delimiter have to return to the state prior to the options state change (phew, I hope that makes some sense).  Anyway, I think it's back to drawing board because this approach seems likely to be too complicated, as the 2 answers already suggest.

body:
Personally I don't think Nick advised to do command line pattern parsing with a state machine. His example is about changing a state machine based on command line input.
I have written some command line parsers and I never used a state machine to do so. I would not advice to use a state machine to do so.
Simple string parsing is far easier.

**Edit To answer the remark below:**
I would not advice to go byte by byte. I'd advice to go the line by line way.
I have written a library to do read line by line and an article on how that one works. http://blog.baeyens.it/#post16
Here a link to the lib https://github.com/jantje/libraries/tree/master/SerialCommunicator.
Here is a parcing code example. It is not so interesting for you as I have it done in a stage by stage way in a very high level way of coding.
https://github.com/jantje/libraries/blob/master/SerialBridgeCommunicator/SerialBridgeCommunicator.cpp#L21

Basically the algorithm is=
1 Take the first word;
2 identify the word.
3 If the command is complete ->do it
 else Send the rest of the string to a specialized piece of code. (which has the same algorithm)