message:
Arduino LDR sensor stained

I bought a light sensor (**LDR**), but he got **stained**, what it means? It is used? Or is **residuum** of time?

I must give back? I have to clean up or something?

I bought as new, so I tested one of the LEDs will not turn on.

I bought the (Mercado Livre in BRAZIL).

The product is:
http://www.gbkrobotics.com.br/exemplo-produto/p7-sensor-de-luz-com-leds.pdf

I pay R$8 BRL (equivalent aprox. $2 dollars) but, i just wanted to know if he had something I could do, because only shipping was R$ 13 BRL ($4 dollars)

* I'm starting with Arduino, thx

[![enter image description here][1]][1]

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

body:
I've read you post a couple of times and I get the impression you would like this board to work, so here are some quick check to try and find the fault.

 - You need a bread board
 - An arduino
 - A 200-300 ohm resistor.
 - Some wires. About 6 hands :)

Connect the board ground to the breadboard.  Then connect the to the resistor.  Then connect that to the power supply ground.

Take the positive off the power supply and touch it to the LED1 pin and check LED1 lights up.  Repeat with 2 and 3.

Switch every thing off

Connect the Positive to the Vcc connection of the board.
Connect a wire between Arduino A0 and "Sinal Analog"

Load this sketch

       void setup() {
           Serial.begin(9600);
        }
       void loop() {
           Serial.println(analogRead(A0));
           delay(250);
       }

When you cover the LDR it should read a lower number when you shine a light on it should read a higher number.

Turn everything off again, and if you have a multi meter test the resistance of the resistor on the board it should be 300 ohms, but I can't remember which way to read the bands and it might be 10K ohms, which would be a problem.

If anything doesn't work then they can all be fixed for a few cents and you don't need to worry about the discolouration.

Hope that helps you.


sender: user

message:
How do I give the ENTER keypress?

I have a Teensy set up as a keyboard, joystick, and I'm giving keyboard commands. Letter and number keys are going fine. But when I try sending ENTER, I get some extra code in my Linux terminal:

<!-- language: lang-none -->

    $ 16424
    16424: command not found

the code I have to give the ENTER key goes like this:

<!-- language: lang-cpp -->

    void setup() {
      pinMode(0, INPUT_PULLUP);
      pinMode(1, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop() {
      // read the digital inputs and set the buttons
      Joystick.button(1, digitalRead(0));
      Serial.println(digitalRead(0));
      if(digitalRead(0)==0){
        Keyboard.println(KEY_ENTER);
      }
      delay(50);
    }

where is this  "16424" coming from, and how do I send an ENTER keypress?
I am using a Teensy 2.0, on Linux, with Arduino IDE 1.6.7.

sender: assistant

body:
You can't just "print" a key like that. You use `print` for sending text.

When you use `println` it sends an enter key along with your text, so you can do :

    Keyboard.println("ls -al");

and it will send the text `ls -al` and press enter for you.

If you want to do it in the 'raw' way you will need to press and then release the key:

    Keyboard.press(KEY_ENTER);
    Keyboard.release(KEY_ENTER);


message:
Make LED blink using AVR assembly

I have an ATmega328P Arduino and am trying to make the LED blink using assembly without any additional includes. The goal is to have it blink for 1 second on, then 1 second off, however, it blinks incredibly quickly and is barely perceptible. Am I doing something incorrectly?

    ; DDRB     = 0x04
    ; PORTB    = 0x05
    ; TCCROB   = 0x25
    ; TCNT0    = 0x26
    ; 0b00000000 = OFF
    ; 0b00100000 = ON

    setup:
        ldi r16, 0b00100000  ; Set r16 to LED ON value
        out 0x04, r16   ; Set DDRB to output
        out 0x05, r16   ; Set PORTB to ON
        ldi r16, 0b00000101     ; Set r16 with prescaler 1024 value
        out 0x25, r16   ; Set the TCCROB to 1024
     ldi r20, 0     ; Reset r20
     ldi r21, 1    ; Hold value 1 to increment r20
    loop:
        in r17, 0x26   ; Read the timer
        cpi r17, 128   ; Check to see if the timer is halfway done (1/2 second, max 255 value)
        brbc 0, increment  ; If r17 <= 128 (max 255 val before resets to 0), invert current LED state
     rjmp loop
    increment:
     adc r20, r21   ; Add r21 (1) to r20 (with carry)
     brbs 0, reset   ; If the carry branch is set, reset the register
     rjmp loop    ; Otherwise, run the clock
    reset:
     ldi r20, 0    ; Reset the delay register
     cpi r16, 0b00000000  ; Check if r16 is set to LED OFF
     brbs 1, switchon  ; If it is, change it to ON
     ldi r16, 0b00000000  ; Otherwise, change it to OFF
     out 0x05, r16   ; Set the LED to the new state
     rjmp loop    ; Run the clock
    switchon:
     ldi r16, 0b00100000  ; Set r16 to LED ON value
     out 0x05, r16   ; Set the LED to the new state
     rjmp loop    ; Run the clock

body:
It appears that your intent is to set TCCROB up with a 1024x prescale, and each time it counts up to 128, increment r20, and toggle the LED each time r20 overflows to zero.

That sequence ought to take 1024/16M · 128 · 256 seconds, or about 2.1 seconds, a fairly leisurely toggle rate.  If instead it's flashing a hundred or more times too fast, probably one of the comparisons is backwards.

Some of the following items might make it easier to debug the problem:

• Instead of `brbc 0,...`, say `brcc ...`
• Instead of `brbs 0,...`, say `brcs ...`
• Instead of `brbs 1,...`, say `breq ...`

That is, use proper mnemonic branch instruction names, rather than referencing SREG bits.

• If my arithmetic was correct and your branch tests were fixed, your rate would be off by a factor of two.  To fix this problem, you could replace one of the more problematic tests (testing for carry clear after `cpi r17, 128`) with `cpi r17, 0` followed by a `breq`, and change the prescale factor to 256 instead of 1024, which gives 256/16M · 256 · 256 seconds, or about 1.05 seconds.

• Use named constants for register names instead of 0x04, 0x05, 0x25, and 0x26.

 • Instead of your lengthy toggle sequence use EOR to toggle the value.  That is, replace

        cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
        brbs 1, switchon        ; If it is, change it to ON
        ldi r16, 0b00000000     ; Otherwise, change it to OFF
        out 0x05, r16           ; Set the LED to the new state
        rjmp loop               ; Run the clock
    switchon:
        ldi r16, 0b00100000     ; Set r16 to LED ON value
        out 0x05, r16           ; Set the LED to the new state
        rjmp loop               ; Run the clock

with

        eor   r18, r16          ; Toggle LED bit
        out   PORTB, r18        ; Set the LED to the new state
        rjmp  loop              ; Go run the clock

where r16 and r18 are initialized as follows in setup:

        ldi r16, 0b00100000     ; bit mask for LED pin
        mov r18, r16


body:
There is a bug with the logic of your program: once TCNT0 gets larger
than 128, it will continue to be larger than 128 for quite some time...
during which time you are continuously incrementing your r20 counter.
The simplest fix would be to reset TCNT0 right after the `increment`
label, with something like `out TCNT0, zero_reg`. Then you may want to
compare TCNT0 with 61 instead of 128, in order to get closer to the
desired blink frequency of 0.5 Hz.

Other than that, there are quite a few problems in the way you write
your code. jwpat7 has already pointed out some of them, and here are
more:

* You should not increment a register with `adc`, but with plain `add`.
  Both instructions update the carry bit, but `adc` also adds the
  previous value of the carry bit to the target register.
* Better yet, increment with `inc`, as it's purpose is more obvious. But
  then you should test the zero bit, as `inc` does not update the carry
  bit.
* There is little point in resetting r20 once it has overflowed, as it
  is zero at this point.

There are also quite a few ways the program could me made simpler. The
simplest would probably be to configure timer 1 to deliver an interrupt
every second, and toggle the LED in the ISR. If you do not want
interrupts, you can configure counter 1 in much the same way, only
without the “interrupt enable” bit, and check the interrupt flag in a
busy loop.

Below is a slightly simplified version of your program. I tried to keep
it as close as possible to yours, without using timer 1, nor interrupts,
and not even the interrupt flag. The code checks for timer 0 overflowing
by comparing its current value with the previous one.

    .set PINB,     0x03
    .set DDRB,     0x04
    .set TCCR0B,   0x25
    .set TCNT0,    0x26
    .set LED_MASK, 0b00100000
    .set PS_1024,  0b00000101

    setup:
        ldi r16, PS_1024    ; Set r16 with prescaler 1024 value
        out TCCR0B, r16     ; Set the TCCROB to 1024
        ldi r16, LED_MASK   ; Set r16 to the LED bit
        out DDRB, r16       ; Set LED pin to output
        clr r18             ; Clear the saved timer
    loop:
        ldi r20, 61         ; Initialize our software counter
    check_timer:
        in r17, TCNT0       ; Read the timer
        cp r17, r18         ; Compare with previous value
        mov r18, r17        ; Save current value
        brsh check_timer    ; unless the timer has decreased, repeat
    decrement:
        dec r20             ; decrement the software counter
        brne check_timer    ; if not zero, go back to checking the timer
    toggle:
        out PINB, r16       ; toggle the LED
        rjmp loop

If we can use the timer overflow interrupt flag, then the test is
simpler, and we do not need to store the previous and current values of
the timer in registers:

    check_timer:
        sbis TIFR0, TOV0    ; unless the timer has overflowed
        rjmp check_timer    ; check again for overflow
        sbi TIFR0, TOV0     ; otherwise clear the overflow flag


message:
Printing decimal numbers

I made simple sketch that generates three random numbers and then calculates the average of these three random numbers.

It divides the total by 3 and then displays that average number with `serial.println`.

Sometimes the generated average number can be decimal (for example 261,333333 or 124,33333).

Interestingly, the serial print doesn't print in decimal format **124,33333**
it prints just integer **124**.

How do I print the value in decimal?

body:
In the C family of languages, if you divide an integer by another
integer, the compiler interprets the division operator (`/`) as an
_integer division_, i.e. you get the integer part of the quotient. Thus,

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

    (first_int + second_int + third_int) / 3

is an integer.

If either operand is a floating point number, then the other one is
implicitly converted to floating point, and you get a floating point
division. Thus

    (first_int + second_int + third_int) / 3.0

is a floating point number, and the result you expect.


body:
In languages such as C or C++ there is a distinction between integer types and floating-point types. You see, computers work using **bits**. A bit is either **0** or **1**. A bit obviously lack in both range and precision, so we combine multiple bits in order to improve.

# Integral Types

A **byte** is a group of 8 bits. In C, the type used is either

    uint8_t x; // Values from 0 to 255.
    int8_t  x; // Values from -128 to 127
    char    x; // Values from the ASCII character set (still -128 to 127)

On Ardiuno Uno, an **int** is a group of 16 bits:

    uint16_t c; // Values from 0 to 2^16-1 = 65535, synonym: unsigned int (Arduino)
    int16_t  c; // Values from -32768 to 32767,     synonym: int (Arduino)

A **long** is a group of 32 bits:

    uint32_t v; // Values from 0 to 2^32-1 = 4,294,967,295 = 4 GiB (unsigned long)
    int32_t  v; // Values from -2,147,483,648 to 2,147,483,647 (long)

There is also usually support for 64-bit numbers, but we try not to use them in Arduino code. The reason is that most Arduino MCUs use **8-bit** registers, so 64-bit operations such as "add", "sub", etc. would be very slow.

**Note**: Different architectures use different numbers of bits for these types. In order to be compatible with other architectures, use `int32_t` etc. to be sure.

## Literals and Casts

Oftentimes, the compiler can not see what type a literal value is supposed to be. In C, the compiler picks a default which is usually larger than you would like. For this reason, it is useful to know how to specify a literal exactly with the type:

     ((uint8_t)200)   // Casting 200 to an unsigned 8-bit integer
     ((char)65)       // Making the ASCII letter 'A'
     ((int32_t)42)    // Force 32 as a signed 32-bit integer (long)
     42L              // The 'L' suffix does the same as above

## Division and Remainder

A common cause of problems when programming in C is the division operator `/`. If the operands are both integer types, the result will also be an integer. So `1/3` is in fact `0`. You can get the remainder of the division using the modulus operation `%`. For instance:

    void show_division(int n, int d)
    {
        Serial.print("The division: ");
        Serial.print(n);
        Serial.print(" / ");
        Serial.print(d);
        Serial.print(" equals ");
        Serial.print(n / d);
        Serial.print(" with a remainder ");
        Serial.println(n % d);
    }

# Floating-point Types

All of the above types are integrals, so they do not support any fractional value. Therefore C defines **two** different floating-point types: **float** and **double**. The former is a 32-bit value and the latter is a 64-bit value. The way it works is that the bits are split in 3:

* A single bit is used for the **sign**.
* A certain number of bits represent the fractional part, the **mantissa**.
* The rest of the bits are used for the **exponent**.

As an example, the 32-bit float value representation for 1.25 is

    seeeeeee_emmmmmmm_mmmmmmmm_mmmmmmmm = s * 2^(e-127) * (1.m...)_2
    00111111_10100000_00000000_00000000 = (+1) * 2^(127-127) * (1.0100)_2
    // Note: Binary 1.01 equals 1.25 in decimal

## For performance, use the `f` suffix

Although 64-bit doubles are very accurate, the resulting code will run much slower. I, therefore, recommend using 32-bit floats instead. It is useful to know that you can tack on an `f` after the floating-point literal:

    (a + b + c) / 3.0f; // Make sure to divide using 32-bit operations.

If `a`, `b` and `c` above are integer types, the additions will also be integer additions. When the compiler sees an `int` divided by a `float`, it will convert the `int` to a `float`, and then perform a float division. This is slow, but certainly faster than a double division.

The compiler is smart, but it doesn't hurt to help it. There is only a very small precision loss in converting this to a float multiplication:

    (a + b + c) * (1.0f / 3.0f);

The compiler will pre-calculate `(1.0f / 3.0f)`, so you get a much faster floating-point multiplication (in addition to the `int` to `float` cast).

**Note**: Arduino Uno defaults all floating point literals to 32-bit, and `double` is the same as `float`. Therefore, the `f` suffix is strictly not needed. It is still good practice to add these for compatibility with other architectures.


message:
Arduino capacitive touch sensor help

So I have been messing around with the Arduino Capsense library with the immensely helpful guide; http://www.instructables.com/id/How-To-Use-Touch-Sensors-With-Arduino/  (many thanks to DangerousTim!)   using the code provided, i managed to get a relay to operate with a sensor.  It worked great and I was able to adjust the distance and sensitivity.  But when i tried adding another sensor and relay, it stopped working.  I've been trying to isolate the problem for a while now and have gotten nowhere.  I'm hoping someone can help me, here's the original code for the single sensor and relay;

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

    #include <CapacitiveSensor.h>
    #include <CapacitiveSensor.h> //change '42' to any desired pin...

    long time = 0;
    int state = HIGH;
    boolean yes;
    boolean previous = false;
    int debounce = 200;
    CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
    // To add more sensors...
    //CapacitiveSensor   cs_4_6 = CapacitiveSensor(4,6);        // 10M resistor       between pins 4 & 6, pin 6 is sensor pin, add a wire and or foil
    //CapacitiveSensor   cs_4_8 = CapacitiveSensor(4,8);        // 10M resistor  between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil

    void setup()
    {
        cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
        pinMode(13, OUTPUT);
    }

    void loop()
    {
        long total1 =  cs_4_2.capacitiveSensor(30);

        if (total1 > 60){yes = true;}
        else {yes = false;}

        // to toggle the state of state
        if(yes == true && previous  == false && millis() - time>debounce){
            if(state == LOW){
                state = HIGH; }
            else state = LOW;
            time = millis();
        }

        digitalWrite(13, state);
        previous = yes;
        delay(10);
    }

and here's the code for the two sensors and relays

    #include <CapacitiveSensor.h>

    int led = 13;
    int led2 = 12;
    long time = 0;
    int state = HIGH;
    long time2 = 0;
    int state2 = HIGH;
    boolean yes;
    boolean previous = false;
    boolean yes2;
    boolean previous2 = false;
    int debounce = 200;

    CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10M resistor  between pins 4 & 2, pin 2 is sensor pin, add a wire and or foil if desired
    CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

    void setup()
    {
        cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
        cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
        pinMode(led, OUTPUT);
        pinMode(led2, OUTPUT);
    }

    void loop()
    {
        int total1 =  cs_4_2.capacitiveSensor(30);
        Serial.println(total1);
        int total2 =  cs_5_7.capacitiveSensor(30);

        if (total1 > 60){yes = true;}
        else {yes = false;}
        if (total2 > 60){yes2 = true;}
        else {yes2 = false;}

        // to toggle the state of state
        if(yes == true && previous  == false && millis() - time>debounce){
            if(state == LOW){
                state = HIGH;
            }
            else
                state = LOW;
            time = millis();
        }

        if(yes2 == true && previous2  == false && millis() - time2>debounce){
            if(state2 == LOW){
                state2 = HIGH;
            }
            else
                state2 = LOW;
            time2 = millis();
        }

        digitalWrite(led, state);
        previous = yes;
        digitalWrite(led2, state2);
        previous2 = yes2;
        delay(10);
    }

body:
I think you are making a mistake initializing **cs_5_7**.

    CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
    CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

You are using same pin 4 for both Capacitive sensors. Try using different pins. I am quite sure that, this would help.


message:
Arduino Hardware serial library with rts/cts flow control support

Does there exist (any user developed etc.) version of the Hardware UART serial library that has support for RTS/CTS based flow control?
More interested in the Tx side (Arduino sends data, while the peripheral can back-pressure). The library should enable the Arduino to stop transmitting within 1 character of seeing a 'not ready' indication from the peripheral.

Thank you.

body:
I believe that CTS would be fairly easy to implement:

    void loop() {
      uint8_t clear_to_send = digitalRead(CTS);
      volatile char data;
      if (clear_to_send) {
        Serial.write(data);
      }
    }

I'm not sure about RTS.


body: I have I discovered that RTS/CTS may be implemented in genuine Arduinos, but is not supported by Arduinos that use the CH340 USB to serial chip. I found this when my JAVA program could talk with a genuine Uno ok, but didn't send any data to several Arduino compatibles that use the CH340 chip (but did receive from them). I had RTS/CTS set on the JAVA program. When I changed it to FLOWCONTROL_NONE it started working just fine.


body:
I am not aware of any such library. You could try to implement one
yourself, and maybe share it with the community. :-)

If you take this route, you will have to copy the file
[HardwareSerial.cpp from the Arduino core][HardwareSerial], make your
changes there, and have your version replace the one from the core. Here
are some ideas that may help to get you started:

- Wire the 'ready' signal from the device to an interrupt-capable pin of
  the Arduino.
- Inside the interrupt handler:
  - when 'ready' is deasserted, disable the UDRE interrupt by issuing
    `cbi(*_ucsrb, UDRIE0)`
  - when ready is asserted, enable it again, but only if the output
    buffer is not empty:
    `if (_tx_buffer_head != _tx_buffer_tail) sbi(*_ucsrb, UDRIE0);`
- Patch `HardwareSerial::write()` to enable the interrupt only if
  'ready' is asserted.
- Note that the UDRE IRQ can be explicitly called
  [by `HardwareSerial::flush()`][flush]
  and [by `HardwareSerial::write()`][write] if interrupts are globally
  disabled. You will have to condition this on the 'ready' signal.
- Note also that [`HardwareSerial::write()` can write directly to the
  UART][direct write] if the buffer is empty. This also has to be
  conditioned on the 'ready' signal.

[HardwareSerial]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/HardwareSerial.cpp
[flush]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/HardwareSerial.cpp#L219
[write]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/HardwareSerial.cpp#L262
[direct write]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/HardwareSerial.cpp#L242


message:
Arduino and 2 Adafruit Fingerprint modules working together

I want to do a project with fingerprint access control. But my client wants one on both sides of the door (inside and outside). Now I am using this product [Adafruit Fingerprint module][1] but I don't want to enroll each person on each fingerprint module. I want to look at enrolling each employee on 1 of these modules and then via arduino "SYNC" the fingerprint models between each other. Is this possible? Can someone maybe point me in the right direction or am I just insane HAHAHA. Look I can do the route of programming/enrolling each person on each module. But we life in a real world and at some point the fingerprint model/id's are not going to match up. And then there is going to come a problem with my online software. As well sorry for my bad lanuage  :)

  [1]: https://www.adafruit.com/products/751

body:
**Yes, you can easily do that**. This finger Print sensor works over Serial communication.

You can have multiple Serial devices connected to your Arduino UNO using [SoftwareSerial][1] library.

All you have to do is to create multiple instances of Adafruit_Fingerprint initialized with different SoftwareSerial objects. i.e.

    // pin #2 is IN from sensor1 (GREEN wire)
    // pin #3 is OUT from arduino to sensor1  (WHITE wire)
    // pin #8 is IN from sensor2 (GREEN wire)
    // pin #9 is OUT from arduino to sensor2  (WHITE wire)
    SoftwareSerial mySerial1(2, 3);
    Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);
    SoftwareSerial mySerial2(8, 9);
    Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&mySerial2);

Now, you can use **finger1** and **finger2** for your finger print operations. (previously referenced as only **finger**)

In order to understand Serial Communication with multiple serial devices, have a look at this [Arduino.cc Offical tutorial][2].

Hope it helps.

  [1]: https://www.arduino.cc/en/Reference/softwareSerial
  [2]: https://www.arduino.cc/en/Tutorial/TwoPortReceive


body:
You should get an Arduino Mega, if you arent using one already. You'll need the SRAM and Serial ports.

When I used this module, I didnt have enough time to experiment with it but here goes:

The **enroll** command for the FPM10 sensor takes an image of a fingerprint, processes it and finally creates a 512-byte model/template that is stored in flash memory with a unique ID (**PageID**) and used for future comparisons. However, it is also possible to read those templates from the flash memory with a few commands.
You have not said much about the role your web server plays here, so I'll assume its possible for you to store data easily and that its responsible for authorizing fingerprint enrollment and deletion. Since you have more than one sensor, a general solution to your problem would be:

 - The server must keep a record of available fingerprint IDs
 - When instructing the Arduino to begin enrollment, the server must also send along a fingerprint ID, based on its records of what ID is free. IDs may be assigned sequentially at first but templates may be deleted, leaving holes, hence the need for the server.
 - The Arduino `begin()`s the current sensor where the user is located and performs the normal enrollment. As soon as enrollment is done, the template that was just stored, should be loaded by the Arduino from the module's flash library and into one of its character file buffers using the **LoadChar** command. The only parameters for this command are the BufferID and the PageID.
 - Then the Arduino should download the template from the character file buffer into a 512-byte buffer that you will create in the Arduino SRAM. The command needed here is the **UpChar** command and its sole argument is the BufferID of the buffer to be read from. As soon as confirmation is received from the module, the sensor begins sending the 512-byte template in packets of 32 bytes (by default), each with a packet identifier of 0x02 until the last packet which has a package identifier of 0x08.
 - Then the Arduino `begin()`s the other sensor and sends the **DownChar** command to the module, which tells the sensor to expect a template to be stored in one of its character buffers (must be specified in the command). Once the Arduino receives confirmation, it should start sending the template to this sensor, using the same packet size and format that has been set for that sensor 9or the default I mentioned before if it hasnt been changed).
 - Finally, the Arduino sends the **Store** command to the sensor, to store the template in the buffer you just wrote to, into its flash library using the same fingerprint ID it was stored with in the first sensor.
 - The Arduino may then send confirmation to the Linux server, which then adds the fingerprint ID to the list of used IDs.

Now both sensors have identical fingerprint libraries and may be used to match fingerprints and get the same results. Deletion of fingerprints may also follow the same process: the server commands the Arduino to delete a print with a given ID and the Arduino sends the **DeleteChar** command to both sensors. All the commands I mentioned here are in the sensor's datasheet, which you must have downloaded along with the Adafruit library.

Use 57600 baud to communicate with the sensors, for reliable results. This is my [fork][1] of the Adafruit library with more functions available and without the buffer overflow issues. It should make the interfacing tasks a lot easier.

  [1]: https://github.com/brianrho/FPM


message:
Arduino Yun Python ImportError: No Module named mime.multipart

So, I have an Arduino Yun, and I'm trying to send an email with python. I have this code that I got from <https://github.com/amicojeko/YouCantTouchThis>

But when I try to call the file with `$python sendemail.py test.png`, it returns me an error:

    ImportError: No module named mime.multipart
I already tried to change to lowercase the imports, but it keeps showing the same error. The python version in the Arduino is 2.7. I've read something about module reorganization but even with the changes the error keep showing.
Here is the code:

    # coding=utf-8
    # Copyright (C) 2014  Stefano Guglielmetti

    # This program is free software: you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation, either version 3 of the License, or
    # (at your option) any later version.
    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    # GNU General Public License for more details.

    # You should have received a copy of the GNU General Public License
    # along with this program. If not, see <http://www.gnu.org/licenses/>.

    import smtplib, os, sys
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders

    #From address, to address, subject and message body
    from_address    = 'FROM_ADDRESS@EMAIL.COM'
    to_address      = ['YOUR_ADDRESS@EMAIL.COM']
    email_subject   = 'Alert!!! Zombies!!! Ahead!!!'
    email_body      = 'A non dead intruder has been detected and needs to be eliminated!'

    # Credentials (if needed)
    username = 'EMAIL_LOGIN'
    password = 'EMAIL_PASSWORD'

    # The actual mail send
    server = 'smtp.gmail.com:587'

    def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
        assert type(send_to)==list
        assert type(files)==list

        msg = MIMEMultipart()
        msg['From'] = send_from
        msg['To'] = COMMASPACE.join(send_to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject

        msg.attach( MIMEText(text) )

        for f in files:
            part = MIMEBase('application', "octet-stream")
            part.set_payload( open(f,"rb").read() )
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
            msg.attach(part)

        smtp = smtplib.SMTP(server)
        smtp.starttls()
        smtp.login(username,password)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()

    send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name

body:
`mime.multipart` isnt used in your code at all so you shouldn't be getting that error. The correct import statements for Python 2.7 are:

    from email.mime.multipart import MIMEMultipart
    from email.mime.base import MIMEBase
    from email.mime.text import MIMEText
    from email.utils import COMMASPACE, formatdate
    from email.encoders import Encoders

Study [these examples][1] in the Python 2.7 documentation.

  [1]: https://docs.python.org/2/library/email-examples.html


message:
Arduino: pins still active after entering sleep mode

I'm writing an Arduino sketch to control a display with my Arduino Nano. I have wired it up as explained [here][1], but used pin 3-7 instead of pin 2-6 listed in the example. The reason I did so is that I also added a push-button on interrupt 0 (= digital pin 2). I'm calling the sleep mode with a method, as explained in the section "Example" [here][2]. The Arduino seems to sleep, turning off all LEDs but the on/off one. The problem I have now is that the LCD display is sometimes still enabled (but only sometimes, not always). Why is it behaving like this? And how can I switch off everything possible to save as much energy as possible?

Here is my code piece:

    int buttonPin = 2;

    void setup()
    {
      pinMode(buttonPin , INPUT);
      digitalWrite(buttonPin , HIGH);
      ...
    }

    void loop() {
      ...
      if(counter == 100) {
        enterSleep();            // Enter sleep method!
      }
      delay(1000);
    }

    void enterSleep()
    {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      attachInterrupt(digitalPinToInterrupt(2), wakeUpNow, LOW);
      sleep_mode();

      /* The program will continue from here. */
      /* First thing to do is disable sleep. */
      sleep_disable();
      detachInterrupt(digitalPinToInterrupt(2));
    }

    void wakeUpNow() {
      // execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      // we don't really need to execute any special functions here, since we
      // just want the thing to wake up
    }

  [1]: http://engineeringlearning.blogspot.de/2013/10/interfacing-lcd-without-potentiometer.html
  [2]: http://playground.arduino.cc/Learning/arduinoSleepCode

body:
The problem is that you are not specifically doing anything to "turn off" the LCD (that is, switch off the back light - note that the LCD module will still be consuming power while you sleep).

When you sleep the MCU it does just that - it goes to sleep. Its clock stops ticking. Not a lot more than that really.  So if you are using PWM to control the backlight of the LCD, when the clock stops ticking the PWM will stop happening, and the I/O pin will remain stuck in whatever state it happened to be in at that moment - leaving you with random on or off at sleep time.

The solution? Manually turn off the backlight just before you sleep.

    digitalWrite(9, LOW);

To save more power you might want to consider adding a high-side switch to the power of the LCD module. With that you can physically disconnect the power to the LCD to stop it consuming any power at all during sleep mode. Of course, after re-enabling it you will need to fully reinitialize the module.

The same goes for any other external hardware that takes a power supply.

A high side switch can be built from a P-channel MOSFET being controlled by an N-channel MOSFET. There's plenty of examples on the web.


message:
How to use voltage divider between ESP8266 (3.3v) and IR proximity sensor (5V)?

I am a software developer and I don't know much about circuits so I need help.

I have an ESP8266 (esp-12) 3.3V and I'm planning to use it with an [IR proximity sensor][1] (runs between 4.5-5V). I have 2 AA batteries (3V total) and 4 AA (6V total) power supplies. Also, I have a bunch of 10K Ohm and 330 Ohm resistors.

How can I use a voltage divider to supply sufficient voltage to these components, based on what I have? If it would help, I have a 100uF capacitor and I use a [CP2102 to TTL Serial Converter to program][2]. Any help will be appreciated. Thank you in advance.

  [1]: https://www.sparkfun.com/products/242
  [2]: http://www.amazon.com/KEDSUM®-CP2102-Module-Download-Converter/dp/B009T2ZR6W?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o02_s00

body:
My experience with esp8266 tells me that if you power esp8266 with a 3.3V supply and you provide 5V/0V signal to its pins (either Tx/Rx or pin0,1) nothing's gonna happen. It will work fine.

Based on this experience, i would like to suggest you to

 1. power your esp8266 with 3.3V pin of your TTL converter
 2. power your IR sensor using 5V output pin of your TTL converter
 3. connect signal pin of IR sensor to your esp8266 digital pin. (just
    in case esp8266 heats up, disconnect circuit and try using voltage
    divided only for this particular connection.

If using those external power supplies don't forget to common GND (or -ive terminal) of those power supplies.


message:
Library LiquidCrystal_I2C don't work in other class (Composition)

Good afternoon, I'm trying to use a class to streamline the writing on the LCD. In this class I have an private attribute (it's a pointer, do not know how I call him) called  `LiquidCrystal_I2C* _lcd`, I instantiate it in the constructor, so far so good, but when I call the `_lcd-> begin (20, 4)` the code below is not executed, but no error is displayed.

Display.h:

    class Display{
        public:
            Display();
            ...
        private:
            LiquidCrystal_I2C* _lcd;
            ...
    }

Display.cpp:

    ...
    Display::Display() {
        _lcd = new LiquidCrystal_I2C(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
        _lcd->begin (20, 4);
    }
    ...

Program.ino

    #include "Display.h"

    Display lcd;

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

    void loop() {
        Serial.println("test");
        delay(3000);
    }

Just I noticed the error when I saw that `Serial.println ("test");` was not running. If I comment the `_lcd->begin (20, 4);` everything works.

I tested writing everything in Program.ino and worked, has nothing to do with connections or something, just do not apply the concept of composition with this class.

Can someone help me? And sorry for the English, i'm from Brazil. Thanks.

body:
# Most likely cause

You are hitting an insidious problem that even experienced C++ programmers frequently miss: order of initialization of global variables. In your case, `Display lcd` is initialized (*i.e.,* its constructor is called) before `main()` and subsequently `setup()` are executed. However, you almost certainly are `#include`ing whatever library is declaring the `LiquidCrystal_I2C` class, probably `Wire.h`, and so on. In many of these classes, a global variable of that type is also defined to make it easier to access stuff. For example, `Serial` (as in `Serial.println("foo")`) is really a global variable of the appropriate type of whatever serial implementation your particular core is using.

The problem you are hitting is that the C++ standard does **not** guarantee the execution order of the constructors of global variables. The order is an artifact of the compiler, the order in which object files were linked, and probably the phase of the moon :)

What is (almost certainly) happening is that the constructor for your `class Display` is being called, which initializes the LCD and the i2c bus, and then something else calls either the LCD constructor or the i2c constructor and messes things up.

OK, "how do I fix this?" I hear you ask. Simple: make the global lcd variable a *pointer*, and allocate the instance in `begin()`, like so:

    #include "Display.h"

    Display *lcd;

    void setup() {
      Serial.begin(9600);
      lcd = new Display();
      // stuff
    }

    void loop() {
      // more stuff
      lcd->some_method(some_argument);
      // even more stuff
    }

Now you are guaranteed that your code will be the last to touch any initialization code that might affect the display or the bus. Just keep accessing the `class Display` methods through the pointer.

# A less likely cause

It is still possible that your constructors are getting executed in the right order, but your hardware does not like being initialized twice (but test that anyway!), so you may have to figure out how to reset the hardware so you can initialize it again. If I understand your posting correctly, the loop never runs, which means that a second initialization probably either causes a exception (which you would not see unless you had some kind of additional debugging channel; in the case of the ESP8266, for example, that would be the output-only `Serial1` port, and even then, you'd have to explicitly turn on debugging. Each core has its own debugging stuff, I forget what the real Arduino does.)

Hope this helps.

/ji


message:
Arduino IDE installation Problems

When installing the IDE there are many "Unable to open *.DLL", errors. I check "ignore errors" and the IDE installed. Now when selecting the correct port and  board the blink sketch is uploaded and several ATK 500 errors result. I have uninstalled and reinstalled the IDE several time, with repeated results.

body: You should check to make sure that your Java installation is up to date. It would also be best to make sure that you're bit types between the Java environment and the Arduino IDE are the same(32bit with 32bit, 64bit with 64bit). If this does not work, you should post your actual errors so we can help more :)


message:
Having 3 buttons with only 2 input pins

for the purpose of learning, I'm trying to have a kind of digital/binary input where I'm using 3 buttons but only 2 input pins.

I thought of

    01 = Button 1
    10 = Button 2
    11 = Button 3

My **first attempt** was like this:
[![first attempt][1]][1]
I left the resistors out right now. The problem here is of course, that it doesn't matter what button I press, both LEDs are lighting up.

I used 2 Diodes in my **second attempt**:
[![second attempt][2]][2]
This time, S1 and S2 work as expected, but S3 brings only one LED up.

Now I was wondering how I can wire things up correctly, using as little components as possible and having in mind, that I'm going to use an Arduino instead of the LEDs.

Thank you for any help!

  [1]: https://i.stack.imgur.com/Z9bpj.png
  [2]: https://i.stack.imgur.com/Eu42f.png

body:
The logic of your second attempt is perfectly correct.

If you put resistors in series with the LEDs you may get more joy out of it. Having two LEDs in parallel without resistors often results in one LED lighting and the other not.

[![enter image description here][1]][1]

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


message:
How to get neopixel to fade colorwipe?

I'm trying to get a fade to happen when an LED turns on/off during the color wipe rather than just abruptly turning on/off. I'm not quite sure how to do this though.

    #include <Adafruit_NeoPixel.h>

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, 3, NEO_RGBW + NEO_KHZ800);
    void setup() {
      strip.begin();
    }

    void loop() {
      colorWipe(strip.Color(255, 255, 255), 150); // Red
     colorWipe(strip.Color(0, 0, 0), 150); // Red
     delay(5000);
    }

    void colorWipe(uint32_t color, uint8_t wait) {
      for(uint16_t i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, color);
          strip.show();
          delay(1000);
      }
    }

body:
You could change the intensity of each colour in steps till you get to your target colour.

    void colorFade(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) {
      for(uint16_t i = 0; i < strip.numPixels(); i++) {
          uint8_t curr_r, curr_g, curr_b;
          uint32_t curr_col = strip.getPixelColor(i); // get the current colour
          curr_b = curr_col & 0xFF; curr_g = (curr_col >> 8) & 0xFF; curr_r = (curr_col >> 16) & 0xFF;  // separate into RGB components

          while ((curr_r != r) || (curr_g != g) || (curr_b != b)){  // while the curr color is not yet the target color
            if (curr_r < r) curr_r++; else if (curr_r > r) curr_r--;  // increment or decrement the old color values
            if (curr_g < g) curr_g++; else if (curr_g > g) curr_g--;
            if (curr_b < b) curr_b++; else if (curr_b > b) curr_b--;
            strip.setPixelColor(i, curr_r, curr_g, curr_b);  // set the color
            strip.show();
            // delay(wait);  // add a delay if its too fast
          }
          delay(1000);
      }
    }

To use it:

    void loop() {
      colorFade(255, 0, 0, 150); // fade into red
      colorFade(255, 255, 255, 150); // and then into white
      delay(5000);
    }

This is untested, so I dont know if it will be too fast or too slow. You'll have to tweak it to your needs.


message:
Dealing with TCCRx

I am totally beginner in Arduino, and i want to ask some questions :

        TCCR1B = (TCCR1B & ~(0x07<<CS10)) | (2<<CS10);

What does the previous line mean? with good explaination please .

        TCCR1A &= ~(3<<COM1A0);

for the previous line , is there difference if i wrote '1' instead of '3' ? why ?

body:
 On the first line, you clear some bits, then set some bits in the same “region” of the byte.

From inside out, get 7 (which is 3 bits of ones: 00000111), shift it upwards (the << operation) by CS10 amount (we don’t know how much, but the compiler does), complement all that (the tilde ~ character) and bitwise ‘and’ it with the value of the TCCR1A register (the & operation). Next, take a 2 (binary 00000010), shift it up by CS10 bits again (<< CS10), and bitwise ‘or’ that bit pattern with the earlier result (the | operator). Finally, assign all that to TCCR1A.

For the second line, yes, changing 3 to 1 will certainly change what happens to TCCR1A. It makes a different bit pattern, and I'm sure you can reason it out after reading the previous explanation.


message:
SDS011 Dust Sensor Checksum Error

I'm working with an SDS011 particular sensor through its serial interface. The spec sheet (http://inovafitness.com/upload/file/20150311/14261262164716.pdf) indicates that the second to last byte of a serial packet is a checksum equal to sum of all the data bytes.

I am using pyserial to read and interpret the serial data. Here's a snippet of the code:

    import serial

    def read_sensor(port):
        while True:
            header = port.read(2)
            if header == b'\xAA\xC0':
                data = port.read(6)
                checksum = port.read()
                tail = port.read()
                if tail == b'\xAB':
                    return header + data + checksum + tail

    port = serial.Serial(port=MY_PORT)
    packet = read_sensor(port)
    data_sum = sum(packet[2:8])
    checksum = packet[8]

    if data_sum == checksum:
      print('Ok')
    else:
       print('Error')

However, I haven't got a single packet whose checksum hasn't been an error. Is there anything I could be potentially doing wrong?

body:
Generally, a checksum byte is computed using 8-bit arithmetic, with overflow ignored.

The Python sum function uses arithmetic of indefinite precision (eg, 32- or 64-bit words for small values, with additional words for larger numbers).

Try comparing `checksum` to `data_sum % 256`.  If that doesn't fix the problem, print out some of the data packets and checksum values so that you can use a calculator to test different combinations.


body:
I assume `MY_PORT` stands for `COMxx`. Since you set no timeout, it means `port.read()` will block till it gets the number of bytes requested. I suggest you add a `print()` to display the bytes returned, if any.

To get the sum, use `data_sum = sum(packet[2:8]) & 0xff` to ensure you only get a byte. Also add `port.reset_input_buffer()` right before you call `read_sensor()`, to flush the input buffer.

It would also be a good idea to take at least 3 consecutive readings from the sensor in case of any errors in the first reading right after opening the port. Dont forget to add a `port.close()` at the end of your code.


message:
FlySky TH9X with Arduino: cant get pulseIn() function to return sensible values for any channel

So I've got a FlySky TH9X and I'm trying to read some pulses using an Arduino Uno.

I'm just starting out so I want to get the hang of using the pulseIn function before moving onto interrupts. My problem is that, when I wire everything up, I don't get sensible values. Furthermore, they don't change even though I move around the sticks on the actual remote.

I tried to start off simple by wiring just the channel 1 of the receiver to pin 3 of the Uno. Then I used this code:

    int ch1;

    void setup() {
      pinMode(3, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      ch1 = pulseIn(3, HIGH, 25000);
      Serial.print("Channel 1: ");
      Serial.println(ch1);
      delay(100);
    }
The serial monitor then spits out numbers ranging from 0 up to 10000+ in a very erratic and apparently not periodic nature. I'll copy a few lines here:

    Channel 1: 9989
    Channel 1: 10063
    Channel 1: 10068
    Channel 1: 274
    Channel 1: 0
    Channel 1: 10085
    Channel 1: 10039
    Channel 1: 10336
    Channel 1: 9629
    Channel 1: 9959
    Channel 1: 10064
    Channel 1: 10088
    Channel 1: 378
    Channel 1: 0
    Channel 1: 10044
    Channel 1: 10059
    Channel 1: 10424
    Channel 1: 9632
    Channel 1: 9867
    Channel 1: 10069
    Channel 1: 10067
    Channel 1: 10473
    Channel 1: 10037
    Channel 1: 10063
    Channel 1: 10063
    Channel 1: 10253
    Channel 1: 9677
    Channel 1: 10013
    Channel 1: 10064
    Channel 1: 10062
    Channel 1: 13

As you can see: not only are the higher-end values a whole order of magnitude too big (i thought pulses are normally between 1000 - 2000us?), but the actual range that these numbers span is far, far too wide for me to do anything with. Also, the sticks on my remote seem to have no influence on the numbers.

Can someone please help me? thank you :)

Hassan

body:
I would not recommend using `pulseIn` for reading values from the receiver.  `pulseIn` blocks the program until a signal is received, which is almost always undesirable.

An alternative approach would be to use CHANGE interrupts.  You get an interrupt when the signal goes high and low.  You take note of the time that each change occurs with `millis` and compare the times to get the duration of the signal.

Here's an example - you can add more channels if you'd like.  Note, this is using the [EnableInterrupt][1] library.

    #include <EnableInterrupt.h>

    #define SERIAL_PORT_SPEED 57600
    #define RC_NUM_CHANNELS  2

    #define RC_CH1  0
    #define RC_CH2  1
    #define RC_CH1_INPUT  A0
    #define RC_CH2_INPUT  A1

    uint32_t last_update_time = 0;
    uint16_t rc_values[RC_NUM_CHANNELS];
    uint32_t rc_start[RC_NUM_CHANNELS];
    volatile uint16_t rc_shared[RC_NUM_CHANNELS];

    void rc_read_values() {
      // read the values out of the shared, volatile array (which can change at any time)
      // and into an array that we only will only change when we call this function

      noInterrupts();
      memcpy(rc_values, (const void *)rc_shared, sizeof(rc_shared));
      interrupts();
    }

    void calc_input(uint8_t channel, uint8_t input_pin) {
      // This is the interrupt.  If the pin is high, we record the start
      // time of the pulse.  If the pin is low, we compare the start time
      // to the current time in order to get the length of the pulse.

      if (digitalRead(input_pin) == HIGH) {
        rc_start[channel] = micros();
      } else {
        uint16_t rc_compare = (uint16_t)(micros() - rc_start[channel]);
        rc_shared[channel] = rc_compare;
      }
    }

    void calc_ch1() { calc_input(RC_CH1, RC_CH1_INPUT); }
    void calc_ch2() { calc_input(RC_CH2, RC_CH2_INPUT); }

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

      pinMode(RC_CH1_INPUT, INPUT);
      pinMode(RC_CH2_INPUT, INPUT);

      // set up CHANGE interrupts, so that we get notified when
      // each signal goes high or low.
      enableInterrupt(RC_CH1_INPUT, calc_ch1, CHANGE);
      enableInterrupt(RC_CH2_INPUT, calc_ch2, CHANGE);
    }

    void loop() {
      rc_read_values();

      Serial.print("CH1:"); Serial.println(rc_values[RC_CH1]);
      Serial.print("CH2:"); Serial.println(rc_values[RC_CH2]);

      delay(200);  // just so serial log doesn't flood
    }

For a more detailed explanation, take a look here:  http://rcarduino.blogspot.com/2012/01/how-to-read-rc-receiver-with.html

  [1]: https://github.com/GreyGnome/EnableInterrupt


body:
Use a bigger timeout (30000):

    int rcPin1 = 3; // PWM signal arduino pin
    int rcPin2 = 4; // PWM signal arduino pin
    int rcPin3 = 5; // PWM signal arduino pin
    int rcPin4 = 6; // PWM signal arduino pin
    int rcPin5 = 7; // PWM signal arduino pin
    int rcPin6 = 8; // PWM signal arduino pin
    int ch1 = 0;    // Receiver channel 1 pwm value
    int ch2 = 0;    // Receiver channel 1 pwm value
    int ch3 = 0;    // Receiver channel 1 pwm value
    int ch4 = 0;    // Receiver channel 1 pwm value
    int ch5 = 0;    // Receiver channel 1 pwm value
    int ch6 = 0;    // Receiver channel 1 pwm value
    void setup() {
      pinMode(rcPin1, INPUT);
      pinMode(rcPin2, INPUT);
      pinMode(rcPin3, INPUT);
      pinMode(rcPin4, INPUT);
      pinMode(rcPin5, INPUT);
      pinMode(rcPin6, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      // Read in the length of the signal in microseconds
      ch1 = pulseIn(rcPin1, HIGH, 30000);
      Serial.print("Channel #1: ");
      Serial.println(ch1);
      ch2 = pulseIn(rcPin2, HIGH, 30000);
      Serial.print("Channel #2: ");
      Serial.println(ch2);
      ch3 = pulseIn(rcPin3, HIGH, 30000);
      Serial.print("Channel #3: ");
      Serial.println(ch3);
      ch4 = pulseIn(rcPin4, HIGH, 30000);
      Serial.print("Channel #4: ");
      Serial.println(ch4);
     ch5 = pulseIn(rcPin5, HIGH, 30000);
      Serial.print("Channel #5: ");
      Serial.println(ch5);
      ch6 = pulseIn(rcPin6, HIGH, 30000);
      Serial.print("Channel #6: ");
      Serial.println(ch6);
     delay(1000);
    }


message:
Does upload using `ICSP`overwrite the bootloader?

If I compile a sketch then upload using `ICSP` does it overwrite the bootloader?

I am using Arduino program and `Arduino Uno` as `ICSP`.

body:
Yes.
When you program using ISP you overwrite everything in the chips flash, even the bootloader.

This has some pro's and con's:

 - Pro: The program starts immediately, meaning it doesn't wait to check if there's any programming coming in before starting your sketch.
 - Con: You need to use ISP to program your Arduino again or to upload the bootloader again.

Normally there is not really any reason for not having the bootloader present but if you are programming bare Atmel chips without a serial interface this way might be preferable.


body:
Yes, it will overwrite the bootloader.

In addition to [Hans Neve's][1] list of Pros, it has the added benefit of gaining you a couple hundred bytes (0.5KB) that is otherwise used by the bootloader.

  [1]: https://arduino.stackexchange.com/a/23188/19409


message:
Arduino Uno Multiple Modules

I have an Arduino Uno and I want to connect;

 - RFID Reader (*RC522*)
 - WiFi Module (*ESP8266 ESP-01*)
 - SD Card Module
 - RTC (*Real Time Clock - DS1307*)

Same time but pinouts are not enough. Is there a way to doing this with Uno or I have to buy an Arduino Mega ? I saw "*Expansion Sensor Shield*"s but I do not know what is the logic of using this ?

Regards

body:
Let's see which device uses which communication protocol:

 1. **WiFi Module (ESP8266 ESP-01)** uses Serial communication.
 2. **RTC (Real Time Clock - DS1307)** uses I²C communication.
 3. **RFID Reader (RC522)** uses SPI communication.
 4. **SD Card Module** also uses SPI communication.

Now, the Arduino UNO supports **One I²C**, **One SPI** and **One Serial** (by default) communication port.

So, you can easily connect your **Wifi** and **RTC** modules.

Now, actual problem is: "[How to access multiple SPI interfaces on Arduino][1]" (and that is a solved problem).

Hope it helps and you don't have to buy an **Arduino MEGA**.

  [1]: https://arduino.stackexchange.com/questions/8425/how-to-access-multiple-spi-interfaces-on-arduino


message:
Using ESP8266 core for Arduino

I am working on a wireless sensor network project, in which data is collected at a central node using nRF24 modules and the `RFNetwork.h` library.

I want to post that to the internet using the famous ESP8266 module, which works fine when used as standalone and programmed with Arduino IDE. But the problem is how to transfer my data from Arduino to the ESP8266 as it only has one serial that is already used to program it?

I have tried to use a nRF24 module that uses SPI with an ESP-12 as it has an SPI header, but it didn't work out and I can't figure out the problem. Is there a way to use ESP core libraries like `esp8266wifi.h`, `wifiClient.h`, `webserver.h` etc., just like we can use the `esp8266.h` library that uses AT commands to communicate to ESP from an Arduino like in a master-slave manner?

body:
Several solutions:

1. Are your SPI components 5V or 3.3V parts? The ESP8266 is 3.3V only, and is NOT 5V-tolerant; you may have already fried it.

2. In most cases that I've had problems with SPI with the ESP8266 (in particular, the Adafruit 8266-12E HUZZAH board), they went away when I drastically lowered the SPI speed to 8000000.

3. Once you've programmed the 8266, and assuming you don't use `Serial` for debugging output, it's free to use to communicate with the world. Again, be careful about signal levels -- the 8266 is NOT 5V-tolerant, and most arduinos have 5V signals. So either use a 3.3V arduino-like part (my favorite is the Teensy 3.2 for larger projects, and the Adafruit Trinket for smaller ones), or use a level converter. If you need debugging output, you can still use `Serial1` for output only (and don't forget to change its bit rate -- by default it's something crazy like 74380bps).

4. Run the 8266 as another SPI slave and have the Arduino write to it. Or come up with your own serial protocol! Again, careful about signal levels.

5. You can use a different version of the 8266 (or another wifi chip), one that's already meant to be used with the Arduino. Sparkfun and Adafruit have several, as do a lot of other vendors.

I'd still suggest that you try to work out the SPI problems and stick to the 8266.

Also, don't forget that neither serial nor SPI guarantees data integrity. Always use a CRC to make sure your data were transferred correctly, and have some provision for retransmissions if you can't afford to just ignore corrupted data.

/ji


body:
(It sounds like you have already used the esp8266 so I hope this background isn't too simple, but I'm not sure from your question where you're stuck.)

The ESP8266 modules are programmable. They are (usually) delivered with an application program installed that uses the manufacturer-defined set of "AT<something>" commands to operate it as a WiFi station or access point. There are code libraries for Arduinos or other computers to set it up and use it that way.

You can use its one serial port for either job - communicating to its current application program (interpreter, or your own custom program), much as you do an Arduino's port.

You can program your entire application on the chip and operate its WiFi radios directly, just as the AT-command interpreter does. You'll need the specs for programming the radios though; the AT-interpreter does that for you. Once you've loaded an application program of your own, it replaces the interpreter. To put it back to as-delivered, with the AT-command interpreter running in it, you'll need to re-upload the interpreter (which of course will replace anything else you've loaded).


body:
Seems like you have several options:

1. Find a nRF24 library that works on ESP with the "arduino core" or port one yourself.

2. Implement your own Arduino-to-ESP protocol, using Serial (SoftwareSerial if needed), I2C or whatever.

3. Flash the ESP with the standard AT commands firmware and command it from the Arduino.

IMO, option 1 is best (you would ditch the Arduino completely), but may require significant effort.

Option 2 is academically better than option 3, as it will skip the hassle of dealing with AT commands on the Arduino side and will eventually be more efficient in terms of data bandwith between the Arduino and the ESP. In practice, it probably won't matter.

Option 3 might be the easiest - as much as I dislike the AT commands, they work and you won't have to program two devices constantly while developing your code.

So, in short, if you can go with Option 1 - please do so :)

If not - quickly asses which one will be easier / better for you - option 2 or option 3 and just go with it. Both will work, and are relatively easy to achieve.


body:
> ...but the problem is how to transfer my data from Arduino to the
> ESP8266 as it only has one serial that is already used to program it.

1. After you flash a new firmware serial port becomes free so you can use it for whatever you like.
2. ESP8266 has two serial ports, not only one (although you can use only TX pin from the second one as RX is connected to SPI bus of the flash).
3. You can use any free GPIOs for software serial communication.

You can find the details about ESP8266's serial porth [here][1], [here][2], [here][3] and [here][4].

  [1]: https://github.com/esp8266/Arduino/blob/master/doc/reference.md#serial
  [2]: http://bbs.espressif.com/viewtopic.php?t=122
  [3]: http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations#uart_pins
  [4]: http://www.esp8266.com/viewtopic.php?f=13&t=476


message:
How is it possible that my skin temperature is so constant?

[![About 30 minutes of data][1]][1]

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

Here's the code

    #include <OneWire.h>

    int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
    unsigned long startTime = 0;
    #define MEASURE_PERIOD 250
    //Temperature chip i/o
    OneWire ds(DS18S20_Pin);  // on digital pin 3

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

    void loop() {
      if((millis() - startTime) >= MEASURE_PERIOD)
        {
            startTime += MEASURE_PERIOD;
            float temperature = getTemp();
            Serial.println(temperature);
        } //just here to slow down the output so it is easier to read

    }

    float getTemp(){
      //returns the temperature from one DS18S20 in DEG Celsius

      byte data[12];
      byte addr[8];

      if ( !ds.search(addr)) {
          //no more sensors on chain, reset search
          ds.reset_search();
          return -1000;
      }

      if ( OneWire::crc8( addr, 7) != addr[7]) {
          Serial.println("CRC is not valid!");
          return -1000;
      }

      if ( addr[0] != 0x10 && addr[0] != 0x28) {
          Serial.print("Device is not recognized");
          return -1000;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44,1); // start conversion, with parasite power on at the end

      byte present = ds.reset();
      ds.select(addr);
      ds.write(0xBE); // Read Scratchpad

      for (int i = 0; i < 9; i++) { // we need 9 bytes
        data[i] = ds.read();
      }

      ds.reset_search();

      //byte MSB = data[1];
     // byte LSB = data[0];

      float tempRead = ((((int)data[1]) << 8) | data[0]); //using two's compliment
      float TemperatureSum = tempRead / 16;

      return TemperatureSum;

    }

body:
Try using [Dallas Temperature Control Library for DS18S20][1]. ([Click Here][2], Download Library). Its simple and easy to use, and it comes with examples.

[Here][3] is tutorial.

Hope it helps.

  [1]: https://github.com/milesburton/Arduino-Temperature-Control-Library
  [2]: https://github.com/milesburton/Arduino-Temperature-Control-Library/archive/master.zip
  [3]: http://www.milesburton.com/?title=Dallas_Temperature_Control_Library


body:
Examine your code closely.  It appears that you are partially implementing extended resolution calculations in this line of code:

      float TemperatureSum = tempRead / 16;

In the [DS18S20 specifications][1] the extended resolution equation used is:

     TEMPERATURE = TEMP_READ * 0.25 - ((COUNT_PER_C - COUNT_REMAIN) / (COUNT_PER_C))

Where COUNT_PER_C is a DS18S20 register containing a value of up to 16.  Maybe that is where 16 originated?

I believe what you want to do is divide the recovered value by 2.0 base on table 1 from the DS18S20 specifications:

      float TemperatureSum = tempRead / 2.0;

Don't forget the "." in case the compiler you are using decides to do integer math dripping the "float" part before assigning it to TemperatureSum.

  [1]: https://datasheets.maximintegrated.com/en/ds/DS18S20.pdf


message:
Connecting a motor to Arduino UNO Play breadboard

I am new to Arduino and have a small query. I am building a simple system that switches on a motor and switches it off after some time and repeats this in a loop.

The Arduino that I am using is a “[DIY UNO Play Breadboard -ATMEGA328P with FT232 Breakout Board](http://www.ebay.in/itm/DIY-UNO-Play-Breadboard-ATMEGA328P-with-FT232-Breakout-Board-/301262281895?hash=item4624a19ca7:g:ox0AAOSwnDZT2Lox')” (Rs. 825, or $12.38USD, from Mangalore).  The Arduino board is similar in size to a Nano but without USB.  The FT232 board has a USB B port on one end and serial pins on the other.
[![picture of boards and cable][1]][1]
My query is whether I should connect the positive end of battery supply to the motor and then connect in series using a motor controller circuit to port 7 and connect the negative terminal to the gnd port.

Or do I need a separate voltage source for my Arduino, because this Arduino has no built in USB ports.

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

This is my code to switch on and switch off the motor:

`  int motorPin = 7;
   pinmode(motorPin,OUTPUT);
   digitalWrite(motorPin,HIGH); //turn motor on
   delay(500); //wait
   digitalWrite(motorPin,LOW); //turn motor off
   delay(500); //wait`

body:
Using same Voltage supply to power Arduino Board and motor simultaneously is usually not a good practice.

So, what you can do is use separate batteries to power Arduino and motor as shown in image below
[![enter image description here][1]][1]
However you can also power arduino and motor from single power supply, but in this case you should first think of current ratting of your battery and current consumption of your Arduino (normally 500mA) and motor. As shown below,
[![enter image description here][2]][2]
Hope it help. Any question Comment below.

  [1]: https://i.stack.imgur.com/o3rDU.jpg
  [2]: https://i.stack.imgur.com/EKHSg.jpg


body: You can use the same power supply for both if it can source enough current for both; USB ports usually can not. But what you must not do is try to supply motor current through the Arduino, from any power supply. You need the Arduino to control a transistor switch which manages the motor current.


message:
How to make Arduino to stop updating i2c data when meet a condition and wait until it receives another serial input from processing?

I am currently making a robot with Arduino Uno, D6T omron thermal sensor (i2c sensor) and some other sensors. My thermal sensor will always update the data in array form. It will display 4 data arrays every 1 second.

I wish to have my Arduino send out a string "found" over serial when it meet a condition, and thermal sensor will stop updating my data. Thermal sensor and Arduino will just have to wait until the user sends a selection, jump to the selected function, and thermal sensor will start updating data again after that. I am new to coding, any suggestion on how to make my arduino and sensor to wait? Thank you guys! =)

Attached below is my code. (Arduino Sketch):

    #include <Wire.h>
    #include <WireExt.h>

    #define D6T_addr 0x0A
    #define D6T_cmd 0x4C

    int rbuf[35];
    float tdata[16];
    float t_PTAT;

    const int S_DATATRANSFER = 0;
    const int S_WAIT = 1;
    const int S_STOPTRANSFER = 2;
    const int S_CONFIRMATION = 3;
    const int S_ALLSTOP = 4;

    float left_sum, right_sum, center_sum;

    //-----------------------------------------------------------------------------

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

    }

    void loop()
    {

    static int state = S_DATATRANSFER;

     switch(state)
     {

     case S_DATATRANSFER:
      //Calculate temp
      //serialprint temp
      int i;

      if (Serial.available() > 0)
      {
                          char inByte = Serial.read();
                          if (inByte == '1')
       {  //processing will send one byte to arduino if ready

        Wire.beginTransmission(D6T_addr);
        Wire.write(D6T_cmd);
        Wire.endTransmission();

       if (WireExt.beginReception(D6T_addr) >= 0)
        {
         i = 0;
         for (i = 0; i < 35; i++)
         {
          rbuf[i] = WireExt.get_byte();
         }
         WireExt.endReception();

         t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
         for (i = 0; i < 16; i++)
         {
          tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
         }
        }

        right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
        left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
        center_sum= tdata[5] + tdata[6] + tdata[9] + tdata[10];
        output_csv();

             }
                          }
      state = S_WAIT;
      break;

     case S_WAIT:
      if (center_sum > 35*4)
      {
      state = S_STOPTRANSFER;
      }
      else
      {
      state = S_DATATRANSFER;
      }
      break;

     case S_STOPTRANSFER:

      Serial.println("F");
                    delay(300);

      state = S_CONFIRMATION;

      break;

     case S_CONFIRMATION:
      while (Serial.available())
      {
       char val = Serial.read();
       if (val == '2')
       {
        state = S_ALLSTOP;
       }
       else if (val == '3')
       {
        state = S_DATATRANSFER;
              }
                            else if (val == '1')
                            {
                                    state = S_DATATRANSFER;
                            }
                    }

      break;

            case S_ALLSTOP:

            break;

     }
    }

    void output_csv()
    {
      for (int i = 0; i < 16; i++)
      {
        Serial.print(tdata[i]);
        if (i < 15)
     {
          Serial.print(",");
        }
        else
     {
          Serial.println();
        }
      }
    }

Attached below is my code in processing:

    import processing.serial.*;
    import controlP5.*;
    import javax.swing.JOptionPane.*;
    import com.onlylemi.processing.android.capture.*;
    ControlP5 cp5;
    javax.swing.JOptionPane JOptionPane;

    AndroidCamera ac;
    PImage img;
    Textlabel myTextlabelA, myTextlabelB;
    boolean canStart = true;
    boolean canInput = false;
    boolean Start = false;
    boolean Start_camera = false;
    String typedText = "Comments: ";
    PFont font;
    String command = "";
    String confirm;
    String found;

    PImage carImage;
    float[] tdata = new float[17];
    float tptat; // PTAT
    String portName;
    //int serialport = 0;

    String buf;
    float colourGreen; //change green in relation to temperature

    int lbTemp = 25; //lowest relative temperature
    int hbTemp = 35; //highest relative temperature
    Serial myPort;  // Create object from Serial class

    void setup() {
      size(1366,768);
      //background(#FFFFFF);
      background(ControlP5.BLACK);
      //println(Serial.list());
      //portName = Serial.list()[serialport];
      myPort = new Serial(this, "COM15", 9600);
      myPort.clear();
      cp5 = new ControlP5(this);
      ac = new AndroidCamera(720, 480, 30);
      ac.start();

      myTextlabelA = cp5.addTextlabel("label")
                        .setText("GUI of Alive Human Detection System.")
                        .setPosition(120,10)
                        .setColorValue(#FFFAF0)
                        .setFont(createFont("Georgia",20))
                        ;

      cp5.addButton("Start")
         .setPosition(115, 670)
         .setSize(100,30)
         ;

      cp5.addButton("Stop")
         .setPosition(375, 670)
         .setSize(100,30)
         ;
      cp5.addButton("Start Camera")
         .setPosition(799, 670)
         .setSize(100,30)
         ;
    }

    public void Start(int theValue) {
      println("Initialising...");
      println("Connected.");
      //start displaying
     // carImage = loadImage(".png");
      Start = !Start;
    }

    public void Stop(int theValue) {
      println("Shuting Down...");
      //finish = loadImage("robot.png");
      //image(finish,30,64);
      myPort.write(0x02);
      Start = !Start;
      //strokeWeight(0);
    }

    public void Start_camera(int theValue) {
      println("Initialising...");
      println("Connected.");
      //start displaying
     // carImage = loadImage(".png");
      Start_camera = !Start_camera;
    }

    void draw()
    {
      //if (Start_camera){
      //img = ac.getCameraImage();
      //image(img, 610, 0);
      //}
      if (Start){

        myPort.write('1');
        delay(100);
        while (myPort.available() > 0) {
        delay(300);
        buf = myPort.readStringUntil('\n');
        if (buf.equals("F")){
        int dialogResult = JOptionPane.showConfirmDialog (null, "Human found? Please Confirm!!", "Alert!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if(dialogResult == JOptionPane.YES_OPTION)
        {
        fill(255,0,0);
        rect(100,670,50,30);
        myPort.write('2');
        }
        else if(dialogResult == JOptionPane.NO_OPTION)
        {
        fill(0,255,0);
        rect(100,670,50,30);
        myPort.write('3');
        }
        }
        else{
        myPort.clear();
        tdata = float(split(buf, ','));
        for (int i = 0; i <16; i++) {
        colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
        fill (255,colourGreen,0);

          if (i == 0)
        { rect(450,64,150,150);}
          else if (i == 1)
        { rect(300,64,150,150);}
          else if (i == 2)
        { rect(150,64,150,150);}
          else if (i == 3)
        { rect(0,64,150,150);}
          else if (i == 4)
        { rect(450,214,150,150);}
          else if (i == 5)
        { rect(300,214,150,150);}
          else if (i == 6)
        { rect(150,214,150,150);}
          else if (i == 7)
        { rect(0,214,150,150);}
          else if (i == 8)
        { rect(450,364,150,150);}
          else if (i == 9)
        { rect(300,364,150,150);}
          else if (i == 10)
        { rect(150,364,150,150);}
          else if (i == 11)
        { rect(0,364,150,150);}
          else if (i == 12)
        { rect(450,514,150,150);}
          else if (i == 13)
        { rect(300,514,150,150);}
          else if (i == 14)
        { rect(150,514,150,150);}
          else if (i == 15)
        { rect(0,514,150,150); }

        if (tdata[i]<5) {fill(255);} else {fill(0);}
          if (i ==0)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]),525, 139);}
          else if (i == 1)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]),375, 139);
          }
          else if (i == 2)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 225, 139);
          }
          else if (i == 3)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]),75, 139);
          }
          else if (i == 4)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 525, 289);
          }
          else if (i == 5)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 375, 289);
          }
          else if (i == 6)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 225, 289);
          }
          else if (i == 7)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 75, 289);
          }
          else if (i == 8)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 525, 439);
          }
          else if (i == 9)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 375, 439);
          }
          else if (i == 10)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 225, 439);
          }
          else if (i == 11)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 75, 439);
          }
          else if (i == 12)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 525, 592);
          }
          else if (i == 13)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 375, 592);
          }
          else if (i == 14)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 225, 592);
          }
          else if (i == 15)
          {
          textAlign(CENTER, CENTER);
          textSize(20);
          text(str(tdata[i]), 75, 592);
          }
        }
        delay(350);
      }
        }
        }
    }

body:
Implement a state machine first in your code for each state:

1) Sending i2c data.

2) Not sending i2c data.

And identify the conditions necessary to switch states:

1 to 2 when condition meet.

2 to 1 when command received.

Then drop your code into the state machine's code.

Read about state machines [here][1] and [here][2].

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: http://teachmetomake.com/wordpress/arduino-tutorial-state-machine


body: Create a flow chart of the entire process you want to happen. Once you proof your flow chart to cover all possible functions, you can create the logic, control, and subroutines that are needed. If you have a good book on Arduino programming, and how I2C works, you will know that the I2c display will hold whatever data you wish until you change it. Also, you probably know that you can chain a whole bunch of I2c devices, no matter if they are displays, or anything else, so each device will hold its own data independent of the others. Any updating is under your control in programming. You might also look into using interrupts for some of your program control. Sensors don't push data, the processor reads the data, and your program is in control of how often and when the data is read, and what it does with the data.  The exception to your program being in control, is when you use interrupts. You should be storing the data so you will always have access to it for program examination and possible decision making. Lastly, to increase the abilities of your system, consider using one master Arduino, and several slave Arduino's. Some of the slaves, depending on what you want them to do, can be very small. Look at the tiny85. Some of the boards with the Tiny85 are the size of a postage stamp. I hope some of these suggestions are helpful to you.


message:
RF24L01+ VER01 with 10 pins

How can I connect this little ship to my Arduino? I can find alot of tutorials how to do it so, but all I find is 8 pins, mine includes 10 pins, and from what I could of understand from searching me myself, that there is 2 pins of VCC and 2 GRN pins.

So I would like to know how to connect this? Not necesserly Arduino, but can someone help me with the pins names at least so I can identify them.
Thanks.

[![enter image description here][1]][1]

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

body:
There are some 10pin adapter boards floating around. See e.g.
https://arduino.stackexchange.com/questions/22914/nrf24l01-8pin-adapter-board-10pin-oops

Their pinout looks to be the following.

[![enter image description here][1]][1]

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


message:
Practicality of recording speech

Is it practical to record speech with the [Leonardo][1]?

I want to record speech via a MEMS microphone and stream it over a serial connection to a Raspberry Pi for speech-to-text processing.

[This article][2] states that the typical bitrate for recording voice podcasts is 64 kbps. The Arduino's `analogRead()` function has a maximum sample rate of typically 8,600 times/sec for a maximum bitrate of 8,600 samples/sec * 10 bits/sample = 86 kbps, so theoretically, it should be fast enough to record decent voice audio.

However, will the serial connection be fast enough to stream this much data? Theoretically, the Leonardo's serial connection can go up to 115,200 bps, but I've never reliably gotten it to go faster than 57,600 bps, which would mean the serial connection would a bottleneck that would prevent it from sending a continuous stream of 64 kbps, and therefore it would be impractical to record speech with the Arduino.

Am I wrong? Has anyone had success with voice recording while streaming it over serial?

  [1]: http://www.arduino.cc/en/Main/arduinoBoardLeonardo
  [2]: http://www.richardfarrar.com/choosing-bit-rates-for-podcasts/

body:
You don't actually have to initialize your connection to 115,200 bps or 57,600 bps. You can use a custom baud rate of 65,000 bps.

One thing to keep in mind that, you can use **any** custom baud rate you want, as long as it's supported by the hardware. The Arduino IDE however only supports standard baud rates.

One more thing, as you are streaming data (kind of), you might also want to look into Arduino serial buffer sizes.


body:
On [my page about the ADC converter](http://www.gammon.com.au/adc) I attempted to record a 4 kHz sine wave on the ATmega328P with the following code:

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

    const byte adcPin = 0;  // A0

    const int MAX_RESULTS = 256;

    volatile int results [MAX_RESULTS];
    volatile int resultNumber;

    // ADC complete ISR
    ISR (ADC_vect)
      {
      if (resultNumber >= MAX_RESULTS)
        ADCSRA = 0;  // turn off ADC
      else
        results [resultNumber++] = ADC;
      }  // end of ADC_vect

    EMPTY_INTERRUPT (TIMER1_COMPB_vect);

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      // reset Timer 1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;
      TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
      TIMSK1 = bit (OCIE1B);  // WTF?
      OCR1A = 39;
      OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

      ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
      ADCSRA |= bit (ADPS2);  // Prescaler of 16
      ADMUX = bit (REFS0) | (adcPin & 7);
      ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
      ADCSRA |= bit (ADATE);   // turn on automatic triggering

      // wait for buffer to fill
      while (resultNumber < MAX_RESULTS)
        { }

      for (int i = 0; i < MAX_RESULTS; i++)
        Serial.println (results [i]);

      }  // end of setup

    void loop () { }

The code (rather inefficiently) sends the results in ASCII, like this:

<!-- language-all: lang-none -->

    378
    710
    899
    992
    966
    827
    609
    367
    159
    38
    35
    147
    350
    593
    817
    965
    1001
    917
    733
    494
    259
    88
    21
    76
    239
    471
    711
    905
    1001
    977
    839
    620
    376
    164
    39

This gave reasonable results:

[![Sine wave with ADC][1]][1]

Now the Leonardo is, of course, a different processor. However it is similar. The ADC on it should be capable of similar performance.

---

I should point out that this code records first, then sends the data. This is so the recording can keep up. A normal ADC conversion (if you don't change the ADC prescaler) takes 104 µs. To send 10 bits via serial at 115200 baud rate would take 173.6 µs because it would require two bytes per sample (unless you somehow compress each reading). If you could put up with 8-bit resolution (per sample) then you halve that, and can probably just stream the data out fast enough.

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


message:
Nrf24L01 with Arduino

When I wanted to test my Nrf24L01 I wanted to be sure of it working fine, so I used this code for an Arduino Uno:

    #include <SPI.h>
    #include <RF24.h>
    #include "printf.h"
    #define RF_CS 9
    #define RF_CSN 7
    RF24 radio(RF_CS, RF_CSN);
    void setup() {
      Serial.begin(9600);
      printf_begin();
      radio.begin();
      radio.printDetails();
    }
    void loop() {
      radio.printDetails();
      delay(5000);

    }
The thing is when I opened my Serial, I got this each 5 second:

    STATUS   = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
    RX_ADDR_P0-1  = 0x0000000000 0x0000000000
    RX_ADDR_P2-5  = 0xff 0xff 0x00 0x00
    TX_ADDR   = 0x0000000000
    RX_PW_P0-6  = 0xff 0x00 0x00 0xff 0xff 0x00
    EN_AA   = 0xff
    EN_RXADDR  = 0xff
    RF_CH   = 0xff
    RF_SETUP  = 0xff
    CONFIG   = 0xff
    DYNPD/FEATURE  = 0xff 0x00
    Data Rate  = 1MBPS
    Model   = nRF24L01
    CRC Length  = 16 bits
    PA Power  = PA_MAX

Which apparently means that there must be something wrong with the connection, as far as I know .

noting that i have this Nrf24L01 with 10 pins, so i tried to attach it just like the following picture shows :

[![enter image description here][1]][1]

So I tried to plug it in with the Arduino just like this:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/5epm9.jpg
  [2]: https://i.stack.imgur.com/PHuWb.png

What was the mistake?

body:
I think problem lies in your Arduino sketch, specifically in this line:

    #define RF_CSN 7

Now, you have set RF_CSN pin to pin#7 while actually, its connected to pin#9

To get this to working you, try changing above lines of code to:

    #define RF_CSN 10

Hope it helps.


message:
Compile `.hex` files on Linux

I build `.hex` files for Arduino. How can I do this in Linux? I use the Linux distro  Mint 17.2.

I need a program to make [`.hex` files] (in Linux).

Can anyone help me?

body:
You can download the Arduino IDE for Linux from [the Arduino site][1].

As mentioned in [Where are the hex files compiled by Arduino?][2], in the Arduino program: go to **Arduino -> Preferences** and then select **Show verbose output during -> compilation**.

> Finally, when you are compiling, the program will show you lots of
> data. At the last lines, you will find the path to the .hex file
> (Every time the path changes!).

If you want to upload this `.hex` file to your **ATmega328P** (the micro controller inside Arduino Uno), `avrdude` can do that for you.

Here, are few useful links:

 1. [Setup Avrdude on Linux][3]
 2. [Programming your chip][4]
 3. [Choosing a Programmer][5]
 4. [Uploading your .hex file][6]

  [1]: https://www.arduino.cc/en/Main/Software
  [2]: https://stackoverflow.com/questions/11607834/where-are-the-hex-files-compiled-by-arduino
  [3]: http://www.ladyada.net/learn/avr/setup-unix.html
  [4]: http://www.ladyada.net/learn/avr/programming.html
  [5]: http://www.ladyada.net/learn/avr/programmers.html
  [6]: http://www.ladyada.net/learn/avr/avrdude.html


body:
How are you creating your `.hex` files? Where are they coming from? Are you cross compiling the `.hex` files on some other machine and then transferring them to the Linux box? What is your Arduino connected to, the Linux box, or some other machine? Why are you even bothering with the .hex files? Your question is a little unclear. As Mikael states in [his comment][1], you do not need to *compile* the `.hex` files, they are already compiled, you merely need to *upload* them, which the Arduino IDE would do for you anyway...

As ARK points out in [his answer][2], you may find the answers to the question [Where are the hex files compiled by Arduino?][3] useful, although it seems like you know where they are but you don't know how to upload them.

Why can you not just use the Arduino IDE, to write your sketch, and then allow it to *automatically* compile the sketch and upload the `.hex` file for you? That way you do not need to manually play with the `.hex` file. Maybe I am missing something.

Is the Arduino IDE bombing out and not uploading the sketch on to the Arduino board?

----

However, if you are merely asking, how can I upload a `.hex` file to an Arduino, in Linux without using the Arduino IDE, then you would use `avrdude`. Taking the answer from [How do I upload a hex file firmware to a target board without using the arduino IDE?][4]

    avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328p -carduino -P/dev/ttyUSB0 -b57600 -D -Uflash:w:/tmp/build8135728863211847829.tmp/sketch_may21b.cpp.hex:i

or alternatively, taking the answer from [Uploading Arduino hex file using avrdude][5]

    avrdude -U flash:w:[put-hex-file-path-here]:i -C avrdude.conf -v -p atmega328 -b 115200 -c stk500v2 -P [put-device-path-here]

  [1]: https://arduino.stackexchange.com/questions/23209/compile-hex-files-on-linux#comment-44093
  [2]: https://arduino.stackexchange.com/questions/23209/compile-hex-files-on-linux#answer-23213
  [3]: https://stackoverflow.com/questions/11607834/where-are-the-hex-files-compiled-by-arduino
  [4]: https://electronics.stackexchange.com/questions/67121/how-do-i-upload-a-hex-file-firmware-to-a-target-board-without-using-the-arduino
  [5]: https://stackoverflow.com/questions/23780125/uploading-arduino-hex-file-using-avrdude


message:
Can I prevent the Stepper library from holding the motor?

I'm using the [Stepper][1] library to control a single stepper motor. When the Arduino is not running the motor it is holding the motor shaft in place. For my application, this is very wasteful and puts unnecessary strain on the motor.

Is the Stepper library supposed to do this or is something else up with my circuit? Can this behavior be overridden?

  [1]: https://www.arduino.cc/en/Reference/Stepper

body:
Stepper library has nothing to do with this. What **holds** your motor are those **GND**s or **0 Volt**s applied to control pins of your Stepper motor.

What you are looking for is [UL2003A][1]. The way ULN2003A works is solution to your problem.

Assuming your stepper is unipolar, [Here is a complete tutorial][2] on how to use Stepper motor with UNL2003A.

  [1]: http://www.ti.com/lit/ds/symlink/uln2003a.pdf
  [2]: https://www.arduino.cc/en/Tutorial/StepperUnipolar


body:
The ability to release all the stepping motor coils depend on the hardware and software used. For example, the Adafruit.com hardware and software has [this][1] function to release all the stepping motor coils.  Investigate their approach and determine if you can contribute to the library you are using by porting this feature.  Also investigate if this feature is not (serendipitously) already part of the library you are using.  For instance, it is not unreasonable to expect the library you are using to return Atmel pins to a passive input state (which, depending on the hardware, may release the stepper) when you destroy the instance of the stepper library class.

  [1]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/library-reference#void-release-void


body:
use disable output class in  accelstepper library.
http://www.airspayce.com/mikem/arduino/AccelStepper/


body:
    //for all pins used for controlling stepper motor assign all of them LOW

    #include<Stepper.h>
    const int stepsPerRevolution = 200;
    Stepper myStepper(stepsPerRevolution, 10, 11,12,13);

    void setup() {
      myStepper.setSpeed(30);

    Serial.begin(9600);
    }

    void loop(){

     Serial.println("clockwise");
      myStepper.step(stepsPerRevolution*5);
      delay(300);
    digitalWrite(10,LOW);
      digitalWrite(11,LOW);
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);

    }


message:
Avoiding float math to speed up arduino

I read and heard that the floating point math is much slower than int math.

And I saw a converting process in here [floath math to integer math][1]

So I want to to convert my floating math calculations to integer math.

Here is the code that include floating math:

    float sensval, lpf, lps;
    float sensinitial; // used to store the initial sensor data
    float x, y, z;
    int heigh;
    int dA;

    void setup() {

      runSensor();
      sensval = readSensorData();
      sensinitial = sensval; // Setting the initial data
      lpf = lps = sensval;
    }

    void loop() {
      sensval =  readSensorData();
      heigh = (float)44330 * (1 - pow(((float) sensval/sensinitial), 0.190295));
      lpf = lpf + (sensval - lpf) * 0.1;
      lps = lps+ (sensval - lps) * 0.05;
      x = (lps - lpf) * 50;
      y = x+ (z - y) * 0.1;
      z = constrain(y, -500, 500);
      dA += z * 100 + 2000;
    }

  [1]: http://www.engblaze.com/faster-code-fridays-avoid-floating-point-math/

readSensorData(); returns 7 decimals maximum(752.4543 for example)

There is pow calculation too.

So how can I convert floath math to int math?

Any optimization code are welcome.

body: Since you are dealing with fractions, you can use fixed point arithmetic. For example, you can use `unsigned short _Accum` for `readSensorData()` if you only need 8 bits for the fraction part. http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1169.pdf tells you about fixed point types in c.


body:
What you are asking for is not simple, especially since you have this
power function that can be hard to approximate.

First, you have to figure out the range and the required precision of
each of the floating point numbers you are manipulating. You wrote that
`readSensorData()` returns 7 decimals. If by that you mean that you
require a relative accuracy of 10−7, then I predict it will
be _extremely_ hard to optimize this as a fixed point calculation. If
you can live with a much lower relative accuracy (say, around
10−3 or 10−4), then it may be worth trying
something.

I would start by writing the expression of `height` as

    height = f(sensval/sensinitial-1)

where

    f(x) = 44330 * (1 - pow(1+x, 0.190295))

I would expect `sensval` and `sensinitial` to be close to one another,
which would imply that _x_ is small. At this point you should try to
estimate the likely range for _x_, because the feasibility of what
follows strongly depends on it. Next step is to approximate f() by a
polynomial. A simple [Taylor
expansion](https://en.wikipedia.org/wiki/Taylor_series) gives:

    f(x) ≈ -x*(8435.78-x*(3415.25-x*2060.2))

You may start by trying this, just to see if it looks kind of OK or
completely hopeless. You will notice that the above approximation is
great when |_x_| is tiny, but it very quickly degrades as |_x_|
increases. This is why you don't use Taylor expansions in real
approximations, I showed it to you only to give you an idea of the
feasibility of a polynomial approximation.

To do better than Taylor, you _must_ specify the range of _x_, then you
can scale that range to [−1, 1] and expand on the basis of the
[Chebyshev
polynomials](https://en.wikipedia.org/wiki/Chebyshev_polynomials). And
then you could fine-tune to get the [optimal
polynomial](https://en.wikipedia.org/wiki/Approximation_theory), but
it's likely to be only marginally better than the Chebyshev expansion.

If all this works with a reasonable polynomial degree (say, no more than
5), then you can start converting to integer math. If it doesn't, you
may try a different type of approximation, like interpolating over
tabulated values. If the problem is the range of _x_ being too large,
you may instead write the power function as

ab = 2b × log2a

and write polynomial approximations to the base-2 exponential and
logarithm (the polynomials only needs to cover one octave). If you try a
rational fraction approximation, beware that divisions are slow on the
AVR platform.

If all the above looks like too complex, or too much work, then just get
a faster CPU, or try to live with your program being slow.


message:
Arduino Leonardo runs unusually hot

I have a genuine (purchased from Adafruit) Arduino Leonardo that I have had for 2 years and I have not had any issues with. However, I have always noticed that it seems to be running suspiciously hot for a low power microcontroller, sometimes even too hot to comfortably touch. I measured the temperature today with an infrared thermometer at 121 degrees Fahrenheit (~49C). Based on observations by feeling the board, the 32U4 seems to be what is getting hot and everything else is cool to the touch. This happens when it is powered over USB as well as through the power jack. The chip gets hot even when nothing is connected to the I/O or power pins. The board is entirely working and does not appear visibly damaged. I am a bit worried about this as I may use this board in a project where it will be inside in enclosure and running for long periods of time. Any ideas why this is happening and if this normal?

body:
My Leonardo, which I leave on all the time, is not hot. The CPU chip feels at room temperature as far as I can tell. If you were powering something from it, maybe you are drawing too much current. If it gets hot just sitting there doing nothing, and with nothing connected, something is wrong.

Maybe you damaged it in the past? Maybe hooked up some LEDs without current-limiting resistors? If not, it sounds like a faulty device to me.