title: Adafruit CC3000 Wifi Shield on IRQ 2?

text:
# Question
Title: Adafruit CC3000 Wifi Shield on IRQ 2?
I'm using an AdaFruit CC3000 Wifi shield as an HTTP server with an Arduino Uno.

I have a script which works fine -- logs into my Wifi and listens for connections as it should.

However, I want to use an infrared library which writes to the CC33000 default IRQ 3, so to avoid conflict I change the following setting:

```
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!

```

to the only other Interrupt pin

```
#define ADAFRUIT_CC3000_IRQ   2  // MUST be an interrupt pin!

```

The device hangs at "Initializing" .. or at least I see neither of the subsequent lines in the following code on my serial monitor:

```
Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

```

I've stripped everything back down to just the example code for HTTPServer to ensure it's not a conflict with my own code or the IR Library. I've changed the setting from 2 to 0 and 1 thinking there was some confusion over literal IRQs vs Pins, but those settings generate the "Couldn't begin" error trap.

Is there any other setting that I need to vary in order to get the CC3000 to opearate on IRQ 2 or is this a hardware bug and I'm out of luck if I want to use Pin 3?

# Answer
> 1 votes
It is a "hardware bug" as you so aptly put it. As far as I know, the only way to get the CC3000 board to use pin 2 as the IRQ is to physically rewire the connections. I did exactly that on my board and it works without a problem, leaving pin 3 free to use for whatever else you want. You can see what I did **here**. It basically involves cutting the trace wire and running a jumper cable between the holes next to the pins.

The important thing to understand perhaps is that pins 2 and 3 are available to use for IRQ on the Mega and Uno, but it is an actual dedicated pin on the CC3000, hence why you have to go to this effort to change it. Also remember that once you have cut the trace to pin 3 it becomes an open/free pin and is no longer connected to the wifi shield. By the sounds of your requirements this shouldn't matter, but it is still useful to know.

If you haven't already, I recommend that you read the documentation for the CC3000 board, as it really helped me understand the irritating intricacies.

But yeah, if you choose to follow this and reroute the pin, it works perfectly. Hope this helps, even if it is a bit late.

---
Tags: arduino-uno, interrupt, adafruit
---


title: Arduino SoftwareServo by example

text:
# Question
Title: Arduino SoftwareServo by example
I am interested in writing a simple Arduino program that will turn a servo back and forth (180 degrees each time) continuously.

I am looking at these servos and am planning on following this example.

Being so new to Arduino, I first wanted to confirm that the `SoftwareServo` library in that example will drive those particular servos. If it will not, then can someone begin by explaining to me *why* these servos are incompatible with the lib?

Assuming they are compatible, I am looking at the main example on that page (comments stripped out for brevity):

```
#include <SoftwareServo.h>

SoftwareServo myservo;

int potpin = 0;
int val;

void setup() {
    myservo.attach(2);
}

void loop() {
    val = analogRead(potpin);
    val = map(val, 0, 1023, 0, 179);
    myservo.write(val);
    delay(15);

    SoftwareServo::refresh();
}

```

My concerns:

* There seem to be 3 pins involved here: a potentiometer pin (`0`), an analog pin (`val`) and a servo pin (`2`). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?
* Is there anything "wrong" with defining `myservo.attach(2);` up *above* the `setup` function, and leave the `setup` function an empty no-op function?
* Where does the `map(...)` function come from? If it was defined inside `SoftwareServo` I would have expected its usage to be something like `SoftwareServo::map(...)`, etc.
* Why do we need the `delay` after calling `myservo.write(val);`? What would happen if this delay wasn't in there?
* According to that link, calling `SoftwareServo::refresh()` once every 50ms is necessary in order to: "*keep your servos updating.*" **But what does this mean, really?** Updating to what?!?

# Answer
> 1 votes
> There seem to be 3 pins involved here: a potentiometer pin (0), an analog pin (val) and a servo pin (2). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?

No, there is only 2 pins. The value of the potentiometer attached to pin 0 is read and stored in the variable `val`. That is then used to set the angle of the servo motor on pin 2.

> Is there anything "wrong" with defining myservo.attach(2); up above the setup function, and leave the setup function an empty no-op function?

Yes. It'll never get called. `setup()` is the first function to be called and its purpose is to perform any initialization routines, such as attaching the servo code to the pin the servo is connected to. So you *have* to call that either from `setup()` or from a function which `setup()` itself calls.

> Where does the map(...) function come from? If it was defined inside SoftwareServo I would have expected its usage to be something like SoftwareServo::map(...), etc.

`map()` is part of the standard Arduino API. http://www.arduino.cc/en/Reference/Map

> Why do we need the delay after calling myservo.write(val);? What would happen if this delay wasn't in there?

You don't need the `delay()` call, but you don't want to set the value of the servo too rapidly. You really want to allow at least one PWM cycle between each call to ensure the values have been set properly.

> According to that link, calling SoftwareServo::refresh() once every 50ms is necessary in order to: "keep your servos updating." But what does this mean, really? Updating to what?!?

SoftwareServo is just what it says - a piece of software. You have to run that software for it to work, and the `refresh()` function is that bit that you run. If you don't call that then the PWM signal for the servo will never get generated and nothing will happen.

Oh, and yes those little servos should be fine.

# Answer
> 1 votes
1- there is only two pins a servo pin which is D2 and an analog pin which is A0. D2 pin for writing analog value to servo. D2 pin is used for getting analog pin value.

2- map function is a default function like sin, cos or digitalRead so library inport not necesary.

3- delay function and waiting 50ms is used to wait servo response time. if you change servo angle too quickly servo will not respond accurately

---
Tags: arduino-uno, servo
---


# Question
Title: How do I scroll through the LCD vertically with joystick?
I have a device I'm working on and the only issue I'm running into is I can't manage to figure out how to get my LCD display to move around vertically with the joystick I have attached to it. I have a feeling with a tip this could be a very simple fix, but I'm just stuck. So the brief of this is that I need someone to fill in the ???'s for me provided in my example code.

```
//Include the LCD Library.
#include <LiquidCrystal.h>
#include <Wire.h>
//Declare the LCD object and define pins.
#include <MFRC522.h>
#include <SPI.h>

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define SAD 10
#define RST 5

//Ignore The below line it is for the master code
#define I2C_ADDR    0x27 // <<----- Add your address here.  Find it from I2C Scanner
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

int n = 1;

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

void setup() {

//Booting the LCD
  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home (); // go home
  lcd.cursor();

//Starting settings
  lcd.begin(1,0);
  lcd.clear();

}

//Sometimes you have to hit reset on the device

//Joystick Defaults X=484 Y=513

void loop() {
  lcd.setCursor(0,0);
  lcd.print("Example");
  delay(100);

for (int positionCounter = 0; positionCounter = 1; positionCounter++) {
if(analogRead(1) > 584) {
  lcd.scrollDisplayLeft();
  delay(30);
  } else if(analogRead(1) < 384) {
    lcd.scrollDisplayRight();
    delay(30);
  } else if(analogRead(0) < 413) {
     lcd.???????????????????();
     delay(30);
  } else if(analogRead(0) > 613) {
     lcd.??????????????????();
     delay(30);
    }
  }
}

```

# Answer
The LCD library provides easy functions that activate commands in the LCD itself. The LCD doesn't have functions that do what you want, so there is no simple vertical scrolling like you're suggesting.

If you need to have it, you'll need to re-write the screen with the content you want to display when the user scrolls around. I can't make any specific suggestions as I don't know the reason you need to scroll around the display this way, but one comprehensive method would be to create a buffer of data the LCD should be displaying, then scroll it using software (move the bytes around the way you want) and then send that buffer to the LCD when it changes.

There may be other more applicable or easier tricks, but that would largely depend on your specific use case and user interface design.
> 2 votes

---
Tags: arduino-uno, programming, sensors, lcd
---


title: Measure SRAM usage

text:
# Question
Title: Measure SRAM usage
I am using an Arduino with 2048 bytes of SRAM. I have a complex project so that it is no longer obvious how much SRAM it would use in total (there is not one large dominant object but many different routines, many libraries most of which I have not written myself etc. Each of these uses some small buffers, global variables etc.).

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

# Answer
> 5 votes
Expanding on my previous comment... The RAM memory map of an AVR-based Arduino looks like this:

```
┌──────┬─────┬──────┬──────────┬───────┐
│ data │ bss │ heap │→  free  ←│ stack │
└──────┴─────┴──────┴──────────┴───────┘

```

The data and bss sections are fixed, and their size can be known at compile time. However, the stack and the heap grow and shrink dynamically as the program runs. You can estimate the amount of free memory at run time by measuring the gap between the heap and the stack. The result may be pessimistic if the heap contains usable holes.

Here you have:

---
Tags: memory-usage, sram
---


title: Problem using Ino build for 8 MHz

text:
# Question
Title: Problem using Ino build for 8 MHz
I want to use the Ino command line toolkit to build and upload my HEXes. It works well for the regular Arduino, however when I try to upload code to a Mini Pro 3.3V at 8 MHz, the code has the timing wrong. The serial output is garbled (I tried at different baud rates and was garbled each time) and `delay(1000);` seems to take double the time. I have selected the correct board (pro328 in my boards.txt), but it didn't seem to make a difference in the generated code. Has anyone used this and encountered a similar problem?

# Answer
Per the Quick start guide, Ino assumes the board is an Arduino Uno unless otherwise specified on the command line:

> All examples were done in assumption that you have Arduino Uno and it is available on default port. Now consider you have Arduino Mega 2560 and it is available on port `/dev/ttyACM1`. We have to specify this for our build steps as command-line switches.
>
> Board model may be set with `--board-model` or `-m` switch. Port is set with `--serial-port` or `-p` switch. So lets do it:
>
> ```
> $ ino build -m mega2560
> $ ino upload -m mega2560 -p /dev/ttyACM1
> $ ino serial -p /dev/ttyACM1
>
> ```
>
> For the full list of board names refer to `ino build --help`.

So you might be able to do this by using

```
$ ino build -m pro328
$ ino upload -m pro328 ...

```

However I don't know what options Ino includes for boards (presumably it uses the boards file), so using `ino build --help` should give you the information you need to select a suitable board if `pro328` doesn't work.

Once that's done, the frequency setting should be taken care of for you.
> 1 votes

# Answer
So it seems the F\_CPU should be set up at compile time and I'm not sure if Ino does that or not (probably, or I'm missing something else).

However after pulling my hair for a day or so I discovered PlatformIO which has a much better functionality - my code works correctly, the lib manager is intriguing, is platform independent and seems it doesn't even require the Arduino environment to be installed (it can pull the required files itself).
> 0 votes

---
Tags: compile, timing, frequency
---


title: Mega 2560 Doesn't Respond

text:
# Question
Title: Mega 2560 Doesn't Respond
When trying to upload to my Mega r2, it simply times out during uploading.

```
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

```

I tried burning the bootloader, but that also gave an error.

```
Error while burning bootloader.
avrdude: usbdev_open(): did not find any USB device "usb"

```

I can see the arduino in my Devices and Printers in control panel, so I don't think the board is burnt. The power light also is on. Any ideas?

# Answer
> 1 votes
I have seen this error numerous times before. I think the possibilities could be that either some external device is connected on RX, TX pins of arduino mega or mega is not getting sufficient power. Some connection from your board is trying to pull more than the limit current.

and off course the answers suggested above are also right. check out every possibility.

# Answer
> 1 votes
Download the devel filter.exe file from this site. Install it and target your programmer (I assume you are programming via ISP if you're using avrdude)

http://sourceforge.net/projects/libusb-win32/files/libusb-win32-releases/1.2.6.0/

This will eliminate the 'USB not found' problem.

# Answer
> 0 votes
1. Check if you have selected the right board
2. Have you installed FTDI drivers? If you have installed them update them to the latest version. They can be found here (Also see http://arduino.cc/en/Guide/Howto)

If this doesn't work check if the device is getting recognized by the system by running:

```
dmesg | grep -i tty

```

If the device is not recognized then try using a different cable/USB port.
Just to make sure, check if the board is working properly by testing it on another computer.

# Answer
> 0 votes
When you try to upload a sketch do the Receive and/or Transmit lights on the Arduino blink? If not you may not be getting serial communication. Try a loopback test (connect D0 to D1 and see if stuff you type in Serial Monitor comes back as it should).

If not, go to `My Computer>Properties>Device Manager` and search for `Ports(COM&LPT)>`is there Arduino MEGA??? If not you have no drivers installed or they haven't been installed automaticly or your arduino is dead :)). If it is drivers you have to update them. In same `Device Manager` expand `Other devices`. There should be some `Unknown devices`. Update Mega drivers `Update Driver Software`, `Browse my computer...` and `C:\...\arduino\drivers`

# Answer
> 0 votes
If you uploaded a program that uses **serial port** **too often** you cannot upload program from arduino IDE. try to **press reset button on mega2560 when you begin to upload** program. Many times I solved like this.

---
Tags: arduino-mega, bootloader, avrdude
---


# Question
Title: Long range wireless communication between two arduinos?
I'm working on a project that will require two arduinos to be able to relay information to each other from long distances (up to about 10 miles or around 16 km). WiFi won't be guaranteed to be available to either arduino as this is a wilderness application.

What are my options for long range wireless communication? I haven't decided on an arduino model yet so if one particular model would be best for this application let me know.

# Answer
> 2 votes
Your range of options depends strongly on what your budget is, what country you are in, whether you are a licensed radio operator, whether cell service is available, etc.

### If you aren't licensed:

In the USA, unlicensed (or lightly licensed) radio options include GMRS (General Mobile Radio Service), FRS (Family Radio Service) and CB (Citizens band radio). GMRS and FRS range typically is at most a few miles – ten miles is too much to hope for. CB range would be ok but CB radios often are fairly large and antennas would be large, eg nine feet long. I don't know whether it is legal to transmit digital data over GMRS/FRS/CB radio.

### If you are licensed:

2-meter band radio might be a good choice. Frequencies are 144 MHz to 148 MHz in the Americas and Asia, or 144 MHz to 146 MHz elsewhere. Per wikipedia,

> The license privileges of amateur radio operators include the use of frequencies within this band for telecommunication, usually conducted locally within a range of about 100 miles (160 km).

### If cell service is available:

Consider a GSM shield, eg the Arduino GSM Shield.

To access the cell network you would need to buy a SIM card for each GSM shield.

GPRS (General Packet Radio Service) on GSM provides data rates between 10 and 240 kbs. Other GSM protocols may be faster or slower. Data rates depend also on whether 3G service is available or only 2G.

---
Tags: communication
---


# Question
Title: Help needed understanding Due performance
I'm going to be writing some performance critical code and have started trying to get an understanding of timers and how much "work" the Due CPU can do per second. To help get started with this, I wrote a bare sketch that simply increments a counter whilst a timer which ticks every second dumps the value of the counter to the serial log and then resets the counter. Here's the code I'm using:

```
#include <Arduino.h>

void EnableTimer7TickEverySecond();

volatile uint32_t gCounter = 0;

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

    EnableTimer7TickEverySecond();

//  while ( true )
//  {
//      ++gCounter;
//  }
}

void loop()
{
    ++gCounter;
}

void EnableTimer7TickEverySecond()
{
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk(ID_TC7);
    TC_Configure(TC2, 1, TC_CMR_WAVE |
        TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1);
    TC_SetRC(TC2, 1, 656000 * 64);
    TC_Start(TC2, 1);
    TC2->TC_CHANNEL[1].TC_IER = TC_IER_CPCS;
    TC2->TC_CHANNEL[1].TC_IDR = ~TC_IER_CPCS;
    NVIC_EnableIRQ(TC7_IRQn);
}

void TC7_Handler()
{
    TC_GetStatus( TC2, 1 );

    Serial.println( (uint32_t)gCounter );

    gCounter = 0;
}

```

When I run this, I get values averaging 446,000 in the serial log for the increments per second. That is way lower than I was expecting. On an ARM chip running at 84MHz, I'd expect at least 14 million increments as few ARM instructions take more than 2 clock cycles and an increment should involve a read from memory, addition and a write back to memory (approx 6 clock cycles by my reckoning).

The timer is configured correctly, the TX led flashes regularly at 1 second intervals as the Serial.println is called. I've checked for overflow on the counter (oddly, I found that the number of increments when working with a uint64\_t was slightly higher). I've also tried not calling Serial.begin() until I'm about to write the value to the log (and then only writing the value once) and whilst there is a slight increase in "performance", it doesn't account for the whole difference between expectation and reality.

My best guess would be that loop() is called on some sort of timer or has a built in default delay, so it occurred to me that if I comment out the counter increment in loop() and instead comment in the infinite while loop in setup(), I should be able to counteract any delay caused by how frequently the Arduino IDE calls loop(). I have seen other examples that never bother with loop() and just stick all their code in setup().

I do see a performance increase with this setup, but only to around 9 million, not the 14+ million I would expect. Oddly though, sometimes, randomly, the value is 2 or 3 times the "usual" value. Not between 2 and 3 times, but exactly 2 or 3 times. This happens regardless of whether I am incrementing the counter inside the loop() function or my own loop inside setup(). It is not a case of the timer "skipping", the output is written every second like clockwork.

So, my questions are:

* What does the Arduino library do to make loop() so inefficient?
* Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?
* Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?

# Answer
> What does the Arduino library do to make loop() so inefficient?

Alot. For a start it's a function, so it has to push registers onto the stack before it runs, and pop them off afterwards. Secondly there is the "serial event" system outside the loop. In main.cpp in the core you can see how loop is called:

```
setup();

for (;;)
{
    loop();
    if (serialEventRun) serialEventRun();
}

```

> Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?

If you don't use serial events, no harm whatsoever.

> Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?

My guess is the operations you are using are not atomic. This is, the interrupt is able to be fired right in the middle of doing the series of instructions that perform the increment. The temporary registers end up not being the same as they were at the start of the operation, and consequently the value is corrupted. You should wrap the increment in a *critical section* (i.e., disable interrupts before it, and enable them afterwards).

To better analyse the speed of execution you can look at the generated assembly code of your program. If we look at the disassembled `main()` function for the bit where it loops you can get this:

```
80596:  f7ff fe05   bl  801a4 <loop>
8059a:  4b04        ldr r3, [pc, #16]   ; (805ac <main+0x30>)
8059c:  2b00        cmp r3, #0
8059e:  d0fa        beq.n   80596 <main+0x1a>
805a0:  f7ff feec   bl  8037c <_Z14serialEventRunv>
805a4:  e7f7        b.n 80596 <main+0x1a>
805a6:  bf00        nop

```

`loop()` consists of this:

```
801a4:  4b02        ldr r3, [pc, #8]    ; (801b0 <loop+0xc>)
801a6:  681a        ldr r2, [r3, #0]
801a8:  3201        adds    r2, #1
801aa:  601a        str r2, [r3, #0]
801ac:  4770        bx  lr
801ae:  bf00        nop

```

If we feed that into `main()` where it calls `loop()` the finished code looks like:

```
80596:  f7ff fe05   bl  801a4 <loop>
801a4:  4b02        ldr r3, [pc, #8]    ; (801b0 <loop+0xc>)
801a6:  681a        ldr r2, [r3, #0]
801a8:  3201        adds    r2, #1
801aa:  601a        str r2, [r3, #0]
801ac:  4770        bx  lr
801ae:  bf00        nop
8059a:  4b04        ldr r3, [pc, #16]   ; (805ac <main+0x30>)
8059c:  2b00        cmp r3, #0
8059e:  d0fa        beq.n   80596 <main+0x1a>
805a0:  f7ff feec   bl  8037c <_Z14serialEventRunv>
805a4:  e7f7        b.n 80596 <main+0x1a>
805a6:  bf00        nop

```

So that is what gets executed for every single iteration of `loop()`. If we (incorrectly) assume that each instruction takes 1 clock tick, that's 13 ticks. 84,000,000 / 13 = ~6.4 million loops per second.

Now - if we map the instructions against actually how many clock cycles they take, we can get a clearer picture:

```
bl                  1+P  (P = 1 to 3)
ldr (pc relative)   2
ldr (word)          2
adds                1
str (word)          2
bx                  1+P  (P = 1 to 3)
nop                 1
ldr (pc relative)   2
cmp                 1
beq.n               1 or 1+P (P = 1 to 3)
bl                  1+P (Only if serial event runs)
b.n                 1 or 1+P (P = 1 to 3)
nop                 1

```

So taking a worst case scenario where P = 3 (pipeline re-fill clock counts, that is), and no serial event running, we can calculate a total number of clock cycles of 4+2+2+1+2+4+1+2+1+4+0+4+1 = 28.

84,000,000 / 28 = 3,000,000 loops per second.

But hang on - that's still much more than you're seeing. That's because you're still only looking at the small picture. You're looking at just your sketch and forgetting what else there is going on.

Every millisecond the `SysTick_Handler()` gets called which does various tasks, including calling the `TimeTick_Increment()` routine to deal with `millis()`. That's 1,000 times per second, and that eats into your processing time somewhat.

Another important point is *it can't be incrementing while you're running your interrupt*. The more you do in your interrupt (*and using serial is a very heavy-weight thing to do in an interrupt*) the less of your 1-second slice you get for doing your incrementing.

As an experiment, why not try disabling all the interrupts except just the one you are using for your timer and see how it changes the value.
> 3 votes

---
Tags: arduino-due, performance
---


# Question
Title: SPI: problems communicating with sensor using Arduino
I have a sensor which I am trying to communicate with over SPI using an Arduino UNO. It is my first time using SPI and I'm experiencing some problems which I'm hoping are just due to some misunderstanding on my part. I have written a simple code to perform one basic operation: Turn on the sensor's fan. The Arduino is being powered through the 2.1 mm barrel jack by a 1.5 A DC adapter. The 5V, GND, MOSI, MISO, SS and SCK pins on the Arduino are connected to the corresponding pins on the sensor. The sensor receives power from the Arduino, drawing up to 250 mA (with the fan on).

The manufacturer provides a list of commands corresponding to each function of the sensor. To turn on the fan, the command list gives the following information:

```
Command_byte: 0x03
Bytes: 0x03, 0x00
Bytes_in: 0xF3, 0x03
Time_between_current_and_next_byte: 1.7ms, NA
Note: 1ms would be adequate delay between command byte and following byte

```

Based on my understanding of this, to turn on the fan, I need to send a command byte (0x03), then wait 1.7 ms and send another byte (0x00). My code for doing this is as follows:

```
#include <SPI.h>
const int chipSelectPin = 10;

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

  SPI.begin();
  pinMode(chipSelectPin, OUTPUT);
  SPI.setClockDivider(SPI_CLOCK_DIV32); //set clock to 500kHz
  SPI.setDataMode(SPI_MODE1);
  SPI.setBitOrder(MSBFIRST);
  delay(10000); // Let the sensor settle for 10 seconds

  digitalWrite(chipSelectPin, LOW);
  indata = SPI.transfer(0x03); //command byte for fan on
  Serial.println(indata);// value returned should be 0xF3
  delay(2);
  indata = SPI.transfer(0x00); //Turn on fan
  digitalWrite(chipSelectPin, HIGH);
  Serial.println(indata);// value returned should be 0x03
}

void loop() {}

```

When I send the command byte, the returned value (which gets printed to the terminal) is 243 which corresponds to the expected hex value of 0xF3. However, the second command does not turn on the fan and the second returned value is 231 which does not correspond to the expected hex value of 0x03.

I don't think it's a hardware issue because at least one of the returned values is correct and because the sensor does work when used with a different platform. I also experimented with different delays between bytes.

# Answer
> -1 votes
Change your chipSelectPin. Pin 10 is exclusively used by SPI library. See Arduino Uno description.

Similar issue has been discussed here.

---
Tags: spi
---


title: Multiple boards blinking at same time

text:
# Question
Title: Multiple boards blinking at same time
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?

# Answer
> 1 votes
Have both sync to a master clock using GSM shields. These shields are getting very cheap (as low as $14 on ebay).

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.

# Answer
> 1 votes
You can also use real time clock (RTC) modules to syncronize arduinos. These are cheaper than other solutions like GPS or WiFi.

# Answer
> 0 votes
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.

---
Tags: led, time
---


title: Calculate how much battery power left

text:
# Question
Title: Calculate how much battery power left
I run my 12V car battery trough a trimpot into my pro micro, micro controller. I am using (voltPinValue1 * 0.01465) to get the Volt out of analog in. I have trimmed the pots and getting the right V.

But now I want to calculate for how long I can run for, example the stereo and some LED:s, but don't know how.. Does anybody know how I can do this??

Sorry for my English

Thanks! //Rasmus

# Answer
You really need to know the current being drawn rather than the instantaneous voltage. A voltage drop profile of a battery changes depending on the current draw, and just using the voltage is very very hard indeed.

You could measure the voltage over time, and try and calculate the slope of the voltage and attempt to predict when it would reach a specific pre-determined cut-off point, but since that change in voltage will be non-linear it's not really something that can easily be calculated.

But, if you can measure the current instead, and you know the Ah of the battery, then you can get a better estimate of how long the battery will run until it's considered flat.
> 1 votes

---
Tags: voltage-level, battery, arduino-pro-micro
---


title: Stack isn't popping off correct data?

text:
# Question
Title: Stack isn't popping off correct data?
So, I was working on a project where I needed to get a random object from a stack, so to make sure my design was correct, I made a dummy program that does nothing but fill a stack with data, then print it out.

why in the world is nothing coming out of the stack but -1s??

Here's the stack.h file.

http://pastebin.com/vjhNLpNu

# Answer
You're not telling it how big your stack should be, and it defaults to 0 entries, which means nothing gets stored.

```
class Stack
{
private:
    int *p;
    int top,length;

public:
    Stack(int = 0);  <<== CONSTRUCTOR - DEFAULT SIZE IS 0
    ~Stack();

    void push(int);
    int pop();
    void display();
};

```

When you make your Stack object you must give it a size for the number of entries in the stack:

```
Stack stack(4);

```
> 3 votes

# Answer
You never allocate space for the stack.

The way it's written, you need to pass the stack size into the constructor, and then it's fixed for the lifetime of the object; i.e. it won't grow automatically when you call `push()`. You're not passing anything into the `Stack` constructor, so the parameter is defaulting to `0`, meaning it has zero size.

The solution is to declare the stack something like this:

```
Stack stack(10);

```

(10 is just an arbitrary size -- use whatever you expect to need.)

Incidentally, there isn't an effective safeguard in your code to handle an empty stack. The result is that you're technically getting undefined behaviour at the moment when you call `push()` (it's writing to arbitrary memory locations).
> 1 votes

---
Tags: arduino-uno, c++
---


title: Can I use Serial.println() in a class?

text:
# Question
Title: Can I use Serial.println() in a class?
I'm trying to convert a class header file from another c++ project to arduino, which in my mind involves replacing cout with Serial.println.

When I try to recomplile with all of these changes, I get this error from the compiler:

```
error: 'Serial' was not declared in this scope
     Serial.print(p[i]);

```

Can someone explain this to me?

# Answer
You have to `#include <Arduino.h>`, or compile with the `-include Arduino.h` flag. The Arduino IDE normally does that for you, but you have to do it yourself if you are working outside the IDE.

There are a couple of Arduino Makefiles floating around the Web which, just like the IDE, take care of this for you.
> 3 votes

---
Tags: arduino-uno, c++
---


# Question
Title: How to power on Arduino a few seconds later after GSM module initialization?
I've connected a SIM900A GSM module to Arduino and the circuit works standalone on a 12V power supply. The problem is when I provide the 12V power supply, both GSM module and Arduino starts but the Arduino don't initializes the program for GSM module and hence the send or receive message functions don't work. Also when I first power on the GSM module and let it initialize first and then power on the Arduino, everything works fine. How to deal with this problem?

# Answer
It sounds like your problem is that the GSM module needs time to initialize before it is ready to be talked to by the Arduino.

A crude way of providing this would be to use the `delay()` function in the Setup() of your sketch. The argument to that is an `unsigned long` number of milliseconds (thousandths of a second) so it can produce delays far longer than you need.

But a more sophisticated solution would be to repeatedly try to talk to the module and check for an expected response. Apparently, with at least some of these, if you disable baud rate detection they will announce themselves with a prompt when they are ready - you could wait for that. But I think repeatedly trying until you get a response is going to be the most robust.
> 1 votes

# Answer
Let the 12 V charge a large capacitor over a resistor. The time to charge to 63% is RxC. Place a 5 V zener diode parallel to the capacitor, so that doesn't damage the microcontroller. Then either connect to the microcontroller's reset, or, and this is "nicer", use a MAX809 reset controller. The latter will keep the output low until a precise threshold is reached, there's for instance a 4.00 V version. Use that output to keep the microcontroller reset for some time.

Not sure how much delay you want, but a 10 uF capacitor and a 100k resistor will give you (from the top of my head) about half a second before the voltage on the capacitor reaches 4 V.
> 1 votes

---
Tags: arduino-uno, programming, gsm, electronics
---


title: How to program thresholds?

text:
# Question
Title: How to program thresholds?
Hello guys (and gals)!

I'm trying to figure out how to program thresholds using my arduino board.

Essentially, to make this as simple as possible, this is what I have going on.

I am sampling a value every one second, I am taking the value and trying to make certain actions occur based on when this value crosses certain thresholds.

The value read every second will be a value between 0-150.

The thresholds will work something like this:

If value crosses over 20 and becomes 20 or higher, do an action.

If value crosses over 20 and becomes 19.9 or less, do a different action.

And then do the same for a threshold at 30, 40, 50, and 65.

I would need to have it so that if it reads a value of 15, and then a second later, reads a value of 23, it does an action. But if it reads 23, and then reads 24 a next, it needs to not do anything because it hasn't crossed over from one threshold to another. I only want an action to perform if a threshold is crossed either by increasing or decreasing past it.

So again, to reiterate;

If first value read is 34, and second is 42, do an action.

If first value is read at 57, and second at 44, do an action.

If first value is 24, and second value is 26, do nothing. (no threshold was crossed)

The next part would be figured out if a threshold was crossed twice, or more, to do that action twice or more times.

Any advice on how to code this?

Thanks in advance.

# Answer
> 1 votes
Thanks again for your contributions.

I've gone ahead and decided to go with the following code. Its purpose is to turn vol up or down based on current car MPH. I choose to define brackets that cover a range of values. When one bracket ends, another begins. I've also set the previous bracket to current bracket at the end of each loop so that the application knows where it was previously, so that if it hops above or goes under a defined bracket, it does the desired action.

I've used a random generator to supply the MPH for testing purposes for now and commented out a few things that disturbed the testing process. If you'd like to critique this code to make is better, please let me know.

Note: I've also borrowed some of this code from another individual (Matthew McMillan, http://matthewcmcmillan.blogspot.com) who wanted to figure out how to convert a vehicle speed sensor wire info into MPH. I needed this code in order to make use of the vehicle's speed.

```
#include <SPI.h>
#include <Wire.h>

const int lightPin = 0;
const int hardwareCounterPin = 5;
const int samplePeriod = 1000; //in milliseconds
const float pulsesPerMile = 4000; // this is pulses per mile for Toyota. Other cars are different.
const float convertMph = pulsesPerMile/3600;
unsigned int count;
float mph;
unsigned int imph;
int roundedMph;
int previousMph;
int prevCount;

// Declare brackets
const int BracketA = 1;
const int BracketB = 2;
const int BracketC = 3;
const int BracketD = 4;
const int BracketE = 5;
const int BracketF = 6;

// Initialize Previous and Current Brackets
int PreviousBracket = 1;
int CurrentBracket = 1;

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

  TCCR1A = 0; //Configure hardware counter
  TCNT1 = 0;  // Reset hardware counter to zero
}

void loop() {

  /////////////////////////////////////////////////////////////
  // This uses the hardware pulse counter on the Arduino.
  // Currently it collects samples for one second.
  //
  bitSet(TCCR1B, CS12); // start counting pulses
  bitSet(TCCR1B, CS11); // Clock on rising edge
  delay(samplePeriod); // Allow pulse counter to collect for samplePeriod
  TCCR1B = 0; // stop counting
  count = TCNT1; // Store the hardware counter in a variable
  TCNT1 = 0;     // Reset hardware counter to zero
  mph = (count/convertMph)*10; // Convert pulse count into mph.
  imph = (unsigned int) mph; // Cast to integer. 10x allows retaining 10th of mph resolution.

  int x = imph / 10;
  int y = imph % 10;

  // Round to whole mile per hour
  //if(y >= 5){
  //  roundedMph = x + 1;
  //}else{
  //  roundedMph = x;
 // }

  //Code to write your own MPH for testing purposes.
  //if (Serial.available() > 0) {
                // read the incoming byte:
               // roundedMph = Serial.read();
               //}

  //If mph is less than 1mph just show 0mph.
  //Readings of 0.9mph or lower are some what erratic and can
  //occasionally be triggered by electrical noise.
  //if(x == 0){
  //  roundedMph = 0;
 // }

  roundedMph = random(1,80);

  // Don't display mph readings that are more than 50 mph higher than the
  // previous reading because it is probably a spurious reading.
  // Accelerating 50mph in one second is rocketship fast so it is probably
  // not real.
  if((roundedMph - previousMph) > 50){
    roundedMph = previousMph;
  }

  //Place the gatherered MPH value into a bracket
  //---------------------------------------------
  if(roundedMph >= 0 && roundedMph < 20) {
   CurrentBracket = BracketA;  //Value1
   Serial.println("I Choose Bracket A");
    }

  if(roundedMph >= 20 && roundedMph < 30) {
   CurrentBracket = BracketB;  //Value2
   Serial.println("I Choose Bracket B");
    }

  if(roundedMph >= 30 && roundedMph < 40) {
   CurrentBracket = BracketC;  //Value3
   Serial.println("I Choose Bracket C");
    }

  if(roundedMph >= 40 && roundedMph < 50) {
   CurrentBracket = BracketD;  //Value4
   Serial.println("I Choose Bracket D");
    }

  if(roundedMph >= 50 && roundedMph < 65) {
   CurrentBracket = BracketE;  //Value5
   Serial.println("I Choose Bracket E");
    }

  if(roundedMph >= 65) {
   CurrentBracket = BracketF;  //Value6
   Serial.println("I Choose Bracket F");
    }

 //Decide if bracket stayed the same, went up, or down.
 //---------------------------------------------------
 if(CurrentBracket == PreviousBracket) {
 //Do Nothing
 Serial.println("Nothing Changed");
 }

if(CurrentBracket > PreviousBracket) {
 //Command for Vol Up
 int VolUp;
 VolUp = CurrentBracket - PreviousBracket;
Serial.println("Volume Went Up One by ");
Serial.println(VolUp);
delay(2000); // Delay to not change Vol to fast if near threshold
}

if(CurrentBracket < PreviousBracket) {
  //Command for Vol Down
  int VolDown;
  VolDown = PreviousBracket - CurrentBracket;
 Serial.println("Volume Went Down One by ");
 Serial.println(VolDown);
 delay(2000); // Delay to not change Vol to fast if near threshold
 }
  previousMph = roundedMph; // Set previousMph for use in next loop.
  PreviousBracket = CurrentBracket; //Set PreviousBracket for use in next loop.
}

```

# Answer
> 0 votes
The way you described it, the first and good solution I can approach it is state machine.

You have a lot of thresholds to check and very specific details such as going up at some level and doing something or nothing depending on the level.

What I advise you is creating the state machine for you code setting up all the thresholds and saving the actual *state* of your system into a variable. After you have this set up, coding is just a matter of switch/cases or if statements.

For example. The first part is to check if it goes until 20 and then keep with at least 20.

```
switch (state) {
    case 1:
        if (value >= 20 && value < 30)
             state = 2;
        break;
     case 2:
        if (value < 20)
             state = 1;  // initial state
        else if (value >= 20 && value < 30)
             state = 3; // or call a function
        break;
     case 3:
          doSomething();
          break;
}

```

And you could have some delay or timer interrupt to check the value each 1s and repeat the state machine again and again. If you change or read the value inside an interrupt function call, make sure you declare the variable as **volatile** otherwise the compiler will optimize it and your machine won't work properly.

This way you can expand the idea and have all the thresholds set up.

---
Tags: arduino-uno
---


# Question
Title: How to I measure the duration of touch with a soft potentiometer?
I'm having a soft pot meter here and I would like to register the duration of the touch event. I'm having a different variable, which keeps going from 1024 to 0 , which regularly takes 60 seconds, but for every second you touch the soft pot meter the count adds 50 up to 1024. Like returning the clock backward.

How would I register/code this?

# Answer
You have to go with timer interrupts. Here is the documentation: http://playground.arduino.cc/code/timer1

Roughly, when you detect a press, an interrupt is raised and the same thing goes for releasing. Using the timer values from both these events, you can accurately measure the time that the press lasted.
> 2 votes

---
Tags: potentiometer
---


# Question
Title: Is supplying 5V from both external 5V and USB harmful?
I have an arduino nano which is powered through unregulated 5V (pin 27). For debugging purpose, I'd like to connect the USB port to my computer in order to use the Serial.Print function. The external 5V will stay connected. Will this cause damage ?

edit : I forgot to mention that the external power supplied to pin 27 is regulated with a switching DC-DC converter (measured 5.1V). Sorry it was not clear in my question.

Here is my circuit :

The switching regulator is not exactly the one in the schema.

Is using the circuit with the battery power supply + usb connection to my computer will damage something ?

# Answer
No, it probably won't damage anything, as the PC's USB port is protected from overvoltage by the D1 schottky device on your arduino board.

**Update, my previous answer contained the following paragraph, which is not related to your problem**

> But you should take care of some things.
>
> 1. Make sure, the voltage applied to your +5V-Net is regulated properly elsewhere. I.e. choose a laboratory PSU or another good source.
> 2. Avoid having both your PC and your 5V-supply connected to line voltage. Ground levels may differ due to Y-capacitors present in the switching PSUs. Those provide a AC voltage of half your line voltage to DC ground (only with 0.3 to 0.7 mA, but enough to cause disturbances on your signals at 55 volts in the US or 115 V in the EU)
> 3. If you have to use two switching PSU for both PC and arduino, provide an equipotential bonding between your PC's mass (e.g. VGA-port-screw) to your arduino's PSU's ground directly, to prevent leakage currents from the Y-capacitors wandering around in your circuitry.

**Update according to your enhanced question**

You are using a battery powered DC-DC supply for your Arduino. So, my previous notes do not apply to your problem.

* 5.1 V seem exact enough to drive your arduino safely. No need for additional stabilisation measures
* D1 (see genuine arduino schematic) separates USB-Power from +5V and prevents current flowing in reverse direction over your USB connection.
* Arduino circuitry and USB port have common GND so there are always well defined voltage levels.

In my opinion, there's nothing with your setup, which may harm your circuitry or your PC.

Depending on the maximum power of your DC-DC converter you may consider adding a fuse to protect converter and components in case of short circuit.
> 1 votes

# Answer
Since the external 5V supply is not regulated, it may cause some problems. It is possible that a small voltage difference will appear if and when the external voltage fluctuates from the 5V level. What you should do is short-circuit the 5V of the USB to pin 27.

And in general, add a 5V regulator circuit to feed the Arduino nano, like this one:
> -1 votes

---
Tags: serial, power, usb
---


title: Simulate a FTDI using an Arduino UNO

text:
# Question
Title: Simulate a FTDI using an Arduino UNO
I'm looking to directly program an ESP8266 WiFi Module with out using a FTDI (USB-Serial interface) as suggested in this excelent tutorial. The real purpose is to have access to the GPIO ports of the module.

I heard (from this page) that one can use an Arduino UNO as an intermediate interface for burning the bootloader onto an AVR (e.g. ATmega168 or ATmega328). That is, using the ArduinoISP code example in the IDE.

Is it possible to use an Arduino UNO as temporal bridge to program the ESP8266? Can anyone please suggest some tutorial? Thanks

# Answer
> 2 votes
The simplest way is to unplug the ATMega328P from the board (or otherwise disable it) and just use the ATMega16U2 by connecting the ESP8266 to pins 0 and 1 of the Uno. No programming required at all then - the ESP8266 just takes the place of the ATMega328P.

If you really want to "pass it through" the ATMega328P then you will need to make a transparent pipe for the serial data. That would involve nominating two more pins on the Uno to be a new serial connection, and using SoftwareSerial to interface with those pins. Then you have a simple loop which reads from one port and writes to the other, and the same in reverse of course. Make sure you have the baud rates right. I don't know how well SoftwareSerial would perform at the (commonly) 115200 baud the ESP8266 works at.

EDIT: (Interfacing to a 3.3-V system)

Since the ESP8266 works at 3.3V, while the ATMEGA16U2 is powered at 5V, you might need to adapt the level of the ATMEGA16U2's TXD line (which is connected to the "RX" input line of the ATMEGA328P/Arduino Uno Board), to 3.3V.

To do this, connect a 1.5 kOhm resistor between the RX pin and ground. In fact, the connection between ATMEGA16U2 and ATMEGA328P is done using an 1kOhm series resistor. This, together with the 1.5k Ohm resistor, will create a resistor divider, which converts the 5V output to 3V.

See schematics below.

---
Tags: arduino-uno, esp8266, ftdi
---


# Question
Title: Can't burn arduino bootloader to atmega8a with usbasp
I want to burn the arduino bootloader with arduino IDE, but I cant get it done. And here is my circuit: I have marked the way I connect the ISP port and the chip.

I choose Arduino NG/older as the board and Atmega8 as the processor, but when I start to burn the bootloader to the chip the LED on the usbasp just blink once and an error was given:

```
Arduino:1.6.5 Hourly Build 2015/05/15 06:16 (Windows 7), 板："Arduino NG or older, ATmega8"

avrdude: warning: cannot set sck period. please check for usbasp firmware update.

avrdude: error: programm enable: target doesn't answer. 1

烧录引导程序出错。

avrdude: initialization failed, rc=-1

         Double check connections and try again, or use -F to override

         this check.

```

What should go wrong? I have check the connection many times and replace a chip as well, and I even add a 12M crystal(with 22pF caps) but things still keep the same.

## **EDIT**

I do the flowing things as advise:

1. short the jp3 jumper of the usbasp to make a slow commiuncation. And remove the crystal.
2. I just found the way I connect the isp port might be wrong. so I changed it as flowing

And my actually circuit is like this:

But got no luck, things still the same :-(

# Answer
> 1 votes
Did you set the SLOW SCK jumper on the USBasp Programmer? Completely new ATMegas use the internal RC-Oscillator at a frequency of 8MHz, but the *divide clock by 8* fuse is set too. That means that (before burning the fuses) the AVR is running at a clock frequency of 1MHz and the standard SCK clockrate of the USBasp is too high for this clock frequency. Therefore, you need to set the SLOW SCK jumper to get a lower SCK clockrate.

# Answer
> 0 votes
You forgot the Pull Up resistor for Reset.

Using 12Mhz crystal is not a good idea because the Atmega8 config probably uses 8Mhz or 16Mhz, and the fuses which are burned during the bootloader process (yes, they burn fuses first, and THEN load the bootloader) will not expect there to be a 12Mhz crystal, so any further communication can fail because of this too.

---
Tags: bootloader, avrdude
---


title: arduino ethernet shield

text:
# Question
Title: arduino ethernet shield
I bought a ethernet shield for my Arduino Uno. I plug it my Arduino and PC with ethernet cable. There is all led is working on ethernet shield. But when i try to examples about ethernet which is in Arduino IDE as "DHCPChatServer" example.

**I hope to see; "Trying to get an IP address using DHCP" "My IP address: 192.168.1.177"**

**But I just see "Trying to get an IP address using DHCP"**

Any problem with my ethernet shield?

# Answer
> 1 votes
When you connect your arduino directly to the PC using the ethernet cable, neither of them have any information about the network.

Most ethernet devices attach to switches, routers, and gateways, and one or more of these devices host network services such as DHCP, DNS, or provide a way to obtain those services.

Without DHCP, for instance, neither your PC nor the Arduino know what IP adress to use, what their netmask is, and whether there's a gateway to other IP addresses.

You have a few options:

* Follow the Automatic Private IP Addressing specification, which windows computers default to when no DHCP server is present or available. Set the IP address of the Arduino to 169.254.x.y where x and y are randomly chosen numbers between 0 and 255, and set th netmask to 255.255.0.0. The windows computer should have done the same if no static IP address was set - use `ipconfig` on the windows command prompt to find its IP address. Your computer and arduino should be able to talk to each other.
* Set up a router. It doesn't need to connect to the internet, it just needs to connect to both the PC and the Arduino. It'll implement a DHCP server and make sure, at minimum, that the two devices can talk to each other and the router.
* Set static IP addresses on both devices. Set up the PC with something like 192.168.42.1 with a netmask of 255.255.0.0 and the Arduino with 192.168.42.2 and the same netmask. Now they should be able to talk to each other.
* Connect both to an existing network. The network should already have a router with DHCP on it, so it'll take care of everything, and as a bonus you may be able to get internet access as well, which could help with testing since you can use the ethernet shield to communicate with google and other known working services, rather than trying to set up a server on the PC.

# Answer
> -1 votes
I changed my Arduino Uno with Arduino Mega and problem is solved.Thank you

---
Tags: ethernet
---


title: arduino weather shield and wind speed

text:
# Question
Title: arduino weather shield and wind speed
I have Arduino Mega and Weather Shield. I want to calculate wind speed.

```
float get_wind_speed()
{

float deltaTime = millis() - lastWindCheck; //750ms

deltaTime /= 1000.0;

  float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4

  windClicks = 0; //Sıfırla ve yeni oluşan rüzgarı izle
  lastWindCheck = millis();

  windSpeed *= 1.492; //4 * 1.492 = 5.968MPH

 Serial.println();
 Serial.print("Windspeed :");
 Serial.println(windSpeed);

 return(windSpeed);
}

```

But when I run my code I see two windspeed value. First one is windspeed=0.0 or any value. Second one is windspeed=nan.

How can I make it better?

# Answer
When debugging a problem like this one, print out values of the variables that the calculation depends on.

In this case, you may find that both `windClicks` and `deltaTime` are 0 or 0.0. The IEEE 754 floating-point-operations specification dictates a result of `NaN` (not-a-number) for various zero over zero calculations. It dictates a result of `+Inf` or `-Inf` for calculations like 7/0.0 or -13/0.0. \[See, for example, the stackoverflow question, Why does division by zero with floating point (or double precision) numbers not throw an exception.\]

If arithmetic generates a `NaN` or `+Inf` result, subsequent arithmetic using that result will also produce `NaN` or `+Inf` results.

To deal with the problem, you could use `deltaTime > 0` as a required pre-condition for calculation of `windSpeed`. That is, have an if-statement protecting the calculation block.
> 1 votes

---
Tags: hardware, software
---


# Question
Title: Is it safe to feed 5v dc 1amp to an Arduino uno R3 board?
Is it safe to feed 5v dc 1amp to an Arduino uno board?

# Answer
> 0 votes
That's a common newbie question: "What will happen when I use a 1 A power supply for a device which only needs 0.1 A?"

The device will only draw the current it needs. It's the same as on your electricity grid. The nuclear power plant can supply a gigawatt, yet the bulb will only draw the 60 W it needs.

But do you want to apply that 5 V to the power connector? Then the 5 V is too low, you'll need at least something like 6.5 V, otherwise the onboard voltage regulator won't have enough headroom to output 5 V. If you're using the USB connector for a **regulated**(!) 5 V, then the onboard regulator will be bypassed. Never place an unregulated 5 V on the USB connector, though.

# Answer
> 0 votes
Yes as long as the polarity is correct, the board will only take the current it requires

# Answer
> 0 votes
The 1 Ampère you're mentioning is likely the maximum rating of the power supply, i.e. it cannot sustain higher currents for a long time. However, if you connect your Arduino board (or any other device) to your power supply, the actually flowing current will depend on the voltage U and the resistance R of the device as I = U/R. You can think of this as the Arduino drawing as much power as it needs.

In other words: you must not exceed the maximum voltage, but you don't have to (and cannot in a simple way) adjust the current flowing into the Arduino.

---
Tags: power
---


# Question
Title: Can anyone explain how hex codes 0x1A is used for sending ctrl+z & 0x0D for Carriage Return & 0x0A for LineFeed?
Please explain in detail. How the Hexadecimal code has been assigned?

Edit: This is the code:

```
#include <Wire.h>
void setup()
{
   Wire.begin();
   Serial.begin(9600);
   delay(1000);
   Serial.println("AT+CMGF=1"); //set to SMS mode
   delay(1000);
   Serial.println("AT+CMGS=\"+918460588440\""); //set the phone number (wrapped in double quotes)
   delay(1000);
   Serial.println("hello world. this is arduino");
   delay(1000);
   Serial.write(0x1A); // sends ctrl+z end of message
   delay(1000);
   Serial.write(0x0D); // Carriage Return in Hex
   delay(1000);
   Serial.write(0x0A);
}
void loop() {}

```

# Answer
They are all to do with where in the alphabet they are. There are 26 letters in the English alphabet, and Z is the 26th. The 26 in hexadecimal is 0x1A.

A carriage return is a CTRL-M, and a line feed is a CTRL-J. M is the 13th letter of the alphabet, and 13 in hexadecimal is 0x0D. J is the 10th letter - 10 is 0x0A in hexadecimal.

Why are they CTRL-M and CTRL-J? Well, that all stems from the old teletype interfaces used on the very early computers. That's what they used, and that's what's stuck, and finally made it into the ASCII standard.
> 1 votes

# Answer
These hex values are the numbers in the ASCII table, https://en.wikipedia.org/wiki/ASCII.

Characters corresponding to values below 32 are control characters, reserved for special purposes. For the values you mention in the question:

* 0x0d = 1\*16 + d\*1 = 13 = CR (carriage return)
* 0x0a = 0\*16 + a\*1 = 10 = LF (line feed)
* 0x1a = 1\*16 + a\*1 = 26 = SUB

("control+Z" is not the ASCII control character, but how you would generate this control character (SUB) on a keyboard.)

A table with both hexadecimal and decimal numbers is also given in the Wikipedia article.
> 0 votes

# Answer
(I've formatted your code and edited it into your question).

This code is apparently driving a device - GPRS shield? - to send an SMS. No doubt the code was written to meet the requirements of the device. Note that the CR and LF literals could have been written as '\r' and '\n', respectively. The author chose to write them in hex, probably because there is no "\\" code defined for Ctrl-Z, and so wrote all three in a consistent style.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Why is the atmega chip reset three times during programming?
I'm trying to understand the auto reset process and why a capacitor hooked up between DTR and Reset works so I ran it through my logic analyzer and I'm seeing the chip reset three times during the programming process. Does anyone know why it's done three times and not just once?

You can see in the picture the top pin is the DTR and the bottom two are attached to reset (digital/analog). When DTR drops low the reset pin does too for between 200-500us but it does it three times in around 1 second.

# Answer
> 2 votes
It does it to "force" a reset.

Historically, when you open the serial port on an FTDI interface, the DTR will automatically go LOW. However, recently FTDI decided it'd be a good idea to change their driver so that when you open the port the DTR line doesn't go low - you have to manually tell it to go low. But this is only on the FTDI official drivers.

If you have a driver that is newer than a certain date (no idea what date) then just running `avrdude` by itself on an FTDI interface may not work properly since DTR isn't being lowered.

To get around that Arduino have included a forced toggling of the DTR line as part of the programming sequence to make the target board reset.

But of course, if the driver is old enough, or not the "official" FTDI driver (i.e., you're in Linux for instance) then the lowering of the DTR by `avrdude` works fine.

So what you are seeing there is first a brief toggle of DTR by the IDE to force a reset, then `avrdude` opening the port and DTR going low, then finally the IDE toggling DTR again one last time to force a final reset.

And to me that says you're either not in Windows, or you have an FTDI driver while does toggle the DTR line automatically.

I also have a feeling that `avrdude` may also have started including manual control of the DTR line within it - so if `avrdude` is new enough, even with a new FTDI driver that doesn't automatically, you will still see the repeated action of DTR.

It's what we call *belt and braces*. Use every method possible to get the board to reset, so no matter what you hardware and software arrangement the board has a very good chance of being reset into the bootloader.

---
Tags: reset
---


# Question
Title: How to fade in and fade out led strip connected to arduino based on continous analog input from capacitative sensor?
So I've been trying to get a capacitive sensor made from aluminum foil to work. And I have had success the kind of proximity and readings I need to light up a single LED and produce basic tone. Using this very basic code :

```
{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  delay(10);

```

All this works perfectly for me, the delay isn't perceivable, the response is for all practical purposes simultaneous to input. Except it's not beautiful, because the LED keeps flickering when values reduce or increase because the jumps are sudden I suppose.

SO I thought I'll try to fade in and fade out to different values from present values. Used the fading examples. Here:

```
Serial.println(value1);
  if (value1<=8) value1=-100;

  if (value1+100<=value2+100) {
    for(int fadeValue = value2+100 ; fadeValue <= value1+100; fadeValue +=5) {

    analogWrite(ledPin, fadeValue);

    delay(10);
    }
  }

  else
  {

    for(int fadeValue = value2+100 ; fadeValue >= value1+100; fadeValue -=5)
    {
        analogWrite(ledPin, fadeValue);

    delay(10);
    }
  }
  //analogWrite(ledPin,value1+100);
  tone(tonepin,value1+100,100);
  delay(10);
  value2=value1;

```

But this takes away the responsiveness, the whole thing is so slow to react, the sound and the light are obviously not in sync as I read my code. But also the light is not really fading, still blinking, but there seems to be some effect but I am not sure.

Any help with what I could do and what I am doing wrong would be nice.

# Answer
> 0 votes
Smooth the change in output value by taking, e.g 10% of the new value, and 90% of the old value. You can try experimenting with different ratios and longer/shorter delays.

```
int lastValue = 0;

{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  value1 = (1*value + 9*lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  lastValue = value1;
  delay(10);

```

# Answer
> 0 votes
You need to re-think the entire way of dealing with the fading.

Instead of saying "The value has changed, fade the LED to that brightness", you need to say "The value has changed. I want the LED to be this brightness." followed by "Is the LED the brightness I want? No? Then move it a bit towards the brightness I want".

Something like, in pseudo-code:

```
TargetBrightness = SensorValue
if LEDBrightness < TargetBrightness
    increment LEDBrightness
    set LED to LEDBrightness
if LEDBrightness > TargetBrightness
    decrement LEDBrightness
    set LED to LEDBrightness

```

If that all happens too fast then you need to only run the brightness tests at certain periods. Something like:

```
TargetBrightness = SensorValue
Has 10ms passed since last check? Yes?
    Remember the time this check happened.
    if LEDBrightness < TargetBrightness
        increment LEDBrightness
        set LED to LEDBrightness
    if LEDBrightness > TargetBrightness
        decrement LEDBrightness
        set LED to LEDBrightness

```

---
Tags: arduino-uno, led, pwm
---


# Question
Title: How to check my Arduino board is working or dead?
When you have a board in your hand but you don't know is it working or not, how to verify if it's working or dead?

# Answer
> **Note :** After the @Ricardo's comment on my last post, I am posting this !

Plug the board into a USB port on your computer and check that the green LED power indicator on the board illuminates. Standard Arduino boards (Uno, Duemilanove, and Mega) have a green LED power indicator located near the reset switch.

An orange LED near the center of the board (labeled “Pin 13 LED” in the image below) should flash on and off when the board is powered up (boards come from the factory preloaded with software to flash the LED as a simple check that the board is working).

If the power LED does not illuminate when the board is connected to your computer, the board is probably not receiving power.

The flashing LED (connected to digital output pin 13) is being controlled by code running on the board (new boards are preloaded with the Blink example sketch). If the pin 13 LED is flashing, the sketch is running correctly, which means the chip on the board is working. If the green power LED is on but the pin 13 LED is not flashing, it could be that the factory code is not on the chip. If you are not using a standard board, it may not have a built-in LED on pin 13, so check the documentation for details of your board.

Online guides for getting started with Arduino are available at for Windows, for Mac OS X, and for Linux.
> 16 votes

# Answer
Supposed one owns a USB programmer, there's another way to inspect the Arduino.

Connect the programmer to the ICSP pins of the Arduino and call `avrdude` with the right parameters to read the fuses of your Arduino.

```
avrdude -c programmer-id -p partno -P port

```

For an Arduino Uno, `partno` is `m328p`. `Programmer-id` depends on the device used. In my case (mySmartUSB light) `stk500v2` is a supported and `port` is `/dev/ttyUSB0`. Here

```
avrdude -c stk500v2 -p m328p -P /dev/ttyUSB0

```

gives the following output

```
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.01s
avrdude: Device signature = 0x1e950f
avrdude: safemode: Fuses OK
avrdude done.  Thank you.

```

The UNO board responds with the correct signature and is ready for some action :)

### How to connect?

My USB programmer came with a 6-wire ribbon cable with 2x3 female connectors on both sides. As usual, the wire for **pin 1** is marked red. Due to a notch in at the 2x3 male connector of the programmer, the cable only fits here in one direction.

If you look at the Arduino UNO, the ICSP header is to the right of the reset button.

The pinout is as follows.

```
MISO  1    2 VCC
SCK   3    4 MOSI
RESET 5    6 GND

```

**NOTE** Pin 1 is the top left one, marked with a white dot!
> 5 votes

# Answer
If you have another, working, Uno, and both have socketed microcontroller chips, you could use the known board to program a test sketch onto the unknown board's chip, put it back on the unknown board, and run it.

I like the following (pseudo-coded) test sketch for quick-checking my hand-built boards; it's just as handy for testing an unknown factory-built one. It's not an exhaustive test, it just checks for basic digital I/O, serial I/O, and shorts or opens:

```
forever,
  for each digital I/O pin:
    write high;
    delay 100ms;
    write low;
  end;

  write "Hello, World!\n" to serial output;
  while serial character available,
    write character to serial output;
  end;
  write "\n" to the serial output;
end;

```
* A test LED - an LED with its resistor soldered to it - connected between any I/O and ground should blink every 2 seconds. If it doesn't, that pin may have failed or have a bad connection.
* Two test LEDs connected to numerically adjacent pins (they may not be physically next to one another) should blink in sequence. If they blink together, it indicates a short, probably a solder bridge, between them.
* The terminal should say "Hello World!" every two seconds. If not, that pin or the FTDI cable or on-board USB/Serial chip may have failed.
* Type something on the keyboard and it should be repeated back to the serial terminal (if the previous test passed). If not, again that pin or the FTDI cable or on-board USB/Serial chip may have failed.
> 2 votes

---
Tags: arduino-uno, testing
---


# Question
Title: How do I even out Infared distance sensor readings?
I am using a standard infared distance sensor on a small robot and i am trying to even out the readings on it so it is more accurate. The readings are very sporadic and often take huge jumps in the distance. Is there a method of programming or circuit design that might make this easier to use? I'm trying to keep my robot from running into things.

# Answer
> 2 votes
Wikipedia has a page on moving averages: http://en.wikipedia.org/wiki/Moving\_average

I'd suggest at first try an exponential moving average:

> average = a * sample + (1 - a) * average

Experiment with different values of a (with 0 \< a \<= 1).

The smaller a is, the smoother the curve, but also the longer (more iterations) it takes for an actual change in the input to be reflected in average.

# Answer
> 2 votes
IR sensors are very erratic in my experience. The best way is to take an average of multiple sensor readings. The number of readings required can be found by experimentation.

**Example Sketch** (Source)

The example below should be similar, and a good start for your model of IR sensor.

```
/*
 Sharp GP2Y0A21YK0F infrared proximity sensor (#28995)
 Collects an average of five readings from the sensor and displays the
 resulting value about every half second.

 See the SharpGP2Y0A21_Simple demonstration for additional usage notes,
 including connection diagram.

 This example code is for the Arduino Uno and direct compatible boards, using the
 Arduino 1.0 or later IDE software. It has not been tested, nor designed for, other
 Arduino boards, including the Arduino Due.

*/

const int irSense = A0;          // Connect sensor to analog pin A0
int distance = 0;

void setup() {
  Serial.begin(9600);            // Use Serial Monitor window
}

void loop() {
  Serial.println(irRead(), DEC); // Call irRead function to read sensor
                                 // Print value in Serial Monitor
  delay(250);                    // Wait another 1/4 second for the next read
                                 // (Note: Because of delays built into the
                                 //   irRead function the display of values will
                                 //   be slower than in the SharpGP2Y0A21_Simple
                                 //   sketch
}

// Take multiple readings, and average them out to reduce false readings
int irRead() {
  int averaging = 0;             //  Holds value to average readings

  // Get a sampling of 5 readings from sensor
  for (int i=0; i<5; i++) {
    distance = analogRead(irSense);
    averaging = averaging + distance;
    delay(55);      // Wait 55 ms between each read
                    // According to datasheet time between each read
                    //  is -38ms +/- 10ms. Waiting 55 ms assures each
                    //  read is from a different sample
  }
  distance = averaging / 5;      // Average out readings
  return(distance);              // Return value
}

```

# Answer
> 2 votes
Averaging is a very good technique for improving noisy data, provided you have a “nice” noise. “Nice” meaning that you never get “atypical” data points, i.e. the error of any given data point is of the order of the “typical” error amplitude. If you have for instance additive white Gaussian noise, then it can be shown that averaging is in some way the “best” way to clean your data.

However, if you have big sporadic errors, then **averaging is not a good solution**. This is because you will have to average *a lot* of samples in order to smoothen out a single big error... and the more samples you average, the more chances you have to get *another* huge error that will ruin your average. Of course, averaging will somewhat improve things, and it is better than no smoothing at all, but there are better options.

The solutions to this problem lye in the realm of robust statistics. It may look like hairy math, but there is actually a very simple smoothing filter that is far more robust than the average: it's called the median. The idea is quite simple: you sort your list of samples from smallest to largest, then you pick the one sample that ends right in the middle of the sorted list. Unlike the average, this filter is completely insensitive to samples carrying *huge* errors, as long as the *majority* of samples are reasonable.

Here is an implementation of a simple moving-median filter based on the standard libc’s `qsort()`. It assumes samples have `int` type, but you can change it to whatever numeric type you want. You can also change the filter length: longer lengths provide more robustness against series of consecutive bad samples, at the cost of more filter delay, more memory, and more processing time.

```
/*
 * Comparison function for qsort(): return an integer "less than, equal
 * to, or greater than zero if the first argument is considered to be
 * respectively less than, equal to, or greater than the second."
 */
int compare(const void *pa, const void *pb) {
    int a = *(int *)pa;
    int b = *(int *)pb;
    return a<b ? -1 : a>b ? +1 : 0;
}

#define FILTER_LENGTH 11  // length of the median filter, should be odd

/*
 * Input: raw sample.
 * Ouput: filtered sample.
 */
int median_filter(int data) {
    static int input_buffer[FILTER_LENGTH];
    static int input_index;
    int sorted_buffer[FILTER_LENGTH];

    // Store the current data point.
    input_buffer[input_index] = data;
    if (++input_index >= FILTER_LENGTH) input_index = 0;

    // Sort a copy of the input buffer.
    for (int i = 0; i < FILTER_LENGTH; i++)
        sorted_buffer[i] = input_buffer[i];
    qsort(sorted_buffer, FILTER_LENGTH, sizeof *sorted_buffer, compare);

    // Return median.
    return sorted_buffer[FILTER_LENGTH/2];
}

```

As I did not explicitly initialize the filter memory, this will output zeros the few first times it is called. I encourage you to try this filter and compare against an exponential moving average, and only then decide which works best for you.

# Answer
> 2 votes
The Sharp GP... infra red proximity sensors can produce noisy output sometimes. This is partly caused by the fact that they work by repeating a brief, powerful IR pulse.

So - the very first tweak I would suggest when using any of these sensors is to try a cheap 10 micro Farad electrolytic capacitor on the 5V power connections, reasonably close to the sensor itself. This is mentioned on some of their datasheets, but gets forgotten...

# Answer
> 0 votes
My solution keeps reading for cycles (10 times) and calculate average it.

Be careful voltage output of many surface NOT same.

---
Tags: sensors
---


title: HIGH and LOW reversed

text:
# Question
Title: HIGH and LOW reversed
i've got a seven-segment-display on my arduino-nano and want to write some numbers on it. The problem is that HIGH and LOW seems to be reversed. If the output should be

```
0

```

it displays

```
-

```

I could solve this, replacing all HIGH and LOW through HIGHX and LOWX, and defining them reversed:

```
 #define HIGHX 0x0
 #define LOWX 0x1

```

but this is reversed and not a *good* solution...

The wiring is correct like this (just GND not connected):

But if i connect the GND, the hole display isn't showing something anymore.

# Answer
With the given schematic both your logic for segments and digits should be active high, so it looks like you made a mistake. Especially because you say it doesn't work anymore when you connect ground. Check that you have the right transistor and that it's connected correctly: Emitter should go to ground, collector to the display's common cathode. (Check that your displays are common *cathode*!)

It's not a good idea to define some version of high as low, that's only confusing. Instead name the signals:

```
#define DISPLAY_SEGMENT_ON HIGH
#define DISPLAY_DIGIT_ON HIGH

```

The image can be found at several places on the Internet, so I guess you didn't draw it. This is a **common cathode** display, and the transistors are **NPN** types. If your displays are **common anode** then the whole thing flips upside-down: The Ground rail becomes Vcc, and the NPN transistors should be **PNP** types. Then you will indeed have inverted logic, and you should define:

```
#define DISPLAY_SEGMENT_ON LOW
#define DISPLAY_DIGIT_ON LOW

```
> 1 votes

# Answer
reversing a boolean can be done using the `!` operator. So doing something like `print(!true);` will print `false` (or 0, I'm not sure.)

And you make a wrapper or class to abstract this specific/odd behaviour.

Like:

"setLedPin(pinnr,state){digitalWrite(pinnr,!state)} //The pins are inverted, LOW is ON, HIGH is off, this piece inverts it."

You may even make a class for these segment displays and pass to your constructor if it's an inverted or "normal" one. Or even make two classes that implement the same interface, but for such a small difference, that shouldn't be necessary.
> 0 votes

# Answer
If your display is a common anode type, the following will happen.

Suppose you put a HIGH on D12, and LOW on D2 then current will flow from D12 through the base-collector diode of Q1, through the LED and out D2 to ground.

If you now connect Gnd to ground wihout changing anything else, the current from D12 will flow through the base-emitter diode of Q1 to ground and not through the LED.

So the display is probably of the wrong type for your design.
> 0 votes

---
Tags: arduino-nano, display
---


title: How to draw a bitmap on a tft display?

text:
# Question
Title: How to draw a bitmap on a tft display?
I'd like to print a bitmap on my TFT.

I setup my screen with this library: http://forum.arduino.cc/index.php?topic=292777.0

It is like the Adafruit\_GFX library (only a little bit changed). Everything works.

With the tool Img2Code I converted my image into a bitmap.

```
void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                               const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

```

How to include this code and print the bitmap on the tft?

# Answer
> 2 votes
As the function prototype you have show suggests, the data needs to be in a uint8\_t array format.

```
void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
            const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

```

So your array data would look like:

```
const uint8_t myBitmap[] = { 0xff, 0xff, 0xc0, 0x00, 0xc0, 0xff,
    0xc0, 0xc0, 0xff, 0xff, 0xde, 0xad, 0xbe, 0xef,
    .... etc ....
    0xff, 0xff, 0xff, 0xff, 0xff
};

```

You then call the function with the needed parameters:

```
tft.drawXBitmap(10, 20, myBitmap, 100, 80, 0xFFFF);

```

That is assuming you want to place it at (top left corner) 10,20 and the bitmap is 100x80 pixels in size. It will draw it in white (0xFFFF).

---
Tags: arduino-mega, display
---


title: Arduino Tre, will it ever come out?

text:
# Question
Title: Arduino Tre, will it ever come out?
Does anyone have any information other than "coming soon" about the Tre?

* Could the Tre be stuck in development hell?
* Perhaps the new partnership with Adafruit could expidite things, seeing as Ardiuno (.cc) was touting the Tre to be the first Arduino made in the USA?

I'm just giddily awaiting its arrival, so I'm just wondering!

# Answer
The latest news from Arduino that I can find is in their blog archive that the second round of beta testing is out.

The mentioned this:

> When is the Arduino TRE going to be finally on the market? The board is ready, but we don’t have a final release date yet because we are still figuring out some manufacturing matters. We’ll keep you posted!

I'd imagine that the Arduino LLC vs Arduino SLR legal issue is also delaying the production.

Other than that, speculation is all that we know.

P.S: it's still spring until Sunday, June 21! :-)
> 0 votes

---
Tags: hardware
---


# Question
Title: How to define function/macro so it is accesible throughout various cpp files
I recently came across this nice `SerialPrint()` implementation:

```
void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

```

I want to use it in my more complex projects to save precious RAM space.

This works really well when I have just one \*.ino file where I'm using the SerialPrint() function. When I try to use it in my more complext projects, which consist of a central \*.ino files and several *.cpp/*.h files (mostly one cpp/h pair per class). The problem is if I put the code below into the \*.ino file, it will not be known inside any of the \*.cpp files. The compiler is not complanining, but I'm never seeing the serial output of my code.

Any ideas how to fix it? I've tried putting this code in a central global.cpp/h file which I include everywhere, but it does not seem to work (no output on serial).

Thanks in advance!-

# Answer
Have you thought of turning it into a small library?

libraries/StreamPrint/StreamPrint.cpp:

```
#include <StreamPrint.h>

void StreamPrint_progmem(Print &out,PGM_P format,...)
{
  // program memory version of printf - copy of format string and result share a buffer
  // so as to avoid too much memory use
  char formatString[128], *ptr;
  strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem
  // null terminate - leave last char since we might need it in worst case for result's \0
  formatString[ sizeof(formatString)-2 ]='\0';
  ptr=&formatString[ strlen(formatString)+1 ]; // our result buffer...
  va_list args;
  va_start (args,format);
  vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args );
  va_end (args);
  formatString[ sizeof(formatString)-1 ]='\0';
  out.print(ptr);
}

```

libraries/StreamPrint/StreamPrint.h:

```
#include <Arduino.h>

extern void StreamPrint_progmem(Print &out,PGM_P format,...);

#define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__)
#define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__)

```

Then in your code, wherever you want to use it:

```
#include <StreamPrint.h>

```

You can read more about writing libraries here: http://www.arduino.cc/en/Hacking/LibraryTutorial
> 3 votes

---
Tags: arduino-uno, programming, c++
---


title: Set dynamically hour - DS1307

text:
# Question
Title: Set dynamically hour - DS1307
I want keep my RTC1307 always updated with my server, so I created this code to first search the time on the server then passes to getServerTime() function to divide it and set in the RTC. I use the rtc.adjust() to adjust my watch.

**Problem**: My watch is getting wrong, this is set **2165/165/165 165:165:85**. I think the problem is in defining the time in rtc.adjust(), I'm going as follows:

```
//tempDate -> May 19 2015
//tempHour -> 09:25:14
rtc.adjust(DateTime(tempDate, tempHour));

```

Does anyone know the cause of this error?

```
#include <Ethernet.h>
#include <SPI.h>
#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 rtc;

byte server[] = { 192, 168, 0, 8 };
byte ip[] = { 192, 168, 0, 237 };
byte mac[] = { 0xDE, 0xAD, 0xAD, 0xEF, 0xFE, 0xED };

void setup() {
    Ethernet.begin(mac, ip);
    Serial.begin(9600);
}

void loop() {
    getServerTime(getSiteData());
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
    delay(5000);

}

char * getSiteData()
{
    EthernetClient http;
    unsigned char startRead = 0, i = 0;
    char inString[50];

    if (http.connect(server, 80)) {
        http.println("GET /util/date.php HTTP/1.1");
        http.println("Host: ");
        http.println("Connection: close");
        http.println();

        while (http.connected()) {
            while (http.available()) {
                char c = http.read();

                if (c == '<' )
                    startRead = 1;

                else if (startRead) {

                    if (c != '>') {
                        inString[i] = c;
                        i++;
                        inString[i] = '\0';
                    } else {
                        startRead = 0;
                        http.stop();
                        http.flush();
                        return inString;
                    }
                }
            }
        }
        Serial.println(inString);
        http.stop();
        http.flush();
    }
    else
        Serial.println("Tentativa de conexão falhou. Sem internet ou servidor inacessivel");
}

//May 19 2015-09:17:24
void getServerTime(char* siteData)
{
    char *tempDate, //May 19 2015
        *tempHour; //09:17:24

    tempDate = strtok(siteData, "-");
    tempHour =  strtok(NULL, "-");

    rtc.adjust(DateTime(tempDate, tempHour));

}

```

# Answer
> 0 votes
The numbers you are reporting are very familiar to me. They are telling me that it is not possible to obtain the time from the RTC chip.

You are getting the time from your server, and as long as the string is actually what you think it is, then the values should be fine. This snippet works perfecty:

```
#include <RTClib.h>

char siteData[] = "May 19 2015-09:17:24";

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

    char *tempDate = strtok(siteData, "-");
    char *tempHour =  strtok(NULL, "-");
    DateTime now(tempDate, tempHour);

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
}

void loop() {
}

```

So it must be in the passing of the data through the RTC chip that is failing.

Check that the chip is actually wired up properly, is running, and is responding normally before you try adding in the code to set the time from the server.

---
Tags: arduino-uno, ethernet, rtc
---


title: Data Logging GPS with Arduino

text:
# Question
Title: Data Logging GPS with Arduino
I am working on a project for my final in a first year programming course at my high school. I would like to make an Arduino based data logging device that I can bring with my on the mountain biking trails around where I live to create a map. I have found a lot of great sources online but I do not have a small budget. I have an Arduino Uno and a breadboard. My first question is whether it is easy to interface between an Uno and my phone for data logging, or if it would just be easier to buy a microSD card shield? And I need help finding a GPS unit. I have no preference and size is not really a problem. I just need to know how to interface with the Uno. Also if you have any links to other sources I can use that would be greatly appreciated!

# Answer
> 1 votes
I've been looking at the same problem, and there is a lot of new stuff now that may still count as a DIY project, but cut out a lot of the leg-work.

On kickstarter there are a lot of new boards that can make it easy: Here is a ready to go GPS tracking band: https://www.kickstarter.com/projects/blipperbands/blipper-bands-safety-wherever-you-go?ref=nav\_search

Spark-IO has a board that gives you 20,000 messages per month, so you could use it instead of a cellphone to send out the data. https://store.particle.io/?product=particle-electron

U-Blox makes gps higher-end consumer GPS units that are used in autonomous drones. There are also a lot of instructables that show how to do the GPS datalogging with while building a drone. These would be small enough and light enough to use while cycling.

# Answer
> 0 votes
first questions; is it easy? Very, do it all the time. But easy to me (30+ year programmer with some embedded experience) may not mean easy to you. Seek out a local make group or friend to help guide you if you are just starting out. I would look into a simple bluetooth adapter for the arduino, they are cheap, $5 in some places like eBay. Then find or write a phone app that log bluetooth.

second question; Pick a GPS unit from SparkFun or somewhere like that.

If it is a serial unit it may need need some sort of FTDI adapter, which can sometimes be just a cable (and it might not need it, depends). You really need to match the GPS with the appropriate way to hook it up and there are so many options I don't think someone will be able to cover them all. Depending on which arduino, you will use softSerial, since the hardware serial pins are probably being used by the bluetooth adapter. BTW, did this exact thing for a robot project not too long ago, work ok. I used XBees instead of bluetooth. If I did it again I would try Bluetooth as the XBee reliability wasnt very good.

Another type of connection is called I2C, and that would attach directly to Arduino UNO SDA/SCL (pins A4/A5 I think).

In both cases there are 3V and 5V devices and again you need to match things up on your own.

Now, to spoil your fun, you realize if you are carrying a phone and it is on, you are already being tracked and they are ways to view the history on the web?

In some cases it is easy to find (used to be called google tracks I think). Others are a little harder and I wont give out details, but I used to follow my ATV excursions on fire roads in the mountain all the time after I got back home.

http://junkee.com/google-maps-has-been-tracking-your-every-move-and-theres-a-website-to-prove-it/39639

Update: gps (https://www.sparkfun.com/products/11571) -\> softSerial on UNO -\> tx/rx -\> bluetooth (http://www.ebay.com/itm/New-Slave-UART-Wireless-Bluetooth-Transeiver-RF-Module-Serial-for-Arduino-AVR-/121643226124) -\> phone logging app.

I picked that bluetooth because it claims it can do 3.3v-6v - the others I looked at said 3.3V but I bet they are all the same. Technically, you probably do not even need the arduino in the middle, but said you wanted to learn.

---
Tags: arduino-uno, gps, datalogging
---