body:
I have a [software][1] sending bitmap data to an Arduino Pro 5V 16MHz 328P that drives an LED display ([sketch][2]). This works using the USB-Serial adapter for the Arduino Pro with baud rates up to 500000 Baud. Now I wanted to switch to Bluetooth...
I tried connecting a 5V HC-05 module (set to 230400 Baud 8N1) to the hardware RX/TX pins on the Arduino Pro (Pins 0/1) and connect the PC to the Bluetooth serial port wirelessly (e.g. /dev/rfcomm0 on Linux). My problem is that I can receive data on the PC side using a terminal (the 'Ada' string is received), but nothing is displayed on the LED display. I have tried connecting an oscilloscope to the RX/TX pins on the Arduino and Data is arriving from the HC-05 module TX pin to the Arduino RX pin.
When the USB-Serial adapter is connected to the same pins (0/1 instead of the regular pin header) it still works as before, so there should be no connection issues.
What I tried was adding a 5kOhm resistor from the Arduino RX line to ground. (I found this hint somewhere [here][3]), but no dice...
I'm not sure what's wrong, because communication IS working over the USB-Serial adapter. Any ideas on what to try?!

  [1]: https://github.com/HorstBaerbel/NerDisco
  [2]: https://github.com/HorstBaerbel/NerDisco/blob/master/LEDStream_WS2812B/LEDStream_WS2812B.ino
  [3]: https://arduino.stackexchange.com/questions/790/corrupted-output-from-hc-05-bluetooth-module

title: Arduino and HC-05 hardware serial issues

Answers: 4

body:
The HC-05 requires a 5V power supply and 3.3V logic.
Using SoftwareSerial might be easier for you as you can use pins 8 and 9 rather than 0 and 1, because there can be issues with the USB.
Are you transmitting the data you think you are, might Big/Little Endian be an issue?
I can get two HC-05 devices to communicate when they are connected to the PC via serial port adapters.  However when I replace the receiver with a HC-05 connected to an UNO I get intermittent garbage received.  So I suspect there may be some sort of problem with PC->Arduino.

body:
I've run into similar issues with the Arduino and serial communications - it's quite a pain.

There really shouldn't be an issue with your sketch if PC->USB->FTDI->Arduino is working since the same protocols are used (UART is UART, after all).

In regard to the BAUD rate, sure, 230400 should work just fine. For purpose of testing, though, I would slow it down to a measly 9600 or something like that just to rule out any possible issues. (Plus, if I remember right, 9600 or ~11000 is the rate at which it operates when being programmed via AT commands).

Now these are my thoughts on what the problem may be:

You said several times that you have a 5V HC-05 with level shifters. The HC-05 chip itself operates on 3.3V, so typically there is a voltage regulator on the breakout board dropping the voltage down to 3.3V for the Vcc pins and whatever else is pulled high on the chip.

However, I have never seen an HC-05 on Amazon, Sparkfun, or Ebay that actually has a true logic-level shifter on the board itself. Instead (and this is true from my experience with Ebay sellers who claim logic-level shifting built in), there is a voltage divider on the HC-05 RX pin that allows you to send a 5V signal without external resistors. But this isn't bidirectional, so your TX pin still has a logic high level of 3.3V. In short, I think your HC-05 chip really doesn’t have a logic-level shifter.

You may be thinking I’m totally wrong about this, and I very well could be since I don’t have your module in front of me, but just hear me out by reading my reasoning below.

(1) You said you can receive data on your PC. This means the HC-05 is receiving data from a 5V signal and successfully converting it to 3.3V. Great. That works!

(2) You said you were able to get an HC-05 (presumably the same model) to work with an Arduino Due in both directions. The Arduino Due operates on 3.3V, so its logic high threshold is around 2.1v.

(3) On the 5V Arduino Pro, the minimum logic high threshold is (0.6)*Vcc -> 3V. So if the HC-05 is transmitting a signal with a logic high of 3.3V, the Arduino is barely registering it. Factoring in resistance and noise, your signal is probably less than 3.3V. (In fact, my HC-05’s usually push out a signal of ~3V).

Reading that you can see a signal on the HC-05 TX line, but the Arduino is not registering it, I’d bet your signal is below the threshold.

So, I’d fire up your oscilloscope again and check the peak voltage to see what it is.

**Additional (Response to "what can I do?)"**

You have a few options. The best option would be to use a bidirectional 3.3V-5V level shifter, but not many people have those laying around. If you happen to have some common components, you could try building a makeshift level shifter like in the images below:

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

The first "level-shifter" is a a voltage comparator using an opamp. If you go this route, ground V-, tie V+ to 5V, and calculate a voltage divider for around 1.5V. (Note: use the non-inverting setup). A cheap TL272 from Radioshack should work.

The second level shifter uses two NPNs and is self-explanatory.

Note, though, that I haven't tried any of these setups nor know their frequency responses. However, the TL272 should handle signals into the MHzs, and BJTs handle high frequencies rather well. My gut tells me it should work, but just in case, I would use a low BAUD rate.

  [1]: https://i.stack.imgur.com/wDavO.png
  [2]: https://i.stack.imgur.com/MCTp5.png

body:
A simple 10k/20k voltage divider is enough to bring the 5V arduino logic-level voltage down to ~3.3 for the HC-05.  It worked for me anyway.

The default baud rate for HC-05 is 9600 baud.  So unless you've changed this with AT- commands you will run into issues.  Although I read that some boards default to 38400 - best check your documentation.  All the cheap HC-05 boards I've tested default to 9600.

body:
I have used HC-05 modules earlier, with baud rate 9600. But the Chinese modules I recently purchased from eBay appear to be pre-wired for 38400. The module refused to transmit anything, and was receiving garbage on the Rx side. So I changed the line

    softSerial.begin (9800);

to

    softSerial.begin (38400);
This solved my problem.


body:
I have the code below. At the moment there is a proximity sensor that makes a speaker play happy birthday when it is set off. I also have an LCD shield attached and when one of the buttons on LCD screens interface is pressed, the time that it was when the button was pressed prints on the screen. I need to get it so that when the proximity sensor is set off it plays the sound on the speaker and then prints the time which is was set off on the screen.

    /*--------------------------------------------------------------------------------------
     Includes
     --------------------------------------------------------------------------------------*/
    #include <Wire.h>
    #include <LiquidCrystal.h>   // include LCD library

    int timer = 1000;
    int C = 262;
    int D = 294;
    int E = 330;
    int F = 349;
    int G = 392;
    int A = 440;
    int B = 494;
    int Bflat = 466;
    int Chigh = 523;

    const int analogPin = A1;    // pin that the sensor is attached to
    const int threshold = 400;

    /*--------------------------------------------------------------------------------------
     Defines
     --------------------------------------------------------------------------------------*/
    // Pins in use
    #define MILLIS_OVERFLOW 34359738
    #define BUTTON_ADC_PIN           A0  // A0 is the button ADC input
    #define LCD_BACKLIGHT_PIN         3  // D3 controls LCD backlight
    // ADC readings expected for the 5 buttons on the ADC input
    #define RIGHT_10BIT_ADC           0  // right
    #define UP_10BIT_ADC            145  // up
    #define DOWN_10BIT_ADC          329  // down
    #define LEFT_10BIT_ADC          505  // left
    #define SELECT_10BIT_ADC        741  // right
    #define BUTTONHYSTERESIS         10  // hysteresis for valid button sensing     window
    //return values for ReadButtons()
    #define BUTTON_NONE               0  //
    #define BUTTON_RIGHT              1  //
    #define BUTTON_UP                 2  //
    #define BUTTON_DOWN               3  //
    #define BUTTON_LEFT               4  //
    #define BUTTON_SELECT             5  //
    //some example macros with friendly labels for LCD backlight/pin control,     tested and can be swapped into the example code as you like
    #define LCD_BACKLIGHT_OFF()     digitalWrite( LCD_BACKLIGHT_PIN, LOW )
    #define LCD_BACKLIGHT_ON()      digitalWrite( LCD_BACKLIGHT_PIN, HIGH )
    #define LCD_BACKLIGHT(state)    { if( state ){digitalWrite(     LCD_BACKLIGHT_PIN, HIGH );}else{digitalWrite( LCD_BACKLIGHT_PIN, LOW );} }
    /*--------------------------------------------------------------------------------------
     Variables
     --------------------------------------------------------------------------------------*/
    unsigned long currentMillis, previousMillis, elapsedMillis;
    int seconds = 0, minutes = 34, hours = 8;

    byte buttonJustPressed  = false;         //this will be true after a        ReadButtons() call if triggered
    byte buttonJustReleased = false;         //this will be true after a     ReadButtons() call if triggered
    byte buttonWas          = BUTTON_NONE;   //used by ReadButtons() for detection of button events
    /*--------------------------------------------------------------------------------------
     Init the LCD library with the LCD pins to be used
     --------------------------------------------------------------------------------------*/
    LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2     LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
    /*--------------------------------------------------------------------------------------
     setup()
     Called by the Arduino framework once, before the main loop begins
     --------------------------------------------------------------------------------------*/
    void setup()
    {
      //button adc input
      pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
      digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
      //lcd backlight control
      digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is     high (on)
      pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
      //set up the LCD number of columns and rows:
       pinMode(13, OUTPUT);
      lcd.begin( 16, 2 );

      //Print some initial text to the LCD.
      Serial.begin(9600);
      lcd.begin( 16, 2 );

    }
    /*--------------------------------------------------------------------------------------
     loop()
     Arduino main loop
     --------------------------------------------------------------------------------------*/
    void loop()
    {

      setClock();
      byte button;

      button = ReadButtons();

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

      //get the latest button pressed, also the buttonJustPressed,     buttonJustReleased flags

      //blank the demo text line if a new button is pressed or released, ready for a new label to be written

      //show text label for the button pressed
       if(buttonJustPressed || buttonJustReleased)
      switch( button )
      {

      case BUTTON_LEFT:
        {
          lcd.setCursor( 0, 0 );
                   lcd.print(hours);
                   lcd.print(":");
                   lcd.print(minutes);
                   lcd.print(":");
                   lcd.print(seconds);
                   lcd.print(":");
                   lcd.print(elapsedMillis);

          break;

        }
      default:
        {
          break;
        }
      }

      if( buttonJustPressed )
        buttonJustPressed = false;
      if( buttonJustReleased )
        buttonJustReleased = false;
    }
    /*--------------------------------------------------------------------------------------
     ReadButtons()
     Detect the button pressed and return the value
     Uses global values buttonWas, buttonJustPressed, buttonJustReleased.
     --------------------------------------------------------------------------------------*/
    byte ReadButtons()
    {
      unsigned int buttonVoltage;
      byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn

      //read the button ADC pin voltage
      buttonVoltage = analogRead( BUTTON_ADC_PIN );
      //sense if the voltage falls within valid voltage windows
      if( buttonVoltage < ( RIGHT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_RIGHT;
      }
      else if(   buttonVoltage >= ( UP_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( UP_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_UP;
      }
      else if(   buttonVoltage >= ( DOWN_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( DOWN_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_DOWN;
      }
      else if(   buttonVoltage >= ( LEFT_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( LEFT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_LEFT;
      }
      else if(   buttonVoltage >= ( SELECT_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( SELECT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_SELECT;
      }
      //handle button flags for just pressed and just released events
      if( ( buttonWas == BUTTON_NONE ) && ( button != BUTTON_NONE ) )
      {
        //the button was just pressed, set buttonJustPressed, this can optionally be used to trigger a once-off action for a button press event
        //it's the duty of the receiver to clear these flags if it wants to detect a new button change event
        buttonJustPressed  = true;
        buttonJustReleased = false;
      }
      if( ( buttonWas != BUTTON_NONE ) && ( button == BUTTON_NONE ) )
      {
        buttonJustPressed  = false;
        buttonJustReleased = true;
      }

      //save the latest button value, for change event detection next time round
      buttonWas = button;

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

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

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

      previousMillis = currentMillis;

     int analogValue = analogRead(analogPin);
      if (analogValue > threshold) {

    tone(13,C,timer/2);// Happy Bday to You
    delay(200);
    tone(13,C,timer/2);
    delay(200);
    tone(13,D,timer/2);
    delay(400);
    tone(13,C,timer/2);
    delay(400);
    tone(13,F,timer/2);
    delay(400);
    tone(13,E,timer);
    delay(750);
     }
    else {

    }
    }

title: Change code so motion sensor prints time instead of a button

Answers: 1

body:
The code seems a little hotchpotch; is the code for reading the sensor supposed to be within the `setClock()` function? It would be better to put the following within `loop()`:

    if(analogRead(analogPin) > threshold)
    {
        playMelody();
        printTriggerTime();
    }

And create two new functions that handle the playing of 'Happy Birthday' and the printing of the time:

    void playMelody()
    {
        tone(13, C, timer / 2);// Happy Bday to you
        ...
        delay(750);
    }

...which is just a cut-paste of what you've got in the `setClock()` function, and:

    void printTriggerTime()
    {
        lcd.setCursor(0, 0);
        ...
        lcd.print(elapsedMillis);
    }
...which is a copy-paste of the code from within `case BUTTON_LEFT:`.

This will now play 'Happy Birthday' and print the time whenever the proximity sensor is triggered, AND it will print the time when the left-button is pressed (unless you remove that part of the code).

On a separate point, it's bad coding practice to use `#define` for a function, as you have done with `#define LCD_BACKLIGHT(state) { if ( state )...` - it makes it quite difficult to read the code, and can't conceive any reason why this isn't its own function. However, a nice trick in C is the following 'shortcut' statement:

    ( CONDITION ? DO_IF_TRUE : DO_IF_FALSE )

Thus you should change that line to:

    #define LCD_BACKLIGHT(state) ( state ? digitalWrite(LCD_BACKLIGHT_PIN,HIGH) : digitalWrite(LCD_BACKLIGHT_PIN,LOW))

That being said, "LCD_BACKLIGHT(state)" isn't actually used anywhere in the program!


body:
I were examining `shiftOut()` function code in `wiring_shift.c` and I didn't quite understand what is going in digitalWrite function. I see `!!(val & (1 << i))` is taking the bit value from `val` but how exactly it works?

The whole function is below.

    void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
    {
     uint8_t i;

     for (i = 0; i < 8; i++)  {
      if (bitOrder == LSBFIRST)
       digitalWrite(dataPin, !!(val & (1 << i)));
      else
       digitalWrite(dataPin, !!(val & (1 << (7 - i))));

      digitalWrite(clockPin, HIGH);
      digitalWrite(clockPin, LOW);
     }
    }

title: How shiftOut function works internally? (explanation on source code)

Answers: 1

body:
I'll assume `bitOrder == LSBFIRST`.

* `i` is the bit number, i.e. the “index” of the next bit to write
* `1` is `00000001` in binary
* `<<` is the shift left operator. It returns its first argument shifted left by as many positions as indicated by the second argument
* `1<<i` is binary `00000001` shifted left by `i` positions, i.e. something like `0...010...0`, where the single 1 is in the i-th position counting from the right (rightmost being position 0)
* `&` is the “bitwise and operator”, where `any_bit & 0` is zero and `any_bit & 1` is `any_bit`
* `val & (1 << i)` is `0...0(i-th bit of val)0...0` in binary, where the i-th bit of val is in the i-th position of the result
* `!!` is a double negation: it converts zero to zero and any non-zero value to one
* `!!(val & (1 << i))` is either 0 or 1, and is exactly the i-th bit of val


body:
I have a little personal project involving an Arduino Uno and an amp board from [Sure Electronics][1]. The amp has contacts for a mute function that involves shorting the contact to ground. I would like to control this muting with the Arduino which I was planning to do with a relay. However I think I might be complicating things and I thought it might be possible to do it directly with the pins.

Can I use the Arduino to directly short a circuit to ground? Or would I need something more complicated to be safe?

  [1]: http://store.sure-electronics.com/audio/audio-amplifier-board/low-power-100w/aa-ab31521 "Sure Electronics"

title: Can I use an arduino as a ground short?

Answers: 2

body: I can't see how much current the amp board will sink into the Arduino so like FuaZe I would recommend using your Arduino to drive an external component that you know can take the current.  This isn't really complicating the design too much, use an NPN transistor, with the P connected to the Arduino and just write High to the pin when you want to apply the mute.  If you blow the transistor then its going to cost you a few pence for a new one, if you blow your Arduino you are down £20!

body:
Depends on the voltage that is on that mute pin. If it's below 5 volt, you could use the arduino pin. You can measure the voltage using a multimeter.

If it's more than 5v you can use a NPN transistor and resistor combination. ![enter image description here][1]

Current isn't a problem with these kinds of "settings" pins, as there is just a pull-up resistor that by default (unconnected) sets the pin to HIGH. By connecting the pin to ground you set the pin to LOW.

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


body:
I will be using the Arduino platform with other data acquisition hardware for a school electronics project. I have limited knowledge of C++ syntax.

Are there good introductory to intermediate books that can bring a high school student with some programming experience to proficiency on Arduino?

title: Books on Arduino development in C++

Answers: 4

body:
I'd recommend you go to [cplusplus.com][1]. Plenty of tutorial pages and topics to further your knowledge. However, be aware that Arduino uses a variant of **C** designed for microcontrollers (the exact flavour depends on the microcontroller type/family), rather than *C++*, so do be aware that some of the topics are not implementable on an Arduino. That said, I can't think why you'd be using some of the more elaborate C++ exclusive features in a fairly middle-of-road embedded system.

The only thing you need to ignore in C++ is memory allocation specifics - you're limited to the 'original' `malloc()` based functions rather than the all-singing-all-dancing `operator new` from C++. If you are in need of memory allocation functions, malloc is well-documented and a tutorial is only a quick Google away.

Of course I must also point you in the direction of the highly popular [Stack Overflow][2] site, part of this Stack Exchange network. While they don't have tutorials, there are plenty of great answers to common questions.

  [1]: http://www.cplusplus.com/doc/tutorial/
  [2]: http://www.stackoverflow.com

body:
There is a book called "C Programming for Arduino" by Julien Bayle that introduces it pretty well if you are just getting started at it. I think it's from Packt Publishing.

Another I found interesting is called "Practical AVR Microcontrollers" by Alan Trevennor that gives examples of programming using C without having to get an Arduino.

Otherwise, Stack Exchange is always really great to browse.

body:
I found the Arduino examples a good reference for refreshing/learning C++.

Important Arduino C++ classes are:

* String: https://www.arduino.cc/en/Reference/String
* Arduino classes for components: https://www.arduino.cc/en/Reference/Libraries

To learn more about the syntax of the language, the inventor of C++ has also a couple of videos online.

body:
I would start with [a standard C++ introduction book][1] to get an understanding for the language. After that I would read a book on [object-oriented design and implementation][2].

There is a lack of books on how to systematically approach programming small scale embedded systems such as Arduino. Due to the restrictions on resources, both processing and memory, C++ has to be used "carefully". There is a need to understand some of the more difficult concepts such as volatile, virtual, ISR, etc.

Reading others code is also a very good way to learn. I would recommend looking at the source code and example sketches to [Cosa][3]. This is an OOP framework for Arduino/AVR.

Last but not least - learning by doing!

Cheers!

  [1]: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
  [2]: http://www.amazon.com/Best-Sellers-Books-Object-Oriented-Design/zgbs/books/4013
  [3]: https://github.com/mikaelpatel/Cosa


body:
I have this:

    class Person{
    public:
     int age;
    };

    Person p;
    p.age;

    void setup() { ... }

    void loop() { ... }

And I got this error:

    Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
    MyProgram.ino:18:1: error: 'p' does not name a type
    Error compiling

But is I use the Person instance inside setup or loop functions it compiles find.

    void setup() {
     // initialize digital pin 13 as an output.
     Person p;
     p.age;
    }

I got this:

    Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
    Binary sketch size: 4,674 bytes (used 2% of a 253,952 byte maximum) (3.45 secs)
    Minimum Memory Usage: 428 bytes (5% of a 8192 byte maximum)

What is the different? Why the instance only can be used into the blocks?

I also declared a file with a simple class and then create a instance of it class outside the blocks and I got the same error. If I put the instance inside the blocks it works. So, any tips?

title: Arduino raise the error: `does not name a type` when an Object is used outside of the main two blocks setup and loop

Answers: 2

body: All code intended to be executed must be inside a function block in C++.

body:
As you have already noticed, you cannot call methods of a class, nor access its properties, outside a "block" (as you call it).  More specifically, you can only perform "programatical" operations from within a *function*.  Anything outside a function (known as the *global scope*) is purely for declaration and initialization of variables and types, etc.

Any class variables declared in the *global scope* have their *constructor* executed before the rest of the program (even before `setup`) gets run.  However, `setup` is not the first function to be called at startup.

Anything you put into a constructor has to take into account the fact that anything might be happening between the constructor being called and the object instance actually being used.  Things like `pinMode` and `digitalWrite` are unsafe to use in a constructor, since there is a chance they may be negated during the startup.  That is why the majority of Arduino classes have a `.begin()` method which is called from `setup()`.

The proper method for using classes with pin control and similar operations is:

1. The constructor takes the pins to use
2. The constructor saves those pins in variables
3. The begin() method is called in setup()
4. The pins are configured appropriately.

For example:

    class myClass {
        private:
            int _myPin;
        public:
            myClass(int pin) : _myPin(pin) {}

           void begin() {
                pinMode(_myPin, OUTPUT);
                digitalWrite(_myPin, HIGH);
            }
    };

    myClass p(4);

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

    void loop() {
    }

The object instance `p` is in the *global scope* and can be referenced from any function. The pin is configured only when setup() is run.

The startup sequence, more specifically, is typically this:

1. The memory used by global and static variables is "zeroed".
2. Any pre-defined variable values (*BSS*) are copied from flash into RAM.
3. Any object constructors are called.
4. The main() function is called (main startup function).
5. The init() function is called which configures the Arduino platform.
6. The initVariant() function is called which performs any board specific setup routines.
7. USB is configured on the boards that have it
8. Your setup() function is called.
10. Your loop() function is called.
11. The serialEvent() system runs if defined.
12. Go to 10.

As you can see quite a lot happens between the constructor being called and setup() being called, and you cannot reliably predict what that might be.  Some boards may do nothing more than configure interrupts and enable timers (for things like `delay` and `millis`), but other boards may configure IO pins to default settings (especially more complex boards with multiple functions per IO pin), so really the only safe operations you can perform in a constructor are operations which act directly on the internals of the class itself.  Anything outside the scope of the class could be changed before you come to use it.


body: I have a brand new arduino(original), and it is not showing up in Device manager or anywhere else. Even the computer doesn't Prompt anything. I am using Windows 7 32 bit.

title: My arduino won't show up in Device Manager in any way, neither in unknown devices nor in COM port.

Answers: 1

body:
As the OP reported: *It worked with a different cable.*

I converted his comment to an answer so the system would regard this issue as solved. Please accept this answer.

---

Some cheap USB cables only carry power, and not data. I have such a cable that came with a USB desk light. To save money they only run two wires and not four, since the desk light is not a data device.

Be cautious about grabbing any old cable from your desk for testing. Make sure it is designed for data use. If in doubt, try a known good cable.


body:
I'm using the apc220 rf modules. Now I'm having the following problem:

My receiving arduino uno only receives data when the tx pin on the arduino (rx pin on the rf module) is disconnected. As soon as I connect the tx pin my serial monitor receives only the value 0.

Is my rf module broken, or can someone help me with this?

title: Serial communication stops when I connect the tx cable

Answers: 1

body:
To have two serial ports on Arduino board like Uno use `SoftwareSerial.h`.

Example

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2,3); // RX, TX

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);

      Serial.println("Hello!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
    }

    void loop() // run over and over
    {
      if (mySerial.available())
        Serial.write(mySerial.read());
      if (Serial.available())
        mySerial.write(Serial.read());
    }

Now after opening `Serial monitor` you should see Hello! and then you can test `SoftwareSerial`.

**DO NOT FORGET!!!**

When you connect to pins 2,3 or etc, this is **TTL** voltage level. You **can't** connect direct to RS232.


body:
what is the difference between a motor driver(like L293D) and a motor shield?

what are the advantage?disadvantages of both?

And which one do you suggest ?

title: What is the difference between a motor driver and a motor shield?

Answers: 3

body:
A motor driver is a chip that drives motors.  A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.

A shield is convenient since you can just plug it in to your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands.

body: The differrence is usablilty and, in some cases, the protection of your chip; if there is a surge of more than 5V to your driver it will fry, which is why some drivers have onboard voltage regulators and a heatsink for overheating problems. Advantage of motor driver is that you can use it as per your requirements, whereas a shield is fixed and you cannot change any aspects.

body:
*A motor driver is a chip that drives motors. A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.*

**A shield is convenient since you can just plug it into your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands**


body:
I'm trying to communicate with two bluetooth module (RN-42) on the Arduino Mega.

I studied about Serial communication in Arduino, and I used Serial1, Serial2 to get information at the same time from the modules.

At the setup period, baud rate will be set. The command "$$$" makes the bluetooth module go into the configuration mode. Until this, everything works pretty well.

The problem is, it seems nothing works inside the loop(). I think Serial1.print(inByte), Serial2.print(inByte) doesn't work properly. I checked the TX1, TX2 port whether it sends any data or not by using LED, and the LED never blinked.

Here's the code that I used.
<!-- language-all: lang-cpp -->

    void setup() {
      // initialize both serial ports:
      Serial.begin(9600);

      Serial1.begin(115200);
      Serial1.print("$$$");
      delay(100);
      Serial1.println("U,9600,N");
      Serial1.begin(9600);

      delay(100);
      Serial1.print("?");

      Serial2.begin(115200);
      Serial2.print("$$$");
      delay(100);
      Serial2.println("U,9600,N");
      Serial2.begin(9600);

    }

    void loop() {
      // read from port 1, send to port 0:

      while(Serial1.available()>0) {
        char inByte = Serial1.read();
        Serial.print(inByte);
      }

      while(Serial2.available()>0) {
        char inByte = Serial2.read();
        Serial.print(inByte);
      }

      // read from port 0, send to port 1:
      while (Serial.available()>0) {
        char inByte = Serial.read();
        Serial1.print(inByte);

        delay(10);
        Serial2.print(inByte);
      }
    }

Thank you

title: Serial Communication with two bluetooth modules on Arduino Mega

Answers: 0


body:
i tried to connect my arduino uno and ethernet shield with Mysql and everything works fine. Then I tried to connect the RF transmitter and receiver. I use a similar code, but i have problem with connection with database.
For the project i use:2xArduino Uno,Rf transmitter and receiver ,DHT11 and BMP080,and Ethernet shield. This is my Code:

transmitter:

    #include <VirtualWire.h>
      #include "LowPower.h"
      #include "DHT.h"
      #include "Adafruit_BMP085.h"
      #include "Wire.h"

      #define DHTPIN 8     // what pin we're connected to
      #define DHTTYPE DHT11   // DHT 11
      DHT dht(DHTPIN, DHTTYPE);
      Adafruit_BMP085 bmp;
      int ledPin = 13;
      char Msg[30];// The string that we are going to send trought rf transmitter
      void setup()
      {
        Serial.begin(115200);
        dht.begin();  // initialing the DHT sensor
        bmp.begin();
        pinMode(ledPin,OUTPUT);
        // VirtualWire setup
        vw_setup(2000); // Bits per sec
        vw_set_tx_pin(12);// Set the Tx pin. Default is 12
      }
      void loop()
      {
         Serial.print("Pressure = ");
         Serial.println(bmp.readPressure());
         Serial.print("Temperature = ");
         Serial.println(bmp.readTemperature());
         Serial.print("Humidity = ");
         Serial.println(dht.readHumidity());

        // Read and store Sensor Data
        int humidity = dht.readHumidity();
        int temp = bmp.readTemperature();
        unsigned long pressure = bmp.readPressure()/100;
         Serial.print("Pressure = ");
         Serial.println(pressure );

        sprintf(Msg, "%d,%d,%d", humidity,temp ,pressure);
       // Turn on a light to show transmitting
        digitalWrite(ledPin, HIGH);
       //LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
        delay(100);
        vw_send((uint8_t *)Msg, strlen(Msg));
        vw_wait_tx(); // Wait until the whole message is gone
       // Turn off a light after transmission
        digitalWrite(ledPin, LOW);
        // put 5 mins sleep mode
        // As lowpower library support maximam 8s ,we use for loop to take longer (5mins) sleep
        // 5x60=300
        //300/4=75
        for(int i=0;i<75;i++)
        {
        LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF);    // Instead of delay(4000);
       //delay(4000);
        }
      }

reciever:

    #include <SPI.h>
    #include <Ethernet.h>
    #include "Wire.h"
    #include <VirtualWire.h> // use Virtual library for decode signal from Rx module

     EthernetClient client;
      byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
      char server[] = "192.168.0.101";

      int humidity=0;
      int temp=0;
      unsigned long pressure=0;
      char MsgReceived[21];

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

        // VirtualWire
        // Bits per sec
        vw_setup(2000);
        // set pin for connect receiver module
        vw_set_rx_pin(5);
        // Start the receiver PLL running
        vw_rx_start();

      }

      void loop()
      {
        uint8_t buf[VW_MAX_MESSAGE_LEN];
        uint8_t buflen = VW_MAX_MESSAGE_LEN;
        //Taking the data from the control base
        if (vw_get_message(buf, &buflen))
        {

          delay(100);
          int i;
          // Message with a good checksum received, dump it.
          for (i = 0; i < buflen; i++)
          {
            // Fill Msg Char array with corresponding
            // chars from buffer.
            MsgReceived[i] = char(buf[i]);
            Serial.print(MsgReceived[i]);
          }
      connection();

        sscanf(MsgReceived, "%d,%d,%d",&humidity, &temp, &pressure); // Converts a string to an array

        memset( MsgReceived, 0, sizeof(MsgReceived));// This line is for reset the StringReceived

        Serial.print("Temperature = ");
        Serial.print(temp);
        Serial.println(" *C");

        Serial.print("Pressure = ");
        Serial.print(pressure);
        Serial.println(" hPa");

        Serial.print("humidity = ");
        Serial.print(humidity);
        Serial.println(" %");

        delay(10000);
        }
    }

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

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

      }

Output receiver:

    70,23,100-> connection failed
    Temperature = 23 *C
    Pressure = 1001 hPa
    Pahumidity = 70 %

title: Arduino uno RF transmitter and receiver, MYSQL

Answers: 0


body:
I bought the below FTDI programmer for use with my 3v3 arduino pro mini. But even when the switch is set to 3v3 it is powering the board with 5v, (hence the IO voltage is also 5v). Note that when the pro mini is powered by batteries on the RAW input the IO voltage is 3v3 as expected. The problem is that when programming at 5v, any 3v3 peripherals (such as the BMP180) will be surely damaged.

http://www.ebay.co.uk/itm/301597777458?_trksid=p2057872.m2749.l2649&ssPageName=STRK:MEBIDX:IT

Now on the eBay description it says:

> This board ship default to 5V, but you can cut the default trace and add a solder jumper if you need to switch to 3.3V

Which trace needs to be cut, and where does the jumper need to connect to/from?

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

  [1]: https://i.stack.imgur.com/XS2lX.jpg
  [2]: https://i.stack.imgur.com/tbIS0.jpg

title: FTDI Adjustable 3v3/5v only outputs 5v

Answers: 1

body:
The 5V/3.3V switch is fed into the "VCCIO" pin which sets the voltage of communication and nothing else.  The 5V pin of the header is connected straight through to the USB port's 5V pin.

You can either take a separate 3.3V feed from the 3V3OUT pin of the FT232RL (limited to 50mA) which is easiest to take from the 3.3V side of the switch's pins (on the underside, either or both of the two pins with no visible trace connecting to them - the lowest two in your top picture), or you can re-wire the header so it takes its voltage from the output of that switch (the middle two pins).  It looks like it would be a case of cutting the left hand portion of the long fat trace at the top edge of the back (on your top picture) then soldering a wire from the 5V pin on the header to the center pins of the switch.  That should make the output power switchable between 5V and 3.3V.

![enter image description here][1]

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


body:
I would like to create a camera dolly for capturing timelapse movies.

i.e. something like this:
http://youtu.be/Qce1f6SKEMU

Whats a reliable way to detect the end of the track and stop the stepper motor moving the camera? In other words how is it possible to get the current position of the camera and stop the motor before the track ends to prevent crashing into the bumpers?

title: Stop at the end of a track

Answers: 3

body:
The simplest way is to have an opto-interrupter fitted at one end of the track (IR LED and IR Phototransistor), and a small bit of plastic or whatever on the dolly which interrupts the IR beam.

Printers have been doing it that way with their print heads for decades.

http://www.martyncurrey.com/connecting-an-photo-interrupter-to-an-arduino/

body:
I find a mechanical switch the simplest and cheapest. But technically it is the same as an opto switch.  These are often refered to as [limit switches][1].

![enter image description here][2]

You tie the switch to a pin with the normally closed (NC) pin, set it to pinMode(pullup), and check it each each loop. When the read value goes low (0), you stop moving your motor.

  [1]: https://www.google.com/search?q=limit switch&tbm=isch
  [2]: https://i.stack.imgur.com/l7PWO.jpg

body:
Many methods exist:

References to unpowered means the switch does not draw power when not operated. When a motor is activated it will draw power.

 - Mechanical switch- microswitch is the most common (as per Spiked3's suggestion). Contamination and weather may be issues (depending on how waterproof your camera is). No power needed for actual switch.

 - Optical (a la Majenko). Some environmental issues. Effect of ambient light needs to be considered.

 - Capacitive. Can be fully sealed. Need to be powered.

 - Magnetic - Hall (powered) and Reed (unpowered).

Whatever is used, the current and voltage ratings need to be compatible with the load. In many cases the actual switch will need a transistor or relay or similar to provide the power drive to the dolly motor. This is not hard to do but needs to be noted.

___________________________
An end of track signalling method that is relatively unaffected by environmental issues is to use a magnet and magnet detector. The most common detectors are either a "Hall sensor" IC or a reed switch.

Reed switches are mechanical and more fragile than Hall sensors but need no power when unoperated and can be bought in ready made encapsulations that are robust enough to be reliable. Properly implemented a reed switch can be essentially indestructible.

Hall sensors need to be powered but power levels are small compared to eg dolly motor current and low current versions are available.

Both Hall sensors and reed switches have a degree of "hysteresis" - the point in the travel where they operate is past the point where they release again, but this is easily allowed for in practice.

____________________________

[Reed switch demonstration](https://www.youtube.com/watch?v=hnCEQYO-i_E) - 38 seconds video - simple and obvious.

Instructables [DIY powered dolly wity reed swithes](http://www.instructables.com/id/DIY-motorized-moving-timelapse-camera-dolly-with-A/all/)

[Sparkfun magnetic door switch set](https://www.sparkfun.com/products/13247) and encapsulated reed switch and magnet.

[Hall sensor theory of operation](http://www.electronics-tutorials.ws/electromagnetism/hall-effect.html)

[Many ideas here](https://www.google.co.nz/search?q=hall+sensor&biw=1280&bih=789&source=lnms&tbm=isch&sa=X&ei=buRtVYmRFtXh8AWv9YOYAQ&sqi=2&ved=0CAYQ_AUoAQ#tbm=isch&q=hall+effect+sensor++circuit) for using hall sensors.

[Reed switches](https://www.google.co.nz/search?q=hall+sensor&biw=1280&bih=789&source=lnms&tbm=isch&sa=X&ei=buRtVYmRFtXh8AWv9YOYAQ&sqi=2&ved=0CAYQ_AUoAQ#tbm=isch&q=reed+switch+)


body:
I have an Arduino Uno.
I am trying to write a code that reads a command and according to that command it saves angles into an array or writes the angles of the array into a servomotor.
I am facing some problems with my code such as executing the instructions of boucle FOR without ending and other strange things.

    #include <Servo.h>

    Servo s;
    int t[6];
    int n, r = 2, b = 4 ;
    char c;
    String ch = "" ;
    int i = 0;
    int nb, rep = 0;
    int cmd = -1;

    void setup() {
     Serial.begin(9600);
     pinMode(r, OUTPUT);
     pinMode(b, OUTPUT);
     digitalWrite(r, LOW);
     digitalWrite(b, LOW);
     s.attach(9);
     t[0] = 0;
     t[1] = 90;
     t[2] = 180 ;
    }

    void loop() {
     while ((cmd == 0) || (cmd == -1)) {
      cmd = lirecmd();
      delay(20);
     }

     if (cmd == 1) {
      digitalWrite(r, HIGH);
      digitalWrite(b, LOW);

      while (i < 3) {
       while (Serial.available() > 0) {
        c = Serial.read();
        ch.concat(c);
       }

       if (ch != "") {
        nb = ch.toInt();
        t[i] = nb;
        i = i + 1;
        ch = "";
       }
      }
     } else if (cmd == 2) {
      int x;
      cmd = -1;
      digitalWrite(b, HIGH);
      digitalWrite(r, LOW);

      for (i = 0; i < 3; i = i + 1) {
       Serial.print(i);
       x = t[i];
       delay(1000);
       s.write(x);
       delay(1000);
       break;
      }
     } else {
      digitalWrite(r, HIGH);
      digitalWrite(b, HIGH);
     }

     i = 0 ;
     cmd = -1;
     rep = 0;
     digitalWrite(r, LOW);
     digitalWrite(b, LOW);
     delay(50);
    }

    int lirecmd() {
     if (Serial.available() > 0) {
      n = Serial.read() ;
      n = n - 48 ;
     }

     return n ;
    }

title: reading from an array and writing into a servomotor

Answers: 0


body:
Can I use the arduino for an application with a frequency of 4 MHz?

I need to create a clk with this frequency and send and receive data on the rising and falling edges. and it is not a normal SPI interface I have my own conditions so I need to do it manually.

If it is not suitable, is it technically possible?

title: Is arduino suitable for high frequency application?

Answers: 2

body:
No, it's not suitable due to the inherent maximum pin output frequencies in relation to the clock divider setting.

Yes, it's technically possible. Edit the divider to a value that sets the output to close to what you need. However this is annoying to do, and has serious repercussions in your code. (i.e. having to multiply every timing/bit value by 16, 8, 4, 2 or whatever you choose)

A clock of that high of a frequency would have to be some crystal to set the base time, and then a comparator circuit that could vary fast enough to push data into the edges.

You could, however, simply note the absence of the 4MHz signal as 0, and it's presence as 1, sending binary data that way it probably a lot easier than encoding it between each individual edge.

body:
Most Arduinos are based on AVR chips clocked at 16 MHz. On those,
you _can_ generate a 4 MHz clock using hardware timers. Bit-banging
data at this speed would be difficult though. It _may_ be possible,
using unrolled loops and hand-crafted assembly... or not, depending on
the specifics of your application. Even if possible, it would be a nice
challenge for an assembly programmer.

The Arduino Due is based on an ARM chip clocked at 84 MHz. This
gives you more leeway to bit-bang at 4 MHz. But even on the Due you
would certainly need hand-crafted assembly.


body:
My leonardo was working fine until today, when I plug it to my computer all led (RX/TX/L/ON) stays on (Green for on, amber for others) and my computer no longer see a com port.
(by the way, do you know what the L led mean ?)
If I add external power, TX goes off then after few seconds RX goes off too then back on.
With external power, the atmega goes very hot (I can't touch it).
RESET button do nothing.

Is my Leonardo dead ? Any idea what could have cause that ? The fact that the atmega is so hot when the board is powered up with 12V let me think that the voltage regulators is no longer working. Good guess ?

title: Leonardo broken?

Answers: 1

body:
By your description, I'd say:

> Quite Probably.

You should check what the 5V and 3.3V voltages are using a DMM.


body:
So I am doing a project where a bunch of servos are moving from 90 - 120 degrees and slowly speed up over time until they reach their max speed and so stay at that speed.
This is being done by editing the delay under the servo sweep for loop.
However though this works it doesn't work with the next component.

WHat I want to happen next is an MFRC522 RFID reader to always be scanning and at any time it detects a card and verifies it the servos from whatever speed they are now at start to slow down.
The problem is I can't get the two functions to run simultaneously. IF the servo is running its sweep function it must finish before the RFID tag can scan. This makes the whole device look very lagy.
Is there a way I can get the RFID scanner to be reading all the time even when the servo sweep for loop is working?

Here is the code:
Please note that I have put printins everywhere to see how often the RFID is scanning etc just while I test the code out.
I essentially have two functions one called nocardservo and yescardservo each one activating if there is a card there or not.
Any help would be fantastic!!

    #include <SPI.h>
    #include <MFRC522.h>
    #include <Servo.h>

    #define RST_PIN  9  //
    #define SS_PIN  10  //

    MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

    Servo myservo;
    int pos = 0;
    int y = 15;
    int z = y;
    void setup() {
      myservo.attach(6);
      myservo.writeMicroseconds(1518);
      Serial.begin(9600);  // Initialize serial communications with the PC
      while (!Serial);  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
      SPI.begin();   // Init SPI bus
      mfrc522.PCD_Init();  // Init MFRC522
      //ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details
      //Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
    }

    void loop() {
      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent()) {
    nocardservo();
        return;
      }
      delay(20);
      Serial.println("carddetected");
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {

      }
      Serial.println("correctcard");
      yescardservo();
    delay(20);
    return;
    }

    //***If card not detected this function runs**//

    void nocardservo() {

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

      }
    }
    }

    //***If card is detected this function runs**//

    void yescardservo() {

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

      }

    }

title: Being able to run two functions at once

Answers: 2

body:
What you want to implement is described in [Blink Without Delay][1].  Basically, instead of using the delay function to just wait until your time has elapsed, you use variables to measure how much time has elapsed and only execute your operation when it has.  In the mean time, you can check on other things and do those in the mean time.

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

body:
have a look my example program below for you reference.

    /*
     * Author BALASAIDULU.N
     * function -1 : Fading led with pwm pin 9
     * fucntion -2 : Blinking LED on pin 13
     * connect an LED on pin 9 with a 330 ohms resistor
     */
         int leda=9;
         int ledd=13;
    int i,g,s1,s2;
    int switchPin=8;

    void setup() {
    pinMode(ledd,OUTPUT);
    pinMode(switchPin,INPUT);
    }

    void fading()
    {
      st:
      if(s1==0){
    if(s1==1){goto hy;}
    analogWrite(leda,i);
    delay(30);
    i+=5;
    if(i>255){s1=1;}
    goto st1;
      }
    hy:

    if(i<0){s1=0;goto st;}
    i-=5;
    analogWrite(leda,i);
    delay(30);
     st1:
    delay(10);
    }

    void blinking()
    {
    digitalWrite(ledd,HIGH);
    delay(30);
    digitalWrite(ledd,LOW);
    delay(30);

    }
    void loop() {

    int g;
    g=digitalRead(switchPin);
    if(g==1) {delay(50);}
    if(g==0){
    blinking();
    fading();}
    }


body:
![Arduino power supply][1]

Folks

I am planning to power my Arduino, which will be mounted on a motorcycle, using the motorcycle's battery. So the same battery will be starting the engine and powering other electrical components.

I am wondering if this circuit will work fine.

C1 - 1000uF 50V;
C2 - 1000uF 25V;
D1 - 1N4001 ;

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

title: Motorcycle Battery Powering Arduino UNO

Answers: 1

body:
Your circuit is 'going in the right direction' but can be improved.
If you wish to use the regulator shown:

 - The larger the input capacitor (C1) the better; it will survive noise spikes and low voltage "droops", eg during starting.

 - Adding a series resistor to drop some of the input voltage will help C1 filter out noise.
*Rin* should be V/I = V_drop_max/I_maximum .
With a 9V regulator and 12V supply you cannot afford much drop in the resistor.
 If you use the 6V output system I recommend below then you could allow closer to 3V drop in *Rin*.
If *Imax* is 100mA then *Rin* = V/I = 3/0.1 = 30 Ohms.
Typically you'd use 27 Ohms (which is the closest E12 standard value.

Power dissipation is the resistor = I^2 x R.
So for eg 27 Ohms and 0.1 A (100 mA) power dissipation in the resistor is
I^2 x R = 0.1^2 x 27 = 0.27 Watt
So you'd use at least a 0.5 Watt resistor and ideally  Watt or more. Air cooled resistors are relatively low cost and a much better way of dealing with heat than trying to cool a regulator.

 - Adding a ~15V zener diode at the input to U1 will help protect against spikes. This works better if *Rin* is used. Without *Rin* the zener may be destroyed by spikes. If you use the LM29xx regulators that I mention below the zener is not needed as the regulator has its own internal protection circuitry.

The LM7809 regulator is somewhat unusual. If you have them available they could be used but there are much more common and/or modern regulators available.

The regulator's Vout should be fed to the Arduino's Vin terminal, which supplies the Arduino's internal regulator, to provide 5V or 3V3 depending on which Arduino you are using. With a 5V Arduino, using Vin of 6V or more will be adequate. Higher Vin causes more heat in the Arduino on board regulator. (As Chaaarlie2 noted, 6V on Vin may be a bit on the low side for heavy loads on the Arduino 5V supply - as may happen if shields use the 5V supply. Increasing Vin to say 6.5V should allow the Arduino's internal regulator to supply its maximum rated current if desired.

9V output is higher than the Arduino needs. It is an acceptable voltage but 6V to 7V will cause less heat on-board the Arduino (and more in the external regulator).

Vehicle power systems can have extremely high voltage spikes present and sudden changes in supply voltage. Some regulators are made to work well in the automotive environment. One such family are the LM29xx series of regulators.

One superb version of this regulator is the LM2931-N [[**Data sheet here**]](http://www.ti.com/lit/ds/snosbe5g/snosbe5g.pdf) - this is available in a range of versions but the simplest is the 3 lead type in a range of packages. The TO220 package is recommended due to its good power dissipation capability and ease of heatsinking if necessary. This data sheet covers versions with about 100 mA output rating, but higher output examples are available. Fixed 3.3V and 5V output versions are available but in this application the variable output version, set to about 6V or maybe 6.5V is "safest". These are very similar to the common LM317 in operation. The basic regulator produces 1.26V output and 2 resistors are used to set the desired output voltage. The advantages over the LM317 are the lower dropout voltage and the protection against typical automotive input problems.

The datasheet description states:

> Designed originally for automotive applications, the LM2931-N and all regulated circuitry are protected from reverse battery installations or 2 battery jumps.
>
>During line transients, such as a load dump (60V) when the input voltage to the regulator can momentarily exceed the specified maximum operating voltage, the regulator will automatically shut down to protect both internal circuits and the load.
>
>The LM2931-N cannot be harmed by temporary mirror-image insertion. Familiar regulator features such as short circuit and thermal overload protection are also provided.


body:
I made a sketch that receives an rgb code from a remote Arduino using nrf24l01 and while it works **for the first receivings** then it stops working. I placed a testing `Serial.println` in the loop to test if Arduino stops to work completely or it doesn't receive any other data. Finally, I understood that it continues to work but it doesnt receive more data. Bellow is my code:
<!-- language-all: lang-cpp -->

    #include <RF24Network.h>
    #include <RF24Network_config.h>
    #include <Sync.h>

    #include  <TimerOne.h>
    #include <SPI.h>
    //#include <nRF24L01.h>
    #include <RF24.h>
    RF24 radio(8,10);
    RF24Network network(radio);
    volatile int i=0;
    volatile int d=0;     // Variable to use as a counter
    volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
    int AC_pin= 4;    // Output to Opto Triac pin
    int dim = 0;  // Dimming level (0-128)  0 = ON, 128 = OFF
    int freqStep = 65;

    struct payload_rgb
    {
      unsigned int red;
      unsigned int green;
      unsigned int blue;
    };
    struct payload_lightuv
    {
      unsigned int light;
      unsigned int uv;
    };
    RF24NetworkHeader header;
    payload_rgb payloadrgb;
    payload_lightuv payloadl;
    void setup() {
      // put your setup code here, to run once:
      pinMode(AC_pin, OUTPUT);// Set AC Load pin as output
      pinMode(9, OUTPUT);// Set AC Load pin as output
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
      attachInterrupt(0, zero_cross_detect, RISING);  // Choose the zero cross interrupt # from the table above
      Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
      Timer1.attachInterrupt(dim_check, freqStep);
      Serial.begin(115200);
      radio.begin();
      network.begin(90,01);
    }

    void loop() {
      network.update();
      while ( network.available() )
      {
        Serial.println("Rec");

        network.peek(header);
        if(header.type=='r'){
          network.read(header,&payloadrgb,sizeof(payloadrgb));
          analogWrite(6,payloadrgb.red);
          analogWrite(9,payloadrgb.green);
          analogWrite(5,payloadrgb.blue);
        }
        if(header.type=='l'){
          network.read(header,&payloadl,sizeof(payloadl));
          dim=payloadl.light;
        }
    }
    Serial.println("!"); //this is the test println
    }
    void zero_cross_detect() {
      zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
      i=0;
      digitalWrite(AC_pin, LOW);       // turn off TRIAC (and AC)
    }
    void dim_check() {
      if(zero_cross == true) {
        if(i>=dim) {
          digitalWrite(AC_pin, HIGH); // turn on light
          i=0;  // reset time step counter
          zero_cross = false; //reset zero cross detection
        }
        else {
          i++; // increment time step counter
        }
      }
    }}

Additionally, this Arduino controls an ac dimmer. Bu I have not done it yet.
How can I fix the problem without removing any feature?

title: Arduino stops working after some receivings from RF

Answers: 0


body:
I am currently working on a RFID card reader. I need the reader to send the ID to a storage space.

What I am trying to achieve is a person swipes their card, enters their name on the serial monitor, and then have that data stored in a pair. The thing is that I do not know how many people will have cards. After that, I could call a person's name and it would show "Hello `w`, your ID number is `xxx xxx xxx xxx xxx`.

So I know there are no such things as "dynamic" variables. And I think I would need to pre-define a TON of arrays if I wanted to use them. So I am kinda at a stopping point. Is there no way to generate a new variable name and store data to that variable?

Also, I work with PLCs so I thought that indirect addressing might work, but I am unfamiliar on how to even do that in C++, only in ladder logic or if it would even work. Or how I would be able to call out an ID by name with that approach.

title: How to add data without pre-defining variables?

Answers: 2

body:
The "key" is creating a means to access a table of IDs that you can search through for a given name or a given ID number. There are various ways of doing this and if you are unclear on these that can be discussed in due course. But, to start, I'll assume that making and searching some form of table or array is not a problem for you.

You obviously MUST have enough storage space for the maximum number of simultaneous IDS that you wish to store at any time. Call this "IDCount".

You can allocate IDCount ID storage locations by whatever means suits you.
In unused locations you store a dummy or null ID number.
eg ID 000 000 000 000 000 is probably invalid so can be used as an 'empty' indicator.

To add a new ID  either search through your table of IDs for an empty location and store the new ID there. To find a given ID match you search the table for the ID and , if it exists, retrieve the matching name.

____________________

**"Improvements":**

**To reduce access times** when the potential entries are large you can store all entries "at the bottom" and have a pointer to the 1st free location. New entries are added "at the end". If an entry is removed, all entries above it are moved down by one. eg   if entry N is removed:
for (entry >= N and entry < end_pointer)
...move entry N + 1 into location N
...and step N by 1.

Another method is to use a "**linked list**" where each entry has a pointer to the next entry in the list. New entries take an address from the empty_locations list and add their address to the used_locations list. Removed entries do the opposite. This can be fast and effective but also mind blowing for beginners and, when it goes wrong it can go VERY wrong. Best avoided initially.

The simple "search for 1st empty entry" method will usually work very well.

body:
Use the EEPROM. This allows data to remain intact and unchanged even when power is disconnected.

As you say you're new to programming, and because I wrote a similar program just last week as an experiment for something bigger, I'll talk you through some of it. However, I'm not going to give you the whole code to copy-and-paste, I'm only going to give you information on dealing with EEPROM and structures. C-aficionados may grumble at some bits, and Arduinites at others - sic vita est. This is something of a crash-course so it's not gospel, but it should be more than enough to guide you. You may already know some or most of it; it's included nonetheless for completeness, for those who don't.

----------

## For those who don't know ##

In C, data relevant to an object can be stored in a [structure][1], or `struct`. You can put all sorts of different types of data in a struct, like so:

    struct personalProfile {
        char    firstName[8];
        char    lastName[8];
        uint    cardID;           // 'uint' is an unsigned int...
        bool    accessAllowed;
    };
You can then use that structure to create a 'personal profile' for however many people you want:

    // within your main program:

    struct personalProfile Person1;
    struct personalProfile Person2;

    // Now you can directly access individual aspects as so:

    Person1.firstName = "John";
    Person1.lastName = "Brown";
    Person1.accessAllowed = TRUE;

    Person2.firstName = "Dodgy";
    Person2.lastName = "Dave";
    Person2.accessAllowed = NOT_A_HOPE_IN_HELL;
You can use the *members* of a structure in exactly the same way you'd use that member type if it wasn't part of a structure. Nice and easy.

The best way to store multiple instances of a particular variable type is in an [array][2]:

    struct personalProfile listOfPeople[5];
You now have an array of five (blank) `struct`s, which can be accessed by `listOfPeople[n].firstName = Potato;`, where 'n' is between 0 and the number-of-entries-minus-one. So far so potato.

An array is pretty basic. It's present in all sorts of programming languages because it's inherently essential to almost any program, but the trouble is that it's static. Using the code above, once the array has been created with five `struct`s in it you can't add or remove any. One solution is to create a massive array, and set all the values in each `struct` to zero, or some other 'empty' identifier, so you're always going to have enough entries (up to a point). However, that's lazy, time inefficient (you've got to set aaaaalll the individual elements to your 'empty' signifier), resource inefficient (look at all that unused space!), and the data only lasts while the program is running. As soon as you cut the power to the Arduino, the information is lost.

Next comes [containers][3]. These are part of the Standard Template Library (STL) in C++. They're great for creating and managing dynamic-length arrays. There are different types for different purposes (see the link), but they don't exist in C (at least as far as this post is concerned) and they're not available as part of the Arduino IDE without installing a bunch of libraries or some other intervention. Therefore you've got to make your own version. It's actually pretty easy...

----------
## EEPROM basics ##

The [EEPROM library][4] that comes with Arduino is of course essential for this. It doesn't have many functions, and the ones that exist are fantastically easy to understand. EEPROM, for those who don't know, is non-volatile memory. That means that when you store data it stays there forever, even if you remove the power. The only way to get rid of the data is to write over it. The downside of EEPROM is that it has limited amount of times it can be written to - 100,000 times per bit typically so you don't need to start keeping count, it just means you shouldn't be using it as regular program memory. Reading data from EEPROM isn't limited in the same manner.

Using the function `EEPROM.put(address, data)` you can put ANY data type - an `int`, `char` or - you guessed it - a `struct` into the EEPROM, starting at the byte specified by *address*. Of course there has to be enough space so you can't put an `int`, which takes up more than 1-byte of space, into the last address without the function failing. (Or can you? I haven't tried it yet because I'd never do it in practice.)

So you've created your structure, and made sure that all it's members are a fixed size. That means the structure has a fixed size. If you know that size, you can start putting them into the EEPROM.

    // within main program

    struct personalProfile Person1;
    struct personalProfile Person2;

    // fill in the details for Person 1...
    // fill in the details for Person 2...

    // ...then put Person1 in the EEPROM at address 0.
    EEPROM.put(0, Person1);

    // Done. Now put in Person2. But where?
    // You need to make sure you put them AFTER Person1.

    int AddressJump = sizeof(personalProfile);

    // AddressJump now equals how many bytes are need to store one person.

    EEPROM.put(AddressJump, Person2);

Simple as that.

If you create a Person3, you're going to need to put them `sizeof(personalProfile)` bytes AFTER Person2, i.e. `EEPROM.put(AddressJump*2, Person3);`. So, you add Person*N* to address `AddressJump * (N-1)`.

Retrieving data is the same principle, except you use `EEPROM.get()`:

    // provided you've used the above snippet somewhere to actually
    // populate the EEPROM with something!

    struct personalProfile personA;

    EEPROM.get(0, personA);

    Serial.print("Person A is called:");
    Serial.println(personA.firstName);

Again, you're going to need `sizeof(personalProfile)` to read the second, third, or *N*th person. If you 'send `EEPROM.get()` to the wrong address it will still populate the personalProfile instance with data, it will just be gobbledygook. Once you start putting people in the EEPROM you're going to need to keep track of things otherwise you'll end up lost. You need to manage the list to make sure you don't `put` one person on top of another (you could get in trouble for that) and you don't want to `get` someone that isn't there.

----------
## List management ##

This is where I leave you, for now. When you have digested the information above, and you want to continue, I'll carry on.

Your first task is to determine what sort of array you want. Inevitably it's going to be a [Linked List][5]. This is an array of `structs`, where each `struct` element in the list *contains the memory address of the following element*, thus the list is **linked**. You need to consider:

 1. How the array will be linked (if at all);
 2. Whether or not the array is space-critical (does it have to be as small as possible);
 3. Where the array is going to start;
 4. How you're going to keep track of how many people are in the array.

@TL140 I await your response, good luck!

  [1]: http://www.cplusplus.com/doc/tutorial/structures/
  [2]: http://www.cplusplus.com/doc/tutorial/arrays/
  [3]: http://www.cplusplus.com/reference/stl/
  [4]: http://www.arduino.cc/en/Reference/EEPROM
  [5]: http://en.wikipedia.org/wiki/Linked_list


body:
So I recently got an Arduino Uno R3. Installed the IDE and drivers under Windows 8.1 and everything seemed to work fine and received the 'Done uploading' message when goofing around with the Blink example(was in a hurry that day).

Next day when I connected the Uno, I noticed the L(yellow) led keeps staying on and I get the following error when trying to upload:

    System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
             User configuration file is "/home/cy/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyS0
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: Send: 0 [30]   [20]

I tried on both Windows and Ubuntu and am really excited about learning things with Arduino. Thanks in advance for your help!

title: Arduino Uno R3 L(yellow) led stays on and error on upload

Answers: 0


body: I recently bought a Atmel Atmega 328 P-PU microcontroller.I tried uploading a program to it by using the circuitry given in the link.I am using a RS 232 breakout board.Here is the link http://www.arduino.cc/en/Main/Standalone .I am not able to upload programs to it.It says problem uploading to board or avrdude attempt 1 out of 10 failed.What can I do about it?

title: Problem uploading program to Atmega 328 microcontroller

Answers: 0


body:
I am using the "SD read/write" code from the Arduino IDE examples to test an ethernet shield (clone). The problem is that although a file is created no data is stored in it.

When running the serial monitor will only show the first characters of the *Serial.print()* sentences, e.g when doing *Serial.print("Initializing SD card...")* the serial monitors displays *Ini* or *In* and nothing else.
Also the IDE shows the following error message: (some words in spanish)

    Error dentro de Serial.serialEvent()
    java.io.IOException: Error de entrada/salida in nativeavailable
 at gnu.io.RXTXPort.nativeavailable(Native Method)
 at gnu.io.RXTXPort$SerialInputStream.available(RXTXPort.java:1598)
 at processing.app.Serial.serialEvent(Serial.java:258)
 at gnu.io.RXTXPort.sendEvent(RXTXPort.java:774)
 at gnu.io.RXTXPort.eventLoop(Native Method)
 at gnu.io.RXTXPort$MonitorThread.run(RXTXPort.java:1644)

I have tried with 2 different SD cards, including a brand new one, and 2 different Arduino Uno (a clone and an original one). The OS is Ubuntu 13.10.

My guess is that it has something to do with the *myFile.println()* sentences, when they are commented the serial monitor works fine.

Any help is much appreciated since I couldn't find the problem anywhere else so far!

title: Problems when communicating with SD card using ethernet shield

Answers: 0


body:
I use Ethernet Shield and Arduino to GET data from the server in JSON format. Request looks like this:

    client.println("GET http://ramp.local/api/actions?");

The response I get is:

    [{"action_id":1,"action_type":"up","action_status":"new","ramp_id":31,"user_id":17},
    {"action_id":2,"action_type":"down","action_status":"new","ramp_id":32,"user_id":20},
    {"action_id":3,"action_type":"up","action_status":"completed","ramp_id":32,"user_id":17},
    {"action_id":4,"action_type":"up","action_status":"failed","ramp_id":31,"user_id":17}]

How to collect a data in a string variable and parse it to get `action_status`?

title: Storing and parsing data with Arduino

Answers: 3

body:
Ideally, you would use a proper recursive JSON parser, like the one
suggested in prakharsingh95's answer. However, if code speed and size
are critical considerations, and if the format of the response is
narrowly constrained, then you can build a fast special-purpose parser.

Here is a simple example. It assumes the response has been stored in the
`response` char array:

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

    static const char key[] = "\"action_status\"";
    const char *p, *q;
    char action_status[16];

    for (p = response; ; p = q) {
        p = strstr(p, key);    // find key
        if (!p) break;         // not found
        p = strchr(p, ':');    // find ':' between key and value
        p = strchr(p, '"');    // find opening quotes for the value
        q = strchr(p+1, '"');  // find closing quotes

        // Report finding.
        strncpy(action_status, p+1, q-p-1);
        action_status[q-p-1] = '\0';
        Serial.print("Found action status: ");
        Serial.println(action_status);
    }

Of course, in production code you would check that every `strchr` call
returns a non-NULL pointer. And you would check that the status you
found fits in your buffer.

**Edit** about the pros and cons of this method:

Compared to a proper JSON parser, this approach will give you smaller
and faster code, the drawback is it being more _fragile_. For example,
this will not detect a corrupted JSON, and it will return garbage if the
action\_status happens to be a number instead of a string, or is a
string with embedded double quotes, or if the string "action\_status"
appears as a value of some other field... A full JSON parser should
correctly handle all these cases.

On a non-embedded computer, a proper JSON parser would probably be the
only appropriate answer. On a constrained microcontroller environment,
you sometimes have to make trade-offs. In this particular instance, the
“best” answer depends on how much you weight speed and size vs.
robustness against unexpected input.

body:
I would recommend a JSON parsing library. Checkout https://github.com/bblanchon/ArduinoJson

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

    var response = [] ; // get response here
    int response_length = 4; //Put length of the response array here
    StaticJsonBuffer<200> jsonBuffer;

    String action_ids[] = new String[response_length];
    String action_types[] = new String[response_length];
    String action_statuses[] = new String[response_length];
    String ramp_ids[] = new String[response_length];
    String user_ids[] = new String[response_length];

    for (int i=0; i < response_length ; i++) {
        JsonObject& data = jsonBuffer.parseObject(response[i]);
        // Note the '&' above

        action_ids[i] = data["action_id"];
        action_types[i] = data["action_type"];
        action_statuses[i] = data["action_status"];
        ramp_ids[i] = data["ramp_id"];
        user_ids[i] = data["user_id"];
    }

Of course, you only need to extract those fields that you need.

body:
[Try this on for size.][1]

This is an arduino based, open source, JSON processor.

  [1]: https://github.com/bblanchon/ArduinoJson


body:
When I upload my program to Arduino it says the memory that the program is used. But what if I use a bad management of dynamic memory, or any object is created several times in use a lot of memory and the Arduino memory overload.

How do I know the current size of memory that Arduino is use?

I am thinking about to create a function in Arduino that return me this information if I send it a request command, but also I don't know how do I inspect the Arduino memory.

Note: I am using the Board: Arduino Mega 2560.

I read the question and the answer for [Measure SRAN usage][1]

In the question @fuenfundachtzig ask:

***Can I determine how much SRAM I have left in the live system?***

In my question I am asking about how do I know or monitoring my program memmory. Ok the Measure SRAN usage answer give me the tips or tools to develop my idea, but the question is not the same.

I am tryin to know in an specific time what is the size of my memmory.

### example...

    void setup() { //doing some configuration };

    void loop() {  // invoke some functions and evil function  };

    // in other place a evil function

    void evil(){
    MyClass * instance = new MyClass();
    //play with the instance and it class create other instances....
    //and a dynamic memmory is used but not deleted.
    }

I am trying to know if it happens and how do I detect with Arduino? I am not talking about how much memmory do I left in the live system.

  [1]: https://arduino.stackexchange.com/questions/11845/measure-sram-usage

title: How do I know how many memory that Arduino is use after my code is running for a few time

Answers: 1

body:
Basically it looks like you want to figure out if you have a memory leak. Since the objects get allocated continuously you will end up having less and less free memory.

You can use the functions presented in the sister question answered very nicely by Edgar (more specifically the complex one that calculates all the memory going through the allocation chain).

You can check the returned value every so often (few seconds/minutes depending on your needs) and if the free memory value drops continuously then you have a memory leak somewhere. This will not tell you where the leak is of course. Also this should work well while debugging the code, but would probably not be a good idea to leave it in "production" code.


body:
Some of the code that I have is unbearably long and drives me insane. I don't know if there were simpler ways to doing what I am doing.

    long turn1;
    long turn2;
    long turn3;
    long turn4;
    long turn5;
    long turn6;
    long turn7;
    long turn8;
    long turn9;
    long turn10;
    long turn11;
    long turn12;
    long turn13;
    long turn14;
    long turn15;

 #################

      turn1 = random(sizeof(turns) / sizeof(char*));
      turn2 = random(sizeof(turns) / sizeof(char*));
      turn3 = random(sizeof(turns) / sizeof(char*));
      turn4 = random(sizeof(turns) / sizeof(char*));
      turn5 = random(sizeof(turns) / sizeof(char*));
      turn6 = random(sizeof(turns) / sizeof(char*));
      turn7 = random(sizeof(turns) / sizeof(char*));
      turn8 = random(sizeof(turns) / sizeof(char*));
      turn9 = random(sizeof(turns) / sizeof(char*));
      turn10 = random(sizeof(turns) / sizeof(char*));
      turn11 = random(sizeof(turns) / sizeof(char*));
      turn12 = random(sizeof(turns) / sizeof(char*));
      turn13 = random(sizeof(turns) / sizeof(char*));
      turn14 = random(sizeof(turns) / sizeof(char*));
      turn15 = random(sizeof(turns) / sizeof(char*));
###########
    if (turn1 == turn2 or turn2 == turn3 or turn3 == turn4 or turn4 == turn5 or turn6 == turn7 or turn7 == turn8 or turn8 == turn9 or turn9 == turn10 or turn10 == turn11 or turn11 == turn12 or turn12 == turn13 or turn13 == turn14 or turn14 == turn15) {

###########

    lcd.print(turns[turn1]);
    lcd.print(turns[turn2]);
    lcd.print(turns[turn3]);
    lcd.print(turns[turn4]);
    lcd.print(turns[turn5]);
    lcd.setCursor(0, 2);
    lcd.print(turns[turn6]);
    lcd.print(turns[turn7]);
    lcd.print(turns[turn8]);
    lcd.print(turns[turn9]);
    lcd.print(turns[turn10]);
    lcd.setCursor(0, 3);
    lcd.print(turns[turn11]);
    lcd.print(turns[turn12]);
    lcd.print(turns[turn13]);
    lcd.print(turns[turn14]);
    lcd.print(turns[turn15]);

title: Shortening large chunks of code

Answers: 1

body:
Yes you can, and the solution is very simple. It's in two parts, and they make up part of the absolute fundamental building blocks not just in C, but in almost any programming language.

You can read good information on arrays [**here**][1], and 'for loops' [**here**][2] (it's about half way down the page). Without wishing to offend, it seems like you are missing some really basic concepts and I recommend starting at the beginning of the [**tutorial series**][3] that the two aforementioned links are part of.

I'll just cover the basics. If you don't understand anything, refer to the tutorials. If you *still* don't understand then please comment, but make sure you can convince us that you've really given it a good go. We're here to help as long as you're here to learn.

To declare an array of *N* variables, all of which are the same type, you use:

    <type> <name_of_variable> [<number_of_elements>];

    or:

    long turns[15];
Now you have an array of 15 `long`s. Ta da!

You now have to set the values of each turn. As your values are all the same (if you ignore the fact that `random()` ultimately leaves you with different values) you can use a **for loop**:

    for (int x=0; x<15; x++)
    {
        turns[x] = random(sizeof(turns) / sizeof(char*));
    }
I won't explain how a for loop works; I gave you a link to the tutorial to save me writing it all out myself.

That covers shrinking of part 1 and 2. Part 3 requires a little more thought. That said, as you didn't complete your *if* statement, I don't actually know what you plan to do if any two adjacent `turn` elements are the same. I shall assume that you would 're-randomise' one of the duplicates. For this you can again use a for loop, starting at the beginning and running to *N-1* th element, where *N* is the total number of elements:

    for (int x=0; x<14; x++)
    {
        if (turns[x] == turns[x+1])
        {
            turns[x+1] = random(sizeof(turns) / sizeof(char*));
        }
    }
You need make sure that `turns[x+1]` is not outside of the array, which is why the for loop runs for one iteration less than there are elements.

The fourth shrinkable part is just a matter of swtiching multiple print statements into single for loops:

    for (int x=0; x<NUMBER_OF_PRINTS_IN_1st_BUNCH; x++)
        lcd.print(turns[x]);
    lcd.setcursor(0,2);
    for (int x=WHERE_YOU_LEFT_OFF; x<NUMBER_OF_PRINTS_IN_2nd_BUNCH; x++)
        lcd.print(turns[x]);
    lcd.setcursor(0,3);
    for (int x=WHERE_YOU_LEFT_OFF_AGAIN; x<NUMBER_OF_REMAINING_PRINTS; x++)
        lcd.print(turns[x]);

All done.

  [1]: http://www.cplusplus.com/doc/tutorial/arrays/
  [2]: http://www.cplusplus.com/doc/tutorial/control/
  [3]: http://www.cplusplus.com/doc/tutorial/


body:
Here is their code:

    /*
     PROJECT: ArduDroid
     PROGRAMMER: Hazim Bitar (techbitar at gmail dot com)
     DATE: Oct 31, 2013
     FILE: ardudroid.ino
     LICENSE: Public domain
    */

    #define START_CMD_CHAR '*'
    #define END_CMD_CHAR '#'
    #define DIV_CMD_CHAR '|'
    #define CMD_DIGITALWRITE 10
    #define CMD_ANALOGWRITE 11
    #define CMD_TEXT 12
    #define CMD_READ_ARDUDROID 13
    #define MAX_COMMAND 20  // max command number code. used for error checking.
    #define MIN_COMMAND 10  // minimum command number code. used for error checking.
    #define IN_STRING_LENGHT 40
    #define MAX_ANALOGWRITE 255
    #define PIN_HIGH 3
    #define PIN_LOW 2

    String inText;

    void setup() {
      Serial.begin(9600);
      Serial.println("ArduDroid 0.12 Alpha by TechBitar (2013)");
      Serial.flush();
    }

    void loop()
    {
      Serial.flush();
      int ard_command = 0;
      int pin_num = 0;
      int pin_value = 0;

      char get_char = ' ';  //read serial

      // wait for incoming data
      if (Serial.available() < 1) return; // if serial empty, return to loop().

      // parse incoming command start flag
      get_char = Serial.read();
      if (get_char != START_CMD_CHAR) return; // if no command start flag, return to loop().

      // parse incoming command type
      ard_command = Serial.parseInt(); // read the command

      // parse incoming pin# and value
      pin_num = Serial.parseInt(); // read the pin
      pin_value = Serial.parseInt();  // read the value

      // 1) GET TEXT COMMAND FROM ARDUDROID
      if (ard_command == CMD_TEXT){
        inText =""; //clears variable for new input
        while (Serial.available())  {
          char c = Serial.read();  //gets one byte from serial buffer
          delay(5);
          if (c == END_CMD_CHAR) { // if we the complete string has been read
            // add your code here
            break;
          }
          else {
            if (c !=  DIV_CMD_CHAR) {
              inText += c;
              delay(5);
            }
          }
        }
      }

      // 2) GET digitalWrite DATA FROM ARDUDROID
      if (ard_command == CMD_DIGITALWRITE){
        if (pin_value == PIN_LOW) pin_value = LOW;
        else if (pin_value == PIN_HIGH) pin_value = HIGH;
        else return; // error in pin value. return.
        set_digitalwrite( pin_num,  pin_value);  // Uncomment this function if you wish to use
        return;  // return from start of loop()
      }

      // 3) GET analogWrite DATA FROM ARDUDROID
      if (ard_command == CMD_ANALOGWRITE) {
        analogWrite(  pin_num, pin_value );
        // add your code here
        return;  // Done. return to loop();
      }

      // 4) SEND DATA TO ARDUDROID
      if (ard_command == CMD_READ_ARDUDROID) {
        // char send_to_android[] = "Place your text here." ;
        // Serial.println(send_to_android);   // Example: Sending text
        Serial.print(" Analog 0 = ");
        Serial.println(analogRead(A0));  // Example: Read and send Analog pin value to Arduino
        return;  // Done. return to loop();
      }
    }

    // 2a) select the requested pin# for DigitalWrite action
    void set_digitalwrite(int pin_num, int pin_value)
    {
      switch (pin_num) {
      case 13:
        pinMode(13, OUTPUT);
        digitalWrite(13, pin_value);
        // add your code here
        break;
      case 12:
        pinMode(12, OUTPUT);
        digitalWrite(12, pin_value);
        // add your code here
        break;
      case 11:
        pinMode(11, OUTPUT);
        digitalWrite(11, pin_value);
        // add your code here
        break;
      case 10:
        pinMode(10, OUTPUT);
        digitalWrite(10, pin_value);
        // add your code here
        break;
      case 9:
        pinMode(9, OUTPUT);
        digitalWrite(9, pin_value);
        // add your code here
        break;
      case 8:
        pinMode(8, OUTPUT);
        digitalWrite(8, pin_value);
        // add your code here
        break;
      case 7:
        pinMode(7, OUTPUT);
        digitalWrite(7, pin_value);
        // add your code here
        break;
      case 6:
        pinMode(6, OUTPUT);
        digitalWrite(6, pin_value);
        // add your code here
        break;
      case 5:
        pinMode(5, OUTPUT);
        digitalWrite(5, pin_value);
        // add your code here
        break;
      case 4:
        pinMode(4, OUTPUT);
        digitalWrite(4, pin_value);
        // add your code here
        break;
      case 3:
        pinMode(3, OUTPUT);
        digitalWrite(3, pin_value);
        // add your code here
        break;
      case 2:
        pinMode(2, OUTPUT);
        digitalWrite(2, pin_value);
        // add your code here
        break;
        // default:
        // if nothing else matches, do the default
        // default is optional
      }
    }

And a photo of my circuit:

![Photo of Arduino and breadboard][1]

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

Is anyone able to tell me why when the ardudroid app and bluetooth shield are linked successfully, my LED won't respond to the commands on the app?

title: Bluetooth shield with ardudroid RGB LED

Answers: 0


body:
I have taken a data file using arduino and ov7670 camera module. In this project I used the famous code https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno . But after taking the datafile ov7670NoRam.hex, I can't open it. I spent 3 hours to search how to open, but failed.

Could anyone please let me know how to have a look the image in .hex? or would it be possible to take image data from ov7670 directly to jpg?

I tried to convert the hex file to bin using hex2bin, but when I opened the bin, only errors occurred.

The following is the content of the ov7670NoRam.hex

    :100000000C9436000C944B000C944B000C944B0059
    :100010000C944B000C944B000C944B000C944B0034
    :100020000C944B000C944B000C944B000C944B0024
    :100030000C944B000C944B000C944B000C944B0014
    :100040000C944B000C944B000C944B000C944B0004
    :100050000C944B000C944B000C944B000C944B00F4
    :100060000C944B000C944B005244590011241FBEB9
    :10007000CFEFD8E0DEBFCDBF12E0A0E0B1E0EAE70D
    :10008000F2E002C005900D92A235B107D9F70E94A7
    :10009000AF000C943B010C9400008093BB0084E8FB
    :1000A0008093BC008091BC0087FFFCCF8091B90099
    :1000B000887F90E070E08617970709F408950E9402
    :1000C000A00084EA8093BC008091BC0087FFFCCF35
    :1000D0008091B900887F883009F408950E94A000BB
    :1000E000CF93DF93D82FC62F0E94610068E182E48E
    :1000F0000E944D0068E28D2F0E944D0068E28C2F17
    :100100000E944D0084E98093BC008FE99FE0019735
    :10011000F1F700C00000DF91CF910895CF93DF93F6
    :10012000EC0103C00E9470002296FE01849131967A
    :1001300064918F3FB9F76F3FA9F7DF91CF91089591
    :10014000259A90E285B1892785B92FEF31EE84E0B9
    :10015000215030408040E1F700C00000F3CFF89418
    :10016000239A8091B6008F798093B60083E48093C0
    :10017000B00089E08093B1001092B30087B1807F16
    :1001800087B98AB183708AB92FEF8BE792E9215042
    :1001900080409040E1F700C000008091B9008C7F62
    :1001A0008093B90088E48093B8001092C50081E084
    :1001B0008093C4008091C00082608093C00088E179
    :1001C0008093C10086E08093C20060E882E10E94D3
    :1001D00070002FEF81EE94E0215080409040E1F7D5
    :1001E00000C0000080E091E00E948E0060E285E1A6
    :1001F0000E94700060E08CE00E9470008AE392E050
    :100200000E948E0088E492E00E948E0069E181E104
    :100210000E947000E8E6F0E094918091C00085FFB4
    :10022000FCCF9093C6008091C00085FFFCCF319633
    :1002300084918111F1CF4B9BFECF4B99FECF40EEC5
    :1002400051E08FE792E04A99FECF36B129B1207F85
    :100250003F70232B2093C6004A9BFECF9C01215068
    :100260003109892B11F0C901EECF415051094115D7
    :0A027000510539F7CFCFF894FFCF06
    :10027A0012803A0412001713180132B619021A7AB8
    :10028A00030A0C003E00703A7135721173F0A20134
    :10029A0015027A207B107C1E7D357E5A7F69807616
    :1002AA0081808288838F849685A386AF87C488D706
    :1002BA0089E813C0000010000D401418A505AB070B
    :1002CA002495253326E39F78A068A103A6D8A7D84A
    :1002DA00A8F0A990AA9413C5300031000E610F4B03
    :1002EA0016021E07210222912907330B350B371DEF
    :1002FA003871392A3C784D404E20690074108D4F70
    :10030A008E008F009000910096009A00B084B10C84
    :10031A00B20EB382B80A430A44F045344658472815
    :10032A00483A59885A885B445C675D495E0E6C0A94
    :10033A006D556E116F9E6A400140026013C74F806F
    :10034A00508051005222535E5480589E41083F000B
    :10035A00750576E14C0077013D484B09C960564066
    :10036A0034113B12A48296009730982099309A84CF
    :10037A009B299C039D4C9E3F78047901C8F0790F14
    :10038A00C8007910C87E790AC880790BC801790C2F
    :10039A00C80F790DC8207909C8807902C8C07903C5
    :1003AA00C8407905C8307926FFFF32F617131801BD
    :1003BA0019021A7A030AFFFF12013D08413D76E14C
    :0203CA00FFFF33
    :00000001FF

title: Cannot open ov7670 output file

Answers: 2

body:
What is it you hope to achieve by "opening" the hex file or "converting it to binary"?

A hex file is a compiled sketch. It is intended to be installed into the Arduino Uno using avrdude.

body: I am the author of the code and needless to say I am very confused right now on what you are trying to do. You run make writeflash in order to do what the target names implies write the hex file to microcontroller's internal flash memory. After that is done the code will run and you will use my frame grabber https://github.com/ComputerNerd/simpleFrameGrabber to capture an image.