title: Serial3.available loop issue

text:
# Question
Title: Serial3.available loop issue
I am trying to read information coming from an Atlas Scientific FLO30 chip.

The following code works fine in an individual sketch:

```
String inputstring = "";                                                       //a string to hold incoming data from the PC
String sensorstring = "";                                                      //a string to hold the data from the Atlas Scientific product
String LPM="";
float LPM_INT;

boolean input_stringcomplete = false;                                          //have we received all the data from the PC
boolean sensor_stringcomplete = false;                                         //have we received all the data from the Atlas Scientific product
#define CIRC_PUMP_PIN 10 // circulation pump pin - high when on, low when off

unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change :
const long interval = 1000;

  void setup(){                                                                //set up the hardware
     Serial.begin(9600);                                                       //set baud rate for the hardware serial port_0 to 9600
     Serial3.begin(38400);                                                      //set baud rate for software serial port_3 to 9600
     inputstring.reserve(5);                                                   //set aside some bytes for receiving data from the PC
     sensorstring.reserve(30);                                                 //set aside some bytes for receiving data from Atlas Scientific product
     pinMode(CIRC_PUMP_PIN,OUTPUT);
     digitalWrite(CIRC_PUMP_PIN,HIGH);

void loop(){

unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

            if(Serial3.available()>0){
              while(sensor_stringcomplete==false){
        char inchar = (char)Serial3.read();                              //get the char we just received
              sensorstring += inchar;                                          //add it to the inputString
              Serial.println("adding to string");
            if(inchar == '\r') {sensor_stringcomplete = true;}               //if the incoming character is a <CR>, set the flag
             }
            }

 if (sensor_stringcomplete){                                                   //if a string from the Atlas Scientific product has been received in its entierty
      Serial.println(sensorstring);                                            //send that string to to the PC's serial monitor
      byte n = sensorstring.length();
      LPM = sensorstring.substring(n-8,n);
      Serial.print("This is the extracted part ");
      Serial.println(LPM);
      LPM_INT=LPM.toFloat();
      Serial.print("Now in float ");
      Serial.println(LPM_INT);
      LPM="";
      sensorstring = "";                                                       //clear the string:
      sensor_stringcomplete = false;                                           //reset the flag used to tell if we have received a completed string from the Atlas Scientific product
      }

      if(sensor_stringcomplete==false){
       Serial.println("Skipping");

      }
  }

      }

```

however when I try to integrate the code with another master sketch, the Arduino seems to jam or lockup when it enters the following part of the code, which is called periodically from the main void loop():

```
    if(Serial3.available()>0){
      while(sensor_stringcomplete==false){
char inchar = (char)Serial3.read();                              //get the char we just received
      sensorstring += inchar;                                          //add it to the inputString
      Serial.println("adding to string");
    if(inchar == '\r') {sensor_stringcomplete = true;}               //if the incoming character is a <CR>, set the flag
     }
        }

```

All the code is the same and I do not understand why the Arduino locks up. I intially thought it was a problem with memory as the master code is singificantly bigger but the line "sensorstring = ""; " and "sensorstring.reserve(30) " should take care of this? Besides it cannot even get one reading from the sensor.

Can anyone give insight as to why this might be?

# Answer
> 0 votes
Firstly, don't use String. It's wasteful of memory and the dynamic aspects of it don't sit well on a tiny resource-starved 8-bit microcontroller.

Secondly, your method of reading from the serial is flawed right from the start.

```
if(Serial3.available()>0){

```

... If there is at least 1 character available ...

```
while(sensor_stringcomplete==false){
    char inchar = (char)Serial3.read(); //get the char we just received
    sensorstring += inchar;     //add it to the inputString
    Serial.println("adding to string");
    if(inchar == '\r') {sensor_stringcomplete = true;} //if the incoming character is a <CR>, set the flag
}

```

... read characters until I get the end of string character regardless of if those characters are even available.

In order to read the data from the serial port you have to ensure that the data is actually available. Just waiting for the first character to arrive and then reading (much faster than the serial is able to receive) other characters is doomed to failure.

I have discussed this at great length in a blog article, including how to perform non-blocking string reads that will not interfere with the rest of your program: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

It even mentions your specific situation since it is something that is so commonly done wrong.

---
Tags: serial, arduino-mega, memory-usage
---


# Question
Title: A question about the possible limits of an Arduino Uno
I've searched the web but could not find a straightforward answer to my query.

I am building a control board for one of my models and this time have decided to also include a computer interface, so I have incorporated an Arduino Uno into my project instead of just analog circuits. I'm not an electronics expert of any sort but I manage by applying basic logic and a lot of trial and error.

Anyway, I have a single Arduino. It is operating the following:

An LCD display, a 4 button operation panel I made using an LS148 ic, an L293 operating 2 small motors, a servo, a dark sensor, a temperature sensor, and it also does serial communication.

Everything is working great, but slow (or so it appears to me).

If i push a button it takes the board about a second to pick up on the signal while an external LED indicator shows the circuit using the LS148 is working as it should. (I basically chained the 1-4 inputs and checking the truth table on the board to determine which button was pressed). Or pick up on a signal sent from the dark sensor for example. It appears as if the whole code in the Arduino runs at a cycle of once per second. Also sending instructions from the computer.

When I disable the LCD code everything works fast(er) and so goes when I remove other parts. So my question is, have I overloaded it?

I am on the verge of ordering another board (which I am going to do anyway), but in this case it is purely due to my belief that if I connect the LCD with the whole display code onto one board and the rest of the sensors and chips to another it will solve my problem.

I haven't figured out yet if it's possible to link the two boards or how to do that, but once I'll get to that bridge I'll cross it as well.

Thanks for your advice.

# Answer
> 4 votes
A lot of Arduino code is written either generally inefficiently, or written in completely the wrong way.

For instance, take the LCD code. Commands have to be sent at the right speed with the proper delays in there for things to happen. LCDs are actually quite slow devices to communicate with, and as a result the LCD code has a large number of delays in it.

Nothing else can happen while there's a delay() running.

Many other things will introduce their own delays. Put them all together and you have a slow system.

No, you're not overloading it, you're slowing it down on purpose, and all those small slow-downs add up to one big grind.

There are other ways of doing these things, of course, which are far more friendly to the chip - things that don't require delays of any form.

For a start there is the millis() function which tells you the time. Using that to know when to do things, instead of sitting waiting for them to happen, allows you to do so much more at once.

It's like boiling an egg. Do you put the egg in boiling water and sit there staring at it for 3 minutes (or however long you like your egg cooking), or do you set the timer on your oven to alert you in 3 minutes time so you can go and do the ironing while the egg is boiling?

It's the same with Arduino programming. Note the time, then check that time against the current time to see if the required time has passed.

Of course, with things like the LCD library, changing it to work that way would be quite a lot of effort.

There are also hardware timers. These allow you to run small snippets of code at regular periods. Great for managing things like servos or other motors where you only want to be changing the state or speed of them say 10 times per second. Instead of updating them all the time, just set a desired speed / position variable and let the timer interrupt update the actual motor at a lower rate.

There are two key phrases to take away here:

* Non-blocking. That is basically writing routines that never wait for something to complete, but can check to see if it's time for something to happen.
* Asynchronous programming. This is using things like timers to make things happen "outside" your main loop.

---
Tags: arduino-uno
---


title: Why is this returning the wrong answer?

text:
# Question
Title: Why is this returning the wrong answer?
Why does this print output -3? xpos can be any value.

```
void loop() {
xPos = analogRead(xPin);
yPos = analogRead(yPin);
pwm = xPos*(255/1023);
Serial.println(pwm);

}

```

# Answer
The problem is that `(255/1023)` is being treated as an integer calculation, meaning the result gets truncated to 0. You can make the compiler promote it to a floating-point calculation by explicitly making at least one of the values floating-point. For example:

```
pwm = xPos*(255.0f/1023.0f);

```
> 1 votes

# Answer
The previous answer correctly suggested writing

```
pwm = xPos*(255.0f/1023.0f);

```

in place of the original form `pwm = xPos*(255/1023);`. But because 255/1023 - 1/4 = -1/1364 which is fairly small (ie it differs by 1 part in 1364), just saying

```
pwm = xPos/4;

```

will usually give the correct result or nearly so.

Note, the following python program shows that this result is exact 514 times as xPos ranges from 0 to 1023, and is one too large 510 times, which for many processes being controlled by PWM signals is close enough.

```
#!/usr/bin/env python
c = [0]*8
for i in range(1024):
    vf = int(i*255.0/1023.0)
    vi = i/4
    d = vi-vf
    c[d+3] += 1
    #print '{:5} {:5} {:5} {:5}'.format(i, d, vi, vf)
print c

```
> 2 votes

---
Tags: arduino-uno
---


title: Remove Bootloader on Arduinos

text:
# Question
Title: Remove Bootloader on Arduinos
I am trying to move from arduinos to AVR C. Would somebody know how to remove the arduino bootloader from the microcontroller? Is there a different process for the different atmega microcontrollers like the 32u4, 328, or 2560?

Thanks.

# Answer
> 2 votes
You don't "remove" the bootloader, you just ignore it. When you program your new code with the hardware programmer of your choice it will just overwrite the bootloader code with your software's startup code.

---
Tags: arduino-leonardo, avr, avrdude, atmega32u4
---


# Question
Title: Beginner here, trying to start learning arduino, which starter kit should I buy?
I'm really interested in arduino but I don't know much about it. I want to buy a starter kit to play with, but when I searched it on amazon, there are couple unofficial starter kit and a more expensive official one. So, can some one tell me the major difference between the unofficial starter kit and official starter kit? And which one would you recommend me to buy? Thank you!

Sorry, bonus question: why is the start kit($89) in arduino website is much cheaper than the official starter kit in amazon($120)?

# Answer
> 2 votes
You could do worse than a cheap 37-in-1 Sensor Kit from eBay and any Arduino board of your choice.

Also some Dupont Jumpers are essential. Get a selection of M/M, M/F and F/F.

# Answer
> 1 votes
I tend to recommend the oomlout ARDX starter kit to students at the university I work at as it is relatively low cost, widely available, and doesn't have too much cheap filler components that you don't use...

---
Tags: arduino-uno
---


# Question
Title: LED too dim when connected to digital output pin
I am making an attempt to put LED headlights in an RC car I am building. I want the headlights to turn on when I click circle on a PlayStation 4 Dual Shock controller. I currently have it working except the LED is very dim and not near as bright as if I just power it from the 5v pin on the arduino board. Since I want it to only turn on when circle is pressed I have it connected to digital pin 7. Here is my code. Any help would be much appreciated!

```
/*
 Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
 For more information visit my blog: http://blog.tkjelectronics.dk/ or
 send me an e-mail:  kristianl@tkjelectronics.com
 */

#include <PS4BT.h>
#include <usbhub.h>
#include <Servo.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
Servo servo1;
Servo servo2;

/* You can create the instance of the PS4BT class in two ways */
// This will start an inquiry and then pair with the PS4 controller - you only have to do this once
// You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode
PS4BT PS4(&Btd, PAIR);

// After that you can simply create the instance like so and then press the PS button on the device
//PS4BT PS4(&Btd);

const int headlights = 7;
bool printAngle, printTouch;
uint8_t oldL2Value, oldR2Value;

void setup()
{
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1)
  {
    Serial.print(F("\r\nOSC did not start"));
    while (1); // Halt
  }
  Serial.print(F("\r\nPS4 Bluetooth Library Started"));

  pinMode (3, OUTPUT);
  pinMode (5, OUTPUT);
  servo1.attach (3);
  servo2.attach (5);
}
void loop()
{
  Usb.Task();

  if (PS4.connected())
  {
    servo1.write(map(PS4.getAnalogHat(RightHatX), 0, 255, 50, 0));
    servo2.write(map(PS4.getAnalogButton(R2), 0, 255, 90, 0));
  }
  else
  {
    servo1.write (25);
    servo2.write (90);
  }

  if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117)
  {
      Serial.print(F("\r\nLeftHatX: "));
      Serial.print(PS4.getAnalogHat(LeftHatX));
      Serial.print(F("\tLeftHatY: "));
      Serial.print(PS4.getAnalogHat(LeftHatY));
      Serial.print(F("\tRightHatX: "));
      Serial.print(PS4.getAnalogHat(RightHatX));
      Serial.print(F("\tRightHatY: "));
      Serial.print(PS4.getAnalogHat(RightHatY));
  }

    if (PS4.getButtonClick(PS)) {
      Serial.print(F("\r\nPS"));
      PS4.disconnect();
    }

    else {
        if (PS4.getButtonClick(CIRCLE)) {
        Serial.print(F("\r\nCircle"));
        digitalWrite(headlights, HIGH);
        }

      if (PS4.getButtonClick(CROSS)) {
        Serial.print(F("\r\nCross"));
        digitalWrite(headlights, LOW);
      }

      if (PS4.getButtonClick(TRIANGLE)) {
        Serial.print(F("\r\nTraingle"));
        PS4.setRumbleOn(RumbleLow);
      }

      if (PS4.getButtonClick(SQUARE)) {
        Serial.print(F("\r\nSquare"));
        PS4.setLedFlash(0, 0); // Turn off blinking
      }

      if (PS4.getButtonClick(UP)) {
        Serial.print(F("\r\nUp"));
        PS4.setLed(Red);
      } if (PS4.getButtonClick(RIGHT)) {
        Serial.print(F("\r\nRight"));
        PS4.setLed(Blue);
      } if (PS4.getButtonClick(DOWN)) {
        Serial.print(F("\r\nDown"));
        PS4.setLed(Yellow);
      } if (PS4.getButtonClick(LEFT)) {
        Serial.print(F("\r\nLeft"));
        PS4.setLed(Green);
      }

      if (PS4.getButtonClick(L1))
        Serial.print(F("\r\nL1"));
      if (PS4.getButtonClick(L3))
        Serial.print(F("\r\nL3"));
      if (PS4.getButtonClick(R1))
        Serial.print(F("\r\nR1"));
      if (PS4.getButtonClick(R3))
        Serial.print(F("\r\nR3"));

      if (PS4.getButtonClick(SHARE))
        Serial.print(F("\r\nShare"));
      if (PS4.getButtonClick(OPTIONS)) {
        Serial.print(F("\r\nOptions"));
        printAngle = !printAngle;
      }
      if (PS4.getButtonClick(TOUCHPAD)) {
        Serial.print(F("\r\nTouchpad"));
        printTouch = !printTouch;
      }
     }
    }

```

# Answer
> 3 votes
You forgot to set `headlights` as an output, meaning that you're attempting to power the LED through the 20k-50kohm input pullup.

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


# Question
Title: How do I turn a number of pins to high and then off after 5 seconds based on a serial command
I have an Arduino sketch where I'm sending commands over serial, and as a result turning pins from low to high. What I'm looking to do is have those pins turn high for 5 seconds and then turn back to low. I was looking for a time or scheduling library for Arduino that allows multiple timers at once and lets you pass a parameter (at least I think that's what I need).

In other words, I would like to implement a "doAfter" method and pass the function it is calling a pin number.

# Answer
Have you tried the `delay()` function? Try putting this in the `loop()` function for pin 3.

```
digitalWrite(3, HIGH);
delay(1000); // time in milliseconds as parameter
digitalWrite(3, LOW);

```
> 1 votes

# Answer
You can use the Timer library to achieve this:

```
#include "Timer.h"
[...]
digitalWrite(3, HIGH);
int afterEvent = t.after(5000, doAfter);
[...]
void doAfter() {
  digitalWrite(3, LOW);
}

```

As you can see, you cannot pass a parameter to the timer, just a callback. I suggest that you implement either a bunch of `doAfter` functions, from `doAfter3` to doAfter9\` for instance, and call the right one in the callback.

There are probably other timer libraries, but this one is simple and complete enough for your needs.
> 0 votes

---
Tags: serial, led, timers
---


title: Attiny45 wake by Software Serial

text:
# Question
Title: Attiny45 wake by Software Serial
I would like to wake Attiny45 from sleep by Serial communication. RX is connected to pin 7 (D2). When I try to use PCINT0\_vect routine, I get an error "multiple definition of \`\__vector\_2'" so it looks like Software Serial already uses "ISR (PCINT0\_vect)" and pin change interrupt.

So my question is, will incomming communication wake Attiny from sleep?

Is there a possibility to change CLKPR when Attiny starts receiving? For example I set clock divider to 256 for the majority of time and when it starts receiving it changes back to 1.

I was thinking of something like this:

```
void loop() {
 if (SWSerial.available()>0) {
   noInterrupts ();
   CLKPR = bit (CLKPCE);
   CLKPR = clock_div_1;
   interrupts ();
 }
//other code here
}

```

I don't mind loosing some bytes, but I need to low Idle current as much as possible. Thank you.

# Answer
# Question #1: Can a change on pin 7 wake from sleep?

Yes. The lowest power mode for this chip is `Power-down`, and you can wake from this state with a pin change interrupt. Assuming that the soft-serial code you are using already enables interrupts on the pin for its own purposes, then you should just be able to sleep and the part will wake on the next pin generated interrupt.

Depending on what compiler/libraries you are using, something like this...

```
include <avr/sleep.h>

...

set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_cpu();
//We will only reach this line after an interrupt has occured

```

...should work. Note that an interrupt when waking from sleep takes longer than when already running, so you'll need to check your soft serial library to see if it will possibly garble the first bit received- it will depend on how they do their timing.

If you really want the lowest power possible, you could write your own soft serial code that drops the processor to idle in between serial bit transitions. Depending on how much time you will be spending actually receiving data this could drop overall power consumption dramatically.

For low baud rates, I could imagine writing serial receive code that woke on an interrupt from the start bit, and used the timer running at a very low clock speed to wake up in the middle of each data bit and very quickly sample and shift the bit in before going idle again. Done right, this could dramatically drop the power used while receiving.

# Question #2: Is there a possibility to change CLKPR when Attiny starts receiving?

Yes. You can change the prescaler any time, but note that...

1. The clock is not running at all during `power-down` mode, so there is no reason to scale back before going to sleep - it will just mean that it takes you longer to wake up when a change happens.
2. Sometimes scaling back the clock can actually use more power, especially when sleeping is envolved. A processor running 1/2 as fast uses more than 1/2 as much power, so it is often more power efficient to wake up at full speed, do what you have to do as fast as possible, and then get back to sleep.

The best option for you will depend on factors like how often will you be receiving data compared to waiting for data, and how much work you wan to put into getting optimal power usage. This chip can be *extremely* power efficient, but it can take work to take advantage of it.
> 2 votes

---
Tags: interrupt, attiny, softwareserial, sleep
---


# Question
Title: Use a PIR Sensor to detect the movements of a paper
I need to detect when a paper comes out from a laser printer and count the number of printed papers. For that I hope to use a PIR sensor to detect the movement of the paper from the printer. Is it possible to detect the movement of a paper using a PIR sensor? Please be kind enough to help me.

# Answer
> 3 votes
If the paper is hot when it comes out of the printer, possibly. Could be unreliable though.

Better would be to place a photo-interrupter (or IR LED and IR Photodiode) in the path of the paper to detect a break in an infra-red beam.

# Answer
> 2 votes
The solution from the OP with the photo-interruptor is probably the most standard one.

However it might be worth checking if you can get away with a light sensor: assuming that the paper is mostly of different colour than the background, the paper should change the current passing through the photodiode.

Alternatively, you could use a proximity sensor, aimed at a location on the path of the paper, where there is typically nothing.

These 2 solutions are trying to avoid having to place something on both sides of the paper. If that doesn't bother you, then I'd recommend the OP's solution.

---
Tags: sensors
---


# Question
Title: Scroll LCD display connected to an Arduino Uno
I want to make some characters scroll left without affecting the first positions in each row of my LCD 16x2 screen. I have this code inside the loop so far:

```
lcd .clear();
lcd.setCursor(17, 0);
for (int i = 15; i > 0; i--) {
  lcd.print("x");
  lcd.scrollDisplayLeft();
  if (digitalRead(switchPin) == HIGH) {
    lcd.setCursor(0, 0);
    lcd.write(5);
  } else {
    lcd.setCursor(0, 1);
    lcd.write(5);
  };
  lcd.setCursor(17, 0);
  delay(500);
}
lcd.noAutoscroll();

```

I think it should work, but the character *x* just moves left by one position, whereas the character in the first position, either in the first or second row doesn't appear at all.

# Answer
> 0 votes
I would do the following (beware - not tested):

```
lcd.clear();
lcd.setCursor(15, 0);
lcd.print("x");
for (int i = 0; i < 15; i++) {
    lcd.setCursor(0, digitalRead(switchPin) == LOW);
    lcd.print("5");
    delay(500);
    lcd.scrollDisplayLeft();
}

```

---
Tags: arduino-uno, lcd, electronics, ui
---


# Question
Title: Error: 'SofwareSerial' does not name a type
I have trouble compiling this sketch. The error I get is

> 'SoftwareSerial' does not name a type

Any ideas how could I fix it?

```
#include SoftwareSerial.h

SoftwareSerial mySerial(10, 11); // RX, TX

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

  Serial.println("Ready!");

  // set the data rate for the SoftwareSerial port

  // for HC-05 use 38400 when poerwing with KEY/STATE set to HIGH on power on
  mySerial.begin(9600);
}

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

```

# Answer
> 4 votes
Add to @geometrikal.

or

```
#include <SoftwareSerial.h>

```

# Answer
> 8 votes
You forgot the quotation marks, try

```
#include "SoftwareSerial.h"

```

# Answer
> 0 votes
```
#include "SoftwareSerial.h" worked instead of

```

`#include <SoftwareSerial.h>` ie " " not \<\>

---
Tags: programming, softwareserial
---


# Question
Title: Testing Arduino with Visual Studio Community 2013 raise LNK error
I have two projects in my Visual Studio Community 2013 solution.

I created a project for Arduino, and create another project for Test. When I run the project tests without adding the Arduino project reference, it run ok, but when I add the Arduino project reference I get it error:

```
LNK1561: entry point must be defined D:\VisualStudioArduino\PrinterProject\LINK PrinterProject

```

What is the entry point for Arduino project?

It does not generate any file like a dll or main file?

What can I do to solve this error?

## UPDATE I

I also tried this configuration in the Arduino Project but I get the same error:

```
Properties -> Linker -> System -> SubSystem to "Windows (/SUBSYSTEM:WINDOWS)"

```

## UPDATE II

I am using Visual Micro extension. But the problems is when I try to compile the Test project. Then I recreate this scenario with a C++ console application and create a simple class, and create a test project and added the console application reference to test project and it worked. Then my doubts is about to how do I configure a Test Project to test my Arduino project.

# Answer
> 1 votes
I use Visual Studio Community Edition 2013 along with the Visual Micro extensions, which I think is what you need as the "missing link" between VS and Arduino.

# Answer
> 0 votes
Visual Studio knows nothing about an Arduino project. Why would you be trying to reference it from the other project. Short answer is that you are not understanding how to use Visual Studio and / or Arduino. Are you using it with some plugin for visual studio? If you are more than likely it does not support being part of a multi solution (at least that has been my experience with them).

Long answer is give some more details about what you are trying to do, including code from both projects.

Update: Sorry but this is not an Arduino topic. You are fundamentally incorrect in your understanding of how compilers and linkers work and what they are for. As are the other answers. You can not reference a project compiled for an Arduino, from a project compiled for Windows, period. I ask you to explain what you were trying to do and I would give you some idea how to accomplish that, but you did not answer. Yes you can use Visual Studio to compile your Arduino project, I do it every day. But I do not 'reference' it from another project on Windows. Do you have any idea what a reference is?

update 2: You can not create a test suite for an Arduino project, at least not in the traditional way. You can not even debug an Arduino project in the traditional way. Arduino is for prototyping, and very basic beginner stuff, and nothing more. What you are asking about is more traditional development, and the Arduino is not for that (and does not do it very well).

Create 2 separate solutions. One with only your visual micro project for the arduino, and another separate solution with a regular C++ or C# project, not a test project or anything special, just a plain console, or winforms, or WPF project. The 2 pieces of code must be run at the same time (F5), and probably connect to each other via the serial port, but it depends on what you are doing.

This IS NOT testing in a traditional sense. This is test running a project. The traditional sense of testing is to test isolated portions of code, which is different, and again, can not be done with an Arduino and visual studio. Since the Arduino only remotely provides 2 wire debugging, and I have never heard anyone actually get it to work at all, you can NOT do any traditional debugging or testing with an Arduino. Instead you are limited to beginner hacks (serial.print).

# Answer
> 0 votes
You are trying to build a Windows program. You need a main() function as an entry point. I suspect that when your code is built through the Arduino IDE it adds in a main function in. You can tell Visual Studio to build your files differently by defining some build rules, but it sounds like someone may have done this sort of thing by looking at the other answers. But the easiest short term solution would be copying and pasting into the Arduino IDE.

# Answer
> 0 votes
The best place for answers is in the Visual Micro forum.

1. Be sure about is that the main .ino source file of your Arduino project matches both the name of the Visual Studio project and the name of the folder they existing in. For example:

* Folder = Sketch1
    * Master Source = Sketch1.ino
    * Visual Studio Project Name = Sketch1

This ensure Visual Micro will compile the project and also it will be compatible with the Arduino Ide.

2. With two projects in a Visual Studio solution it is important to note which is the "Startup Project". You can control which is the startup by right clicking a project in the explorer and clicking "Set as Startup project". The project name will then appear in **bold**.

The startup project affects which project is uploaded/started/debugged when you click any of the "Start" commands.

3. The menu item "Build\>Configuration Manager" allows you to exclude your Arduino project from Visual Studio Win32 builds but changing this option should not normally be required.
4. You can right click each project and click "Start\>New instance" to override the current "Startup project" and specifically build and upload a project.

**Summary**

If the build/upload fails and you see the visual studio c++ compiler error that you have described above this means that Visual Micro is not handling the build process for the project.

Therefore, please confirm point *1* is correct by trying out build task described in point *4* above.

It would be useful to know which build command you are selecting when the problem happens.

---
Tags: arduino-mega, visualstudio, testing
---


# Question
Title: Error in code saying "expected primary expression before "<" token" and other errors
I am Creating a laptop controlled robot using an arduino nano using the instructbles. I have tried running the code but it is throwing back lots off error and the main one is "expected primary expression before "\<" token"

as well as various other error. if anyone could take a look and try help me out i would be grateful thank you!

```
#include <NewPing.h>

#include <LiquidCrystal.h>

LiquidCrystal lcd(11, 8, 7, 4, 3, 2);
float temp =1;
int temppin = A0;
int r_motor_n = 9; //PWM control Right Motor +
int r_motor_p = 10; //PWM control Right Motor -
int l_motor_p = 6; //PWM control Left Motor -
int l_motor_n = 5; //PWM control Left Motor +
int f_light = A3;
int b_light = A4;
int horn = 12;
int n_light = 13;
int speedy = 255;
int incomingByte = 0; // for incoming serial data
#define TRIGGER A2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO A1 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER, ECHO, MAX); // NewPing setup of pins and maximum distance.
void setup()
{
pinMode(r_motor_n, OUTPUT); //Set control pins to be outputs
pinMode(r_motor_p, OUTPUT);
pinMode(l_motor_p, OUTPUT);
pinMode(l_motor_n, OUTPUT);
pinMode(f_light, OUTPUT);
pinMode(b_light, OUTPUT);
pinMode(n_light, OUTPUT);
pinMode(horn, OUTPUT);
digitalWrite(r_motor_n, LOW); //set both motors off for start-up
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
digitalWrite(l_motor_n, LOW);
Serial.begin(9600);
Serial.println("Start");
lcd.begin(16,2);
lcd.clear();
lcd.print("     Hello      ");
lcd.setCursor(0,1);
lcd.print("   I'm Robot   ");
delay(3000);
}
void loop()
{</liquidcrystal.h></newping.h></p><p>if (Serial.available() > 0)
{
incomingByte = Serial.read();
}</p><p>switch(incomingByte)
{</p><p>case 'S': // control to stop the robot
digitalWrite(r_motor_n, LOW);
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
digitalWrite(l_motor_n, LOW);
Serial.println("Stop");
lcd.clear();
lcd.print("Stop");
incomingByte='*';
break;</p><p>case 'R': //control for right
analogWrite(r_motor_n, speedy);
digitalWrite(r_motor_p, LOW);
analogWrite(l_motor_p, speedy);
digitalWrite(l_motor_n, LOW);
Serial.println("right");
lcd.clear();
lcd.print("Right");
incomingByte='*';
break;</p><p>case 'L': //control for left
digitalWrite(r_motor_n, LOW);
analogWrite(r_motor_p, speedy);
digitalWrite(l_motor_p, LOW);
analogWrite(l_motor_n, speedy);
Serial.println("left");
lcd.clear();
lcd.print("Left");
incomingByte='*';
break;</p><p>case 'F': //control for forward
analogWrite(r_motor_n, speedy);
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
analogWrite(l_motor_n, speedy);
Serial.println("forward");
lcd.clear();
lcd.print("Forward");
incomingByte='*';
break;</p><p>case 'B': //control for backward
digitalWrite(r_motor_n, LOW);
analogWrite(r_motor_p, speedy);
analogWrite(l_motor_p, speedy);
digitalWrite(l_motor_n, LOW);
Serial.println("backwards");
lcd.clear();
lcd.print("Backward");
incomingByte='*';
break;</p><p>case 'f': //control for stop
digitalWrite(r_motor_n, LOW);
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
digitalWrite(l_motor_n, LOW);
Serial.println("Stop");
lcd.clear();
lcd.print("Stop");
incomingByte='*';
break;</p><p>case 'd': // control for right
analogWrite(r_motor_n, speedy);
digitalWrite(r_motor_p, LOW);
analogWrite(l_motor_p, speedy);
digitalWrite(l_motor_n, LOW);
Serial.println("right");
lcd.clear();
lcd.print("Right");
incomingByte='*';
break;</p><p>case 'a': // control for left
digitalWrite(r_motor_n, LOW);
analogWrite(r_motor_p, speedy);
digitalWrite(l_motor_p, LOW);
analogWrite(l_motor_n, speedy);
Serial.println("left");
lcd.clear();
lcd.print("Left");
incomingByte='*';
break;</p><p>case 'w': // control for forward
analogWrite(r_motor_n, speedy);
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
analogWrite(l_motor_n, speedy);
Serial.println("forward");
lcd.clear();
lcd.print("Forward");
incomingByte='*';
break;</p><p>case 's': // control for backward
digitalWrite(r_motor_n, LOW);
analogWrite(r_motor_p, speedy);
analogWrite(l_motor_p, speedy);
digitalWrite(l_motor_n, LOW);
Serial.println("backwards");
lcd.clear();
lcd.print("Backward");
incomingByte='*';
break;</p><p>case 'J': // front lights on
digitalWrite(f_light, HIGH);
Serial.println("front lights on");
incomingByte='*';
break;</p><p>case 'j':
digitalWrite(f_light, LOW); // off
Serial.println("front lights off");
incomingByte='*';
break;</p><p>case 'K':
digitalWrite(b_light, HIGH); // back lights on
Serial.println("back lights on");
incomingByte='*';
break;</p><p>case 'k':
digitalWrite(b_light, LOW); // off
Serial.println("back lights off");
incomingByte='*';
break;</p><p>case 'G':
digitalWrite(n_light, HIGH); // neon lights on
Serial.println("neon lights on");
incomingByte='*';
break;</p><p>case 'g':
digitalWrite(n_light, LOW); off
Serial.println("neon lights off");
incomingByte='*';
break;</p><p>case 'H':
digitalWrite(horn, HIGH); // horn on
Serial.println("horn on");
incomingByte='*';
break;</p><p>case 'h':
digitalWrite(horn, LOW); off
Serial.println("horn off");
incomingByte='*';
break;</p><p>case 'O': // PWM speed values
speedy = 0 ;
Serial.println("speed= 0");
lcd.clear();
lcd.print("Speed=0");
incomingByte='*';
break;</p><p>case '1':
speedy = 155;
Serial.println("speed= 10");
lcd.clear();
lcd.print("Speed=10");
incomingByte='*';
break;</p><p>case '2':
speedy = 165;
Serial.println("speed= 20");
lcd.clear();
lcd.print("Speed=20");
incomingByte='*';
break;</p><p>case '3':
speedy = 175;
Serial.println("speed= 30");
lcd.clear();
lcd.print("Speed =30");
incomingByte='*';
break;</p><p>case '4':
speedy = 185;
Serial.println("speed= 40");
lcd.clear();
lcd.print("Speed=40");
incomingByte='*';
break;</p><p>case '5':
speedy = 195;
Serial.println("speed= 50");
lcd.clear();
lcd.print("Speed=50");
incomingByte='*';
break;</p><p>case '6':
speedy = 205;
Serial.println("speed= 60");
lcd.clear();
lcd.print("Speed=60");
incomingByte='*';
break;</p><p>case '7':
speedy = 215;
Serial.println("speed= 70");
lcd.clear();
lcd.print("Speed=70");
incomingByte='*';
break;</p><p>case '8':
speedy = 225;
Serial.println("speed= 80");
lcd.clear();
lcd.print("Speed=80");
incomingByte='*';
break;</p><p>case '9':
speedy = 235;
Serial.println("speed= 90");
lcd.clear();
lcd.print("Speed=90");
incomingByte='*';
break;</p><p>case 'q':
speedy = 255;
Serial.println("speed= 100");
lcd.clear();
lcd.print("Speed=100");
incomingByte='*';
break;</p><p>case 'p':
delay(50);  // display temp. and distance
unsigned int uS = sonar.ping();
Serial.print("Distance: ");
Serial.print(uS / US_ROUNDTRIP_CM);
Serial.println("cm");
lcd.clear();
lcd.print("Distance: ");
lcd.print(uS / US_ROUNDTRIP_CM);
lcd.print("cm");
lcd.setCursor(0,1);
temp = analogRead(temppin);
temp = temp * 0.48828125;
Serial.print("Temperature = ");
Serial.print(temp);
Serial.print("*C");
Serial.println();
lcd.print("Temp. = ");
lcd.print(temp);
lcd.print("*C");
delay(1000);
incomingByte='*';
break;</p><p>delay(5000);
}
}</p>

```

# Answer
> 2 votes
your code is ridden with html tags, like

`</p> <p>` or `</liquidcrystal.h></newping.h>`

Try removing them all, but it would be better if you could copy it from a plain ASCII source.

And when reporting a compiler bug, it's always good to paste it exactly as it is shown (it would have listed also line and possibly column where the error was detected)

---
Tags: programming, sensors, arduino-ide, arduino-nano, robotics
---


# Question
Title: Serial communIcation from OS X app to Arduino Mega
I am new to stack overflow. I have a question regarding using the USB serial communication sending data from an OS X app to the Arduino Mega 2560.

What happens is, when I have the Arduino running with the Serial monitor open, then I run the OS X app to send data, the Arduino does receive the data for a few seconds, then it stops.

This is the simplified Object-C code on the Mac side:

```
-(IBAction)sendData:(id)sender{
    NSString *toSend=[NSString stringWithFormat:@"echo %f > /dev/tty.usbmodem1a1341" ,vector.x];
    //vector is the continuous data generated by the Mac
    const char *toCSend =[toSend UTF8String];
    //converting to c string
    printf("%s", toCSend);
    popen(toCSend, "r");
}

```

This is the code on the Arduino side:

```
// Read Serial input:
void setup() {
  // Open Serial commurial1.beginnications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    // wait for Serial port to connect. Needed for Leonardo only
  }
}

void loop() {
  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    } else {
      // if you get a newline, print the string,
      // then the string's value as a float:
      Serial.println(inString.toFloat(), 6);
      // clear the string for new input:
      inString = "";
    }//end of if else
  }//end of while (Serial.available() > 0)
}

```

I am not sure what the problem, could it be the OS X app send out too much data to quickly? Or could it be the Arduino serial buffer is overflowed?

I really don't know much about serial communication so I don't know what I am missing. Any help will be greatly appreciated.

# Answer
> 1 votes
One problem is here:

```
  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    }

```

Your Serial.available() call guarantees that you have **one** byte of serial input, but you are attempting to read two of them if the first one is not a newline. This is not valid.

How to process incoming serial data without blocking

---
Tags: serial, communication
---


# Question
Title: Why is the output on the MOSI line shifted 1 bit over from what I commanded?
I've been trying to work with an AD5685R DAC. Per that datasheet, to get `DAC1` to output max voltage (5V), I would perform:

```
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE3); // DAC uses CPHA=1, CPOL=1

digitalWrite(CS, LOW);
SPI.transfer(0x31); // upper nibble sends a "write and update" command, lower nibble says "DAC1"
SPI.transfer(0xFF);
SPI.transfer(0xFC); // 14-bit DAC, last 2 bits are dontcares, make them 0
digitalWrite(CS, HIGH);

```

Replace `0xFFFC` with `0x0000` to get 0 volts out.

Sending this command as written somehow writes to `DAC4` instead of `DAC1`! and while 5V will come out when I write `0xFFFC`, I get to 2.5V when writing `0x0000` instead of 0V.

If I command this with a Bus Pirate and directly write the bytes out, it works exactly as desired.

I used the Bus Pirate to sniff the SPI traffic and it turns out I'm not getting what I've commanded. Rather than `0x31 0x00 0x00` for instance, I get `0x18 0x80 0x00`.

If we break this out into bits:

```
0x310000: 0011 0001 0000 0000 0000 0000 // commanded
0x188000: 0001 1000 1000 0000 0000 0000 // actually sent

```

So the command actually sent out is shifted by 1 bit!

Here's the bit pattern for 16383 counts (i.e., 2^14-1):

```
0x31FFFC: 0011 0001 1111 1111 1111 1100 // commanded
0x18FFFE: 0001 1000 1111 1111 1111 1110 // actually sent

```

The opcode corresponding to `0x18` is "write to input register 4" (the output occurs because I've pulled the `/LDAC` pin permanently low, see the datasheet), which explains why I'm getting an output on `DAC4` instead of `DAC1`.

This occurs with both a Sparkfun Pro Micro and an Arduino Mega 2560.

What is going on here? Why is the Arduino not sending out what I've actually commanded? Again, writing the hex codes directly to the DAC using a Bus Pirate works perfectly.

# Answer
> 1 votes
CPOL is clock **polarity**, and CPHA is clock **phase**.

The SPI modes are:

* Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)

* Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)

* Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)

* Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

---

According to your datasheet:

> Data from the SDIN line is clocked into the 24-bit input shift register on the falling edge of SCLK.

Judging by the diagrams on the datasheet, Mode 1 is what you want. You want the trailing edge of high to low.

More information at SPI - Serial Peripheral Interface - for Arduino

---
Tags: spi
---


# Question
Title: Lockup while evaluating Wire.requestFrom function (Arduino)
I am currently working on a Arduino project that combines an InertiaOne IMU sensor board (from Atmel), with an Arduino UNO and two motors driven by a Makeblock driver board. All sensors communicate using I2C, with different addresses. My issue is that the program runs just fine for a while (everything between 1 second and 2 minutes), but suddenly lock up inside the Wire.requestFrom-function that handles I2C communication. More specifically, I believe that the code hangs at one of these points in the Wire library (the code is a direct copy):

```
...
// wait until twi is ready, become master receiver
while(TWI_READY != twi_state){
    continue;
}
...
// wait for read operation to complete
while(TWI_MRX == twi_state){
    continue;
}

```

As far as I know, there are only two units that utilise I2C in the system, both of which are embedded onto the InertiaOne circuit board. What I find very strange is that reading these two sensors works just fine when no motors are running, but that the problem occurs when the motors are activated. My first reaction was to use separate power supplies for the motors and sensor board since the issue could have been caused by a dip in the voltage and a reset of the sensor board, but without any change of result.

I am running out of things to try, and do simply not have the required understanding of I2C and embedded systems to see what exactly the issue is. Could it simply be that some of my parts are faulty, or am I perhaps overlooking something?

# Answer
> 3 votes
The Wire library has an issue in the lines you posted, that if an interrupt is lost, it will stay in that loop forever. There are two things you could do to fix this:

* Stop the interrupt from being lost (ie. fix electrical problems)
* Use a library that has a time-out.

For the electrical issues, I would make sure you have pull-up resistors from SDA and SCL to +5V - typically 4.7k (for each one), but that would depend a bit on whether the device already has them. Also make sure you have decoupling capacitors on the Vcc lines as appropriate.

For the software side, there is an alternative library (master only) at Arduino I2C Master Library.

I haven't personally needed to use that library, as with pull-up resistors and short cable runs, I haven't had problems with the Wire library. However if things are marginal you may well find that it helps.

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


# Question
Title: Arduino sketch behaves differently depending on version of Arduino IDE
I am assisting some friends on an Arduino Uno project, and we've noticed that when using some earlier versions of the Arduino IDE (In this case 1.0.5), the sketch behaves as desired. However, when using 1.6.5, the program behaves differently. The sketch in question is here:

https://github.com/CymaSpace/Programs---Sketches/tree/master/Tim%20Gorbunov/a3%20with%20monosetting/a3

I have noticed that when enabling verbose compilation output, the size of the compiled binary is different between the two different IDE versions. There are also some warnings in the older IDE that are not present in the newer version. There is at least one other version before 1.6.5 that is behaving the same way as 1.0.5 (it's a later version but at the moment I don't know which, I will see if I can find out and post it here later).

Any idea why the two sketches might be behaving differently and how to go about troubleshooting the problem? This occurred on both a windows and mac computer. Thanks!

# Answer
> There are also some warnings in the older IDE that are not present in the newer version.

It is a **huge** mistake to disregards those warnings, especially:

> warning: array subscript is above array bounds

You declared an array `int useColor[2]`. Its length is 2 and its indices can be either 0 or 1. Yet you are using `useColor[2]`, which is out of bounds and likely to corrupt memory.

From the language point of view, this is called *undefined behavior*, which means that *anything* can happen. In particular, it could very well happen that the program behaves as you expect... which seems to be the case with IDE 1.0.5. Simply changing the compiler version, or event the compiler settings, can change the behavior.
> 0 votes

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: What maximum length of wire can I use to connect a push button to an Arduino?
I am trying to get 8 stop buttons to cause an Arduino UNO to activate a single relay!

The stop buttons have been placed 30' to 250' away from the Arduino uno board.

Q: How far can you go with 5v and still get signal back?

Q: Is there a way to boost the signal?

# Answer
> Q: how far can you go with 5v and still get signal back?

That depends on two main factors:

1. The gauge of the wire
2. The noise in the environment

Assuming a low-noise (where noise is negligible) environment, we will first look at the wire.

All wire has an inherent resistance to it. The thicker the wire, the lower the resistance. This table has good information about the resistance of different gauges of wire: http://www.powerstream.com/Wire\_Size.htm

Given a typical arrangement where the internal pullup resistor of the Arduino's IO pin is used to create an "active low" arrangement (`pinMode(x, INPUT_PULLUP`) the equivalent circuit can be seen as this:

Given that the "Input Logic Low" (VIL) level of an input pin (according to the ATMega328P Datasheet (Table 30-1) is 0.3Vcc, and Vcc is 5V, the input low level would therefore be 1.5V. The voltage present at the IO pin has to be below 1.5V in order for the input to be seen as a LOW.

The circuit, when the button is pressed, can be simplified to this:

That is a simple voltage divider. The formula for calculating Vout is (R2/(R1+R2))\*Vin. We know that the Vout limit is 1.5, and Vin is 5V. Also that R1 is approximately 50KΩ (very approximately). So we can rearrange the formula to:

R2 = R1(1/((Vin/Vout)-1))

Substituting our known values we have:

R2 = 50,000 × ( 1 / ((5 / 1.5) - 1)) = 21428.57Ω

So the total resistance of the wire permissible is around 20KΩ assuming the internal pullup resistor is 50KΩ (note: it could be as low as 10KΩ or as much as 70KΩ).

Divide that value by 2, since the wire has to run twice the distance (once there and once back again) and you get a total resistance of around 10KΩ for one leg of the journey.

Now assume a wire gauge of 24AWG. That has a resistance of 84.1976Ω/km. So we can work out that 10,000 / 84.1976 = 118.77km.

So with 24AWG wire you could theoretically have your button about 100km away from the Arduino and *just about* have it still register properly.

But of course that's with no noise, and there *will* be noise - especially over that kind of distance.

The noise will basically make the voltage seen at the input vary randomly around the theoretical value. Those wires act like great big antennae, and they pick up all sorts of stray EMI. The longer the wires the more noise there will be, and consequently the lower the voltage you will need to aim for (or higher voltage if using a pull-down arrangement - just turn the whole thing upside down) to keep the logic level below (or above) the right threshold value.

> Q: is their away to boost the signal?

Yes, you can use a higher voltage. There is nothing to say that you have to interface your button directly with the Arduino. There are many ways of having your button switch a higher voltage on and off and use that to trigger the Arduino. The simplest (and also the safest) may be to use an opto-coupler. Use your button(s) to switch a 12V power supply on and off, and that then passes through a suitable resistor to power the LED in the opto-coupler. That then switches on the built-in transistor to turn on the IO pin.

Another option may be to use a reliable communication bus with a small microcontroller at each stop-button point (maybe something like RS-485), though that may be overkill for this kind of application.
> 6 votes

# Answer
Majenko's answer is probably the safest option. There is, however, something simpler that you can try:

* Use a strong pull-up (or pull-down). Something around 1 kΩ will make it quite difficult for the noise to pull your signal low, at the cost of increased current consumption.
* Connect each push button to the Arduino using a twisted pair of copper wires. This will minimize the inductive pickup effect.
> 4 votes

---
Tags: voltage-level
---


# Question
Title: How do I add additional compiler switches in Visual Studio
Using Visual Studio to program my Arduino. I want to add additional compiler switches and include paths.

How can this be done?

# Answer
> 0 votes
Use the ExtraFlags in the project properties. The flags can be specified for the currently selected configuration or for all builds of the current project.

The feature was released in the 15.06 version of the Visual Micro Arduino plugin for Visual Studio.

This guide shows how to access the project properties

---
Tags: visualstudio
---


title: Attiny88 programming with Arduino

text:
# Question
Title: Attiny88 programming with Arduino
I want to program Attiny88 with Arduino IDE 1.6.5. I chose Attiny88 because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins. I found a library that support Attiny88 (https://github.com/TCWORLD/ATTinyCore) but it seams it does not support IDE 1.6.5 and generates errors when I burn bootloader or during ISP.

Is there any library to program Attiny88 with Arduino 1.6.5?

# Answer
> 2 votes
Finally I found ATTinyCore library. I have tested it with a blink sketch. Just download the zip file. Unzip and copy Attinycore-master directory into "program files/Arduino/hardware/arduino/avr" directory. Restart the IDEA. Select ATTiny x8 Series from the boards menu, and select the specific chip (48 or 88), clock speed, and BOD level from the appropriate menus that will appear in the tools menu after selecting ATTiny x8 series as the board.

https://github.com/SpenceKonde/ATTinyCore

# Answer
> 1 votes
I went through the same problem finding the cores for the attiny 88 and found this

http://forum.arduino.cc/index.php?topic=320742.0

programming attiny88 & attiny828 with arduino

However, I have not yet found the core for the attiny88 at 12mhz (http://co.mouser.com/ProductDetail/Atmel/ATTINY88-AU/?qs=sGAEpiMZZMvqv2n3s2xjscfa4zIkTHJI8r77%252bczQD%252bE%3d)

---
Tags: attiny, isp
---


# Question
Title: How to avoid pulling the RX0 pin to reset sketch
My project requires reading 5 serial devices (RFID readers) at the same time. I chose an Arduino Mega 2560 as it comes with 4 serial RX ports. For the fifth port I am using the SoftwareSerial library.

My loop() checks each Serial port to detect if an RFID tag is being read. This works perfectly.

However, I am powering the board from an wall wart. When the power is disconnected the sketch no longer runs. I must unplug RX0, plug in the power supply, and reattach RX0.

If the board ever loses power it will have to be reset manually which is not ideal.

Please help me understand Why is this happening? and how can I fix it?

# Answer
It looks like your RFID readers are very chatty on startup, and the board is going into bootloader mode.

I'd consider either controlling the RFID reader's power using another pin (and a transistor or mosfet if the reader needs more than 20mA), or using a gate ( `AND` for instance, or a simple switch IC like the 4066) that you can control to disable the `RX0` input until program start.

Another thing I've done in the past is multiplexed multiple serial devices to one serial input. The RFID readers probably have outputs that indicate a card presence, so use those and a multiplexor. When the card presence is indicated, connect that serial port using the multiplexor, read the card and act accordingly, then wait for another card detect event.
> 1 votes

# Answer
You can simply disable the bootloader rather than erasing it. Find out the current fuse settings using a fuse-detection program. Change the BOOTRST flag in the High fuse to be unchecked, referring to this page: Engbedded Atmel AVR® Fuse Calculator

Write the High fuse back. Then it will ignore the bootloader and go straight to your code. Of course, to upload a new version you will have to put the BOOTRST fuse back, or you won't be able to use the bootloader to upload a new sketch.

One way of changing the fuse is to use my Atmega chip stand-alone programmer sketch. This has an interactive "change fuses" option. To run this you just need a spare board (eg. a Uno) and 6 wires to connect the programming board to your target Mega2560.

Example wiring shown on the linked page. Note that you do **not** need the SD board to merely change fuses. Just the two Arduinos and the connecting wires are enough for that.

When you first run the sketch it should inform you of the current fuses. Look at the High fuse and follow my instructions above.

You should see something like this:

```
Entered programming mode OK.
Signature = 1E 98 01
Processor = ATmega2560
Flash memory size = 262144
LFuse = FF
HFuse = D8
EFuse = FD
Lock byte = FF
Bootloader in use: Yes

```

In this case the High fuse was D8, which has the bootloader enabled. Using the Fuse Calculator site we can see that it should now be D9 which disables the bootloader.

---

An alternative way to change the fuse is to use Avrdude, if you have a stand-alone ISP programmer handy.
> 1 votes

---
Tags: serial, arduino-mega, softwareserial, rfid
---


# Question
Title: best way to protect a digital or analog input from 12volts
At work, I have connected an Arduino to a security key (which has a 12v power supply) in order to give us a more versatile door lock. Unfortunately, people keep removing the key pad, disconnecting the wires and re-connecting them (defective keypad I guess.) In the process, I am afraid that they will accidentally send 12v into the Vcc, ground, digital in, and/or analog in pins. What is the best way to protect my Arduino from the 12 volts? I really need a component or two that I can to my pins.

Edit: it is difficult for me to describe this problem without mentioning the danger to all components. Please describe ways to protect digital outputs HERE

# Answer
There are some suggestions at Protecting Inputs in Digital Electronics.

*Amended answer*

Testing of my earlier answer involving clamping diodes gave unsatisfactory results. Due to the small current flow the diodes allowed a considerable voltage to reach the input pin (like, 9 V).

The amended circuit below, tested with 12V input, satisfactorily keeps the Arduino input pin to 4.9 V, even with 12 V from the device. The current through R1 is around 7 mA which is what you would expect:

```
I = V / R
I = 7 / 1000
I = 7 mA

```

The 1N4733A is a 5.1 V, 1 W zener diode which can therefore handle dropping 5 V at 7 mA.

In case you are wondering where the number 7 comes from in the calculations above:

* The input voltage is 12 volts
* The desired output is 5 volts
* Therefore we need to drop (12 - 5) volts over the resistor
* Thus 7 volts are dropped over the resistor

---

Further reference material:
> 5 votes

---
Tags: voltage-level, voltage-protection
---


# Question
Title: Delay not working in function other than loop
So I just got an Arduino and thought I would play around a bit.

However not five minutes in I already ran into a problem.

I tried programming a simple SOS blinking light sequence. To get rid of code duplication I refactored the on and off turning of the LED into functions and then again refactored a short blink and a long blink function which are expected to turn the LED on for a short time and then for a long time.

The problem is the delay in those functions is completely ignored.

```
int ledPin = 13;

void on()
{
 digitalWrite(ledPin,HIGH);
}

void off()
{
 digitalWrite(ledPin,LOW);
}

void shortB()
{
 on();
 delay(1000);
 off();
}

void longB()
{
 on();
 delay(2000);
 off();
}

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

void loop()
{
 shortB();
 shortB();
 shortB();
 shortB();
 longB();
 longB();
 longB();
 shortB();
 shortB();
 shortB();
 delay(5000);
}

```

My expected behavior would be that it does an SOS and then waits 5 seconds and repeats.

What really happens however is that it stay continuously lit for a second or so then turns off for 5 seconds.

Using

```
on();
delay(1000);
off();

```

In the main loop works so I guess it simply ignores the delays that are put into the other functions. My question would be why and ho do I fix it?

I know that I can use other timer function constructs however I really think this is something that should work by default.

# Answer
You have no delay in between turning the LED off and turning it back on. Add one.
> 1 votes

# Answer
In addition to the other problems, you should have a break between **letters**. So, for example, "S" is not just dot-dot-dot it is dot-dot-dot-pause.

Example code below that implements pauses between letters, as well as longer pauses between words.

```
const byte LED = 13;

char * letters [26] = {
   ".-",     // A
   "-...",   // B
   "-.-.",   // C
   "-..",    // D
   ".",      // E
   "..-.",   // F
   "--.",    // G
   "....",   // H
   "..",     // I
   ".---",   // J
   "-.-",    // K
   ".-..",   // L
   "--",     // M
   "-.",     // N
   "---",    // O
   ".--.",   // P
   "--.-",   // Q
   ".-.",    // R
   "...",    // S
   "-",      // T
   "..-",    // U
   "...-",   // V
   ".--",    // W
   "-..-",   // X
   "-.--",   // Y
   "--.."    // Z
};

char * numbers [10] =
  {
  "-----",  // 0
  ".----",  // 1
  "..---",  // 2
  "...--",  // 3
  "....-",  // 4
  ".....",  // 5
  "-....",  // 6
  "--...",  // 7
  "---..",  // 8
  "----.",  // 9
  };

const unsigned long dotLength = 100;  // mS
const unsigned long dashLength = dotLength * 3;
const unsigned long wordLength = dashLength * 2;

// get a line from serial
//  forces to upper case
void getline (char * buf, size_t bufsize)
{
byte i;

  // discard any old junk
  while (Serial.available ())
    Serial.read ();

  for (i = 0; i < bufsize - 1; )
    {
    if (Serial.available ())
      {
      int c = Serial.read ();

      if (c == '\n')  // newline terminates
        break;

      buf [i++] = toupper (c);
      } // end if available
    }  // end of for
  buf [i] = 0;  // terminator
  Serial.println (buf);  // echo what they typed
  }     // end of getline

void dot ()
  {
  digitalWrite (LED, HIGH);
  delay (dotLength);
  digitalWrite (LED, LOW);
  delay (dotLength);
  }  // end of dot

void dash ()
  {
  digitalWrite (LED, HIGH);
  delay (dashLength);
  digitalWrite (LED, LOW);
  delay (dotLength);
  }  // end of dash

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop ()
  {
  Serial.println ("Enter your message ...");
  char buf [60];
  getline (buf, sizeof buf);

  // for each letter
  for (char * p = buf; *p; p++)
    {
    char c = *p;
    char * sequence = NULL;

    if (c >= 'A' && c <= 'Z')
      sequence = letters [c - 'A'];
    else if (c >= '0' && c <= '9')
      sequence = numbers [c - '0'];
    else if (c == ' ')
      {
      delay (wordLength);   // gap between words
      continue;
      }

    // ignore not in table
    if (sequence == NULL)
      continue;

    // output sequence for one letter
    for (char * s = sequence; *s; s++)
      {
      if (*s == '.')
        dot ();
      else if  (*s == '-')
        dash ();
      }
    // now a gap
    delay (dashLength);
    }  // end of for each letter

  }  // end of loop

```
> 0 votes

---
Tags: programming, led, time
---


title: DIY Watering - Required components

text:
# Question
Title: DIY Watering - Required components
I am looking as a first project after some simple project kits, to make a watering system for my indoor plants. I have seen a few projects on instructables, so I went to look for components. I am not sure how to power the pump from the Arduino.

My idea is the following:

A bucket of water with a water pump inside. An irrigation system linked to the pump, which then goes to all the plants. The pump linked to arduino which turns it on and off based on a timer.

The components that I will be using are an Arduino uno and:

Also I guess I will need some tube to connect the pump to the watering kit.

I am not sure how to connect and power the pump (12V) with the arduino. The arduino it self will be powered by a USB on a wall socket.

# Answer
> 1 votes
I have some details about running motors etc. from Arduino pins at Driving motors, lights, etc. from an Arduino output pin.

Quite possibly what would work for you is a MOSFET - as Majenko suggested - connected up like this:

In this case you connect the positive side of your 12V supply for your pump to the pump, and the MOSFET sinks current to ground, when you require the pump on.

Don't forget the diode D1 which prevents damage from the inductive load of the pump generating high-voltage spikes.

---
Tags: arduino-uno, motor, voltage-level
---


title: fading colors on a ws2812 strip

text:
# Question
Title: fading colors on a ws2812 strip
I have a strip of 7 leds. its ws2812. Im starting them on blue. Next I want them to do a slow fade into pink. So all Im trying right now is to increment r.

I can get them to work one by one. But I need them to all fade together from blue to pink.

Ive moved my r++ loop around till I was cross-eyed. Still it didnt fade all 7 leds to pink all at once.

sometimes it would stay blue and do nothing sometimes fade to pink one pixel at a time.

How do I get all 7 leds to fade together? Thank you.

```
#include <FastLED.h>
#define NUM_LEDS 7
#define DATA_PIN 6
#define BRIGHTNESS 45
#define COLOR_ORDER GRB
#define g 50
#define b 100

int r; //changed it to undefined

CRGB leds[NUM_LEDS];

void setup(){
FastLED.addLeds<WS2812, DATA_PIN, GRB>(leds, NUM_LEDS);

 }
void loop(){

```

this lights all leds to blue

```
  for(int x = 0; x < NUM_LEDS; x++){

  leds[x] = CRGB(r,g,b);
 }
  FastLED.show();
  delay(10);

```

this code should grab all 7 leds in NUM\_LEDS store it in x

```
  for(int x = 0; x < NUM_LEDS; x++){

  leds[x] = CRGB(r,g,b);

```

Heres the problem area. I get no errors but it doesnt fade all 7 leds at a time. Ive tried moving my code around but it either doesnt fade or fades to pink one led at a time. where should my 'for loop' for incrementing r be at? Should I be changing rgb all at once using array?

```
//take r and fade it up to 254

for(int r = 0; r < 254; r++) {

  }
  }
     FastLED.show();
 delay(100);

}

```

# Answer
If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...

```
#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}

void loop(){

  // Let's take 256 steps to get from blue to red
  // (the most possible with an LED with 8 bit RGB values)

  for( int colorStep=0; colorStep<256; colorStep++ ) {

      int r = colorStep;  // Redness starts at zero and goes up to full
      int b = 255-colorStep;  // Blue starts at full and goes down to zero
      int g = 0;              // No green needed to go from blue to red

      // Now loop though each of the LEDs and set each one to the current color

      for(int x = 0; x < NUM_LEDS; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
      FastLED.show();

      delay(10);
  }

}

```
> 1 votes

# Answer
@bigjosh has provided code, so I will provide some plain text logic to explain what you should be doing.

To fade from one color to the next, in this case from Solid Blue (0,0,255) to Pink (Red + Blue, 255,0,255), you need to change the value a little, latch it, then wait before you change the value again. Pseudo code:

> rgb = 0,0,255
>
> write rgb
>
> wait X milliseconds
>
> rgb = r + 1,0,255
>
> write rgb
>
> wait X milliseconds
>
> loop until r = 255

At each step, you need to push out the value to the leds before delaying and then starting again. The delay can and should be varied to your satisfaction. I find a fast fade better. At single steps of r + 1, even slow delays will seem mostly smooth.
> 0 votes

---
Tags: c++, led, rgb-led
---


title: Connect an mp3 player to an Arduino?

text:
# Question
Title: Connect an mp3 player to an Arduino?
I have been looking for a good way to play sounds using an Arduino. I started to consider just buying a cheap mp3 player and replacing the player's buttons with optical switches, which connect to an Arduino. I wanted to know if anyone has done this before and if there was a good mp3 player for this (one that may have some sort of control port / ir sensor.)

# Answer
Yes, people have done this before, and they have documented it on their own blogs and similar sites. Maybe you should have asked Google first before you came here? You'd most likely have ended up on instructables, where someone has documented exactly what you want to do and how to do it. and saved yourself this entire step.
> 2 votes

---
Tags: sound
---


title: Motor Shield StepMotor

text:
# Question
Title: Motor Shield StepMotor
What the two yellow cables as you can see in the picture do not know?

# Answer
> 0 votes
There are two types of stepper motors: unipolar and bipolar. Bipolars usually have four wires and unipolars have six.

> --http://hobbymilling.com/wp-content/uploads/2011/05/Unipolar-stepper-motor-windings.png
>
> --https://www.codeproject.com/KB/system/steppermotorcontrol/pic6.jpg

The motor shield is designed to drive a bipolar motor (4 wires) but the motor is unipolar (6 wires). As you can see in the pictures, if you ignore the middle wire of the unipolar motor, it is the exact same as a bipolar stepper motor.

---
Tags: arduino-motor-shield
---


title: Encrypting data for webserver

text:
# Question
Title: Encrypting data for webserver
I'd like to send sensor values over ethernet shield to a webserver. But for this I'd like to encrypt the data on the arduino and decrypt it on the webserver (PHP). Do you have any suggestions or examples?

# Answer
XTEA is probably your best bet. It's lightweight, easy to implement, and secure enough for a bit of sensor data...

There's also the slightly more complex, and also slightly more secure, XXTEA:
> 1 votes

---
Tags: web-server
---


title: Attiny88 as SPI slave

text:
# Question
Title: Attiny88 as SPI slave
I have programmed Attiny88 with Arduino IDE 1.6.5 using https://github.com/SpenceKonde/ATTinyCore . I chose Attiny88 because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins with dedicated SPI. I wrote a code for arduino to work as SPI master, and a code for Attiny88 as SPI slave but I get only 0 as answer from Attiny.

SPI master code for ARduino UNO

```
#include <SPI.h>

// set up the speed, data order and data mode
SPISettings settingsA(2000000, MSBFIRST, SPI_MODE0);
const int slaveAPin = 10;

void setup() {
  // set the Slave Select Pins as outputs:
  Serial.begin(9600);
  Serial.println("SPI ON");
  pinMode (slaveAPin, OUTPUT);
  SPI.begin();
}

uint8_t stat, val1, result;

void loop() {
   // read two bytes from device A
   SPI.beginTransaction(settingsA);
   digitalWrite (slaveAPin, LOW);
   // reading only, so data sent does not matter
  stat = SPI.transfer(0);
  val1 = SPI.transfer(0);
  digitalWrite (slaveAPin, HIGH);
  SPI.endTransaction();
  Serial.println("data");
  Serial.println(stat);
  Serial.println(val1);
  Serial.println("end");
  SPI.endTransaction();
  delay(300);
}

```

SPI slave code for Attiny88:

```
#include <SPI.h>

// set up the speed, data order and data mode
SPISettings settingsA(2000000, MSBFIRST, SPI_MODE0);
const int slavePin = 14;
const int ledPin = 9;

uint8_t stat, val1, val2, result;

void setup() {
  // set the Slave Select Pins as outputs:
  pinMode (slavePin, INPUT);
  pinMode (ledPin, OUTPUT);
  // initialize SPI:
  digitalWrite(ledPin, HIGH);
  delay(1000);
  SPI.begin();
  stat =128;
  val1= 1;
}

void loop() {

  if (slavePin==LOW) {
    SPI.beginTransaction(settingsA);
    SPI.transfer(stat);
    SPI.transfer(val1);
    result = SPI.transfer(0);
    digitalWrite(ledPin, result);
    SPI.endTransaction();
  }

}

```

# Answer
> 2 votes
You do not appear to be configuring the slave as an SPI slave. Merely changing the pin modes won't achieve this. Example code at SPI - Serial Peripheral Interface - for Arduino \- however that does not specifically mention the Attiny88.

In my example in reply #1 on that page I have this code:

```
  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

```

This sets SPCR bit MSTR to zero (by not mentioning it). If you call SPI.begin() it will be activated in **master** mode.

It looks like the Attiny88 has the same register.

So in my opinion your code merely has two SPI masters.

Also, you seem to be doing 3 transfers in the master, but only 2 transfers in the slave.

---
Tags: arduino-uno, attiny, spi
---


title: Pinout of Arduino 9 Axes Motion Shield

text:
# Question
Title: Pinout of Arduino 9 Axes Motion Shield
I bought an Arduino 9 Axes Motion Shield without looking at the pinout. I'm worried it won't work with my Adafruit Motor Shield v1.

It seems the 9 axes shield uses I2C, a reset pin and several other pins for the TinkerKit Input, Output and TWI connectors. Does anyone have a list of specific ports used by the shield on the Arduino UNO?

It also seems that my Arduino UNO r1 only has the original analog pins for I2C, while the 9 axes shield uses the new pins next to the digital pins.

*update: I asked support from arduino.org on twitter and on their forums, no reply yet and it seems their twitter account has been suspended. Should have bought a Genuino I guess.*

# Answer
> 1 votes
The I2C pins on the V3 shield are just copies of A4 & A5 - so just run a jumper wire some way.

BTW that Motion shield looks like it only uses 1 interrupt pin in addition to I2C, so you may be ok.

The motor board does have a library at https://learn.adafruit.com/adafruit-motor-shield/downloads and you can look at the code to see what it uses.

I personally use the mpu6050 - same kind of thing, I2C one interrupt but only 6DoF (which is plenty). The 6050 has been superseded with the 9150, 9DoF. 6050 break out boards sell for $6 (or less). Actually I put all this together on one piece (http://www.spiked3.com/new-products/)

---
Tags: arduino-uno, pins
---


# Question
Title: Is there any way to run binary code from RAM?
I am looking for an inexpensive single board computer that I could program in assembly language, using limited facilities to load the object code from a PC and simple I/O peripherals.

Ideally I would like to be able to write in a reasonable time all the code on the machine myself. I don't want an OS in the way, as I want to have a program that writes in RAM some code and then branches to execute it. Arduino would probably be my best choice, as far as system simplicity suitable for assembly programming goes, but it has a Harvard architecture and it won't allow me to execute from RAM.

Years ago I was using a Von Neumann architecture 8-bit CPU that could branch execution to any address, no matter whether it was mapped to ROM, RAM or whatever. This is what I would like to do now.

I probably could write and load in Flash memory an interpreter of op codes written in RAM, but it is a very complex and time-consuming solution, unless virtual machines of this kind exist already.

Any suggestions on other workarounds with Arduino or of other micro-controllers I might use?

Thanks!

Pierre

# Answer
> 1 votes
In my opinion the interpreter idea is much more feasible. The notion of writing, in assembler, code that itself generates machine code, in RAM, and then executes it, is itself incredibly complex.

You haven't said why you want to do this, so this is somewhat of an X-Y problem.

> I don't want an o.s. in the way ...

The normal Arduinos do not have an OS in the way - basically the code you write is what gets loaded onto the chip.

---
Tags: memory-usage
---


# Question
Title: PROGMEM: do I have to copy data from flash to RAM for reading?
I have got some difficulties understanding the memory management.

Arduino documentation says, it is possible to keep constants like strings or whatever I don't want to change during runtime in program memory. I think of it as embedded somewhere in the code segment, which must be fairly possible inside a von-Neumann-architecture. I want to make use from that to make my UI menu on a LCD possible.

But I'm bewildered by those instructions to just read and print data from program memory:

```
strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy.
    Serial.println( buffer );

```

Why on earth do I have to copy the damn content to RAM before accessing it? And if this is true, what happens to all the code then? Is it also loaded to RAM before execution? How is the code (32kiB) handled then with only 2kiB RAM? Where are those little goblins carrying floppy disks?

And even more interesting: What happens to literal constants like in this expression:

```
a = 5*(10+7)

```

are 5, 10 and 7 really copied to RAM before loading them into registers? I just can't believe that.

# Answer
AVR is a modified Harvard architecture family, so code is stored in flash only, whereas data exists primarily in RAM when being manipulated.

With that in mind, let's address your questions.

> Why on earth do I have to copy the damn content to RAM before accessing it?

You don't need to per se, but by default code assumes that data is in RAM unless the code is modified to specifically look in flash for it (such as with `strcpy_P()`).

> And if this is true, what happens to all the code then? Is it also loaded to RAM before execution?

Nope. Harvard architecture. See the Wikipedia page for the full details.

> How is the code (32kiB) handled then with only 2kiB RAM?

The preamble generated by the compiler copies the data that should be modifiable/modified into SRAM before running the actual program.

> Where are those little goblins carrying floppy disks?

Dunno. But if you happen to see them then there's nothing I can do to help.

> ... are 5, 10 and 7 really copied to RAM before loading them into registers?

Nah. The compiler evaluates the expression at compile time. Whatever else happens depends on the lines of code around it.
> 10 votes

# Answer
This is how `Print::print` prints from program memory in the Arduino library:

```
size_t Print::print(const __FlashStringHelper *ifsh)
{
  const char PROGMEM *p = (const char PROGMEM *)ifsh;
  size_t n = 0;
  while (1) {
    unsigned char c = pgm_read_byte(p++);
    if (c == 0) break;
    n += write(c);
  }
  return n;
}

```

`__FlashStringHelper*` is an empty class that allows for overloaded functions like print to differentiate a pointer to program memory from one to normal memory, as both are seen as `const char*` by the compiler (see https://stackoverflow.com/questions/16597437/arduino-f-what-does-it-actually-do)

So you could overload the `print` function for your LCD display so that it takes a `__FlashStringHelper*` argument, lets call it `LCD::print`, and then use `lcd.print(F("this is a string in progmem"));' to call it.`F()\` is a macro that ensures the string is in program memory.

To predefine the string (to be compatible with built-in Arduino print) I have used:

```
const char firmware_version_s[] PROGMEM = {"1.0.2"};
__FlashStringHelper* firmware_version = (__FlashStringHelper*) firmware_version_s;
...
Serial.println(firmware_version);

```

I think an alternative would be something like

```
size_t LCD::print_from_flash(const char *pgms)
{
  const char PROGMEM *p = (const char PROGMEM *) pgms;
  size_t n = 0;
  while (1) {
    unsigned char c = pgm_read_byte(p++);
    if (c == 0) break;
    n += write(c);
  }
  return n;
}

```

which would avoid the `__FlashStringHelper` cast.
> 8 votes

# Answer
> Arduino documentation says, it is possible to keep constants like strings or whatever I don't want to change during runtime in program memory.

**All** constants are initially in program memory. Where else would they be when the power is off?

> I think of it as embedded somewhere in the code segment, which must be fairly possible inside a von-Neumann-architecture.

It's actually Harvard architecture.

> Why on earth do I have to copy the damn content to RAM before accessing it?

You don't. In fact there is a hardware instruction (LPM - Load Program Memory) which moves data directly from program memory into a register.

I have an example of this technique in Arduino Uno output to VGA monitor. In that code there is a bitmapped font stored in program memory. It is read from that on-the-fly and copied to the output like this:

```
  // blit pixel data to screen
  while (i--)
    UDR0 = pgm_read_byte (linePtr + (* messagePtr++));

```

A disassembly of those lines shows (in part):

```
  f1a:  e4 91           lpm r30, Z+
  f1c:  e0 93 c6 00     sts 0x00C6, r30

```

You can see that a byte of program memory was copied into R30, and then immediately stored into the USART register UDR0. No RAM involved.

---

However there is a complexity. For normal strings the compiler expects to find data in RAM not PROGMEM. They are different address spaces, and therefore 0x200 in RAM is something different from 0x200 in PROGMEM. Thus the compiler goes to the trouble of copying constants (like strings) into RAM at program startup, so it doesn't have to worry about knowing the difference later on.

> How is the code (32kiB) handled then with only 2kiB RAM?

Good question. You won't get away with having more than 2 KB of constant strings, because there won't be room to copy them all.

That's why people who are writing things like menus and other wordy stuff, take extra steps to give the strings the PROGMEM attribute, which disables them being copied into RAM.

> But I'm bewildered by those instructions to just read and print data from program memory:

If you add the PROGMEM attribute you have to take steps to let the compiler know that these strings are in a different address space. Making a complete (temporary) copy is one way. Or just print directly from PROGMEM, a byte at a time. An example of that is:

```
// Print a string from Program Memory directly to save RAM
void printProgStr (const char * str)
{
  char c;
  if (!str)
    return;
  while ((c = pgm_read_byte(str++)))
    Serial.print (c);
} // end of printProgStr

```

If you pass this function a pointer to a string in PROGMEM, it does the "special read" (pgm\_read\_byte) to pull the data from PROGMEM rather than RAM, and the prints it. Note that this takes one additional clock cycle, per byte.

> And even more interesting: What happens to literal constants like in this expression `a = 5*(10+7)` are 5, 10 and 7 really copied to RAM before loading them into registers? I just can't believe that.

No, because they don't have to be. That would compile into a "load literal into register" instruction. That instruction is already in PROGMEM, so the literal is now dealt with. No need to copy it to RAM and then read it back.

---

I have a lengthy description of these things on the page Putting constant data into program memory (PROGMEM). That has example code for setting up strings, and arrays of strings, reasonably easily.

It also mentions the F() macro which is an easy way of simply printing from PROGMEM:

```
Serial.println (F("Hello, world"));

```

A bit of preprocessor complexity lets that compile into a helper function which pulls the bytes in the string from PROGMEM a byte at a time. No intermediate use of RAM is required.

It is easy enough to use that technique for things other than Serial (eg. your LCD) by deriving the LCD printing from the Print class.

As an example, in one of the LCD libraries I wrote, I did exactly that:

```
class I2C_graphical_LCD_display : public Print
{
...
    size_t write(uint8_t c);
};

```

The key point here is to derive from Print, and override the "write" function. Now your overridden function does whatever it needs to output a character. Since it is derived from Print you can now use the F() macro. eg.

```
lcd.println (F("Hello, world"));

```
> 2 votes

---
Tags: flash, progmem, memory-usage
---


title: Determine XBee Packet Route

text:
# Question
Title: Determine XBee Packet Route
I am trying to build a ZigBee network using XBee Pro S2 devices (API Mode). Setting up the network and sending packets is easy enough.

Is it possible to trace the route a packet travelled from the end-device to the coordinator?

Example:
I have 2 routers, one in area A connected to the coordinator, and the other in area B connected to the router in area A. End-device enters area B, and transmits a packet to the coordinator.
**Path: end-device-\>routerB-\>routerA-\>Coordinator**.
Is it possible to know the end-device is in area B as it is the first router device the packet travelled through?

# Answer
It is done by using Source Routing

The 16-bit addresses of the hopped devices are added to the RF payload space, thus it will reduce the number of bytes that can be sent in one RF packet.
> 1 votes

---
Tags: xbee
---


title: coding problems

text:
# Question
Title: coding problems
I'm working on a Arduino controlled solenoid motor project that I found on Instructables. I have been able to piece together what I think is most of the code but I'm getting some syntax errors and was wondering if I could get some help? Here is the code and the errors.

```
   // Including Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>

LiquidCrystal_I2C mydisplay(0x27,16,2);

// Define Input/Output Pins
#define solenoidpin 9
#define potpin 1
#define ignitioninputpin 2
///#define interruptnumber 3
#define isr_rpm(INT0_vect)

// Defineing Variables
 int previousstate;
 byte buttonstate;
 int counter1;
 int start;
 int finish;
 int elapsed;
 int RPM;

// Main setup
void setup(){
  pinMode(ignitioninputpin,INPUT);
  digitalWrite(ignitioninputpin,HIGH);
////  attachInterrupt(3,isr_rpm, FALLING);
  counter1=1;

  mydisplay.init();
  mydisplay.backlight();
  mydisplay.setCursor(0,1);
  mydisplay.print(" Soleniod Motor ");

  previousstate=HIGH;
  Serial.begin(19200);
  buttonstate = digitalRead(ignitioninputpin);
}

// Main program loop
void loop() {
  buttonstate = digitalRead(ignitioninputpin);
  Serial.println(buttonstate);
  Serial.write("previousstate");
  Serial.println(previousstate);
  Serial.println(counter1);
  float elapsed=start=finish;
  float RPM= (6000/elapsed);
{

if  (buttonstate==LOW && previousstate==HIGH && (counter1%2)==0){
    digitalWrite(solenoidpin,HIGH);
  }

if  (buttonstate==HIGH && previousstate==LOW && (counter1%2)==0){
    digitalWrite(solenoidpin,HIGH);
  }

if  (buttonstate==LOW && previousstate==HIGH && (counter1%2)==0){
    digitalWrite(solenoidpin,LOW);
  }

if  ((counter1%2)==0){                                            for rpm calcs
    finish=start;
    start=millis();
  }

if  ((counter1%6)==0){
    mydisplay.setCursor(0,0);
    mydisplay.print(" RPM ");
    mydisplay.print(RPM);
    mydisplay.setCursor(0,1);
    mydisplay.print(" Solenoid Motor ");
  }

void ISR1();
  buttonstate=LOW;
  counter1=counter1+1;
  previousstate=HIGH;
  }
 }

```

Error messages:

Binary sketch size: 7,594 bytes (of a 32,256 byte maximum)

# Answer
Welcome to Arduino.SE. I am not going to rewrite the code for you but from this and other answers and comments you should be able to correct the code for yourself from constructive criticism.

To start at the beginning. You have defined `interruptpinnumber` but you don't use it in the `attachInterrupt` function as you declare interrupt pin 1(digital pin 3) and not 0 as the interrupt pin, this will cause problems in your code.

Next, for your timing variables, they need to be `unsigned long` as the `millis()` function will return unsigned long. There is also no need to declare them volatile as you are not using them in the ISR routine.

On the topic of the ISR, you have used the arduino attachInterrupt() and you have used the actual `ISR()` routine from the AVR libraries, also without including it. In the ISR you need to give it a vector which is not there and that is going to give errors later on. You also do not need the ISR routine if you have used the function from Arduino. You need to ensure that what you declare as the routine( that being `isr_rpm`) in the `attachInterrupt()` function to be executed when the interrupt occurs, actually exists.

Also there are some basic arithmetic issues with the `elapsed` time calculation, that is if you were trying to determine the difference.

As @Majenko also pointed out and I was going to too, that the use of a bitwise AND, `&` in your `if()` statements might not be a problem but best to learn now that you should use logical AND for comparison `&&`.

There is also a redundant `if` statement, that I will leave to you to find as it is your code and you can determine if it is of use or not. Also you need to keep track of you braces as this will cause the errors you are seeing too.

***Edit***

I think I need to elaborate on a few things as I think you got confused a bit more.

Concerning the whole arduino attachInterrupt function, the `isr_rpm()` needs to be a function and not a define, I think this caused it

> In the ISR you need to give it a vector which is not there and that is going to give errors later on. You also do not need the ISR routine if you have used the function from Arduino. You need to ensure that what you declare as the routine( that being `isr_rpm`) in the `attachInterrupt()` function to be executed when the interrupt occurs, actually exists.

A function of that would be:

```
void isr_rpm(){

   //code

}

```

As @Majenko has kindly done you a favor and annotated your code, look at the stuff *related to the interrupt routine* (and other stuff) and compare it with the below avrfreaks tutorial, and the original code if you have it, the problem to begin with was that you had *too many braces*:

```
void ISR(){
      buttonState = LOW;
      counter1 = counter1 + 1;
      previousState = HIGH;
    }
    }

```

it should be:

```
ISR(INT0_vect){
      buttonState = LOW;
      counter1 = counter1 + 1;
      previousState = HIGH;
    }

```

There is no need to give your own special name to ISR either, this is from the newer code.

AVRfreaks tutorial concerning interrupts and the ISR stuff it will give you an explanation on the volatile stuff too.

I cannot stress the point more but, look through your code that Majenko has annotated and see where you can fix the code.
> 3 votes

# Answer
Ok, I swore I wasn't going to do this, but I have re-formatted your latest code and I am going to go through and annotate it.

```
// Including Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>  /// << WHY?!  You're not using it!

LiquidCrystal_I2C mydisplay(0x27, 16, 2);

// Define Input/Output Pins
#define solenoidpin 9
#define potpin 1
#define ignitioninputpin 2
///#define interruptnumber 3
#define isr_rpm(INT0_vect)  /// << What is this hoping to achieve?

// Defineing Variables
int previousstate;
byte buttonstate;
int counter1;
int start;  ///
int finish; /// << These should be unsigned long
int elapsed;///
int RPM;

// Main setup
void setup() {
    pinMode(ignitioninputpin, INPUT);
    digitalWrite(ignitioninputpin, HIGH);
    ////  attachInterrupt(3,isr_rpm, FALLING);  /// << This will never work with that #define I pointed out...
    counter1 = 1;
    mydisplay.init();
    mydisplay.backlight();
    mydisplay.setCursor(0, 1);
    mydisplay.print(" Soleniod Motor ");
    previousstate = HIGH;
    Serial.begin(19200);
    buttonstate = digitalRead(ignitioninputpin);
}

// Main program loop
void loop() {
    buttonstate = digitalRead(ignitioninputpin);
    Serial.println(buttonstate);
    Serial.write("previousstate");
    Serial.println(previousstate);
    Serial.println(counter1);
    float elapsed = start = finish;  /// << You already defined these as ints in the global
    float RPM = (6000 / elapsed);    /// << scope. Why are you defining them again as floats?!  Also,
                                     /// << elapsed = start = finish?!?!  I think you have an = instead of a -
    { /// << Why are you starting a new block here???
        if (buttonstate == LOW && previousstate == HIGH && (counter1 % 2) == 0) {  /// << counter1 % 2 is very inefficient since counter1 is signed.
            digitalWrite(solenoidpin, HIGH);
        }

        if (buttonstate == HIGH && previousstate == LOW && (counter1 % 2) == 0) { /// << previousstate never changes from HIGH - this will NEVER run!
            digitalWrite(solenoidpin, HIGH);
        }

        if (buttonstate == LOW && previousstate == HIGH && (counter1 % 2) == 0) {  /// << You have already checked this state above with a different outcome.  WHY?!?!
            digitalWrite(solenoidpin, LOW);
        }

        if ((counter1 % 2) == 0) {
            for rpm calcs /// << This isn't even C!!!
            finish = start;

        start = millis();
        }

        if ((counter1 % 6) == 0) {
            mydisplay.setCursor(0, 0);
            mydisplay.print(" RPM ");
            mydisplay.print(RPM);
            mydisplay.setCursor(0, 1);
            mydisplay.print(" Solenoid Motor ");
        }

        void ISR1(); /// << This is a function prototype, not a function definition.
        buttonstate = LOW;       /// << I guess these should be inside
        counter1 = counter1 + 1; /// << a function called ISR1() but that
        previousstate = HIGH;    /// << function hasn't been written.
    }
}

```

You're trying to mess around writing low-level interrupt routines without having a clue how to work with low level interrupt routines. Go back and read the manuals on how to do external interrupts with Arduino. It's very very simple.

There are things about your program that just make me thing "What?!?!" and things that are just plain missing.
> 1 votes

---
Tags: arduino-uno, i2c, lcd, interrupt
---