title: Making analog telephone calls?

text:
# Question
Title: Making analog telephone calls?
How can we make the Arduino board interact with old, analog telephone, and to make phone calls?

I guess it involves connecting the board to the telephone with some specific cable (how it's called?)

In addition, I assume it will require us to use the telephone low-level dialing protocol (in order to actually interact with the phone and to send commands). Where can I read about it?

Is there a reason to concern about conversation between the digital/serial board and an analogous device?

By the way, I've read that analog telephones have relatively high voltages that can easily damage the board. I'd love to get any information about things like this, related to connecting Arduino to analog telephones, in order to know about such issues and about what to be concerned and to explore.

Thanks a lot!

# Answer
Buy an external voice modem with a RS-232 connection. Connect it to a RS-232C shield. Use AT commands to dial numbers and pick up calls. Use voice AT commands to transmit or receive audio.

Never attempt to connect the telephone line directly to an Arduino since, yes, you will fry it. The voltage is all wrong in the first place, and goes even higher when the phone line rings.
> 5 votes

# Answer
Connect a microcontroller to a telephone line is a rather technical task and requires knowledge concerning the operation of the line, but it is not an impossible task, although it can be dangerous, and sample some nasty shocks if you're not prepared for such work.

Initially you should build a rectifier circuit, mainly for its polarizing power circuit, since you do not know which is the antibody positive your telephone line but know that tensions are measured inversely ie, when measured with respect to ground (GND) the measures will be negative, this is because it was discovered that the poles of the batteries used to be gnawed less well when connected to the system.

A second step is you develop a small coupler to avoid connecting your circuit directly to the telephone line. For this you can use a pair of low-pass filters, which are placed at each connection point of the line after the bridge rectifier, and the downside of the bridge rectifier is connected to ground your circuit with this filter. And the plus point is connected to a PWM output of your controller.

Other important information you can not connect the PWM port directly to this filter, because the voltage levels in the telephone line are quite different, namely:

* When the line rings you get a voltage exceeding 60V oscillating above 20Hz.
* When the line is in standby mode it remains between 30V and 48V as your carrier and region.
* When the line is busy or because your circuit or another extension you will have a voltage between 6V and 12V.
* Already the audio modulation in their line occurs with peak 0,7Volts equivalent to 3dBm therefore its PWM output should give output like this.

To match the level of your line voltage with the telephonic system you can use a voltage divider which has an output of 0 to 0,7Volts ie when the door PWM pulse maximum output voltage of 5V should be 0,7Volts the divisor resistive. Another way is to use an operational amplifier having a gain reverse, thus reducing output. you can also use a optoacoplado circuit with 4n25 and thus polarize the phototransistor for such variation with the pulses in your diode.

Another important component in this circuit is a pair of diodes to be done clipping the signal, ie, as our voltage limit for audio is 0,7Volts after the filters put a couple of diodes between the positive and negative of your signal filtered in the bridge rectifier, so prevent signals above this level reaches the arduino when ouver noise on the line.

More Information: http://carlosdelfino.eti.br/WorkshopTelefoniaAutomacao/
> 3 votes

---
Tags: arduino-uno, serial
---


# Question
Title: Seeeduino V3.0 (Atmega 328P) and Rotary Angle Sensor Mystery Message
I am attempting to do a simple example with the Rotary Angle Sensor.

**Here is my development environment:**

**Board setup (Simple as can be single analog input):**

**Code:**

```
const int ROTARYSENSOR = A0;

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

    pinMode(ROTARYSENSOR, INPUT);

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

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

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

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

```

**Issue:**

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

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

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

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

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

```

Should be

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

```

And of course your posted code never reads the sensor...
> 2 votes

---
Tags: sensors, atmega328
---


# Question
Title: How to upload an arduino sketch from java / processing?
I'm trying to upload a hex file from Java/Processing but running into some issues. Here is my code so far, based on the Arduino IDE's upload verbose output:

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

    String s = null;

    try {

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

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

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

  }

```

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

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

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

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

avrdude done.  Thank you.

```

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

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

---
Tags: arduino-uno, avrdude, terminal
---


# Question
Title: Why does my dc motor immediately spin when connected to a 9v battery?
I've set up a DC motor connected to my Arduino Uno with the following layout. I'm using a 1.5V - 3V DC motor that was purchased from RadioShack.

Here is my code:

```
int controlPin = 9;

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

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

```

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

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

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

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

# Answer
> 3 votes
Your wiring diagram is a jumbled mess, and makes it impossible to figure out what's really going on.

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

Problems I see with your wiring diagram:

* You show pin 9 from the Arduino wired to the positive rail of your breadboard. If the positive rail is connected to a 9V battery, this will likely destroy pin 9 of your Arduino.
* You show the gate/base of your transistor wired to the positive rail of your breadboard. This would switch your transistor on constantly.
* You show the symbol for a MOSFET transistor, but the label on it lists it as a 222A, which is an NPN BJT, not a MOSFET.
* You don't show any wires connecting the left and right side rails of your breadboard.
* You're using a row of your breadboard as the ground rather than the rails.

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

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

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

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

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

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

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

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

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

```
digitalWrite(controlPin, LOW);

```

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

# Answer
> 2 votes
You need to turn the transistor 180 degrees (assuming you are indeed p2n2222a).

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

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

---
Tags: arduino-uno
---


# Question
Title: Visual clock with millisecond display refresh rate
I need to create a millisecond capable visual clock - I will use the clock for visual frame synchronization of multiple cameras. I found this project but it seems to use a LED display that only has resolution of one 1/100th of a second. Not sure if the digits can be shifted to show milliseconds.

I guess I need to use LED instead of LCD display because of the ms refresh rate? Can someone help with my project please? I am a SW programmer and have zero experience in HW programming. So I am new to Arduino too - I have not done any project at all yet. I do own neither Arduino nor LED display.

Thanks!

# Answer
> 7 votes
You need to define the parameters of the problem more clearly.

First, and most importantly, what is the shutterspeed you'll be using? If it's longer than 1 ms, then you can't use a 7-segment display to show the MS count, since the camera shutter would be open for multiple values.

Even if your shutterspeed is a single MS, your shutter won't be synchronized with your timer, so sometimes the shutter will be open when the display switches. That can even happen with the seconds digit of your time display.

If you're using a video camera, assume the frame rate is 60 fps, which gives a likely shutterspeed somewhere around 16.6 ms. That's way too long to display ms time values using 7-segment displays.

The ring of LED idea is good, but I would tweak it.

Here's what I would do: Build an LED clock to display whole number seconds. Don't multiplex, use latches and drive each 7-segment display constantly. (There are off-the-shelf CMOS chips that are latching 7-segment drivers.) If you only care about the 1s digit of the second value, only use 1 7-segment display. That will make things easier to wire.

Use 3 rings or columns of 10 LEDs for the MS display: tenths, hundredths, and thousandths. I would lean towards using columns since it would be visually easier to read.

The display will show your seconds as numbers, and 3 columns of 10 LEDs, showing the sub-second time range in 10ths, 100ths, and 1000ths. If the shutter opening spans multiple MS, as it will very likely do, all the LEDs that represent the sub-second time will be lit in the image, so you will get a nice clean visual image of the time SPAN that the shutter was open (All the LEDs from the start to the end of the shutter opening will be lit.)

You could drive the 3 columns of LEDs using 3 4017 divide-by-10 counters. These chips have both a 1-of-10- output, which will drive an LED, and a count/10 output, which would feed the next stage.

Write Arduino code that generates a short positive pulse every MS. Feed that into the clock input of the 4017 driving the thousandths digit. Feed the out/10 output of that chip to the clock input of the hundredths 4017, and the output of the hundredths 4017 into the clock input of the tenths 4017.

You can drive the whole ms display with 2 Arduino lines: The ms clock, and a reset line tied to all your 4017 counters' reset lines. To start timing, first pulse the reset line to zero them all out, then start your ms clock.

My CMOS cookbook doesn't say how much current the 4017 will put out to it's 1-of-10 outputs, but I bet it's enough to drive a display LED directly. You could wire all 10 LEDs in each column as common cathode, with a single current limiting resistor between each column's common cathode and ground.

You could probably set up a timer pin on the Arduino to generate a millisecond pulsed output, but that's not something I've learned how to do yet.

Occasionally you'll get a whole second 7-segment display with 2 different values captured in a frame, but that will be rare, and you will be able to figure out what happened from the frames immediately before and after it. (Previous frame shows a 5. Current frame shows a 5 and a 6 superimposed, so it's a mess. Conclusion, this frame shows the end of second 5 and the beginning of second 6.)

# Answer
> 3 votes
I think Duncan C's 'user interface' is excellent. It is clean, simple and elegant.

Using individual LEDs is much better than digits. IMHO it is much more flexible, and avoids the ambiguity of digits. +1 for the concept.

However, I would make it 'softer', and use a lot fewer components.

By going 'softer' you could have more flexibility, which would give you the ability to expand the useful resolution of the 'clock'.

Duncan C made a very important point that digits are useless if a digit changes during the photograph. However, that is still a potential problem with the three lines of LEDs. When the exposure time is longer than the duration of the 'lower digit' line of LEDs, information is lost.

Certainly Duncan C's design could be speeded up or slowed down to adjust for that, but it has a built in resolution limit because it counts in 10's. Imposing the digital idea of '10' on an analogue system (which is similar to a child's abacus) loses some of three inherent flexibility in the fundamental superiority (in this case) of an analogue display. I suggest making it 'soft' so that the system can be 'tweaked' in software after the electronics are completed.

Instead of fixed function decade counters, use shift registers . Then there is complete flexibility to change the 'user interface' in software.

To reduce the number of components use shift registers *designed to drive LEDs*.

For example, Texas instruments make many LED-drivers. The lowest cost ones, in Dual-In-Line packages (which can be used in a breadboard, and so would be easier to prototype) that I found on RS were TLC5916/TLC5917. Each device drives 8 LEDs, so Duncan C's design would use 4. This is *more expensive* than decade counters. However, I think the cost (about 5GBP) may be worth it.

One benefit is they are 'constant current' drivers, and so eliminate the current-limiting resistors on each LED. Each device uses one resistor to program the current for all 8 LEDs. That won't save much money, but it will save a lot of wiring.

These shift registers are fed a pattern of data bits, one at a time, using a second 'clock' signal to tell the shift-register when the data bit is valid. Toggling the clock loads the data bit. So you could cascade them, end-to-end, exactly like cascaded counters. To reduce the CPU load, the input to the chain of shift registers could be loaded autonomously, 8 bits at a time by using the SPI peripheral in the Arduino.

Alternatively, you could use 4 pins to load data simultaneously, with one pin driving a shared clock. Those shift registers can operate much faster than even Arduino assembler (upto 30MHz/bit). So this needn't take much time.

The outputs of the shift registers do not change until a further signal is sent. Then they all change output simultaneously. So your cameras won't be confused by seeing the data being loaded.

So there is more software complexity than cascaded counters. However, there is no constraints on what data they show. For example, you might decide that you would like 20 LEDs worth of resolution, so that cameras have a wider exposure time and the frames can still be synchronised or 'positioned' relative to one another in time.

Anther advantage of this 'soft' behaviour is, you could add lots more LEDs and get pretty much any resolution you might need, using exactly the same hardware technology.

This approach shares an advantage of Duncan C's design. Time is indicated by discrete points of light, and not shape. So it should be relatively straightforward to use image processing to process images. That might be very important if the cameras are video cameras.

Edit:
To clarify a few points.

It is purely software which determines the behaviour of the LEDs in a shift-register based approach. Hence it is practical and straightforward, to simulate decade counters. So the 'user interface' can not be worse.

The complexity of a chain of shift-registers is the same as decade counters, if you want to use them that way. However for a few pins more, the shift registers could be loaded independently, which might have some benefits.

Using constant current LED drivers reduces the number of resistors to wire by a factor of 8. TI and others sell devices with 16 and 24 LED drivers, so the number of packages might be reduced.

The decade counter has a built in restriction. Not suprising, it gives no more than 10% resolution. However if you need 5%, it can't do it.

The shift-register-based electronics could emulate a 'clock face', so if 5% is needed, use 20 LEDs for that part. If 1% is required, add some more shift registers and LEDs

***Summary***:
Duncan C's concept of using an 'analogue abacus' display is, IMHO, a more robust user interface than LED Arabic digits.

However, IMHO a hard-wired implementation using decade counters is an unnecessary restriction, limiting resolution. Shift registers make the display 'soft'. Wiring up shift registers is the same complexity as decade counters. Using LED drivers, saves a lot of wiring.

# Answer
> 1 votes
Assuming you camera's shutter is fast enough to capture a display updating every millisecond:
Get individual digit seven segment (LED) displays. The ones with multiple digits together are usually multiplexed and that might not work for your application(the multiplexing frequency would have to be higher than 1000 Hz or only one/some digits would be visible at a time). Using single digit displays, hook up each digit to a shift register such as the 74HC595. Then you only need two Arduino pins to control each digit (Data and clock, latch clock can be shared by all the shift registers). Use protection resistors for each individual segment diode and mind the current limit of the shift register when lighting all segments.

At 16 MHz you have 16000 instructions per ms so that shouldn't be an issue.

I don't know too much about LCD displays, but with LED's and a latching shift register transitions should be update pretty much instantaneous(from a millisecond perspective).

---
Tags: led, timers, millis
---


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

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

What could be wrong here?

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

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

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

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

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

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

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

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

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

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

---
Tags: i2c, arduino-leonardo
---


title: OBD Connector to Arduino

text:
# Question
Title: OBD Connector to Arduino
I bought an OBD connector from Sparkfun to try to connect to my vehicle via arduino.

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

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

# Answer
> 1 votes
I briefly read up on this subject and I found out this:

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

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

*More on this topic...*

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

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

---
Tags: hardware
---


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

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

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

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

Many thanks in advance.

edit: Update boot loader size for different boards

# Answer
You'll need to use an ISP programmer with avrdude. Perform a chip erase and then unprogram the `BOOTRST` fuse in the high fuse byte.
> 2 votes

---
Tags: bootloader, atmega328
---


# Question
Title: Does ATMega 328/2560 chips support JTAG-type programmer and hardware debugger?
As stated in www.Arduino.cc FAQ, "Can I use an Arduino board without the Arduino software? Sure. It's just an AVR development board, you can use straight AVR C or C++ (with avr-gcc and avrdude or AVR Studio) to program it."

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

Many thanks in advance.

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

---
Tags: arduino-uno, avrdude, debugging, avr-gcc
---


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

# Answer
Short answer: No; From the atmega328's data sheet (though it applies to all AVR's):

> AVR uses a Harvard architecture – with separate memories and buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory
>
> ...
>
> Program Flash memory space is divided in two sections, the Boot Program section and the Application Program section. Both sections have dedicated Lock bits for write and read/write protection. The SPM instruction that writes into the Application Flash memory section must reside in the Boot Program section

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

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

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

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

---
Tags: arduino-uno, sketch, compile, flash, eeprom
---


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

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

# Answer
> **Can** two LEDs attached to different pins share their resistor?

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

Your resistor act here as a current limiter, say to *3mA*

If you light one LED at a time, you give 3mA to *that* LED If you light 2 LEDs, you give 3mA for both of them (more of less 1.5mA each) If you light 3 LEDs, you give 3mA for all of them (*on average* 1mA each)
Things are even a little bit more subtle, as different LED might have different forward voltage, so one LED might very well drain 10% more current than an other.

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

---

As an edit to that answer, there is one case I might consider that arrangement for "multi-LED lighting". This is if you are multiplexing your LEDs

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

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

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

A separate resistor per LED is probably best.
> 19 votes

---
Tags: led, resistor
---


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

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

Did I miss anything in the followings?

I tend to believe that it is possible as

a) same ATMega328 chip is used in both board

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

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

Many thanks in advance

# Answer
> 1 votes
You can just flash the newest optiboot\_atmega328-Mini.hex. That one should also be only .5k in size, as it starts writing at the same address (`7E00`).

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

`3F00` is exactly the start of the `Boot Loader Flash Section` when you have selected a 256-words `Boot Size` (page 291 of the datasheet). 256-words is the 0.5kb you want.

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

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

---
Tags: arduino-uno, bootloader, arduino-pro-mini
---


title: Arduino Custom Function Problem

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

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

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

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

int CS = 53;

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

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

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

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

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

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

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

```

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

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

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

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

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

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

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

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

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

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

```

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

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

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

Thank you.

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

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

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

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

...

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

...

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

```

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

---
Tags: programming, atmega328, sd-card
---


title: Arduino Leonardo timing Inconsistency

text:
# Question
Title: Arduino Leonardo timing Inconsistency
I've got a question regarding the use of Millis() on a Leonardo Arduino. I'm currently using it to time 4 seconds elapsed while sending a serial message every second. These messages play a sound. On the fourth message the sound is different to signify that the Arduino has started an event.

I'm running into an issue where the sounds are **occasionally** being played sporadically without a consistent 1 second between them. I'm wondering if there is a better way of doing what I'm doing? During the timing the Arduino is doing nothing else, and the receiving computer is also generally not doing anything taxing. Is this even an issue from the Arduino side? My receiving program is written in C# using System.IO.Ports.SerialPort.

The reason this is done through Arduino is because the event started by the Arduino needs to correspond exactly to the sounds, though if this remains unresolved I will need to rework this.

Edit: Code as requested.

```
void setup()
{
    //Setup Code
}

void loop()
{
    //Code that handles other serial messages and various states
    if (isSpecificState == true)
        onSpecificState();
}

void onSpecificState()
{
    //Setup to handle state

    long holdStart = millis();
    long holdDuration = 0;

    boolean print1 = false;
    boolean print2 = false;
    boolean print3 = false;
    boolean print4 = false;

    while(holdDuration <= 4000)
    {
        if (holdDuration >= 4000 && !print4)
        {
            Serial.println("tt_sound:2");
            print4 = true;
        }
        else if (holdDuration >= 3000 && !print3)
        {
            Serial.println("tt_sound:1");
            print3 = true;
        }
        else if (holdDuration >= 2000 && !print2)
        {
            Serial.println("tt_sound:1");
            print2 = true;
        }
        else if (holdDuration >= 1000 && !print1)
        {
            Serial.println("tt_sound:1");
            print1 = true;
        }
        holdDuration = millis() - holdStart;
    }

    //Handle state
}

```

As I mentioned in the comments, the Arduino is doing nothing else while the timing is happening.

# Answer
**Thoughs:** Unfortunately I have been unable to get to the bottom of this issue. I noticed the problem tends to happen the first time the interaction starts after the computer and Arduino are idle.

Without knowing too much about how the serial communication is built I'm guessing that without traffic the connection is put to sleep, or generally inactive, and the sound delay is a result of the connection needing to re-initialize or something of that nature. I cant recall a time when the issue occurred and I had a recent correct previous interaction. Once it works any immediate retrial will also behavior correctly.

**Solution:** I have since moved my timing/sound playing component within my C# app. The Arduino now signals the start of the timer, and then end of the timer with an immediate start to my event.
> 0 votes

# Answer
There is only a very slight chance that you meet the `holdDuration >= 4000` condition in the while loop. Only when holdDuration will be exactly 4000 the while loop will be executed AND the subsequent test in the if statement will pass.

The serial print commands can easily take long enough to have `millis()` jump from a number less than 4000 to a number higher than 4000 in a single pass of the while loop.

To prove this assumption, increase the while test to `holdDuration <= 4100` and see if the intermittent effect goes away.
> 1 votes

---
Tags: serial, arduino-leonardo, time
---


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

# Answer
These steps will allow your Android device to function as an Arduino Terminal.

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

---
Tags: android
---


# Question
Title: Which wireless technology should I use for medium range, many to one, bidirectional communication?
Some clients, let's say 5 \<= x \<= 10, have to send information wirelessly to a server. Transmission does not need to be reliable (ACK).

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

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

Thoughts?

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

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

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

Down sides:

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

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

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

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

---

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

---
Tags: wifi, bluetooth, rf
---


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

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

```

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

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

example:

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

```

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

---
Tags: avr-toolchain
---


# Question
Title: ArbotiX-M Problem uploading to the board
I have an ArbotiX-m Arduino board, and have followed the setup guide on Trossen robotics all the way to the 5th step. I have a Mac running OS X 10.10 and use Arduino 1.0.5. I installed the necessary drivers and copied the files to the Sketchbook directory. When I try to load the sample ArbotiXBlink program:

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

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

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

```

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

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

```

Any ideas?

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

# Answer
> 2 votes
I figured why my board wasn't responding! Apparently, the power pin was connected to the 5V supply instead of usb. Silly me!

---
Tags: avrdude, mac-os
---


# Question
Title: Getting a random number for electronic dice
I am making a "Electronic Dice".

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

My problem is getting a random result on the output.

```
int die_face = 1;

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

    die_face += 1;
}

```

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

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

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

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

# Answer
First of all, look at this line of code:

```
if (analogRead(BUTTON_PIN) == HIGH)

```

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

From the Arduino Source:

```
#define HIGH 0x1
#define LOW  0x0

```

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

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

For your actual code, since you want it to be simple, I suggest you forget that code that you wrote. Arduino has a built in random library, which works unless you have some special need for a random number.

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

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

```

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

```
randomSeed(analogRead(A1));

```

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

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

# Answer
I've had better success with this version.

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

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

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

#define BUTTON_PIN  6  // Input

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

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

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

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

}

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

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

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

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

```
> 0 votes

---
Tags: arduino-uno, programming
---


title: Arduino yun as ssh client

text:
# Question
Title: Arduino yun as ssh client
Is it possible to set the Arduino Yun up as an ssh client? If so, how?

# Answer
You need to install package `openssh-client`: it's available in the package list. See this tutorial about how to install optional packages.

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

```
ssh user@your_other_host 'echo 1; echo 2'

```

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

---
Tags: arduino-yun, ssh
---


# Question
Title: YUN. How to reset the micro controller from linux?
As the title, I'd like to reset the Arduino sketch from the linux machine. Is it possible? how?

One solution could be to save the hex file inside the sd card and then upload it via the lua sketch but I think there is a smarter solution.

# Answer
Use command `reset-mcu`: it's a linux script that resets the 32u4 via GPIO
> 3 votes

# Answer
According to the Yun schematic, GPIO18 of the SoC is connected to the MCU reset circuitry. Toggling it should allow you to reset the MCU.
> 2 votes

---
Tags: arduino-yun
---


# Question
Title: MCU fuses used by Pro Mini and ATMega 2560 and power down
In context of Pro Mini and ATMega2560

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

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

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

Many thanks in advance

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

1) Online Fuse Calculator There are many others.

2) avrdude-GUI there are many others out there.

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

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

```

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

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

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

---
Tags: power, fuses
---


# Question
Title: How do I specify a working directory when saving to SD card?
I'm trying to datalog to a EyeFi SD card by writing to a file with a jpg extension. Here's that portion of my code so far:

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

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

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

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

```

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

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

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

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

From the Arduino Docs:

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

(emphasis mine)
> 5 votes

---
Tags: arduino-mega, sd-card
---


# Question
Title: Mega 2560 powered with 7V don't work correctly
I have an Arduino Mega 2560 with a GPRS seeedstudio shield and an USB Host CircuitsAtHome shield which work fine when powered with USB or with an adjustable voltage regulator set at 8V.

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

Why 7V fail while 8V is ok?

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

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

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

Arduino-Mega-2560-schematic: http://arduino.cc/en/uploads/Main/arduino-mega2560\_R3-sch.pdf
> 2 votes

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

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

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

---
Tags: arduino-mega, power
---


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

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

```

collect2.exe:

**TimerTwo.h:**

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

```

**TimerTwo.cpp:**

```
extern void TIMER2Services(void);

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

```

**TimerTwoTest.ino:**

```
volatile unsigned long burpCount = 0;

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

```

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

Please try this:

**TimerTwo.h**

```
#ifndef __TIMER_TWO_H__
#define __TIMER_TWO_H__

extern void TIMER2Services(void);

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

#endif // #ifndef __TIMER_TWO_H__

```

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

**TimerTwo.cpp**

```
#include "TimerTwo.h"

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

```

**TimerTwoTest.ino**

```
#include "TimerTwo.h"

Tmb2 tmb2;
volatile unsigned long burpCount = 0;

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

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

```

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

---
Tags: interrupt, timers, class
---


title: LCD display under power saving mode

text:
# Question
Title: LCD display under power saving mode
To make LCD display, Pro Mini and ATMega2560 to run on one set of battery for months, appreciate idea and comment.

Which LCD to use?

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

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

Under context of

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

Many thanks in advance

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

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

---
Tags: power, lcd
---


# Question
Title: Running an LCD keypad shield from a separate power source
I need to use a motor shield and an LCD keypad shield simultaneously hooked up to a single Arduino Mega Board. Since I can't physically stack them, I decided to reroute all the pins used for the LCD keypad shield. When I reroute all pins **except** the two power pins, the LCD and keypad work fine. But when I disconnect those 2 pins and connect them to any other power source than the Arduino Mega, it fails. The screen becomes either blank / jumble of illegible characters / brief moments of expected output followed by the same jumble.

This behavior is really strange since the power pins don't carry any information, they are just power sources. The LCD keypad shield shouldn't be able to discriminate whether the power is coming from the Arduino Mega or not - but it does. I checked with a voltmeter that all power sources I tried are DC 5V.

At first I thought this is because the `lcd.begin()` function is called only once, so I rewrote my code to re-initialize the lcd at every iteration. This doesn't solve the problem.

Here is a picture of the setup that works. (rerouting all pins *except* the power.) Ignore the location of analog input cable, since it doesn't do anything in the current code.

And one that fails. The only difference from above is the power source.

And my code.

```
#include <LiquidCrystal.h>

// select the pins used on the LCD panel
LiquidCrystal lcd(28, 29, 24, 25, 26, 27);

void setup()
{
  lcd.begin(16, 2);
  lcd.print("Hello World!");
}

void loop()
{
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Hello World!");
  delay(1000);
  lcd.setCursor(0, 0);
  lcd.print("Hello Again!");
  delay(1000);
}

```

Any suggestions?

# Answer
You can use a different power source, but the two circuit need to have a common ground, since all electrical signals are relative to ground. So connect a wire from GND on the LCD to GND on your Arduino and everything should work as expected.
> 1 votes

# Answer
Those little 16x2 LCDs are quite prone to power fluctuations. Even powered solely by an Arduino I've seen them run OK for a few minutes than turn to showing gibberish. Ensure you have good power connections, bring your power in as close as possible.

Maybe a capacitor across the power input to the display might help.
> 1 votes

---
Tags: power, lcd
---


# Question
Title: Parse data from sensor without delimeters
Im using a variant of Arduino Due embedded on a ARM (Udoo). And I have connected a Medlab SPO2 Pearl 200 sensor to Serial1.

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

The protocol is described in this image:

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

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

      readed = 0;
    }

  }

```

Output with no finger is:

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

```

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

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

```

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

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

```
boolean startbyte = false;
byte buf = 0;

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

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

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

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

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

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

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

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

```
> 0 votes

# Answer
actually I don't think it is all mixed up

as per geometrikal use the markers to parse the data stream

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

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

```

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

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

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

---
Tags: serial, sensors, arduino-due
---


# Question
Title: Wifi server to control led on and off from local webpage.. - ..if statement doesnt work...
Im a newbie on this arduino thing and I would like to build a curtain remotecontrolled from a local webpage with 2 buttons... a up an a down...

I got the connection via my phone the the local page with the buttons. :D

My problem on this one is that the buttons' if statement (command == on); doesnt work or in other words the client.println(command); get the "on" command and write it on the page... but it dont do the function in the if statement (the button)...

Can anybody help me...? it should be simple..:D

```
    #include <Bridge.h>
    #include <YunServer.h>
    #include <YunClient.h>

    int LEDPIN = 3; // your LED PIN
    YunServer server;

    String readString;

    void setup() {
  // Start our connection
  Serial.begin(9600);
  pinMode(LEDPIN,OUTPUT);
  digitalWrite(LEDPIN,HIGH); // turn on Led while connecting
  Bridge.begin();

  // Show a fancy flash pattern once connected
  digitalWrite(LEDPIN,LOW);
  delay(150);
  digitalWrite(LEDPIN,HIGH);
  delay(150);
  digitalWrite(LEDPIN,LOW);
  delay(150);
  digitalWrite(LEDPIN,HIGH);
  delay(150);
  digitalWrite(LEDPIN,LOW);
  delay(150);

  // Disable for some connections:
  // Start listening for connections

  // server.listenOnLocalhost();
  server.begin();

}

/* ------------------------------------------------*/
/* --------------- End WIFI connection ------------*/
/* ------------------------------------------------*/

void loop() {
  YunClient client = server.accept();
  if (client) {
      process(client);
    client.stop();
  }
  delay(50);
}

void process(YunClient client) {
  String command = client.readStringUntil('\\');

  client.println("Status: 200");
  client.println("Content-type: text/html");
  client.println();
  client.println("<B><Center><br><br><br>");
  client.println("<a href='/arduino/on\\'>ON</a><br><br><br>");
  client.println("<a href='/arduino/off\\'>OFF</a><br><br><br>");
  client.print("Command: ");
  client.println(command);
  client.println("</B></Center>");

/* ------------------------------------------------*/
/* ------------------- Buttons --------------------*/
/* ------------------------------------------------*/

  if (command == "on") {
    digitalWrite(LEDPIN,HIGH);
    digitalWrite(13,HIGH);
  }

  if (command == "off") {
    digitalWrite(LEDPIN,LOW);
     digitalWrite(13,LOW);
  }
}

```

# Answer
Pretty sure your problem is coming from the fact that you chose to use the backslash as your terminator character. The backslash requires special handling when encoded as a URL. You can observe this by Googling for "\\" and and the results page you'll see your query in the address bar assigned to the "q" variable: q=%5C my entire URL looked like this, you may have something a bit different: https://www.google.com/?gws\_rd=ssl#q=%5C

Ok - so if you want a quick fix, stop using the \ to terminate your commands, since backslashes are often used to help sort out special characters (like "TAB" as \t) it's a a really bad choice, but an honest mistake.

If you change your code to generate links terminated with dashes you can get around the issue

```
client.println("<a href='/arduino/on-'>ON</a><br><br><br>");
client.println("<a href='/arduino/off-'>OFF</a><br><br><br>");

```

and of course change your readStringUntil invocation too

```
client.readStringUntil('-');

```

Edit: You might want to use the "*" if the hostname part of your URL contains a space: http://my-web-server.com/on*

And one more alternative, seek the "%" instead since that's going to be used to encode the backslash. In that case you just need to change the readStringUntil()
> 1 votes

---
Tags: wifi, led, arduino-yun, web-server
---


# Question
Title: In Linux, how do I get this Arduino library to work
In Linux Fedora 20 Arduino I want to use the Timer library from here, from which I have downloaded the folder `Timer-master.zip`, but, when I try to import it, I get the Arduino message that it cannot be imported because its name includes characters other than plain ACSII letters and numbers. I have tried copying the file to `Timermaster.zip` and importing that instead, but still got exactly the same failure message.

Please, how do I get out of this impasse?

# Answer
What's causing the problem is that the folder name inside the zip has a hyphen in it, just extract the folder from this zip and rename it to `timer` instead of `timer-master`. I just imported it on Fedora 20.
> 4 votes

---
Tags: arduino-uno, library, timers, linux
---


title: SD datalogger sometimes skips readings

text:
# Question
Title: SD datalogger sometimes skips readings
I'm using the Adafruit SD shield with a Mega board and wrote a simple program to log data. I am outputting a constant stream of data at 115200 baudrate from another Arduino to the Mega. The data output is mostly good, but there are places where some data are skipped. These skipped data usually occurs around a file flush. I've tried playing around with the flush frequency and the soft buffer size, but to no avail. I'm not sure what these hiccups are caused by and would like some help.

```
void loop(void)
{
  while (Serial1.available())
  {
    softBuffer[i] = Serial1.read();
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    for (x = 0; x < SOFT_BUFFER_SIZE; x++)
    {
      logfile.print(softBuffer[x]);
    }

    logfile.flush();

    i = 0;
  }
}

```

# Answer
> 1 votes
The SD card library works by filling up a 512 byte buffer. Once full, the data is written to disk.

The `flush` command updates the directory listing with the correct size for the file and also updates the file allocation table. It only needs to be done once, just before you pull the card out.

While `flush` is doing its thing, the internal serial buffer of the Arduino is filling up with new bytes. The internal buffer is 64 bytes long so if `flush` takes too long, the internal buffer fills up and you lose characters. You could edit HardwareSerial.cpp in the Arduino program directory to make it say 256 bytes.

Because of this `softBuffer` is not needed. Simply write straight to the card and let the internal buffer handle the buffering. See https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp for the Serial code.

```
unsigned long bytesWritten = 0;
void loop(void)
{
  while (Serial1.available())
  {
    logfile.write(Serial1.read());
    bytesWritten++;
    if(bytesWritten > BYTES_PER_FLUSH) logfile.flush();
  }
}

```

---
Tags: arduino-mega, sd-card
---


# Question
Title: perform an action maximum x times per hour
is it possible to perform an action maximum x times per hour on the arduino?

I made a automatic water sprinkler that sprays when the humidity is lower than 50%. but if the sprayer performs this "spray" more than 4 times an hour the humidity wil be to high and wil rise to fast.so is there a way to restrict the amount of times an action is performed per hour,and then if the next hour comes the sprayer can perform his "sprays" 4 times before it stops again

sorry for bad english, this is not the language I speak (and type) mutch

# Answer
Sure it's possible. It would be better if you had a real time clock module. Then you could use time-of-day.

You need to define your problem a little better. Would it be ok to run the sprinkler every 5 minutes, then not again for 40 minutes, for a total of 4 sprays in an hour, but clustered together? Do you want to prevent 4 sprays in a clock hour, or not go over an average of 4 sprays per hour?

Without a realtime clock module, I guess here's what I would do:

After a spray, record the time (in millis). Then in your loop, don't spray again for 15 minutes (15\*1000\*3600 milliseconds.)

The code would look something like this: (not real code, more like pseudocode)

```
const unsigned long fifteenMinutes = 15*1000*3600;
unsigned long nextSprayTime = 0;

loop()
{
  if (millis() >= nextSprayTime)
  {
    if (humidity < 50)
    {
      spray();
      nextSprayTime = millis() + fifteenMinutes;
    }
  }
}

```

Edit: You said, in comments:

> i want it not to go over 4 sprays an hour,i have the ds1307 rtc module. situation: ist an automatic egg incubator and the humidity must be between 50% and 60%.i control the sprayer whit a dht11 sensor an a servo connected to an spray bottle. if the humidity is below 50 % the servo starts whit spraying.the servo keeps on spraying every second until that 60% mark is reached and then shuts of.so the amount of water in the box is way to much and so the humidity keeps on climbing until the 100% mark whit is deadly for the eggs

Ok, that gives your readers a clearer picture.

You're dealing with a process control problem, not just a hardware or software problem.

When you spray water, it will likely take several minutes for the change in humidity to stabilize and be detected by your sensor.

Your current approach sounds wrong because you dump far too much water into the system, and don't give it time to reach a new equilibrium before adding more water.

You need to collect some data.

There is going to be a significant lag between putting a spray into the incubator and sensing the increase in humidity, and when the increase reaches it's max.

You need to measure that lag.

You also need to know how much a single spray increases the humidity.

You should probably \**ALSO\* figure out how many sprays at a time you can spray before water droplets form on the walls of your incubator and on your eggs, since I assume that is very bad and to be avoided at all costs. Thus I would add a moisture detector to your system (A small piece of cloth with electrodes on it at 2 locations a couple of CM apart, and a sensitive conductivity sensor that detects the change from insulator to weak conductor that takes place when the cloth becomes saturated with water.)

You should also figure out how fast the humidity in your incubator drops if you don't add any water, for a variety of different conditions. (Likely affected by current humidity, outside temp and outside relative humidity, so you probably want 2 humidity sensors, one inside and one outside the incubator, and to record all the variables and graph them.)

I would suggest writing a data collection program. You might want to run it with the serial cable connected to a PC constantly, or install an SD card and save your data there.

In all your tests, you probably want to wait a significant time (15 minutes? 1/2 hour? 1 hour?) for the incubator to reach equilibrium before beginning your test.

You want the conditions of your incubator to be as close to your real-world conditions as possible. You might want to put eggs (dummy eggs, grocery store eggs at room temp, or something like that) in the incubator during the test to allow for the amount of water they absorb. You want the outside temp to be as close to your real-world temp as possible. If the incubator will be exposed to direct sunlight, air vents, wind, etc, then you want those same conditions.

At each step in every test you should record the current time, the current outside temp and humidity, and the current incubator temp and humidity, and the time of each spray you trigger.

Add your condensation detector at the beginning, and any time it detects condensation you should sound an alarm, record the time that it trips, and abort the current test. If you get liquid condensation you've done something wrong and need to adjust.

Write a program for your computer that graphs all your data points over time. Every time you run a test (other than the very first test) graph all the data and look at it. Patterns will probably jump out at you.

**Test 1:**

Record the time and the current humidity. Add one spray of water, and then record the humidity for 15 minutes. Look for an increase in humidity and when it peaks. The time from adding a spray to the peak increase in humidity is what you want.

**Test 2:**

Then modify your program to log the spray-to-peak-humidity-increase time, and each time it detects the humidity starting to drop again, spray once more, log the current outside temp and humidity, the inside humidity and outside time of the spray, and repeat.

This will give you spray-to-peak-humitity lag times over a range of humidity values. Graph that data with starting relative humidity on the x axis and the lag time on the y axis and look at it. Is it a constant value? A straight line? Is it a geometric curve? Exponential? Come up with a curve that fits the data fairly well.

**Test 3:**

A test that uses an increasing number of sprays, looking for how many sprays you can do at once before you cause condensation.

Start with 2 sprays.

Look for the peak increase in humidity, and once the humidity starts to drop, increment your spray counter to 3, spray that many times, and repeat. When the condensation alarm trips, stop the test.

Note that the number of consecutive sprays you can do before the moisture alarm trips will probably change for different starting humidity levels. My guess is that the max number of sprays you can add without triggering condensation will be highest at your lowest humidity level, and as the humidity increases, you'll get condensation with less and less sprays.

**Test 4:**

Figure out how to measure the max number of sprays that trigger condensation when you start at less than your minimum humidity, at your minimum humidity, at halfway between min and max, and at max. (This experiment will take some thought since it's not easy to get to a given humidity level, and once you trigger condensation you'll have to stop, dry everything out, and start again.)

**Test 5:**

Get your incubator as close to the maximum acceptable humidity (60%) as you can at the beginning of the test, or even a little above. Simply record the humidity every minute until it drops to the lowest acceptable level (50%). Graph the data. That will show you how fast the humidity drops if you do nothing.

**Test 6:**

Repeat test 5 for the range of outside conditions you might find in your production environment. (If you're in a climate-controlled space, do you have summer and winter thermostat settings? Test for those upper and lower ranges. How much does your indoor humidity level vary?)

## Now what?

Now you have lots and lots of data.

More than likely you have an idea of how many sprays you can add at a time without triggering condensation over your humidity range. This should be fairly simple: (for example, at humidity \< 50% to 52%, you can use 3 sprays. AT 53-55%, 2 sprays. Above 55%, 1 spray.) You should also have a rough idea how much increase you'll get in humidity for a given number of sprays.

You have an idea of how fast the humidity drops if you don't add water.

You have an idea how long it takes for a spray set of sprays to cause a peak in the humidity level.

Write a program that strives to keep the incubator in the middle of your desired range. If 50% is your absolute minimum humidity level and 60% is your max, then trigger sprays at 52%, not 50%. Spray as many sprays as you can without causing condensation (or overshooting your max humidity), then lock out sprays for the time period you calculated as the time it takes for your sprays to cause the maximum increase in humidity.

If you've found that the max number of sprays you can do at a time is different for different humidity levels, use code that comes up with a number of sprays that stays below that limit. Also try to estimate how much increase in humidity you get per spray, and each time you trigger a series of sprays, stay below the number of sprays that reaches your max humidity.

If you've found that the conditions outside the incubator have a big effect on your system, adjust your code to compensate for those changing conditions.

You want a system that uses small adjustments over time to keep a system at near equilibrium. Big adjustments will likely cause wild variations in conditions that go outside of the acceptable range.

## Other considerations:

Do you need to open the incubator at regular intervals to check on the eggs or turn them, or do you have an egg turner? If you do need to open the incubator, you will need to figure out the effect this has on your temp and humidity levels for the range of outside conditions you face. You can probably build your system with a door sensor that detects you opening the door, the outside temp and humidity, and how long the door is open. Once you close the door, it would note the new inside temp and humidity and make an educated guess as to how much the humidity will drop after being open, and add water accordingly.
> 3 votes

# Answer
You might be spraying faster than the sensor or the environment can respond, causing your humidity overshoot your goal. Try spraying way less often, experimenting with the interval until you understand more about the dynamics of the humidity.

My first guess would be to try once per minute and see whether that still overshoots or if it fails to maintain the humidity. That will tell you whether to increase the interval more or to decrease it. Writing the time and humidity readings to the terminal and plotting those may help you understand your system behavior better.
> 0 votes

---
Tags: arduino-uno
---


title: Arduino Digitalwrite for while loop set

text:
# Question
Title: Arduino Digitalwrite for while loop set
My question is simple. Does Arduino set the digitalwrite() the moment it is called or at the end of the while loop. E.G.

```
int ledPin = 13;
void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{for(int i=0; i<10; i++){
if(i%2==0){
  digitalWrite(ledPin, HIGH);
  delay(1000);}else{
  digitalWrite(ledPin, LOW);
  delay(1000);      }
}

```

# Answer
> 2 votes
A key point of the Arduino 'language' is *every* statement is completed before the next one can begin.

A simple statement has a '`;`' at the end of it.
Or followed by '`)`' instead of '`;`' in `for (...; ...; statement)` loop.

So `digitalWrite()` will set the pin, HIGH or LOW, *before* it completes and allows the next statement, `delay(...)` to begin.

Side note:
Actually `digitalWrite()` takes a small amount of time to do its work, so it is not *exactly* 'the moment' it is called. `digitalWrite()` *is* pretty quick, a few millionths of a second, which is usually near enough to be practically 'the moment' for most applications.

# Answer
> 0 votes
Arduino sets the pin at the moment digitalWrite() is called.

# Answer
> 0 votes
The condition

```
if(i%2==0)

```

will be checked immediately upon entering the "for" loop, and again on every iteration of that loop. It will be the first code executed on each iteration. One form or another of the digitalWrite() will be called next, followed by the delay().

---
Tags: programming
---


# Question
Title: How do I write an Arduino program to an AVR chip without the Arduino bootloader?
Is it possible to write an Arduino program to an AVR chip that does not have teh Arduino bootloader installed? What is the process to do so?

# Answer
> 6 votes
### Step 1: Get yourself a programmer.

This can be anything from a USBasp to an Arduino programmed for ISP all the way to an AVR ONE!. Some can be used from the IDE, and some cannot.

### Step 2: Set up the chip as expected from the entry in boards.txt and from the datasheet.

Add a crystal, decoupling caps, whatever. Don't connect power yet.

### Step 3: Connect the programmer.

If using ISP, connect the ISP pins. If using JTAG, connect the JTAG pins. If using something else, see the programmer and chip documentation for connection details. You may want to connect power at this point for the next step.

### Step 4: Program fuses.

Program the oscillator, BOR, CKDIV8, EESAVE fuses as desired/required. Fuse calculator.

### Step 5: Compile the program and write it to the chip.

If using the IDE, select the programmer in `Tools` | `Programmer` and then hold shift when clicking the Upload button (or press Ctrl-Shift-U). If your programmer is not supported by the IDE then compile the program (`Sketch` | `Verify/Compile` or Ctrl-R), locate the temporary directory it has been built in, and use avrdude or your JTAG program to upload it to the programmer.

### Step 6: There is no step 6. You're done.

I just wanted to see if you would read this far.

# Answer
> 1 votes
If there are no memory restrictions (too large program) which eliminates this option, I'd try to write the Arduino bootloader first and then continue normally. This has the advantage of simple reprogramming if required.

---
Tags: bootloader
---