# Question
Title: ArrayList implementation fails for string object
I'm using a customised C++ implementation of ArrayList based on the method found in Processing. The original code is by Obed Isai Rios, but I've added a version to Github with more explicit file structure. The arraylist is appended to by the `add_string_item` method, which works ok in the format `arraylist->add_string_item("text string")` but fails when the same input is a String variable. The following script illustrates:

```
#include "ArrayList.h"
void setup(){
  ArrayList *list = new ArrayList("text1");
  list->add_string_item("text2");
  String str = "text3";
  list->add_string_item(str);
}
void loop(){}

```

This fails on the last line with error message:

```
no matching function for call to 'ArrayList::add_string_item(String&)'

sketch_aug24b.ino: In function 'void setup()':
sketch_aug24b:7: error: no matching function for call to 'ArrayList::add_string_item(String&)'
/Users/robinedwards/Documents/Arduino/libraries/ArrayList/ArrayList.h:17: note: candidates are: void ArrayList::add_string_item(char*)

```

I'm not familiar with C++ so can't figure out why this method accepts a string but not when assigned to a String object `str`. I'm pretty sure it's because I need to coerce to char\* but not sure how to do this. I've tried `toCharArray` without success, although this seems the right direction. Very grateful for any assistance.

ArrayList.cpp code:

```
#include "Arduino.h"
#include "ArrayList.h"

ArrayList::ArrayList(char* init){
  stringlist = (char**)malloc(10*sizeof(char*));
  stringlist[0] = init;
  this->size = 1;
}

ArrayList::~ArrayList(void)
{
}

void ArrayList::add_string_item(char* item){
  char **neulist = (char**)malloc((size+1)*sizeof(char*));
  for(int i=0; i<size; i++){
    neulist[i] = stringlist[i];
   }
   //
   neulist[size] = item;
   stringlist = neulist;
   size = size + 1;
}

void ArrayList::set_string_item(char* item, int index){
  stringlist[index] = item;
}

void ArrayList::remove_selected_item(int index){
  char **neulist = (char**)malloc((size-1)*sizeof(char*));
  //From Begining
  for(int i=0; i<index; i++){
    neulist[i] = stringlist[i];
  }
  //From next Index
  for(int i=index; i<=size-1; i++){
    neulist[i] = stringlist[i+1];
  }
  //free(matrix);
  stringlist = neulist;
  size = size - 1;
}

void ArrayList::empty_list(){
   size = 1;
   char **neulist = (char**)malloc((size)*sizeof(char*));
   stringlist = neulist;
   stringlist[0] = "EMPTY";
}

void ArrayList::display_string_list(){
   Serial.begin(9600);
  for(int i=0; i<size; i++){
    Serial.println(stringlist[i]);
   }
}

char** ArrayList::get_stringlist(){
  return this->stringlist;
}

char* ArrayList::get_item(int index){
  return this->stringlist[index];
}

void ArrayList::set_stringlist(char** stringlist){
  this->stringlist = stringlist;
}

int ArrayList::get_size(){
  return this->size;
}

```

# Answer
*In theory*, there's no reason why you shouldn't be able to call it by using `toCharArray()`. You would need to call it like this:

```
String str = "text3";
char * buf = new char[str.length()+1];
str.toCharArray(buf, str.length()+1);

list->add_string_item(buf);

```

That allocates a `char` buffer, copies the string data into it, then passes that buffer pointer to the list to be stored. Note that the buffer is one character larger than the string, as it needs to add a null terminator at the end.

However, there is a **major** problem with the rest of your code, which could eventually cause your Arduino to crash or do other strange things (depending on how much you use the list object).

Unlike Java, C++ is not a garbage-collected language, meaning it won't automatically clean-up memory for you. If you call `new` or `malloc()` to allocate heap memory, you have to call `delete` or `free()` (respectively) when you're finished with it to deallocate it.

Simply overwriting a pointer with another call to `malloc()` is not enough; it results in a **memory leak**. This means the block of memory it was previously using is lost, and cannot be reused again as long as the program is running. On a platform like Arduino, which has limited memory, you can very quickly run out.

Fixing the design of your class is probably beyond the scope of an answer on this site. I would strongly recommend working through some C++ tutorials (of which there are hundreds online).

As a side note, you should generally use `new`/`delete` instead of `malloc()`/`free()`. It doesn't make much difference when you're using arrays of `char` or `char*`, but it's important if you want to allocate class instances.
> 2 votes

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


# Question
Title: What is the capability of AVRISP and USBASP on ATMega48, 328, 2560?
For use with ATMega 48 (old Arduino?), 328 (UNO, Pro Mini) and 2560 (Mega2560) chips, what is the capability for the AVRISP and USBASP programmers on:

1. Can it read, write fuse?
2. Can it read, write Program Flash?
3. Can it work 3.3 and 5 volts?
4. What workable clock frequency range on the MCU?
5. Can it be used under Arduino ISP to write to board so as to erase the bootloader and use the FULL flash space for big user program (eliminate boot loader saves 0.5 to 8KB space on above Arduino boards)?
6. Can it be used with ATMel factory software development tools (Atmel studio and associated tools) to use MCU on chip hardware based breakpoint (Debug wire, JTag, or other names, as on different MCU)?

Many thanks in advance

# Answer
> 1 votes
1. Yes.
2. Yes.
3. Depends on the specific hardware. See the documentation for the *exact* variant you have.
4. See 3.
5. No. They have their own protocol that you must use instead. They are selectable from the `Programmer` menu in the IDE though. However, you must unprogram the fuse bits outside of the IDE.
6. No. They are low-cost tools meant to be used for programming only. You will need an Atmel-supplied debugger in order to use Atmel Studio's debugging features.

---
Tags: flash, debugging, fuses
---


title: Using an array as a queue

text:
# Question
Title: Using an array as a queue
I recently created a state machine for my latest Arduino project. It is a simple LED control, but it has many different modes and functions. I created a template for my state machine so I can use it in the future, but I am looking to take it to the next level. Here is a copy of the current template for reference:

```
/*Setup Variables here*/
int nextState;
int currState;

/*Fill enum with all case names*/
enum cases{

  init;
  idle;
  case1;
  case2;
  leave;

};

/*Begin Program*/
void setup(){
  Serial.begin(9600);
  currState = init;
}

void loop(){
  switch(currState){

    case init:
      /*Prepare program here*/
      nextState = idle;
      break;

    case idle:
      if (input1){
        nextState = case1;
      }else if (input2){
        nextState = case2;
      }else{
        nextState = idle;
      }

    case case1:
      //Code for case1 here
      break;

    case case2:
      //Code for case2 here
      break;

  }

  currState = nextState;
}

```

I am trying to make a Queued State Machine (QSM). This means that instead of a single variable nextState, I can add several states to be executed. Is the best way to do this an array? I have not found much in my research about how to add and remove elements easily, so if this is the best way, could you point me towards a good tutorial on these types of array functions?

Thanks in advanced for all the help!

# Answer
> 5 votes
Have an array with fixed size, and have **two** indexes. One pointing to the first/current item in the queue, the other to the last item in the queue.

(It actually better/easier to have the second index point to where the next item has to be written)

To add an item to the queue:

1. Check that that the queue isn't full (second index is the same as the first)
2. If not write to second index.
3. Increment second index, and modulo array/queue size, so it wraps around.

To read from the queue

1. Read value at the first index
2. Increment first index, modulo array/queue size

---
Tags: programming, c++
---


# Question
Title: Why is Arduino STINO upload function not working?
I'm using sublime text for editing and modifying my arduino libraries. Sublime text is pretty pretty, useful and embed a very powerfull plugin system. Someone created an Arduino plugin for it. The compilation function works but the upload doesn't.

I'm trying to upload on an arduino leonardo using Windows 7 x64.

Did anyone tried to fix this problem ?

# Answer
I finally found it: Problem was solved after commenting those three lines in \*/Arduino-like IDE/app/uploader.py:

```
if force_to_reset:
    pre_serial_port = serial_port
    wait_for_upload_port = self.args.get('upload.wait_for_upload_port', 'true') == 'true'
    serial_port = resetSerial(pre_serial_port, self.output_console, wait_for_upload_port)
    # if self.args['cmd'] != 'avrdude':
    #   if serial_port.startswith('/dev/'):
    #       serial_port = serial_port[5:]
    if serial_port:
        for cur_command in self.command_list:
            command_text = cur_command.getCommand()
            command_text = command_text.replace(pre_serial_port, serial_port)
            cur_command.setCommand(command_text)

```
> 2 votes

---
Tags: uploading, arduino-leonardo, arduino-ide, debugging
---


title: Control Arduino via Wifi directly?

text:
# Question
Title: Control Arduino via Wifi directly?
I want to build an arduino-based RC Tank, which should be controlled with a notebook or smartphone (Android). Bluetooth would be an easy solution, but the range is a bit short for a RC Vehicle, so I want to controll it via WIFI. I found a ton of examples and tutorials on how to do that but all of them reqire a router which both the arduino and the Smartphone are connected to. Any idea on how to directly control an Arduino with an smartphone via WIFI?

# Answer
If your computer/tablet/phone can act as a WiFi hotspot, you could use that to avoid the router. Many smartphones have that capability, as do many notebooks (as geometrikal mentioned, it's usually referred to as an 'ad-hoc' network on PCs). Create the network (or turn on hotspot capability), and connect to the network you created from your Arduino.
> 1 votes

---
Tags: wifi
---


# Question
Title: Uploading bootloader on ATmega328P SMT package using Arduino Uno
I have been trying to upload bootloader on ATmega328P SMT package on a custom PCB using Arduino Uno as ISP, I was quite successful.

I have Googled a lot and have tried numerous ways, sometimes I was able to successfully upload the bootloader, but I am not able to upload the sketch am getting "avr sync error".

* What kind of bootloader should I use for this particular package?
* How should I upload the sketches into the chip?

# Answer
> 2 votes
I've had success with bootloader of the Arduino IDE. I used to have some trouble uploading sketches, but I solved them by doing this:

1. If the atmega is already soldered in a pcb and you have a pull up resistor, or something else connected to the reset pin, disconnect it. reset pin must be free.
2. Connect the tx, rx and rst pins of your atmega to your arduino.
3. Press the Upload button in the Arduino IDE and see the leds tx,rx in your arduino, just after the first blink, press the reset button, after that both of the leds should start blinking and in the end your code should be uploaded.

---
Tags: bootloader
---


# Question
Title: Arduino Wifi Shield with monitor mode ( promiscuous mode )
Is there a WiFi Shield or driver that supports monitor mode and receiving raw packets ?

# Answer
> 2 votes
Does it have to be a shield?

I would consider buying a cheap Wi-Fi router instead with good open-source support and a way to interface it to the Arduino. Their price is near to the price of Wi-Fi shields.

* They consume little power, can be powered by 5V and have built in Wi-Fi.
* Some have a built-in USB port, most have a serial port, which can be used to talk to the Arduino.
* You would have to put custom firmware on it, plus the program which receives the raw packets for you.

Specifically, I would get a TP-Link TL-WR703ND for this task.

* It can be fed 5 Volts, or 3.3 Volts with a little hacking
* It has USB
* It also has serial, and you can even hack an I2C port onto it
* It can run OpenWRT

More info on this particular router

---
Tags: wifi
---


title: Mac Power via Keyboard Shortcut?

text:
# Question
Title: Mac Power via Keyboard Shortcut?
many mac keyboards have a power button. Is there a way to mimic this power button shortcut from an arduino?

# Answer
There are multiple ways to do that.

* You could use an Arduino Leonardo as a keyboard, then send a shortcut command to shut down or sleep the computer. You can edit these from System Preferences\>Keyboard\>Shorcuts\>Services. The keycode 0x66 does not work for mac, but may for other operating systems source
* You could write a small program (I'd do it in Python) which communicates with the Arduino over the serial port and shuts down the Mac if the Arduino wants it to.
* You could sacrifice an USB keyboard and use a relay to "press" the power key.
> 2 votes

---
Tags: mac-os
---


# Question
Title: Leonardo (32u4): ways to brick it programmatically
When the Leonardo was introduced, I think, I've read some articles about being cautious to do some things, that could cause it to not load any new sketches any more, so one has to rewrite the bootloader. Because I plan to use power-saving options, e.g. to disable unused hardware components like USB port, I fear to do something wrong.

One Leonardo-delicacy I've found so far:

* if interrupts are disabled, uploading new sketches fails unless one presses the Reset button as soon as the Arduino IDE is showing "Uploading..."

What stuff (except of the usual hardware-related thinks like connecting output-configured pins to fixed potentials) could damage the controller or require to reflash the Leonardo with a fresh bootloader?

# Answer
> 1 votes
If you upload a program that changes the speed of the USB core it would be almost bricked. What would happen is this:

1. Power on, boot loader starts, USB device enumerated on PC.
2. A few second later program start, USB core speed changed, USB device disappears from PC

The issue here is that not only do you have to hit reset to program, after the reset you have to quickly select the right com port and then upload before the program starts.

The Redbearlab Blend Micro requires a USB core speed to be set in the user program. In their setup instructions there is a step to edit the Arduino main.cpp and add a section to do so. If this step is missed, the above problem happens.

# Answer
> 1 votes
I managed to brickwall an ATMega128RFA1. The bootloader, and the software I uploaded in it, were working fine. But it was impossible to erase/write the ROM.

After checking for what have happened, I discovered in the datasheet that some fuses in the AVR core are intended to protect accidental writing on the ROM. Some kind of security fuses.

I never found the bug which wrote in these bytes (as it was a really big program and we were 3 peoples involved in the coding) but yeah, we just blew a fuse and lost an MCU because of a bug.

As for the leonardo, several things could happen, but none of these can brickwall your board unless you blow one of this protection fuse.

# Answer
> 1 votes
It is possible, with some really clever code, to exploit the bootloader to overwrite itself.

Excerpt:

> The solution is actually conceptually fairly simple. A bootloader, by its very nature is designed to download new firmware to the device. Therefore it will contain at least one spm instruction. Because the spm configuration register must be written no more than 4 cycles before the spm instruction it means there are very few sequences that practically occur: just sts, spm or out, spm sequences. So, all you need to is find the sequence in the bootloader section; set up the right registers and call it.
>
> However, it turned out there was a major problem with that too. The V-USB self-programming bootloader's spm instructions aren't a neat little routine, but are inlined into the main code; so calling it would just cause the AVR to crash as it tried to execute the rest of the V-USB bootloader.
>
> Nasty, but again there's a solution. By using a timer clocked at the CPU frequency (which is easy on an AVR), you can create a routine in assembler which sets up the registers for the Bootloader's out, spm sequence; calls it and just at the moment when it's executed the first cycle of the spm itself, the timer interrupt goes off and the AVR should jump to your interrupt routine (in Application space). The interrupt routine pops the bootloader address and then returns to the previous code - which is the routine that sets up the out, spm sequence. This should work, because when you apply spm instructions to the bootloader section the CPU is halted until it's complete.

So basically, you can do some fancy programming, and get the bootloader to hose itself, rendering the MCU useless without a dedicated programmer.

# Answer
> 0 votes
The one I know of is making the Leonard act like a USB mouse that flaps everywhere and types random keys so you can't reprogram it without doing some kind of trick to get around it. But they mention this on the api docs.

---
Tags: power, arduino-leonardo
---


# Question
Title: What's the best way to control a USB-powered desk light
I recently bought a USB-powered desk light. Is it possible to control (turn on/off) it with the Arduino Uno? The desk light has 3W so needs 600mA.

1. Should I connect the USB wire with the 5V pin of the Arduino (which can spend up to 800mA) or should I use an external USB power supply ?
2. How to control the light when using an external USB power supply ?

# Answer
Use a TIP120 Darlington transistor to switch the current. This webpage has a detailed guide. http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/ Use the example with the light bulb - no diode is needed in your case.
> 0 votes

# Answer
You have a couple options here. The main idea is that you're going to add a switch to the light's circuit and that switch will be controlled by the arduino. It's important that you keep the electronics for the light and the electronics for your arduino separate, 600mA will damage your arduino which no one wants. You can power the light and arduino from the same power supply, make sure it can handle the power draw though.

To actually switch the circuit you could use an NPN transistor as mentioned above, with the lamp's - terminal flowing into the C pin, an arduino GPIO pin connected to the B pin and the E pin grounded. When you set your arduino's pin `HIGH` the transistor will allow current to flow and light up the lamp.

Another option that actually physically separates the circuits is to use an opto-coupler. They're little IC's that serve this exact purpose. The have a light and a light sensitive transistor inside them, so when the light illuminates, the transistor allows current to flow. In your case, you would hook up an arduino pin to the + pin on the light side of the coupler and ground the - pin. Then connect your lamp in the same to the other side, +5v into the + pin on the transistor side and the lamp's positive terminal to the output pin. Again, when the arduino pin goes `HIGH`, the lamp will light up.
> 0 votes

# Answer
* **power lamp from 5v source ( not from the arduino 5v port, but could be spliced into the same line powering the arduino or use a hub )**
* **use a transistor to switch the usb 5v line**
    + **connect the base pin (and resistor) of the transistor to any arduino digital out pin**
> -1 votes

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


# Question
Title: File Size Problem with EyeFi SD Card and Arduino Mega
I've been writing to an EyeFi SD card with an Arduino Mega. I've managed to get the files to upload wirelessly, but I noticed that my data gets cut off when the file reaches a size of 24 kb. If I use a normal SD card, the file is able to keep logging past 24 kb. The EyeFi card is able to upload large images, so I'm not sure what is limiting my file size for the EyeFi card. Can I get some advice?

```
/*************** SETUP ***************/
void setup(void)
{
  Serial.begin(115200);

  // initialize the SD card
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT); // make sure that the default chip select pin is set to

  // see if the card is present and can be initialized:
  if (!SD.begin(10,11,12,13))
  {
    error("Card failed, or not present");
  }
  Serial.println("Card initialized");

  // see if the directory exists, create it if not.
  if( !SD.exists(directory) && !SD.mkdir(directory) )
    error("File directory not created");

  newFile();

  Serial1.begin(115200);

  while (Serial1.peek() != '!' )
    Serial1.read();

  i = 0;
}

/*************** MAIN LOOP ***************/
void loop(void)
{
  if (Serial1.available())
  {
    logfile.print( (char)Serial1.read() );
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    logfile.flush();

    if( logfile.size() > 20480 && logfile.size() < (20480 + SOFT_BUFFER_SIZE) )
      Serial.println("Minimum File Size Achieved.");

    i = 0;
  }
}

```

# Answer
After some testing and research, I found out that the Eye-Fi SD card starts a transfer once a file reaches 20kb or more and will not upload a file again once it has been transfered already. The solution, as suggested by ChrisStratton, is to log to a temporary file and trigger a transfer once the file is ready.

I took advantage of the fact that the Eye-Fi only transferring files in the standard camera folders. In my case, I used the Nikon naming convention: DCIM/100NIKON/DSCNxxxx.JPG (xxxx is the photo number ranging from 0000 to 9999), but there are also others. Check on the Eye-Fi website for compatible cameras. I created a temporary file called TEMP.TMP and stored it to the root folder of the card and logged to it. Once I'm ready to transfer the file, TEMP.TMP gets renamed to "DCIM/100NIKON/DSCNxxxx.JPG" and the whole file is transferred all at once.

Here's my code. I'm using the software serial (pins 10, 11, 12, 13) of the Mega:

```
//Running with 256kb serial buffer (modified HardwareSerial.cpp)
//Added file time stamps

#include "SdFat.h"
#include "SdFatConfig.h"
#include <Wire.h>
#include "RTClib.h"

#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_Serial     1 // echo data to Serial port
#define WAIT_TO_START      0 // Wait for Serial input in setup()
#define MESSAGE_SIZE      11 // Message size of "!G N +1234" + CR
#define SOFT_BUFFER_SIZE  256// 25 Messages of 11 chars each

const uint8_t chipSelect = 10;

SdFat sd;
SdFile logfile; //create log file

RTC_DS1307 RTC;
DateTime filedate;

uint16_t date;
uint16_t time;

int i = 0;
int x = 0;

char directory[] = "DCIM/100NIKON";
char filename[] = "DCIM/100NIKON/DSCN0000.JPG";
char tempfile[] = "TEMP.TMP";

/*************** ERROR ***************/
void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  while(1);
}

/*********** TEMP FILE CREATION ***********/
void newFileName()
{
  sd.chdir("/"); //check DCIM/100NIKON directory
  // create a temp file
  for (uint16_t i = 0; i < 10000; i++)
  {
    filename[18] = i/1000 + '0';
    filename[19] = (i/100)%10 + '0';
    filename[20] = (i/10)%10 + '0';
    filename[21] = i%10 + '0';
    if (! sd.exists(filename))
    {
      Serial.print("New file name: ");
      Serial.println(filename);
      break;  // leave the loop!
    }
  }
}

/****** call back for file timestamps *****/
void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

/*************** SETUP ***************/
void setup(void)
{
  Serial.begin(115200);
  Wire.begin();
  RTC.begin();

  if(! RTC.isrunning() )
    Serial.println("RTC is not running");

  // set date time callback function
  SdFile::dateTimeCallback(dateTime);

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

  // see if the card is present and can be initialized:
  if (! sd.begin(chipSelect, SPI_HALF_SPEED))
    error("Card failed, or not present");

  Serial.println("Card initialized");

  // see if the directory exists, create it if not.
  sd.chdir("/");
  if( !sd.exists(directory) && !sd.mkdir(directory) )
    error("File directory not created");

  // create new file name
  newFileName();

  // Scan root folder for temp files
  sd.chdir("/");
  while( logfile.openNext(sd.vwd(), O_READ)){
    if( !logfile.isDir() ) {
      logfile.printName(&Serial);
      if( logfile.fileSize() < 20480 ){
        Serial.print(" file size too small. ");
        Serial.print(logfile.fileSize());
        Serial.println(" bytes.");
        logfile.remove(); //Delete under sized files
      }else
        if( !logfile.rename(sd.vwd(), filename))
          error(" could not be renamed.");
        else{
          Serial.print(" renamed to ");
          Serial.println(filename);
        }
    }
    logfile.close();
  }

  // create temp file
  sd.chdir("/");
  if(!logfile.open(tempfile, O_WRITE | O_CREAT)) // only open a new file if it doesn't exist
    error("couldnt create temp file");

  Serial1.begin(115200);

  // Rotate the buffer
  for( int j = 0; j < 256; j++) {
    Serial1.read();
  }

  // Look for the '!' character
  while (Serial1.peek() != '!' )
    Serial1.read();

  Serial.println("Logging...");
  Serial.println();

  // Reset buffer index to 0
  i = 0;
}

/*************** MAIN LOOP ***************/
void loop(void)
{
  if (Serial1.available()){
    logfile.print( (char)Serial1.read() );
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    logfile.sync();
    i = 0;
  }
}

```
> 2 votes

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


title: Arduino Underwater Inertial Navigation

text:
# Question
Title: Arduino Underwater Inertial Navigation
I am working on prototyping an underwater navigation system with Arduino. It's going to be used to track movement underwater from a starting point and then be able to tell how to get back to that point or relatively close. The unit would only be going a few hundred feet underwater.

I am using an Arduino Nano, is this going to be sufficient? Also, what IMU would you recommend? I'm sure it will need to at least have a 3-axis gyroscope, 3-axes accelerometer, and possibly a 3-axis magnetometer.

This does need to be relatively affordable. Currently I'm building a unit that can go underwater and just record data onto an SD card so that I can take the data and map it out to check the IMUs accuracy, error margin, along with test various filters on the data. Any recommendations would be greatly appreciated.

# Answer
> 4 votes
The nano can run an IMU just fine, but unfortunately no accelerometer based IMU short of some fancy missile guidance tech is going to be able to track position as accurately as you seem to want.

Since the Gyro and Magnometer only help with rotational orientation, the accelerometer is the only source of info on linear motion, and it has to be integrated twice to get position or distance. This site has a great explanation: http://www.chrobotics.com/library/accel-position-velocity

As their table shows, even with an angular error of only .1 degrees, after 1 minute your position could be off by 62 meters with a standard quality accelerometer.

As far as IMU's go, the MPU 6050 (accl, gyro) and MPU 9150 (Accl, gyro and mag) are pretty standard in the hobby area, and sparkfun has some breakouts. The AltiIMU from Pololu has similar features and comparable cost. If you don't want to do the sensor processing the UM7 from chrobotics works well, but is significantly more expensive.

---
Tags: arduino-nano
---


# Question
Title: Arduino Uno- Analog serial monitor not reading values over 174
I am simultaneously using a LEGO sound sensor in pin A5 and a RadioShack Tricolor LED Strip (Product #2760339) in pin A0.

The sound sensor alone works as expected (producing values based on volume) running only code to read the value and output to the serial monitor. However when I upload the program to use the LED strip, read the sensor value and output to the serial monitor, the sensor value caps at 174.

The program given to run the LED strip can be found at http://blog.radioshack.com/2013/06/tricolor-led-strip/ The code I added to this was pulled mostly directly from the AnalogInOutSerial example provided by Arduino.

Here is the full code;

```
/***************************************************************************/
//            Hardware: RadioShack Tricolor LED Strip
//            Arduino IDE: Arduino-1.0
//            Date:      April 17, 2013
//            Copyright© 2013 RadioShack Corporation
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, see <http://www.gnu.org/licenses/>
//
/*****************************************************************************/

#include <avr/pgmspace.h>

// ******** DEBUG ==== should auto config to adapt different mother board *********
//#define DATA_1 (PORTF |=  0X01)    // DATA 1    // for ATMEGA
//#define DATA_0 (PORTF &=  0XFE)    // DATA 0    // for ATMEGA
//#define STRIP_PINOUT DDRF=0xFF  // for ATMEGA
#define DATA_1 (PORTC |=  0X01)    // DATA 1    // for UNO
#define DATA_0 (PORTC &=  0XFE)    // DATA 0    // for UNO
#define STRIP_PINOUT (DDRC=0xFF)    // for UNO

PROGMEM const unsigned long rainbow_full[5][10]={
  {0xff0000,0x00ff00,0x0000ff,0xffff00,0xff00ff,0xffffff,0xff6622,0xff0000,0xff0000,0xff0000},

};
PROGMEM const unsigned long off[1][10] = {
   {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red1[1][10] = {
   {0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red2[1][10] = {
   {0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red3[1][10] = {
   {0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red4[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red5[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red6[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red7[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000},
};
PROGMEM const unsigned long red8[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000},
};
PROGMEM const unsigned long red9[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000},
};
PROGMEM const unsigned long redfull[1][10] = {
   {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000},
};

/*PROGMEM const unsigned long pattern_test_blue[10][10]={
  {0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00},
};

PROGMEM const unsigned long pattern_test_green[10][10]={
  {0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff},
};

PROGMEM const unsigned long pattern_test_white[10][10]={
  {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff},
};

PROGMEM const unsigned long pattern_test_comet1[][10]={
  {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
  {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff},
};

PROGMEM const unsigned long pattern_test_comet2[][10]={
  {0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
  {0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
  {0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
  {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff},
  {0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
  {0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
  {0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
  {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff},
};

PROGMEM const unsigned long pattern_test_comet3[][10]={
  {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff},
  {0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x444444},
  {0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0xffffff,0x444444,0x111111},
  {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0xffffff,0x444444,0x111111,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0xffffff,0x444444,0x111111,0x000000,0x000000},
  {0x000000,0x000000,0x111111,0x444444,0xffffff,0xffffff,0x444444,0x111111,0x000000,0x000000},
  {0x000000,0x000000,0x000000,0xffffff,0x444444,0x444444,0xffffff,0x000000,0x000000,0x000000},
  {0x000000,0x000000,0xffffff,0x444444,0x111111,0x111111,0x444444,0xffffff,0x000000,0x000000},
  {0x000000,0xffffff,0x444444,0x111111,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
  {0xffffff,0x444444,0x111111,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff},
};

PROGMEM const unsigned long pattern_test_rainbow[10][10]={
  {0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000},
  {0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000},
  {0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000},
  {0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff},
  {0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff},
  {0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff},
  {0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00},
  {0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00},
  {0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00},
  {0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000},
};

*/

// ***********************************************************************************************************
// *
// *                            Power Up Init.
// *
// *
// ***********************************************************************************************************

int sensorvalue = 0;
int outputvalue = 0;
void setup() {

  STRIP_PINOUT;        // set output pin - DEBUG: should auto detect which mother board for use

  reset_strip();
  Serial.begin(9600);
  //noInterrupts();

}

// ***********************************************************************************************************
// *
// *                            Main Loop
// *
// *
// ***********************************************************************************************************
void loop()
{

    sensorvalue = analogRead(A5);
    outputvalue = map(sensorvalue, 0, 174, 0, 18);
    if(outputvalue == 0){
      send_1M_pattern(off, 1, 20);
    }

    else if(outputvalue > 0 && outputvalue <= 3){
      send_1M_pattern(red1, 1, 20);
    }
    else if(outputvalue > 3 && outputvalue <= 5){
      send_1M_pattern(red2, 1, 20);
    }
    else if(outputvalue > 5 && outputvalue <= 7){
      send_1M_pattern(red3, 1, 20);
    }
    else if(outputvalue > 7 && outputvalue <= 9){
      send_1M_pattern(red4, 1, 20);
    }

    else if(outputvalue > 9 && outputvalue <= 11){
      send_1M_pattern(red5, 1, 20);
    }

    else if(outputvalue > 11 && outputvalue <= 13){
      send_1M_pattern(red6, 1, 20);
    }

    else if(outputvalue > 13 && outputvalue <= 16){
      send_1M_pattern(red9, 1, 20);
    }

    else if(outputvalue > 16){
      send_1M_pattern(rainbow_full, 1, 20);
    }
    Serial.print("sensor = " );
    Serial.print(sensorvalue);
    Serial.print("\t output = ");
    Serial.println(outputvalue);

    delay(2);

  /*
    frame++;
    if(frame<=10) LEDSTRIP_PATTERN_0();
    if(10<frame<=20) LEDSTRIP_PATTERN_0();
    if(20<frame<=30) LEDSTRIP_PATTERN_0();
    if(frame>30) frame=1;
   */
  //delay(1);
}

/*******************************************************************************
 * Function Name  : send_1M_pattern
 * Description    : Transmit pattern to whole 1 meter strip
 *
 * Input          : pointer to ROM pattern; pattern length; frame rate
 *
 * Output         : None
 * Return         : None
 *******************************************************************************/
void send_1M_pattern(const unsigned long data[][10], int pattern_no, int frame_rate)
{
  int i=0;
  int j=0;
  uint32_t temp_data;

  for (i=0;i<pattern_no;i++)
  {
    noInterrupts();
    for (j=0;j<10;j++)
    {
      temp_data=pgm_read_dword_near(&data[i][j]);
      send_strip(temp_data);
    }
    interrupts();

    delay(frame_rate);

  }

}

/*******************************************************************************
 * Function Name  : send_strip
 * Description    : Transmit 24 pulse to LED strip
 *
 * Input          : 24-bit data for the strip
 *
 * Output         : None
 * Return         : None
 *******************************************************************************/
void send_strip(uint32_t data)
{
  int i;
  unsigned long j=0x800000;

  for (i=0;i<24;i++)
  {
    if (data & j)
    {
      DATA_1;
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");

/*----------------------------*/
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
/*----------------------------*/
      DATA_0;
    }
    else
    {
      DATA_1;
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
      DATA_0;
/*----------------------------*/
       __asm__("nop\n\t");
      __asm__("nop\n\t");
      __asm__("nop\n\t");
/*----------------------------*/
    }

    j>>=1;
  }

}

/*******************************************************************************
 * Function Name  : reset_strip
 * Description    : Send reset pulse to reset all color of the strip
 *
 * Input          : None
 *
 * Output         : None
 * Return         : None
 *******************************************************************************/
void    reset_strip()
{
  DATA_0;
  delayMicroseconds(20);
}

```

# Answer
A5 is PC5. Your code sets it as an output. Since you only need A0 (PC0) to be an output:

```
#define STRIP_PINOUT (DDRC = _BV(PC0))

```

Uno pin mappings
> 2 votes

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


title: Arduino Yun Webpage Server Issues

text:
# Question
Title: Arduino Yun Webpage Server Issues
So, I've made a sketch on my Yun, which I would like to be able to take information from a webpage (like a button) and have the Arduino Microcontroller perform functions based on what button is being pressed. I have an html file with the webpage of buttons. I also have a sketch that responds to those button presses. When I upload the project via WiFi, everything copies over properly. The html file gets copied to the SD card, the sketch gets loaded onto the Arduino Microntroller, and I can browse to the webpage with my browser. However, whenever I click on the button within the webpage, nothing gets sent back to the Arduino Microcontroller. If actually program the webpage into the actual sketch, everything works fine, but not if the webpage is being loaded onto the SD card. After that, no data gets passed between the Linio and the Atmel Microcontroller.

I would like to be able to have the webpage be hosted by the Linio processor, but pass information about button presses to the actual Atmel Microcontroller.

Does anybody know how to do this properly? I would like to stay away from JScript and AJAX as much as possible. However, I guess I'll use them only if it's absolutely necessary.

Here is my arduino sketch:

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

YunServer server;
boolean receiving = false;

void setup() {
  Bridge.begin();
  Console.begin();
  server.listenOnLocalhost();
  server.begin();
  Console.println("Ready");
}

void loop() {
  YunClient client = server.accept();

  if (client) {
    Console.println("Client Connected");
    String request = client.readString();
    Console.println(request);

    boolean currentLineIsBlank = true;
    boolean sentHeader = false;

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

       if (receiving && c == ' ') receiving = false;

       if (c == '?') receiving = true;

       if (receiving) {
          if (c == 'A') {
            Console.println("Three Beeps");
            threeBeeps();
            break;
          }
          else if (c == 'B') {
            Console.println("Fast Beeps");
            fastBeeps();
            break;
          }
          else if (c == 'C') {
            Console.println("Fast Scale");
            fastScale();
            break;
          }
          else if (c == 'D') {
            Console.println("Alarm");
            playAlarm();
            break;
          }
          else if (c == 'E') {
            Console.println("Evil Alarm");
            evilChord();
            break;
          }
        }
        if (!sentHeader) {

  /*** I COMMENTED THIS PART OUT WHEN TESTING THE ACTUAL HTML FILE ***/
  /************************* ON THE SD CARD **************************/

           //client.println("HTTP/1.1 200 OK");
           //client.println("Content-Type: text/html\n");
           //
           //client.println("<form action='' method='get'>");
           //client.println("<input type='hidden' name='A' value='1' />");
           //client.println("<input type='submit' value='Three Beeps' />");
           //client.println("</form>");
           //
           //client.println("<form action='' method='get'>");
           //client.println("<input type='hidden' name='B' value='2' />");
           //client.println("<input type='submit' value='Fast Beeps' />");
           //client.println("</form>");
           //
           //client.println("<form action='' method='get'>");
           //client.println("<input type='hidden' name='C' value='3' />");
           //client.println("<input type='submit' value='Fast Scale' />");
           //client.println("</form>");
           //
           //client.println("<form action='' method='get'>");
           //client.println("<input type='hidden' name='D' value='4' />");
           //client.println("<input type='submit' value='Alarm' />");
           //client.println("</form>");
           //
           //client.println("<form action='' method='get'>");
           //client.println("<input type='hidden' name='E' value='5' />");
           //client.println("<input type='submit' value='Evil Siren' />");
           //client.println("</form>");

             sentHeader = true;
        }
        if (c == '\n' && currentLineIsBlank) break;

        if (c == '\n') {
           currentLineIsBlank = true;
        }
        else if(c != '\r') {
          currentLineIsBlank = false;
        }
      }
    }
    delay(5);
    client.stop();
  }
}

void threeBeeps() {
  for (int i = 0; i < 3; i++) {
    tone(11,2200);
    delay(100);
    noTone(11);
    delay(100);
  }
  noTone(11);
}

void fastScale() {
  for (int i = 0; i < 1000; i++) {
    tone(11,(i * 2));
    delay(1);
  }
  for (int i = 1000; i > 0; i--) {
    tone(11,(i * 2));
    delay(1);
  }
  noTone(11);
}

void playAlarm() {
  for (int i = 0; i < 5; i++) {
    for (int j = 1000; j < 4000; j++) {
      tone(11,j);
    }
    for (int j = 4000; j > 1000; j--) {
      tone(11,j);
    }
  }
  noTone(11);
}

void fastBeeps() {
  for (int i = 0; i < 6; i++) {
    tone(11,2000);
    delay(50);
    noTone(11);
    delay(50);
  }
  noTone(11);
}

void evilChord() {
  for (int i = 0; i < 5; i++) {
    tone(11,1110);
    delay(500);
    tone(11,785);
    delay(500);
  }
  noTone(11);
}

```

Here's the code in my index.html file:

```
<!DOCTYPE html>
<head>
</head>
<body>
    <form action='' method='get'>
    <input type='hidden' name='A' value='1'>
    <input type='submit' value='Three Beeps' />
    </form>

    <form action='' method='get'>
    <input type='hidden' name='B' value='2'>
    <input type='submit' value='Fast Beeps' />
    </form>

    <form action='' method='get'>
    <input type='hidden' name='C' value='3'>
    <input type='submit' value='Fast Scale' />
    </form>

    <form action='' method='get'>
    <input type='hidden' name='D' value='4'>
    <input type='submit' value='Alarm' />
    </form>

    <form action='' method='get'>
    <input type='hidden' name='E' value='5'>
    <input type='submit' value='Evil Siren' />
    </form>
</body>

```

As you can probably tell, the 5 buttons the webpage generates tells the Arduino to play a sound corresponding to the pressed button.

Like I said, I can program the webpage into the actual sketch (all commented out for the time being), and everything works just dandy. However, if I load the webpage onto the SD card in the Yun, I can still browse to it by browsing to `"Arduino.local/sd/<project name>"`, but the buttons no longer function since the webpage was sent to the client from the Linio and not the Arduino. The reason I am wanting to let the Linio handle the webpage is because it can handle much larger webpages much more quickly without taking up precious sketch room on the Arduino. Also, I CAN read an SD card with the Arduino and send the webpage to the clients that way, but it's way too slow compared to using the Linio. So, does anybody know how to take the button presses from the Linio and send them back to the Arduino?

Any help would be greatly appreciated!

# Answer
> 1 votes
Your form actions are empty: when you'll press the buttons, they will send data to the current URL (something like `/sd/project_name/index.html`) instead of the `/arduino` url, which sends data to YunClient.

Reading your sketch, I think they are something like `/arduino/?A=1`, right?

A couple of advices:

1. start from the sketch and make sure you can control it from the browser. Manually type the expected URLs and verify the played sound.
2. Make the URLs easy to read, like `/arduino/sound/A`
3. Use the approach of Bridge example: code something like

`String command = client.readStringUntil('/');
if (command == "sound") {
 char soundType = client.read()
 if (soundType == 'A') {
 ...`

# Answer
> 0 votes
I fixed my problem by changing my sketch to this:

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

YunServer server;
boolean receiving = false;

void setup() {
  Bridge.begin();
  Console.begin();
  server.listenOnLocalhost();
  server.begin();
  Console.println("Ready");
}

void loop() {
  YunClient client = server.accept();

  if (client) {
    String command = client.readString();
    command.trim();

    if (command == "threeBeeps") {
      Console.println("Three Beeps");
      threeBeeps();
    }
    if (command == "fastBeeps") {
      Console.println("Fast Beeps");
      fastBeeps();
    }
    if (command == "fastScale") {
      Console.println("Fast Scale");
      fastScale();
    }
    if (command == "siren") {
      Console.println("Siren");
      playSiren();
    }
    if (command == "evilAlarm") {
      Console.println("Evil Alarm");
      evilChord();
    }
    client.stop();
  }
  delay(50);
}

void threeBeeps() {
  for (int i = 0; i < 3; i++) {
    tone(11,2200);
    delay(100);
    noTone(11);
    delay(100);
  }
  noTone(11);
}

void fastScale() {
  for (int i = 0; i < 1000; i++) {
    tone(11,(i * 2));
    delay(1);
  }
  for (int i = 1000; i > 0; i--) {
    tone(11,(i * 2));
    delay(1);
  }
  noTone(11);
}

void playSiren() {
  for (int i = 0; i < 5; i++) {
    for (int j = 1000; j < 4000; j++) {
      tone(11,j);
    }
    for (int j = 4000; j > 1000; j--) {
      tone(11,j);
    }
  }
  noTone(11);
}

void fastBeeps() {
  for (int i = 0; i < 6; i++) {
    tone(11,2000);
    delay(50);
    noTone(11);
    delay(50);
  }
  noTone(11);
}

void evilChord() {
  for (int i = 0; i < 5; i++) {
    tone(11,1110);
    delay(500);
    tone(11,785);
    delay(500);
  }
  noTone(11);
}

```

And also by changing my webpage to this:

```
<!DOCTYPE html>
<html>
    <head>
    <script type="text/javascript" src="zepto.min.js"></script>
    <script type="text/javascript">
function threeBeeps() {
$('#content').load('/arduino/threeBeeps');
}
function fastBeeps() {
$('#content').load('/arduino/fastBeeps');
}
function fastScale() {
$('#content').load('/arduino/fastScale');
}
function siren() {
$('#content').load('/arduino/siren');
}
function evilAlarm() {
$('#content').load('/arduino/evilAlarm');
}
</script>

</head>

<body onload="setInterval(refresh, 2000);">
<span id="content"></span>

<button onclick="threeBeeps()">Three Beeps</button>
<button onclick="fastBeeps()">Fast Beeps</button>
<button onclick="fastScale()">Fast Scale</button>
<button onclick="siren()">Siren</button>
<button onclick="evilAlarm()">Evil Alarm</button>

</body>
</html>

```

I also include the `zepto.min.js` Javascript file.

---
Tags: arduino-yun, web-server, web-service
---


title: Two devices on one SDA input

text:
# Question
Title: Two devices on one SDA input
I have two devices. Sensor for temperature and humidity and lcd screen. Both require SDA pin, and I have only one on my arduino.

I want my display to show current temperature but I don't know how to connect two things on one pin.

Can I somehow read from other pins maybe?

Also, what can I do if I have only 1 5V source and I have two devices that require 5V?

My arduino model is Arduino Mega 2560 R3

I have this aosong sensor (AM2301), and I have YwRobots 2 row LCD screen which I want to connect to my board along with sensor.

**So... I'm not sure how to connect those two if both require SDA and I have only one.**

# Answer
You can have multiple I2C devices on the same bus (sharing both SDA and SCL), as long as they have different addresses. The library used to access them should know (or be told, if required) what the address for the device is.

If they are not I2C devices then they cannot both use SDA.

The Aosong device is *not* an I2C device, but there is no need to connect its "SDA" pin to the Arduino's "SDA" pin; any unused digital pin should work, as long as the library is told which pin to find it on and as long as the electrical requirements of the connection are met.
> 3 votes

---
Tags: sensors, pins
---


title: Arduino Shield Pin Conflict

text:
# Question
Title: Arduino Shield Pin Conflict
I have a Freetronics Etherten and am trying to use the NFC Shield \- both the board and shield are trying to use Pins D10,D11,D12,D13

So my question - Is there an elegant way to have these two work together. This really applies to any combination of shield with conflicting pins. I'm thinking maybe use some in between headers or M/F jumper wires?

Is there a neat way to do it?

# Answer
> 2 votes
You need this: https://www.sparkfun.com/products/11002
"The Go-Between Shield “goes between” two shields that aren’t compatible and effectively reassigns the pins. This trickery is achieved by isolating the top and bottom sides of the shield with surface mount headers and breaking them out into tables of jumpers that can be bridged to divert signals to and from different pins."

---
Tags: pins
---


# Question
Title: May arduino hang when current is changing over time?
As in title. I've got quadrocopter where Li-Po is parallely connected to motors as well as to arduino. May current driftage cause arduino hangs ?

# Answer
> 4 votes
There really isn't any such thing as "Current driftage". If you draw too much current from your battery it will cause the voltage to drop, and if it drops too much, the Arduino will stop working.

If you have high current devices like motors being switched on the same power supply as your Arduino you should add a reservoir capacitor as close to the input of your Arduino as possible. That will even out short term drops and spikes in supply voltage as your motors switch.

If you draw too much current continuously then your supply voltage will drop and stay dropped, and a reservoir capacitor won't help. In that case you need a higher current battery (or separate power supplies for your Arduino and motors.)

Edit: From your question it's pretty clear that you don't understand voltage and current and how they relate. I suggest you read up on the subject.

In short, the amount of current that flows through a component is determined by the voltage divided by the resistance: i = v/r. (Where i = current in amps, v = voltage, and r = resistance in ohms.)

The current that will flow will be limited by the max current that the power supply can provide.

For a non-regulated supply like a battery, the voltage from the supply will drop as you draw more and more current.

For a regulated supply, the supply keeps the voltage constant up to it's maximum current limit.

# Answer
> 1 votes
May i ask why you don't have a separate battery for the arduino? If it is because of weight, an arduino can run of CR2032 batteries, gives it its own power supply, this should solve the problem.

If you want a battery with more longevity Google "6v 2/3 battery" (2/3 the size of an AA battery), small with loads of voltage for the arduino and with some skilled programming it should last for a flight or two, and the +side, you can get it rechargable.

---
Tags: current
---


title: Arduino UNO USB not recognized

text:
# Question
Title: Arduino UNO USB not recognized
I've just received my Uno today and already I think I may have broken it :(

I was able to connect to usb and upload a sketch (the blink). However, I then tried to connect a circuit to do the Hello World LCD example. After trying this a few times, I noticed the LCD chip get very hot...and I had mis-wired it. In any case, after a few more tries, the USB connection to my Arduino UNO stopped working.

I tried swapping the cable, connecting it to another mac and to a windows with no luck. I'm worried I may have shorted the USB bus chip when trying Hello World.

I also tried connecting a 12V DC power supply.

I still get the green power light and the amber L light... Did I break my Uno? How do I troubleshoot this one? thanks

# Answer
> 2 votes
When the LCD pulled enough current to overheat, the Arduino's power supply (which I gather was the Uno's USB interface, at the time) was probably stressed to the point of failure. One fortunate result is that the Arduino took the hit instead of the computer's USB port that was supplying it. It's not clear which part was involved but here's a discussion on another forum concerning a similar failure and replacing the ATMegaxU2 which does USB-interface duty on the Uno (x = 8, if it's a rev 2 Uno, x = 16, if rev 3). It may be possible to replace the failed chip - regulator or USB interface (though with LEDs working, it's probably not the regulator). Otherwise, you can probably still program it with an ISP (In System Programmer). But the easiest way to do that is probably involves another Uno.

# Answer
> 2 votes
You can try and buy the Arduino serial board, and connect it directly to the pins on the Arduino , see if this works, basicly override the Arduino's own interface, or if you have another Arduino you can try and "serial" connect them using the first Arduino as ISP.

Else it is like JRobert says, you could move the chip from another arduino burn it on that one and then put it back, using the second Arduino as a run only.

Last but not least, you may find a cheap broken Arduino board on some online auction site, where the chip is broken, then move the defect chip to your defect board, and the working chip to the working board, and throw the defect Arduino in the electronics recycling.

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


# Question
Title: Code does not pass `gsmAccess.begin(PINNUMBER)==GSM_READY)`
I am not able to get my code to pass

> if(gsmAccess.begin(PINNUMBER)==GSM\_READY) {

I have modified the PIN number on my sim card to be `0000`, and yet its stuck on `begin`.

How do I prepare the SIM CARD to pass the begin

# Answer
> 1 votes
Try putting the SIM card into a mobile phone in case it hasn't been initialised by your provider. Set up the PIN for the card using the settings on the phone, see the manual for instructions on how to do this.

Now you can use the PIN you entered on the phone to unlock the SIM in your code.

---
Tags: gsm
---


# Question
Title: how to use strstr() in serial communication?
I have a SIM900 module and Arduino, both are working fine. In my previous programs I have use strstr() command to find specific word from a string but they were constants and pre defined in the program but now I want to read serial communication from SIM900 and detect a specific word from it. But it is showing me

> invalid conversion from 'char' to 'const char'

This is my program:

```
int x;
char sms;
char response;
char disp;
void setup()
{
  Serial.begin(2400);
}

void loop() {
  while(Serial.available() == 0);

  if(Serial.available() > 0)
  {
    sms = Serial.read();

    disp = sms;
    if (strstr(disp,"track")) //Comparing word entered with word stored in program
    {
      Serial.println("Found the  word!");
    }
  }
}

```

# Answer
> 1 votes
There are two problems.

1) you are trying to have the Arduino's single UART talk to both the SIM900 and the PC.

2) disp needs to be an array of char's, as to compare for words phrases.

Try the following. It implements a 2nd Soft serial port to which you can connect the SIM900. Along with building an array char at a time.

```
#include <SoftwareSerial.h>

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

char buffer[16];
#define buffer_size sizeof(buffer)/sizeof(buffer[0])
int8_t buffer_pos = 0;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Serial to mySerial demo started");

  buffer_pos = 0;
}

void loop() {
  char inByte;
  while (mySerial.available()) {
    inByte = mySerial.read();
    while (buffer_pos >= buffer_size) {
      for (int8_t i = 0; i < buffer_size - 1; i++) { // if shift buff left if at end of buff
        buffer[i] = buffer[i + 1];
      }
      buffer_pos--;
    }
    buffer[buffer_pos++] = inByte;
    if (strcasestr(buffer, "track")) {
      buffer_pos = 0;
      Serial.println("TRACK FOUND!");
    } else {
      Serial.write(inByte);
    }
  }
}

```

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


title: Mega2560 R3 pin functions

text:
# Question
Title: Mega2560 R3 pin functions
When I read about mega2560 I saw it has 54 digital that can be used as input or output.
later on I saw the some of them are used for things like communication.

So I would like to know if the communication pin can still be used as output ? (to power leds)

# Answer
Yes. ***Any* pin can be used as a digital input/output.** However, you cannot use certain communications when using those pins.

*The types of communication and their effects on the pins:*

* **SPI:** This protocol is used for certain communications with certain breakout boards and shields. For example, the ethernet shield uses SPI to connect. On the Mega(2560), it is pins 50-53.
* **I2C:** This protocol is also for connecting to external items. It is much slower than SPI, but uses only two pins. On the Mega, it uses pins 20/21.
* **UART/Serial:** UART is a communication method that uses two wires and transmits bytes of data. It is often used to connect to things that don't need *extreme* amounts of data passed, but need a stable two way connection.
    + On all standard boards, the main UART is on pins 0 and 1. This is usually connected to a UART to USB chip which is sent to the computer. Note: you should still be able to upload sketches if they act as an *output* and random on/off won't hurt the device.
    + The Mega(2560) also has UART on pins 14/15, 16/17, and 18/19.
> 2 votes

# Answer
Yes, you can.

You are referring to SPI, I2C, and the 4 serial interfaces. If you want to use those you have to use the predefined pins for that. If you are not using those you can use them as normal GPIO.

If you want Serial communication for debugging, you shouldn't use digital pins 0 and 1.

If you need even more pins, you can even use the analog pins and digital input/output pins.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Scroll String Only On Second Line Using 2x16 LCD
I'm trying to scroll a string in the second row of the LCD while letting the string on the first row stay intact. I use Serial to run that part of the code as you can see. It work at first but when I try to make it run again it doesn't display anything on the second row.

I borrowed the code from :

http://code.nishantarora.in/arduino-lcd-projects/src/3f10686e7464665c5c59d7be772c00af7a4a93e8/scrollOneLine/scrollOneLine.ino?at=master

And made some changes:

```
// include the library
#include <LiquidCrystal.h>

// init the lcd display according to the circuit
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

// it's a 16x2 LCD so...
int screenWidth = 16;
int screenHeight = 2;

String line1;
String line2;

int stringStart, stringStop = 0;
int scrollCursor = screenWidth;

String CompleteString;
String stringArray[] = {"s=Plane", "i=Car", "h=Boat", "u=Rocket", "d=Jet",  "p=Submarine", "l=Truck", "b=Bicycle", "m=Skate", "enter=Train"};

String string1 = "String";

int countMovement=0;
int arraylimit = 9;

void setup() {

   lcd.begin(screenWidth,screenHeight);
   Serial.begin(9600);

}

void loop(){

   char ser = Serial.read();

   if ( ser == 'c' ) {
     CompleteString="";

     for (int i = 0 ; i <= arraylimit; i++) {
        CompleteString += stringArray[i] + " "; // Convert String Array To Single String
     }

     roop(string1,CompleteString);
  }

}

void roop(String line1, String line2) {

  countMovement = 0;

  while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

     lcd.setCursor(scrollCursor, 1);
     lcd.print(line2.substring(stringStart,stringStop));
     lcd.setCursor(4, 0); // 1 = word eat array of words very cool
     lcd.print(line1);
     delay(300);
     lcd.clear();

     if(stringStart == 0 && scrollCursor > 0){
        // Serial.println(scrollCursor);
        scrollCursor--;
        stringStop++;
     } else if (stringStart == stringStop){
        stringStart = stringStop = 0;
        scrollCursor = screenWidth;
     } else if (stringStop == line1.length() && scrollCursor == 0) {
        stringStart++;
     } else {
       stringStart++;
       stringStop++;
     }

     countMovement++;

  }

  lcd.setCursor(4, 0);
  lcd.print(line1);

}

```

From what I can see using Serial as debugging is that the problem resides in the function "roop" and in specific the line:

```
 if(stringStart == 0 && scrollCursor > 0){

```

It seems that the statement is being pass on and so it doesn't move the string as it's suppose to. I could be wrong but placing a Serial call in there yields no result the second time the function is called but the first time it did.

Any help would be much appreciated! And I know the community will be grateful too since it's difficult from what I can see in post to achieve this and make it autonomous so that no big modifications needs to be done.

# Answer
> 1 votes
You need to reset the `stringStart`, `stringStop` and `scrollCursor` at the beginning of the roop function.

```
void roop(String line1, String line2) {

  countMovement = 0;
  stringStart = 0;
  stringStop = 0;
  scrollCursor = screenWidth;

  ...

```

I think you also need to move the `lcd.clear` up. Or else the screen will be blanked when the roop function is done scrolling.

```
...

  while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

     lcd.clear();
     lcd.setCursor(scrollCursor, 1);
     lcd.print(line2.substring(stringStart,stringStop));
     lcd.setCursor(4, 0); // 1 = word eat array of words very cool
     lcd.print(line1);
     delay(300);

...

```

# Answer
> 0 votes
The answer from the user Gerben worked perfect. So I'll be posting another solution I came upon and the one from my original question for feature reference.

Original Code:

```
// include the library
#include <LiquidCrystal.h>

// init the lcd display according to the circuit
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

// it's a 16x2 LCD so...
int screenWidth = 16;
int screenHeight = 2;

String line1;
String line2;

int stringStart, stringStop = 0;
int scrollCursor = screenWidth;

String CompleteString;
String stringArray[] = {"s=Plane", "i=Car", "h=Boat", "u=Rocket", "d=Jet", "p=Submarine", "l=Truck", "b=Bicycle", "m=Skate", "enter=Train"};
String string1 = "String";
boolean ArrayRead = true;
int countMovement=0;
int arraylimit = 9;

// most of the part is pretty basic
void setup() {

   lcd.begin(screenWidth,screenHeight);
   Serial.begin(9600);

}

void loop(){

   char ser = Serial.read();

   if ( ser == 'c' ) {
      CompleteString="";

      for (int i = 0 ; i <= arraylimit; i++) {
         CompleteString += stringArray[i] + " "; // Convert String Array To Single String
      }

      roop(string1,CompleteString);
   }

}

void roop(String line1, String line2) {

   countMovement = 0;
   stringStart = 0;
   stringStop = 0;
   scrollCursor = screenWidth;

   while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

      lcd.clear();
      lcd.setCursor(scrollCursor, 1);
      lcd.print(line2.substring(stringStart,stringStop));
      lcd.setCursor(5, 0); // 1 = word eat array of words very cool
      lcd.print(line1);
      delay(300);
      lcd.clear();
      if(stringStart == 0 && scrollCursor > 0){
         scrollCursor--;
         stringStop++;
      } else if (stringStart == stringStop){
         stringStart = stringStop = 0;
         scrollCursor = screenWidth;
      } else if (stringStop == line1.length() && scrollCursor == 0) {
         stringStart++;
      } else {
         stringStart++;
         stringStop++;
      }

      countMovement++;

   }

   lcd.setCursor(4, 0);
   lcd.print(line1);

}

```

The other code provided by the user "HazardsMind" for I2C LCD Module: The changes made are Serial communication and adapted for the 6 pin LCD Module.

```
// include the library
#include <LiquidCrystal.h>

// init the lcd display according to the circuit
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

//char * SerialComm[70];
//{"s = Plane i=Car h=Boat u=Rocket d=Jet p=Submarine l=Truck b=Bicycle m=Skate enter=Train"};

#define N_CHARS  ((sizeof(MessageOut)/sizeof(MessageOut[0]))-1)
#define N_CHARS2  ((sizeof(MessageOut2)/sizeof(MessageOut2[0]))-1)

//int len = strlen(SerialComm);

char MessageOut[30];
char MessageOut2[30];

int index = 19, index2 = 0;
unsigned long oldTime = 0, oldTime2 = 0;

byte indexer = 0; // Index into array; where to store the character
char inData[58]; // Allocate some space for the string
char inChar; // Where to store the character read

void setup()
{
   Serial.begin(9600);
   lcd.begin(16, 2);                      // initialize the lcd
}

void loop()

  while(Serial.available() > 0) // Don't read unless
                                              // there you know there is data
  {
      if(indexer < 57) // One less than the size of the array
      {
         inChar = Serial.read(); // Read a character
         inData[indexer] = inChar; // Store it
         indexer++; // Increment where to write next
         inData[indexer] = '\0'; // Null terminate the string
      }
  }
  // Now do something with the string (but not using ==)

  // Serial.print(inData);
  setHeadingRight("Royal", 0, 500);
  setHeadingLeft(inData, 1, 500);

  //setHeadingRight("Hello Welcome", 0, 1000); // message, row, duration
  // setHeadingLeft("Welcome", 1, 500);
}

void setHeadingRight(char * msg, byte row, unsigned long duration)
{
   strncpy(MessageOut, msg, sizeof(MessageOut));
   if(millis() - oldTime > duration) // check the difference of the current time "millis()" to the previous time "oldTime" against the duration you want.
   {
      oldTime = millis(); // update oldTime with the current time
      if(index >= 0) // make sure the index does not go under 0
      {
        index--; // decrecment index by 1
        for (int i = 0; i < N_CHARS; i++) // this part here displays the message on the display
        {
           lcd.setCursor(i,row); // set the column to show the element in the array
           if(index == N_CHARS) index = 0; // set index back to 0 if the index has reached the arrays max size.

              if(MessageOut[index++] != NULL) // if the element @ index is anything but NULL, show it.
                  lcd.print(MessageOut[index-1]);
              else
                  lcd.print(' '); // if the element @ index is NULL, display a space.
        }
      }
   else index = 19; // if index is less than 0, then set it back to 19
 }
}

void setHeadingLeft(char * msg, byte row, unsigned long duration2)
{
  strncpy(MessageOut2, msg, sizeof(MessageOut2));
  if(millis() - oldTime2 > duration2)
  {
     oldTime2 = millis();
     if(index2 < 20) // check to see if index2 is under the array max size
     {
        index2++; // increment index
        for (int i = 0; i < N_CHARS2; i++) // same as above
        {
           lcd.setCursor(i,row);
           if(index2 == N_CHARS2) index2 = 0;

              if(MessageOut2[index2++] != NULL)
                 lcd.print(MessageOut2[index2-1]);
              else
                 lcd.print(' ');
              }
           }
           else index2 = 0; // otherwise set it back to 0
     }
}

```

---
Tags: programming, lcd
---


title: Slice string at “:”

text:
# Question
Title: Slice string at “:”
I need to slice a string (eg- 4:288:18464:288:4) at ":" into an array({4, 288, 18464, 288, 4}) I used the following code, but its giving only '4' in the serial monitor when "4:288:18464:288:4," is given to arduino.

```
void displayString(char* s)
{
  char* text = strtok(s,":");

  while(text != NULL){
  text = strtok(NULL,":");}
}

void loop()
{
  if(Serial.available() > 0)
    {
        str = Serial.readStringUntil(',');
        str.toCharArray(text,99);
    }
  displayString(text);
Serial.println(text);
}

```

# Answer
> 1 votes
You don't use `strtok` the way it should:

```
char* text = strtok(s,":");
while(text != NULL){
    text = strtok(NULL,":");
}

```

Your code just replaces, in `s`, all occurrences of `:` with `0` (i.e. a byte of value 0, not the ASCII value of `'0'`), thus terminating each substring.

At the end of `displayString(text)` call from `loop()`, `text` still points to the 1st character of the original string (in your post `4:288:18464:288:4`), but that string now terminates at the position of the first `:`, which explains why `Serial.println(text)` prints just `4`.

Now if you want to split the original string into an array of substrings, as asked in your question, you need to modify `displayString` this way:

```
// Maximum number of substrings expected
const int MAX_SUBSTRINGS = 5;
// Array of pointers to each substring after displayString() has been called
static char* substrings[MAX_SUBSTRINGS];

void displayString(char* s) {
    // First clear the array of substrings
    for (int i = 0; i < MAX_SUBSTRINGS; i++)
        substrings[i] = 0;
    // Now split the input string
    char* text = strtok(s,":");
    int i = 0;
    while (text != 0 && i < MAX_SUBSTRINGS) {
        // A toekn was found: append it to the array of substrings
        substrings[i++] = text;
        text = strtok(0,":");
    }
}

```

After calling `displayString(text)`, you can use its result in `loop()` as follows:

```
void loop()
{
    if (Serial.available() > 0)
    {
        str = Serial.readStringUntil(',');
        str.toCharArray(text,99);
    }
    displayString(text);
    for (int i = 0; i < MAX_SUBSTRINGS; i++) {
        if (substrings[i] != 0)
            Serial.println(substrings[i]);
    }
}

```

Note that this will work **ONLY** if the original string contains no more than 5 substrings delimited by `:`. If the max number of substrings cannot be known at compile time, then you'll have to use dynamic allocation, which is generally not a very good idea on embedded platforms.

---
Tags: serial, string
---


# Question
Title: Why does an Arduino UNO need two GND ports?
I have really bad eyesight, so whenever I plug in the power wire and the GND wire I always double check if I'm actually plugging in to the power port not one of the two GND ports.

Why does an Arduino UNO have two GND ports, and for what application would one use both of them?

# Answer
> 12 votes
In electronics circuits, a major point in connecting two circuits and make them "talk" together is to ensure, at the minimum, that they have a common reference of voltage (typically called `GND` and defined as `0V` voltage).

On Arduino, GND pins can be used in 2 situations:

1. to directly power the Arduino with an external supply which cannot be plugged to USB or power jack. In this case, the positive voltage of that external power source shall also be supplied to **Vin** pin.
2. to connect Arduino GND to your circuits.

Having 2 distinct GND pins is, I think, just a matter of convenience when you want to build prototypes but don't necessarily have a breadboard (if you use a breadboard, you will just need to connect its power rail to Arduino GND pin and use this power rail directly).

# Answer
> 2 votes
If you are not using a shield and are directly adding components to the arduino it is nice to have 2 ground so you can attach several components without having to add a bread board.

To be precise, you have 3 ground, since the third is sitting on the left hand side of the board (looking in to the USB port)

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


# Question
Title: Controlling flexinol with an arduino board?
I am looking to wire up 16 pieces of flexinol (http://www.musclewires.com/MWFlexinol.php) using an arduino board. Ideally I would like to be able to activate them independently, meaning that they could all be on, off or in any combination in between. My understanding that they would need to draw more current than the board could handle so some type of shield would be necessary?

Any suggestions would be greatly appreciated.

# Answer
First thing's first, this just seems to be a wire that has special characteristics. If so, we just need to find out the resistance and use **Ohm's law**.

From the product page, I found this image:

>

I can tell from that that it has a resistance of 20 ohms and a recommended current of 1 amp. First, let's see how much current it would draw with a 5V supply. I prefer using a Ohm's law triangle, just because I'm a very visual person. So with this math:

> 5 / 20 = 0.25

That's 250 mA, but an Arduino can only provide 40 mA! Furthermore, it is only 1/4 of the recommended current that the manufacturer specifies.

To get the full current the OEM specifies you'll need a 20 V power supply capable of at least 1A. Even then, you might want to put in a *power resistor* to limit the current.

**Driving this with Arduino:** So, we have a few problems here:

* It is 20W, which is quite a bit in the Arduino world
* We need to control the current/voltage dynamically
* You need 16 of them, so we don't want something too costly
* You probably can't find something to fit your needs that is *one* shield.

What comes to mind is a transistor. I'm not skilled with picking them out, but there are a lot of guides online. You'd then want to add a capacitor and a resistor to make some sort of filter and connect it to a PWM pin to send a varied voltage to the transistor, which will vary the amount of power going through it.

Alternatively, you could use a *relay*. However, that only does ON or OFF. A *solid state relay (SSR)* would allow you to use PWM on the relay and then you could add a capacitor/resistor combo on the other end of it, but you'd need a pretty large capacitor or a pretty large frequency for the PWM (which you can modify).
> 1 votes

---
Tags: power, shields
---


# Question
Title: How to detect if running Arduino or bare Atmega328p?
I'm building something that will mostly run on bare ATmega328p at 8 MHz (as described eg. **here**), but sometimes I need to run the same code on an Arduino.

I need to **initialize the DHT library** depending on the clock frequency. For simplicity, I'd rather detect the running environment runtime, in the program itself.

So, is there a straightforward way to detect the clock speed (from fuses?) or some other difference between a stock UNO board and a bare ATmega328p using the internal 8 MHz clock?

# Answer
> 3 votes
Bare vs Stock is nearly impossible to detect at compile time. Where it depends on what you think you are trying to determine versus detect.

The best I can think of is creating a different Board definition; one for your bare and the other being the stock (i.g. UNO). Where now in IDE 1.5 see github.com/arduino/Arduino/wiki/… the parameter uno.build.board=AVR\_UNO, which provides is used to set a compile-time variable ARDUINO\_{build.board} to allow use of conditional code between #ifdefs. So you can create bare board definition with e.g. bare.build.board=MY\_BARE and then have some #ifdef's for ARDUINO\_MY\_BARE

Otherwise wrap some #ifdef's around F\_CPU as @sechleen points out. This is viable and done often in the core libraries.

# Answer
> 1 votes
The easiest way to distinguish your bare AVR from the arduino board at run time is to build the bare AVR board with a distinguishing feature - such as a known voltage on one of the D/A ports - that won't be present on your Arduino.

---
Tags: frequency
---


title: Arduino Serial Communication

text:
# Question
Title: Arduino Serial Communication
I'm trying to communicate with the Arduino through the serial port to fade the LED. There's the code running on my Arduino:

```
#include <aJSON.h>
aJsonStream serial_stream(&Serial);

const int localID = 1;
int intensity = 100;        // fadeTo value(0% - 100%)
int currentIntensity = 0;   // how bright the LED actually is (0-100%)
int time = 0;               // milliseconds
int color[] = {0, 255, 0};

int pinRed = 11;
int pinGreen = 10;
int pinBlue = 9;
int pinPower = 8;

void fadeTo() {
  if(intensity != currentIntensity) {
    if(intensity > currentIntensity)
      currentIntensity+=1;
    else
      currentIntensity-=1;

    analogWrite(pinRed,255-currentIntensity);
    analogWrite(pinGreen,255-currentIntensity);
    analogWrite(pinBlue,255-currentIntensity);
  }
}

aJsonObject *createMsg()
{
    aJsonObject *orbData, *colorData;

    orbData = aJson.createObject();
    aJson.addNumberToObject(orbData, "id", (int)localID);

    aJson.addNumberToObject(orbData, "currentIntensity", (int)currentIntensity);

    //aJson.addNumberToObject(orbData, "time", (int)time);

    colorData = aJson.createIntArray(color, 3);
    aJson.addItemToObject(orbData, "color", colorData);

    return orbData;
}

// echo {\"id\":1, \"intensity\":150, \"time\":10} >> /dev/ttyACM0 in terminal
// {"id":1, "intensity":150, "time":10} in Serial Monitor
void processMsg(aJsonObject *msg)
{
    //Serial.println("Data succefully received.");
    Serial.println("received message: ");
    aJson.print(msg, &serial_stream);

    aJsonObject *idData = aJson.getObjectItem(msg, "id");
    if(idData != NULL)
    {
        Serial.println("ID data succefully received.");
        if(localID == (idData->valueint)) {

            aJsonObject *intensityData = aJson.getObjectItem(msg, "intensity");
            if(intensityData != NULL) {
                if(intensityData->type != aJson_Int) {
                    Serial.println("Invalid data type for Intensity");
                    return;
                }

                if(intensityData->valueint == currentIntensity) {
                    Serial.println("The received intensity value is already the current LED intensity");
                    return;
                }

                else {
                    Serial.println("Intensity data succefully received");
                    intensity = intensityData->valueint;
                }
            }
            else {
                Serial.println("No intensity value received.");
                return;
            }

            aJsonObject *timeData = aJson.getObjectItem(msg, "time");
            if(timeData != NULL) {
                if(timeData->type != aJson_Int) {
                    Serial.println("Invalid data type for time");
                    return;
                }
                else {
                    Serial.println("Time data succefully received");
                    time = (timeData->valueint);
                }
            }
        }

        else {
          Serial.println("The received ID is not mine.");
          return;
        }
    }

    else {
      Serial.println("No ID data received.");
      return;
    }

    Serial.println("received message: ");
    aJson.print(msg, &serial_stream);
}

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

    pinMode(pinRed,OUTPUT);
    pinMode(pinGreen,OUTPUT);
    pinMode(pinBlue,OUTPUT);
    pinMode(pinPower,OUTPUT);

    digitalWrite(pinPower,HIGH);
    digitalWrite(pinRed,HIGH);
    digitalWrite(pinGreen,HIGH);
    digitalWrite(pinBlue,HIGH);
}

void loop()
{
    aJsonObject *orbData = createMsg();

    Serial.println("current status: ");
    aJson.print(orbData, &serial_stream);

    Serial.println();

    aJson.deleteItem(orbData);
    delay(100);

    fadeTo();

}

void serialEvent()
{
    if(serial_stream.available())
    {
        // first, skip any accidental whitespace like newlines
        serial_stream.skip();
    }

    if(serial_stream.available())
    {
        aJsonObject *msg = aJson.parse(&serial_stream);

        processMsg(msg);

        aJson.deleteItem(msg);
    }
}

```

The problem is, I can open my Serial Monitor in the Arduino IDE and send json data to the Arduino and I see live the changes through the output and the LED on the board. I can also send data through terminal to /dev/ttyACM0 while running Serial Monitor in the IDE and it works fine too. But as soon as I close the Serial Monitor and send data to the device through terminal, it breaks down. I can then open Serial Monitor and every time I get the ERROR from json parser --\> ("No ID data received.").

Has anyone any idea why this is happening?

# Answer
I had a similar problem trying to use the commands such as :

> echo 1 \> /dev/ttyACM0

and found that I needed privileges to perform serial communication in this way like:

> sudo echo 1 \> /dev/ttyACM0

You could also try setting the baud rate you are communicating at :

> sudo echo 1 \> /dev/ttyACM0 9600

GOOD LUCK!
> 1 votes

---
Tags: linux
---


# Question
Title: Can I specify that analog pins be used for digital output?
http://arduino.cc/en/Reference/pinMode notes that

> The analog input pins can be used as digital pins, referred to as A0, A1, etc.

Is it possible to configure these pins as digital output pins as well?

# Answer
Yes.

http://arduino.cc/en/Tutorial/AnalogInputPins states

> The analog pins can be used identically to the digital pins, using the aliases A0 (for analog input 0), A1, etc. For example, the code would look like this to set analog pin 0 to an output, and to set it HIGH:

```
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH)

```

There are several caveats on that page regarding this.
> 2 votes

---
Tags: digital
---


# Question
Title: Can the nRF24L01+ CE and CSN pins be attached to Arduino pins A0 and A1?
This documentation states that the CE and CSN pins can be specified. Can I specify A0 and A1 as these pins?

# Answer
> 2 votes
Yes, you can. The mirf library is using the regular arduino functions `pinMode` and `digitalWrite` to manipulate the pins. So A0 and A1 should work as expected.

Please note that when you use SPI (which the NRF does), you have to use pin 10 (SS) as an OUTPUT (as to not put the AVR into SPI slave mode).

---
Tags: nrf24l01+
---


title: Using a 16 bit ADC chip with arduino

text:
# Question
Title: Using a 16 bit ADC chip with arduino
I need to measure voltage between 0-10 volts using my Arduino Due. I have an ADS7805p chip, which I believe will work, but am not sure how to wire it on my breadboard. I'm used to just using the chip on the arduino, but that only goes 0-5 volts and I can't loose the resolution by converting. Can someone, please, point me to or instruct me on how to wire something like this to my arduino?

# Answer
> 1 votes
The ADS7805 is old but still a pretty good ADC. I could imagine that you just have a few lying around that you want to use. I would simply wire it to two parallel in / serial out chips like the 74HC589 or CD4021 as used in this example:
http://www.arduino.cc/en/Tutorial/ShiftIn

Start the conversion as described in Duncan C's answer and then simply clock in all 16 bits. I think you could then probably get away with 4 or 5 control lines.

# Answer
> 0 votes
If you really need 16 bits of resolution then you could use that chip, but it's going to be a lot of work. Also beware that according to Mouser's website, it is not recommended for new applications. It sounds like it's being phased out/replaced.

Take a look at the data sheet linked from Mouser's website: ADS7805p datasheet

It has 16 bits of parallel data output, plus what sounds like 2 control lines, CS and R/(not)C (Don't know how to make the proper symbol.)

It sounds like you pull CS and R/C low to trigger a conversion, then wait for not busy to go low, switch R/C to high, then read the 16 bits of data.

To use this chip you're going to need 18 or 19 pins from your Arduino. You might want to consider a chip with a serial interface instead.

---
Tags: arduino-due
---


# Question
Title: Difference between PWM and regular output port for servos?
I have been controlling my servomotors for a while now only using pin 0. After some research, it has became apparent to me that the ports with `~` are the PWM pins.

I thought that all pins sent out PWM signals, therefore the motor was able to move back and forth. Now I'm really confused as to how the motor was able to turn without using a `~` pin like pin 5.

Can someone explain why I should or should not use PWM signal when controlling a motor?

# Answer
> 3 votes
Servos does not use PWM, it uses PPM:

* PWM = Pulse width modulation, The pulse start at 0ms, and is high for the percentage of the time compared to the percentage of the voltage you want, 5v signal, if you want 1v, the pulse is 20ms High and 80ms Low.
* PPM = Pulse position modulation, The pulse length is always 5ms High and 95ms low, but the interesting part is if high starts after 5ms or 50ms (or any other).

So PWM is to lower voltage, PPM is a signal pulse.

This means that no matter what port you are using on the arduino you are able to control a servo since you only need High or Low, and not a lower voltage.

What you need to be aware of in this case is on the arduino is a PPM signal is using up a timer. The arduino has 3 timers where of 2 is available, one is used internally. Though there is code where you can attach up to 3 servos on the same internal timer.

---
Tags: pins, pwm, servo
---


# Question
Title: Internal volts in arduino for percent battery
I'm working on a small project that is creating me a headache. I know arduimo (ATmega 328P .... etc. ..) has an internal voltage source code millivolts, but I would like to know how the full source code become percentage where 3 volts = 0% and 4.2 volts = % 100% ??? . I appreciate the help because in codes is not my forte. I leave the code so Help me complete. Thank you.

```
long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

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

void loop() {
  Serial.println( readVcc(), DEC );
  delay(1000);
}

```

# Answer
`map()`

```
unsigned char level = map(readVcc(), 3000, 4200, 0, 100);

```
> 2 votes

---
Tags: voltage-level, battery
---


title: Break statement terminating loop()

text:
# Question
Title: Break statement terminating loop()
I am experiencing some very strange behavior with my arduino. I have a switch-case statement in the loop() method, and the break methods are not only breaking out of the case block, but also out of the loop() statement. Is this normal, and if so, how can I edit the structure so it doesn't do that? My code structure looks like this:

```
void loop(){
  switch(int i){
    case 1:{
      //do something
      break;// this also breaks out of the loop() method.
    }
  }
}

```

# Answer
I just realized it wasn't the sketch, but a faulty SD card reader on my computer corrupted my SD card. BIG TIME.
> 1 votes

# Answer
Your sample is too simple to test your hypothesis (which is wrong, by the way.)

Set up serial output so you can test:

```
void loop()
{
  Serial.println("Before switch statement");
  int i = 1;
  switch (i)
  {
    case 1:
      Serial.println("In case 1");
      break;
    default:
      Serial.println("In default case");
  }
  Serial.println("After switch statement.");
}

```

You can even add an outer for loop to make things a little more complicated:

```
void loop()
{
  Serial.println("Before for loop statement");
  for (int i = 1; i< 10; i++)
  {
    Serial.print("In for loop before switch, i = ");
    Serial.println(i);
    switch (i)
    {
      case 1:
        Serial.println("In case 1");
        break;
      default:
        Serial.println("In default case");
    }
    Serial.println("After switch statement.");
  }
}

```

Examine the output on the serial monitor of your computer. You should find that the "After switch statement" line always appears after the "before switch..." line in both versions of the code.

Break breaks from the innermost scope. If you have nested levels of scope, like a function and then a switch statement inside the function, the break statement breaks out of that inner level. In the second example, the break broke out of the switch but the for loop kept running.

This is very basic C programming and not specific to Arduino.
> 1 votes

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


title: Arduino + simple DC motors? (4WD kit)

text:
# Question
Title: Arduino + simple DC motors? (4WD kit)
I am trying to connect 4 small DC motors to Arduino, like those in the following image:

The specification for each of them is:

> Suggested Voltage: 3V DC;
> No Load Speed: 65 ± 10rpm;
> No Load Current: 125mA (170mA MAX).

But I have no useful knowledge in electronics to do so...

I would be really thankful if anyone could explain me why it is so difficult to connect DC motors to Arduino (I've heard about problems with the magnetic field, but I don't really understand why); and possible point me to an easy (and cheap) solution. I am, of course, willing to study (not expecting a complete solution).

I'm aware there are some shields for doing this kind of connection, but they are really expensive, and I've seen some people using only transistors or components like SN754410.

Thank you in advance! :-)

# Answer
First you make 4 parallel H-Bridges, http://en.wikipedia.org/wiki/H\_bridge then you attach it to an external powersource ( or attach directly to the battery to prevent burning your arduino )

Attach every up to a pin, making it high makes the motor running, you need 8 pins for this, eg pin 1 makes motor 1 go forward, pin 2 makes motor 1 go back and so.

This is by far the most practical solution, but it is the easiest, and can be done with 8 PNP and 8 NPN transistors.

If you don't know how transistors work i suggest https://www.youtube.com/watch?v=-td7YT-Pums collins lab, it is both educational and entertaining.
> 0 votes

---
Tags: arduino-uno, motor, robotics, arduino-motor-shield
---


title: Arduino not responding

text:
# Question
Title: Arduino not responding
I have been using my arduino uno for many months and it worked very well even till today morning but an hour ago I tried to upload a sketch and arduino IDE showed my this "**avrdude: stk500\_getsysc(): not in sync: resp =0x00**" , at first I thought maybe I burned my atmega32 chip but I bypassed reset and gnd with a jumper wire and opened serial monitor and my atmega32 still printing serial data,so problem must be something else,and also my led13 isn't blinking.Is it problem with bootloader?if so how can I reload bootloader in my board without using another arduino?

# Answer
I'm personally not really in to this RTFM kind of answer, but in this case it really do answer most of your questions about the bootloader part: http://arduino.cc/en/Hacking/Bootloader

About the error, a quick search on SO gives you this: https://stackoverflow.com/questions/24240285/arduino-nano-3-avrdude-stk500-getsync-not-in-sync-resp-0x00
> 2 votes

---
Tags: arduino-uno, bootloader, avrdude
---