body:
I'd like to make three arrays of the same length. According to the [documentation][1], Arrays must be defined as `int myArray[10];` where 10 can be substituted for a known length (another integer), or filled with an array `{2, 3, 5, 6, 7}`.

However, when I attempted to declare a value `int arrSize = 10;` and then an array based on that size `int myArray[arrSize];`, I get the following: `error: array bound is not an integer constant`.

Is there a way to variably determine array sizes, or do I just need to hardcode them? (I was taught hardcoding is bad and something to avoid at all costs.)

  [1]: http://arduino.cc/en/Reference/array

title: How can I declare an array of variable size (Globally)

Answers: 5

body:
The size of the array must be known at compile time. Otherwise you should allocate memory dynamically using:

    char *chararray = malloc(sizeof(char)*x);

where x(an integer) can be set in the application code (you could load it from eeprom if you wanted it be a persistent but configurable setting).

---

However if you just want to declare some arrays of the same size, you just have to declare the number a constant like this:

    const int arrsize = 10;
    char array1[arrsize];
    int array2[arrsize];

---

I think not hardcoding things only makes sense if you would reasonably expect the user to want to change the setting at some point. I don't know if that's the case.

body:
Your question has 2 parts actually.

**1/ How can I declare the constant size of an array outside the array?**

You can either use a macro

    #define ARRAY_SIZE 10
    ...
    int myArray[ARRAY_SIZE];

or use a constant

    const int ARRAY_SIZE = 10;
    ...
    int myArray[ARRAY_SIZE];

if you initialized the array and you need to know its size then you can do:

    int myArray[] = {1, 2, 3, 4, 5};
    const int ARRAY_SIZE = sizeof(myArray) / sizeof(int);

the second `sizeof` is on the type of each element of your array, here `int`.

**2/ How can I have an array which size is dynamic (i.e. not known until runtime)?**

For that you will need dynamic allocation, which works on Arduino, but is generally not advised as this can cause the "heap" to become fragmented.

You can do (C way):

    // Declaration
    int* myArray = 0;
    int myArraySize = 0;

    // Allocation (let's suppose size contains some value discovered at runtime,
    // e.g. obtained from some external source)
    if (myArray != 0) {
        myArray = (int*) realloc(myArray, size * sizeof(int));
    } else {
        myArray = (int*) malloc(size * sizeof(int));
    }

Or (C++ way):

    // Declaration
    int* myArray = 0;
    int myArraySize = 0;

    // Allocation (let's suppose size contains some value discovered at runtime,
    // e.g. obtained from some external source or through other program logic)
    if (myArray != 0) {
        delete [] myArray;
    }
    myArray = new int [size];

For more about problems with heap fragmentation, you can refer to [this question][1].

  [1]: https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino

body: If you know the maximum length of array, just initialize the array to that length and use an integer to tell the program how much of that array to use.  If it's the difference between 7,10 bytes then you are not wasting that much memory allocation.

body:
I know I'm a little late here, but in theory regular arrays can't be created using a variable to define the amount of elements the array is going to have as in:

    int arrSize;
    int myArray[arrSize];

This will display an error since when declaring the array, the program expects for the value between the brackets to be a constant. Yet, there is a way in which you could create an array with a variable defining the amount of values this arrays is going to have through dynamic memory allocation for value sets (this method has been tested with monodimensional arrays only, haven't tried for multidimensional yet), and it goes something like this:

    //First you create a pointer for the memory space to be separated for the set you're creating
    int* myArray;
    int arrSize; //Then you define the variable that will determine the amount of elements the array is going to have, you can give it a value whenever you want as long as this int is defined before the values in myArray are set
    myArray=(int*)calloc(arrSize,sizeof(int)) //Here, you establish that the instance myArray (whose memory space has already been separated through the creation of the pointer) will be separated into arrSize amount of elements of type int with a maximum memory value (in bytes) equal to the maximum available for the int type variables

After this, all that's left to do is assign a value for every element created in the instance myArray (which is already an Array by now) as you would for a normal array created as myArray[arrSize].

body:
The coderwall explains in Some detail the theory of how best to get the size of an array in C++ [https://coderwall.com/p/nb9ngq/better-getting-array-size-in-c][1]

  [1]: https://coderwall.com/p/nb9ngq/better-getting-array-size-in-c


body:
I try to connect arduino with motor using DRV-8835. The problem I have - simply nothing happens. I used tutorial from http://www.instructables.com/id/The-SnapMobile-Start-Your-Physical-Computing-Engin/step6/Building-the-Prototype-Wiring-Up-the-Arduino-the-D/

Code for arduino:

    void setup() {
        pinMode(7, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(8, OUTPUT);
    }

    void loop() {
      digitalWrite(8, HIGH);
      digitalWrite(7, HIGH);
      analogWrite(5, 255);
    }

Maybe someone has scheme how to connect wires to motor. Now I'm not sure if I made a mistake or motor driver is broken.

![enter image description here][1]

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

title: How to connect DRV-8835 to arduino

Answers: 2

body:
Try this code:

    void setup() {
        pinMode(8, OUTPUT);//MODE
        pinMode(5, OUTPUT);//AENBL
        pinMode(7, OUTPUT);//APHASE
    }

    void loop() {
      pinMode(7, HIGH);//APHASE
      pinMode(8, HIGH);//MODE
      pinMode(5, HIGH);//AENBL
      delay(200);
      pinMode(5, LOW);//AENBL
    }

[Here is a description of the breakout board][1], this shows a requirement of PWM on AENBL for speed control. Try different  delays.

  [1]: http://www.pololu.com/product/2135

body:
Setting AENBL HIGH should drive the motor at full speed - it has the same effect as analogWrite(5, 255). Dropping it from high to low should stop the motor.

Are you sure the DRV8835 is working properly? You can in theory diagnose it with a logic analyzer, but a scope will work better as the motor outputs aren't really logic. My test setup (yeah, I had one die on me) watched PHASE (just make sure it would toggle), MODE (should be HIGH), and AENBL (should show a square wave for the PWM duty cycle) as logic inputs, then watched the motor outputs on the scope to verify that one of them is the inverse of AENBL and the other is HIGH. Which follows AENBL and which is HIGH depends on PHASE, so you can toggle it if you can only check one output.


body:
I'm using an Arduino UNO to program a pre-compiled hex image to an ATTINY45, using the avrdude in the Arduino IDE directory, on Windows 7. The Uno has the ISP sketch loaded from the examples directory and that works- the heartbeat LED pulses nicely.

On the hardware side I have [this setup](http://highlowtech.org/?p=1706), except the ATTINY is surface-mount, soldered to a surfboard with all its pins verified-soldered with a voltmeter. I use a header-pin strip, held by hand to get the pins touching the surfboard, to get the signals from the Uno to the ATTINY.

Here are the command lines, which I took from looking at the IDE's debugging output:

    REM set the fuse for 8MHz, so the ISP programmer can work
    C:\Progra~1\Arduino\hardware\tools\avr\bin\avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m
    REM load the program
    C:\Progra~1\Arduino\hardware\tools\avr\bin\avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -Uflash:w:firefly.hex:i
    REM set fuse for 1MHz, as the project requires
    C:\Progra~1\Arduino\hardware/tools/avr/bin/avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0x62:m

-I try running those separately, but always get this error:

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

but sometimes the number is ff0000 or ffff00 or ffffff

I read that "Arduino uses a slightly modified version of avrdude to upload sketches to the Arduino board. The standard version queries for the board's device signature in a way not understood by the bootloader, resulting in this error." Does this mean that using the Arduino avrdude with a new ATTINY chip, no bootloader on it, would also cause that same error? In other words, is the modified avrdude incapable of querying a non-Arduino-bootloaded AVR chip?

Or does that error simply mean I don't have a good contact between all my programmer pins and the ATTINY?

And, are the fuse settings truly needed, can the Uno program the flash into an attiny running at 1MHz and thus save me some steps?

(I would just buy a "real" programmer, but need to get this code in the next two days, and am in a rural part of Nova Scotia)

title: When using Arduino Uno as ISP does "Yikes! Invalid device signature" mean a bad connection, bad config, or bad version of avrdude?

Answers: 3

body:
I soldered wires to pads to be sure the connection was good, and used those wires for programming from the Uno. Then the programmer worked, without any edits to the command lines as posted in the question. I ran a few variations and was able to answer all my questions, and a few more besides:

1. The "Yikes! Invalid device signature" error was being caused by poor contact between the programmer (Uno) and the ATTINY pins.

2. It had nothing to do with the bootloader not being on the new microcontroller. The new ATTINY45 chip doesn't need a bootloader for the in-circuit programmer to work.

3. The Uno can program the ATTINY45 configured to either of its speeds, 1MHz or 8MHz. The factory settings are fine, and don't require changing the fuses.

4. Both avrdude versions worked for programming- the 6.1 from the author's site, and the modified one from the Arduino IDE.

5. avrdude can program via the Uno using any of `-c avrisp`, `-c arduino`, or `-c stk500v1`, it doesn't matter which.

One little question I wasn't able to answer, was what speed the Uno programs at (communication speed between the Arduino I/O pins & microcontroller being flashed). Is it related to the serial port speed? But it turned out to be not pertinent to answering this problem. Someone else can ask it if curious enough.

body:
Add the board and their fuse description from what is already set and it will work.

For adding just `C:\Program Files\Arduino\hardware\arduino\avr\boards.txt` and add the board description.

    ########
    ############ Definitions for ATmega 8MHz
    ##############################################################
    atmega16-8.name=Atmega16 (internal 8MHz clock)

    atmega16-8.upload.tool=avrdude

    atmega16-8.upload.protocol=stk500v1

    atmega16-8.upload.maximum_size=14336
    atmega16-8.upload.speed=19200

    atmega16-8.bootloader.low_fuses=0xE8
    atmega16-8.bootloader.high_fuses=0x99

    atmega16-8.build.mcu=atmega16
    atmega16-8.build.f_cpu=8000000L
    atmega16-8.build.core=arduino:arduino
    atmega16-8.build.variant=mega16

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

I used it.

body:
I had *exactly* this problem. If the ATtiny is set for external clock, then the ArduinoISP will not be able to program it without an external crystal. Connected a 16 MHz crystal and 2 capacitors and worked perfectly.

(I was then able to set ATtiny to internal clock, remove the crystal, and then worked perfectly without the crystal.)


body:
I'm trying to upload a hex file from Java/Processing but running into some issues.
Here is my code so far, based on the Arduino IDE's upload verbose output:

    void setup(){
        //C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM96 -b115200 -D -Uflash:w:C:\Users\HM\AppData\Local\Temp\build5909267154049588263.tmp/sketch_aug13a.cpp.hex:i
        String ArduinoPath = "C:\\Program Files (x86)\\Arduino";
        String hexPath = "C:\\Users\\HM\\AppData\\Local\\Temp\\build1023547366107161384.tmp/sketch_aug13a.cpp.hex";
        String port = "COM96";
        runCommand(new String[]{ArduinoPath+"/hardware/tools/avr/bin/avrdude", "-C"+ArduinoPath+"/hardware/tools/avr/etc/avrdude.conf","-v","-v","-v","-v","-patmega328p","-carduino","-P"+port,"-b115200","-D","-Uflash:w:"+hexPath+":i"});
      }
      void runCommand(String[] cmd){

        String s = null;

        try {

          Process p = Runtime.getRuntime().exec(cmd);
          BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
          BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

          // read the output from the command
          System.out.println("command out:\n");
          while ( (s = stdInput.readLine ()) != null) System.out.println(s);
          System.out.println("errors (if any):\n");
          while ( (s = stdError.readLine ()) != null) System.out.println(s);

        }catch (IOException e) {
          System.out.println("something went wrong: \n");
          e.printStackTrace();
        }

      }

If I run this from command line it uploads without any issues, but from the code above I always get this output:

    avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardw
    are\tools\avr\etc\avrdude.conf"

             Using Port                    : COM96
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
    avrdude: ser_open(): can't open device "\\.\COM96": Access is denied.

    avrdude done.  Thank you.

title: How to upload an arduino sketch from java / processing?

Answers: 1

body:
I'd first would try to find out the right command when running on command line (`cmd.exe`).

When you launch an external command from Java which generates output, you should/must read the output (`p.getInputStream()`, `p.getErrorStream()`) using separate threads. Otherwise your application might hang for no obvious reason.


body:
I attached two images of the shield.

![TFT Front image][1]

![TFT Back Image][2]

I bought an Arduino Mega 2560 R3 with a TFT 3.5 Display shield in China.

What I know from my research is:

 1. There are no data sheets available in the Internet.
 2. The factory's web site, in China, is in Chinese, and there is no information in English.
 3. I achieved to know the factory is www.mcufriend.com, because it is the only reference in the shield.
 4. Apparently the drive to use is R61581.
 5. Using suggested libraries from Henning Karlsen (http://www.henningkarlsen.com/electronics/library.php)
(UTFT, UTFT Geometry, tiny Fat, UTFT Tiny Fat, UTouch and UTFT buttons) . These libraries don't work with this shield.
 6. Some people say that this shield requires 3.3 [Volts] to work, but the Vcc pin connected goes to 5V and it contains a Voltage regulator. I suppose it drops the voltage from 5[V] to 3.3[V] in the middle of the back side of the screen shield (see the upper photo - U1).
 7. The specs that I found, say that this is a 262,144 Color 320x480 Dot Graphic LCD screen using a LCD driver a Si TFT Panel.
 8. This screen includes a touch pad and a Micro SD memory reader.
 9. After using the geometry test included in the library folder UTF Geometry mentioned on #5, and using all the drivers found in the documentation included by Henning Karlsen in a .pdf doc, I couldn't get this shield to work.

Does anyone know how to make this screen work?

I know is too much technology involved to be a fake shield, but it should be very useful to have this working. Do you agree with me?

  [1]: https://i.stack.imgur.com/0iL7l.jpg
  [2]: https://i.stack.imgur.com/csK7R.jpg

title: Arduino Mega 2560 - TFT 3.5 Display is not working with libraries suggested

Answers: 1

body:
I have the same display. It has ILI9137 chip using 8-bit mode, so original Henning Karlsen UTF library doesn't work. You can find this library patched to support this display using Arduino MEGA at https://github.com/dgolda/UTFT

If display wouldn't work it is probably broken. I've received first piece broken - only backlight was working, but second and third was OK.


body:
I've set up a DC motor connected to my Arduino Uno with the following layout. I'm using a 1.5V - 3V DC motor that was purchased from RadioShack.

Here is my code:

    int controlPin = 9;

    void setup(){
      pinMode(controlPin, OUTPUT);
      Serial.begin(9600);
      while(!Serial);
      Serial.println("Ready");
    }

    void loop(){
      if(Serial.available()){
        int s = Serial.parseInt();
        if(s >= 0 && s <= 255){
          Serial.println(s);
          analogWrite(controlPin, s);
        }
      }
    }

If I connect the motor through the Arduino 5V pin it only hums until I set the speed `s` to 200 or greater. This seems odd because I'm supplying 5V.

As a next step I decided to try a 9V battery (I don't really care if I fry the motor, I just wanted to experiment). Of course this is over the recommended voltage, but I assumed if I sent a low enough signal (`s`) through pin 9 it might not destroy the motor. However, to my surprise, when I connected the 9V battery (as illustrated below) the motor immediately starts spinning. I measured the current and it seems to be ~150mA when connected to the 9V battery. It seems like the circuit is connected even though I'm not sending any signal from pin 9 to the transistor. If I removed any of the wires connected to ground, the motor, obviously, stops spinning. My expectation, which is apparently wrong, was that the motor wouldn't spin until I sent a signal from pin 9 to the transistor. What am I not grasping here?

![enter image description here][1]

Here's a picture as my diagram may be wrong based on comments below. This shows the diode reversed as suggested by Chris.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/FUsj6.png
  [2]: https://i.stack.imgur.com/l9RFU.jpg

I also moved the jumper going from pin 9 to the breadboard out of the Vcc column and directly into the row with the resistor. I'm not sure if that resolves the short mentioned in comments.

title: Why does my dc motor immediately spin when connected to a 9v battery?

Answers: 2

body:
Your wiring diagram is a jumbled mess, and makes it impossible to figure out what's really going on.

My guess is that you have a mistake somewhere in your wiring.

Problems I see with your wiring diagram:

  * You show pin 9 from the Arduino wired to the positive rail of your breadboard. If the positive rail is connected to a 9V battery, this will likely destroy pin 9 of your Arduino.

  * You show the gate/base of your transistor wired to the positive rail of your breadboard. This would switch your transistor on constantly.

  * You show the symbol for a MOSFET transistor, but the label on it lists it as a 222A, which is an NPN BJT, not a MOSFET.

  * You don't show any wires connecting the left and right side rails of your breadboard.

  * You're using a row of your breadboard as the ground rather than the rails.

The picture you posted is too small to tell if your wiring diagram is wrong or if you actually connected things incorrectly, and the wire from your 9V battery is blocking the camera's view of key connections.

It looks like your wire from pin 9 is NOT connected to the power rail, but is instead connected to column 1 in your breadboard, which is good.

There are some strong conventions in wiring with breadboards and you should learn to follow them. The two pairs of columns of sockets on the left and right are for positive and negative supply voltage. Usually you wire them together and connect them to regulated power. Sometimes they will be used for different voltages, although you need to be really careful if you do this, since connecting to the wrong side can fry components.

It's confusing the way you've created your wiring diagram, but it looks like you have your flyback protection diode wired correctly, which is good. That's very important, as DC motors and other inductors create destructive reverse voltages as they are switched on and off, and without a flyback diode it can destroy solid state devices like ICs or even transistors.

You should re-wire your breadboard using the proper conventions, and post a corrected wiring diagram that really shows what's going on.

A picture where we can see all the wires and components clearly would also help.

Until you better learn what you are doing I would strongly advise against powering things directly from a 9V battery. When you do that, a mistake in wiring will fry your Arduino and/or any ICs you have on your breadboard.

Wire the 9V to the V-in pin on your Arduino, and then bring 5V and ground from the Arduino onto the +/- supply rails of the breadboard.

I also notice that in your code, you never set the state of controlPin in your setup method. You should add this line to your setup:

    digitalWrite(controlPin, LOW);

That way the pin starts out in the OFF state, and then later on you can us an analogWrite to set it to the desired output level.

body:
You need to turn the transistor 180 degrees (assuming you are indeed p2n2222a).

![enter image description here][1]

Collector should go to the motor, Emitter should go to ground. In your photo you have those two swapped.

Also, I don't think the diode is the correct way around in that photo. That will just short out the battery, thought admittedly that would prevent the motor from spinning (-:

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


body:
I am attempting to do a simple example with the Rotary Angle Sensor.

**Here is my development environment:**

 - [Visual Studio 2013 Premium][1]
 - [Arduino Debug Tool][2]

![Visual Studio Solution and Projects][4]

**Board setup (Simple as can be single analog input):**
![Seeeduino V3 Setup][3]

**Code:**

    const int ROTARYSENSOR = A0;

    void setup()
    {
     Serial.println("Setup Start...");
     Serial.begin(9600); //Set the serial communication frequency at 9600 bits per second

     pinMode(ROTARYSENSOR, INPUT);

     Serial.println("Setup End!");
    }

    void loop()
    {
     Serial.println("Loop Start...");

     int value = analogRead(ROTARYSENSOR);
     Serial.println(value); //display on serial monitor
     delay(1000); //wait 1000ms before printing next value

     Serial.println("Loop End!");
    }

**Issue:**

I have a single solution with multiple projects as my sensor playground. All other projects I have so far work flawlessly no issues.  Although with this project (RotaryAngleSensor) I am getting a strange message.

I am not seeing any of the Serial.println() messages. What is printed to the screen after a good 30 seconds is ***S?***

Does anyone know what could be returning this S? to the standard output?

  [1]: http://www.visualstudio.com/en-us/products/visual-studio-premium-with-msdn-vs.aspx
  [2]: http://www.visualmicro.com/page/Arduino-Debug-In-Visual-Studio.aspx
  [3]: https://i.stack.imgur.com/dBgoO.jpg
  [4]: https://i.stack.imgur.com/oyOS4.png

title: Seeeduino V3.0 (Atmega 328P) and Rotary Angle Sensor Mystery Message

Answers: 1

body:
One problem is that you try to generate serial output **before** you initiate Serial.  This could have odd results beyond just making that message fail.

    Serial.println("Setup Start...");
    Serial.begin(9600);

Should be

    Serial.begin(9600);
    Serial.println("Setup Start...");

And of course your posted code never reads the sensor...


body: I want to make two or more boards to blink an LED at the same time (within 1 ms difference) The boards cannot be connected with wires to each other and will be located in different rooms. How can I do this? What components do I need?

title: Multiple boards blinking at same time

Answers: 3

body:
You could certainly do it with multiple Arduinos, each with a WiFi shield, but that would cost a lot of money.

Instead I would suggest building a low power radio transmitter that sends simple morse code clicks, and then building amplifier boards that use the clicks to trigger LED blinks. You'd need to use a frequency that is open for low power use in your country, like the range for garage door openers.

I've seen circuits in old electronics kits for building morse code transmitters, but they might not meet current FCC regulations.

body:
Have both sync to a master clock using GSM shields. These shields are getting very cheap ([as low as $14 on ebay][1]).

The shields receive the time wirelessly from the cellular network and this time base is extremely accurate. Here is some example code to read the current time from the shield...

http://forum.arduino.cc/index.php?topic=163155.msg2102141#msg2102141

Note that you will need a SIM card to get the time, but you should not need an active cellular account.

  [1]: http://www.ebay.com/itm/like/181722612700?lpid=82&chn=ps

body: You can also use real time clock (RTC) modules to syncronize arduinos. These are cheaper than other solutions like GPS or WiFi.


body:
I am making a fire fighting robot and I need a sensor. I want the sensor detection range to be about 6m or 7m (about 18ft to 20ft).

The question is which sensor should I choose to get that detection range? I've found that some small IR sensors are not suitable for my range required.

I'm making a simulated one. It might be confused if there are non-fire distractions so I'm asking for a technique that can improve the sensor range and determination very very effective... or which sensor should I choose??

I don't want the IR sensor to be more directional. If I need it to be more directional I can use 2 or 3 or more. It is no problem. I want the IR sensors to improve their detection range. I can only get 2m now. I want it to be about 4m or 5m.

title: Flame Sensors Problems

Answers: 0


body:
I have connected my GSM module to my Arduino. Using AT commands I am able to connect to internet.
  Using the following link of tutorials, I tried to connect to internet
http://arduino.cc/en/Tutorial/GSMExamplesXivelyClient
  In this the device is showing not connected. So I tried to debug it. In the attachGPRS
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)

gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD = 2

and GPRS_READY = 4

Why is this happening? What is GPRS_READY ?

title: SIM 900 + Arduino Mega attachGPRS problem, GPRS_READY

Answers: 0


body:
I have a cheap MPU 6050 chip that communicates over 3.3V I2C. I can talk to it just fine on my Leonardo. If I add an additional Adafruit Motor shield (the old one), my MPU 6050 demo sketch hangs somewhere, and I get nothing back.

As far as I see, the pins I use for the I2C communication are not used at all by the motor shield.

What could be wrong here?

I have the MPU6050 connected to SCL, SDA, GND and 3.3V, the motor shield uses almost all other pins.

Additional Info:
I am using this sketch currently: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050

Update:
Lots of "Serial.println"s later, I've narrowed it down a bit. The example sketch above hangs on the statement "Wire.endTransmission();" on line 279 of the I2CDev library.

Update:
Connecting the motor shield to external power seems to fix my problem. Weird =) I am still interested in the reason for this behavior.

title: I2C seems to stop working when I attach an AF motor shield

Answers: 1

body:
Motors draw large amounts of current, and will either cause your power supply voltage to sag if you draw more current than your power supply can support, or cause blips in the power supply that will cause you all sorts of problems.

You need to take steps to isolate the power from the motor shield from the power for the Arduino.

How are you powering the motor shield? How are you powering the Arduino?

If your power supply has enough current to support both your Arduino and your motors then you can probably solve the problem by adding an isolation capacitor between the Vin port on your Arduino and ground.

What that does is to filter out temporary variations in the input voltage that's being fed to the Arduino. Without it, the Vin voltage to the Arduino is probably dropping as your motor draws large pulses of current, and **that** causes the output from the voltage regulator to droop as well.

I don't know how to pick the rating of the cap. A trip to the Electrical Engineering stack exchange is probably in order.


body:
In order to fit **maximum user program** into the chip, how to free up Flash space (0.5 kilo bytes for UNO, 2 KB pro Mini, 8KB for ATMega2560) by **removing the bootloader on Atmega328** (UNO, Pro Mini, or similar)?

What **software** development tools needed (like Atmel AVR Studio software or similar)?

What **hardware** flash writing / debug tools needed (like JTAG hardware programmer/debugger)?

How is the **procedure**? Where can I get **more information**.

Many thanks in advance.

edit: Update boot loader size for different boards

title: How to free up Flash space by removing the bootloader on UNO?

Answers: 1

body: You'll need to use an ISP programmer with avrdude. Perform a chip erase and then unprogram the `BOOTRST` fuse in the high fuse byte.


body:
I bought [an OBD connector][1] from Sparkfun to try to connect to my vehicle via arduino.

I'm just beginning and am not sure if I can just connect the connector pics to the arduino directly, or if there is some other required hardware?

Does anyone know if I can connect directly and why or why not?

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

title: OBD Connector to Arduino

Answers: 1

body:
I briefly read up on this subject and I found out this:

It seems like there's a protocol called *J1850*. There's no native support on the Arduino for that, but you might be able to do something bit-banging if you can find the specifications for this protocol. If you do this, I'd advise accessing the registers directly and skipping the `digitalRead()` command.

There are a few protocols in use, so it is hard to know without knowing the car you drive to even tell what the car will send.

*[More on this topic...][1]*

Anyway, it seems like you need a chip to use with this. [Sparkfun also sells a breakout board for the STN1110 OBD-II to UART chip][2] *([tutorial)][3]*. I couldn't really find anything else besides [this][4].

Anyway, you probably need another chip to do this work. The Arduino isn't meant to do all of these protocols, and the OBD isn't UART-compatible.

  [1]: http://pinoutsguide.com/CarElectronics/car_obd2_pinout.shtml
  [2]: https://www.sparkfun.com/products/9555
  [3]: https://learn.sparkfun.com/tutorials/obd-ii-uart-hookup-guide
  [4]: http://arduinodev.com/hardware/obd-kit/


body:
According to [official web info][1] bootloader sizes are **0.5, 2 and 8 kilo bytes** for UNO, Pro mini and ATMega2560. I believe all three boot loaders do similar job of receiving serial link data and write to Flash memory.

UNO and Pro mini use **same/similar** ATMega168/328 chips but boot loader size are 0.5 and 2 KB.

ATMega2560 apparent has a more **advanced MCU** which presumably should use similar or even less memory to do the same task, but the size is significantly large at **8 KB**.

Why sizes differ? Small difference may be explained by different development teams, but, should be **that much different**, from 0.5 to 8KB.

  [1]: http://arduino.cc/en/Main/ArduinoBoardProMini

title: Why bootloader sizes differs from 0.5 to 8 kilo bytes for different boards?

Answers: 2

body:
Bootloader of the Mini and Uno are pretty much the same. (I can't find the source-code but the hex files are only slightly different).

The 2k is because they haven't updated `mini328.upload.maximum_size` in `boards.txt`. Probably because that would break the board for users that haven't updated the bootloader yet.

The 2560 is using a stk500v2 compatible boot loader instead of Optiboot (uno and mini), because optiboot only supports upto 64kb addresses. Not sure why it is that much bigger though.

body:
Generally speaking the chips offer four possible bootloader size configurations. For example, on the Atmega328 you can have 512, 1024, 2048 or 4096 bytes (notice that the sizes increase by a power of 2).

The chips with less program memory offer smaller bootloaders because they won't want to use a lot of that memory for something that is only used to upload code. The chips with more memory (like the Atmega2560) offer larger bootloaders, ie. 1k, 2k, 4k, 8k (again it increases by a power of 2).

The Uno manages to use a 512 byte bootloader (Optiboot). The Mega, which has more complex instructions (to handle a larger address space) would need larger bootloaders. Also in some cases the bootloader writers add in extra stuff like a debugging console.


body:
As stated in [www.Arduino.cc FAQ][1], "Can I use an Arduino board without the Arduino software? Sure. It's just an AVR development board, you can use straight AVR C or C++ (with avr-gcc and avrdude or AVR Studio) to program it."

For UNO/Pro Mini(ATMega328) and ATmega2560, does these two chips support JTAG type (some chip manufacturers may use different name) programmer / hardware-based debugger in same manner as the ST-Link/J-Link programmer/debugger where one can **load code** into the MCU and perform **hardware break point** and single stepping? Example as in  [STM32 development board with ST-LINK programmer / debugger][2] where the chip has built-in debug circuit that communicate with ST-Link.

Many thanks in advance.

  [1]: http://arduino.cc/en/Main/FAQ
  [2]: http://www.st.com/web/catalog/tools/FM116/SC959/SS1532/PF252419?sc=internet/evalboard/product/252419.jsp

title: Does ATMega 328/2560 chips support JTAG-type programmer and hardware debugger?

Answers: 1

body: The ATmegaXX8 does not support JTAG, but the ATmegaXX0, 'XX1, and 'XX4 do. The 'XX8 (as well as other AVR families) supports debugWIRE, which allows debugging over ISP. You will need one of Atmel's debuggers such as the AVR ONE! or the Atmel-ICE as well as Atmel Studio in order to use it.


body:
I'm designing an Arduino style board with built-in LEDs for several of the pins. To simplify assembly of the board and save on components, I was wondering whether it would be safe for those LEDs to share a single resistor, as in this diagram:

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

Obviously, the power dissipated through the resistor (3mA per pin @ 3V) is not a real problem. The reason I was hesitating is that LEDs in a parallel configuration should not share resistors, but is it safe to think that separate microcontroller pins don't count as a common anode, even if both pins are high?

title: Can two LEDs attached to different pins share their resistor?

Answers: 2

body:
Your circuit is safe from the electronic viewpoint, so long as the LEDs used can withstand a back-emf of 4v or so.

If only one LED is on at a time, all will be sweet. But if two or more are on, the brightness will drop and the brightness between LEDS will probably be inconsistent. The forward voltage drop of individual LEDS tend to vary a little, so one is likely to hog most of the available current.

A separate resistor per LED is probably best.

body:
> **Can** two LEDs attached to different pins share their resistor?

 + **can** : yes
 + **should** : probably not

Your resistor act here as a current limiter, say to _3mA_

If you light one LED at a time, you give 3mA to _that_ LED
If you light 2 LEDs, you give 3mA for both of them (more of less 1.5mA each)
If you light 3 LEDs, you give 3mA for all of them (*on average* 1mA each)

Things are even a little bit more subtle, as different LED might have different forward voltage, so one LED might very well drain 10% more current than an other.

As "Amps made LED bright", less Amp is less light. On LED light with that setup will give "full light on", and more LED you add, less would bright each one.

As an edit to that answer, there is one case I might consider that arrangement for "multi-LED lighting". This is if you are [multiplexing your LEDs](http://en.wikipedia.org/wiki/Multiplexed_display)

That is lighting only one at a time, but cycling fast enough from one LED to the next so that the human eye would _see_ them all lit at once.


body: Say I wrote a compiled sketch to EEPROM then read it. Could I run the program from EEPROM? I guess the question is: Can an Arduino run software not in flash memory in the middle of executing the software in flash?

title: Is it possible to run a binary from EEPROM?

Answers: 2

body: No. The foundation of a Harvard architecture such as AVR is to only allow code that exists within program space to be executed, and EEPROM is not within program space. It is possible, however, to write a virtual machine that will run from flash. This VM can then read program-become-data from anywhere and take action based on it.

body:
Short answer: No; From the atmega328's data sheet (though it applies to all AVR's):
>AVR uses a Harvard architecture – with
separate memories and buses for program and data. Instructions in the program memory are
executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory

>...

> Program Flash memory space is divided in two sections, the Boot Program section and the
Application Program section. Both sections have dedicated Lock bits for write and read/write
protection. The SPM instruction that writes into the Application Flash memory section must
reside in the Boot Program section

It's architecture prevents using external program memory, but you can load anything into program memory at boot. At that point I would venture to say you are just programming AVR and not arduino, since you would need to replace the arduino bootloader and break the arduino IDE's ability to upload programs.

Alternately you could also use an emulator or interpreter of some intermediate language; basically code that steps through and runs other code. As a general rule an emulator runs around 8x slower.

There are micro-controllers from other brands that do support this functionality, I know a couple different PIC's do.


body:
I'm a beginner in Arduino world and I want to create a simple SD datalogger that works with GPS (module NEO-6M) and light sensor. I know there are a number of tutorials on GPS logging including:

 - [Create a GPS Data Logger Using The Arduino][1] (Bob Cravens)
 - [Geo Data Logger: Arduino+GPS+SD+Accelerometer][2] (Instructables)
 - [Making a SD card GPS logger with Arduino and MTK3329 GPS module][3] (Arduinodev)

but my problem is that those tutorials are either too complex (i.e. include extra stuff like displays) or they don't use [TinyGPS][4] or [TinyGPS++][5] library. In the first step I've managed to get GPS working and displaying the result on my laptop screen (via `Serial.print()`) using example code from [TinyGPS][6] library. In the next step I managed to use tutorial for [Adafruit Data Logger][7] to log data on SD card. The problem: light sensor logs ok, but for GPS it only logs a strings of 99.999999. Tried various tweaks but so far not sure what I got wrong. I use Arduino Uno, NEO-6M GPS, Catalex MicroSD Card Adapter, simple LDR. Here is my current code:

        #include <TinyGPS++.h>
        #include <SoftwareSerial.h>
        #include "SD.h"

        //input for the light detecting sensor (LDR)
        int LDR = A3;

        //inputs and triggers for GPS
        TinyGPSPlus gps;
        SoftwareSerial ss (7, 8); // TX=7, RX=8

        // digital pin 4 for the SD cs line
        const int chipSelect = 4;
        File logfile;// the logging file

        //data logger timing and other
        #define LOG_INTERVAL  1000 // mills between entries
        #define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
        uint32_t syncTime = 0; // time of last sync()
        #define ECHO_TO_SERIAL   1 // echo data to serial port
        #define WAIT_TO_START    0 // Wait for serial input in setup()

        void setup() {
          Serial.begin(9600);
          ss.begin(9600);
          Serial.println();

          #if WAIT_TO_START
            Serial.println("Type any character to start");
            while (!Serial.available());
          #endif //WAIT_TO_START

          // initialize the SD card
          Serial.print("Initializing SD card...");

          pinMode(10, OUTPUT);

          // see if the card is present and can be initialized:
          if (!SD.begin(chipSelect)) {
            Serial.println("Card failed, or not present");
            // don't do anything more:
            return;
          }
          Serial.println("card initialized.");

          // create a new file
          char filename[] = "LOGGER00.CSV";
          for (uint8_t i = 0; i < 100; i++) {
            filename[6] = i/10 + '0';
            filename[7] = i + '0';
            if (! SD.exists(filename)) {
              // only open a new file if it doesn't exist
              logfile = SD.open(filename, FILE_WRITE);
              break;  // leave the loop!
            }
          }

          Serial.print("Logging to: ");
          Serial.println(filename);

          logfile.println("date,time,lat,long,light");

          #if ECHO_TO_SERIAL
            Serial.println("lat,log,date,time,altitude,light");
          #endif// attempt to write out the header to the file
        }

    void loop(void) {

       // delay for the amount of time we want between readings
       delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));

       //here is GPS data (if I got it right)
       while (ss.available() > 0)
       gps.encode(ss.read());
       logfile.print(gps.date.value());
       logfile.print(", ");
       logfile.print(gps.time.value());
       logfile.print(", ");
       logfile.print(gps.location.lat(), 6);
       logfile.print(", ");
       logfile.print(gps.location.lng(), 6);
       logfile.print(", ");
       #if ECHO_TO_SERIAL
          Serial.print(gps.date.value());
          Serial.print(", ");
          Serial.print(gps.time.value());
          Serial.print(", ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(", ");
          Serial.print(gps.location.lng(), 6);
          Serial.print(", ");
       #endif

       //Read light intensity
       float lux = 500/(10.72/(5-(photocellReading * 0.00488759))*(photocellReading * 0.00488759));
       logfile.println(lux);
       #if ECHO_TO_SERIAL
          Serial.println(lux);
       #endif //ECHO_TO_SERIAL

       //write data to disk
       if ((millis() - syncTime) < SYNC_INTERVAL) return;
       syncTime = millis();
       logfile.flush();
    }

  [1]: http://bobcravens.com/2010/08/create-a-gps-data-logger-using-the-arduino/
  [2]: http://www.instructables.com/id/Geo-Data-Logger-ArduinoGPSSDAccelerometer-to-l/
  [3]: http://arduinodev.com/mtk3329-10hz-gps-module-with-arduino/
  [4]: http://arduiniana.org/libraries/tinygps/
  [5]: http://arduiniana.org/libraries/tinygpsplus/
  [6]: http://arduiniana.org/libraries/tinygps/
  [7]: https://learn.adafruit.com/adafruit-data-logger-shield?view=all

title: GPS logging on SD card using TinyGPS

Answers: 0


body:
In order to allow **bigger user program size**, is it possible and advisable to **reload Pro Mini** with the boot loader originally **designed for UNO**. This will save 1.5 KB flash space (UNO boot loader is 0.5KB, Pro Mini is 2KB).

Using a smaller boot loader is an 'intermediate' step to get more space while still enjoy the easy benefit of the Arduino IDE and many library/code example. Of course, ultimate step is to remove all boot loader (only small saving of 0.5KB if above is possible) and switch to ATmel development environment, ATmel studio, which is complex but programmer has full control of everything.

Did I miss anything in the followings?

I tend to believe that it is possible as

a) same ATMega328 chip is used in both board

b) Pro Mini is essentially cutting UNO into two halves, the MCU and the USB/Serial converter now use external USB to Serial converter

If the Pro Mini board is reloaded with UNO boot loader, how should the boards.txt file be edited to reflect the changes so that the IDE will handle it correctly?

Many thanks in advance

title: Is it advisable to reload Pro Mini with the bootloader originally designed for UNO to save 1.5 KB flash space?

Answers: 1

body:
You can just flash the newest [optiboot_atmega328-Mini.hex](https://raw.githubusercontent.com/arduino/Arduino/master/hardware/arduino/bootloaders/optiboot/optiboot_atmega328-Mini.hex). That one should also be only .5k in size, as it starts writing at the same address (`7E00`).

If you divide `7E00` by two you get `3F00` (This is because AVRs use 16-bit words for addressing while .hex files work with bytes (8-bit)). (I figured that one out, just now)

`3F00` is exactly the start of the `Boot Loader Flash Section` when you  have selected a 256-words `Boot Size` (page 291 of the [datasheet](http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf)). 256-words is the 0.5kb you want.

Just make sure you have the `BOOTSZ1`, `BOOTSZ0` fuses set to `1`

As for the `boards.txt`. I think you only need to change `mini328.upload.maximum_size=28672` to `mini328.upload.maximum_size=32256`.


body:
Some clients, let's say 5 <= x <= 10, have to send information wirelessly to a server. Transmission does not need to be reliable (ACK).

The range would be between 50 and 100m, and may include soft obstacles like trees, cars, etc, but not major ones like whole buildings or concrete walls.

Also, as I plan to build about 20 clients, the price should be as low as possible.

Thoughts?

title: Which wireless technology should I use for medium range, many to one, bidirectional communication?

Answers: 2

body:
RF433 modules are about as cheap as you get. You can get a tx/rx pair(separate modules) for 1-2 USD on ebay. Just search for "433mhz module". 100m or longer range should be possible with a proper antenna - a wire of the correct length. Use wavelength / 4, for 433MHz that is ~173mm.

The modules just communicate over a serial interface and they send the data straight to the air. But for better transmission the 1's and 0's need to be balanced and a "training preamble" before a data transmit balances the receiver for better noise immunity. Use a library such as [virtualwire](http://www.airspayce.com/mikem/arduino/VirtualWire/) to take care of data decoding/encoding.

The common cheap transmitters on ebay allow you to supply a higher voltage to the module for increased transmission power.

---

Alternatively if you want transmitter and receiver in the same module you could go for nrf24l01 based modules. I haven't yet used them myself but they are dirt cheap as well. They operate at 2.4Ghz using a proprietary protocol with retransmit etc built-in. The modules have way more pins than the cheap RF433 modules, but you can also find arduino libraries to interface with them. The cheap kind use an antenna etched straight on to the print board. According to [this article](http://hallard.me/nrf24l01-real-life-range-test/) the open air range is 50-80m depending in the data payload in a transmission.

body:
Depends on how much data you're sending, what packet structure you want to use, whether you want to spin your own PCBs or use a plug-in module, whether you need a low-power solution, etc..

For that distance, probably a sub-1GHz solution would work best.

I've had good results with the TI range of [Value Line transceivers][1] as they offload all the packet-handling, sync-words, CRC etc. from the microcontroller.  The modules also handle addressing, and have a "listen before talking" functionality - both of which could be useful with your physical architecture.

Down sides:

 - You'd probably need to spin your own PCB - they have good reference
   designs.
 - No library for Arduino... but I'd personally rather use a
   transceiver that manages all the low-level comms between the modules
   so I can focus on the application.

  [1]: http://www.ti.com/product/CC110L


body:
I am experiencing problems when I put parts of my code into custom functions and then have Arduino Mega 2560 run it. The code works fine when I put it all in the void loop() function, but when I create new functions then call those functions in the loop() function, it doesn't do what I want it to.

Here is the code where I put everything in the loop function

    /*
    Location.txt: Date/Time , Latitude (deg decimal), Longitude, Altitude (m)
    Speed.txt: Date/Time, Speed (m/s), Heading (deg)
    */

    #include<TinyGPS.h>
    #include<SD.h>
    #include<SPI.h>

    int CS = 53;

    long lat,lon;
    unsigned long time, date;
    int year,tinseconds;
    byte month, day, hour, minute, second, hundredths;
    unsigned long age;
    char dataString[20];
    TinyGPS GPS;

    struct GPSstruct {
      String dateTime;
      int timeseconds;
      float C_lat;
      float C_lon;
      float C_alt;
      float heading;
      float speedmps;
    };

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(38400);
      pinMode(CS, OUTPUT);
      if(!SD.begin(CS))
      {
        Serial.println(F("Card Failure"));
      }
    }

    void loop()
    {
    if(Serial1.available()){ // check for gps data
       if(GPS.encode(Serial1.read())){ // encode gps data
        GPS.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
        GPS.get_position(&lat,&lon); // get latitude and longitude in degree decimals multiplied by 10^5
        sprintf(dataString, "d/d/d d:d:d",month,day,year,hour,minute,second);
        tinseconds = second + minute*60 + hour*3600;
        float C_lat = ((float)lat)/1000000; //to get degree decimals
        float C_lon = ((float)lon)/1000000;
        float C_alt = GPS.f_altitude();
        float heading = GPS.f_course();
        float speedmps = GPS.f_speed_mps();
        GPSstruct A = {dataString,tinseconds,C_lat,C_lon,C_alt,heading,speedmps};

    //DEBUG
        Serial.println();
        Serial.print(F("Date/Time: "));Serial.println(dataString);
        Serial.print(F("Time (sec): "));Serial.println(tinseconds);
        Serial.print(F("Lat: "));Serial.println(C_lat,5);
        Serial.print(F("Lon: "));Serial.println(C_lon,5);
        Serial.print(F("Alt: "));Serial.println(C_alt);
        Serial.print(F("Heading: "));Serial.println(heading);
        Serial.print(F("Speed: "));Serial.println(speedmps);
    //END of DEBUG

    //add the code below makes alt = 1000000 for a long time then it fixes at some ?wierd? number
    //------//
      File dataFile = SD.open("Location.txt", FILE_WRITE); //Records date/time, lat, lon, alt
        if (dataFile)
        {
          dataFile.print(A.dateTime);dataFile.print(" , ");dataFile.print(A.C_lat,5);dataFile.print(" , ");dataFile.print(A.C_lon,5);dataFile.print(" , ");dataFile.println(A.C_alt);
          dataFile.close();
        }
        else
        {
           Serial.println(F("Location.txt cannot be opened!"));
        }

       File dataFile2 = SD.open("Speed.txt",FILE_WRITE); //Records date/time, speed, heading
       if (dataFile2)
       {
         dataFile2.print(A.dateTime);dataFile2.print(" , ");dataFile2.print(A.speedmps);dataFile2.print(" , ");dataFile2.println(A.heading);
         dataFile2.close();
       }
       else
       {
         Serial.println(F("Speed.txt cannot be opened!"));
       }
    //------//
       }
    }
    }

 Here is the code where I put them into two custom functions and call them in loop()

    #include<TinyGPS.h>
    #include<SD.h>
    #include<SPI.h>

    int CS = 53;
    long lat,lon;
    unsigned long time, date;
    int year,tinseconds;
    byte month, day, hour, minute, second, hundredths;
    unsigned long age;
    char dataString[20];
    TinyGPS GPS;

    struct GPSstruct {
      char dateTime[20];
      int timeseconds;
      float C_lat;
      float C_lon;
      float C_alt;
      float heading;
      float speedmps;
    };

    //Function Prototypes
    struct GPSstruct GPSdata(void);
    void SDlogger(struct GPSstruct);

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(38400);
      pinMode(CS, OUTPUT);
      SD.begin(CS);
    }

    //GPS data function:
    struct GPSstruct GPSdata(void) {
    static GPSstruct A;

     if(Serial1.available()){ // check for gps data
       if(GPS.encode(Serial1.read())){ // encode gps data
        GPS.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
        GPS.get_position(&lat,&lon); // get latitude and longitude in degree decimals multiplied by 10^5
        sprintf(dataString, "d/d/d d:d:d",month,day,year,hour,minute,second);
        tinseconds = second;
        float C_lat = ((float)lat)/1000000; //to get degree decimals
        float C_lon = ((float)lon)/1000000;
        float C_alt = GPS.f_altitude();
        float heading = GPS.f_course();
        float speedmps = GPS.f_speed_mps();
        strcpy(A.dateTime, dataString);
        A.C_lat = C_lat;
        A.C_lon = C_lon;
        A.C_alt = C_alt;
        A.heading = heading;
        A.speedmps = speedmps;

    //DEBUG
        Serial.print(F("Date/Time: "));Serial.println(dataString);
        Serial.print(F("Time (sec): "));Serial.println(tinseconds);
        Serial.print(F("Lat: "));Serial.println(C_lat);
        Serial.print(F("Lon: "));Serial.println(C_lon);
        Serial.print(F("Alt: "));Serial.println(C_alt);
        Serial.print(F("Heading: "));Serial.println(heading);
        Serial.print(F("Speed: "));Serial.println(speedmps);
        Serial.println();
    //END of DEBUG
      }
     }
     return A;
    }

    //SD data logging funct:
    void SDlogger(struct GPSstruct A)
    {
       File dataFile = SD.open("Location.txt", FILE_WRITE); //Records date/time, lat, lon, alt
        if (dataFile)
        {
          dataFile.print(A.dateTime);dataFile.print(" , ");dataFile.print(A.C_lat);dataFile.print(" , ");dataFile.print(A.C_lon);dataFile.print(" , ");dataFile.println(A.C_alt);
          dataFile.close();
        }
        else
        {
           Serial.println(F("Location.txt cannot be opened!"));
        }
       File dataFile2 = SD.open("Speed.txt",FILE_WRITE); //Records date/time, speed, heading
       if (dataFile2)
       {
         dataFile2.print(A.dateTime);dataFile2.print(" , ");dataFile2.print(A.speedmps);dataFile2.print(" , ");dataFile2.println(A.heading);
         dataFile2.close();
       }
       else
       {
         Serial.println(F("Speed.txt cannot be opened!"));
       }
    }
    void loop()
    {
      struct GPSstruct Gdata = GPSdata();
      SDlogger(Gdata);
    }

The one with all the code in the loop function prints all the serial.println commands and writes data into the micro SD card, but the one with custom functions DOESN'T print serial.println commands in GPSdata function and only prints that "Location.txt/Speed.txt cannot be opened!" and have writes 0 into the mirco SD card.

Why is this happening? Is it memory problems? (But the other one works fine)

The code here is meant to be a part of a bigger main code that uses these GPS data, so I would prefer it if I can keep the main script clean using custom functions.

Thank you.

title: Arduino Custom Function Problem

Answers: 1

body:
Admittedly, your code is somewhat hard to read without an actual editor (not your fault), but I think the issue is that in the first code (everything in one loop), the matching bracket from the initial if-statement (`if(Serial1.available()) {`) is located *after* the SD logging functions.

In the second code (decomposing the code), you have the SD logging done *outside* the if-statement. My guess is that `Serial1.available() = false` initially, so in the first piece of code, it skips everything else and loop until `Serial1.available() == true`. That probably doesn't take long, so you just see everything working. In the second code, you return `static GPSstruct A` (I'm not sure you want this to be static, but I could be wrong) which has been initialized but contains no useful data (it's uninitialized). The `void loop()` then takes that empty struct and passes it over to `SDlogger(struct GPSstruct)`. That function doesn't do any error-checking to make sure that `A` has useful information.

An easy workaround would be to add a field to the `GPSstruct` for whether or not it contains data. It's a simple `boolean` value. The code might look something like this:

    struct GPSstruct {
      boolean containsData;
      String dateTime;
      int timeseconds;
      float C_lat;
      float C_lon;
      float C_alt;
      float heading;
      float speedmps;
    };

    ...

    if(Serial1.available()){
      A.containsData = true;
      ...
    } else {
      A.containsData = false;
    }

    ...

    void SDlogger(struct GPSstruct A) {
      if(A.containsData) {
        ...
      } else {
        return;
      }

Also, as I was typing this, it got migrated...


body: Within the Arduino IDE Serial.* output can be viewed with Tools / Serial Monitor.  How can I view Serial.* output on an Android?  As a concrete example, how can I view the output from Examples / Communication / ASCIITable?

title: How do I view Serial Output on an Android Device?

Answers: 1

body:
These steps will allow your Android device to function as an Arduino Terminal.

- Download a Serial Terminal app.  I'm using [Android Hyperterminal, English version][1].
- Attach an OTG ("On The Go") cable to your Android device.
- Attach your Arduino to the OTG using your regular USB cable.
- Make sure the terminal program is set to the same baud rate as your sketch.
- Run the terminal App and select the USB port.

  [1]: https://play.google.com/store/apps/details?id=com.passiontech.support.en


body:
I'm using `avr-size` to see the size of library objects to free up some FLASH. Why are `Tone.cpp` and `IPAddress.cpp` getting built? e.g.

    $ cd /var/folders/3j/6wp3hvrj34n0xg3xzq6vjq380000gn/T/build8391693238079360471.tmp/
    localhost:build8391693238079360471.tmp
    $ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size *.o
       text    data     bss     dec     hex filename
          0       0       0       0       0 CDC.cpp.o
          0       0       0       0       0 HID.cpp.o
       1816       0     170    1986     7c2 HardwareSerial.cpp.o
        512       0       6     518     206 IPAddress.cpp.o
      10186     391     377   10954    2aca MainINOFile.cpp.o
       1872      14       0    1886     75e Print.cpp.o
       1414       1       0    1415     587 Stream.cpp.o
       1365       1      21    1387     56b Tone.cpp.o
          0       0       0       0       0 USBCore.cpp.o
        288       0       4     292     124 WInterrupts.c.o
        306       0       0     306     132 WMath.cpp.o
       4796       1       1    4798    12be WString.cpp.o
         30       0       0      30      1e main.cpp.o
        618       6       0     624     270 malloc.c.o
         56       0       0      56      38 new.cpp.o
        450       0       0     450     1c2 realloc.c.o
        588       0       9     597     255 wiring.c.o
        266       1       0     267     10b wiring_analog.c.o
        550       0       0     550     226 wiring_digital.c.o
        320       0       0     320     140 wiring_pulse.c.o
        260       0       0     260     104 wiring_shift.c.o
    $ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size */*.o
       text    data     bss     dec     hex filename
       2790       0       0    2790     ae6 DS3231/DS3231.cpp.o
         38       0       1      39      27 EEPROM/EEPROM.cpp.o
       1444       0       0    1444     5a4 LSM303/lsm303.cpp.o
        782       0       0     782     30e Messenger/Messenger.cpp.o
        116       0       1     117      75 SPI/SPI.cpp.o
        142       0       4     146      92 SdFat/MinimumSerial.cpp.o
       2568       0       0    2568     a08 SdFat/Sd2Card.cpp.o
      10644       0       4   10648    2998 SdFat/SdBaseFile.cpp.o
       1322       2       0    1324     52c SdFat/SdFat.cpp.o
        152       0       0     152      98 SdFat/SdFatUtil.cpp.o
        233       0       0     233      e9 SdFat/SdFile.cpp.o
        736       0       0     736     2e0 SdFat/SdStream.cpp.o
       2604       0     523    3127     c37 SdFat/SdVolume.cpp.o
       3395       0       0    3395     d43 SdFat/istream.cpp.o
       1635       0       0    1635     663 SdFat/ostream.cpp.o
        754       0      86     840     348 Wire/Wire.cpp.o
    $ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size *.elf
       text    data     bss     dec     hex filename
      29204     442    1279   30925    78cd MainINOFile.cpp.elf

title: Why are Tone.cpp and IPAddress.cpp getting built for my project?

Answers: 1

body:
As stated the IDE's equivalent to the make will compile anything everything it can find, in scope. But its linker has eliminate garbage enabled, hence anything not called or not static will not be linked into the EXE.

You can "avr-objdump -t" to create a map from your elf. And -d for an assembly listing. As to see exactly what is in the EXE, for your self. You need to enable show verbose output of compilation from the IDE's preferences, to display the temporary directory that contains the elf file.

example:

    C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp>C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -t MP3Shield_Library_Demo.cpp.elf > MP3Shield_Library_Demo_wo_mem.cpp.elf.map
    C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp>C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -d MP3Shield_Library_Demo.cpp.elf > MP3Shield_Library_Demo_wo_mem.cpp.elf.lst

I did the above and commented out a call to a function member of my library, between subsequent builds. To see that the code was not linked into the assembly.


body:
I got this 8-unit, 7-segment, 2-digit display board with 24 pins and I am wondering how I can interface with this from my Arduino Uno.

The board is labeled ROHM BP-006LH-GC and it has 8 units of the LB202VL LED display. Please see these photos of the board:

![Front of ROHM BP-006LH-GC board][1]

![Back of ROHM BP-006LH-GC board][2]

![Side of ROHM BP-006LH-GC board][3]

I found the datasheet for the LB202VL unit and I have been trying to make an independent unit on the board to work but I haven't been successful in setting its display.

The datasheet for the LB202VL unit can be found here: http://pdf.datasheetarchive.com/datasheetsmain/Datasheets-27/DSA-525461.pdf

Can anybody help me explain how I can work with this and set the display from my Arduino? After having attempted a few times I feel a little lost with this so any help would be greatly appreciated!

  [1]: https://i.stack.imgur.com/FcZRY.jpg
  [2]: https://i.stack.imgur.com/67bhk.jpg
  [3]: https://i.stack.imgur.com/vBymz.jpg

title: How to use ROHM LB202VL display (on BP-006LH-GC board) with Arduino?

Answers: 1

body:
I have a similar display, and I found the wiring by inspection and trial and error:

The display consist of 8 pairs of digits (LB-202VL, common cathode).

If contact points are numbered from 1 to 24 from left to right then
the common cathodes for the digits D1-D16 and the segments D.P. and 'a' - 'g' are noted below.
If you i.e. connect 1 to GND and 7 to + then segment 'c' of the first digit will be on. You have to multiplex the digits in order to use it.

1. D1
2. D2
3. D3
4. D4
5. D.P.
6. D5
7. c
8. D6
9. e
10. D7
11. a
12. D8
13. g
14. D9
15. d
16. D10
17. f
18. D11
19. b
20. D12
21. D13
22. D14
23. D15
24. D16


body: Is it possible to set the Arduino Yun up as an ssh client? If so, how?

title: Arduino yun as ssh client

Answers: 1

body:
You need to install package `openssh-client`: it's available in the [package list][1]. See [this tutorial][2] about how to install optional packages.

You can call `ssh` on the Linux side using `Process` from the `Bridge` Arduino library.
Best is when you execute single or grouped commands using a syntax as:

    ssh user@your_other_host 'echo 1; echo 2'

Managing an open ssh session is possible but I think may be troublesome, so avoid it if you can.

  [1]: http://downloads.arduino.cc/openwrtyun/1/packages/index.html
  [2]: http://arduino.cc/en/Tutorial/YunPackageManager


body:
I have an ArbotiX-m Arduino board, and have followed the [setup guide](http://learn.trossenrobotics.com/arbotix/7-arbotix-quick-start-guide) on Trossen robotics all the way to the 5th step. I have a Mac running OS X 10.10 and use Arduino 1.0.5. I installed the necessary drivers and copied the files to the Sketchbook directory. When I try to load the sample ArbotiXBlink program:

    // Pin 0 maps to the USER LED on the ArbotiX Robocontroller.
    int led = 0;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
    }

It verifies just fine, but when I click upload, I get:

    Binary sketch size: 1,088 bytes (of a 65,536 byte maximum)
    avrdude: stk500_recv(): programmer is not responding
Any ideas?

**EDIT:** The board was trying to get power from the 5V instead of USB

title: ArbotiX-M Problem uploading to the board

Answers: 1

body: I figured why my board wasn't responding! Apparently, the power pin was connected to the 5V supply instead of usb. Silly me!


body:
When I remove the SD card and try to open a file, I can detect the error properly.

But how do I detect that the card has been replaced after an error? My first thought was to call `SD.begin()` again but it appears that this function returns true exactly once and false thereafter.

Simplified example:

    void setup() {
      SD.begin(pin); // called exactly once. Works.
    }
    void loop() {
      // stuff
    }

But this does not:

    void setup() {
      SD.begin(pin); // first time calling this function: works.
    }
    void loop() {
      delay(1000);
      SD.begin(pin); // always fails
    }

I'd rather not reset the microcontroller just for this.

title: SD.begin() fails second time

Answers: 2

body:
# Update
A **software reset**, while inelegant, was much simpler to implement and debug than trying to add "retry" type functionality to `SD.h`. The other alternative would be to access `SDFatLib.h` or the other lower-level stuff (which `SD.h` is a wrapper for) directly, so if someone has that solution, I'll accept it instead of this one.

# Original
Here is something, which <s>is working well enough for me at the moment:</s> does not reliably work:

    bool SDState{false};
    File LogFile;

    bool trySDCard(void)
    {
        // sanity check: maybe the SD card is actually here?
        LogFile = SD.open("test.txt", FILE_WRITE);
        delay(10);
        if (LogFile) {
            LogFile.close();
            return true;
        }
        int8_t counter{10};
        while (counter && !SDState) {
            SDState = SD.begin(TFT_CARD_CS);
            Serial.print(counter);
            Serial.print(" ");
            counter--;
            delay(100);
        }
        Serial.print("SD: ");
        Serial.println(SDState);
        return SDState;
    }

    void setup() {
        SDState = SD.begin(TFT_CARD_CS);
        Serial.begin(115200);
    }

    void loop() {
        // NB. Simplified a lot (exitMenuMessage(string) is my custom function defined elsewhere)
        switch (state) {
            case SD_RETRY:
                exitMenuMessage(trySDCard() ? "found SD card" : "no SD card");
                break;
        }
    }

<s>Seems to work</s> Sometimes works if I insert the SD card *while* `trySDCard()` is running.

body: I know this question is relatively old but still, if you wnat to run  `SD.begin(chipselect);` again first call `if(root.isOpen()) root.close();` I added this to the library. This way `SD.begin(chipselect)` will return `true` if a card is present and `false` when it's not.


body:
I am making a "Electronic Dice".

I have 7 LEDs to form the output, and this works fine.

My problem is getting a random result on the output.

    int die_face = 1;

    void loop()
    {
        if (analogRead(BUTTON_PIN) == HIGH)
        {
            paintDieFace((die_face % 6) + 1);
        }

        die_face += 1;
    }

The problem is, that roughly 95% of the time I get a 1.
Most of the time it's not a 1, it's a 2, or very rarely a 3.

I've tried paintDieFace() with millis()%6+1 too, but always get the same result.
When it's painted with random(1,7); I get 1, 2 or 3 100% of the time.

Is this some sort of timing issue?  I just don't get it.

Just to clarify - The paintDieFace() function is working perfectly, I'm logging the result to serial too.

title: Getting a random number for electronic dice

Answers: 2

body:
I've had better success with this version.

I did not work out the problem with the first version.  Although I did find the rear legs of the push-button were lighting up a LED - but only when pushed.  As the result is only displayed when the button is not pushed, I don't see how it could make a difference.

I believe the modulus of 6 is a problem, perhaps this does really output more ones than anything else.  Obviously looping the dice_number variable 1->6 removes the necessity for it.

    #define LEDS_34_PIN 2  // Output pins used
    #define LEDS_16_PIN 3
    #define LEDS_25_PIN 4
    #define LED_7_PIN   5

    #define BUTTON_PIN  6  // Input

    unsigned char dice_number  = 0;     // this is what will be shown on the die face

    void setup()
    {
        // Tell the Arduino we're writing to some pins
        pinMode(LEDS_34_PIN, OUTPUT);
        pinMode(LEDS_16_PIN, OUTPUT);
        pinMode(LEDS_25_PIN, OUTPUT);
        pinMode(LED_7_PIN,   OUTPUT);

        // ... and reading a button
        pinMode(BUTTON_PIN, INPUT);

        // Do a testing-dance first
        for (int i=1; i<=6; i++)
        {
            paintDieFace(i);
            delay(500);
        }
        paintDieFace(0);

    }

    // Show a dice-dot-style number
    // based on LEDs laid out like
    //    [1]     [4]
    //    [2] [7] [5]
    //    [3]     [6]
    void paintDieFace(unsigned char number)
    {
        // Turn off all LEDs
        digitalWrite(LEDS_34_PIN, LOW);
        digitalWrite(LEDS_16_PIN, LOW);
        digitalWrite(LEDS_25_PIN, LOW);
        digitalWrite(LED_7_PIN,   LOW);

        if (number == 1 || number == 3 || number == 5 || number > 6)
        {
            digitalWrite(LED_7_PIN, HIGH);
        }
        if (number >= 2)
        {
            // LEDs 3 & 4 are on for all numbers greater-than 1
            digitalWrite(LEDS_34_PIN, HIGH);
        }
        if (number >= 4)
        {
            // LEDs 1 & 6 are on for 4, 5 and 6
            digitalWrite(LEDS_16_PIN, HIGH);
        }
        if (number >= 6)
        {
            // LEDs 2 & 5 are only on for 6 (or more)
            digitalWrite(LEDS_25_PIN, HIGH);
        }
    }

    void loop()
    {
        int button_pushed = digitalRead(BUTTON_PIN);
        if (button_pushed == HIGH)
        {
            // The user has pushed the button, change the die reading
            paintDieFace(dice_number);
            delay(20);  // flicker the LEDs if button held in
        }

        dice_number += 1;
        if (dice_number == 7)
            dice_number = 1;
    }

body:
First of all, look at this line of code:

    if (analogRead(BUTTON_PIN) == HIGH)

You probably want to use *`digitalRead()`*. Note that it is okay to use digitalRead() on an analog pin, just make sure to use the right pin number (`A0`, etc.)

From the [Arduino Source](https://github.com/arduino/Arduino/blob/3a8ad75bcef5932cfc81c4746a87ddbdbd7e6402/hardware/arduino/cores/robot/Arduino.h):

    #define HIGH 0x1
    #define LOW  0x0

*(Ignore the `0x`, that is just specifying that it's hexadecimal. However, 0 and 1 are the same in any base)*

So, really, this function is only activated when `analogRead()` returns 1, which could possibly cause a problem later if it doesn't check at the right time. **Note:** now is a good time to remind you about debouncing...

For your actual code, since you want it to be simple, I suggest you forget that code that you wrote. [Arduino has a built in random library](http://arduino.cc/en/reference/random), which works unless you have some special need for a random number.

Your final code should look like something like this in the end:

    void loop() {
        if (analogRead(BUTTON_PIN) == HIGH) {
            paintDieFace(random(1, 6);
        }
    }

Note that you should also use this code here in your setup (make sure that analog pin is floating: nothing should be attached to it):

    randomSeed(analogRead(A1));

It actually isn't random, just *pseudo-random*. That means it relies on an equation to generate what seem to be random numbers. Because there has to be a default value of where the equation starts (the *seed*), it will repeat the same numbers *every time* you run it.

If you're wondering how this works, know that the analog pin is affected by a ton of external factors when there is no other electric signal attached.


body:
In context of getting the MCU on Pro Mini and ATMega2560 (chip is ATmega328 and ATMega 2560) to **sleep and power down modes,** so as to run on **one set of battery for months**, appreciate idea and comment.

Initially, I looked at web postings and get the following general idea. Did I miss anything?

Is sleep mode done via ATMel factory library, Arduino-level user contributed library, or the Arduino IDE? Many web posting are along the line of getting it partially working but only at half expected current reduction, etc. That is, current do reduced, but, not enough.

Are there several such library?

How are they?

Which one is better support and more functions? (no need for easy to use, can do registers programming, when needed)

Many thanks in advance

title: Sleep mode and months of operation on small battery

Answers: 3

body:
Have a read through the Jeelabs blog which documents the author's very successful attempt at making a very low power wireless sensor node that can run for months off coin cells.

http://jeelabs.org

There is also a library based on this project called Jeelib:

http://jeelabs.net/pub/docs/jeelib/

Jeelib contains a class called `Sleepy` that allows for easy sleeping.

Rocketscream did a thorough test of the current consumptions with the different modes here:

http://www.rocketscream.com/blog/2011/07/04/lightweight-low-power-arduino-library/

According to them, you can get the ATMega328P down to 1.7uA.

Unless you do something about the power supply on a normal Arduino board you won't be able to extend the battery life by much at all. See my answer here for some more details:

https://arduino.stackexchange.com/questions/3688/arduino-powering-from-9v-battery/3689#3689

body:
I could reproduce these power requirements - main thing is to get rid of the Arduino board and start with a Bareduino or sth similar. (find a detailed description [here][1])

  [1]: https://holadimake.wordpress.com/2015/01/02/building-a-cellular-tracker-part3-running-on-batteries-for-months/

body:
* I have a page about saving power with the Atmega328P chips (similar techniques apply to other chips): [Power saving techniques for microprocessors](http://www.gammon.com.au/power)

* I made a [Temperature and humidity sensor - battery powered](http://www.gammon.com.au/forum/?id=12106) - this runs from 3 x AA batteries, and writes to an SD card. From memory it ran for 2 years before I needed to replace the batteries.

* Another project flashes an LED every second: [Simple project - torch-locator](http://www.gammon.com.au/forum/?id=12769). I made something similar a couple of years ago that is still running from the same button battery.

As a rule-of-thumb, you should be able to achieve 100 nA of current consumption, and still be "alive" and able to respond to external events, like button-presses (eg. a calculator or TV remote). To wake periodically (without an external event) takes more current, because you need the watch-dog timer to be active, but that can still be as low as 6 µA.


body:
In context of Pro Mini and ATMega2560

Fuses, as documented in chip factory doc are complex topics (I have not really used it before), appreciate pointers and advises, to narrow down those that are **needed for contexted task** and left un-needed in their default modes.

Which fuses are used within context of the IDE in **general**, and in specific of software **loading** via bootloader and ISP?

Which fuses related to sleep and power down modes, in context that individual chip modules can be set to various power-saving modes via registers. Does fuses play a part in getting the power-saving effect?

Many thanks in advance

title: MCU fuses used by Pro Mini and ATMega 2560 and power down

Answers: 1

body:
The data sheets are the ultimate source. However, that may be a bit overwhelming. I find the below great resources very helpful.

1) [Online Fuse Calculator](http://www.engbedded.com/fusecalc/) There are many others.

2) [avrdude-GUI](http://translate.google.com/translate?hl=en&sl=ja&u=http://yuki-lab.jp/hw/avrdude-GUI/&prev=/search?q=avrdude-GUI+yuki-lab.jp&client=firefox-a&hs=rmn&rls=org.mozilla:en-US:official&channel=sb&biw=1160&bih=724)
there are many others out there.

3) the .\arduino-1.5.7\hardware\arduino\avr\boards.txt

    uno.bootloader.low_fuses=0xFF
    uno.bootloader.high_fuses=0xDE
    uno.bootloader.extended_fuses=0x05

4) I also read the fuses from any device before I stomp over them. And check into what each mean.

As for narrowing down the features the Online Calculator very helpful to start with and then read into the data sheet for ones of interest.

For the most part there have several questions and answers for low power modes, using interrupts to re-awake. Where there appears to no direct fuses to save power, outside of clock source and speed. Arguably Brown Out detect is a fuse, but that is not directly related to saving power.


body:
To make LCD display, Pro Mini and ATMega2560 to run on one set of battery for months, appreciate idea and comment.

Which LCD to use?

Which LCD chip controller chip (hide inside the LCD) has better power saving mode?

Which library with functions of power saving and also can put out **VERY beautiful** per-programmed display, like multiple fonts, different fonts size, some graphics like circle, rectangles, color fills, gradual-color-changing background with text and graphic at 'foreground' (as in PC power point style)?

Under context of

 1. Small Mono chrome 2 lines text display
 2. 3 inches mono chrome graphic 128 x 64 or similar
 3. 3 inches color graphic, 320 x240 or similar

Many thanks in advance

title: LCD display under power saving mode

Answers: 1

body:
Use an eInk/ePaper style display, which uses no power while the display is not changing.  These come in monochrome greyscale, and have excellent readability.

This solves only part of your problem as you still need to power the CPU.


body: Where is a simple program that demonstrates unidirectional data transmission over a pair of nRF24L01+ radios?  It should have adequate output so that a beginner can determine that the transmission is working properly.

title: "Hello World" program for nRF24L01+?

Answers: 3

body:
Here are several "getting started" articles that contain simple programs.

http://tmrh20.github.io/RF24

https://groups.google.com/forum/#!topic/nrf24-arduino/VaC2U5D1o_s

http://arduino-for-beginners.blogspot.com/2013/02/setup-nordic-nrf24l01-rf-modules-to.html

body:
TMRh20 RF24 library examples work well.

Install TMRh20 RF24 library in the Arduino IDE Library Manager (“Sketch/Include Library/Manage Libraries...” and search for “RF24”). Then open the Getting Started example (“File/Examples/RF24/GettingStarted”).

You’ll need to change the “radioNumber” variable to `0` or `1` on the sending and receiving Arduino (line 13 of the code).

For the hardware I prefer to use pins 9 and 10 instead of 7 and 8 (line 16 of the code), so that all pins are connected to port B.

The nRF24 is supposed to be 5V tolerant on the data lines, but not for the power supply, so you need to connect VCC to 3.3 V. In my experience, it works best if you use it with a full 3.3 V board (ESP8266 or Arduino Pro Mini).

You absolutely need to add a strong capacitor between VCC and ground. I use a 2200 µF capacitor, but 10 µF may be enough (http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo).

[I also wrote a small article about the nRF24L01+.](https://translate.google.com/translate?sl=fr&tl=en&js=y&prev=_t&hl=fr&ie=UTF-8&u=http://ouilogique.com/tests_nRF24L01+/&edit-text=)

body:
I found this site to have pretty strait forward instructions:

https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/

Main Library: https://github.com/maniacbug/RF24/

Example Sketch: https://github.com/maniacbug/RF24/blob/master/examples/pingpair/pingpair.pde


body:
I have an Arduino Mega 2560  with a GPRS seeedstudio shield and an USB Host CircuitsAtHome shield which work fine when powered with USB or with an adjustable voltage regulator set at 8V.

When I set this voltage regulator at 7V (minimum voltage from the spec to get the better efficiency) I am still reading 5V and 3.3V on the pins of the Arduino and all the leds of the Arduino and the GPRS shield seems fine but the USB Host CircuitsAtHome shield seems to not work properly.
I cannot debug it using the console because if I plug the USB cable, everything works fine...

Why 7V fail while 8V is ok?

The adjustable voltage regulator can provide up to 5A which is plenty.

title: Mega 2560 powered with 7V don't work correctly

Answers: 2

body:
The Voltage-Regulator has a dropout-voltage of 1,2V, but in line to the regulator is a diode, which adds another minimum 0,7V (dont know the exact part number, so i guessed the voltage of a Si-diode at ~1A). So you have to supply at least 5 + 1,2 + 0,7 = 6,9V. I presume the circuit doesnt draw a constant current all the time, so from time to time the regulator cant supply the 5V because you sink under the necessary dropout-voltage of the rehulator/diode-combination.

-> Use 8V  or bypass the Diode D1 (with a solder-bridge) and use 7V if its a must and you are sure the input-polarity is always correct.

Arduino-Mega-2560-schematic: http://arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf

body:
You need to be clear about how you are hooking this up. Are you feeding 7V into the Vin on the Arduino? If so, then the voltage regulator on the Arduino is attempting to regulate 7V down to 5V. As Echo says, 7V isn't quite enough for the built-in voltage regulator.

If your voltage regulator outputs clean, noise and ripple free regulated voltage, you could set it to 5.0 volts and feed it directly into the Arduino's 5V line, bypassing the regulator on the Arduino completely. If you do this you need to make absolutely sure that you give it exactly +5V though, as you will likely destroy the board if you go much over 5V or wire it backwards.

If it's a switching regulator then you might need to add a choke to the output of the regulator to get rid of high frequency noise on its output.


body:
Im using a variant of Arduino Due embedded on a ARM (Udoo). And I have connected a Medlab SPO2 Pearl 200 sensor to Serial1.

Im just trying to parse input from Serial1 to Serial, in a human-readable format (Hexadecimal).

The protocol is described in this image:
![Protocol SPo2][1]

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

And using this Arduino code I reveice two times the "no finger detected line"

    int lineLength = 16;
    int spo2read[16];
    int readed = 0;
     if (Serial1.available()) {
        int inByte = Serial1.read();
        if (readed < lineLength) {
          spo2read[readed] = inByte;
        }
        readed++;
        if (readed == lineLength) {
          Serial.print("SPO2: ");
          for (int i = 0; i <= lineLength; i++) {
            Serial.print(spo2read[i], HEX);
            Serial.print( delimeter);
          }
          Serial.println("");

          readed = 0;
        }

      }

Output with no finger is:

    SPO2: A,FB,2,F9,0,FA,0,FC,A,FB,2,F9,0,FA,0,FC,0,

Buf if I put my finger, all is messed up:

    SPO2: 7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,
    SPO2: 36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,
    SPO2: 24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,
    SPO2: 35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,
    SPO2: 5E,60,61,F9,0,FA,0,FC,1A,FB,0,F8,62,62,62,63,0,

Sensor doesn't sends a \n or \r so I don't know exactly how to parse the data

title: Parse data from sensor without delimeters

Answers: 2

body:
actually I don't think it is all mixed up

as per geometrikal use the markers to parse the data stream

I believe your above sample data started mid-stream during the 0xF8 of the wave form.

    F8,...
    ...,7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,5E,60,61
    F9,0
    FA,0
    FC,1A
    FB,0
    F8,62,62,62,63,0,...

I believe reading this as a finite length does not portray the data for easy interpetation. Given that 0xF8 is a variable length protocol.

Where the reparse of your data initially appears to be legitimate parse.

That said I do read the SPO2, Pulse as zero. Where it may be likely the sensor has not finished its reading and auto gain cycles.

body:
I have used the source code available on the Medlab web, and do some "modifications" to be Arduino compatible.
I dont wanna the waveform data, because my final program will do the waveforms acording the data received, so I don't "listen" to the waveform packet

    boolean startbyte = false;
    byte buf = 0;

      while (Serial1.available() > 3)
      {
        buf = Serial1.read();
        if (buf > 0xfc)
        {
          buf = Serial1.read();
        }

        if ((startbyte == true) && buf > 0xF7)
        {
          startbyte = false;
        }

        if (buf > 0xf7 && startbyte == false)
        {
          //startbyte = true;
          if (buf == 0xf8)
          {
            startbyte = true;
          }

          if (buf > 0xf8)
          {
            byte RX = buf;
            buf = Serial1.read();
            if (buf > 0xfc)
            {
              buf = Serial1.read();
            }

            if (RX == 0xf9)
            {
              //SPO = buf;
              Serial.print("SV:");
              Serial.print(buf, DEC);
              Serial.println();
            }

            else if (RX == 0xfa)
            {
              //Pulse = buf;
              Serial.print("SPV:");
              Serial.print(buf, DEC);
              Serial.println();
            }
            else if (RX == 0xfb)
            {
              //Status = buf;
              Serial.print("StV:");
              Serial.print(buf, DEC);
              Serial.println();
            }

            else if (RX == 0xfc)
            {
              //quality = buf;
              Serial.print("QV:");
              Serial.print(buf, DEC);
              Serial.println();
              Serial.println();
            }
            else { }
          }

        }
        else if (startbyte == true)
        {
         //Waveform data
        }
      }


body:
I'm trying to datalog to a EyeFi SD card by writing to a file with a jpg extension. Here's that portion of my code so far:

    // see if the directory exists, create it if not.
    if( !SD.exists("/DCIM/100NIKON") )
    {
      if( SD.mkdir("/DCIM/100NIKON") )
      {
        Serial.print("File directory created: ");
      }
      else {
        error("File directory not created");
      }
    }
    else
    {
      Serial.print("File directory exists: ");
    }

    // Test file
    char filename[] = "DSCN0000.JPG";

    if (! SD.exists(filename))
    {
      logfile = SD.open(filename, FILE_WRITE); // only open a new file if it doesn't exist
    }

    if (! logfile)
    {
      error("Couldnt create file");
    }

The Arduino creates the directory, but the file is still saved to the root.  I would love some help or tips on this.

title: How do I specify a working directory when saving to SD card?

Answers: 1

body:
You're creating a directory, and then *not writing the file into it*.

You need to change the filename to `/DCIM/100NIKON/DSCN0000.JPG";`

Note that `SD.open()` takes the **full filepath to the file**, not just the file*name*.

From the [Arduino Docs](http://arduino.cc/en/Reference/SD):

> The file names passed to the SD library functions can include paths
> separated by forward-slashes, /, e.g. "directory/filename.txt".
> Because the **working directory is always the root of the SD card**, a
> name refers to the same file whether or not it includes a leading
> slash (e.g. "/file.txt" is equivalent to "file.txt"). As of version
> 1.0, the library supports opening multiple files.

(emphasis mine)


body:
I have an Arduino sketch with a timer interrupt class and would like to place the TIMER2Services() function in the TimerTwoTest.ino file for easy access. On compile I get a multiple definition of tmb2 error in the .ino TIMER2Services() function. I have tried all the variations I can think of but no luck. Is there a way to do this?

    TimerTwoTest.cpp.o: In function `TIMER2Services()':
    D:\Arduino157/TimerTwoTest.ino:41: multiple definition of `tmb2'
    TimerTwo.cpp.o:C:\Users\...\build8577138580185682113.tmp/TimerTwo.cpp:10: first defined here

collect2.exe:

**TimerTwo.h:**

    class Tmb2
    {
      public:
      void initTIMER2(unsigned int Hz, unsigned int ulPeriod);
      void resetTIMER2(unsigned int Hz, unsigned int ulPeriod);
      TIMER2_TYPE getPeriodTIMER2(void);
      void activeTIMER2 (void);
      private:
    }tmb2;

**TimerTwo.cpp:**

    extern void TIMER2Services(void);

    [this function is line 10 for the error]
    void Tmb2::initTIMER2(unsigned int Hz, unsigned int ulPeriod){  //setperiod and enable interrupt
      if (Hz){
        ulPeriod = 1000/Hz;    //if Hz > 0 use frequency microseconds
      }
      Timer2.attachInterrupt(TIMER2Services).setPeriod(ulPeriod).start();
    }

**TimerTwoTest.ino:**

    volatile unsigned long burpCount = 0;

    //This routine services the interrupt
    void TIMER2Services(void){
      burpCount++;
    }

title: Calling a function that is outside of a class from inside

Answers: 1

body:
The problem is your definition of tmb2.  You're declaring the variable in the header file, and not the C(++) file.

Please try this:

**TimerTwo.h**

    #ifndef __TIMER_TWO_H__
    #define __TIMER_TWO_H__

    extern void TIMER2Services(void);

    class Tmb2
    {
        public:
            void initTIMER2(unsigned int Hz, unsigned int ulPeriod);
            void resetTIMER2(unsigned int Hz, unsigned int ulPeriod);
            TIMER2_TYPE getPeriodTIMER2(void);
            void activeTIMER2 (void);
        private:
    };

    #endif // #ifndef __TIMER_TWO_H__

The #ifndef TIMER stuff saves you getting multiple definitions from header files if they're included more than once.  There's other ways to do this, but this is simple and well-known.

**TimerTwo.cpp**

    #include "TimerTwo.h"

    void Tmb2::initTIMER2(unsigned int Hz, unsigned int ulPeriod)
    {
        //setperiod and enable interrupt
        if (Hz)
        {
            ulPeriod = 1000/Hz;    //if Hz > 0 use frequency microseconds
        }
        Timer2.attachInterrupt(TIMER2Services).setPeriod(ulPeriod).start();
    }

**TimerTwoTest.ino**

    #include "TimerTwo.h"

    Tmb2 tmb2;
    volatile unsigned long burpCount = 0;

    // This routine services the interrupt
    void TIMER2Services(void)
    {
        burpCount++;
    }

    void setup()
    {
        tmb2.initTIMER2(blah1,blah2);
    }

For the sake of neatness, I'd move TIMER2Services into class Tmb2 as a static function... if possible.


body:
I'm using my Arduino Leonardo as a Mouse but I'm experimenting a strange behaviour.
I put my mouse at (-1, -1) (absolute) coordinates and then I execute this code:

    Move.move(com[curr_cmd_id].x, com[curr_cmd_id].y, 0);

where that point is (334, 180) (relative coords) (and I checked it through Serial console)

Now, the pointer is actually moving to the right but then it stops. Let's say it reaches the point (334, 0).

Then I tried:

    Mouse.move(com[curr_cmd_id].x, 0, 0);
    delay(500);
    Mouse.move(0, com[curr_cmd_id].y, 0);

but still the same behaviour.

Then finally I tried this one (which it actually solves my problem but it's a dirty solution):

    int i;
    for(i=0; i<com[curr_cmd_id].x; i++){
      Mouse.move(1,0,0);
      delay(1);
    }
    for(i=0; i<com[curr_cmd_id].y; i++){
      Mouse.move(0,1,0);
      delay(1);
    }

Could anybody help me in understanding what's going on here? How can I achieve a simple and direct relative movement for my pointer?
Thanks you in advance!!

title: Wrong Mouse.move() output in Arduino Leonardo

Answers: 1

body:
I struggled with this too until I realized this

> Parameters
>
> xVal: amount to move along the x-axis - signed char
>
> yVal: amount to move along the y-axis - signed char
>
> wheel: amount to move scroll wheel - signed char

Note it says signed char.

That means the value you pass to the Mouse.move is a signed 8-bit. (-128 to 127)

My work around is this below:

    void moveMouse(int x, int y, int w){
      x = (int)x / 1.59; //Adjust these two values accordingly. I found out that 100, 100 does
      y = (int)y / 1.58; //not move 100, 100. It moves 159, 158 for me.

      while(x!=0 || y!=0 || w!=0){
        int moveX, moveY, moveW;
        if(x > 0){
          if(x >= 100){
            moveX = 100;
          }else{
            moveX = x;
          }
        }else if (x < 0){
          if(x <= -100){
            moveX = -100;
          }else{
            moveX = x;
          }
        }else{
          moveX = 0;
        }

        if(y > 0){
          if(y >= 100){
            moveY = 100;
          }else{
            moveY = y;
          }
        }else if (y < 0){
          if(y <= -100){
            moveY = -100;
          }else{
            moveY = y;
          }
        }else{
          moveY = 0;
        }

        if(w > 0){
          if(w >= 127){
            moveW = 127;
          }else{
            moveW = w;
          }
        }else if (w < 0){
          if(w <= -128){
            moveW = -128;
          }else{
            moveW = w;
          }
        }else{
          moveW = 0;
        }

        x = x - moveX;
        y = y - moveY;
        w = w - moveW;

        Mouse.move(moveX, moveY, moveW);
      }