message:
Arduino Servo circuit by example

I have an Arduino program that uses the [Thread library](https://github.com/ivanseidel/ArduinoThread) to create two concurrent threads, where:

* Thread #1 blinks an LED every 500ms; and
* Thread #2 blinks another LED every 250ms

I wired things up, flashed the program to my Arduino Due, and it ran beautifully.

I am now trying to add a 3rd thread that [sweeps](http://www.arduino.cc/en/Tutorial/Sweep) a servo back and forth.

Here's my design:

![enter image description here][1]

And the schematic that Fritzing generated for me:

![enter image description here][2]

And an accompanying actual picture of the wire up:

![enter image description here][3]

If you can see it, I've rigged Pin 10 as an `OUTPUT`, and attached the servo's signal line to Pin 9. Here's the code:

    #include <Thread.h>
    #include <ThreadController.h>
    #include <Servo.h>

 int SERVO_SIGNAL_PIN = 9;
    int SERVO_PWR_PIN = 10;
    int LED_1_PIN = 12;
    int LED_2_PIN = 13;

    Servo servo;
    int pos = 0;

    static bool LED_1_STATUS = false;
    static bool LED_2_STATUS = false;

    Thread blinkLED1Thread = Thread();
    Thread blinkLED2Thread = Thread();
    Thread servoThread = Thread();
    ThreadController master = ThreadController();

    void setup() {
        pinMode(LED_1_PIN, OUTPUT);
        pinMode(LED_2_PIN, OUTPUT);
        pinMode(SERVO_PWR_PIN, OUTPUT);

        servo.attach(SERVO_SIGNAL_PIN);

        blinkLED1Thread.onRun(blinkLED1);
        blinkLED1Thread.setInterval(250);

        blinkLED2Thread.onRun(blinkLED2);
        blinkLED2Thread.setInterval(500);

        servoThread.onRun(runServo);

        master.add(&blinkLED1Thread);
        master.add(&blinkLED2Thread);
        master.add(&servoThread);
    }

    void loop() {
        master.run();
    }

    void runServo() {
        // Give the servo a few seconds to reset to the starting position.
        servo.write(0);
        delay(5000);

        while(true) {
            for(pos = 0; pos < 180; pos += 1)  {
                servo.write(pos);
                delay(15);
            }

            for(pos = 180; pos >=1; pos-=1) {
                servo.write(pos);
                delay(15);
            }
        }
    }

    void blinkLED1() {
        LED_1_STATUS = !LED_1_STATUS;
        digitalWrite(LED_1_PIN, LED_1_STATUS);
    }

    void blinkLED2() {
        LED_2_STATUS = !LED_2_STATUS;
        digitalWrite(LED_2_PIN, LED_2_STATUS);
    }

When I flash this to the Due, two disappointing things happen:

 1. The LEDs, which previously blinked at the correct rates, now stay lit and do not blink at all; and
 2. The servo doesn't move

Now perhaps I have a bum servo, or perhaps I haven't wired it up correctly, but the most concerning thing to me is that the LEDs are no longer blinking. I have a *feeling* that once I get those blinking again, the servo will *probably* start sweeping as well.

Can anyone spot *anything* that jumps out at them as being wrong here, wiring and code alike?

  [1]: https://i.stack.imgur.com/kIYK9.png
  [2]: https://i.stack.imgur.com/VSuFE.png
  [3]: https://i.stack.imgur.com/HjUyc.jpg

body:
One thing that immediately jumps out at me is you are trying to power the servo from a digital pin.  That is very very wrong.

The servo must be powered from the +5V pin (or +3.3V pin if it's a 3.3V servo) and only the "pulse" pin is connected to an Arduino's PWM capable IO pin.

Also, I don't know how the "Threads" library works, but it looks to me like it's not real threads, but a "round robin" execution of function with time delays.  If one of your functions never returns (like your servo one) then the whole system will lock up.  You need to make your servo function non-blocking like your LED functions.  Give it a 15ms time setting and only move one step of the servo each time it gets called.

Ok, according to comments and research I can confirm that in fact the Thread library is really badly named.  It doesn't run threads, it just runs different functions at different times.  Those functions MUST be "single shot" - i.e., they MUST complete before anything else can happen.  There is absolutely no concurrency whatsoever.  It is entirely up to you to ensure that all your "threads" are fairly simple repetitive operations which are to be run at specific points in time.

Basically the operation is thus:

* Add a function and its time to a list.
* Work through the list to find a function whose time has expired
* Call that function
* Continue through the table
* Go back to the beginning

If you have two functions both with the same time then one function will be called first and execute to completion, then the other function will be called afterwards, to execute to completion.  Only when a function returns is the system able to move on to the next entry in the function list.

You *must not* use `delay()` in your "thread" functions for anything more than maybe 1-2ms of delay *in total*.  You *MUST* return from your thread with enough time for your next timed event to execute, otherwise it will be delayed, or never run at all.

So your servo thread would look something like this:

1. Add my current "direction" to the servo value
2. If the servo value < 0 or > 180 then invert the direction and limit the value to 0-180.
3. Write the value to the servo

That is then triggered every 15ms by the thread library.

So as real code it may look like:

    void runServo() {
        static int direction = 1; // 1 = up, -1 is down
        static int value = 0;

        value += direction;
        if ((value <= 0) || (value >= 180)) {
            direction = 0 - direction; // Change direction from + to - or - to +
        }

        value = max(min(180, value), 0); // Clamp it to between 0 and 180

        servo.write(value);
    }


sender: user

message:
What to with reset pin when laying out Arduino PCB?

I'm designing a PCB with a standard arduino ATMEGA328 DIP IC. Do I need to make a connection to the reset pin?

sender: assistant

body:
Yes, you do.  The pin needs to be pulled up to Vcc via a pullup resistor - typically 10KΩ.  Also, if you are using the Arduino bootloader and want to program via serial then this pin should be connected to your serial interface's DTR pin through a 100nF (typically) capacitor.  It is also often desirable to provide a reset button which switches this pin to ground.

You should examine the Arduino Uno's schematics and use them as a reference.


body:
"Atmel AVR042: AVR Hardware Design Considerations"

![AVR reset connections][1]

  [1]: https://i.stack.imgur.com/QDsBy.png


message:
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.

body:
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.


body:
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](http://www.nongnu.org/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.


message:
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!!!!!

body:
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


message:
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])

body: 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.


message:
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

body:
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.


message:
Arduino Servo is behaving strangely

I am trying to use the [Arduino Servo](http://www.arduino.cc/en/Reference/Servo) library to drive a simple [servo](http://torqpro.com/?product=sg92r-7) and am having some difficulty getting it to even move.

Here's the setup:

![enter image description here][1]

And the schematic that Fritzing generated for me:

![enter image description here][2]

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!

  [1]: https://i.stack.imgur.com/91RAN.png
  [2]: https://i.stack.imgur.com/sPxMd.png

body: 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.


message:
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.

body:
    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.


message:
Arduino Uno not appearing under ports

I have an Arduino Uno attached to my MacBook Air running the Arduino IDE 1.6.4.

The Arduino was visible in the Serial port section this morning, but then it just disappeared. The ON light on the Arduino still comes on, but I cannot connect to it through the port section. I attached the Uno to another computer and it did not appear there either. However, when a different Arduino is connected to my computer it does show up. I also tried using a different IDE version, and it did not appear there either.

All of the other topics I found regarding this were saying it is the OS's fault, but since I was able to see the other Arduino, I am pretty sure it is not. I updated the FTDI drivers, and I tried using a powered hub and it is still not there.

UPDATE:

When I took the chip out of the UNO that is not appearing and put it into a working UNO, I was able to see it, is it possible that the Serial port is just not working, and if so how would I fix that

Any help would be appreciated.

body:
If the Arduino doesn't show up on multiple computers, and others do, it may be bricked, or dead. You might try reflashing the chip, and hope that solves your issue. If it doesn't, chances are it's toast.

If however the device simply doesn't show up on one computer, but does on another. It's either a software issue, or a USB issue with that computer.

If winblows OS, try reinstalling, or updating the drivers for the USB, as well as the Arduino. And check your power management on the USB as well. I've seen Windows USB poop the bed if a device is connected / disconnected, or restarted several times in rapid succession. When this happens, sometimes Windows will think the port or device is faulty, and simply stop responding to its presence.

If *nix, make sure you've configured it properly.


body:
When an Arduino stops appearing, it is usually because it's fried. Especially if other machines appear when connected, and the faulty machine appears on no other machine.

Try [burning the bootloader][1].

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP


message:
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**](https://en.wikipedia.org/wiki/CAN_bus)  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.

body:
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.


message:
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?

body:
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()`.


body:
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 '`


message:
Store floats in and reading them from flash

How do I store floats in flash and how do I read them from there? (I need a look-up table for pairs of float values.)

The storing part doesn't seem to be so difficult as this compiles:

    PROGMEM float value1 = 1.23456;

But how do I read them? Do I need to copy them byte by byte to a float variable, or is there a better way? (I am using an Arduino ATmega 328p with 4-byte floats.)

body:
There is a helper macro in avr-libc that is designed just for this purpose:

    #define pgm_read_float_near(address_short) __LPM_float((uint16_t)(address_short))

    Read a float from the program space with a 16-bit (near) address.

    Note
        The address is a byte address. The address is in the program space.

Use it like:

    PROGMEM float pi=3.141592653;  // constant value in flash
    float diameter = 24.332154;    // variable user value

    float circumference = diameter * pgm_read_float_near(&pi);


body:
I realize that the OP asked about a single value, but I thought I'd add info on retrieving from an array.

    const float pmdata[] PROGMEM = {1.0, 2.0, 3.0};

then retrieve thusly:

    float val = pgm_read_float(&pmdata[idx]);


message:
How to use Ultrasonic Sensor's trig pin, and why it is needed?

I have HC-SR04 Ultrasonic Sensor with me. I couldn't understand the "Trig" pin's working structure and the working technic. Do we really need it while we use?

(With Arduino examples, I generally use Echo pin more than trig pin.)

![image][1]

  [1]: https://i.stack.imgur.com/X2dK8.jpg

body:
Yes, you do need it.

The purpose of the TRIG pin is to cause the module to send out a "Ping".  It's what makes the whole thing work.  As soon as the TRIG pin goes HIGH then LOW (for a period of not less than 10µs) the internal clocks start ticking.  8 cycles of 40KHz audio are sent out of the transmitter and it starts counting how long it takes for the echo to arrive.

If you don't use the TRIG pin the module won't be able to do anything at all.


body:
![Two versions of ultrasonic sensors][1]

  [1]: https://i.stack.imgur.com/p3fjW.jpg
There are two versions of this device. In the threepin version you trigger the measurement and receive the echo pulse on the same pin. In the four pin version trigger and echo are on separate pins.

Possibly your Arduino example is written for the three pin version.


body:
I stumbled across your topic while working in a personal project. As people said earlier, your doubts must be related to the different versions of this board.

Keep in mind that, when using the 4-pin you can keep the ECHO full online as an input, while in the 3-pin version, you need to cancel the ECHO to use it as Output for the TRIG.

This is particularly useful when you need to make a environmental analysis to different responses to different actions.


message:
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

body:
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?"

![enter image description here][1]

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...?!

  [1]: https://i.stack.imgur.com/K3Yks.jpg


message:
Arduino Yun used as Wi-Fi hotspot

I use for a project an Arduino Yun with Node.JS + socket.io to provide interactivity between a smartphone, driving through a webpage different devices.

I would like to enable this service for several smartphones at the same time. However I would like to work in the very same conditions that a (well configured) hotspot does:

1. I want to ensure that no user can see the other users on the network,
2. I want to have a limited number of connections on the Yun at the same time,
3. I want to force the different users when connected to the Wi-Fi to be routed to a captive portal on the first connection.

Does anyone know first if it is possible with an Arduino Yun (maybe some actions must be performed on a NodeJS virtual server as point 2). If yes, do you have a tutorial or any clues (do I have to use LuCi)?

Last question, in the same topic, I would like to use a fast granted access using NFC tag emulation to provide Wi-Fi credentials. Has anyone tried this with Arduino Yun and a shield?

body:
Finally, here is how I did the job. In short, I separated the two topics of getting a trace of any user using `socket.io` and giving a limitations of the number of users.

First, my Arduino Yun is on a Ethernet network where a router, acting also as the internet gateway, is a dhcp server. My Arduino Yun have a static IP address in the subnet of this router (so it is not a dhclient). This can be set either by modifying the file `/etc/init.d/network`.

Including the lines:

    config 'interface' 'wan'
            option 'proto' 'static'
            option 'ifname' 'your_interface_name'
            ipaddr xxx.xxx.xxx.xxx

or by using the LuCi interface.

For more information about the way to properly configure the network in OpenWRT, see [Network configuration][1].

Then the router is set to authorize only few IP addresses.

The last step is to bridge the Wi-Fi and the Ethernet (WAN and LAN) keeping the configuration of the Ethernet interface. This can be done using the LuCi interface. Be careful of what interface configuration you keep. [How to setup an OpenWRT router as a Wi-Fi bridge to an Ethernet router][2] gives the way to do this.

Note that this can also be done using the Arduino Yun as a DHCP server if you don't want to be connected on a network.

In the end, any connections on the Arduino Wi-Fi will get its IP address in the authorized range (up to 16 users at the same time in my case) by the router/DHCP server through the bridge.

In `socket.io`, I took the id that is given to any connected client and the IP address to ensure that I have a same user.

About the NFC dynamic tag, I developed a NFC specific board with a dynamic tag in the Arduino Yun/Uno format and its library to push through the bridge between ATmega and Atheros any new Wi-Fi code or any webpage. I think it is outside of this scope so if you need anything about this I can give you in PM.

I finally get at the end a device:

- Connected to an existing network and accessing the internet,
- Serving the webpages I want using my node serve,
- Able to push any information on any other devices on the network through my nodeJS server,
- Enabling access to people to local or network content,
- Serving some specific local information through the NFC shield.

  [1]: https://wiki.openwrt.org/doc/uci/network
  [2]: http://root42.blogspot.fr/2014/01/how-to-setup-openwrt-router-as-wifi.html


message:
ACS712 to build doorbell sensor - Arduino Hangs up

I have a [ACS712 module][1] that I am connecting to my Arduino Uno to read the current spike when my door bells rings (and then trigger some events in my "sketch").

In my country doorbells use the ~115 VAC at ~60Hz. So, I just opened the doorbell and connected the ACS712 module in series.

I do not know how much amperage my doorbell draws, but it is hardly the 30A supposedly supported by the module.

At this point I am *not* connecting the OUT pin to the Arduino, only VCC and GND to the +5V and GND of the Arduino Uno. (I am also tried connecting the OUT pin to A2 in the Arduino).

What happens is that as soon as I ring the doorbell the Arduino hangs up. Sometimes I even have to physically unplug the Arduino to get it back to life.

It doesn't necessarily happens in the first bell, but it does not survive 3 rings in a row.

The [ACS712 chip][2] is supposed to provide 2.1 kVRMS of isolation... it doesn't seem likely that the "kickback" from the bell would be 2100 VAC... so I cannot imagine how/why my Arduino is hanging up, when it is supposed to be completely isolated from the AC (that's the whole point of the Hall Effect current sensor).

I added some capacitors to the VCC/GND pins with no luck.

So... any ideas on 1) how to protect the Arduino from hanging up?, 2) what is making the Arduino hang up?.

  [1]: http://www.banggood.com/1PC-30A-New-Range-Current-Sensor-Module-for-ACS712-p-86583.html
  [2]: https://www.sparkfun.com/datasheets/BreakoutBoards/0712.pdf

body:
There are two probable solutions to your problem:

1. The ACS712 is a hall effect based sensor and also door bells have a solenoid attracting a hammer to hit the bell. Try and place the sensor away from the bell, this could avoid any possible magnetic interference. (This is less likely to happen but there is a fair amount of chance)

2. May be, there is a problem with the code OR the laptops USB. Connect the Arduino to the sensor and the OUT pin to an analog input. Run the following code:

<!-- language: lang-js -->

      void setup()
      {
         Serial.begin(9600);
      }
      void loop()
      {
         Serial.println(analogRead(A2));
      }

If this doesn't work, probably there's a problem with the sensor or the connections.

Give me more details about your connections, code and post a picture of your project for more help.


message:
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:

![enter image description here][1]

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?

  [1]: https://i.stack.imgur.com/TCe9F.png

body:
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);
    }


body:
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?


message:
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. ![Schematic][1]

  [1]: https://i.stack.imgur.com/TKtrK.jpg

body:
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/


message:
Fastest wireless communication

Hy guys,

I am currently working on a quadcopter stabilization algorithm for an indoor quadcopter. I now need to setup a wireless communication between my onboard Arduino and my controlling Arduino (and/or RasperryPi (not shure yet)).

My question is: What would be the fastest wireless communication possibility?

I am not worrying about distance; they won't get far apart from eachother. I want to keep a lot of resources on the stabilization algorithm and to keep down resources used for the communication and thus get the fastest communication on very few resources.

What are your opinions and experiences, what is going to be fastest?

body:
There is a difference between Wifi and Wireless. Wifi requires an already established network and uses the standard internet protocols. If this is what you mean, then the communication speed would only be influenced by the bandwidth of your network and the speed of the arduinos. I have not been able to find what the speeds of the modules are, but if they are 150 mB/s and your network is only 100, then you'll only get a speed of 100mB/s (which is a pretty decent speed).

If you want wireless (they create their own network using the unlicensed 2.4ghz spectrum, then buy these: nRF24L01+ 2.4GHz. They seem pretty reliable at short distances, and have a low power and high power variant. These have a speed of (at tops) 2 mB/s, but you won't have to worry about having a Wifi connection.

I personally do not know much about Bluetooth modules, so I cannot comment there.

Hope this helped.


message:
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.

body:
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][1]

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? ...).

  [1]: http://www.arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor

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.


body: 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.


message:
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][1] 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

  [1]: http://www.dx.com/p/ps-2-keyboard-adapter-module-for-arduino-works-with-official-arduino-boards-324893#.VX6FnfntlBc

body: 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.


message:
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**][1]

  [1]: http://pasted.co/479b09a3

[**uart.cpp**][2]

  [2]: http://pasted.co/6279fbae

[**print.h**][3]

  [3]: http://pasted.co/61714885

[**print.cpp**][4]

  [4]: http://pasted.co/d085dcba

>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.

body:
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/


message:
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?

body:
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


message:
PIR motion sensor stuck in a loop

I've bought an HC-SR501-compliant **PIR motion sensor** (like [this one](https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/)) and connected it to a **Teensy 3.1**. The circuit seems fine, and the LED lights up. However, **when nothing is moving in front of it, the sensor keeps reporting HIGH and LOW in suspiciously constant intervals**. The monitor reads like this (numbers in milliseconds)

    motion detected  4113
    motion stopped   7234
    motion detected  4114
    motion stopped   7274
    motion detected  4113
    motion stopped   7204
    motion detected  4111
    motion stopped   7184

When it detects movement, it stays on the triggered position for longer, but even then goes back to predetermined intervals, e.g.

    motion detected   4113
    motion stopped   17204
    motion detected   4111
    motion stopped   41754
    motion detected   4113

This is the sketch ([as found on Adafruit](https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/using-a-pir)):

    int ledPin   = 13;              // choose the pin for the LED
    int inputPin = 1;               // choose the input pin (for PIR sensor)
    int pirState = LOW;             // we start, assuming no motion detected
    int val      = 0;               // variable for reading the pin status

    unsigned long lastTime = millis();

    void setup() {
      pinMode(ledPin, OUTPUT);      // declare LED as output
      pinMode(inputPin, INPUT);     // declare sensor as input

      Serial.begin(9600);
    }

    void loop(){
      unsigned long currentTime = millis();

      val = digitalRead(inputPin);   // read input value
      if (val == HIGH) {             // check if the input is HIGH
        digitalWrite(ledPin, HIGH);  // turn LED ON
        if (pirState == LOW) {

          // we have just turned on
          Serial.print("motion detected ");
          Serial.println(currentTime - lastTime);

          // We only want to print on the output change, not state
          pirState = HIGH;

          // Save time for measurement
          lastTime = currentTime;
        }
      } else {
        digitalWrite(ledPin, LOW); // turn LED OFF
        if (pirState == HIGH){

          // we have just turned off
          Serial.print("motion stopped ");
          Serial.println(currentTime - lastTime);

          // We only want to print on the output change, not state
          pirState = LOW;

          // Save time for measurement
          lastTime = currentTime;
        }
      }
    }

**Could this be a faulty device?** I'm thinking about getting a new one for testing. While I can compensate for the gaps when triggered, I can't think of a way to make sure that it's not actually being triggered by this weird internal interval.

body: Try powering the PIR motion sensor with a higher voltage.  I get the same problem you're seeing when powering it with the 3.3v output of an Adafruit Huzzah ESP-12, but it works just fine when I power it with the 5v USB power.


message:
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?

body:
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.


message:
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;
     }

body: 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.


body:
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.


message:
SFML Packet and Arduino

Can the [`sf::Packet`][1] 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

[1]: http://www.sfml-dev.org/documentation/2.3/classsf_1_1Packet.php

body:
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?


message:
LiquidCrystal_i2c and Pin 2

I'm trying to read temperature and humidity from a DHT11 sensor and write values to a 20x4 LCD.
I hit a behaviour I don't understand. When I use the DHT tester program that come with the DHT library, everything works well. I get the DHT information on the Serial console. This DHT tester program use the pin 2 to read the data from the DHT.

I wrote the following code who works perfectly:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>  // F Malpartida's NewLiquidCrystal library
    #include <DHT.h>

    #define DHTTYPE DHT11
    #define DHTPIN 13      // Digital

    DHT dht(DHTPIN, DHTTYPE);
    LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    void setup() {
      Serial.begin(9600);
      while (!Serial) {
      }
      Serial.println("Serial OK!");

      dht.begin();
      lcd.begin(20,4);
      lcd.setBacklight(0);
      lcd.clear();
      lcd.print("Hello! ");

      Serial.println("Init finished!");
    }

    void loop() {
      delay(2000);

      float DHT_hum = dht.readHumidity();
      float DHT_temp_c = dht.readTemperature(false);
      float DHT_temp_f = dht.readTemperature(true);

      if (isnan(DHT_hum) || isnan(DHT_temp_c) || isnan(DHT_temp_f)) {
        Serial.println("Failed to read from DHT sensor!!");
        lcd.clear();
        lcd.print("fail! ");
        return;
      }

      float heat_index = dht.computeHeatIndex(DHT_temp_f, DHT_hum);

      Serial.print("Humidity: ");
      Serial.print(DHT_hum);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(DHT_temp_c);
      Serial.print(" *C ");
      Serial.print(DHT_temp_f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(heat_index);
      Serial.println(" *F");

      lcd.clear();
      lcd.print("Humi: ");
      lcd.print(DHT_hum);
      lcd.print("%");
      lcd.setCursor(0, 1);
      lcd.print("Temp: ");
      lcd.print(DHT_temp_c);
      lcd.print("C");
      lcd.setCursor(14, 0);
      lcd.print("HI: ");
      lcd.setCursor(14, 1);
      lcd.print(dht.convertFtoC(heat_index));
      lcd.print("C");

    }

As you can see, I use pin 13 for the DHT11 (DHTPIN).
If I set to it to "2" then my program is no longer working (having the pin connected or not doesn't change the result).
The serial display

    Serial OK!
    Init finished!
    Failed to read from DHT sensor!!
and that's all, it even doesn't loop to display "Failed to read from DHT sensor!!" again. LCD text doesn't change too. Like if the program is totally exiting after "Serial.println("Failed to read from DHT sensor!!");"

I'm lost... The LCD lib I use is the very common one from fm
https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

body:
<!-- language-all: lang-C++ -->

    LiquidCrystal_I2C    lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

<s>Are you not using pin 2 in the LiquidCrystal_I2C constructor? So you can't also use it for the DHT sensor.</s>

---

I withdraw that suggestion.

---

Can you please try saving some RAM?

Use the F macro with your prints, eg.

      Serial.print(F("Humidity: "));
      Serial.print(DHT_hum);
      Serial.print(F(" %\t"));
      Serial.print(F("Temperature: "));

Ditto with the `lcd.print()` calls.


body:
I'm self answering..
On my Arduino Leonardo, the SDA and SCL pin used for the I2C connexion to the LCD panel, are the same pin than the Digital pin 2 and 3. So using SDA/SCL remove ability to use pin 2 & 3.


message:
MQTT for GSM/GPRS sheild

I want to publish sensor data to server using MQTT protocol via GPRS/GSM modem.

I googled MQTT for Arduino, AQTT Arduino available only for Ethernet shield or will MQTT Arduino Ethernet shield work in GSM modem?

body:
MQTT is an TCP/IP protocol. MQTT-SN is for wireless serial and is slightly different but you can bridge the two.  Since you can establish a TCP/IP session over GSM, I would expect that functionality would not be duplicated in any way by MQTT, but would instead depend on your GSM hardware providing the TCP layer.

And the final comment, I doubt if you would ever see this on an Arduino. Simple alternative, use a common smartphone as a wifi hot spot, done.


body:
Nick O'leary published an MQTT client for Arduino.
I use it extensively.  You can find it here: <http://knolleary.net/arduino-client-for-mqtt/>.
Once you have established a tcpip connection you can use this library to send/receive via the MQTT protocol across a GPRS/GSM modem.  I have used it successfully on:

 - the Arduino GSM shield
 - the Seeeduino GPRS IoT panel
 - a Freetronics Arduino Mega connecting via ethernet to a TPLink MR3020 router


body:
Arduino MQTT Library for SIM800 (and SIM900) GSM Modem is available at [ElementzTechBlog][1], [ElementzGithubRepository][2]

**Functionalities:**

**Auto connect**

 - Automatically connect to TCP and to MQTT server.

**connect function**

 - This function can be used to connect your client to MQTT broker.
 - Use only if you do not use Auto connect functionality.
 - Optionally  you can use username, password, WILL topic and WILL
   Message.

**OnConnect CallBack function**

 - This call back function is called when MQTT connection is
   established.

 - You can call subscription and publish functions inside it (according to your need).

**publish function**
 - This function can be used to publish messages to different topics.

 - You can select  QoS levels and RETAIN flag according to your need.

**subscribe function**

 - This function can be used to subscribe messages from different
   topics.

**OnMessage CallBack function**

 - This callback function is called when messages are received from
   subscribed topics

 - Topic, TopicLength, Message, MessageLength are the arguments of
   OnMessage callback function.

 - Inside this, you can write your custom code.

**unsubscribe function**

 - This function can be used to unsubscribe from a previously subscribed
   topic.

**disconnect function**

 - This function can be used to disconnect your client from MQTT broker.

**Keep Alive**

 - You can specify your KeepAlive duration while initializing.

 - Ping requests are sent and received automatically.

**Subscribe Publish examples are also provided.**

  [1]: https://elementztechblog.wordpress.com/2016/07/18/arduino-mqtt-library-for-sim800-gsm-modem/
  [2]: https://github.com/elementzonline/SIM800_MQTT


message:
DS1302 as a counter/count-up timer

I would like to use the [DS1302][1], 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][2] of a car, except its going to be the time, instead of distance.

  [1]: http://playground.arduino.cc/Main/DS1302
  [2]: https://en.wikipedia.org/wiki/Odometer

__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?

body:
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.


body:
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.


message:
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.

<!-- language: lang-c++ -->

    #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

body:
You are never really invalidating the passwords. The statement

<!-- language: lang-c++ -->

    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.


message:
Transmitting sketches to Yun with Autobahn - a byte at a time?

I am using [this tutorial](https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/wamp/app/serial2ws) 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!

body:
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


message:
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?

body:
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);
    }


message:
Arduino does not work on battery

The day before I got my used full package arduino uno. I tested it on USB plug. Everything worked fine. I wrote a piece of testing code and uploaded. After I have accomplished with the test I have unpluged arduino from PC and connected to battery and I see that it does not work. I have used a multi-tester to find out the voltage. It showed 4.7V. Now I wonder should I buy a new battery or there is another reason for this. Anybody, please suggest me what to do.
**Update**
The battery came with arduino set. It is written that it is a 9V battery. I am plugging it to the battery input in my arduino uno. Polarity is ok. The same program working on connection via usb, does not when connected to battery.

body:
Did you make sure the battery is charged? Does it have enough voltage to power the board? Remember that Arduino has internal voltage regulator, so you need something little more than 5V in order to get it working okay.

*(Comment by bpinhosilva re-purposed as an answer so this will stop showing up as unanswered).*

> @bpinhosilva you are right, the battery was not supplying enough power to make arduino work.

Please accept this so that the number of unanswered questions goes down. :)


body: Check the serial number of your board. Some boards were shipped with a defective boot loader, which has the loader stuck in an infinite loop when powered off and on again. Just Google the serial range of possible defective boards, and check if your board is in that range.


body: Try to use a battery that provides at least 7-12 volts. The voltage regulator will regulate the needed 5 volts for the arduino.


body:
simply you can weld a little electrolytic capacitor eg. 4 or 6 microfarads, 12 or more Volts, with the positive wire on the reset pin and the negative on the GND pin. in this way you can solve the restart without the USB connection.
This is what I did
Enjoy with Arduino.
By Daniele


message:
Which type of sensor should i use to get RPM of an engine?

Using Arduino _(i got **leonardo** and **uno**)_,
I'm looking for a way to get the **RPM of my car's engine**.
I know this can be done using an OBD2 connection however i'm looking for a different way.

# Sensing?
I need a reference for a **sensor** / a **creative way** to get this data.

Having said that, these approaches came up:

- guessing the RPM by reading the amps in the car's 12V connection
- recording the sound of the engine using a microphone and setting thresholds for certain RPM values

body: What about measuring the speedometer? I suspect that would be easiest - you may get away with hooking up the speedo directly to the Arduino analog (but measure with multimeter first!).


body: I would think [something like this](http://arduinodev.com/hardware/obd-kit/) would benefit you greatly. If your vehicle was produced after 1996 it will have an [OBD port](https://en.wikipedia.org/wiki/On-board_diagnostics) near the steering wheel that allows you to read diagnostic information from the car. This diagnostic information always includes error codes (think: Check engine light), and often includes operating information like speed and engine rpm.


body:
I'm doing this with a TCRT5000 and a LED+phototransistor, you can find them all over Amazon and eBay. I painted one quarter of a camshaft pulley white, and the other three-quarters flat black, and mounted the optical sensor over the edge of the pulley. This is on a Subaru, where the cam pulley and timing belt are all underneath a shroud, which keeps out ambient light. It works quite well.

Plus a .1uf capacitor next to the Arduino, because the transitions between high and low were pretty noisy without it.


message:
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 ?

body:
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:

* http://www.arduino.cc/en/Main/Standalone

> 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.

* http://www.arduino.cc/en/Main/ArduinoBoardMini
* http://www.arduino.cc/en/Main/ArduinoBoardNano


message:
Determine XBee Packet Route

I am trying to build a ZigBee network using XBee Pro S2 devices (API Mode).
Setting up the network and sending packets is easy enough.

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

Example:

I have 2 routers, one in area A connected to the coordinator, and the other in area B connected to the router in area A. End-device enters area B, and transmits a packet to the coordinator.
Path: end-device->routerB->routerA->Coordinator.

Is it possible to know the end-device is in area B as it is the first router device the packet travelled through?

body:
It is done by using [Source Routing](https://www.digi.com/wiki/developer/index.php/Large_ZigBee_Networks_and_Source_Routing)

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


message:
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
      }
}

body:
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](http://www.arduino.cc/en/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
    }


message:
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?

body:
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.


body:
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:

* [Bitlash](http://bitlash.net/), a C-like language
* [iArduino](http://n.mtng.org/ele/arduino/iarduino.html), another
  C-like language
* [FlashForth](http://flashforth.com/), a
  [Forth](http://en.wikipedia.org/wiki/Forth_(programming_language))
  implementation
* [FINF Is Not Forth](https://github.com/lpereira/finf), a Forth-like
  language

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.


body:
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.


message:
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?

body:
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.


body:
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.


message:
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.*

![example shield with unused pins in the center section][1]

  [1]: https://i.stack.imgur.com/6vn7I.jpg

body: 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.


body:
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.