body:
It is hard to understand what your code does. You said that arduino recives text from the server, but I see in the code is that the arduino **is** the http server, serving an html page with a form in it.

That is also the reason you recieve spaces replaced with "+", the http request is [**url encoded**][1].

The problem with a search and replace solution of a "+" sign is that url encoding is more than a "+" sign. A space can also be encoded into   and there are several other characters that are being encoded as well.

What you will have to do is to implement a **decoding** function. It is not that hard but if you are lazy, there are plenty of C implementations available on the net. Here is a quick google search hit: https://gist.github.com/jmsaavedra/7964251

  [1]: https://en.wikipedia.org/wiki/POST_(HTTP)#Use_for_submitting_web_forms


sender: user

message:
Why does Arduino Due Native Port change serial ports after every reset? (Linux)

Previously I had my Due connected via Programming Port for weeks, and it never changed serial ports after pressing the reset button. Recently I switched to having it connected via the Native Port instead, and was surprised to see that it changes port numbers every time I press the reset button.

For example if it was on ttyATM1 beforehand, after pressing reset it'll be on ttyATM2 instead. It changes numbers like this after every reset. Is this normal behavior?

I have a python script sending serial data to the Due, and I have to change the port number in the python code every time the Due changes ports.

sender: assistant

body:
It happens because of Linux, not because of the Arduino.
Since you unplug/reset the DUE while the port is still open, when it's back online, the old file name is still in use, so a new one is created.
Just close the port before resetting the DUE and you will see that after the reset it will have the same one.

You can easily reproduce the same issue with a serial to usb adapter (/dev/ttyUSBS0,1,2,etc) and screen or minicom.

To make your program more robust, you should listen for kernel events and open the port accordingly.


message:
Will there be any pin interference in this Project?

I am working on a project with Arduino Uno Clone. After having a look on my arrangement, please tell me whether I will have to face any difficulty or consider any thing.

I have a relay on pin 2 (drive An Induction cooktop from AC Mains),

6 mini 9g servo from pin 3-8 (want to drive non-pwm pins with any Software library),

a 8 ohm speaker on pin 9,

a microSd card module from pin 10-13 (play .wav files through speaker),

5 pushbuttons from pin A0-A4,

a toy dc motor on A5 (Drive through a transistor). So my questions are:

 1. Will I have to face any pin arrangement problem in my project? If yes, please give me a solution
 2. I have six servos and a dc motor in which only one will be moving at a time, is there really a need of external power source for motors
 3. I have to drive this arrangement through AC Mains, but i dont want to buy An adapter. I have a mobile charger which have written "INPUT 100-250V AC, OUTPUT 4-12V, 800mA" , can I drive my arduino with this?
 4. Can I boost the volume of my speaker by using a transistor or capacitor (I have no idea about amplifier IC) ?
 5. I have to include these librairies, SD library, tmrpcm, SPI, servo, and any one extra to drive servos on non-pwm pins. What would be the total size because my arduino has only 30kb approx?  Thanks To Give Me Time. Please help me.

body:
 1. possibly you will face problems with current drain and timing. There is no ready made solution. You have to get a bit farther by yourself and come back with detailed descriptions of your problems.
 2. check on other threads (google) the issues with driving directly a coil. There are plenty of explanations why you need to be careful about it.
 3. you should at least try to do the math yourself, then ask for verification. Try to calculate the power requirements of each component (average, maximum, peak) and add them up for every scenario. The you can report your finding and ask for confirmation/advice.
 4. Sure you can, there are plenty of solutions available, but you have to define your requirements and constraints. Then it's easy to pick one solution (or at least google for it).
 5. Just try to include them in the project and compile them. It's fast and you will get the answer immediately. There are ways to optimize things, but first you should assess if it's needed.

All in all, to get more help, you should show more in detail what you have already done, what are your concerns and why.


message:
Should long wires be kept separated from each other, to reduce interference?

Let's say someone has four CAT5 cables that are running along the ceiling for the length of a room (30 feet), of which most of the twisted pairs are connected to Arduino input/output pins on one end. Would it be okay to keep these wires bundled together when running along the ceiling? Or is it safer to keep them separated by a few inches? Is interference usually a problem only in very specific situations, or should it be considered for all long wire runs?

How about if there is a telephone cable (hooked up to a landline telephone) running along the same length? Is there any chance of interference if this is too close to the Arduino cables?

How about if there are 120v mains lines running the same length? Should these be kept at a distance from the Arduino cables?

On the other end of the cables that are hooked up to the Arduino, some of the following are connected: temperature sensors, light sensors, servo motors, LCDs, relays, and push-buttons.

body:
It depends on the frequency/frequencies you care about transmitting on your cables. One simple approach is to put on both ends a filter that lets pass only those frequencies you care about.
You can also consider using some error detection/correction encoding or check if there is some existing library that suits your needs. This last approach will work if you do not get too many interferences and your application can tolerate that data is re-transmitted every now and then, making the communication timing not 100% deterministic.


body: A benefit of using CAT-5 is that the pairs are twisted.  You would want to look at how you are using the pairs so that you're not introducing cross talk inadvertently, but the twisted pairs tend to resist RFI which is why its used.  Telephone wire, however, can be a completely different story.  You may find some that is twisted pair, but most if it is simply flat cable.  Worse, much of it is very cheap flat cable with what amounts to a piece of thread with a very thin foil wrapped around it.  This is very high loss and very vulnerable to RFI.


body:
CAT5 should work well with what you are trying to do, however stay away from power lines unless they are in a grounded conduit.  The phone lines would most likely generate interference when the phone is ringing as there is a lot of voltage transients on the line at that time.

To get the full benefit of the twisted pairs send and receive your signals with differential transceivers, one transceiver per pair.

Personally I will not connect a microprocessor pin to the outside world without some type of buffering isolation etc.  Those pins were not designed to drive long lines, although it may work eventually it will fail, that may be momentary to many years in the making but it will fail.

Lines connected directly to the microprocessor pins will all act as bidirectional antennas. They are not only are sustainable to interference they also generate it.  Remember the wires are small inductors which can generate some huge voltages when the transition time is short.

I typically use Schmidt devices such as a 74C14, 74HC etc. as my input receivers for switches etc.  I normally use an active low input signal, this help to keep noise out of the power supply. The input to the gate is pulled up to the 12VDC with a 10K resistor, this keeps a minimum of about 1 mA through the contact. The other end of the resistor is connected to a 100K resistor that in turn connects to the microprocessor input pin. You can add a cap to de-bounce at the gate if you want. The software is easier as it is looking for an active high which is a logic "1".  This circuit has been replicated hundreds of thousands of times and is very stable and reliable.

What you are doing will work for dorm room, testing etc...


message:
Broken Score on Game Sketch

I have modified the code for Flappy Duino to give me a score at the end of the game. Here is the code:

    #include <SPI.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_PCD8544.h>

    Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);

    #include "Sprite.h"
    #include "Chym.h"
    #include "Bar.h"

    Chym player;
    Bar bar; Bar bar2;
    int gameScore = 0;
    int highScore = 0;
    int KNOCK_PIN = 2;
    int LED_PIN = 8;

    boolean clicked = false;

    void loop(){}

    void resetGame() {
      player.respawn();
      bar.setPos(0, 20);
      bar2.setPos(50, 30);
      gameScore = 0;
    }

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

      display.begin();
      display.setContrast(50);
      display.clearDisplay();
      display.display();

      digitalWrite(LED_PIN, HIGH);

      pinMode(KNOCK_PIN, INPUT_PULLUP);
      pinMode(LED_PIN, OUTPUT);

      resetGame();

      while(1) {
        getInput();
        player.update();
        bar.update(); bar2.update();
        drawLCD();
      }
    }

    void getInput() {
      int knock = digitalRead(KNOCK_PIN);
      if (knock == 0) { // push down
        clicked = true;
        gameScore = gameScore + 1;
        Serial.println(gameScore);
      }
      else {
        clicked = false;
      }
    }

    void drawLCD() {
      display.clearDisplay();

      if (!player.isDead()) {
        int ht1 = bar.hitTest(player.getX(), player.getY());
        int ht2 = bar2.hitTest(player.getX(), player.getY());
        int die = ht1 + ht2;
        if (die == 1) {
            // game over
            player.die();
        }

        if (clicked) {
          player.flyUp();
        }
        else {
          player.cancelJump();
        }
        player.render();

        bar.render(); bar2.render();
      }
      else {
        if (gameScore >> highScore) {
          highScore = gameScore;
        }
        display.setCursor(0, 0);
        display.setTextSize(1);
        display.print("ur Score- ");
        display.println(gameScore);
        display.print("HI Score- ");
        display.println(highScore);
        if (clicked) {
          resetGame();
        }
      }

      display.display();
    }

The first time the game runs thru the gameScore is greater than highScore so gameScore and highScore print as the same. However every other time the function is called up the highScore doesn't change even when the following statement is true:

    if (gameScore >> highScore) {
              highScore = gameScore;
            }
What am I doing wrong?

body:
    if (gameScore >> highScore)

You have the wrong operator there.  `>>` is *right shift*, so you are right shifting the `gameScore` by `highScore` bits, which if it's more than 16 will end up as 0.

Instead you just want `>` for *greater than*:

    if (gameScore > highScore)


message:
What could make an LCD stop working permanently after being connected for 5 seconds to Arduino?

I was using a 20x4 LCD connected to Arduino Uno via [a common I2C adapter board.][1] Everything was working perfectly, including the LCD. I had it running like this for a couple of days without any problems.

My next step was to connect the LCD to a Nano instead in order to make the package smaller. The exact same code from the Uno was uploaded to the Nano, and I connected the wires in the exact same way. The major difference here was that I soldered the wires onto the Nano, because I didn't want to use headers. I did a continuity test for shorts and the connections seemed to be fine. There are only 4 wires between the Arduino and LCD adapter board: 5v, ground, SDA and SCL.

The Nano powers up fine, and the LCD powers up fine, but immediately the LCD shows the following:
[![Corrupt LCD][2]][2]

That had never happened when I had the LCD connected to the UNO.

After that, the LCD stops working completely, even when I move it back to the UNO. It just constantly displays those 2 lines. (Adjusting the contrast makes the boxes appear or disappear).

After the first LCD seemed permanently broken like that, I tested it on a 2nd brand-new LCD. First I connected it to the same Uno with the same code, and everything was working perfectly. I re-uploaded that same code again to the Nano, just to make sure everything was in sync. Then upon connecting the 2nd LCD to the Nano, immediately it displayed those 2 lines. I disconnected it right away (within 5 seconds), and tried to put it back on the Uno, but still the display is corrupted. I've tried other sketches, but both of these displays seem to be broken and never display anything except for those 2 lines.

Even if I just connect 5v and ground to the LCD, no matter from what source, it just constantly displays those 2 lines.

Any ideas as to what could "break" an LCD so quickly like that, and if it's possible fix it?

**Edit:**
As per Gerben's suggestion, I removed the I2C backpack and hooked the LCD up directly. This was the 2nd one I had broken, the one where I'm more certain of its entire (short) history. I ended up with the exact same result. Adjusting the pot only makes the boxes appear or disappear. I tried skipping the Arduino completely and giving it 5v power from an adapter, and it still has the same result.
[![Corrupt LCD without backpack][3]][3]

  [1]: http://www.ebay.com/itm/IiC-I2C-TWI-SP-I-Serial-Interface-Board-Adapter-Module-Port-For-Arduino-1602LCD-/181576314435
  [2]: https://i.stack.imgur.com/E6Qzl.jpg
  [3]: https://i.stack.imgur.com/O5DY3.jpg

body:
It's unlikely that you have killed the unit as this is pretty hard to do from the data interface and your picture is typical for an LCD that has not gone through the initialization sequence.  A dead LCD driver will usually display nothing and what your picture shows is that the LCD controller itself is operating.  If anything is dead, I would suspect the I2C interface board as this would yield the same result you are seeing.  It may also be that the timing of the I2C interface is right on the edge which may explain why a long cable'd setup is working.

Note that if the initialization is not done, no other commands will work.  Note also that the initialization timing and sequence of events is ABSOLUTELY CRITICAL and missing any single step or time requirement will give the result you are showing.

Starting at page 10 of this [instructional PDF][1] is my favorite and the basis of my driver that I have been using since the 80's.

  [1]: http://www.tayloredge.com/reference/Electronics/Displays/lcdtech.pdf

----------------------------------------

The driver I use works on every display I have ever hooked to it, regardless of changes in the particular project's processor clock speed because I paid strict attention to the worst case timing requirements.  If the timing of the I2C interface violates one LCD it may not violate another, i.e. one display can tolerate bad timing while another can't.  There are also issues if the LCD driver uses the busy flag or not:  Blind data transmission without reading the LCD's busy state will work if the LCD is fast enough and the driver is slow enough, otherwise 'No bueno!' plus the interface is not going to operate at its maximum speed.  When using the busy flag (Bit 7 of the interface) there is solid handshaking which confirms (Instead of "Trusts") that the LCD is ready for the next cycle and allows operation right up to the limit of performance.

What I would suggest is that you put the interface on a logic analyzer and verify that the timing is not being violated.

Timing tolerances and variation between parts is like lug nuts on a car... If you car has 5 lug nuts per wheel, it will probably work with 3 or even 2 but NOT UNDER ALL CONDITIONS.  SOME LCDs will be happy with bad timing but ALL LCDs NEVER will be.


message:
Arduino number detection

I am planning for a project but i am stuck with a task and hope you could help me. My work is to note down a number which is actually a set of readings displayed on a meter and store it on a arduino. My problem is that i need a detection technique so that i could record the number or extract the number from a image or video if u suggest to use a camera or recorder or purely can be a sensor. Thank you guys, waiting for you.

body: "Number detection" sounds like you're trying to interpret a 7-segment digital display - is that correct? One way would be to place 7 photo-detectors (times the number of digits), one per segment, on or at the face of the display. Sample the photo-detectors and create a 7-bit code representing the lit segments, into a byte. You could start with a simple lookup table that translates from code to the digit it represents. You might need to get clever about interpreting codes that shouldn't appear, but do, due, perhaps to light leakage, ambient lighting, or noise. The "lit" segments may only be lit for a fraction of second at a time, and only one at a time, if the display is multiplexed, so your sampling algorithm will have to take that into account. Must the display remain visible? You might need optics or optical fibers to view the segments without obstructing them.


message:
Ultrasonic sensor returns random values on external power supply

my Problem is, that I get random values from my ultra sonic sensor if my arduino is connected to any external power supply (vin port 30) on my arduino nano.

If I power up from the laptop usb port, I get consistent values.

I have tested 3 different power supplies between 7-17V and up to 2000mA.
I have tested this on 2 different nano boards.
Also tested with an extra 2000uF capacitor between vin and gnd

pls help if you got an idea :)

body:
So i tried to used a stable 5V input on the 5V input pin and got the same more or less random values (jumping all around... especially on targets more than 1m away)

So I changed form newPing lib (http://forum.arduino.cc/index.php?topic=37712.0) to Ultrasonic lib (http://forum.arduino.cc/index.php?topic=37712.0).

Now the values are correct on each power supply and even more accurate on high distance than with newPing on USB power supply.

Don't know whats broken with the newPing v1.7 lib -.- but this works!


message:
Where do avrdude parameters get defined in the Arduino IDE?

I am interested in learning how the Arduino IDE handles parameters in order to correctly upload hex files with *avrdude*.

I found this in *boards.txt*:

    uno.name=Arduino/Genuino Uno

    uno.vid.0=0x2341
    uno.pid.0=0x0043
    uno.vid.1=0x2341
    uno.pid.1=0x0001
    uno.vid.2=0x2A03
    uno.pid.2=0x0043
    uno.vid.3=0x2341
    uno.pid.3=0x0243

    uno.upload.tool=avrdude
    uno.upload.protocol=arduino
    uno.upload.maximum_size=32256
    uno.upload.maximum_data_size=2048
    uno.upload.speed=115200

    uno.bootloader.tool=avrdude
    uno.bootloader.low_fuses=0xFF
    uno.bootloader.high_fuses=0xDE
    uno.bootloader.extended_fuses=0x05
    uno.bootloader.unlock_bits=0x3F
    uno.bootloader.lock_bits=0x0F
    uno.bootloader.file=optiboot/optiboot_atmega328.hex

    uno.build.mcu=atmega328p
    uno.build.f_cpu=16000000L
    uno.build.board=AVR_UNO
    uno.build.core=arduino
    uno.build.variant=standard

There is this in *platform.txt*:

    # AVR Uploader/Programmers tools
    # ------------------------------

    tools.avrdude.path={runtime.tools.avrdude.path}
    tools.avrdude.cmd.path={path}/bin/avrdude
    tools.avrdude.config.path={path}/etc/avrdude.conf

    tools.avrdude.upload.params.verbose=-v
    tools.avrdude.upload.params.quiet=-q -q
    tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

    tools.avrdude.program.params.verbose=-v
    tools.avrdude.program.params.quiet=-q -q
    tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

    tools.avrdude.erase.params.verbose=-v
    tools.avrdude.erase.params.quiet=-q -q
    tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

    tools.avrdude.bootloader.params.verbose=-v
    tools.avrdude.bootloader.params.quiet=-q -q
    tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.platform.path}/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m

This line is particularly interesting:

    tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

It seems like these variables are corresponding:

    {cmd.path} --> tools.avrdude.cmd.path
    {config.path} --> tools.avrdude.config.path
    {upload.verbose} --> tools.avrdude.upload.params.verbose
    {build.mcu} --> uno.build.mcu
    {upload.protocol} --> uno.upload.protocol
    {serial.port} --> ?
    {upload.speed} --> uno.upload.speed
    {build.path} --> ?
    {build.project_name} --> ?

It seems these are likely used in the Java code for the IDE. There are obviously a few I am unsure of. I would guess these are considered user inputs in the IDE. Though I am by no means a Java or JavaScript programmer.

Where are these variables explicitly defined in the Arduino library? (e.g. `{runtime.tools.avrdude.path}`, `{path}`, `{cmd.path}` ....) Or how do they get defined by IDE?

body:
There are 3(or 4) places that you need to look at to know how to upload.
There is the boards.txt file and the platform.txt file.
You can consider a platform.txt file line

    tools.avrdude.path={runtime.tools.avrdude.path}

as (in linux in windows replace ${xx} by %xx%)

    set tools.avrdude.path ${runtime.tools.avrdude.path}
and the board.txt for the selected board like

    uno.bootloader.tool=avrdude
as

    set bootloader.tool avrdude

The arduino ide uses the following string to know the upload command environment variable

    tools.${bootloader.tool}.upload.pattern

 This way it knows the command to upload is

    "{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

{cmd.path} is hardcoded as tools.${bootloader.tool}.cmd.path which equals {path}/bin/avrdude
where {path} is to be understood as tools.${bootloader.tool}.path wich equals {runtime.tools.avrdude.path}.
{runtime.tools.avrdude.path} is defined by the boardsmanager based n the json file and the location where the boardsmanager extracted the download.

So that makes 3 files: boards.txt, platform.txt and json file and some hard coding.

A 4th file comes into play when you use the "other upload commands". These are located in the programmers.txt file.

IMHO Arduino IDE core team did not opt for the simplest solution to define these things. They also change the way they work from time to time.
If you use a makefile know that a lot of people have done this already so it may be a good idea to "reuse other peoples work" instead of "reinventing the wheel". It is not so easy or straightforward.

**Note** I know all these things because I implemented the Arduino eclipse IDE. As far as I know none of this is documented.


message:
Understanding values from an MPU6050

I'm trying to understand the values that I'm getting from my MPU6050. I believe that there is a problem with my code. I'm not entirely sure how the code is supposed to look like. There doesn't seem to be very many examples on the MPU6050.

What is wrong?

*After taking a look at the system print I found that the numbers that are written out is the time and not the values of the MPU6050. Why am I getting the zeros and nan for?*

*I also had a library problem thats fixed now.*

I got the code from a site and I've modified it because it didn't run for me.

This is my code:

    // collect readings
    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    // apply gyro scale from datasheet
    gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;

    // calculate accelerometer angles
    ary = -(180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
    arx =  (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
    arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);

    // set initial values equal to accel values
    if (i == 1) {
    grx = arx;
    gry = ary;
    grz = arz;
    }
    // integrate to find the gyro angle
    else{
    grx = grx + (timeStep * gsx);
    gry = gry + (timeStep * gsy);
    grz = grz + (timeStep * gsz);
    }

    // apply filter
    rx = (0.1 * arx) + (0.9 * grx);
    ry = (0.1 * ary) + (0.9 * gry);
    rz = (0.1 * arz) + (0.9 * grz);

     Serial.print(ax);   Serial.print("\t");
     Serial.print(ay);   Serial.print("\t");
     Serial.print(az);   Serial.print("\t\t");
     Serial.print(gx);   Serial.print("\t");
     Serial.print(gy);   Serial.print("\t");
     Serial.print(gz);   Serial.print("\t\t");
     Serial.print(arx);   Serial.print("\t");
     Serial.print(ary);   Serial.print("\t");
     Serial.print(arz);   Serial.print("\t\t");
     Serial.print(grx);   Serial.print("\t");
     Serial.print(gry);   Serial.print("\t");
     Serial.print(grz);   Serial.print("\t\t");
     Serial.print(rx);   Serial.print("\t");
     Serial.print(ry);   Serial.print("\t");
     Serial.println(rz);

This is the output im getting

    2 1.00 61.00 0.06000  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    3 61.00 139.00 0.07800  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    4 139.00 219.00 0.08000  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    5 219.00 300.00 0.08100  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    6 300.00 380.00 0.08000  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    7 380.00 462.00 0.08200  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    8 462.00 543.00 0.08100  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    9 543.00 624.00 0.08100  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    10 624.00 705.00 0.08100  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    11 705.00 788.00 0.08300  0 0 0  0 0 0  nan nan nan

...

    41 3223.00 3307.00 0.08400  0 0 0  0 0 0  nan nan nan nan nan nan  nan nan nan
    42 3307.00 3392.00 0.08500  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    43 3392.00 3476.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    44 3476.00 3560.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    45 3560.00 3645.00 0.08500  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    46 3645.00 3729.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    47 3729.00 3813.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    48 3813.00 3897.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    49 3897.00 3982.00 0.08500  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    50 3982.00 4066.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    51 4066.00 4150.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    52 4150.00 4234.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    53 4234.00 4319.00 0.08500  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    54 4319.00 4403.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    55 4403.00 4487.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    56 4487.00 4571.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    57 4571.00 4656.00 0.08500  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    58 4656.00 4740.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan
    59 4740.00 4824.00 0.08400  0 0 0  0 0 0  nan nan nan  nan nan nan  nan nan nan

body:
The output MPU 6050 does need filtering/processing before you can get any sense from it.  I have used the library "MPU6050_6Axis_MotionApps20.h" with success, it is located here: [MPU6050_6Axis_MotionApps20.h][1]

I have written an example here: [MPU 6050 for MicroView][2].

  [1]: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/MPU6050_6Axis_MotionApps20.h
  [2]: https://codebender.cc/sketch:118202


body:
I think the best choice for you is to read raw data from the sensor using Wire library.

1. First of all, you have to include the "Wire.h" library:

    ```c++
    #include "Wire.h"
    ```
2. Next step is to start the I2C communication by calling the following function in `setup()`

    ```c++
    Wire.begin();
    ```

3. Now that the master joined the I2C bus, all you have to do is to set the power mode of the module by setting the register `0x6B` to `0x0`. You can use the following function:

  ```c++
  int sendCommand(int8_t register_address, int8_t register_value) {
  Wire.beginTransmission(mpu_address);
  Wire.write(register_address);
  Wire.write(register_value);
  int statusCommand = Wire.endTransmission(true);
  Serial.print("I2C Address: "); Serial.print(mpu_address, HEX);
  Serial.print(" Register address: "); Serial.print(register_address, HEX);
  Serial.print(" Register value: "); Serial.print(register_value, HEX);
  Serial.print(" Status command: "); Serial.println(statusCommand);

  return statusCommand;
}
```

Please note that the default I2C address for the MPU6050 is `0x68`. You can use the [I2C Scanner][1] to find its address.

To actually set the register `0x6B` to `0x0` you have to call the `sendCommand` like below:
```c++
sendCommand(0x6B,0x0);
```

4. Request the raw data from the MPU6050. You can check the [MPU6050 Register Map][2] for additional information.  Accelerometer can be found from `0x3B` to `0x40`, temperature from `0x41` and `0x42`, and finally, the gyro from `0x43` to `0x48`. **IMPORTANT!!!** Every register's value occupy 1 byte (int8_t), so you have to get the values of two registers (2 bytes) and store them in an int16_t.

Here is the full code to get the angles from the sensor:

```c++
#include "Wire.h"

int8_t mpu_address = 0x68;
int sendCommand(int8_t register_address, int8_t register_value) {
  Wire.beginTransmission(mpu_address);
  Wire.write(register_address);
  Wire.write(register_value);
  int statusCommand = Wire.endTransmission(true);
  Serial.print("I2C Address: "); Serial.print(mpu_address, HEX);
  Serial.print(" Register address: "); Serial.print(register_address, HEX);
  Serial.print(" Register value: "); Serial.print(register_value, HEX);
  Serial.print(" Status command: "); Serial.println(statusCommand);

  return statusCommand;
}

void setup() {
  //join the I2C bus
  Wire.begin();
  //start serial communication
  Serial.begin(115200);
  delay(1000);

  /* sendCommand can return 5 possile values:
   * -> 0:success
   * -> 1:data too long to fit in transmit buffer
   * -> 2:received NACK on transmit of address
   * -> 3:received NACK on transmit of data
   * -> 4:other error
   */
  while(sendCommand(0x6B,0x0) != 0){
    delay(1000);
  }

  Serial.println("MPU6050 started");
}

void convertRawDataToAngle(int16_t AcX, int16_t AcY, int16_t AcZ) {
  int minVal = 265; int maxVal = 402;
  int xAng = map(AcX, minVal, maxVal, -90, 90);
  int yAng = map(AcY, minVal, maxVal, -90, 90);
  int zAng = map(AcZ, minVal, maxVal, -90, 90);

  int x = RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
  int y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI);
  int z = RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

  Serial.print("X angle: "); Serial.print(x);
  Serial.print(" Y angle: "); Serial.print(y);
  Serial.print(" Z angle: "); Serial.print(z);
}

void readData(int8_t register_address) {

  int bytesReceived = -1;
  int statusCommand = -1;
  do {
    Wire.beginTransmission(mpu_address);
    Wire.write(register_address);
    statusCommand = Wire.endTransmission(false);
    bytesReceived = Wire.requestFrom(mpu_address, 6, true);
    Serial.print("I2C Address: "); Serial.print(mpu_address, HEX);
    Serial.print(" Register address: "); Serial.print(register_address, HEX);
    Serial.print(" Status command: "); Serial.print(statusCommand);
    Serial.print(" Bytes received: "); Serial.println(bytesReceived);
  } while (statusCommand != 0 && bytesReceived != 6);
  //check if MPU6050 sent all the requested data
  //in total 6 bytes, 2 bytes for each axis
  if (Wire.available() == 6) {
    int16_t AcX = Wire.read() << 8 ;
    AcX |= Wire.read();
    int16_t AcY = Wire.read() << 8 ;
    AcY |= Wire.read();
    int16_t AcZ = Wire.read() << 8 ;
    AcZ |= Wire.read();
    convertRawDataToAngle(AcX, AcY, AcZ);
  }
}
void loop() {
  //put your main code here, to run repeatedly:
  readData(0x3B);
  delay(100);
}
```

  [1]: https://playground.arduino.cc/Main/I2cScanner/
  [2]: https://www.invensense.com/wp-content/uploads/2015/02/MPU-6000-Register-Map1.pdf


message:
I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?

I have **two 6 volts DC motors** connected to **L298N motor Driver**. Do I need to use 12 Volts battery?

body:
No, you need to use a (roughly) 6V battery. They are 6V motors, so they need a 6V battery.

However, you *do* need to sum the *currents* not the voltages. The battery must be able to provide *at least* the current required by *both* motors together.


message:
Arduino Temperature sensor with a LED

I want to program a temperature sensor with a LED using Arduino.
the goal is to make a sensor, when the temperature is over than Temperature max, the LED turns off and when the temperature is small than temperature max we turn on the LED.

my problem is when I programed the void setup() as followed, the LED doesn't work, and when I comment Serial.begin (9600) the LED work but I cannot diplay the value of the temperature.

    void setup() {
       Serial.begin(9600);
       pinMode(tempPin, INPUT);
       pinMode(led, OUTPUT);
    }
here you find my complet code:

        int tempPin = A0;   // the output pin of LM35
    float Max_temp = 24.0;
    int led = 1;

    float  temp, cel;
    void setup() {
       Serial.begin(9600);
       pinMode(tempPin, INPUT);
       pinMode(led, OUTPUT);
    }
    void loop() {
          cel = readTemp();
      if(cel< Max_temp) {        // if temp is higher than tempMax
          digitalWrite(led, HIGH);  // turn on led
          delay(300);
         }
         else {                    // else turn of led
           digitalWrite(led, LOW);  // turn on led
          delay(100);
      }
       Serial.print("TEMP: ");
       Serial.print(cel);      // display the temperature
       Serial.print("C ");
       Serial.println();
       delay(300);
    }

    float readTemp() {  // get the temperature and convert it to celsius
      temp = analogRead(tempPin);
      return temp * 0.48828125;
    }
thank you very much in advance

body:
    int led = 1;

You do know that pins 0 and 1 are the serial port don't you?

Take your pick.... Either use pin 1 for the LED *OR* use pin 1 for the serial connection.  You can't do both!

As it says *[in the manual](https://www.arduino.cc/en/Main/ArduinoBoardUno)*:

> In addition, some pins have specialized functions:
>
> - Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.


body:
Your logic is backwards. Your program says if the temp is LESS THAN max then turn on the LED.

But worse than that, you should not use pin 1.  Pick any other pin.


message:
Arduino + TMP36 + DC Motor

I made this circuit:

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

The part with the DC motor is from this tutorial: https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-12-driving-a-motor ( I only use another resistor, with 220 OHM)

As you can see, I also have a TMP36 sensor attached. What I would like to do is this:
When the temperature is 25 degrees or more, the motor should turn on.

I have this code:

    //TMP36 Pin Variables
    int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
                            //the resolution is 10 mV / degree centigrade with a
                            //500 mV offset to allow for negative temperatures

    /*
     * setup() - this function runs once when you turn your Arduino on
     * We initialize the serial connection with the computer
     */
    void setup()
    {
      Serial.begin(9600);  //Start the serial connection with the computer
                           //to view the result open the serial monitor
    }

    void loop()                     // run over and over again
    {
     //getting the voltage reading from the temperature sensor
     int reading = analogRead(sensorPin);

     // converting that reading to voltage, for 3.3v arduino use 3.3
     float voltage = reading * 5.0;
     voltage /= 1024.0;

     // print out the voltage
     Serial.print(voltage); Serial.println(" volts");

     // now print out the temperature
     float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
                                                   //to degrees ((voltage - 500mV) times 100)
     Serial.print(temperatureC); Serial.println(" degrees C");

     if(temperatureC >= 25){
      analogWrite(9, 250);
     }

     delay(1000);                                     //waiting a second
    }

But I get this result:

    0.74 volts
    24.22 degrees C
    0.74 volts
    24.22 degrees C
    0.74 volts
    24.22 degrees C
    0.74 volts
    24.22 degrees C
    0.74 volts
    24.22 degrees C
    0.74 volts
    24.22 degrees C
    0.75 volts
    25.20 degrees C <------
    0.87 volts
    36.91 degrees C
    0.66 volts
    16.41 degrees C
    0.78 volts
    27.64 degrees C
    0.77 volts
    26.66 degrees C
    0.84 volts
    34.47 degrees C

The point where the sensor measures > 25 degrees, the motor turns on but the circuit gets "poluted" and the temp sensor starts to send all kinds of strange values.

How do I solve this?
Thanks in advance!

<hr />

I got it to work in with the following: http:// i.stack.imgur.com/4GFPH.png

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

body: Motors tend to use more current than the arduino can supply, try hooking up the motor to a different power supply than the arduino 5V. What most likely is happening, is that when the motor turns on, it alters the value of the voltage, which the temperature sensor is using to tell the arduino what the temperature is. You need to have the temperature sensor hooked up to the arduino to have the reference at the right voltage, so the motor should be on a different power supply. That should fix things.


message:
Using / calibrating pH sensor module

I've bought this sensor module board to link to an Arduino nano: http://www.ebay.com/itm/For-Arduino-Liquid-PH-Value-Detection-detect-Sensor-Module-Monitoring-Controller/321764233326

I assumed the two screws were for calibration (low point + slope), but it seems the operation is different and I can't figure out how. I've got two reference liquids for pH of 4.0 and 7.0. When I put the probe in either one, I get readings. Turning one of the two screws seems to offset the reading so for instance I had pH 4 = 900 and pH 7 = 1000 (0 - 1023 range). Turning one of two screws would lower the value a bit, but it never gets below 500 or so.

So what I can do is measure two points (4.0 and 7.0) and their respective measurement values. That way I could calculate points in between, but as far as I know pH is not a linear scale, but logarithmic. If I get this wrong, the reading might seem right but only show 4.0 and 7.0 correct and not the rest of the values (I don't have 10.0 reference fluid at the moment).

Now onto the second screw, that one at first seemed to do nothing. But then I noticed that it sets some kind of threshold value, turning a LED on the board on and off. That LED seems to be linked to the value being read, but it's further purpose? Calibration? No idea.

Ok so best case someone has an equal module and wants to detail how it works. Otherwise maybe some of you have some bright ideas on what I could try in order to get this to work the way I want it to :)

**Update 09-11-2015**

Got feedback from the seller. She sent me the following ZIP: http://1drv.ms/1MSk1DX. It contains some files in Chinese but one had sourcecode in it. Tried it on my Arduino but unfortunately the values still don't make much sense. Depending on how I turn the knob on the print, I get values between 9 and 17 for a liquid that's in real life 7.0. I didn't try but doubt that doing a -7 offset is sensible.

The code itself is pretty straightforward, taking a 6-center average of ten consecutive measures. The interesting lines are these:

     avgValue = 0;
     for (int i=2;i<8;i++)       // take the average value of 6 center sample
       avgValue+=buf[i];

     float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
     phValue=3.5*phValue+Offset;

Maybe someone can make sense of this, because I can't. I don't understand the 5.0 multiplication and the 3.5 after that one. Where do these come from?

Anyway, when I dip the probe into the storage liquid, my normal meter plummets to pH 0.5 whilst the software is giving me 17 (which is a higher value than the one I got from reading my 7.0 liquid). So either my board is broken or this sample code is useless.

Schematics can be found in the ZIP file by the way.

**Update 11-11-2015**

Did some more experimenting. First I found out that the readings from the module increased for more acidic liquid. So I reversed the value by using

    buf[i]=1024 - analogRead(SensorPin);

Ok, now the values made more sense. Then I adjusted the pot to be in the middle of the available range. I dipped the probe in the 7.0 liquid, read the value and adjusted the offset. Then dipped in 4.0, adjusted the pot to match with 4.00, here are the results:

    pH 7.0 reference --> 6.27
    set offset to: 0.73
    pH 4.0 reference --> 5.17
    adjusted the pot so value read 4.0
    pH 7.0 reference --> 5.86

So as I expected, adjusting the pot also messes up the 7.0 reference measurement. I then though it might be because of the slope of the pot (if there would be any), so I went to the lowest value first to have the least difference. Again the readings:

    pH 7.0 reference --> 8.70
    set offset to: -1.70
    pH 4.0 reference --> 5.17
    adjusted the pot so value read 4.0
    pH 7.0 reference --> 5.70

The interesting thing here is that the 4.0 value reads 5.17 in both cases, even though the pot was in a different position. I cannot explain why though.

To make sure the probe is fine I re-calibrated my normal pH meter, operates as usual. This one also has two pots, one for 7.0 calibration and one for 4.0 slope. Calibration is done by setting 7.0, then measuring 4.0 and ajusting the slope pot. Measure 7.0 again, change 7.0 pot, measure 4.0 again, etc. until the values match their liquids. Usually takes me about 3 - 4 loops to get it right.

**Another update**

Took the two containers of reference fluids and started mixing. This gave me measurements in the range of pH 4 - 7.5. Also measured the storage liquid which has a pH of 1.00. Results are in an Excel sheet: http://1drv.ms/1lkAO6e. Next question is how to convert this into a suitable formula?

**Update 18-11-2015**

Working on @slash-dev's solution, here's what I did:

I first turned the pot all the way down to the lowest value. The readings (for pH 7.0) are as follows: low = 540 and high = 1017. Code as follows:

    int rawValue = analogRead(SensorPin);
    int buf[10];                //buffer for read analog

    for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
    {
       buf[i] = rawValue;
       delay(10);
    }

    // sorting left out to reduce the sample length

    int avgValue=0;
    for(int i=2;i<8;i++)  // take the average value of 6 center samples
       avgValue += (buf[i] - CENTER);

In this stage I'm printing the raw value of course.

The shorting of the BNC connector I don't exactly understand, should I short the inside (where the pin goes) or the outside of the connector? And short it to the GND? I used the reference solution instead.

Now I added the formula to determine the voltage. For the low value that reads 0.10. I now put in the center value of 540 which brings the voltage reading to 0.0, seems good.

Now for step 2 I placed the probe into the 4.0 reference solution. The voltage now reads 0.48, raw value 637. I start adjusting the pot to where the voltage reads 2.25, takes quit some adjusting. Raw now reads 1000.

Now comes the part I don't exactly get. You say we can now calculate the pH/V, but with what variables? I mean, -3 / 2.25 will always result in -1.33 but shouldn't there be a variable here depending on how far I actually adjusted the pot?

When I now put in the formula to calculate the pH as expected it reads 4.0 for the 4.0 reference solution. But it now screws up the 7.0 solution as we adjusted the pot but didn't compensate for it as far as I see? I also tried the adjusted pH formulas but I guess those are meant for the first code we had and not this adjusted one.

So what am I missing between step 2 and 3 that messes up things here? Also, you state that the inverting by subtracting from 1024 is correct, but when I do that the voltage readings become minus.

Another thing I wonder about; if the pot has to be a slope, shouldn't it be a different one than the one next to it (where a linear one makes more sense)? Cause it isn't, they both read "W103 / 143C". In the meantime, the vendor is kindly sending over a replacement one to ensure it's not a hardware defect somewhere.

**Next update: :)**

So I now reverted to my original code to try the adjusted pH calculations. I used the 7.0 reference solution to calibrate again and then measured the 4.0 solution. It reads 4.1! Ok, not completely spot on but not bad either. It's a small difference which might as well come from the probe, not the most expensive one.

So I wonder whether we should still try to get the other approach working cause it sounds better (more scientific?) for some reason. Anyway, this is at least a whole lot better than nothing :)

**USB power vs linked?**
Another strange thing seems to happen when I disconnect the Nano from the USB port of my laptop and instead power it via a Raspberry. I want to use I2C to send the value from the Nano to the RPi. This works, but as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

body:
I don't know if this is a complete answer, but I can't comment yet.

The analogRead function in Arduino which is used by your sensor reads values from 0 - 5V. It divides the values between 0 and 5V in 1024 steps. So it returns a value between 0 and 1023. That is why it is multiplied by 5. It is easier to understand if the calculation is done in reverse order. Example:

analogRead returns 512, so that is on 1024 / 512 = 0,5th part of its range. Multiply that by 5.0 to get the actual voltage. 0.5 * 5.0 = 2.5. It is then divided by 6 to get the average.

I would also change the order of the calculation. The comments say that it calculates the average, but it doesn't it just adds the values. It does divide it by 6 eventually so that does not cause the error, but for readability it is generally good practice to let your code do what the comments say.


body:
As a first approach, I'd collect a number of measurements from each of as many knowns as you can find or make, and plot them for a visual clue to the linearity or not (probably not) of the sensor's output vs. pH. You could try to eyeball-fit a curve to the data; interpolate linearly between sample points if you have enough of them; or run a least-squares approximation fit. The key is you'll need enough data - knowns - to make whatever approach you use give results accurate enough for your intended use. (Obviously this will be different if you just need to know if something is acidic or basic, or you're monitoring tropical fish tanks, etc.)

Update:
If your pH meter is good enough for the fish, and if your sensor is reliably repeatable and sensitive enough, why not check your meter against the two standards, then calibrate the sensor to your meter? Once you're happy with the result, lock down the screws with a dab of nail polish (it's not very tamper-proof but it will be tamper-evident). A pH 10.0 standard won't be very useful to you; at that extreme you'll already know the pH is out and you probably won't care about the exact value. You need your precision between the fish-tolerable limits, close to the pH goal.
In fact, if you trust your meter, you don't even need the standards. In that case you need only make up a few samples as you described, covering the pH range of interest, and use them to calibrate your sensor to the meter.


body:
The schematic only shows one trim pot (R23), and it does, as you suspect, set a level for the LED to illuminate.  More of a GOOD/BAD indicator, and is available on pin `DO`.

The other trim pot is not on the schematic.  Is it marked on the board?  R6, R7, R8 or R9 maybe?  It probably controls the gain on `p_AOUT`.

`t_AOUT` is an analog temperature voltage, and appears to measure the temperature of the board.

**Edit - official but totally bogus:** According to my secret source, you are supposed to put the probe in the pH 7.0 reference solution and, with `Offset` defined to be 0.0, run the program and display the calculated pH value.  You may need to decrease the trim pot gain to get smaller (the smallest?) numbers.  Now take that displayed value and modify the `Offset` constant in the sketch to be 7.0 minus the displayed value.  If the displayed value is 8.1,

    #define Offset (-1.1)

Build and upload the modified sketch.  This time, put the probe in your pH 4.0 reference solution and adjust the gain pot until the displayed value is as close to 4.0 as you can get.  This will calibrate it for mostly acidic solutions.

# Edit 1: Iterate?

It's not clear, but I also wondered if this procedure is supposed to be iterated.  Go back to 7 and make sure that adjusting the gain didn't change `Offset`. Then test the pH 4 solution again; the gain pot may require a small(er) change. If it seems to be diverging, um, don't do that. ;)  I think it would diverge only if the probe had an inverted response, which would probably mean it's bad.

If you are measuring basic solutions, do the same procedure with reference solutions of pH 7.0 (of course) and a basic reference solution.

Voilà!

NB: For the 7.0 test, you could short the probe pins together. It really should look like a short circuit when pH == 7.0.  If switching to using the real probe in the pH 7.0 solution gives wildly different readings, the probe _may_ be bad.  If you're able to calibrate it, it _may_ be "good enough".

# Edit 2: Fix the formulas in the provided sketch.

The schematic shows a non-inverting op amp with `PH+` on the input, and `p_AOUT` on the output.  The (adjustable?) gain is

    R9/R8 + 1 = 10k/10k + 1 = 2

The slope of an ideal probe response is -59mV/pH.  You were experimentally getting a negative slope, which agrees with the schematic.  I believe it was correct to "invert" the `analogRead` value by subtracting it from 1024.  There is no way that the provided code could have worked with a positive slope of 3.5.

The reference voltage provided to the the `PH-` pin is half the zener diode voltage... which is unidentified.  It could be the very-common 5.1V part, which is essentially forcing `PH-` to be at

    5.1V/((R6+R7)/R6) = 5.1V/2 = 2.55V

I say probably, because you usually want the plus or minus probe voltage swing to have as much room as possible.  This would imply (an ideal) `analogRead` of pH 7.0 to be

    2.55V/5.0V * 1024 = 522

This is the "center" of the probe swing about pH 7.0.

### Step 1: Determine the reference voltage
At pH 7.0, print out the raw `analogRead` return value, before inverting it.  (The pot wiper should be at it's limit.  Which way, I don't know.  Changing the gain pot shouldn't change the `analogRead` very much at the low-gain end.  If it does change it, turn it to the other extreme.)

As stated before, you can run the pH 7.0 test by shorting the BNC connector pin to the shield or by using your reference solution.  I recommend shorting for now, to eliminate any possible interference from the probe.  It will absolutely determine the offset, but only if the gain is as small as possible.  You have to start here.  Once you know the center reading, you can change the code to display the voltage:

    #define CENTER 522
    int avgValue=0;
    for(int i=2;i<8;i++)  // take the average value of 6 center samples
      avgValue += (buf[i] - CENTER);
    float voltage = (((float)avgValue) / 6.0) * (5.0 / 1024.0);

Print this out.  You'd better get something close to 0.0... don't make me come over there.  :)

### Step 2: Set the gain pot.
This is determining the slope, but you need to maximize the swing for the most extreme pH you want to read, say 4.0.  Using the 4.0 reference solution, adjust the gain pot so that the displayed voltage is close to +2.5V, say +2.25V to make sure it's not pegged at 1024.  (Let's see, slope is negative, 4.0 is < 7.0, so voltage should increase...)  With that reading, you can calculate the pH/V:

    -3pH/2.25V  =  -1.33 pH/V

### Step 3: Calculate and print pH
Modify the original computation to use the pH/V slope:

    float phValue = voltage * (-1.33) + 7.0;

This is not even close to `phValue = 3.5*voltage + Offset`.  -\_-    I have found several source now that echo my original answer.  Totally wrong, and wrong to the point of misleading.  I do think these steps will do it.  It sounds good in my head, anyway.  :D

# Edit 3: "Next question is how to convert this into a suitable formula?"

Ok, if you don't want to fix the formula in the code, you can fit a linear or quadratic curve to your data.  Linear is actually recommended as "good enough", and that is effectively the change suggested in **Edit 2**.  If we just use your data points, though, this would be the linear approximation:

    float adjustedPh = phValue * 1.627 - 2.499;

...and the quadratic approximation:

    float adjustedPh = (-0.01796 * phValue + 1.8056) * phValue - 2.94;


body:
I can't ask a question but make sure you're giving it enough power for the heating element, its not much but you never know try a separate power source if you are not.

Now you mentioned the nano, are you using a 3.3v nano or 5V nano?  (the regulator would have a 33 or 50 on it after a letter or two)  if 3.3V and assuming by example code they give the analog output is 5V you'll need a level shifter of sorts to map to 3.3V, then change the calculations to use 3.3 instead of 5 value.    if that's not the case and it's not power or connections then it may be broke or the probe etc.... there's a few variables.


body:
> **USB power vs linked**

Just to add my 2 cents on your latest update about the USB or 5V from the PI.

You say you connect it to the VIN:

> as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

If you look at the below image you see that Vin goes to a good old 7805, which needs a IN voltage > 7.5V, thus the output when its connected to the 5V of the PI is going to be very low and thus mess up readings.

![enter image description here][1]

I recommend you connect your ***power from the PI to the arduino's VCC*** as this is a regulated 5v and doesn't need to be regulated again.

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


message:
How to simulate delay() to debounce mechanical button using millis()?

Im trying to use the millis() function as a replacement for the delay() function in order to debounce a mechanical button. This is for an electric drum kit I am building. Im using a teensy Arduino to send MIDI signals from the drum pads to an external music program. The mechanical button needs to be responsible for cycling through five different states which change the MIDI signal sent from each pad, thus changing the sound, as well as lighting up one of five LEDs on my drum pad so I know which state i'm in.  However I cant use delay() to debounce the button because that effects the efficiency of the drum pads, with some hits not being registered, latency etc.

Im trying to debug the code by just getting the LEDs to light up correctly when I press the button. This was the original code I wrote with the delay() function. This worked perfectly to debounce the button, but messed with my drum pads:

    int but = 12;
    int led0 = 7;
    int led1 = 8;
    int led2 = 9;
    int led3 = 10;
    int led4 = 11;

    int ledCase = 0;
    int butState = 0;
    int oldButState = 0;

    void setup()   {
    pinMode(led0, OUTPUT);
    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(led4, OUTPUT);
    pinMode(but, INPUT_PULLUP);
    }

    void loop()    {

       oldButState = digitalRead(but);
       delay(10);
       butState = digitalRead(but);

       if (butState != oldButState && butState == LOW) {
         ledCase += 1;
         oldButState = butState;
       }

       if (ledCase > 4) {
        ledCase = 0;
       }

       Serial.println(ledCase);

    switch (ledCase) {
    case 0:
    digitalWrite(led0, HIGH);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    break;
    case 1:
    digitalWrite(led0, LOW);
    digitalWrite(led1, HIGH);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    break;
    case 2:
    digitalWrite(led0, LOW);
    digitalWrite(led1, LOW);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    break;
    case 3:
    digitalWrite(led0, LOW);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, HIGH);
    digitalWrite(led4, LOW);
    break;
    case 4:
    digitalWrite(led0, LOW);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, HIGH);
    break;
    }
    }

This is what I tried to use to replace the delay() function, but that hasn't worked. Note I added these lines in and removed the delay section:

    unsigned long onTime;
    unsigned long delayTime;

    void setup() {
    delayTime = millis() + 10;
    }

    void loop()    {
    oldButState = digitalRead(but);
    onTime = millis();
    if (onTime >= delayTime) {
    butState = digitalRead(but);
    delayTime = millis() + 10;
    }
    }

Any pointers as to how I can make the millis() function work to debounce this would be would be very much appreciated, thank you :)

body:
To better understand how you can do this it is good to understand first just what goes on when a button bounces.

It is, literally, bouncing - just like a ball when you drop it.  Due to the fact that it's either connected to ground or pulled up to +5V by the pullup resistor it's either going to be LOW or HIGH with very little time between when it's not in either state, so we can pretty much ignore the rise and fall times of the signal.  It's either connected to ground, or it's not connected to ground.  And we're only really interested in when it's connected to ground.

More importantly we're interested in *how long* it's been connected to ground for.

By remembering the time it transitioned from HIGH to LOW and then comparing that time to the current time you can know how long it has been connected to ground.  By noticing when it's no longer connected to ground and "forgetting" the time you remembered you can start counting afresh with the next transition from HIGH to LOW.

Take the following diagram for instance:

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

The blue line is the state of the button.  As you can see it starts HIGH, then it gets pressed to be LOW and bounces between HIGH and LOW a number of times before it settles on being LOW.

The red line is the difference between a timestamp that is set to be equal to `millis()` at the moment the button transitions from HIGH to LOW and the current `millis()` value, and is ignored when the button is HIGH.  As you can see the difference between that timestamp and the current `millis()` value steadily increases. Whenever the button bounces to the HIGH state it resets that difference, and it starts again with the next LOW transition.

When the button has finished bouncing there is nothing to change the state of the timestamp, so the difference keeps increasing.  Eventually that difference will pass a trigger point (the yellow line in this diagram) and at that point you can be fairly sure that the button has finished bouncing and you should react to it.

To translate that into some code, you may end up with something like this (untested):

    // Two variables to store remembered state information - the time
    // of the last HIGH-LOW transition and the previous state of the
    //  button.
    static uint32_t debounceTime = 0;
    static uint8_t buttonState = HIGH;

    // Check to see if the button has changed state
    if (digitalRead(buttonPin) != buttonState) {
        // Remember the new state
        buttonState = digitalRead(buttonPin);
        // If the new state is LOW ...
        if (buttonState == LOW) {
            // ... then record the time stamp
            debounceTime = millis();
        } else {
            // ... otherwise set the time stamp to 0 for "don't care".
            debounceTime = 0;
        }
    }

    // If the time stamp is more than 0 and the difference between now and
    // then is greater than 10ms ...
    if (debounceTime > 0 && (millis() - debounceTime > 10)) {
        // ... set the time stamp to 0 to say we have finished debouncing
        debounceTime = 0;
        // and do whatever it is you need to do.
        digitalWrite(ledPin, HIGH);
    }

There are various tweaks and additions that could be made to that method, but that gives you the basic idea of how you split the debouncing away from the reacting, and it's the *results* of the debouncing that you react to, not the button state itself.

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


body:
Actually, Majenko's diagram assumes the interplay of the pullup resistor forces the line back to a HIGH position (as quickly as the internal transistors can overpower the drop from the switch).  If the switch itself is mechanical with a pullup resistor (external or internal), then the only thing "bouncing" is the switch.  If you use a digital switch, the rise is much sharper without significant bounce.

A cheap and effective debouncing tactic is to add a capacitor in parallel with the switch.  The cap will drop to GND quickly as the switch drains the charge stored in the cap.  But the cap will take a while to recharge since its only source is through the resistor (during which time the mechanicals settle down).  (This looks much better in a diagram, but I haven't figured out how to draw on here yet.) I wish I could recommend values, but it really depends on the mechanicals of the switch and the certainty of the debounce desired--make everything HUGE and you're guaranteed no bounce, use values in between and you go on probabilities.  I usually start out with 0.1uF and vary it up or down until I get a balance between reliability and speed.

The main advantage is, of course, you use absolutely no computing time to debounce any number of switches.

Potential disadvantages:

 - Added hardware cost for each switch, making this technique less desirable in production scenarios

 - 0/1 thresholds of input pins will vary across the manufacturing process, so one cap / input pin may have a different debounce time than another on an identical circuit.

 - Software debouncing schemes can note that the switch is pushed on the first drop to GND, where this hardware-only tactic relies on the last actual contact with GND.  As the switch ages, I've seen this delay exceed 50 mSec.

 - Since the bounce is mechanical at its core, bounce worsens over the life of the mechanical part (in this case the switch).  Typically, software can be fine-tuned easier than hardware. Often, however, swapping out a cap is easier than reflashing firmware.


message:
Pro Micro Voltage regulator burned

I'm using Arduino Pro Micro (5v version) in one of my project for my car. The car's 12V +ve connected to RAW input of ProMicro and everything seems to work perfectly until I crank the ignition of my car.
Here's what actually happened, my circuit works perfectly fine when car's ignition is in ON state. However, as soon as I started my car the voltage dropped from 12v to between 9-10volt and the LG33 (SMD voltage regulator) burned out. Now, I want a good solution as what should I do now?
I have already LM2596 DC 3A Step-Down regulator. So should I use that to step-down 12v to 5v OR is there anything else I can do which might be a better solution?

body:
What happened was the ignition caused massive spikes on the 12V power. You require an automotive grade regulator that can cope with spikes in excess of around 70V or more.

Your best bet is probably a car USB charger adapter since they are cheap and easy to get hold of.


message:
Arduino Mega 2560 multiple slave via SPI

I'm new to Arduino and microcontroller . I want to connect my Arduino Mega to three slaves which Arduino Unos. I know that these slaves will share MISO, MOSI, and SCK lines. However, SS is unique to each slave.

For single slave, the SS is pin 53. So, for three slaves, which other two pins can I use as SS?

Thank you for your help.

body: Any you like. There's nothing magic about them, as long as you have the main SS pin as an output to ensure the SPI port is in master mode.


body:
You can use any pin for the Slave Select. The SS pin on the Arduino is only used as SS when the arduino is an SPI slave, not (like in your case) when it's the master. The only thing you have to take care of is to not use the SS pin as an Input.

Just make sure the library you are using allows you to specify your own SS output pin.


message:
Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?

I have a simple set of 8 push buttons wired to a Teensy 3.2 board (which uses Arduino via Teensyduino plugin). The 8 buttons are on pins 1-8 and their common ground line (one line soldered to each of them) is on the GND pin. I have code to get any one button working that works. It's currently set to make pressing the second button type "A."

I'd like to make push buttons 1 through 8 type out A,B,C...etc respectively as you press them. I've been told of two problems with my setup, the first being that copying the code for every button is a bad way to go about it and second that it's subject to bouncing issues (creates a keystroke once every 5 presses or so.) I'd also like to set this up so in the future I can write a 3rd party app that configures the keys based on the user's preference.

Adding those needs up I'm not sure where to go next. I'm beginner enough that I'm not sure how to properly incorporate the bounce class or if that's the right way to go given the needs.

Is a matrix the way to go or is there an elegant way to manual set each button and compensate for bounce? I'd really appreciate a small example if anyone has done this. Thanks~ Current code follows:

    #define CHECK_EVERY_MS 20
    #define MIN_STABLE_VALS 5

    unsigned long previousMillis;
    char stableVals;
    char buttonPressed;

    void setup() {
      // make pin 2 an input and turn on the
      // pullup resistor so it goes high unless
      // connected to ground:
      pinMode(2, INPUT_PULLUP);
      Keyboard.begin();
    }

    void  loop() {
        if ((millis() - previousMillis) > CHECK_EVERY_MS)
        {
            previousMillis += CHECK_EVERY_MS;
            if (digitalRead(2) != buttonPressed)
            {
                stableVals++;
                if (stableVals >= MIN_STABLE_VALS)
                {
                    buttonPressed = !buttonPressed;
                    stableVals = 0;

                    if (buttonPressed)
                    {
                        //Send an ASCII 'A',
                        Keyboard.write(65);
                    }
                }
            }
            else
                stableVals = 0;
        }
    }

**-------**
**Edit: WORKING CODE FOLLOWS**

    /*  jw - 3 Nov 2015 - Program for button debounce demo
    Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
    */

    //--------------------------------------------------------
    enum { sw0=3, sw1=4, sw2=5, sw3=6, sw4=7, sw5=8, sw6=9, sw7=10}; // Switchbutton lines
    enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
    struct ButtonStruct {
      unsigned long int bounceEnd;  // Debouncing-flag and end-time
      // Switch number, press-action, release-action, and prev reading
      byte swiNum, swiActP, swiActR, swiPrev;
    };

    struct ButtonStruct buttons[nSwitches] = {
      {0, sw0, 'A'},
      {0, sw1, 'B'},
      {0, sw2, 'C'},
      {0, sw3, 'D'},
      {0, sw4, 'E'},
      {0, sw5, 'F'},
      {0, sw6, 'G'},
      {0, sw7, 'H'}};
    //--------------------------------------------------------
    void setup() {
      for (int i=0; i<nSwitches; ++i)
        pinMode(buttons[i].swiNum, INPUT_PULLUP);
    Keyboard.begin();
    }
    //--------------------------------------------------------
    byte readSwitch (byte swiNum) {
      // Following inverts the pin reading (assumes pulldown = pressed)
      return 1 - digitalRead(swiNum);
    }
    //--------------------------------------------------------
    void doAction(byte swin, char code, char action) {
      Keyboard.write(action);
    }
    //--------------------------------------------------------
    void doButton(byte bn) {
      struct ButtonStruct *b = buttons + bn;
      if (b->bounceEnd) { // Was button changing?
        // It was changing, see if debounce time is done.
          if (b->bounceEnd < millis()) {
        b->bounceEnd = 0;    // Debounce time is done, so clear flag
        // See if the change was real, or a glitch
        if (readSwitch(b->swiNum) == b->swiPrev) {
          // Current reading is same as trigger reading, so do it
          if (b->swiPrev) {
            doAction(b->swiNum, 'P', b->swiActP);
          } else {
            doAction(b->swiNum, 'R', b->swiActR);
          }
        }
          }
      } else {  // It wasn't changing; but see if it's changing now
        if (b->swiPrev != readSwitch(b->swiNum)) {
          b->swiPrev = readSwitch(b->swiNum);
          b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
        }
      }
    }
    //--------------------------------------------------------
    long int seconds, prevSec=0;
    void loop() {
      for (int i=0; i<nSwitches; ++i)
        doButton(i);
    }

body:
I'm not sure what you mean by “Is a matrix the way to go”, so will ignore that question.

Shown below is a way of using an array of structs (one of C's ways of organizing a collection of items) to keep data for several buttons, such that it's straightforward to use one subroutine to process each button the same way, using a for-loop to call the routine for each button.

Each element of the array `buttons` is a `ButtonStruct`, and each `ButtonStruct` contains five items: bounceEnd, swiNum, swiActP, swiActR, swiPrev, which respectively represent a debouncing-flag and end-time; a switch number [ie a pin number]; a code for action to take on a press; a code for action to take on a release; and previous state of button.  (In many special cases, some of these items will be irrelevant and you can leave them out of the `ButtonStruct`.)  The form `b->x` that is used in the `doButton()` routine says to access element `x` of the struct that `b` points to.

At the start of each `loop()` pass, `doButton()` is called once for each button.  It first tests if debouncing was underway for the button.  If so, it sees if enough time has gone by to suppose button bounce is over.  If so, it reads the button's state, and if different from previous state, does an action for whichever way the button changed.  (If the button state is unchanged after a debounce delay, the program supposes there was a glitch.)  If debouncing was not underway, the program checks if the button state is different from most recent pass.  In that case, it sets up a debounce test for the button.

The buttons are tested and debounced individually, as you can see in the sample output that is shown following the program.  (This program was tested on an Uno, with four independent buttons used in the test. *Edit: Made corrections to handle 32-bit overflow, 2016.10.17*)

    /*  jw - 3 Nov 2015 - Program for button debounce demo
    Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
    */

    //--------------------------------------------------------
    enum { sw0=8, sw1=9, sw2=10, sw3=11}; // Switchbutton lines
    enum { nSwitches=4, bounceMillis=42}; // # of switches; debounce delay
    struct ButtonStruct {
      unsigned long int bounceGo; // Debouncing-flag and end-time
      // Switch number, press-action, release-action, and prev reading
      byte swiNum, swiActP, swiActR, swiPrev;
    };

    struct ButtonStruct buttons[nSwitches] = {
      {0, sw0, 'A','a', 0}, {0, sw1, 'B','b', 0}, {0, sw2, 'C','c', 0}, {0, sw3, 'D','d', 0}};
    //--------------------------------------------------------
    void setup() {
      for (int i=0; i<nSwitches; ++i)
        pinMode(buttons[i].swiNum, INPUT_PULLUP);
      Serial.begin(115200);
      Serial.println("Starting");
    }
    //--------------------------------------------------------
    byte readSwitch (byte swiNum) {
      // Following inverts the pin reading (assumes pulldown = pressed)
      return 1 - digitalRead(swiNum);
    }
    //--------------------------------------------------------
    void doAction(byte swin, char code, char action) {
      Serial.print("Switch ");
      Serial.print(swin);
      Serial.print(code);
      Serial.print(' ');
      Serial.print(action);
      Serial.print(" at t=");
      Serial.print(millis());
      Serial.println();
    }
    //--------------------------------------------------------
    void doButton(byte bn) {
      struct ButtonStruct *b = buttons + bn;
      if (b->bounceGo) { // Was button changing?
        // It was changing, see if debounce time is done.
          if (millis() - b->bounceGo > bounceMillis) {
     b->bounceGo = 0;    // Debounce time is done, so clear flag
     // See if the change was real, or a glitch
     if (readSwitch(b->swiNum) == b->swiPrev) {
       // Current reading is same as trigger reading, so do it
       if (b->swiPrev) {
         doAction(b->swiNum, 'P', b->swiActP);
       } else {
         doAction(b->swiNum, 'R', b->swiActR);
       }
     }
          }
      } else {  // It wasn't changing; but see if it's changing now
        if (b->swiPrev != readSwitch(b->swiNum)) {
          b->swiPrev = readSwitch(b->swiNum);
          b->bounceGo = millis(); // Set the Debounce flag
        }
      }
    }
    //--------------------------------------------------------
    long int seconds, prevSec=0;
    void loop() {
      for (int i=0; i<nSwitches; ++i)
        doButton(i);
    }

In the sample output below, a P line indicates a button press, detected at given `millis()` time, and an R line indicates a button release.   Observe, near the end, overlaps among separate button presses and releases.

    Starting
    Switch 8P A at t=2170
    Switch 8R a at t=2322
    Switch 9P B at t=2789
    Switch 9R b at t=2969
    Switch 10P C at t=3395
    Switch 10R c at t=3562
    Switch 11P D at t=4087
    Switch 11R d at t=4260
    Switch 11P D at t=6518
    Switch 10P C at t=6961
    Switch 8P A at t=7070
    Switch 10R c at t=7112
    Switch 11R d at t=7427
    Switch 8R a at t=7598
    Switch 10P C at t=8502
    Switch 9P B at t=8642
    Switch 10R c at t=8961
    Switch 9R b at t=9054
    Switch 9P B at t=9954
    Switch 11P D at t=10073
    Switch 8P A at t=10164
    Switch 8R a at t=10215
    Switch 9R b at t=10315
    Switch 11R d at t=10354


message:
Timer interrupt won't work if the ISR is not set

I am using an Arduino Mega 2560.

I have a code in a c file, that looks like this:

        #include <avr/io.h>             /* for DDRB, PORTB, etc. */
    #include <util/delay.h>         /* for _delay_ms () */
    #include <arduino.h>

    int main(void){
      DDRB    |= ((1 << DDB7)); // Define pin 13 as output

      noInterrupts();

    //set timer1 interrupt at 1Hz
      TCCR1A = 0;// set entire TCCR1A register to 0
      TCCR1B = 0;// same for TCCR1B
      TCNT1  = 0;//initialize counter value to 0
      // set compare match register for 1hz increments
      OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
      // turn on CTC mode
      TCCR1B |= (1 << WGM12);
      // Set CS12 and CS10 bits for 1024 prescaler
      TCCR1B |= (1 << CS12) | (1 << CS10);
      // enable timer compare interrupt
      TIMSK1 |= (1 << OCIE1A);
      interrupts();

      while(1){
            asm("nop");
      }
    return 0;
    }

      ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
    {
      PORTB ^= ((1 <<  PB7));   // toggle LED pin
      PINB |= _BV(7);
      PINB = PINB | _BV(7);
    }

Which is called from an ino file, like this:

        extern "C"
     {
     void foo ();
     }

    void setup ()
      {
      foo ();
      }  // end of setup

    void loop ()
      {
      }  // end of loop

However, if I set up another timer interrupt (ex Timer Interrupt 0 or 2, the blink will stop happening, for some reason...

For example:

    //set timer0 interrupt at 2kHz
      TCCR0A = 0;// set entire TCCR2A register to 0
      TCCR0B = 0;// same for TCCR2B
      TCNT0  = 0;//initialize counter value to 0
      // set compare match register for 2khz increments
      OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
      // turn on CTC mode
      TCCR0A |= (1 << WGM01);
      // Set CS01 and CS00 bits for 64 prescaler
      TCCR0B |= (1 << CS01) | (1 << CS00);
      // enable timer compare interrupt
      TIMSK0 |= (1 << OCIE0A);

Now, the strangest part happens that if all the three (or just the same two) timer interrupts are set, and with everything defined in the INO file, it works fine...

    //this code will enable all three arduino timer interrupts.
    //timer0 will interrupt at 2kHz
    //timer1 will interrupt at 1Hz
    //timer2 will interrupt at 8kHz

    //storage variables
    boolean toggle0 = 0;
    boolean toggle1 = 0;
    boolean toggle2 = 0;

    void setup(){

      //set pins as outputs
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(13, OUTPUT);

    cli();//stop interrupts

    //set timer0 interrupt at 2kHz
      TCCR0A = 0;// set entire TCCR2A register to 0
      TCCR0B = 0;// same for TCCR2B
      TCNT0  = 0;//initialize counter value to 0
      // set compare match register for 2khz increments
      OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
      // turn on CTC mode
      TCCR0A |= (1 << WGM01);
      // Set CS01 and CS00 bits for 64 prescaler
      TCCR0B |= (1 << CS01) | (1 << CS00);
      // enable timer compare interrupt
      TIMSK0 |= (1 << OCIE0A);

    //set timer1 interrupt at 1Hz
      TCCR1A = 0;// set entire TCCR1A register to 0
      TCCR1B = 0;// same for TCCR1B
      TCNT1  = 0;//initialize counter value to 0
      // set compare match register for 1hz increments
      OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
      // turn on CTC mode
      TCCR1B |= (1 << WGM12);
      // Set CS12 and CS10 bits for 1024 prescaler
      TCCR1B |= (1 << CS12) | (1 << CS10);
      // enable timer compare interrupt
      TIMSK1 |= (1 << OCIE1A);

    //set timer2 interrupt at 8kHz
      TCCR2A = 0;// set entire TCCR2A register to 0
      TCCR2B = 0;// same for TCCR2B
      TCNT2  = 0;//initialize counter value to 0
      // set compare match register for 8khz increments
      OCR2A = 249;// = (16*10^6) / (8000*8) - 1 (must be <256)
      // turn on CTC mode
      TCCR2A |= (1 << WGM21);
      // Set CS21 bit for 8 prescaler
      TCCR2B |= (1 << CS21);
      // enable timer compare interrupt
      TIMSK2 |= (1 << OCIE2A);

    sei();//allow interrupts

    }//end setup

    ISR(TIMER0_COMPA_vect){//timer0 interrupt 2kHz toggles pin 8
    //generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles for full wave- toggle high then toggle low)
      if (toggle0){
        digitalWrite(8,HIGH);
        toggle0 = 0;
      }
      else{
        digitalWrite(8,LOW);
        toggle0 = 1;
      }
    }

    ISR(TIMER1_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
    //generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)
      if (toggle1){
        digitalWrite(13,HIGH);
        toggle1 = 0;
      }
      else{
        digitalWrite(13,LOW);
        toggle1 = 1;
      }
    }

    ISR(TIMER2_COMPA_vect){//timer1 interrupt 8kHz toggles pin 9
    //generates pulse wave of frequency 8kHz/2 = 4kHz (takes two cycles for full wave- toggle high then toggle low)
      if (toggle2){
        digitalWrite(9,HIGH);
        toggle2 = 0;
      }
      else{
        digitalWrite(9,LOW);
        toggle2 = 1;
      }
    }

    void loop(){
      //do other things here
    }

Is anybody able to explain why it works in the first case, doesn't work in the second, and in the third, it works as well?

body:
I found out that it's not enough to just define the interrupts, there must also be an ISR method with the compare vector...

      ISR(TIMER0_COMPA_vect)          // timer compare interrupt service routine
    {
      PORTB ^= ((1 <<  PB6));   // toggle LED pin
      PINB |= _BV(6);
      PINB = PINB | _BV(6);
    }

There was no error at compile, though.


message:
Horse racing game

Basically i would like to create a horse racing game, (5 horses starting all to a point A and finishing in a random position to a point B).

I did an animated GIF for you to understand it more clearly :

https://i.stack.imgur.com/oOZvB.jpg

This exactly what i want to do, but in real.

I was thinking of using 5 motors (one for each horse) with a string they pull where the horse is attached on it (like this : https://www.youtube.com/watch?v=NjuoCS9-pCY), and to create randomness at each race, do a random speed for each motors every 1 or two seconds and then stop when each horse hit the finishing line (by pushing a sensor ?). Finally when all horses hit the finishing line, the motors goes backward and get the horses back to the start line.

The horses will be tiny like 1 inch (2.5cm) and the distance from start to finish line will be like 20inch (50cm) and i need the race to last at least 5-10 sec so motors don't need to turn too fast.

I don't know if it is the best way or if it is even possible (and how ? with what components?)

I have been searching for solutions to my project but didn't found anything suitable yet so here i am..

Thank you a lot for you help

body: If it is going to be tiny, I would use continuous rotation servos and rubber belts. They are nice because you dont need motor drivers, unlike stepper motors. Also they consume a lot less power than stepper motors, so you may not need to attach them to external power (not just the arduino 5v). However, because you can not control how far they move, you will need buttons at the end of the race. I think you can get them from Adafruit.


message:
Circuit doesn't work when multimeter/current meter is attached

I'm working on a battery-powered data logger, using a bare Atmega 328. I'm using sleep between sensor readings, via the Narcoleptic library. Everything seems to work fine, until I connect my multimeter to check on the current.

The multimeter uses manual range-setting (i.e., not autoranging). If I set the multimeter to the 0-20 mA range, I can see that my idle current is about 0.250 mA, but the upper value is off-scale. If I try to get a reading on the 0-200 mA range, the circuit misbehaves, never goes into sleep, and doesn't record any data. The current stays constant somewhere around 14-20mA.

Do I need to do something special to accurately measure current in the range of 0.25-40+mA? Or do I need a different kind/quality of multimeter?

My multimeter is a $15 digital unit from Circuit Test, model DMR-1100A.

body:
If your tester has autorange function, you have to disable it, as it can interfere with normal operations by changing the internal shunt resistor.

Did you configure the meter as current meter, DC, connected in series between the power supply/battery and the rest of the circuit?

The tester might give a poor reading at low current values but it shouldn't interfere(much) with the circuit itself.


body:
Multimeters have something called a "burden voltage". See this PDF: [uCurrent - A professional precision current ... - EEVblog](http://www.eevblog.com/files/uCurrentArticle.pdf).

Also see Dave Jones' video: [µCurrent](https://www.youtube.com/watch?v=i069j6S80OU)

Meters measure current by dropping voltage over an internal resistor, and measuring the drop. By definition therefore, there is a voltage drop, which is the "burden voltage".

>  the circuit misbehaves, never goes into sleep, and doesn't record any data

If you put a voltmeter on the processor side of the ammeter you will probably find that the voltage going into your processor is somewhat less than you think. That would account for the misbehaving.

One possible approach is to crank up the voltage from your power source, checking the voltmeter to see that it reaches the expected voltage on the **processor** side of the ammeter, however in a circuit which might turn on and off (ie. sleep) this voltage might jump around (depending on the current) so this should be done with caution (to not exceed the maximum processor voltage).

---

> Or do I need a different kind/quality of multimeter?

A higher quality meter may well help - watch that video and look at the PDF to see what I am talking about. My meters (which cost more than $15) don't have this problem to the same extent.


message:
Arduino UNO with Sparkfun MP3 Trigger

I have a basic mp3 trigger with arduino uno setup:

Trigger - https://www.sparkfun.com/products/11029

Arduino Uno code:

    #include <MP3Trigger.h>

    //  Script Function:  RobertSonics mp3trigger (v2) paired with an Arduino UNO
    //
    //  Jumper Connections:   UNO  ------  mp3trigger (v2)
    //             (UNO RX)     0  ------  TX
    //             (UNO TX)     1  ------  RX
    //             (Ground)   GND  ------  GND
    //           (+5 volts)    5v  ------  USBVCC

    #include <SoftwareSerial.h>
    void setup(){
        Serial.begin(38400);    // Standard for mp3trigger
        Serial.print("t");
        Serial.write(1);
        delay(50000);
    }

    void loop()
    {

    }

I can't get it to play any tracks. The response in the Serial monitor just says tt

body:
So, from the beginning:

 1. Have you got data on you SD card and is it is FT16 or FAT32 format?
 2. Is the MP3 status light giving any indication of life?
 3. Does the MP3 card detect when you start it up without the SD card in (One long flash).
 4. Do you have a data file named "001SomethingOrOther.MP3"?
 5. Have you tried the command "v" 0x00?
 6. Have you tried the commands "S0" and "S1"?
 7. Have you looked at the sample data on http://robertsonics.com/mp3-trigger-support/?

Hope that helps, an please post your finding, because mine arrives next week :)


body:
Finally I got it working yesterday, and by accident!!!! Sorry it was not sooner, hope you had better luck with it. In any case if anyone wants to know what I did, you can read about it here.
https://forum.sparkfun.com/viewtopic.php?f=14&t=44292


message:
Regulation of the temperature using PID

I'm making a control system for the heating of a plate using a PID control.

the goal is to regulate the temperature of the plate by changing the power dissipated by the resistance. By using a sensor I read the temperature  of the plate and is then used as the input in the PID control.
I programmed also a signal wave square for the PWM.

but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive.
and I cannot connect between the PWM and the PID.

Code of the square signal:

    void setup()
    {
      pinMode(9, OUTPUT);
    }
    void loop()
    {
       // phase haute
       digitalWrite(9,HIGH);
       delay(30);
       // phase basse
       digitalWrite(9,LOW);
       delay(70);
       //ton+toff = 0.1;
    //   ton = 0.1*Output;
    }

 Code of PID and the sensor

    /********************************************************
     * PID Basic Example
     * Reading analog input 0 to control analog PWM output 3
     ********************************************************/

    #include <PID_v1.h>

    int val;
    //Define Variables we'll be connecting to
    double Setpoint, Input, Output;

    //Specify the links and initial tuning parameters
    PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);

    void setup()
    {
      Serial.begin(9600);
      //initialize the variables we're linked to
      Input = analogRead(1);
      Setpoint = 37; //temperature a reguler

      //turn the PID on
      myPID.SetMode(AUTOMATIC);
    }

    void loop()
    {
      val = analogRead(1);
      float mv = ( val/1024.0)*5000;
      float Input = mv/10;
      myPID.Compute();
      analogWrite(3,Output);
      Serial.print("input temperature is :");
      Serial.println(Input);
      delay (1000);
    //  delay(1000);
      Serial.print("output is :");
      Serial.println(Output);
      delay(1000);
    }

Thank you in advance

body:
A PID only has one input and one output. In your case, the input will be the temperature. The use of the arduino would be to process the raw data of the temperature sensor and relay the temperature to the PID. Depending on the make and model of the PID, there could be certain transfer protocols you must adhere to. There are most likely open source libraries that will take care of transferring the data properly.

Your PID is the piece of hardware that will "decide" when it is appropriate to turn the heater on and off, therefore it shall be responsible for driving the heater. That is what the output of the PID is responsible for.

Lastly, your PID has a set point. In your case, the set point would be the desired max temperature of the plate. This set point is set and altered manually through user input.

On a side note, if this is a personal project or a non deliverable, I'd recommend not using a PID. Try processing and analyzing all of the data exclusively on the Arduino, as it would be a challenging and rewarding task.


message:
Arduino W5100 AVR

I'm trying to use a W5100 Arduino Ethernet Shield on a ATMega2560 using avr code.

There exists a library written in C, which should work http://www.seanet.com/~karllunt/w5100_webserv.zip from http://www.seanet.com/~karllunt/w5100_library.html

The w5100_webserv.c should be a working example for an ATmega644p. He mentions that the four callback functions should be modified, namely my_select(), my_deselect(), my_xchg() and my_reset()

The w5100_webserv.c also contains the following definitions for SPI_PORT/DDR CS_PORT/DDR/BIT and RESET_PORT/DDR/SPI:

 /*
 *  Define the SPI port, used to exchange data with a W5100 chip.
 */
 #define SPI_PORT     PORTB                /* target-specific port containing the SPI lines */
 #define SPI_DDR      DDRB                /* target-specific DDR for the SPI port lines */

 #define CS_DDR        DDRD                /* target-specific DDR for chip-select */
 #define CS_PORT     PORTD                /* target-specific port used as chip-select */
 #define CS_BIT        2                    /* target-specific port line used as chip-select */

 #define RESET_DDR   DDRD                /* target-specific DDR for reset */
 #define RESET_PORT    PORTD                /* target-specific port used for reset */
 #define RESET_BIT    3                    /* target-specific port line used as reset */

I've changed it to the following according to what i think the ATmega2560's datasheet specifies

    /*
     *  Define the SPI port, used to exchange data with a W5100 chip.
     */
    #define SPI_PORT     PORTB                /* target-specific port containing the SPI lines */
    #define SPI_DDR      DDRB                /* target-specific DDR for the SPI port lines */

    #define CS_DDR        DDRB                /* target-specific DDR for chip-select */
    #define CS_PORT     PORTB                /* target-specific port used as chip-select */
    #define CS_BIT        10                  /* target-specific port line used as chip-select */

    #define RESET_DDR   DDRB                /* target-specific DDR for reset */
    #define RESET_PORT    PORTB                /* target-specific port used for reset */
    #define RESET_BIT    20                   /* target-specific port line used as reset */

Furthermore, in the main(), there are also specific code for the AT644p:

    /*  * Initialize the ATmega644p SPI subsystem */
    CS_PORT |= (1<<CS_BIT);                                    // pull CS pin high
    CS_DDR |= (1<<CS_BIT);                                    // now make it an output

    SPI_PORT = SPI_PORT | (1<<PORTB4);                        // make sure SS is high
    SPI_DDR = (1<<PORTB4)|(1<<PORTB5)|(1<<PORTB7);            // set MOSI, SCK and SS as output, others as input
    SPCR = (1<<SPE)|(1<<MSTR);                                // enable SPI, master mode 0
    SPSR |= (1<<SPI2X);                                        // set the clock rate fck/2

I've changed it to the following according to what i think the ATmega2560's datasheet specifies

    /*
     *  Initialize the ATmega2560 SPI subsystem
     */
    CS_PORT |= CS_BIT;                                    // pull CS pin high
    CS_DDR |= CS_BIT;                                    // now make it an output

    SPI_PORT = SPI_PORT | (1<<PORTB0);                        // make sure SS is high
    SPI_DDR = (1<<PORTB0)|(1<<PORTB2)|(1<<PORTB1);            // set MOSI, SCK and SS as output, others as input
    SPCR = (1<<SPE)|(1<<MSTR);                                // enable SPI, master mode 0
    SPSR |= (1<<SPI2X);                                        // set the clock rate fck/2

Lastly i've changed the my_reset() function:
    void  my_reset(void)
    {
        RESET_PORT |= RESET_BIT;                            // pull reset line high
        RESET_DDR |= RESET_BIT;                            // now make it an output
        RESET_PORT &=~RESET_BIT;                            // pull the line low
        _delay_ms(5);                                            // let the device reset
        RESET_PORT |= RESET_BIT;                            // done with reset, pull the line high
        _delay_ms(10);                                            // let the chip wake up
    }

I am not sure whether my changes are 100 % correct and i don't know what changes needs to be done to my_select() my_deselect and my_xchg. I hope someone can suggest som corrections.

Thanks in advance.

body:
I've managed to specify the correct ports and bits in order to make the library function on the Arduino ATmega2560 using their Ethernet Shield.

The SPI port definitions has to be changed to the following:

 #define SPI_PORT  PORTB    /* target-specific port containing the SPI lines */
 #define SPI_DDR   DDRB    /* target-specific DDR for the SPI port lines */

 #define CS_DDR  DDRB    /* target-specific DDR for chip-select */
 #define CS_PORT  PORTB    /* target-specific port used as chip-select */
 #define CS_BIT  4     /* target-specific port line used as chip-select */

 #define RESET_DDR   DDRB    /* target-specific DDR for reset */
 #define RESET_PORT PORTB    /* target-specific port used for reset */
 #define RESET_BIT 8     /* target-specific port line used as reset */

The section about the AT644p in the main() function has to be changed to the following:

 /*
  *  Initialize the ATmega2560 SPI subsystem
  */
 // Initial SPI Peripheral
 SPI_DDR = (1<<PORTB2)|(1<<PORTB1)|(1<<PORTB0);

 // CS pin is not active
 SPI_PORT |= (1<<CS_BIT);

  // Enable SPI, Master Mode 0, set the clock rate fck/2
 SPCR = (1<<SPE)|(1<<MSTR);
 SPSR |= (1<<SPI2X);

 //Disable the SD card
 DDRB |= (1<<CS_BIT);


message:
graph of a function Arduino

I am making a temperature circuit with arduino.
is there any way to plot the value of the temperature in a graph using arduino?
thank you very much in advance

body:
Yes you can use the [Plot][1] menu command in the new Arduino 1.6.6 or you can use the [Visual Micro debugger][2] to create graphs in Visual Studio

  [1]: https://blog.arduino.cc/2015/11/03/arduino-ide-1-6-6-released-and-available-for-download/
  [2]: http://www.visualmicro.com/post/2015/08/16/Arduino-Breakpoint-Command-Syntax-Plotting-Values-Example.aspx


message:
Alternative to patching core library source and header files

I am following a DIY guide that requires me to patch two arduino core library files: `HID.cpp` and `USBAPI.h`. This is not really practical for many reasons. I am not a native C programmer, but I am sure there are better ways to achieve the same without messing directly with system files. How can I override system library files without modifying the originals?

body: Unfortunately there *really* isn't any way of doing that other than modifying those files. The good news is that it is perfectly viable to make the modifications under a different "core" and then amend boards.txt with the core containing the modifications.