# Question
Title: 2 Arduino Unos Connected with 1-Wire and Receiver Pin getting Stuck High
I am trying to accomplish 1-wire communication between 2 Arduinos and so I wanted to start off by having 1 Arduino toggle a digital output pin and have the other read the state of that pin. To accomplish this, I have 2 computers with Arduino IDE installed and each one is connected to one Arduino Uno. Both Arduino Uno's are connected with a single male-male jumper cable on Pin 13 of the header. I am watching the state of the pin by looking at the prints in the Serial Console on both computers.

Here is a diagram of my setup:

```
Computer1 ---> Arduino1[Sender] --------> Arduino2[Receiver] -----> Computer2

```

The problem I have is that I am seeing when I first start both Arduinos - the sender is definitely toggling the output pin high-\>low-\>high forever - but the receiver Arduino only shows its input pin as toggling for a few seconds and then it gets stuck high. Sometime later, it may go low for 1 iteration, but then sticks at high again. What is going on? I would expect to see the sender and receiver show high-\>low-\>high forever. The code seems simple but I must be doing something wrong - thanks for your help.

Sender Code:

```
int led = 13; // Comm Pin

// Setup pins
void setup() {

  // put your setup code here, to run once:
  Serial.begin(9600);

  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);

}

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.println("high");
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  Serial.println("low");
  delay(1000);               // wait for a second
}

```

Receiver Code:

```
int led = 13; // Comm Pin

// Setup pins
void setup() {

  // put your setup code here, to run once:
  Serial.begin(9600);

  // Pin is an input - normal state high
  pinMode(led, INPUT);

}
void loop() {

  // Put your main code here, to run repeatedly:
  Serial.println(digitalRead(led));
  delay(1000);

}

```

# Answer
> -1 votes
You should add a random delay in setup of receiver and reduce the sampling time of the receiver to 200ms.

That said, digital communication is an INSANELY EXTREMELY complex process, especially on the physical layer. This is not the correct way for two arduinos to digitally communicate.

Unless you are a teacher and are trying to demonstrate why this would fail, (not criticising), you mustn't use it.

You should use the Arduino wire library to establish communication instead. You can send whole integers, and it's totally reliable (it uses hash checks, guaranteeing correct communication even at 1152000 baud). As a comparison, you're at 1 baud.

You can get a tutorial here: http://www.instructables.com/id/I2C-between-Arduinos/.

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


# Question
Title: Same Arduino Sketch when uploaded from a Linux machine does not work
I am trying out some code using the Arduino IDE. The code basically tries to connect to a server and push some data to it.

When I upload the sketch to the Arduino from Mac (Apple PC running on Mac OS) the code works as expected without an error.

However, when I upload the same code/sketch from a Linux machine on Ubuntu, the arduino does not operate as expected.

I tried taking a diff comparison of the HEX files created in both machines to check whether there are any differences (expecting very few). But found that there a lot of differences.

What am I missing? Why isn't my code working when uploaded via the Linux PC!!!!!

# Answer
> 1 votes
Got this sorted.

The issue was that different versions of the library was being used in both the PCs. One we made sure that the Linux PC used the same as the MAC one it all worked fine!!!

Thanks Guys

---
Tags: arduino-uno, linux, mac-os
---


title: 16u2 programming

text:
# Question
Title: 16u2 programming
How does one go about programming the 16u2 on an Uno? **I have the isp header (for the 16u2) hooked up to another Uno programmed as ArduinoISP** I'm not talking about DFU or USB-\>UART, I'm talking about using it like a standalone chip (Like, say, a Leonardo or Yun \[the 32u4, not the Linux, obviously\])

# Answer
First you need to write a program for it. There is no Arduino core for the 'XU2, so you will need to write it out longhand. Then you compile it. Then you upload it using ISP. Then you run it. Note that the only pins you have access to on the board are the UART pins, the two on the LEDs, and the 3 on the ISP header.
> 1 votes

---
Tags: isp
---


# Question
Title: What is Reverse Current through an Arduino?
Can someone explain (in a non-wiki technical way) what reverse current is through an Arduino ? Cheers y'all

# Answer
> 1 votes
It's current flowing "the wrong way".

The electronics inside the main chip are designed such that the + side (Vcc) must be at a significantly higher voltage than the - side (GND). By significantly I mean 2.1-5.5V higher.

Because of that it is expected that the current will flow through the components in one direction (or in a couple of pre-determined directions depending on settings). Any situation which causes a reversal of that current through the internals is bad, and as called "reverse current".

It could be caused by something as simple as connecting a power supply backwards, or more technical things like the "Back EMF" from an inductive load (motor, relay, etc) entering a pin that is an output and flowing backwards up to Vcc, or "Back Powering" where the chip is not powered but some external device connected to it is powered, and it "leeches" power backwards through IO pins to power the chip.

All of those situations are bad and should be avoided.

---
Tags: sketch, current, electronics
---


title: Custom Arduino library problem

text:
# Question
Title: Custom Arduino library problem
I have made my custom serial(UART) library. So I made uart.h and uart.cpp files as following.

> uart.h

```
#ifndef UART_H
#define UART_H

#include <avr/io.h>
#include <stdlib.h>

//creating class named uart
class uart{

  public:

    // creating constructor
    uart(void);

    //function to start uart at given baudrate
    void start(int baudrate);

    // function to read uart input
    unsigned char read();

    // function to print data on serial monitor
    void print(unsigned char data);

    // function to print string on serial monitor
    void print(char *string);

    // function to print data with given base
    void print(unsigned char data,unsigned int base);

    //function to print data like printf
    void print(char* str,unsigned char data);

    // function to read data by printing string
    unsigned char read(char* string);

};

#endif

```

> uart.cpp

```
#include "uart.h"

uart::uart(void);

void uart::start(int baudrate){

    long BAUDRATE = ((F_CPU)/(baudrate*16UL)-1);

    UBRR0H = (BAUDRATE >> 8);

    UBRR0L = BAUDRATE;

    // enable recieve and transmit
    UCSR0B |= 1 << RXEN0 | 1 << TXEN0;

    // data size is equal to 8 bits
    UCSR0C |= 1 << UCSZ00 | 1 << UCSZ01;
}

unsigned char uart::read(){

    //wait until receive complete.
    while(!(UCSR0A & (1 << RXC0)));

    // return received byte
    return UDR0;
}

void uart::print(unsigned char data){

    // wait until UDR is empty
    while(!(UCSR0A & (1 << UDRE0)));

    //place data into UDR
    UDR0 = data;
}

void uart::print(unsigned char* string){

    int index = 0;

    // print string character by character
    while(string[index] != '\0'){

        print(string[index]);

        index++;
    }
}

void uart::print(unsigned char data,unsigned int base){

    //buffer to store converted data
    char buffer[10];

    //convert data to ascii
    itoa(data,buffer,base);

    //print converted data
    print(buffer);
}

// function to print data like printf(%d,data);
void uart::print(char* str,unsigned char data){

    int index = 0;

    // print string character by character
    while(str[index] != '\0'){

        if(str[index] == '%'){

            index++;

            if(str[index]=='d') print(data,10);

            else if(str[index] == 'b') print(data,2);

            else if(str[index] == 'x') print(data,16);

            index++;
        }
        print(str[index]);

        index++;
    }
}

unsigned char uart::read(unsigned char* string){
    // print given string
    print(string);
    // return read char
    return(read());
}

```

> test.cpp

```
#include "uart.h"
int main(){
    uart.start(9600);
    uart.print("Hello world\n");
}

```

Now all of above function works if i write all function and declations in single **.h** file and don't divide my header file in **.h** and **.cpp** file. if i compile this given program i get following error.

> Error

```
src/uart.cpp
src/uart.cpp:3:16: error: declaration of 'uart::uart()' outside of class is not definition [-fpermissive]
 uart::uart(void);
                ^
src/uart.cpp:39:6: error: prototype for 'void uart::print(unsigned char*)' does not match any in class 'uart'
 void uart::print(unsigned char* string){
      ^
In file included from src/uart.cpp:1:0:
src/uart.h:31:7: error: candidates are: void uart::print(char*, unsigned char)
  void print(char* str,unsigned char data);
       ^
src/uart.h:28:7: error:                 void uart::print(unsigned char, unsigned int)
  void print(unsigned char data,unsigned int base);
       ^
src/uart.h:25:7: error:                 void uart::print(char*)
  void print(char *string);
       ^
src/uart.cpp:30:6: error:                 void uart::print(unsigned char)
 void uart::print(unsigned char data){
      ^
src/uart.cpp:91:15: error: prototype for 'unsigned char uart::read(unsigned char*)' does not match any in class 'uart'
 unsigned char uart::read(unsigned char* string){
               ^
In file included from src/uart.cpp:1:0:
src/uart.h:34:16: error: candidates are: unsigned char uart::read(char*)
  unsigned char read(char* string);
                ^
src/uart.cpp:20:15: error:                 unsigned char uart::read()
 unsigned char uart::read(){
               ^
.build/uno/Makefile:166: recipe for target '.build/uno/src/uart.o' failed
make: *** [.build/uno/src/uart.o] Error 1
Make failed with code 2

```

> **PS:** I use `inotool` to compile and upload my programs to arduino and it works great. So you will find `src/` in error.

Please help me. I'm stuck here.

# Answer
> 3 votes
```
uart::uart(void);

```

That's a prototype, not a function. It needs a body. Also, using "void" to say "no parameters" is really confusing. Better to leave it out all together.

```
uart::uart() {
}

```

---

```
uart.start(9600);
uart.print("Hello world\n");

```

`uart` is a class, not an instance. You should be using `uart::start(9600)` if you first set your functions to be `static`, or create an instance from the `uart` class:

```
uart myUart;

int main() {
    myUart.begin(9600);
    myUart.print("Hello world\n");
}

```

---

Watch your random `unsigned` entries...

```
uart.h:
unsigned char read(char* string);

uart.c:
unsigned char uart::read(unsigned char* string){

```

... There may be others too.

---
Tags: serial, library, avr, uart, class
---


title: New Language - Interfacing with AVR

text:
# Question
Title: New Language - Interfacing with AVR
So I'm taking a class where the project is to create a new embedded language. We are using OCaml for the compiler, so I was looking for a way to interface with AVR or its C library in such a way as I can write programs in my language, then compile and somehow get it on the arduino I have. I was curious if there's a library for OCaml or some sort of white paper for interfacing with the board at a high level or even at a low level where I can get this to work.

# Answer
> 1 votes
The OCAML compiler can emit C code and the Arduino IDE takes C code, so in theory it is possible.

You would need to get the OCAML runtime code ported over to the Arduino IDE. At very least, I think this would be a lot of work. At worst, the Arduino might not have enough memory to support it.

# Answer
> 1 votes
I have no experience with OCaml or with writing compilers, but I would suggest that you first *learn* how to program the Arduino, then *teach* your compiler to do so.

You may start by using the Arduino IDE and a couple basic tutorials. There is an option in the IDE for displaying all the commands it runs to get your program compiled and linked. Take note of these commands, then throw the IDE away. Alternatively, you can download one of the few Arduino Makefiles that float around the Web.

You will see that the basic toolset you need is the following:

* The AVR flavor of GNU GCC and the binutils. This allows you to program the AVR in assembly, C and C++. Calling these tools from your own compiler should be as easy as calling them from the command-line.
* The avr-libc, which is a port of the libc for the AVR, together with some AVR-specific stuff, and the C runtime. It does *not* provide a hardware abstraction layer.
* The Arduino core library, a beginner-oriented C++ library built on top of avr-libc. It does provide a hardware abstraction layer and is source-level compatible with non-AVR based Arduinos.

In terms of language and API, your main choices are: AVR assembly, C + avr-libc, C++ + avr-libc, C++ + Arduino core + avr-libc. There are others, of course, these are just the better known. Pick your favorite, learn how to use it, then teach your compiler.

---
Tags: arduino-uno, programming, avr-gcc
---


# Question
Title: Can a connection of HC-05 and Arduino Nano receive audio and display waveform on computer?
Working to receive Music for Bluetooth Speaker via HC-05

# Answer
> 2 votes
No, it can't. The HC-05 is a Bluetooth Serial device, Bluetooth speakers are Bluetooth Audio Sink devices.

It's like asking "Can my bicycle fly?"

I think you'll agree the answer is "NO".

The only possible way of doing it using the HC-05 is to receive the audio using your computer then pre-process it and send the important information to the Arduino through the HC-05, so the Arduino can then send it back to the computer for displaying. But then, what *really* is the point of the Arduino...?!

---
Tags: arduino-uno, bluetooth
---


# Question
Title: How to control a large number of devices with an Arduino
I'm doing some initial research on a project I have in mind. I am super new to all this Arduino stuff so taking it slow and gathering lots of info.

I want to control around 1000 small linear actuators to push/pull a very small load. The purpose of this question is specifically how to manage that many devices. The devices won't ever need to start their own transmissions so the Arduino can get everything done by polling them ...I hope ...and I don't think it would be a lot of data to each device but I imagine overall it may be. I want to control each device at the "same" time, all with the same cabling distance (around 2m). From what I can tell, a **CANbus** is exactly what I need, where I can assign a unique ID to each device (node) and then write some code to control the network array.

In summary, is a CANbus the ideal bit of hardware here to work with an Arduino to control in real time such a high number of devices?

Thanks, Nick.

Edit: Sorry for the vagueness, I'm very new to all this so really just looking for keywords to help scope my project out before asking more complex specific questions. It's difficult to formulate what's in my head to experienced people without sounding like a goose. I'm experienced on the software side, but the hardware i/o is all brand new.

Ultimately, I am wanting to sample a grey scale image/sequence of images and depending on the value sampled in a 0-255 range which is mapped to the extension capabilities of each actuator to extend/contract in that pixel.

Hope that is more helpful. Thanks.

# Answer
> 2 votes
This is just a suggestion, certainly not the only possible approach.

**Step 1**: Get a handful of small linear actuators *with a builtin controller*. Some actuators have no controller, and will require one H-bridge and one analog input each. You do not want these. I have seen some actuators with built-in controllers that can be driven just like servos, I would suggest you get some of those. At this point you should carefully look at costs when choosing the actuators.

**Step 2**: Learn how to drive those actuators from an AVR-based Arduino, like an Arduino Uno, using the Servo library. I believe you can drive up to 12 actuators with a single Arduino.

**Step 3**: Drive them using *two* Arduinos in a master-slave configuration. The master would be a beefy Arduino, like a Mega or a Due. It would send commands to the slave using, say, an I2C bus. After sending the set points for the actuators, it would send a "go" order to the I2C broadcast address. The slave would be the Uno. It would interpret the commands and actually drive the actuators.

**Step 3b**: Change the master's program to *pretend* it is controlling many slaves, and a total of 1000 actuators. In reality, all the slaves would have the same I2C address: that of the unique slave actually available. This will tell you whether your master is powerful enough for the job, and you will see how the performance scales.

**Step 3c**: Optimize the slave's code. Try to have it work with an 8 MHz clock, and use as little flash and RAM as possible.

**Step 4**: Replace the slave Arduino with a bare AVR chip. You will have to learn how to program it via ISP, but the information is widely available. An Uno is an ATmega328P at heart, but depending on the program size, you may get away with an ATmega48A, which is the same thing only with less memory, and dirty cheap. Or even with a still cheaper ATtiny. If you can make your program work with an 8 MHz clock, then use the internal oscillator, which will save you having to buy an external resonator. All this is to keep the costs reasonable.

**Step 4b**: Test, test, test. Last chance to change your mind before committing big bucks.

**Step 5**: If everything works at this stage, it's time to scale up. The same master Arduino, and one bare AVR for each dozen actuators, each with it's own I2C address.

---
Tags: arduino-uno
---


title: Intializing Serial crashes UNO

text:
# Question
Title: Intializing Serial crashes UNO
I have a somewhat large sketch that uses the `Adafruit_ssd1306`(I2C) library for a 128X64 LCD. The sketch is a designed to be an alarm clock. When I upload the sketch with out initializing serial, it works as designed. However if I do intialize serial:

```
Serial.begin(9600);

```

the program fails to run on my UNO. After many hours of troubleshooting I noticed I have several large char arrays that may be the culprit.

```
const char *menusDisplay[] = {"1. Alarm-is Off", "2. Month", "3. Hour", "4. Minute", "5. Exit", "6. Alarm Set", NULL};
const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec", NULL};
const int days[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

```

The months array as 12 elements. If I shorted it down to 2 elements and upload the programs with serial initialized, the program runs. At first I thought is was a memory leak in perhaps the `Adafruit_ssd1306`. But I also have another LCD library `Adafruit_ssd1306syp` that the issue occurred too. So that ruled out those libraries.

When I compile the sketch without Serial:

```
Sketch uses 16,846 bytes (52%) of program storage space. Maximum is 32,256 bytes.
Global variables use 737 bytes (35%) of dynamic memory, leaving 1,311 bytes for local variables. Maximum is 2,048 bytes.

```

With Serial:

```
Sketch uses 17,862 bytes (55%) of program storage space. Maximum is 32,256 bytes.
Global variables use 910 bytes (44%) of dynamic memory, leaving 1,138 bytes for local variables. Maximum is 2,048 bytes.

```

Any ideas of what may be going on? I would load the sketch but its very large. If needed, I can try to cut it down and reproduce the issue.

# Answer
@EdgarBonet pointed out in a comment, I need to check my dynamic ram, which could be used by the Heap and Stack. The class can be found here to measure ram usage. Since links can die, here is the code:

Here is the header:

```
/* MemoryFree.h */

// MemoryFree library based on code posted here:
// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1213583720/15
// Extended by Matthew Murdoch to include walking of the free list.

#ifndef MEMORY_FREE_H
#define MEMORY_FREE_H

#ifdef __cplusplus
extern "C" {
#endif

int freeMemory();

#ifdef  __cplusplus
}
#endif

#endif

```

Here is the .cpp

```
/* MemoryFree.cpp */

#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif

extern unsigned int __heap_start;
extern void *__brkval;

/*
 * The free list structure as maintained by the
 * avr-libc memory allocation routines.
 */
struct __freelist {
  size_t sz;
  struct __freelist *nx;
};

/* The head of the free list structure */
extern struct __freelist *__flp;

#include "MemoryFree.h"

/* Calculates the size of the free list */
int freeListSize() {
  struct __freelist* current;
  int total = 0;
  for (current = __flp; current; current = current->nx) {
    total += 2; /* Add two bytes for the memory block's header  */
    total += (int) current->sz;
  }
  return total;
}

int freeMemory() {
  int free_memory;
  if ((int)__brkval == 0) {
    free_memory = ((int)&free_memory) - ((int)&__heap_start);
  } else {
    free_memory = ((int)&free_memory) - ((int)__brkval);
    free_memory += freeListSize();
  }
  return free_memory;
}

```

From this I was able to see how much ram was used. Of the avialable 2k, I had only 100k left. So now I know why my program is crashing, I need a solution. The solution was to store the static content in program memory (PROGMEM):

```
const char* const months[] PROGMEM =
    {
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };

const uint8_t days_of_month[] PROGMEM =
    {
        31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    };

```
> 0 votes

# Answer
Since no other code is posted, I am going to guess that you're performing a loop on months\[\], which has 13 elements (last one is NULL).

You are likely also trying to walk the days\[\] array (or some other array), which only has 12 elements.

Since days\[\] or the other (not pasted) array doesn't have 13 elements, you're probably overriding a critical bootloader memory which causes a crash.
> 0 votes

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


title: Multiple LEDs & HC-SR04

text:
# Question
Title: Multiple LEDs & HC-SR04
I want to use a distance sensor like the HC-SR04 to power a stop light like parking sensor for my garage. I have seen a lot of tutorials on how to use the HC-SR04 to power a single LED and found the schematic below on how to control up to 14 LEDs by hooking them onto the 5v and using a transistor. I have added a box where I would hook the sensor in. My question is, would it work if I had the sensor hooked into the 5v as well. The plan is to have 3 sets of 14 LEDs and have one set on at any given time. I plan on using an Arduino Uno.

# Answer
If I am understanding correctly, you have 3 LEDs ... call them A, B and C (the fact that they are a group of 14 LEDs is a red herring). As a function of the distance measured, you want ONE of LED A, B or C lit.

Since you are using an Arduino, you have GPIO pins. Connect a different GPIO to each of A, B and C. You can then write an application that senses the distance (as measured by the HC-SR04) and depending on the distance returned, have a set of "if" statements which will choose which of the GPIOs to set HIGH and the others LOW. The GPIO set HIGH will switch on the corresponding LED.

In fact, its going to look a lot like this Instructable:

http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/
> 0 votes

---
Tags: sensors
---


# Question
Title: Read signal from USB mouse on an Arduino ?
I've got a project where I'd need to read my mouse's signal. My mouse is a G700S (so USB) and the thing was I don't really know how to do and even if it's feasible. I'm using an Arduino Micro and my initial idea was to get a PS/2 to USB Adapter (I already have one) and then to plug it to something like this wired to my Arduino. So my question basically is "will it work ? and if not, why ?"

The main idea is not to use USB (like an USB Host Shield) because Arduino doesn't have any USB mouse driver.

Thank you in advance

# Answer
This would be possible **only** if the mouse actually supports PS/2. USB to PS/2 adapters are entirely passive, and in order to function it requires that the controller in the mouse is designed to communicate in both protocols. Modern mice, especially wireless ones don't tend to have this capability anymore as PS/2 is all but a dead standard.
> 3 votes

---
Tags: usb, hardware, arduino-micro
---


# Question
Title: Can't use base class and derived class functions
I have made two libraries and one test program.I have made my custom uart library.first i have included all functions for printing in single uart library file.but then i have made print library for printing functions only.my files are listed below.i have not posted my code directly so it can be read separately.

**uart.h**

**uart.cpp**

**print.h**

**print.cpp**

> Test.cpp

```
#include <avr/io.h>
#include "uart.h"

int main(){
    uart.start(9600);
    uart.print("Test");
}

```

and i get this error..

> Error

```
src/print.cpp
src/print.cpp: In member function 'void PrintClass::print(unsigned char)':
src/print.cpp:4:12: error: 'write' was not declared in this scope
write(data);
          ^
src/print.cpp: In member function 'void PrintClass::print(char*)':
src/print.cpp:13:22: error: 'write' was not declared in this scope
write(string[index]);
                   ^
.build/uno/Makefile:47: recipe for target '.build/uno/src/print.o' failed make: *** [.build/uno/src/print.o] Error 1
Make failed with code 2

```

i have referred default arduino libraries like hardwareSerial and LiquidCrystal and i made my library like that but i cant get rid of that. Please Help me.

# Answer
Any functions that the base class needs to call that will be defined in the child class must also be defined in the base class. They should be defined "virtual" so they can be overridden, and can even be "pure virtual" so they *have* to be defined in the child class.

So for any function in the child class that the base class needs to access, add this to the base class's definition (print.h):

```
virtual void write(unsigned char data) = 0;

```

The `= 0` bit defines it as *pure* virtual, and any classes than inherit this class *without* defining their own copy of the `void write(unsigned char)` function will thrown an error.

Instead of *pure* virtual you can provide a *default* function that a child *can* override if they want to, which can be useful if most classes will work the same way (define it in the parent) but some want to do it differently (override it in the child), in which case you treat it like a normal class function but add the `virtual` tag.

The whole topic is called *polymorphism* and is an incredibly powerful system. It's discussed in detail here: http://www.cplusplus.com/doc/tutorial/polymorphism/
> 2 votes

---
Tags: arduino-uno, avr, uart, class
---


# Question
Title: print data after being plugged back into USB
I have an arduino uno powered by a battery on a buggy with a sonar distance sensor. I have a program that calculates the speed it's going, and I want to correlate speed with stopping distance. I can measure the stopping distance manually, but I want the arduino to report to me the speed it was going when the motor was turned off. I don't have an LCD display - I wanted to print the number to the serial monitor, but plugging it back into the USB port resets everything I think, or at least the serial monitor.

Without buying more components, can I get the data (calculated speed) somehow?

# Answer
> 2 votes
You could have it write the final speed to EEPROM after the motor is shut-off, and output this value when the Arduino boots, see: http://www.arduino.cc/en/Reference/EEPROM

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


title: Arduino Servo is behaving strangely

text:
# Question
Title: Arduino Servo is behaving strangely
I am trying to use the Arduino Servo library to drive a simple servo and am having some difficulty getting it to even move.

Here's the setup:

And the schematic that Fritzing generated for me:

And the code:

```
#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;

Servo servo;
int pos = 0;
bool GOING_UP = true;

void setup() {
    // Attach the servo and give it a few seconds to reset to the starting position.
    servo.attach(SERVO_SIGNAL_PIN);
    servo.write(0);
    delay(5000);
}

void loop() {
    if((GOING_UP && pos < 180) || pos == 0) {
        GOING_UP = true;
    } else {
        GOING_UP = false;
    }

    int step = 1;

    if(!GOING_UP) {
        step *= -1;
    }

    pos += step;

    servo.write(pos);
    delay(15);
}

```

When I run this, nothing happens. When I attach a multimeter and set it to the "6V" setting, I have found some strange readings:

* When I connect the red multimeter lead ("red lead") to the 5V line connecting the Arduino to the breadboard, and the black multimeter lead ("black lead") to the black GND line connecting the Arduino to the breadboard, I get readings around 5V; but...
* When I connect the red lead to the red power line going *to* the servo, and the black lead to the black GND line coming back *from* the servo, I get a voltage reading of roughly **-20V**!!!

I'm not sure what this means/implies. Is anything jumping out at anyone? Anything I can troubleshoot here? Thanks in advance!

# Answer
The odd voltages might suggest that the servo isn't actually (fully) connected to the Arduino. As it's a diagram of the breadboard layout, not a photo, I can't say for sure, but on some breadboards the +ve/red and -ve/black rows are sometimes split in the middle. i.e. if you were to connect the Arduino's +5v to one end of the breadboards red row, and the servo to the other end, they might not be joined (same applies for -ve/black). Just a thought; apologises in advance if I’m stating the obvious.
> 1 votes

---
Tags: arduino-due, servo, wires
---


# Question
Title: How to avoid that my arduino clicks eternally?
I have accidentally implemented a program that imitates the click of the mouse.

The problem is that now I can´t delete the program because each time that I connect the USB, the computer starts clicking everything and it is not possible to upload a new program.

Can I solve this problem?

# Answer
> 18 votes
Hold the RESET button as you plug the Arduino in and keep it pressed all the time it's plugged into your computer. Load Blink.ino into the IDE and compile it. Press the UPLOAD button in the IDE and move the mouse to somewhere "safe". Release the RESET button.

Do those last three steps in rapid succession and you should be fine.

---
Tags: button
---


title: SFML Packet and Arduino

text:
# Question
Title: SFML Packet and Arduino
Can the `sf::Packet` class of SFML-network be ported over to arduino for use with the Ethernet library or would it be too big? I'm working on a client-program where an arduino is a server and a regular computer is the client making a request. I'm using the SFML-network library to make networking easier on myself and would prefer to use the built in features of SFML to make networking easier. If it is not feasible would I be better off using fixed width data to communicate with the arduino

# Answer
Without knowing how it all works, my guess is that you would have to port the whole of SFML, which would be **HUGE**. So, "No!" is the answer.

You could, of course, write a library of your own that had an SFML-like interface, but the Arduino networking libraries are already pretty simplistic and easy to use, so what's the point?
> 0 votes

---
Tags: ethernet, networking
---


title: Running multiple tasks at once

text:
# Question
Title: Running multiple tasks at once
For a school project we're working on a wearable device to track people's movement and heart rate. We use an Arduino Pro Mini with a heartbeat sensor and an accelerometer. The wearable device uses Bluetooth to send data, but only once or twice a day to save battery.

The problem we currently face is having the Arduino keep track of the accelerometer data while also reading the heartbeat sensor on a select interval. See the pseudo-code underneath. In what way (preferably without implementing too many libraries) could we merge these two loops so the accelerometer is read non-stop while keeping an interval (of about 30 minutes) between the heart beat readings? Any input would be greatly appreciated and if needed I can provide additional information.

```
void loop() {
// Heartbeat sensor loop
  while (array is not full) {
    delay(30 minutes);
    heartbeatArray[index++] = readHeartbeat();
  }
  sendData_Bluetooth(heartbeatArray);
  emptyArray();
// End of heartbeat sensor loop

// Accelerometer loop
  while (true)
    if (readAccelerometerData > limit)
      sendAlert();
// End of accelerometer loop
}

```

# Answer
What you want to do is rather easy task, you just need to forget about `delay()` function. When writing some more complex programs using it is generally a bad idea, as it blocks code execution, so you won't get any sensor readings, communication, anything. Instead try something like this:

```
unsigned long delay1 = 100;
unsigned long delay2 = 1800000; //30 minutes in miliseconds
unsigned long t1, t2;

void setup() {
  t1 = t2 = millis();
}

void loop() {
  if(millis() - t1 > delay1) { //this will be executed every delay1 ms
    // do one part of code
    t1 = millis();
  }

  if(millis() - t2 > delay2) { //this will be executed every delay2 ms
    // do another part of code
    t2 = millis();
  }

  // here insert the code that should be executed as frequently as possible
  // (every loop passage)
}

```

There is also a nice Arduino library called TaskScheduler, that basically does the same thing: periodically executes different functions with different time intervals.
> 4 votes

# Answer
millis() is your great friend here.

millis() is function that returns the value of a 32 bit counter that is incremented once per millisecond. By adding the current value returned by millis() to a value representing the number of milliseconds that you want to 'delay' for you get a value that can be compared with the ongoing value returned by millis() to see if the time period has elapsed.

You can have as many variables as you wish which hold future timeout values for millis(0 - you perform the related action when millis() returns \>= the saved value and reinitialise the value to some new future time.

Variables used to hold values from millis() **MUST** be type unsigned long.
The millis() timer rolls over every 49.7 days.
( = 2^32/1000 ms/s / 3600 s/hr / 24 h/day)

* If your system may run for longer than that without being reset or powered down then handling millis()'s timer rollover must be known about.

It's MUCH easier than many people realise but best not dealt with here EXCEPT to know that if you add a constant to millis() and the value exceeds 2^32 and is truncated the comparisons with and subtractions wrt millis() still work correctly if the variable is type unsigned long. ("Why" is for elsewhere)

micros() is like unto millis() but returns the time since reset in microseconds. Depending on the processor used micros() may have a granularity of 4 uS rather than one uS. ie it steps by 4 counts every 4 uS rather than 1 count per uS.
micros() rolls over every 1.19 hours
( = 2^32 / 10^6/3600s/h)

---

// **Example - not tested:**

```
unsigned long DoitNow;

void setup(){
  DoitNow = millis() + 1800000; // Add half an hour of milliseconds
 }
void loop(){
   if(millis() > DoitNow)
   { Do heartbeat stuff;
      DoitNow = millis() + 1800000; // Add another half hour of ms
   }
 Do accelerometer stuff;
}

```
> 1 votes

# Answer
To keep the 10Hz accelerometer sample rate consistent, you'll need an 10Hz interrupt routine to do the sampling, and probably queue them somewhere, as they will accumulate while you're off measuring the heart rate.

Your main loop can collect any accelerometer samples out of the queue periodically, and at appropriate intervals, read the heart beat. This organization will keep the accelerometer sample rate stead whether your main loop has anything else to do or not.

Make the queue more than long enough to hold all the samples that could collect during a heartbeat measurement, which you should probably make one at a time, even though you might do it in rapid succession, so the main loop gets to drain the accelerometer queue as often as possible.

Otherwise you'll need a queue as large as (10 Hz * 10 sec * maxPossibleConsecutiveHeartBeatMeasurements * factorOfSafety * sizeof(oneSample) bytes; and you don't have a whole lot of memory to play with in an Atmega 328.

Where will you be storing the measurements between Bluetooth connects? If it's an SD card, you'll need some space for its write-buffer, and the main loop will have to manage the card writing.
> 0 votes

# Answer
See https://electronics.stackexchange.com/a/67091/10371 (Since this is another stack exchange site, I won't copy the info)

The short answer is to use timers that trigger interrupts. Examples are shown in the link.
> 0 votes

---
Tags: sensors, bluetooth, interrupt
---


title: Is my Arduino fried?

text:
# Question
Title: Is my Arduino fried?
I am worried that my Arduino is fried from a previous attempt at connecting a servo to it. To test my concerns, I changed the circuit to see if Arduino could even power a simple LED:

Code:

```
int led = 13;

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

void loop() {
    digitalWrite(led, HIGH);
    delay(4000);
    digitalWrite(led, LOW);
    delay(4000);
}

```

Wiring:

In that pic, the Arduino is connected to a 9V battery. When I test the purple connections with my multimeter, the power bounces between ~5V and a weird 1.65V value every four seconds. I *assume* thats power being applied to the output pin in keeping with my code.

However, the LED does *not* light up. Any ideas as to what could be going wrong or how I could troubleshoot?

# Answer
As noted in the previous answer, being able to upload a new sketch indicates an Arduino is ok in general – in particular has a functioning CPU – but of course that does not test all features. For example, individual inputs and outputs can be damaged.

You can easily change your sketch so that it drives some range of outputs, as shown below. Thereafter, try moving the red wire (that now connects on 13) to some other of the outputs in the selected range.

```
enum { LedLo=2, LedHi=20}; // Set lo and hi limits of range

void setup() {
  for (int led=LedLo; i <= LedHi; ++i)
    pinMode (led, OUTPUT);
}

void loop() {
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, HIGH);
  delay(4000);
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, LOW);
  delay(4000);
}

```
> 1 votes

# Answer
If the LED 'ON' is lit, the board has 3.3v power. Does the LED 'L' blink? It is also on pin 13, the one your sketch controls. If so, perhaps your breadboard circuit is likely at fault. Do you have a multimeter? Does the voltage on whichever pin # your sketch controls change as you would expect it to? If both are correct, then if you recompile your sketch to use a different pin #, and adjust your connections to match, does your breadboard LED light then?
> 0 votes

---
Tags: led, arduino-due
---


# Question
Title: Exiting from one loop and get ready for another
I am working on a keypad password lock system based on arduino UNO. I have used the password library from Arduino's website.

What I am trying to accomplish is to set two passwords, namely pass1 and pass 2.

The condition is that this circuit is attached to a gate, if user 1 lets say knows pass1, after entering the pass the gate will unlock for 10 seconds and the pass1 becomes invalid i.e. can not be used in future. However if user 2 comes and knows pass2, after entering the pass2, the gate will open for 10 seconds and then pass2 becomes invalid; so each password can be used only once. I am attaching the code I already have below.

The problem with this code is that when pass1 is executed, the system does not take pass2 until unless the system is reset.

Kindly tell me a solution to fix this.

```
#include <Password.h>
#include <LiquidCrystal.h>
#include <Password.h>
#include <Keypad.h>

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
Password password1 = Password("1234");
Password password2 = Password("4567");
int ledpin = A5;
int a = 0;
const byte ROWS = 4; // Four rows
const byte COLS = 4; // columns

char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
};

byte rowPins[ROWS] = {A0, A1, A2, A3};
byte colPins[COLS] = { 8,  9, 10, 11};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup() {
    lcd.begin(16, 2);
    keypad.addEventListener(keypadEvent); //add an event listener for this keypad
}

void loop() {
    keypad.getKey();
}

void keypadEvent(KeypadEvent eKey) {
    switch (keypad.getState()) {
        case PRESSED:
            lcd.println(eKey);
            switch (eKey) {
                case '*':
                    checkPassword();
                    break;
                case '#':
                    password1.reset();
                    password2.reset();
                    break;
                default:
                    password1.append(eKey);
                    password2.append(eKey);
            }
            return;
    }
}

void checkPassword() {
    if (password1.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code1 OK");
        delay(2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password1.append('1');
        lcd.clear();
        return;
    } else if (password2.evaluate()) {
        lcd.setCursor(0, 1);
        lcd.println("code2 OK");
        delay (2000);
        digitalWrite(ledpin, HIGH);
        delay(10000);
        digitalWrite(ledpin, LOW);
        password2.append('2');
        lcd.clear();
        return;
    } else {
        lcd.setCursor(0, 1);
        lcd.println("Wrong");
        delay(2000);
        lcd.clear();
        lcd.print("Wait for 5 Sec");
        delay(5000);
        lcd.clear();
        return;
    }
    return;
}

```

Regards Fawad

# Answer
You are never really invalidating the passwords. The statement

```
password1.append('1');

```

adds '1' to the **guess**, it does not change the **password** itself. If you really want to invalidate the password, you should change it to something that cannot be typed on the keypad. For example

```
password1.set("X");  // untypable password

```

Whether or not you do invalidate the previously used passwords, you should reset the guesses once a password has been checked. This can be done in `checkPassword()`, or in `keypadEvent()` as follows:

```
switch (eKey) {
    case '*':
        checkPassword();
        password1.reset();
        password2.reset();
        break;
    ...
}

```

BTW, **all** your `return` statements are useless, and the first switch/case in `keypadEvent` can be replaced by

```
    if (keypad.getState() == PRESSED)

```

which would be easier to read.
> 1 votes

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


# Question
Title: Determining which section of code uses the most flash
I'm running into the 32k flash ceiling of my 328p. The code is pretty compact but I need help making it smaller.

Is there an analysis tool (part of avr?) that can tell me which functions take up the most space? Obviously looking at the source code won't help because I don't know how the compiler decides to reorganize things.

I've moved strings to PROGMEM, but I'm still hitting the ceiling.

What are some tips for space saving? What are some ways of seeing what's taking up the most space?

# Answer
For knowing which functions take the most space, I generally use `avr-nm`. This command is intended to display the symbol table of a compiled program. It is one of the tools that you get when you install the Arduino environment, so you already have it. avr-nm provides the same information as `avr-objdump -t`, but it can display it in a nicer format.

As an example, I ran the following command on the basic blinky program:

```
avr-nm --size-sort -Crtd blink.elf

```

And this is the output:

```
00000148 T __vector_16
00000118 T init
00000114 T pinMode
00000108 T digitalWrite
00000082 t turnOffPWM
00000076 T delay
00000070 T micros
00000040 T loop
00000026 T main
00000020 T digital_pin_to_timer_PGM
00000020 T digital_pin_to_port_PGM
00000020 T digital_pin_to_bit_mask_PGM
00000016 T __do_clear_bss
00000010 T port_to_output_PGM
00000010 T port_to_mode_PGM
00000008 T setup
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000001 b timer0_fract

```

The first column is the size of the object referenced by the symbol. Second column is the type, where ‘t’ (upper or lower case) means “text” (code and PROGMEM data), ‘d’ means “initialized data” (stored in flash and copied to RAM at startup) and ‘b’ means “uninitialized data” (a.k.a. “BSS”, occupies no flash, only RAM). The last column is the symbol's name. In this example you can see that the biggest function is `__vector_16` (the ISR for timer 0 overflow), and it takes 148 bytes of flash.

The options I passed to avr-nm are the following:

* `--size-sort`, obviously, sorts the symbols by size. It also displays the size, instead of the address, on the first column.
* `-C` is for demangling the C++ symbols. For example, instead of displaying “\_ZN14HardwareSerial5beginEm”, it would display “HardwareSerial::begin(unsigned long)”.
* `-r` means “reverse sort”. This is for having the biggest functions at the top, instead of at the bottom.
* `-td` is for displaying the sizes in decimal instead of hexadecimal.

Since you are only interested in flash usage, you can ignore the symbols in BSS. On a unixish OS, you could just pipe into `grep -iv ' b '`
> 4 votes

# Answer
Moving strings *to* PROGMEM will only exacerbate the problem, since PROGMEM *is* the 32k flash.

You can easily get your "symbol table" from the compiled .elf file by using `avr-objdump -t <.elf file>`.

It results in a list something like this:

```
... scrolls past ...
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
00800110 g       .bss   00000000 __bss_start
000008a2 g     F .text  00000022 main
00000126  w      .text  00000000 __vector_4
00000000  w      *ABS*  00000000 __heap_end
00000126  w      .text  00000000 __vector_9
000003ae g     F .text  000000d0 delay
00000126  w      .text  00000000 __vector_2
00000126  w      .text  00000000 __vector_21
00000126  w      .text  00000000 __vector_15
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
008001c3 g       .stab  00000000 __heap_start
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
000008ff  w      *ABS*  00000000 __stack
0000008d g     O .text  0000000a port_to_input_PGM
00800110 g       .data  00000000 _edata
008001c3 g       .stab  00000000 _end
00000126  w      .text  00000000 __vector_8
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000a08  w      .text  00000000 exit
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
00000126  w      .text  00000000 __vector_14
00000126  w      .text  00000000 __vector_10
000002a8 g     F .text  00000090 __vector_16
00800100 g       .data  00000000 __data_start
00000480 g     F .text  00000076 __vector_18
00000126  w      .text  00000000 __vector_20
00000108 g       .text  00000000 __do_global_ctors
... etc ...

```

The lines you are interested in are `.text` sections. The first big number is the HEX location in memory. The second one is the important one - that is the size.

You can see from that snippet that the function `delay` is located at address 0x3ae and is 0xd0 bytes in size.

If you're on Unix or OSX you can employ the more advanced searching tools that are at your disposal. For instance, to just list the "global" `.text` entries:

```
$ avr-objdump -t <elf file> | grep '\.text' | grep ' g '

```

Which for my test program results in:

```
00000079 g     O .text  0000000a port_to_mode_PGM
00000918 g     F .text  00000040 _ZN5Print7printlnEv
00000a00 g       .text  00000000 __tablejump__
000006c2 g     F .text  00000040 _ZN14HardwareSerial4peekEv
000008c4 g     F .text  00000054 _ZN5Print5writeEPKhj
000000d4 g       .text  00000000 __trampolines_start
00000a0c g       .text  00000000 _etext
000006a0 g     F .text  00000022 _ZN14HardwareSerial9availableEv
0000012a g     F .text  0000002a loop
00000774 g     F .text  00000080 _ZN14HardwareSerial5writeEh
00000126 g       .text  00000000 __bad_interrupt
000000d4 g       .text  00000000 __trampolines_end
00000200 g     F .text  000000a8 digitalWrite
00000592 g     F .text  0000010e _ZN14HardwareSerial5beginEm
00000182 g     F .text  0000007e pinMode
00000097 g     O .text  00000014 digital_pin_to_port_PGM
000000d6 g       .text  00000000 __dtors_end
00000754 g     F .text  00000020 _ZN14HardwareSerial5flushEv
0000051c g     F .text  00000076 __vector_19
00000990 g     F .text  00000026 _ZN5Print7printlnEPKc
000000f8 g       .text  00000000 __do_clear_bss
000000ab g     O .text  00000014 digital_pin_to_bit_mask_PGM
00000000 g       .text  00000000 __vectors
000009fc g       .text  00000000 __tablejump2__
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
000008a2 g     F .text  00000022 main
000003ae g     F .text  000000d0 delay
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
0000008d g     O .text  0000000a port_to_input_PGM
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
000002a8 g     F .text  00000090 __vector_16
00000480 g     F .text  00000076 __vector_18
00000108 g       .text  00000000 __do_global_ctors

```

From that I can see that the function `_ZN14HardwareSerial5beginEm` is the biggest and takes up 0x10e bytes. That strange named function is a "C++ Munged" name. It actually corresponds to `HardwareSerial::begin()` and is the parent class name for `Serial.begin()`.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: How to read bytearray from arduino pin in arduino sketch
I'm using the DYP-ME007TX sensor with arduino uno. The output from this sensor comes in packets of 4-bytes:

```
Data[0]= 0xFF: Packet Header
Data[1]= 0x0-0xFF: Data Most Significant Byte (MSB)
Data[2]= 0x0-0xFF: Data Least Significant Byte (LSB)
Data[3]= 0x0-0xFF: Data Checksum: = (0XFF + MSB + LSB) & 0xFF

```

Data is in MILLIMETERS

16 bit value in `mm = Data[1] << 8 | Data[2]`

How can exctract this packet in arduino sketch and extract millimeter number?

# Answer
I found the answer from forum.arduino.cc There is a sketch

```
#include <SoftwareSerial.h>

// TX_PIN is not used by the sensor, since that the it only transmits!
#define PING_RX_PIN 6
#define PING_TX_PIN 7

SoftwareSerial mySerial(PING_RX_PIN, PING_TX_PIN);

long inches = 0, mili = 0;
byte mybuffer[4] = {0};
byte bitpos = 0;

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

  mySerial.begin(9600);
}

void loop() {
  bitpos = 0;
  while (mySerial.available()) {
    // the first byte is ALWAYS 0xFF and I'm not using the checksum (last byte)
    // if your print the mySerial.read() data as HEX until it is not available, you will get several measures for the distance (FF-XX-XX-XX-FF-YY-YY-YY-FF-...). I think that is some kind of internal buffer, so I'm only considering the first 4 bytes in the sequence (which I hope that are the most recent! :D )
    if (bitpos < 4) {
      mybuffer[bitpos++] = mySerial.read();
    } else break;
  }
  mySerial.flush(); // discard older values in the next read

  mili = mybuffer[1]<<8 | mybuffer[2]; // 0x-- : 0xb3b2 : 0xb1b0 : 0x--
  Serial.print("PING: ");
  Serial.print(mili/10);
  Serial.println("sm");
  delay(500);
}

```
> 1 votes

---
Tags: arduino-uno
---


title: Tile NeoPixel NeoMatrix 8x8

text:
# Question
Title: Tile NeoPixel NeoMatrix 8x8
As a programmer I am new and lack some knowledge in electronic and I will appreciate the help.

I wish to connect 3 Adafruit NeoPixel NeoMatrix 8x8 - 64 RGB LED Pixel Matrix (https://www.adafruit.com/products/1487) can some one please provide me a scheme how to connect/tile 3 these NeoMatrix 8x8 to one Arduino Uno.

Thanks a lot

# Answer
> 5 votes
On **the page that you cite** they say

If, say, you need MORE blinky, **you can chain these together.**

* For the second shield, connect the DIN connection to the first panel's DOUT.
* Also connect a ground pin together
* and power with 5V.
* There you go!

You can chain as many as you'd like although after 4 or more panels you may run low on RAM if you're using an UNO. Watch your power usage too, you may need a 5V 10A power supply for so many of these!

---

Related:

They also say:

* There is a single data line with a very timing-specific protocol. Since the protocol is very sensitive to timing, it requires a real-time microconroller such as an AVR, Arduino, PIC, mbed, etc. It cannot be used with a Linux-based microcomputer or interpreted microcontroller such as the netduino or Basic Stamp.

Our wonderfully-written Neopixel library for Arduino supports these pixels! As it requires hand-tuned assembly it is only for AVR cores but others may have ported this chip driver code so please google around.

An 8MHz or faster processor is required.

# Answer
> 2 votes
On the products page, they link to the Neopixel Uberguide, which should really contain what you need :-)

The good thing about the NeoPixels is that they can be chained, since each pixel is supplied with VCC, GND, Data in and Data out. Data out of LED1 will be data in for LED2, and afaik you can make infinitely long chains this way

# Answer
> 1 votes
I found the http://fastled.io/ libary to be a useful and well documented (https://github.com/FastLED/FastLED/wiki/Overview) alternative to Adafruit's NeoPixel library.

FastLED has some clever compression of palettes, and many other nice features that might save you valuable memory when using many neopixels.

---
Tags: arduino-uno
---


title: How to start Arduino programming?

text:
# Question
Title: How to start Arduino programming?
I am totally new to and don't know where to start, I am interested in building new system with combination of hardware and software and every time I search how to make that embedded system it finally reaches to Arduino and don't know anything about that what to buy and I also have some more question like

1. Is one Arduino device required for each Arduino project ?
2. Should I have to buy more then one device for each project ?
3. If not then how I will make that project run without Arduino ?

# Answer
An Arduino is basically a Microcontroller on a handy PCB with built-in programming interface. It also has a simple programming environment to get you up and running quickly.

The chip on the board can be thought of as the "brain" of the system. It's what you program and it's where you upload your software to.

> Is one Arduino device required for each Arduino project?

Yes and no. You can't "remove" your Arduino from your project and expect it to still work - it'd be like beheading someone - they cease to function without their brain. However you can replicate the Arduino in your system fairly easily so you don't have to embed the whole Arduino into it. You can get a blank chip the same as is on the Arduino reasonably cheaply and program the bootloader (the serial interface for programming it) into the chip using your existing Arduino, then build a new circuit around it. More information here:

> Should I have to buy more then one device for each project?

That depends if your project is complex enough to warrant more than one "brain". Using the "standalone" instructions above you could make multiple chips from one Arduino and embed them all in your one project.

> If not then how I will make that project run without Arduino?

There are other Arduino boards available that are designed to be embedded in your project. These are much smaller than the "development" boards like the Uno etc. They are also cheaper, being typically the absolute bare minimum you need to get you going. These can be a great way of saving time compared to the Standalone system above, and at the same time saving money compared to using the full blown Arduino boards. Boards include the Mini and Nano range of boards.
> 2 votes

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


title: DS1302 as a counter/count-up timer

text:
# Question
Title: DS1302 as a counter/count-up timer
I would like to use the DS1302, as a count up timer. My goal is to have the arduino time the amount of me driving my car. So it DS1302 will be used a count-up timer ie accumulate time. however when the car is switched off, I don't want to lose the value, and when I use my car again I would like to the time to continue accumulating. The resolution can be in minutes, as this will probably be the best.

I would like something like an odometer of a car, except its going to be the time, instead of distance.

**Q:** Can this be done with the DS1302 Module? and also how can I do this? Is there a sample code for a count-up timer?

# Answer
> 2 votes
Do you mean only accumulate during powered/driving, or also during standing still?

If the former, just get the start time in setup, then in loop continuously get the time and calculate the difference between it and the time read in setup. Since you don't know when power is lost you need to continually write the elapsed time to some form of non-volatile memory. You could use the Arduinos EEPROM, but that can wear out over time. It's better the use the DS1302s 31 byte of battery backed RAM. Next time the arduino starts up you need to read out this value and add this to the difference.

In case of the latter, you can halt the DS1302 so it stops incrementing time.

# Answer
> 1 votes
What you're describing is the equivalent of a digital Hobbs hour meters. You can read up about them if your are interested. The old ones (not digital in today's sense) clicked an odometer-like movement every 0.1 hours (typically). I don't think you need a real-time clock module as long as you're not interested in *when* you drove the car, but only in the accumulated duration.

A simple way would be a 1-minute delay loop that increments a counter and writes it to EEPROM. The EEPROM has a write-endurance spec of 100,000 writes, equivalent to over 800 hours, used this way. You'll lose the last fraction of a minute, whether it's a few seconds or nearly a while minute, whenever you shut down the Arduino. There are ways around this, if it matters, but that's an "exercise left for to the reader" as my textbooks used to say. Clock your micro with a crystal, not with its internal resonator, for best accuracy.

---
Tags: timers, time
---


# Question
Title: Transmitting sketches to Yun with Autobahn - a byte at a time?
I am using this tutorial to connect an Arduino Yun with a browser using Autobahn.

In the python file in the above repo, there is this code:

```
def controlLed(self, turnOn):
    if turnOn:
        payload = b'1'
    else:
        payload = b'0'
    self.transport.write(payload)

```

Here's the thing - I need to send whole sketches to my Yun, not just '1' or '0'. I tried sending more to the payload (like `payload = b'this is part or all of a sketch'`) but that doesn't work. I experimented with some other data types but at the moment these are shots in the dark.

How can I send some proper data (like 100 lines of Arduino sketch) with this mechanism? The end goal is that my existing sketch receives the new sketch commands via serial and runs them.

```
if (port->available()) {
  int commands = port->read();
  // Run commands here
}

```

I would be hugely appreciative of any help. Thank you!

# Answer
> 0 votes
Partial answer: to send more information than just a single byte, it is possible to run:

```
# python
payload = "Here is a longer string"

# arduino
String commands = port->readString();           // Reads the whole thing
String commands = port->readStringUntil('\n');  // Reads until the given separator

```

---
Tags: serial, arduino-yun, sketch, python
---


# Question
Title: Arduino processing serial comunication - losing data?
I'm trying to send an array back and forth between Processing and an Arduino UNO. But I think data is being lost along the way. I simply iterate over the array in Processing and send the Values separately. A new set of data is indicated by the character `<`. On the Arduino the data gets added to a string and sent back for testing. When I print out the string in processing, some data changed to `-1`.

The array contains `{1,2,3,4,5,6,7,8}`

The Output looks like this:

```
12345678
12345678
1234-1-1-1-1
12345678
12345-1-1-1

```

Is there something I'm missing in terms of implementation, or is this simply a hardware related problem (like slightly different clock speeds)? Is there any way to improve this?

**Arduino Sketch:**

```
int srr[8];

int content; // Data received from the serial port
void setup() {
  Serial.begin(9600); // Start serial communication at 9600 bps
}

 void loop() {
   String str = "val:";
   int test;
   if (Serial.available()){ // If data is available to read,
     content = Serial.read();
   }

   if (content == 60){
     for(int i=0; i<=7; i++)
   {
       str+=Serial.read();
   }
   Serial.println(str);
   }
}

```

**Processing**

```
Serial myPort;  // Create object from Serial class
int arr[]={1,2,3,4,5,6,7,8};  //The array to send

String str;
void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw() {
  //write
  myPort.write("<");
  for (int i =0; i<=7;i++){
    myPort.write(arr[i]);

  }
  //read
  if ( myPort.available() > 0){  // If data is available,
    str = myPort.readStringUntil('\n');         // read it and store it in val
    println(str); //print it out in the console
  }

```

}

# Answer
Ok, let's look at your Arduino program a bit at a time (for that is where the problem lies).

```
if (Serial.available()) { // If data is available to read,
    content = Serial.read();
}

```

If there is at least one character available in the buffer then read one character into the variable *content*.

```
if (content == 60) {

```

If the variable content is *60* (better to use '\>' so you can see what it is), then ...

```
 for(int i=0; i<=7; i++) {
     str+=Serial.read();
 }

```

... read 8 characters from the serial buffer *whether there are any characters in there or not*.

That last bit is the crunch point. You have an unknown number of characters in the buffer. You had at least one, and that one you read into *content*. You don't then check to see if there are the required 8 more characters available (or wait in each iteration of the loop for each character to actually arrive) before trying to read that character in.

If you take a moment to read the documentation on Serial Read you will see this:

> **Returns**
>
> the first byte of incoming serial data available *(or -1 if no data is available)* \- int

The simplest fix is just to make your loop *blocking* so it waits for a character to arrive before reading it:

```
for(int i=0; i<=7; i++) {
     while (!Serial.available());  // Wait for a character to arrive
     str+=Serial.read();  // Read it
}

```
> 1 votes

---
Tags: serial
---


# Question
Title: Sanity check with potential project. IoT with a dishwasher
So sanity check for a potential project.

We have an old dishwasher at work, a GE QuietPower 3, and being a technology company, we want to connect it to our chat room to notify that the cycle is done, so someone can unload it.

The first iteration of the project we were just going to cover the "finished" indicator light with a photoresistor, so when it lights up, the microcontroller will know it is done.

However, that is not very nice looking, the second approach, after quickly looking at the technical maintenance manual. Is to literally solder the ground and + of the "finished" indicator light to a digital or analog pin, and the ground pin on the micro controller, so the results are more precise.

I suspect the LED is probably less than 12V, (will confirm with a multimeter). I will step it down to 5V.

Then it is just a matter of checking if the pin is high or not on the microcontroller, is this simple enough to solve the problem, or am I overlooking something obvious?

# Answer
If connecting to the wiring, using an opto-coupler will ensure that your Arduino's days will be long on the face of the land. If it is an LED indicator you may be able to connect the opto-coupler LED input directly across the existing LED, but use of an appropriate series resistor would be wise. Optocoupler LEDs may have about 2 V forward operating voltage which is in the same range as a red LED. Some use lower forwards voltage LEDS (probably IR).

If your opto coupler has low input current requirements then connecting it via a series resistor across the existing LED will allow the indicator to still operate.

R series = (Vsource - V\_opto\_LED) / I\_opto.
eg 12V source, 2V opto\_LED (typical), 1 mA (should be enough for logiclevel signal.)
R = (12-2) / .001 A = 10/.001 = 10 k Ohm.

For direct connection across an existing red LED a 100 Ohm series resistor should avert disaster.
V drop in resistor at 1 mA:
V = IR = 0.001 x 100 = 0.1 V
= liable to be OK.

Ask if more information wanted.
> 2 votes

# Answer
More or less. LEDs are often around the 2.something volt range, which won't be enough to power an Arduino. In addition, if you set it to run in parallel with the LED, then the path of least resistance will get most of the current.

I would probably use the led power to turn on a transistor, then use the transistor to signal the Arduino. Be aware that if you want to power it off an external source, you may find that the ground on the washing machine is not the same as the ground on your power supply. If you're powering it off a battery, this won't matter, but otherwise power can flow from one "ground" to another. If you stick a resistor (maybe start with 1kOhm, if that's too much drop it down) between the washing machine led + and the transistor, and the same between the arduino and the transistor.
> 0 votes

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


title: Arduino UNO button LED brightness vary

text:
# Question
Title: Arduino UNO button LED brightness vary
I am using an Arduino UNO and I am trying to vary the brightness by steps by 0.5 volts till it gets to a max of 5.0 V using buttonA and decrease the brightness of the LED by 0.5 volts with buttonB. The Problem I have is that when I push buttonA the LED steps it's voltage by 0.5V all the way to 5.0V and with buttonB its steps down to 0. I would like to have the LED step each time I press the button not all at once. Here is my code that I have so far can someone help me with telling the Arduino to Step each time a button is pressed. CODE IS DIFFERENT from another post I did

HERE is my code:

```
int ledPin = 9; // must be a PWM digital pin
int buttonApin = A2; //buttonA to analog 2
int buttonBpin = A1; // buttonB to analog 1
int maxBright = 255; // between 0 and 255
int ms = 1500;    // delay in milliseconds
int buttonPushCounterA = 0; //counter for the number of button presses
int buttonStateA = 0; // current state of the button
int lastButtonStateA = 0; // previous state of the button
int buttonPushCounterB = 0; //counter for the number of button presses
int buttonStateB = 0; // current state of the button
int lastButtonStateB = 0; // previous state of the button

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW) //if buttonA is pushed
   {
      buttonStateA = digitalRead(buttonApin);

     if (buttonStateA != lastButtonStateA)
     {
        if(buttonStateA == LOW)
     {
        buttonPushCounterA++;
     }
    }

// fade from min to max in increments of 25.5 points: basically (0.5 volts)
for (float n = 0; n <= maxBright; n +=25.5)
{
 // sets the value (range from 0 to 255):
 analogWrite(ledPin,n);
 delay(ms);
}
  }

  if (digitalRead(buttonBpin) == LOW) //if buttonB is pushed
  {
     buttonStateB = digitalRead(buttonBpin);

       if (buttonStateB != lastButtonStateB)
         {
            if(buttonStateB == LOW)
              {
                buttonPushCounterB--;
              }
         }

     // fade from max to min in increments of 25.5 points: basically (0.5 volts)
     for (float n = maxBright; n >= 0; n -= 25.5)
    {
     // sets the value (range from 0 to 255):
     analogWrite(ledPin, n);
     delay(ms);
    }
  }

  lastButtonStateA = buttonStateA;
  lastButtonStateB = buttonStateB;
 }

```

# Answer
One problem in your original code is that you are only storing the current state of the buttons if they are pressed. The next problem is that you are looping through all your brightness values when a button is pressed giving you your "fades all the way up in one go" problem.

This would be my replacement for your loop() code:

```
loop()
{
    int currentButtonStateA = digitalRead(buttonApin);
    if (currentButtonStateA != lastButtonStateA && currentButtonStateA == LOW)
    {
        currentBrightness += BRIGHTNESS_INCREMENT;  // BRIGHTNESS_INCREMENT is defined at the top of the file with #define BRIGHTNESS_INCREMENT 25
        if (currentBrightness > MAX_BRIGHTNESS)     // MAX_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 255
        {
            currentBrightness = MAX_BRIGHTNESS;
        }
    }
    lastButtonStateA = currentButtonStateA;

    int currentButtonStateB = digitalRead(buttonBpin);
    if (currentButtonStateB != lastButtonStateB && currentButtonStateB == LOW)
    {
        currentBrightness -= BRIGHTNESS_INCREMENT;
        if (currentBrightness < MIN_BRIGHTNESS)     // MIN_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 0
        {
            currentBrightness = MIN_BRIGHTNESS;
        }
    }
    lastButtonStateB = currentButtonStateB;

    analogWrite(ledPin, currentBrightness);
}

```

Hopefully this is pretty self explanatory. The current button A state is read and stored in a local variable. If it is different to the previous state and it is low, the current brightness is incremented and capped at a maximum value. Next the current button state is stored as the previous state ready for the next run through the loop.

Similar actions are performed for the B button, but with a decrement rather than an increment. Finally the LED brightness is set regardless of whether any buttons have been pressed.

You do not need to store your current button states (buttonStateA) or your counts for the number of button presses (buttonPushCounterA - which you never referenced anyway) or your ms value so could get rid of those global variables. You need a new global variable at the top of your file for currentBrightness (int currentBrightness = 0;).

You have used variables to store various non-changing numeric values, such as "maxBright = 255;" which is good practise, but is better (particularly with Arduino development) to use #define macros instead, such as "#define MAX\_BRIGHTNESS 255".

The reason for this is that variables take up memory when the code is running - something that an Arduino Uno doesn't have a lot of, whereas a #define takes up no memory - the compiler uses it as a "search and replace" before compiling your code.
> 1 votes

# Answer
You forgot to check to see if the button was actually *pushed* or if it was just *held down*. See the State Change Detection example to understand how to perform edge detection.
> 0 votes

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


# Question
Title: How can I create a power rail on my Arduino shield?
I have an Arduino that has 4 devices within an enclosure. Each of the 4 devices needs 5 V and GND. I have a shield with lots of unused pins (see photo). I'd like to "bridge" one row of the pins to create a power rail, and I'd like to bridge another row to create a ground rail.

I think most people are using an external breadboard for this. Also, I see that there is a shield that has power rails, but I don't have room for it. I'm looking for a female header, or another way to bridge these unused pins.

*Note: I'm not asking about wiring voltage in parallel or amperage consumption.*

# Answer
Just bridge them. Wire in your +5V connections then join them together on the back with lots of solder. Maybe with a strand of 0.6mm single core wire along it for extra ruggedness.
> 4 votes

# Answer
Have you considered "Conductive Silver Paint"? With this you can literally paint tracks to join any arrangement of holes you so desire.

Everybody from Maplins to Rapid Electronics sell it. There are many brands to choose from. Here is one at random: http://www.rapidonline.com/mechanical-fastenings-fixings/kemo-conductive-silver-paint-180423 ...I like Rapid because they have a helpful Q&A section for each product.
> 3 votes

---
Tags: arduino-mega, shields
---


title: Increase PWM bit resolution

text:
# Question
Title: Increase PWM bit resolution
I would like to increase the PWM bit resolution of the Arduino Uno. At this moment it is 8-bit which I consider too low. Is this possible without losing the ability of interrupts and delays?

Koen

EDIT This setup delivers a 16-bit resultion

```
void setupPWM16() {
    DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
    TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
    TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS11);                    /* prescaler: clock / 8 */
    ICR1 = 0xffff;                      /* TOP counter value (freeing OCR1A*/
}
/* Comments about the setup
Changing ICR1 will effect the amount of bits of resolution.
ICR1 = 0xffff; (65535) 16-bit resolution
ICR1 = 0x7FFF; (32767) 15-bit resolution
ICR1 = 0x3FFF; (16383) 14-bit resolution etc....

Changing the prescaler will effect the frequency of the PWM signal.
Frequency[Hz}=CPU/(ICR1+1) where in this case CPU=16 MHz
16-bit PWM will be>>> (16000000/8)/(65535+1)=30.5175Hz
*/

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
    switch (pin) {
        case  9: OCR1A = val; break;
        case 10: OCR1B = val; break;
    }
}

```

# Answer
The Arduino Uno is based on an ATmega382P microcontroller. This chip has two 8-bit timers, driving two PWM channels each, and one 16-bit timer, driving the last two channels.

You cannot increase the resolution of the 8-bit timers. You can, however, put the 16-bit timer in 16-bit mode, instead of the 8-bit mode used by the Arduino core library. This will give you two 16-bit PWM channels, with a reduced frequency of 244 Hz (maximum). You will probably have to configure the timer yourself, and will not benefit from the easy to use `analogWrite()` function. For details, see the section on Timer 1 in in the ATmega328P datasheet.

**Update**: Here is an implementation of a 16-bit `analogWrite()`. It only works on pins 9 and 10, as these are the only pins connected to the 16-bit timer.

```
/* Configure digital pins 9 and 10 as 16-bit PWM outputs. */
void setupPWM16() {
    DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
    TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
    TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS10);                    /* no prescaling */
    ICR1 = 0xffff;                      /* TOP counter value */
}

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
    switch (pin) {
        case  9: OCR1A = val; break;
        case 10: OCR1B = val; break;
    }
}

```

You may notice that the top of the counter sequence is configured explicitly. You can change this to a smaller value to make the PWM faster, at the cost of decreased resolution.

And here is an example sketch illustrating its use:

```
void setup() {
    setupPWM16();
}

/* Test: send very slow sawtooth waves. */
void loop() {
    static uint16_t i;
    analogWrite16(9, i);
    analogWrite16(10, 0xffff - i);
    i++;
    delay(1);
}

```
> 16 votes

# Answer
With some calibration you could sum the outputs of two PWM channels with differing weighting resistors. At the extreme you could notionally use one output to provide 8 bits of resolution and scale the other to 1/256th the level and add them so the 2nd channel covers one bit of range and you (again notionally) get 16 bits of resolution. Without immense care and adjustment all you'd get would be a mess.
However by dividing the 2nd channel by 16 or 32 you could add several extra bits of PWM resolution. Just by adding 2 PWM channels analog filtered outputs you add an extra bit (as potential range is doubled for unchanged mV/bit).
Notionally (again) for every additional divide by 2 you get an extra bit of resolution, but this can only be carried out for maybe 4 or 5 or 6 extra bits, with increasing accuracy requirements of scaling resistors and more difficult calibration and proneness to errors.

Brief example.
If one PWM is scaled down to give say 0 - 255 mV in 1 mV step, then summing two PWMs with equal amplitude would give a 0 - 510 mV range in 1 mV steps.
If one PWM is scaled down by a factor of 32 then instead of adding 255 mV to the initial PWMs range it would add only 8 mV to the top end (0.256.32 = 8 mV, but resolution would be in 0.03125 (1/32nd) mV steps.

While this could perhaps be achieved purely with resistor summing and RC filtering, use of an op amp summer would greatly improve results.

Also PWM ripple could be filtered with a simple RC filter but use of one opamp as a buffer (or even just a single transistor as an emitter follower) would give you 3 or 5 poles of low pass filtering and much better chance of achieving extra PWM resolution. I have not inspected the "phase coherence" of the PWM outputs but expect that they move in relative lockstep so you don't get the smoothing advantage of adding two uncorrelated waveforms.

More comment can be made if needed. Ask if interested.
> 4 votes

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


title: Detect my position

text:
# Question
Title: Detect my position
I'm new to Arduino, but I have this idea for a game I would like to build.

I need the Arduino to be able to determine my relative position on a straight line - 20 feet (6 meters) long.

What would be the best way to achieve that?

Priorities:

1. Durable (Outdoors proof)
2. Easy for a newbie
3. Cheap

*EDIT. Some more context* \- I want to play Pong over a physical area (A grid of LEDs to act as pixels), and I want the use player's position on a line to set the position of the paddle.

# Answer
> 3 votes
Whether it's outdoor proof or not depends on the housing where you put your electronics.

For position tracking, there are basically 2 ways:
1. GPS
2. Acceleration sensors

For the given distance, a (cheap) GPS solution is not accurate enough (See https://www.sparkfun.com/tutorial/GPSTracking/clamped\_edit2-L.jpg, for instance). And it may be too slow for your purpose.

Acceleration sensors also have a simple serial interface, but handling the data to get accurate results is not really easy (However I'm sure that someone has already written a public available software library)

Luckily, for position tracking on a straight line, there's another solution:
3. use a ultrasonic sensor

Maybe there are even better solutions; to evaluate, it would help if you could specify your project more detailed (how exact shall the relative position detection be? Static or dynamic calculation? If dynamic, how fast will the movement be? ...).

Edit:
It could be worth considering the following alternative:
4. Use a rotary encoder, mount it to a retractable dog leash and hook this to the player's waist. The other end of course must be mounted to a steady pillar. Perhaps this is mechanically tricky, and it limits the mobility of the players, but electrically it's very easy.

# Answer
> 0 votes
If it's a grid of LEDs you may be able to place pressure sensors at points up and down the grid. Then you need to step on them in order to place the paddle at that point. Doesn't sound like you need 'exact' position, just a point on a grid. And you may be able to set up such pads to step on relatively cheap: force sensitive resistors or even whip up your own w/ cardboard and thin metal (foil?) separated with foam. We did similar for a halloween prop that was activated by stepping on the doormat.

---
Tags: sensors
---


# Question
Title: Relationship between baud rate and the frequency of vibration read using ADXL
I am doing a project using Arduino Uno and ADXL 345. I am quite new to this and I came across this post in the link" : https://www.sparkfun.com/tutorials/240. Here, a user had posted the below question in the forum.

"Im trying to use this accelerometer to test various frequencies of vibration on a cantilevered beam and I wanted to know what the maximum vibration frequency I could find with using this accelerometer, connected to a 16MHz processor, connected to my laptop. I’m mainly a mechanical person, but after doing some research I found the following: Accelerometer has a maximum of 3200Hz output data rate (so maximum frequency would be 1600Hz) Processor can execute 16,000,000 instructions/sec so this probably is okay Communication rate is 9600 bits/sec so in the program above we read at a minimum 6 bytes for each axis, so that’s 24 bits, leaving you able to read 9600/24 = 400 reads/sec resulting in a one to be capable of reading vibrations at 200Hz. If I bump up the baud rate to 115200, I should be able to then read 4800 times a second, thus measuring 2400Hz vibrations?"

But I do not see any replies to this question. I feel the above analysis mostly makes sense. It would be helpful if someone could confirm that the above analysis is right. If not right , then why isn't it right?

Thanks

# Answer
Firstly, the datasheet for the accelerometer suggests using \>=2Mhz SPI communication rate with 3200 or 1600 Hz output data rate operation.

Since the Arduino SPI library default clock is 4Mhz, the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz.

So the Arduino and accelerometer can detect vibrations up to 1600Hz.

Next, you send the data to your laptop. At 9600 BAUD, you are correct in saying that since the data is 24 bits, it will only update your laptop with the Arduino's measured frequency at 9600/24 = 400 Hz. So 400 times a second the Arduino could tell the laptop what frequency it measures, the measurement having a maximum frequency of 1600 Hz.

For the Arduino to simply pass the raw data to the laptop at 3200 Hz, you would need 24 bits * 3200 Hz = 76800 BAUD minimum.

The measurement data is in any case limited by the accelerometer sampling rate of 3200Hz.
> 1 votes

---
Tags: arduino-uno, frequency
---


# Question
Title: Connecting an Arduino to a telephone line?
I would like to connect my Arduino Uno to a telephone line in order to answer a call, record a sequence of DTMF tones, generate a DTMF tone in response, and hang up.

The telephone line uses a standard RJ11 connector. When a touch-tone phone is connected to the line, it receives one of two rings:

* a standard ring, which signals an incoming call
* a shorter "two-ring" sequence which signals a call from a local intercom

I would like my Arduino to listen for the "two-ring" sequence and only answer those calls.

How would I go about connecting my Arduino to the telephone line? Is there a shield designed for this purpose? I know I can use the `tone()` function to generate the DTMF tones, but I'm assuming I would need to perform some form of Discrete Fourier transformation in order to "read" the DMTF tones from the other end of the line.

Any suggestions would be appreciated.

# Answer
You can interface arduino to telephone line using MT8870D chip. This IC can decode DTMF tones. Below is a reference schematic from the datasheet.

Another popular design floating on the internet is below:

There are pre-build modules available from futurelec :

You can use Holtek HT9200 IC to encode DTMF that can be interfaced with Arduino. Below is the reference schematic from its datasheet.
> 7 votes

# Answer
You'll need some hardware assistance for the DTMF detection and generation; I doubt many Arduinos (you didn't say which, but maybe ARM?) have the horsepower to run an FFT (and deliver the results while anyone still cares....)\* `tone()`may not be precise enough in frequency for DTMF detection by the calling device; you'll have to check that out. A quick search finds a number of articles on building or buying tone detectors and generators.

Ringing pattern detection is a little easier but you'll still probably want to sense the ringing and convert it to a level in hardware, rather than tracking the instantaneous line voltage and trying to distinguish in software between noise, ringing, noisy ringing, and various degrees of quiet.

<sub>* But maybe this Hackaday project can give you some alternate and computationally feasible ideas.</sub>
> 1 votes

---
Tags: arduino-uno, wires, audio
---


# Question
Title: How can I add some additional 5 volt power
I have an Arduino which is being powered by a 9v, 2 amp power supply. I have about 20 relays which are powered by 5 volts each. I do not want to over work the voltage regulator on the board, so I would like to add another (possible 2) 5 volt regulator that I bought on amazon. I am planning to:

1. Connect the regulators VIN to the Arduino's vcc (9 volt)
2. Connect the regulator's GND to the Arduino's GND.
3. Connect the regulator's VOUT to the Relay's VCC

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

# Answer
> At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Absolutely. But don't daisy-chain the regulator to each supply input in turn, connect each one separately directly from the regulator.

> Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

It is not advisable. Small manufacturing differences between regulators can result in them outputting slightly different voltages, which will lead to destruction of hardware.
> 1 votes

---
Tags: power
---


title: Find number of RX and TX-pin on ArduiMu

text:
# Question
Title: Find number of RX and TX-pin on ArduiMu
I've got an Arduino V3+ and need to find the correct PIN number for its RX and TX-pin on the FTDI-connector.

How can I find out the correct number of them to use them with the SoftwareSerial-library?

**Why I need these numbers:**

I'm connecting a Sparkfun Bluetooth Mate/BlueSMIRF to the ArduiMUs FTDI headers and need to set a few settings in its command mode before it operates without flaws. This is the code I'm using:

```
#include <SoftwareSerial.h>

int bluetoothTx = ???;  // TX-O pin of bluetooth mate, Arduino D2
int bluetoothRx = ???;  // RX-I pin of bluetooth mate, Arduino D3
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  Serial.begin(9600);  // Begin the serial monitor at 9600bps

  bluetooth.begin(115200);  // The Bluetooth Mate defaults to 115200bps
  bluetooth.print("$$$");  // Enter command mode
  delay(5000);  // Short delay, wait for the Mate to send back CMD
  bluetooth.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
  // 115200 can be too fast at times for NewSoftSerial to relay the data reliably
  bluetooth.begin(9600);  // Start bluetooth serial at 9600
}

```

# Answer
You can use FTDI cable with your board on the last row of pads as you have highlighted.

Unfortunately your board designers do not publish a pdf version of the schematic so I opened the provided schematics in EAGLE and exported the FTDI connector diagram.

Here is the FTDI connector connections from the schematic:

Here is the pinout of the FTDI cable

So you can solder a 6 pin header on the bottom row and use the standard FTDI cable.

The FTDI row on your board indicates "BLK" on the left so orient your FTDI connector's black wire with the "BLK" pad on your board.

**EDIT:**

As per your edits you are using hardware serial on your arduino board to monitor and you are using one instance of "SoftwareSerial" to interface with bluetooth.

As SoftwareSerial library says, you can define any digital pins for Tx and Rx. In the example they have used Arduino pins 10 (pin 14 of the ATMEGA) and 11 (pin 15 of ATMEGA) for Rx and Tx respectively. In your non-standard arduino board, the micro-controller pin 14 is labeled as PWM1 and pin 15 is labeled as MOSI and they are brought out on connector JP7.

So in a nutshell you can use pin 4 of JP7 as SoftRx and pin 5 of JP7 as SoftTx.

If those pins are in use, you can always use other digital pins that are unused in your design. Just refer to the schematic of your board, ATMEGA328 datasheet and arduino libraries.
> 2 votes

---
Tags: serial, programming, pins, ftdi
---


# Question
Title: Convert a Serial string to a sketch command on Yun?
How can I convert a string like the following:

```
"pinMode(2, INPUT_PULLUP)"

or

'Keyboard.print("Hello world")'

```

into actual code that the Arduino can act on?

# Answer
> 1 votes
You can't - not directly.

There are two things you can do:

1. Build your "command" into a sketch and compile it, then upload it in to the Yun's AVR chip. The compiling will have to be done on your PC, and the HEX file uploaded to the AVR (you can do it directly through the Yun's web interface).
2. Don't send sketch code, but send pre-defined instructions like "Turn on pin 3" which your sketch then interprets. That could be as simple as two bytes "P3" for instance. It's entirely up to you how you craft that.

Firmata might help with option 2 if uploading a new sketch every time isn't what you want to do.

# Answer
> 3 votes
There is a third option: install an interpreter on the Arduino, then just send it the program you want it to run. There are a few such interpreters available. A quick search showed:

There are probably many others.

The difference between this option and Majenko's option 2 is that this would allow you to send a complete program, with functions, conditionals, loops, etc., whereas with a Firmata or similar approach you would keep the program logic (functions, loops, conditionals) on the host computer, and only send simple commands to the Arduino.

# Answer
> 0 votes
You might also try the Firmata library, too. It provides similar functionality, and there are some libs for the computer side of it, if you are so inclined.

---
Tags: arduino-yun, sketch
---


# Question
Title: Arduino ADK, other board, shield or what?
Sorry for bothering. I have a problem with my project and I can't fine someone who can help me yet.

I need the next configuration: PC --------------USB cable-----------------MegaA---------------USB cable----------------MegaB

I need serial communication with USB cable in both boards.

I have now solved the ( PC --------USB cable------MegaA) part.

And the other part, I have done PC------------------USB cable------------------MegaB

But I need do that like the first schematic. I don't have access to the MegaB because this is inside a machine, I can't access to its pines, I need connect to it by USB Cable. Is possible do that with ARDUINO MEGA ADK in the MEGA A position? or I need other kind of board or add one shield (like USB host)? I need send one thing from the pc to MegaA and Mega A send the same thing to MegaB. Is it possible? because I can't find some way to specify that I need recieve the information from one serial port, and send it to another different serial port. I need help, is very important. Excuse my english Thanks

# Answer
You would need a USB host shield to achieve what you want.

The Arduino by itself is not capable of connecting to both a PC and another Arduino through USB without the addition of extra hardware. In this case the USB Host Shield as detailed on the Arduino website:

http://www.arduino.cc/en/Main/ArduinoUSBHostShield

In the list of supported devices is:

* USB to serial converters: FTDI, PL-2303, ACM, as well as certain cell phones and GPS receivers.

The magic word there is ACM - that (or more specifically CDC/ACM) is what the Arduino USB Serial interface is.
> 1 votes

# Answer
A USB host is far beyond what an AVR Mega handle. You could add a 'daugther' board of some kind, but that would be a computer far more powerfull than the Mega itself (think of a RaPi, or a fat 32-bit micro-controller), so it would be a bit weird.

You might physically patch the first USB through to the second one, using for instance a relay. That would allow the PC (but not the first Mega) to talk to the second Mega.
> 0 votes

# Answer
You don't actually need to use serial-over-usb, the two devices can communicate more simply. The simplest way would be to Serial1, which uses pins D18 and D19; connect Serial1 on MegaA to either the serial or serial1 on MegaB. Since MegaA's transmit is MegaB's receive, you need to cross-over the wires (i.e. connect MegaA's TX to MegaB RX and vice versa).

Complete details can be found at: http://www.arduino.cc/en/Tutorial/MultiSerialMega

Make sure the two Megas have a common ground - the easiest way is to use one power supply (in your case, the USB) - you should just be able to wire GND and +5V from one board to the same pins on the other. If you use two different power supplies (e.g. two USB ports, even on the same PC), they may have different ground levels, and you can get a current flow directly out of one ground, and in to the other, damaging your PC.
> 0 votes

---
Tags: serial
---


# Question
Title: Need help with on off switch to power arduino.
I am trying to add an on and off power switch to my arduino project. My project is running off a 9v battery and I would like to save as much power as I can. There might be a better why that I don’t know. I added SLEEP\_MODE\_PWR\_DOWN to my project and from what I can tell, the arduino enters sleep mode. I am having a hard time getting the arduino to wake from sleep mode. Am I able to do this from a full power down? I have been reading this link. http://www.gammon.com.au/forum/?id=11497 and others.

# Answer
> 4 votes
Since you are using an Arduino Uno board, putting the MCU (the ATmega328P-PU) to sleep won't save you much battery juice. Putting the MCU to sleep won't make a difference because the voltage regulator on the Uno will waste a lot more power than anything else on the board. The ON LED will also draw significant amount of current on that board.

To really save power you should look into getting an Arduino board that has a more efficient voltage regulator, or use no regulator at all by changing your 9V battery by, say, 4 NiMH AA cells.

Here's some more information about the issue for you to look at: What are (or how do I use) the power saving options of the Arduino to extend battery life?

# Answer
> 1 votes
There is a very good write-up on how to save power, use sleep mode etc, at: http://www.gammon.com.au/power

This includes step-by-step examples of what was done to save power, and how much power was saved, including examples on how to go to sleep and wake back up.

---
Tags: power
---


# Question
Title: Using Multiple Serial Ports with arduino nano
I am using a arduino nano to control a adafruit ultimate gps and a xbee wireless controller. However I recently ran into a problem using both at the same time (before I was using each separately until now) and read that I cannot listen to 2 software serials at the same time with a arduino. The biggest problem I see is that since I can only listen to one at a time, if I open a port, will cached data from the xbee and/or gps instantly start transferring in? Or or it more luck based that I will catch it as it comes? How should I go about coding around this? Should I just close and reopen the ports as needed(assuming there is no luck factor involved)? Any help is greatly appreciated. I will explain more if necessary.

# Answer
You can use SoftwareSerial library in order to instantiate a second (soft) serial port.

By looking at the example, it seems that you can use any two digital pins to use SoftwareSerial library and instantiate a second serial port along with the hardware serial port.
> 2 votes

# Answer
You might be able to use the GPS's EN pin to enable and disable the communication to it, and also try to use the RTS/CTS pins of the XBee to control the flow, since that's their actual purpose there :)

I hope that helped.
> 0 votes

# Answer
The Mega and the Due have 4 UARTs. It seems like those should work, but they are much larger. I'm embarking on a project that needs to be small and use two serial ports. I'm looking at the Teensy, which has three UARTs.
> 0 votes

---
Tags: serial, xbee, gps
---


title: Weird Arduino math result

text:
# Question
Title: Weird Arduino math result
I have a simple code, part of which contains the calculation 800/1000, which seems to return a value of zero for some reason (even though I store it in a float variable). When I replace the calculation with the expected result (0.8) the code works as expected, I just wonder why the calculation doesn't produce the same result.

# Answer
Both 800.0/1000 or ((float)800)/1000 will work.

The former works only with hardcoded constants, while the latter works also with variables:

```
int a = 800;
int b = 1000;
float c = ((float)a) / b;

```
> 3 votes

# Answer
A whole numbers like 800 or 1000 are integers, while a number like 800.4 is considered fractional and is treated as a float. Two integers divided gives an whole integer result, in your case 0. If one number in the division is an integer, and one is a float, the result is a float.
> 6 votes

---
Tags: programming
---