body:
I got a new servo a few days back (RC Servo, Futaba FP-S148). I first tested it out with the Sweep sketch on Arduino, powering it with the Arduino 5v and GND pins only. It was working, just fine.

Today I was trying to use it in my robot and I tried powering it with 2 LiPo batteries (Samsung ICR16850 2200mAh, from an old laptop battery) connected in series, giving 8.32v. As soon as I connected my servo, it started rotating randomly, I had not connected it to my Arduino yet. I quickly took it out.

Next, I used a L7805 to get 5.13v regulated supply out of my batteries that I used earlier. When I connected my batteries to the servo, and the servo to the Arduino, uploaded the sketch, the servo started behaving rather strangely, it first did a complete turn and then stopped. Only a humming sound came from the servo. Strange thing is, whenever I connect one of my Multimeter leads to the power cables, the servo immediately turned in the opposite direction only as long as only lead was in contact with either the positive or negative wire.
Otherwise, the servo just gives a humming sound.

I stripped down the servo and checked the motor. It is working fine. Moreover now the servo doesn't even makes the humming sound. It just sits there, no movement, no sound.

Have I fried my servo? Or is it some other issue?

title: Did I fry my servo?

Answers: 2

body:
Since a servo is basically the combination of this components:

1. Motor
2. Gearbox
3. Position sensor (i.e a potentiometer)
4. Motor control electronics (e.g some useful stuff to protect the system and to relate d.d.p. over it's node to position => angle[i.e could by just an operational ampifier])

![servo disassembled](https://a.pololu-files.com/picture/0J3188.450.jpg?8db0bf79b0d26db613e6730cedbc62f7)

The unusual behaviour could have been raised by a single component of the system, most likely the variable resistor.
There's no guarantee of sucess, but maybe we can use this event to discover soimething!
My advce is try to discover the potentiometer used by the producer of the servo by looking at related datasheet. Then solder/attach temporarly an half-value or a quarter-value, resistor if the servo change it's orientation consider a replacing, if not just get rid f it.

Hope helps :)

Reference https://www.pololu.com/blog/15/servo-servo-motor-servomotor-definitely-not-server

body:
> As soon as I connected my servo, it started rotating randomly,

The random movement could be from a floating control line, i.e. random voltages signals are being interpreted as random positions, and the servo is responding.

> I stripped down the servo and checked the motor. It is working fine. Moreover now the servo doesn't even makes the humming sound. It just sits there, no movement, no sound.

Assuming it was put back together properly, then it sounds like the control circuitry has been damaged.

> I had not connected it to my Arduino yet. I quickly took it out.

Have you tried it on the sweep example again, or a servo tester? It could be working.

> Strange thing is, whenever I connect one of my Multimeter leads to the power cables, the servo immediately turned in the opposite direction only as long as only lead was in contact with either the positive or negative wire.

Sounds like you are accidentally sending it control signals with your multimeter.

--------------
Your servo is dead if:

- it is properly connected and doesn't respond to any control signals
- it is properly connected and responds randomly to control signals
- it is properly connected and responds randomly to a grounded control line

n.b. unconnected (floating control lines could cause random behavior in an otherwise good servo).


body:
This is likely a duplicate, but I couldn't find the original question. This is really basic, but just can't figure it out.

I'm trying to combine a few char arrays together. This is what I've tried so far.

    float a = 12.3456;
    float b = 5.4321;
    bool c = true;

    char a_string[4];
    dtostrf(a, 4, 1, a_string);

    char b_string[4];
    dtostrf(b, 4, 1, b_string);

    char c_string[2] = {'0', '\0'};
    if (c) {
      c_string[0] = '1';
    }

    char output[12] = "-----------";

    output[0] = a_string[0];
    output[1] = a_string[1];
    output[2] = a_string[2];
    output[3] = a_string[3];

    output[4] = ' ';

    output[5] = b_string[0];
    output[6] = b_string[1];
    output[7] = b_string[2];
    output[8] = b_string[3];

    output[9] = ' ';

    output[10] = c_string[0];

    Serial.println(output);

Results in an empty string in seems.

If I remove the second [dtostrf()][1], and change b_string[0] ... to a_string[0] Then I get `12.3 12.3 1`. Doesn't seem to like having dtostrf() called more than once, but it seems like the function I want, since it allows me to set a fixed strint size. The output I'd be looking for is `12.3  5.4 1`

another approach

    String a_string = String(a, 1);
    String b_string = String(b, 1);
    String c_string = String(c);

    String output;
    String space = " ";

    output.concat(a_string);
    output.concat(space);
    output.concat(b_string);
    output.concat(space);
    output.concat(c_string);

    Serial.println(output);

This outputs `12.3 5.4 1`. Is there a way to make the String fixed width? I'm looking for

`12.3  5.4 1` instead of

`12.3 5.4 1`

What's the proper way of doing this?

EDIT
---

-----------

After trying to use the @Majenko's answer I sometimes get garbage values printed. Any ideas why?

    float a = analogRead(A1) / 1023.;
    float b = analogRead(A2) / 1023.;
    bool c = analogRead(A3) / 1023;

    char* output = createString(a, b, c);
    Serial.println(output);

    char* createString (float _a, float _b, bool _c)
    {
        char a_string[5];
        dtostrf(_a, 4, 1, a_string);

        char b_string[5];
        dtostrf(_b, 4, 1, b_string);

        char out[12];
        snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
        return out;
    }

and the output:

     0.6  1.0 0
     0.6  1.0 0
     0.6  1.0 0
     0.6  1.0 0
     0.6  1.0 0
     0.6  1.0 0
     0.�tS
    �
     0.6  `S
    �
     0.6  1.0
    }
     0.6  1.0 0
     0.7  1.0 0
     0.6  1.0 0
     0.6  1.0 0

using

      Serial.print(a_string);
      Serial.print(" ");
      Serial.print(b_string);
      Serial.print(" ");
      Serial.println(c);

doesn't produce the errors

  [1]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html

title: build fixed size strings from floats

Answers: 1

body:
The simple way would be to format the string with `sprintf` - however `sprintf` on the Arduino lacks floating point support (although it is possible to enable it).

So if you convert your floating point numbers into strings first (remember to provide room for the NULL terminating character!) you can then use `sprintf` to format those converted numbers into what you want:

    float a = 12.3456;
    float b = 5.4321;
    bool c = true;

    char a_string[5];
    dtostrf(a, 4, 1, a_string);

    char b_string[5];
    dtostrf(b, 4, 1, b_string);

    char out[12];

    snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);

`%4s` is replaced by a string which is padded to at least 4 characters wide. The padding is to the left of the string. If you want the padding to the right you can use `%-4s` instead.

----

# Addendum:

In your new posted code you are making a fundamental error:

    char out[12];
    snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
    return out;

`out` is a local variable to the function. Its memory is allocated on the stack. You fill that with data and then return the address of that location on the stack. As soon as you leave the function that memory allocation is lost. Yes, the data is still there, but the moment you call another function that memory gets overwritten with the call frame of the new function you have called - thus corrupting your data.

You have two main options:

1. Make `out` global
2. Make `out` static

The effect of the two options is pretty much the same, except that in the second option the scope of `out` is restricted to the function which means you can use the *name* `out` elsewhere without it conflicting. In both options though the memory allocated to `out` is in the BSS not the stack and thus won't get overwritten.


body:
I have a three-axis accelerometer that reads me its x, y, and z components.  This results in three graphs.  Is there a way to "combine" these components into one reading, hence, one graph?   Same question holds for a gyroscope.

The datasheet for my device is [here][1]:

  [1]: https://www.pololu.com/file/download/LSM6DS33.pdf?file_id=0J1087

title: Is there a way to combine a 3-axis accelerometer/gyroscope into one value?

Answers: 1

body:
The answer is: technically, yes, it is possible. The combined result is called [Quaternion][1]. This is what is typically used in 3D programs.

But most likely that is not what you had in mind.

Usually one can do a simplification and reduction of dimensions when in presence of some constraint.

Imagine that your moving object is bound to a planar surface: no matter how you tilt and rotate and pan it, it is still a 2D surface, plus a quaternion indicating the rototranslation.

But, once you have established the coefficients applied to the rototranslation, it is 2D.

Similar 1D case: imagine that your moving object is bound to some well-known geometrical shape, say a circumference. Once you have established how the circumference is oriented in the 3D space and its radius, you can express the position of your device by indicating either the angle or the distance from a reference point on the circumference.

In both cases you can simplify the representation because of constraints that do not allow for real 3d movement.

But if your device is a flying drone that can rototranslate freely within certain boundaries (max horizontal range, min/max altitude), there is no way that you can simplify the 3d coordinates.

If, instead, your question was related to the protocol used to read info from the accelerometer, you are bound to the protocol defined in the datasheet, by the manufacturer.

  [1]: https://en.wikipedia.org/wiki/Quaternion


body:
My program has a hardware interrupt to digital pin 2,  it is an IR obstacle detection sensor which gives “open collector” signal.  My program is executing an array — “for” loop.   At some point it has to wait for the input from the IR sensor, so I am using a “while” loop to pause and wait for the input.

   When the program gets the signal from the sensor at which point the interrupt occurs, the program collects the data (millis) and goes on for another round.  Everything works fine, but I would like to limit the time that the program is waiting for the interrupt signal, let’s say to 5 or 10 seconds. I do not want it to just sit there forever if the signal is not coming for some reason.   So what I am trying to do is to trigger the same interrupt pin (2) by another digital pin.  I  set this pin (7) on OUTPUT wrote a little “if-then” statement  so it will go HIGH when the time is up and connected this pin (7) to pin 2.

   The scheme works partially.  When the pins are connected and the time limit is reached the pin 2 gets signal and gets triggered.   But the IR signal seems to be disabled and not functioning while it is waiting for the time limit.  I tried to connect pull-up and pull-down resistors to no avail.  It seems that when the pins are linked the IR signal disappears.  I do not even get any voltage readings on that wire. If I disconnect the pins the IR signal works again and I get voltage readings on the wire.

Can anyone tell me what is going on and how can I make it work.  Is even possible?  Or what I have concocted is just plain silly?

Thank you!

title: Hardware Interrupts Issues

Answers: 2

body:
It is likely that the Arduino's digital output is of a totem poll type.  That is, it is both actively being driven high and low.  And when high, is probably over powering the IR sensor's signal.  You should not use this setup!! As it could possibly short out both your processor and IR sensor.

Instead you could emulate an open collector Arduino output.  By switching the second pin from a digital input to a digital output sending 0 then back to a digital input. (Never set this pin to digital output and send a 1 as this could short to ground through the IR open collector.)

I am assuming that the IR sensor, when activated, is momentarily pulling a pull up resistor low through the open collector to ground.  Let us know if this is incorrect as the above description would then not apply.

body:
Wouldn't it be easier just to have the interrupt call a function, that you also call after 5 seconds are up? This sounds a round-about way of doing it.

If you *must* do this, setting your other pin to output is not correct, because then the IR sensor and your other pin (7) are fighting each other. You should set the pin to *input*, and when you want it to do something briefly make it OUTPUT, and send HIGH. Then send LOW, and go back to INPUT.

However this might still make the output pin "fight" the IR sensor pin.

---

> But the IR signal seems to be disabled and not functioning while it is waiting for the time limit.

Naturally, as your output pin is holding the line low.

---

If the sensor just uses a pull-down resistor (and not actively drive the line low) then my scheme should work.

---

However a simpler scheme is just to set a flag in the ISR, (which you test for in the main loop) and if the flag isn't set within your timeout period, do whatever you want to do if it times out. Then you don't need to try to trigger the interrupt yourself.


body:
I have a SIM900 module connected to an Arduino Uno, using an AT command for listing the SMS I get this output, how can i split this based on (`,`) to store each data in an array?

    AT+CMGL="ALL"

    +CMGL: 2,"REC READ","+639321576684","Ralph Manzano","16/04/25,21:51:33+32"
    Yow!!!

    OK

title: Split string into an array of string

Answers: 1

body:
You could try to use strtok. Code from my mind and not tested:

    #include <stdio.h>
    #include <string.h>

    int main(int argc, char *argv[])
    {
        char string[] = "AT+CMGL=\"ALL\"\n"
        "\n"
        "+CMGL: 2,\"REC READ\",\"+639321576684\",\"Ralph Manzano\",\"16/04/25,21:51:33+32\"\n"
        "Yow!!!\n"
        "\n"
        "OK\n";
        char delimiter[] = ",\n";

        // initialize first part (string, delimiter)
        char* ptr = strtok(string, delimiter);

        while(ptr != NULL) {
            printf("found one part: %s\n", ptr);
            // create next part
            ptr = strtok(NULL, delimiter);
        }

        return 1;
    }

Outputs:

    found one part: AT+CMGL="ALL"
    found one part: +CMGL: 2
    found one part: "REC READ"
    found one part: "+639321576684"
    found one part: "Ralph Manzano"
    found one part: "16/04/25
    found one part: 21:51:33+32"
    found one part: Yow!!!
    found one part: OK


body: Friends... I have an idea to attach the **compass sensor (HIMC5883L)** with my  **android smartphone** using arduino, but I don't clearly know how to do this. I mean I want to make an OTG compass for smartphone for map navigation etc.(Many Smartphones have compass but mine have not).  If anyone had do this or know how to do this, please guide me. Thanks!

title: How can I interface HMC5883L compass board to a smartphone with OTG?

Answers: 1

body:
A cheaply available USB OTG adapter cable (ask eBay) will connect the Arduino to the phone.

You can then connect the compass sensor to your Arduino and write a sketch to retrieve the data from it and send it through the USB serial connection.

Then you need to write some software for the phone to receive and interpret the serial data and display it as a compass.  That is unless you are happy just to have a simple text display (like the Arduino's Serial Monitor) with the compass information showing in it, in which case there is off-the-shelf software that would do that (search Play)


body:
I'm trying to measure kWh with an Arduino that I have connected to a ESP8266 that communicates this value to a web server I have. And I've been trying to find the best and easiest way to go about this.

I'm thinking that I can hook a PMAC903 up to the Arduino using the interrupt pins and measuring the pulses, but I don't really know how I'm supposed to do that? Will it even work? Is this the way it's normally done? I can't really say I've found an easy solution to measure current.

You can find documentation for the PMAC903 [here][1] and I'm currently in possession of an Arduino Uno that I'm using.

  [1]: http://en.pmac.com.cn/downloadsfront.do?method=picker&flag=all&id=fba7e17b-464f-4df0-afc1-e1eeb4289986&fileId=55&isDownloadPermissions=true&memstate=/members_login.html

title: Measure current and consumption

Answers: 1

body:
The state of this meter can be read in 3 ways:

 * Pulse, this is very easy to implement. But depending on the stability of the hardware u can miss pulses leading to inaccurate values. In this way u have to calculate the meter value yourself.

 * RS485, this is a communication bus not default on arduino. But given this link https://arduino-info.wikispaces.com/RS485-Modules i think it is doable but not easy. This will read the value from the meter.

 * M-Bus: There is special hardware needed to interact with it. This is the industry standard of doing it. It's not cheap. But u can link many meters together. This will read the value from the meter.

Depending on your time/knowledge/other requirements u have to make a chose what way your going to use.


body:
I've build a fairly simple doorbell using Arduino Pro Mini 3.3V: https://www.youtube.com/watch?v=WFd94CYT2Lw&feature=youtu.be

Here's the current setup:

  - Arduino running off the 9 V battery
  - A simple speaker is connected to Arduino (powered from the battery, Arduino just drives it through a transistor)
  - Arduino is reading light level from the light meter every 200 ms.
  - Bulb is connected to the wire that is lit up when someone presses the doorbell button.

It works well - someone presses the doorbell button, bulb gets lit up, Arduino notices that (using light meter) and doorbell rings.

**Problem**

In short - battery life. This kind of setup lasts around 2-3 days off a single battery. I was reading all about how to run Arduino off a single battery for a few weeks, even months, but I'm not sure it's feasible in my case. First of all, I need to wake up Arduino every 100-200, maybe 500 milliseconds, to read the light level. Plus, many of those long-battery-life solutions involved basically building own Arduino-compatible scheme from scratch, which I'd like to avoid.

**Idea**

But... I have a 230 V power source - the one that drives the bulb. Issue is that this power source is down all the time, unless someone is pressing the doorbell button.

I could approach it in two ways:

1. When someone presses the button, I'd power the Arduino and immediately play a song. Issue with that approach is that if someone presses the button for just a split second, my Arduino would be powered up for just that short amount of time, and I wouldn't have enough time to play the complete song.

2. If I could possibly reverse the way doorbell button works, I could have +230V all the time, and 0 when someone presses the button. This way Arduino would be on all the time, and it would "notice" someone pressed the button when power would go down. Issue with that approach is that song would be played only once guest would release the doorbell button, + the time it takes for an Arduino to boot.

In both #1 and #2, I need two things then:

a) have Arduino on all the time, regardless of whether button is pressed or not

b) power Arduino from the doorbell to avoid having to use a battery

Which kind of means that I need to power Arduino from a dual source - 230 V and rechargeable battery. 230 V when available, and battery when 230 V goes down. In a perfect scenario, this battery would be charged from 230 V source too :)

Any ideas how to built such a thing? Is there some AC power module that I could use? How would I wire things up in such a case - Arduino, AC power module, rechargeable battery?

Or maybe I'm missing some easier, simpler solution here?

title: Power Arduino from 230v with battery fallback

Answers: 4

body:
You can run a Pro-Mini just fine of a battery. It's the UNOs that cause a lot of problems, because of the onboard USB-to-Serial chip. The only thing you might want to tweak on this board, is removing the power-led, which I've recently done with a knife.

I poll the reflectivity of my power-meter every 250ms, and I'm getting at least 3 months of battery life out of 2 AA-batteries.

Depending on the light sensor you are using, you could even use interrupts to wake up the Arduino when the light is on, instead of having to poll every few milliseconds.

body:
> This kind of setup lasts around 2-3 days off a single battery.

I measured 15.8 mA consumption on my Pro Mini, running from 9V. A typical 9V battery may have a capacity of 500 mAh, so that is 500 / 15.8 = 31.6 hours. Thus your observed consumption is about right.

Probably 10 mA of that is the LED, so removing it would help. I have a [page about power saving](http://www.gammon.com.au/power). You would want to investigate going into sleep mode, and waking long enough to check the light. You might be able to arrange a LDR in such a way that it generates an interrupt and wakes the processor immediately from a deep sleep.

---

## Example of waking using an LDR

I made up a test like this:

[![LDR schematic][1]][1]

D2 is one of the external interrupt pins so we can write a simple low-power sketch that sleeps all the time until the LDR gets enough light that the resistance drops, and D2 goes HIGH.

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

    #include <avr/sleep.h>

    const byte LED = 9;

    void wake ()
    {
      // cancel sleep as a precaution
      sleep_disable();
      // precautionary while we do other stuff
      detachInterrupt (0);
    }  // end of wake

    void setup ()
      {
      }  // end of setup

    void loop ()
    {

      // flash LED 5 times
      for (byte i = 0; i < 5; i++)
        {
        pinMode (LED, OUTPUT);
        digitalWrite (LED, HIGH);
        delay (100);
        digitalWrite (LED, LOW);
        delay (100);
        }

      pinMode (LED, INPUT);

      // disable ADC
      ADCSRA = 0;

      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      sleep_enable();

      // Do not interrupt before we go to sleep, or the
      // ISR will detach interrupts and we won't wake.
      noInterrupts ();

      // will be called when pin D2 goes high
      attachInterrupt (0, wake, RISING);
      EIFR = bit (INTF0);  // clear flag for interrupt 0

      // turn off brown-out enable in software
      // BODS must be set to one and BODSE must be set to zero within four clock cycles
      MCUCR = bit (BODS) | bit (BODSE);
      // The BODS bit is automatically cleared after three clock cycles
      MCUCR = bit (BODS);

      // We are guaranteed that the sleep_cpu call will be done
      // as the processor executes the next instruction after
      // interrupts are turned on.
      interrupts ();  // one cycle
      sleep_cpu ();   // one cycle

      } // end of loop

---

My example just flashes an LED on pin 9 five times, that is where you can play your doorbell sound. Now, with no major external circuitry (like LEDs that are always on) it should have low power consumption.

> What would be a good replacement for it, with low power draw and support for interrupts?

The LDR as described above. I measured 3 µA through the LDR when it was partly covered with a black box (my glasses case) and the room lights off. However it was daylight. I think that is pretty acceptable.

---

Come to think of it, you could probably turn this into a nice "doorway detector" (like they have in shops where it plays a sound when you break a light beam at the doorway). By arranging the LDR in a tube at one side of the door, and shining a light across the doorway into it (and probably tweaking the resistor values a bit) it would play a sound once you cross the beam.

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

body: A small solar cell would not require excitation and would probably generate enough voltage to trigger an interrupt pin and wake up the MCU.

body:
If you make it so that the light only goes out when you press the button, and connect a battery charger with that bulb in parallel, put a battery in the charger and plug the arduino into the battery, then use the light sensor approach to detect the button press and play a tune, it would work just fine... Really the only 3 things you might wanna worry about are the user holding the button for a few hours (which is very unlikely), power outages (can be solved using a UPS), and replacing the battery/bulb once every few years, depending on how good it is... Probably the simplest approach, not sure if it is the best tho...
But why not just plug the arduino to a phone charger that is then connected to the wall, and then use the doorbell switch as input for the arduino?


body:
I'm trying to use a distance sensor to trigger an LED light, as you can see below. However, I also want the LED to stay on/white when a person is within the 38 inches range. How should I do that?

    //Tell the Arduino IDE to include the FastLED library
    #include <FastLED.h>

    //Setup the variables for the HC-SR04
    const int trigPin = 9;
    const int echoPin = 6;
    //Setup the variables for the NeoPixel Strip
    #define NUM_LEDS 60 // How many leds in your strip?
    #define DATA_PIN 4 // What pin is the NeoPixel's data line connected to?
    CRGB leds[NUM_LEDS]; // Define the array of leds

    void setup() {
      // initialize serial communication:
      Serial.begin(9600);
      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
    }

    void loop() {
      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm;

      // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
      // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
      pinMode(trigPin, OUTPUT);
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(2);
      digitalWrite(trigPin, LOW);

      // Read the signal from the sensor: a HIGH pulse whose
      // duration is the time (in microseconds) from the sending
      // of the ping to the reception of its echo off of an object.
      pinMode(echoPin, INPUT);
      duration = pulseIn(echoPin, HIGH);

      // convert the time into a distance
      inches = microsecondsToInches(duration);
      cm = microsecondsToCentimeters(duration);

      Serial.print(inches);
      Serial.print("in, ");
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();
      if (inches <= 38)  {
        for ( int colorStep = 0; colorStep < 256; colorStep++ ) {
          int r = 255 - colorStep;
          // Redness starts at zero and goes up to full
          int b = 255 - colorStep;
          // Blue starts at full and goes down to zero
          int g = 255 - colorStep;
          // No green needed to go from blue to red
          // Now loop though each of the LEDs and set each one to the current color
          for (int x = 0; x < NUM_LEDS; x++) {
            leds[x] = CRGB(r, g, b);
          }
          // Display the colors we just set on the actual LEDs
          FastLED.show();
          delay(10);
        }
      } else if (inches > 38) {
        fill_solid( &(leds[0]), NUM_LEDS /*number of leds*/, CRGB::Black);
        FastLED.show();
      }
      delay(1000);
    }

    long microsecondsToInches(long microseconds) {
      // According to Parallax's datasheet for the PING))), there are
      // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
      // second). This gives the distance travelled by the ping, outbound
      // and return, so we divide by 2 to get the distance of the obstacle.
      // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
      return microseconds / 74 / 2;
    }

    long microsecondsToCentimeters(long microseconds) {
      // The speed of sound is 340 m/s or 29 microseconds per centimeter.
      // The ping travels out and back, so to find the distance of the
      // object we take half of the distance travelled.
      return microseconds / 29 / 2;
    }

title: Use distance sensor to trigger LED strip and stay on while the person is in range

Answers: 1

body:
if (inches <= 38)

That You might want to change. Try using "while(inches <= 38)" and moving sensor calculations to that loop. When ever the distance stays less than You want the light should stay on.


body:
When I plug in my nanoatmega328 to my computer, nothing shows up in `/dev` as I expect it to. If I plug in my Uno, `/dev/ttyACM0` shows up. I have tried several Nanos.

Linux Mint 17.2.

title: Arduino Nano not showing up in /dev

Answers: 3

body:
Did you try with `lsusb` and `dmesg`?

They should show if the Arduino was detected and what are its parameters (use `lsusb -v` for more detailed info).

If it is detected but you do not get the corresponding tty device, it might be because of missing/different rules.

You could check out [this link][1] and edit the parameters idProduct and idVendor to match what you get from `lsusb`, in case your rule is not matching.

Then remember to [reload the modified rules][2].

Protip: compare the parameters of your working Uno against the ones from the Nanos and the values set in the rules.

  [1]: http://playground.arduino.cc/Linux/Udev
  [2]: https://unix.stackexchange.com/questions/39370/how-to-reload-udev-rules-without-reboot

body:
`dmesg` should be the tool to help you.

Run:

    $ dmesg -w

Then hit return a few times (to get some blank lines).

Next plug in your Nano.  Some text should appear on the screen, which will give you a clue as to what is going on.  I don't have a Nano to try with, but a typical working device would look something like:

    [29125.599800] usb 9-1.4.1: new full-speed USB device number 13 using ehci-pci
    [29125.694742] usb 9-1.4.1: New USB device found, idVendor=04d8, idProduct=0208
    [29125.694747] usb 9-1.4.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [29125.694749] usb 9-1.4.1: Product: Lenny
    [29125.694751] usb 9-1.4.1: Manufacturer: chipKIT
    [29125.694753] usb 9-1.4.1: SerialNumber: CK1660A05353C5
    [29125.695213] cdc_acm 9-1.4.1:1.0: This device cannot do calls on its own. It is not a modem.
    [29125.695240] cdc_acm 9-1.4.1:1.0: ttyACM0: USB ACM device
    [29125.695768] cdc_acm 9-1.4.1:1.2: This device cannot do calls on its own. It is not a modem.
    [29125.695791] cdc_acm 9-1.4.1:1.2: ttyACM1: USB ACM device
    [29125.697772] input: chipKIT Lenny as /devices/pci0000:00/0000:00:1a.7/usb9/9-1/9-1.4/9-1.4.1/9-1.4.1:1.4/0003:04D8:0208.0004/input/input19
    [29125.698394] hid-generic 0003:04D8:0208.0004: input,hidraw2: USB HID v1.11 Mouse [chipKIT Lenny] on usb-0000:00:1a.7-1.4.1/input4

If it doesn't know what the device is it will give you a fraction of the information, and probably tell you it can't attach a driver.

If the device is faulty and not recognisable you will get messages similar to:

    [29125.698394] usb 2-2.1: device not accepting address 5, error -71

If you get absolutely nothing displayed then it can't even recognise that anything has been attached to your computer.  Try different USB sockets and different USB cables to see if that helps.

Note: some cheap USB cables used purely for charging small batteries don't have any data wires in them - just power. Using one of these will fail for sure.

body:
Like Majenko said, if dmesg shows nothing then your cable could be to blame. It could be for power only (no data lines). This happened to me. I wouldn't have even thought of the cable if I did not read it here.
My hardware is also Arduino nano clone (atmega238 + ch340) and the machine runs Ubuntu 15.04. With a good cable the device is recognized like this (dmesg -w):

    usb 4-2: new full-speed USB device number 24 using ohci-pci
    usb 4-2: New USB device found, idVendor=1a86, idProduct=7523
    usb 4-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
    usb 4-2: Product: USB2.0-Serial
    ch341 4-2:1.0: ch341-uart converter detected
    usb 4-2: ch341-uart converter now attached to ttyUSB0


body: so I'm making a project, kind of BB-8 droid replica, and I stumbled upon a problem. Since I am using two RC brushless motors, ESC's and batteries, I want to make my Uno board fed up from those batteries. Also, I want to use inductive charging set that would charge both batteries. Can anyone tell me or give some kind of scheme how should I distribute the power from batteries and what additional boards should I buy?

title: Can't figure out how to distribute the power

Answers: 1

body:
The best option is to connect the 5V/2A output of the UBEC to the 5V pin on the Arduino. In my experience, 7.4V is not enough to feed into the input jack on an Arduino especially if it is from a battery, as the voltage will drop when current is being drawn by other loads. I have built an Arduino controlled robot using a 6V NiMH battery and brushed DC gearmotors (so no ESCs or UBEC) and used a [$5 5V 1A step-up/step-down converter][1] so that even if the battery voltage dropped below 5V, it could still power the board. However, since you have a UBEC that is not in use, use it. **Note that if you put voltage into the 5V pin, disconnect it when you are connecting the arduino over USB or you might damage your board.**

As for inductive charging, I don't know of any off-the-shelf solution designed for charging a 2S lithium ion battery. The best option for charging would probably be an easy way to open the ball to access the batteries.

  [1]: https://www.pololu.com/product/2119


body:
A 32 inch flat screen was embedded in a coffee table and covered by a protective layer of glass. Sensors around the edge of the glass surface need to be able to detect the precise location of an object on the glass so that a mouse cursor can be controlled with a stylus.

What sensors would you use to ensure accuracy of stylus location above the screen?

title: Gesture sensing TV coffee table - what sensors would you use?

Answers: 1

body:
Perhaps if you drop the monitor an inch or 2 away from the glass you can use a Frustrated Total Internal Reflection ([FTIR][1]) IR scheme.  But at that shallow angle it will be tricky and may require several cameras around the edges.

[![enter image description here][2]][2]

added later...

Should mention the parallax problem given there is a gap of an inch or more between the monitor and the touch screen.  FTIR is better when you project the image onto the touch screen.

If you don't mind lower resolution, I believe the micro dose dispenser soda machines use a capacitive touch wire mess embedded in the transparent plastic front panel.  Although micro dose dispensers appear to only need to emulate about 100 to 200 buttons.  Not enough to control a mouse with any accuracy.  But enough to control a GUI designed with such constraints.

Loose high resolution capacitive touch screens can be bought with out a monitor.  However they tend to be much smaller then 32 inches.

  [1]: http://mmu.ic.polyu.edu.hk/mu_proj/2011/IPD/IPD04/Research.html
  [2]: https://i.stack.imgur.com/0mnrG.jpg


body:
I am new to arduino, I started learning about it today and i'm stuck. I ripped out a small stepper motor from an old DVD drive. I got a polulu a4988 driver and I have wired it up as follows:

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

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

 /*     Simple Stepper Motor Control Exaple Code
  *
  *  by Dejan Nedelkovski, www.HowToMechatronics.com
  *
  */
 // defines pins numbers
 const int stepPin = 3;
 const int dirPin = 4;

 void setup() {
   // Sets the two pins as Outputs
   pinMode(stepPin,OUTPUT);
   pinMode(dirPin,OUTPUT);
 }
 void loop() {
   digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
   // Makes 200 pulses for making one full cycle rotation
   for(int x = 0; x < 200; x++) {
  digitalWrite(stepPin,HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin,LOW);
  delayMicroseconds(500);
   }
   delay(1000); // One second delay

   digitalWrite(dirPin,LOW); //Changes the rotations direction
   // Makes 400 pulses for making two full cycle rotation
   for(int x = 0; x < 400; x++) {
  digitalWrite(stepPin,HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin,LOW);
  delayMicroseconds(500);
   }
   delay(1000);
 }

But nothing happens, the motor doesn't even vibrate. Any idea what could be wrong?

title: DVD drive stepper motors with polulu a4988 on Arduino

Answers: 1

body: According to Pololu's website, the VMOT pin needs at least 8V to function. Try a 12V **switching** (important!) wall wart supply that can supply at least 1A instead of your USB supply. Avoid supplies that can deliver currents >3A, as they are overkill for a small stepper motor and can be dangerous if shorted. Be sure to put a large (100uF is good) capacitor across that supply to prevent voltage spikes. To prevent damaging the motor from the higher voltage, follow the information Pololu provides on setting the current limit and set it to about 350mA. If you notice the motor is too hot to touch, try 200mA.


body:
I am using ESP8266 with Arduino MEGA. ESP8266 is powered 3.3v via voltage divider, which is taking 5v from arduino and converting it down to 3.3v with the help of 5K and 10K resistors. AT commands seems to be working OK. I am using SD_card reader and kept my index.html file in SD_card. I am able to make a successful connection and esp also sends the whole index.html file, But the issue is my browser does not shows the page in html format, instead the whole html code appears on the browser. Can anyone help me to sort this issue ?
Herez the whole code;

  #include <SPI.h>
  #include <SD.h>

   #define SSID "Maxcotec"   // change this to match your WiFi SSID
   #define PASS "qamar0334" // change this to match your WiFi password
   #define PORT "80"      // using port 80 by default
  #define DEBUG true
   #define BUFFER_SIZE 1024
   char buffer[BUFFER_SIZE];
  //SoftwareSerial Serial2(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
          // This means that you need to connect the TX line from the esp to the Arduino's pin 2
          // and the RX line from the esp to the Arduino's pin 3
  File webFile, CSS_file;
  String webpage;
   // By default we are looking for OK\r\n
   char OKrn[] = "OK\r\n";
   byte wait_for_esp_response(int timeout, char* term=OKrn) {
    unsigned long t=millis();
    bool found=false;
    int i=0;
    int len=strlen(term);
    // wait for at most timeout milliseconds
    // or if OK\r\n is found
    while(millis()<t+timeout) {
     if(Serial2.available()) {
   buffer[i++]=Serial2.read();
   if(i>=len) {
    if(strncmp(buffer+i-len, term, len)==0) {
     found=true;
     break;
    }
   }
     }
    }
    buffer[i]=0;
    Serial.print(buffer);
    return found;
   }

  void setup()
  {
    Serial.begin(9600);
    Serial2.begin(115200); // your esp's baud rate might be different

     setupWiFi();
    // print device IP address
    Serial.print("device ip addr:");
    //esp.println("AT+CIFSR");

    //sendData("AT+RST\r\n",2000,DEBUG); // reset module
    //sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
    sendData("AT+CIFSR\r",1000,DEBUG); // get ip address
    sendData("AT+CIPMUX=1\r",1000,DEBUG); // configure for multiple connections
    sendData("AT+CIPSERVER=1,80\r",1000,DEBUG); // turn on server on port 80

   // initialize SD card
   Serial.println("Initializing SD card...");
   if (!SD.begin(53)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;    // init failed
   }
   Serial.println("SUCCESS - SD card initialized.");
   // check for index.htm file
   if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
   }
   Serial.println("SUCCESS - Found index.htm file.");

     // send web page
   webFile = SD.open("index.htm");        // open web page file
   if (webFile) {
    while(webFile.available()> 0) {
     //client.write(webFile.read()); // send web page to client
       char ch = webFile.read(); // Read a character
       webpage += ch; // Add it
    }
    webFile.close();
   }
    Serial.print("file contents>>>");
    //Serial.println(webpage);
    //delay(20000);
  }

  void loop()
  {
    if(Serial2.available()) // check if the esp is sending a message
    {
   /*
   while(Serial2.available())
   {
     // The esp has data so display its output to the serial window
     char c = Serial2.read(); // read the next character.
     Serial.write(c);
   } */

   if(Serial2.find("+IPD,"))
   {
    delay(1000);

    int connectionId = Serial2.read()-48; // subtract 48 because the read() function returns
               // the ASCII decimal value and 0 (the first decimal number) starts at 48

    //String webpage = "
Hello

World!
<button id=\"11\">Toggle Pin 11</button>";//<button>LED1</button>";

    //Serial.print("file contents>>>");
    //Serial.println(webpage);
    //delay(20000);
    String cipSend = "AT+CIPSEND=";
    cipSend += connectionId;
    cipSend += ",";
    cipSend +=webpage.length();
    cipSend +="\r\n";

    sendData(cipSend,1000,DEBUG);
    sendData(webpage,1000,DEBUG);

    //webpage="<button>LED2</button>";

  //     cipSend = "AT+CIPSEND=";
  //     cipSend += connectionId;
  //     cipSend += ",";
  //     cipSend +=webpage.length();
  //     cipSend +="\r\n";
  //
  //     sendData(cipSend,1000,DEBUG);
  //     sendData(webpage,1000,DEBUG);

    String closeCommand = "AT+CIPCLOSE=";
    closeCommand+=connectionId; // append connection id
    closeCommand+="\r\n";

    sendData(closeCommand,3000,DEBUG);
   }
    }
  }

  void setupWiFi() {
    // try empty AT command
    Serial2.println("AT");
    wait_for_esp_response(2000);
    // set mode 1 (client)
    Serial2.println("AT+CWMODE=1");
    wait_for_esp_response(2000);
    // reset WiFi module
   /*
    esp.print("AT+RST\r\n");
    wait_for_esp_response(3000);
    delay(5000);
    */
    // join AP
    Serial2.print("AT+CWJAP=\"");
    Serial2.print("xxxxxxx");
    Serial2.print("\",\"");
    Serial2.print("xxxxxxx");
    Serial2.println("\"");
    // this may take a while, so wait for 5 seconds
    wait_for_esp_response(5000);
    Serial2.println("AT+CIPSTO=30");
    wait_for_esp_response(1000);
    // start server
    Serial2.println("AT+CIPMUX=1");
    wait_for_esp_response(1000);
    Serial2.print("AT+CIPSERVER=1,"); // turn on TCP service
    Serial2.println(PORT);
    wait_for_esp_response(1000);
   }

  String sendData(String command, const int timeout, boolean debug)
  {
   String response = "";

   Serial2.print(command); // send the read character to the Serial2

   long int time = millis();

   while( (time+timeout) > millis())
   {
     while(Serial2.available())
     {

    // The esp has data so display its output to the serial window
    char c = Serial2.read(); // read the next character.
    response+=c;
     }
   }

   if(debug)
   {
     Serial.print(response);
   }

   return response;
  }

And this is what I am getting in web browser;[![Opera browser][1]][1]

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

I am using Opera browser but I have tried in Chrome and firefox aswell. when I open this index.html page in my laptop with the same browser, it opens perfectly.

title: ESP8266 sends webpage to client, but html codes appears in browser instead of webpage?

Answers: 4

body:
See the text from "'HTTP/1.1 200 OK'" until "'DOCTYPE html'" in the following couple of links which say the same, and you might like to read the rest of those pages:

- https://www.arduino.cc/en/Tutorial/WebServer
- http://www.allaboutcircuits.com/projects/using-an-arduino-as-a-web-server

body:
Slightly off-topic, as this is not the source of your problem, but as jBot42 says, you need a proper regulator. When you use a voltage divider, your load (the ESP8266) is connected in parallel with one of the resistors (the 10K one) and effectively changes the output voltage of the regulator. As the consumption of power in the ESP8266 changes (e.g. when the wifi circuit transfers data), the voltage will also change.

At the very least you should place an electrolytic capacitor in parallel with the 10K resistor, but even this is not a good solution.

body:
It looks like you did not send the HTTP headers. Before sending any of the HTML content send following lines:

    "HTTP/1.1 200 OK\r\n"
    "Content-Type: text/html\r\n\r\n"

Make sure you send all the `\r\n` !

body:
Make sure you save the SD card file as `index.htm`.

That is what you are calling for in your code. Your description has a reference to `index.html`. You will get the result you see.


body:
I am in a fix since last one week regarding this:

As mentioned in a previous question (asked here only), I have been working to develop a APA102 LED based display. Now for this I have an Arduino Due. The display area is non rectangular however there is a central rectangular region measuring 63 cm X 36 cm. I have managed to do everything from the software side however stuck with the hardware (first time, its mostly vice-versa!!). The confusion is this, 2 options that I have at my disposal:

1. Go for the APA102 144 LEDs/meter (high density required) strip and then use them to make the display. On doing a small approximate calculation, I found I would have close to 2500-2600 LEDs. My first question is that:

  a. Can Arduino Due handle this? I also need to display static images (bitmaps) (forget animations) and perform fading. Would the refreshing be fast enough? I have some values from APA102 datasheet and Arduino Due but cannot make head or tail of it...I do not know how to find out time taken, data rate etc.

 b. The other problem I have with this is that for the bitmap to be "perfect", the pixel pitch needs to be same. In vertical direction, this is not possible without cutting the strip along the length to reduce its width. This a damn tedious and useless job. This act along with the soldering and everything involved makes me go for option 2 (below).

2. I go for eight 8*32 APA102 flexible displays and arrange them in two columns so that to display the bitmap, I split the bitmap data into two 32*32 matrices and then pass them separately. this is because I cannot find the relation between the bitmap pixel index and the actual display index. The arrangement is like that. Here Also, my question is: Can Arduino Due deal with this a good refresh rate without flickering etc. (POV display req.) The problem with this option is that I can cover only the rectangular region of the area and I am left with some area which makes me feel guilty to see it not lighted whereas with strip I can cover the whole area and only display bitmaps for the rectangular area. Both options have serpentine arrangement. This option also has cleaner and easy construction.

Both options seem plausible to me but I really cannot decide which one is better. Confused! Please, any help, idea, guidance, advice...anything would be great. I would be ordering this stuff from aliexpress etc. and thus a wrong decision would be taxing on my pocket.

I would be glad to provide any other info if required.

Thanks!

title: Help with Arduino Due and APA102 LED strip Vs Matrix

Answers: 0


body:
Its being a few days i am trying to achieve something that I dont really know if possible.
Using the `Samd21` chip(`Arduino Zero`), I am using a timer and a `DAC` to produce a sine wave.

The required frequencies are **100Khz to 3Mhz**. I know its sounds too much, but according to my calculations its possible- I would like to know if I am wrong with my software approach.

Pseudo is this :

1.I create a look-up table of a sine wave = array of a sine samples that holds N samples
2.I use a timer with a pre scale of 1, where the clock speed is 48Mhz
3.Each timer tick I produce from the DAC 1 sample from the sine wave
4.To change frequencies I am changing the timer top counter value.

If we try to speak about the max frequency, according to Nyquist , a 3MHz sine must be sampled with at least 6MHz sample rate, and my sine array has 15 samples, means 45Mhz sampling rate.(=good)

Then the sine frequency is :

    sineF= TimerF*sineSamples = TimerF*15

Than means I need a timer frequency of :

    TimerF=15*sineF = 15*3Mhz=45MHz

So, both are good, the timer max f can be 45Mhz, and the sampling rate is good according to Nyquist.

The only concern here, is **if the DAC can do that(speed)**, and if changing the timer frequency fast enough (even every period) is acceptable.

Is this whole software approach true ?
If its not, producing a square wave probably possible,since it requires much less speed, but then, can you turn it into a nice clean sin wave with filters?

Thanks.

title: Producing a sine wave with the DAC?

Answers: 1

body:
First, I have to say I am not familiar with the Zero hardware, so I am
answering in quite general terms. Hopefully you will also get some
answers with hardware-specific information. That being said, here are my
first thoughts:

1. Your approach seems reasonable to me, but you are too optimistic
regarding the achievable sampling rate.

2. DACs are usually fast. It's unlikely that the DAC will limit the
frequency you can achieve.

3. You cannot achieve a sampling frequency of 45 MHz in software
with a CPU running at 48 MHz: your code to output a sample would
have to run in less than 1.07 CPU cycles.

4. You may achieve a higher sampling rate with an array of
16 samples rather than 15, as wrapping the array index modulo 16
can be optimized by the compiler into a bitwise AND, which is likely to
be faster than computing `index`.

5. Fastest would probably be to use a busy loop with constant execution
time and interrupts turned off (I know how to do that on AVR, but not on
ARM). Problem is: the program cannot do anything else than outputting
samples.


body:
so I have a project which is to make a simple memory game using Arduino where the LEDs have to blink in a certain pattern and the player has to imitate the same pattern
but unfortunately I'm having so much trouble with the code
I want to make an if statement to check whether the button was pressed or not if it was it continues to check on the second button and if it wasn't the red led (which means wrong) has to  turn on
this is how i started:

    enter code here

    const int button1 = 2;          // 1st button controls Blue LED
    const int button2 = 3;          // 2nd button controls Yellow LED
    const int button3 = 4;          // 3rd button controls Green LED
    const int button4 = 5;          // 4th button controls Red LED
    const int led1 = 7;             // Blue LED
    const int led2 = 8;             // Yellow LED
    const int led3 = 9;             // Green LED
    const int led4 = 10;            // Red LED
    const int correctLED = 6;
    const int wrongLED = 11;
    int val = 0;

    // Variables
    int buttonState[] = {0,0,0,0};         // current state of the button
    int lastButtonState[] = {0,0,0,0};     // previous state of the button
    int buttonPushCounter[] = {0,0,0,0};

    void setup() {
      // initialize inputs :
      randomSeed(analogRead(0));
      pinMode(button1, INPUT);
      pinMode(button2, INPUT);
      pinMode(button3, INPUT);
      pinMode(button4, INPUT);

      // initialize outputs:
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      // initialize serial communication for debugging:
      Serial.begin(9600);
            }
      }

     void loop() {
           digitalWrite(7, HIGH);
           digitalWrite(8, HIGH);
           digitalWrite(9, HIGH);
           digitalWrite(10, HIGH);
           digitalWrite(7, LOW);
           digitalWrite(8, LOW);
           digitalWrite(9, LOW);
           digitalWrite(10, LOW);

           digitalWrite(7, HIGH);
           delay(500);
           digitalWrite(7,LOW);
           delay(500);
           digitalWrite(8, HIGH);
           delay(500);
           digitalWrite(8,LOW);
           delay(500);
           digitalWrite(9, HIGH);
           delay(500);
           digitalWrite(9,LOW);
           delay(500);
           digitalWrite(10, HIGH);
           delay(500);
           digitalWrite(10,LOW);
           delay(500);

           val = digitalRead(2);  // read input value
           if (val == HIGH) {         // check if the input is HIGH            (button released)
           digitalWrite(wrongLED, LOW);  // turn LED OFF
           } else {
           digitalWrite(wrongLED, HIGH);  // turn LED ON
           }
           val = digitalRead(3);  // read input value
           if (val == HIGH) {         // check if the input is HIGH           (button released)
           digitalWrite(wrongLED, LOW);  // turn LED OFF
           } else {
            digitalWrite(wrongLED, HIGH);  // turn LED ON
           }
           val = digitalRead(4);  // read input value
             if (val == HIGH) {         // check if the input is HIGH (button released)
           digitalWrite(wrongLED, LOW);  // turn LED OFF
           } else {
           digitalWrite(wrongLED, HIGH);  // turn LED ON
           }
           val = digitalRead(5);  // read input value
           if (val == HIGH) {         // check if the input is HIGH (button released)
           digitalWrite(wrongLED, LOW);  // turn LED OFF
           } else {
             digitalWrite(wrongLED, HIGH);  // turn LED ON
           }
           digitalWrite(correctLED, HIGH);

           }
           }

title: memory game arduino

Answers: 3

body:
For this kind of thing you don't really want to be worrying about "is this button and then this button pressed" etc. That thinking is very much "of the moment" in that it is all about what is happening now - not what has gone on in the past.

You need to be thinking about the sequence of button presses that you have seen so far - not what is happening right now.

Say you have three buttons.  Let's assign a number to each of them - say they are buttons 1, 2 and 3.

And you have 3 LEDs - let's call them A, B and C.

So you light and extinguish the LEDs in a specific order, say BAC, and you expect the buttons to be pressed in the same order - 213.

You can't be checking all the time for "If 2 is pressed then 1 is pressed then 3 is pressed" because, basically, where are you in that sequence at any one instance in time?  Instead you need to go:  "A button has been pressed. I'll store that fact." And then: "Have three buttons been pressed? Yes. Do their numbers match?"

Basically like a PIN code for your bank card, or a password for your computer. It's not what you are pressing now, it's what it remembers you pressing in the past.

And the simplest way of doing that is to literally allocate numbers to the buttons. When a button is pressed you assign a number representing that button to a variable. Then append that number to the list of numbers you have seen recently. When that list is the right length you compare it. Just like entering a password.

You can even compare what you have so far with a portion of what you expect to catch incorrect presses early.

So say you have an expected value of "213" stored in a string. You also have an empty string. When you press a button you append that number to the string - so say you press "212" you could then append and compare the string like this:

    Button  Input  Expected
    2       2      2         Correct
    1       21     21        Correct
    2       212    213       Incorrect - erase input content
    2       2      2         Correct
    1       21     21        Correct
    3       213    213       Correct - next round please.

body:
Format and extra braces aside there are other issues with your code, too many to fit in a comment.

 1. You have used led1, led2 etc in the setup routine and the resorted to numbers in the loop function.

 2. At the start of loop() you turn the leds high then low, you won't see this because the processor is faster than your eye, you need a delay statement after the last high and last low.
 3. You can make you code more elegant by writing a function that takes the pin as a parameter and toggles the led high then low and call this rather than repeating 4 lines of code.

>     void togglePin(int pinNumber, int interval)
>     {
>        digitalWrite(pin, HIGH);
>        delay(interval);
>        digitalWrite(pin, LOW);
>        delay(interval);
>     }

4. When it comes to reading values you have blocks of repeated code, again these could be a separate function, which will make your code easier to read and understand.

When you have done that you might want to so a bit of research on 'switch debouncing' because I'm guessing you might have issues with that too.

body:
Your code as written will have both the `wrongLED` and `correctLED` on. It will also continuously loop showing the sequence.

Showing the Sequence
====================
To show the sequence once at the start, put it in the setup function.
Read more about the setup function here: [http://www.arduino.cc/en/Reference/Setup][1]

Detecting the Button Presses
============================
You want to detect each press of the buttons. For this you will need **edge detection code**. There is an Arduino example built into the IDE and information describing the function here: [http://www.arduino.cc/en/Tutorial/StateChangeDetection][2]
To add to the Arduino explanation, you can either detect the rising edge (ie. the transition from a LOW to a HIGH) or the falling edge (ie. the transition from a HIGH to a LOW). I personally prefer the following code to detect a rising edge:

    if ( (lastButtonState == LOW) && (buttonState == HIGH) )

where `buttonState` would be assigned by a `digitalRead` and `lastButtonState` would record the value of `buttonState` at the end of the loop function (ie. just before it reads in the button states again).

Using your global arrays you could write:

    buttonState[0] = digitalRead(button1);
    buttonState[1] = digitalRead(button2);
    buttonState[2] = digitalRead(button3);
    buttonState[3] = digitalRead(button4);

    if ( (lastButtonState[i] == LOW) && (buttonState[i] == HIGH) )

where `i` is a number between 0 and 3. You could use a [for loop][3] to cycle through the 4 available buttons.

Recording the Button Presses
============================
The StateChangeDetection example above counts the number of button presses. Instead, you want to record 4 button presses. To do this create a global variable called `pressNumber`. Create it with the initial value of 0.

Create an integer array of 4 elements called `userSequence'.

Every time the if statement detects a rising edge, store the button number in the `userSequence' at position `pressNumber` and then increment the `pressNumber`.

When `pressNumber` reaches 4, the user has entered his/her guess.

Evaluating the Guess
====================
This only occurs once the user has entered the guess. Start off by creating a boolean variable and assign it TRUE. Cycle through the elements in the `userSequence` array and compare the users guess to the correct answer. If the user gets one wrong set the boolean variable to false. At the end, turn on the red LED or green LED depending on the state of the boolean variable (ie. if it is true turn on the green LED, otherwise turn on the red).

Final Notes
===========

 - As Matt suggests, try [refactoring][4] portions of code into functions. It makes the code more readable and reduces the complexity of the code.
 - You can use the variables for the pin numbers of the buttons and LEDs in the `digitalWrite` and `digitalRead` functions. Eg:

    digitalRead(button1);
    digitalWrite(led1);

  [1]: http://www.arduino.cc/en/Reference/Setup
  [2]: http://www.arduino.cc/en/Tutorial/StateChangeDetection
  [3]: http://www.arduino.cc/en/Reference/For
  [4]: https://en.wikipedia.org/wiki/Code_refactoring


body:
The problem occurred while testing a ping program with the ethercard examples from github.

Now no program will upload. It will say uploading.... and gets stuck there. The error message below appears:

    Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

    WARNING: Category '' in library UIPEthernet is not valid. Setting to 'Uncategorized'

    Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xdf
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xdf
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

      This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.

title: Problem uploading to Arduino Uno

Answers: 5

body:
 1. Remove the ethercard, return to the basic board.
 2. Disconnect the Arduino from the host.
 3. Reboot the host computer.
 4. Reconnect the Arduino.
 5. Upload the Blink example.

This should sort things out, well it did when it happened to me.

body:
I'm having the same issue on my Macbook Pro. It happens randomly. The only solution i found is disconnecting the USB cable from the PC wait for a few mins and reconnect it again (possibly using another USB port).
It worked for me!

body:
When you get this error, they have several things to check :

- Is my board reconised by Windows ?
- Is my board model is the right one ?
- Is the serial port is the right one ?
- Is my cable damaged ?

Generally the upload problem is easy to fix.

If your board is a custom one

- bootload problem
- crystal problem.
- reset not triggered properly ? (try to push it when arduino ide say "uploading sketch")

body:
If you have the Arduino Uno with removable chip then try to remove the IC. Then plug it again and check the power on the IC with a multimeter on pin 7 (+ positive) and pin 8 (- negative). If you are getting 5V there then you need to try to upload a simple blink sketch. If you are not getting the appropriate voltage then you can try to use a different wire to upload the sketch.

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

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

body:
Disconnect everything to Arduino, Plug in your Arduino to your computer - check for the Serial port, Check for your Arduino Model, select programmer as USBasp, open up BLink sketch from Examples and HIT upload.

if you don't see your Arduino in Tools>Port then it should be the problem of USB cable, Computer USB port or "DRIVERS"


body: in the datasheet, it's stated that I should apply 32 serial clocks to get the 32 bits of data. How can I program this is Arduino?

title: How to read data using Arduino SPI

Answers: 3

body:
You call `SPI.transfer()` four times, each time saving the returned value to a variable after proper bit shifting.

    uint32_t val;
    val = SPI.transfer(0xff);  //0xff is a dummy
    val |= (uint32_t)SPI.transfer(0xff) << 8;
    val |= (uint32_t)SPI.transfer(0xff) << 16;
    val |= (uint32_t)SPI.transfer(0xff) << 24;

I assume the least significant byte is received first. Make sure the SPI mode is the right one, as indicated in your datasheet.

If the slave can't handle being deasserted between bytes (which is what `SPI.transfer()` will do at the end of the transaction), then you can either try st2000's hardware SPI approach or use bitbanged SPI with `shiftIn()`.

body:
Objective is to read 32 bits using the (unknown) device's SPI port.

If the device will tolerate the SPI Chip Select line activity (going from inactive to active to inactive for each 8 bit byte read) you should be able to get the desired 32 bits of data by performing 4 consecutive 8 bit SPI reads.

However, if the device will not tolerate the above SPI Chip Select line activity (that is, if the device requires the SPI Chip Select to be active for the entire 32 bit SPI transaction), you can not separate the 32 bit transaction into 4 individual 8 bit SPI transactions with out controlling the SPI Chip Select line.  The following code example illustrates how this is done:

    void loop(){
    //transfer 0x0F to the device on pin 10, keep the chip selected
    SPI.transfer(10, 0xF0, SPI_CONTINUE);
    //transfer 0x00 to the device on pin 10, keep the chip selected
    SPI.transfer(10, 0×00, SPI_CONTINUE);
    //transfer 0x00 to the device on pin 10, store byte received in response1, keep the chip selected
    byte response1 = SPI.transfer(10, 0×00, SPI_CONTINUE);
    //transfer 0x00 to the device on pin 10, store byte received in response2, deselect the chip
    byte response2 = SPI.transfer(10, 0×00);
    }

The above example comes from the [Arduino SPI library web page][1] and is a 16 bit (not 32 bit) transfer.  To code up a 32 bit transfer, continue to call the SPI.transfer method using the SPI_CONTINUE parameter.

added later...

It appears people are discouraging use of the DueExtendedSPI methods. And SPISettings and SPI.beginTransaction() are to be used? If so [this page][2] show example code where the code is explicitly controlling the SPI Chip Select line (look for slaveAPin & slaveBPin).  Note how the code is reading 24 bits from slave A and writing 8 bits to slave B. To read 32 instead of 24 bits, we need to alter a segment of the code (along with a few other supporting changes) in this fashion:

    ...
      SPI.beginTransaction(settingsA);
      digitalWrite (slaveAPin, LOW);
      // reading only, so data sent does not matter
      val0 = SPI.transfer(0);
      val1 = SPI.transfer(0);
      val2 = SPI.transfer(0);
      val3 = SPI.transfer(0);
      digitalWrite (slaveAPin, HIGH);
      SPI.endTransaction();
    ...

  [1]: https://www.arduino.cc/en/Reference/DueExtendedSPI
  [2]: https://www.arduino.cc/en/Tutorial/SPITransaction

body:
Sparkfun has a good explaination of what SPI is:
https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi

The Arduino IDE has a SPI library that comes with the IDE.
http://www.arduino.cc/en/Reference/SPI

The library comes with two examples:
[Using SPI to read a Barometric Pressure Sensor][1]
[Controlling a Digital Potentiometer Using SPI][2]

  [1]: http://www.arduino.cc/en/Tutorial/BarometricPressureSensor
  [2]: http://www.arduino.cc/en/Tutorial/DigitalPotControl


body:
I am using ESP8266 and Arduino with `SoftwareSerial`. My requirement is to use MQTT protocol with it. So I am using an MQTT library named `pubSubClient` but the problem is it doesn't support `SoftwareSerial`. Could anyone tell me how can I use MQTT protocol with it?

    #include
    #include
    SoftwareSerial esp(2, 3); // RX, TX
    PubSubClient client(esp);

The error I get is: `no matching function for call to 'PubSubClient::PubSubClient(SoftwareSerial&)`

title: mqtt library which support softwareSerial on arduino uno with ESP8266

Answers: 2

body:
Not sure what you're trying to do - but thought I would offer this since I just spend some time on getting my esp8266 to act as a wifi shield for my arduino.  Basically I wanted to subscribe to an mqtt channel and send the payload to my arduino.  So the esp8266 connected to a broker, upon reading a message, it would simply write it via serial to the arduino (I used software serial on the arduino side so I could use the standard serial for debugging).  If it helps, check out http://mganis.blogspot.com for the details

--Matt

body:
In order to use the ESP8266 WiFi module with `pubSubCient`, you need a library that interfaces with the module with the usual AT commands, while presenting an Arduino `Client` interface on the surface. A while back, I found [this library][1] after a great deal of searching. It supports `SoftwareSerial` as well as `HardwareSerial` objects. Its ESP8266 interface provides the standard `Client` methods of `write()`, `read()`, `connected()`, etc. There are some issues, of course, but its the best I've found so far. You can pass the created `Client` object to the `pubSubClient` constructor and you're good to go.

  [1]: https://github.com/bportaluri/WiFiEsp


body:
I think that Visual Studio is a great product! I find the Arduino IDE is limited in its features. For example the Arduino IDE does not have:

 - Code prediction
 - Error highlighting
 - Previews of #define values
 - Peek at code definition
 - Jump to code definition
 - and many more...

Since the Arduino ino & pde file types are basically C++, Can I use the Visual Studio IDE instead of Arduino IDE?

To be considered as a replacement, Visual Studio must be able to:

 - Save & open ino & pde files.
 - Compile my code.
 - Download my code.
 - Use existing/custom libraries from the Arduino IDE.
 - Detect and display an Arduino project.

I would consider these features as a bonus:

 - Arduino board selection.
 - Debugging
   - Variable watch window
   - Breakpoints
   - Step through code
 - Simulation
 - Open the Arduino Examples
 - Automatic board detection
 - Serial Monitor

title: Can I use Visual Studio instead of Arduino IDE?

Answers: 4

body:
It's not exactly what you are asking, but maybe you would be willing to consider a solution based on [Eclipse][1]?

Eclipse has the advantage of being cross platform, so you can have the same experience no matter what your OS might be.

Although, for the sake of completeness, almost all you mentioned can be done even with vim, if adequately configured. But I wouldn't recommend it as first choice, if you have never used it before.

  [1]: http://eclipse.baeyens.it/

body:
I only use Visual Studio for Arduino programming.
[Arduino Plugin for Visual Studio][1]

  [1]: http://www.visualmicro.com/

body:
Atmel Studio 7 which is built with Visual Studio. Google "Atmel Studio 7" or [click here][1]. It has everything you want and it's released by the company that makes the atmega328 your Arduino is built on.

  [1]: http://www.atmel.com/Microsite/atmel-studio/

body:
Note, this answer is not technically for the full edition of Visual Studio, rather Visual Studio Code.

Microsoft has released an [Arduino extension](https://marketplace.visualstudio.com/items?itemName=vsciot-vscode.vscode-arduino) for VS Code that can do most (all?) of the required items in the OP's list.

Added this answer as a free alternative to the accepted answer.


body:
i use this simple code for arduino :

    const int buttonPin = 2;
    const int ledPin =  13;

    int buttonState = 0;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      Serial.begin ( 9600 ) ;
    }

    void loop() {
      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH) {
        digitalWrite(ledPin, HIGH);
        Serial.println ( buttonState ) ;
      } else {
        digitalWrite(ledPin, LOW);
        Serial.println ( buttonState ) ;
      }
    }
it's so basic program, I've seen some people work with Resistors when they use buttons, so i wanted to know why, i plugged in one side of the button to the pin 2 , no matter if i plugged in the other side of the button or no to the 5 volte source, the arduino started giving me some ones and zeroes therefore the blinking of the led, so basically that means there's a certain voltage comming from the button to the pin 2, I wonder why and what's the reason for this ?

title: upcoming voltage from a button

Answers: 2

body:
I see you are new to Arduino, so let's start:
1) if you say it works you might be using an circuit like this:

![button no GND](https://i.stack.imgur.com/DVLkW.jpg)

which is not all bad but you might find trouble. I explain:

**1.** When you set pinMode(pin,**INPUT**); you tell arduino to enable a **high-impedance state** on that pin: it's equivalent to **100Mohm** resistor in series in front of that pin, good for getting sensor readings, but when you use a switch the state/reading of that pin (HIGH or LOW) is "floating" when the switch is opened which will give unpredictable readings.
That's why you need to use a "pull-down" resistor, which means you pull down the value of that pin when the switch is OPENED by using GND as reference value for LOW so you are sure it goes down when switch is opened. The resistor also serves as protection (10Kohm is recommended) when the switch is CLOSED as it stops the high current flow/drain (!!5V pin connected to GND!!) that arduino can't support without (aka short-circuit).

**2.** So you end up with something like this:
![button with pull-down](https://www.arduino.cc/en/uploads/Tutorial/button.png)
I would personally put the resistor and the GND wire between the button and the digital pin wire.
I hope I was useful! If you need/want more documentation check those two links out:

https://www.arduino.cc/en/Reference/Constants look into "Defining Digital Pins modes" section

https://www.arduino.cc/en/Tutorial/DigitalReadSerial here you have an practical example.

body: Note that there is another, easier way to do this. If instead of setting your pin to INPUT, you set it to INPUT_PULLUP then internally the input line is connected through a resistor to +5 volts. Then when nothing is connected to the pin, it reads as HIGH. You connect your input to a switch, and connect the other pin of the switch to ground Now when you press the switch it grounds the input pin, pulling it low. No resistors needed, but it does mean the state of your switch is reversed (HIGH = switch not pressed, LOW = pressed)


body:
So I am building a project that uses the analog pins for precise measurements of resistance through a voltage divider and I have been having some seemingly unsolvable problems with nonlinear response to linearly changing resistances when using the A0 pin to measure.

I first realized this was the problem when I had a voltage divider consisting of a 76.8K and 100K 1% resistors with Vout connected to A0, and I was consistently getting wrong values. I measured the output voltage of the voltage divider and got 1.7V, instead of the ~2.7 volts I should be getting with my supply. When I disconnected the wire to A0, the voltage rose to the expected level.

I disconnected power and measured resistance between the analog pins of the Atmega328 I was using and ground and found that A0 had 220K of resistance, while all other pins measured as infinite. When using the other pins, the voltage divider returned the expected values and was able to measure a wide range of resistors with values just as accurate as my multimeter. I know I have changed a lot of low-level things with code (analog reference, the comparator, ADC clock prescalers, using analog pins as outputs, etc.) but I don't think any of this could persist while the chip is not powered on. Does doing any of these things connect a resistor in the way I was describing, and is there anything that could cause this to stay "stuck" this way?

title: It seems as if there is a 220K pull-down resistor on analog pin 0

Answers: 1

body:
They don't connect a resistor as such, but analog input pins do have an *impedance* which can affect your readings.

If your output impedance (the resistance of your resistors) is within about a tenth of the impedance of the input pin then you will (and have) noticed skewing of the results.  This is normal.  The input impedance is somewhere in the region of 1MΩ - 10MΩ.

You have to keep your output impedance to a value below the order of a few tens of kΩ to minimise the effect the measuring of the value has on the value.

If you want to measure higher resistances then you will need to buffer the voltage with a very high impedance op-amp buffer.

Incidentally, your volt meter probably has an input impedance in the region of 10GΩ - around 1000x higher than the Arduino's ADC.


body:
I have multiple Arduinos that I want to control using Python. My problem is that when I plug my Arduinos into the computer, they get assigned the port `/dev/ttyUSBx` where `x` increments with each one I connect.

Is there any way to reserve a certain number for a certain Arduino so that I can hard code that into the Python script? If not, can I scan the port to figure out which Arduino it is?

title: Reserve /dev/ttyUSBx

Answers: 1

body:
Yes. You need to create new unique names for them using udev rules.

By using the unique serial number, along with the VID and PID of the board you can use udev to create a symbolic link to a device name of your choice. Best to keep it to something that the Arduino IDE recognises if you want to access the link from within there for programming (otherwise you can choose what you like).

Rules are stored in /etc/udev/rules.d and take the form of `.rules` files with various instructions in.  One example, that should do what you want, is:

    SUBSYSTEMS=="usb", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="6493832323135111C0A1", KERNEL=="ttyACM*", SYMLINK+="ttyACM50", MODE="0666", GROUP="plugdev"

Of course, tweak it to your personal requirements.

Once you have crafted your rules be sure to restart udev:

    sudo systemctl restart udev

or

    sudo /etc/init.d/udev restart

and plug your board in.

Genuine Arduino devices usually use /dev/ttyACM* not /dev/ttyUSB*. If you have /dev/ttyUSB* then you are either on a very old device (with an FT232 chip) or a cheap Chinese clone.

If the latter then your mileage may vary somewhat.


body:
I'm trying to use the Arduino IDE (1.6.8 downloaded from arduino.cc) on a MacBook running OS X (10.11.5 beta).

The IDE seems to run and I can open and upload the examples and they run. But…

I can't type in the editor window of the IDE – either with the examples or with the new sketch that opens when you launch the IDE.

I have a similar problem with the version of the IDE distributed with mBlock (1.6.5) if I use the Edit in Arduino IDE button. I also tried the 1.6.9 hourly version. All to no avail. So I'm thinking that this is a OS X problem, or maybe an issue with version of Java (1.8.0).

Any ideas or troubleshooting suggestions?

title: Unable to type in Arduino IDE running on OS X

Answers: 3

body: Make sure that in `preferences` the option `Use external editor` is **not** checked.

body:
I find solution on this forum [http://forum.arduino.cc/index.php?topic=93338.]
File | Preferences | Use External Editor (Don't use)

body: you may also consider Sublime Text -> with the STino plug-in, it is a full-fledged editor that does everything your arduino IDE does, in a much more stylish way.


body: Can I make all in one arduino robot? Example - line follower, bluetooth control, sonar sensor,dtmf in one arduino robot just switch to any mode without change the parts.

title: all in one Arduino robot

Answers: 1

body:
Yes, actually it has been done before (multiple times).
I, along with some other students did such a project at my school.

https://www.youtube.com/watch?v=GTJQ2VXtmk0
https://www.youtube.com/watch?v=sXXh3Q8WoEM

**Materials needed**

 - Arduino (or other programmable microcontroller board with voltage regulation)
 - Battery pack (and charger)
 - 2 to 5 line sensors
 - ultrasonic sensor
 - Bluetooth module
 - Robot chassis
 - Atleast two motors (with encoders is nicer, but not neccesary)
 - Motor driving circuitry
 - Switch and emergency stop button

It can be useful to buy a "line follower robot kit"

**Connection**

This is the connection we used. You're free to make your own adjustments.

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

**Programming**

We used a server that (was connected via bluetooth) and has the map and a user-interface.
When you press the end-point on the server, it would generate the shortest route, calculate the directions, and send it to the robot.

The robot would then drive until it comes to a junction and then executes the direction command.

I've attached some preview code. It's better to do it yourself, but if you really don't know where to get started, you can try this.
You will have to implement the low-level code yourself.

The robot will wait for Bluetooth messages. You can set it to a "direct drive" modus or "line following" modus.

    void setup() {
      // put your setup code here, to run once:
      setupBluetooth();
      setupUltrasonicSensor();
      setupMotors();
      setupLinesensors();
      state=waiting;
    }

    void loop() {
      char receivedCharacter = bluetoothReceiveCharacter();

      switch (state) {
        case waiting:
          switch(receivedCharacter){
            case 'd':
              bluetooth.println("Direct Drive enabled!");
              state = directDrive;
            break;
            case 'l':
              bluetooth.println("Line following enabled!");
              state = following;
              motor1.setSpeed(50);
              motor2.setSpeed(50);
            break;
          }
          break;
        case directDrive:
            directDrive(receivedCharacter);
          break;
        case following:
            followLine(receivedCharacter);
          break;
        default:
          bluetooth.println("STATE ERROR!");
          buzzer.buzz();
          led.blink();
        break;
      }
    }

    void followLine(){
        long distance = ultrasonicSensor.measureDistance();
        unsigned char lineSensorsPattern = lineSensors.getPattern();

        switch(receivedCharacter){
          case 'X':
            bluetooth.println("Line following disabled! (Now waiting)");
            state = waiting;
          break;
        }

        if(distance > 100 || distance == -1){
          switch(lineSensorsPattern){
            case 0b00000000:
              motor1.setSpeed(0);
              motor2.setSpeed(0);
              bluetooth.println("Following interrupted, lost path!");
              findPath();
            break;
            case 0b00000100:
              motor1.setSpeed(100);
              motor2.setSpeed(100);
              bluetooth.println("Following line, middle sensor on.");
            break;
            case 0b00000100:
              motor1.setSpeed(100);
              motor2.setSpeed(100);
              bluetooth.println("Following line, middle sensor on.");
            break;
            case 0b00000110:
              motor1.setSpeed(70);
              motor2.setSpeed(100);
              bluetooth.println("Following line, middle & right sensor on.");
            break;
            case 0b00001100:
              motor1.setSpeed(100);
              motor2.setSpeed(70);
              bluetooth.println("Following line, middle & left sensor on.");
            break;
            case 0b00000010:
              motor1.setSpeed(0);
              motor2.setSpeed(100);
              bluetooth.println("Following line, right sensor on.");
            break;
            case 0b00001000:
              motor1.setSpeed(100);
              motor2.setSpeed(0);
              bluetooth.println("Following line, left sensor on.");
            break;
          }
        }else{
          bluetooth.println("Following interrupted, obstacle in path!");
        }
    }

    void directDrive(char receivedCharacter) {
      switch (receivedCharacter) {
        case 'X':
          motor1.setSpeed(0);
          motor2.setSpeed(0);
          state = waiting;
          bluetooth.println("Direct Drive disabled! (Now waiting)");
          break;
        case 'w':
          motor1.setSpeed(motor1.getSpeed()++);
          motor2.setSpeed(motor2.getSpeed()++);
          break;
        case 'a':
          motor1.setSpeed(motor1.getSpeed()++);
          motor2.setSpeed(motor2.getSpeed()--);
          break;
        case 's':
          motor1.setSpeed(motor1.getSpeed()--);
          motor2.setSpeed(motor2.getSpeed()--);
          break;
        case 'd':
          motor1.setSpeed(motor1.getSpeed()--);
          motor2.setSpeed(motor2.getSpeed()++);
          break;
      }
    }

**My advice**

My best advice is to work in iterations. Slowly add more features until you've got the product that you desire. Or develop parts of it individually.

 1. Get a bluetooth link working, send some messages back and forth.
 2. Connect motors to an Arduino and chassis let it drive a pre-programmed path.
 3. Get some line sensors to work (non reflecting black tape!)
 4. Get a ultrasonic sensor to work.
 5. Start combining these! Control the robot over bluetooth. Let the robot follow the lines. Add a breaking when it sees something within range.

----------

As addition/clarification.
You could make a button, that increases the state every time you press it.
If you then check which state the robot is in, you can make it perform his task for that state.

    if(buttonPressed){state++;}
    if(state>3){state=0;}

    if(state==0){
      //code for DTMF handling
    }else if(state==1){
      //code for bluetooth
    }else if(state==2){
      //code for sonar
    }else if(state==3){
      //code for line sensors
    }

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


body:
I'm measuring two temperatures  and powering both tmp36 sensors off of the 5v pin.  For some reason pin A0 (t0) will periodically spike or dip 100°f over actual ambient and pin A1 (t1) will spike or dip but only by about 30°f at the same time but not necessarily in the same direction at A0.

I'm using about 4' of 24ga solid wire to each sensor.

This began with a wall adapter putting out 5v 850ma connected to the barrel connector

Previous adapter of 5.3v 2a worked fine connected via USB.

I don't think it's SW because the arduino is doing exactly what I want it to do: measure t0 and t1 and write them to a database table via wifi.  I'm thinking that I need a 5.3v 2a barrel connector.  Am I right?

title: Tmp36 spike and dip

Answers: 0


body:
What is the "proper" way to handle an error during setup on an Arduino -- for example some attached component is missing or returning an error code or invalid response?  The `setup()` function returns void so that's no help. This just doesn't seem to be an issue that is addressed in the official docs -- at least not that I have found so far.

Here are some options I have considered:

 - Throw an exception (but where does that go?)
 - Write a message to `Serial` and then go into an infinite loop or wait for a y/n to continue.
 - Set a setup_successful flag and then do `if (!setup_successful) return;`  in the main `loop()`

title: How to handle an error in setup()

Answers: 2

body:
Same way you would handle any error in an embedded system; either try to recover from it if you can, or use whatever communications mechanism you have to let the user know that something failed.

I normally use a combination of Serial.println in case I happen to have a serial connection at the time, and also a blinking pattern on an LED (which most boards I use have). As an example, look at my code here: https://github.com/jayeye/jardino/blob/master/libard/WiFiSPIFFSConfig/src/WiFiSPIFFSConfig.cpp#L11. `error()` will do a sequence of slow and then fast blinks, and either return if I think the error is recoverable and I'm merely warning the user, or just stay in an infinite loop and keep blinking in despair :)

Obviously this is not an original idea -- think beep codes!

body:
> The setup() function returns void so that's no help.

You wouldn't be able to get the return value anyway even if it did return something - it's not you calling the `setup()` function, but `main()`, which is not in your code or control.

> This just doesn't seem to be an issue that is addressed in the official docs

That is because it is not within the remit of the API and its associated documentation.

> Throw an exception (but where does that go?)

It goes in the bin.  Exceptions are disabled.  They make little sense in an embedded system.  Yes, it is possible to use them, but not worth it.

> Write a message to Serial and then go into an infinite loop or wait for a y/n to continue.

That kind of thing is what most people do - or variations on that kind of theme.

> Set a setup_successful flag and then do if (!setup_successful) return; in the main loop()

That will just run `loop()` again - after all, it's called `loop()` for a reason.

You seem to be in the mindset of a PC programmer. Embedded programming is a very very different beast. You don't (usually) have an operating system to handle exceptions and errors and things like that. You don't have a keyboard and mouse, and a screen with pretty pictures on it. Every single thing that the board does is what you program. If you want it to raise an error when an error occurs then it is up to you to program a suitable mechanism for that to happen. Reporting that error and asking for feedback in some way is entirely governed by your system's design. If you have a TFT screen you could put an error message on that. If you have a serial connection you can use that to show error messages. If you don't have any of those you can blink an LED or use a buzzer to beep in a specific pattern (like a PC's POST beeps).


body: If Arduino IDE itself is built on Java can I run JVM on the Arduino? If yes how should I do it?

title: I want to run jvm on arduino.What minimum configuration do I need?

Answers: 1

body:
Search for "embedded java". Oracle supports it for ARM cores, which is what some of the arduino-like boards such as the Teensy 3.X have, but I doubt they have enough resources to support it.

There is haiku-vm (google it!) that's designed with AVR processors in mind, but I don't know how actively it is being worked on.

Googling "embedded java avr" yields a tremendous amount of results; did you even try that?


body:
So I'm running a program that involves both Arduino and a Raspberry PI and they are communicating between the Serial port. As you can see below when my an emergency stop door, involving a magnetic switch, is opened then the PI sends a message to the Arduino. When the door is closed the PI sends a different value telling the Arduino to continue with the program. The Arduino is receiving and reading the messages correctly as I have ran a few tests with the serial monitor.

When the door is open the PI is printing '1' which shuts down the Arduino correctly. My problem is that when I close the doors nothing happens when in theory it should break the loop and continue to run the main Arduino code. The raspberry PI is correctly printing '2' and the Arduino is correctly reading this value as it prints "Logoff" in the serial monitor.

If anyone can help or lead me to correctly breaking this loop and returning to the main code that would be great.

Thanks.

Below is the emergency part of the code that continues to run. If the full code is needed I will gladly edit it into this post. Also if the PI code is needed I will post that too, I don't believe is necessary because there are no problems on that side.

    void Estop() {
     if (Serial.available()) {
      int d = Serial.read() - '0';

      while (d == 1) {
       digitalWrite(green, HIGH);
       digitalWrite(red, LOW);
       digitalWrite(blue, HIGH);
       digitalWrite(estopout, HIGH);
       digitalWrite(piston, LOW);
       digitalWrite(belt, HIGH);
       Serial.read() - '0';
       Serial.print(d);
       delay(2000);
       break;

       if (d == 0) {
        Serial.print("Logoff");
        delay(2000);
       } else {
        break;
       }
      }
     }
    }

`

title: My code is stuck in a loop involving Serial.read. How can I break this?

Answers: 2

body:
You never reassigned the variable d anywhere within the loop. The `while` breaks after a 2 seconds delay after printing what is the value of d. That means that your `if (d == 0) [...]` never gets hit. I presume that you expect to read 'logoff' on your code?

    void Estop() {
        if (Serial.available()) {
            int d = Serial.read() - '0';

            while (d == 1) {
                digitalWrite(green, HIGH);
                digitalWrite(red, LOW);
                digitalWrite(blue, HIGH);
                digitalWrite(estopout, HIGH);
                digitalWrite(piston, LOW);
                digitalWrite(belt, HIGH);
                d = Serial.read() - '0';
                Serial.print(d);
                delay(2000);
                #break;

                if (d == 0) {
                    Serial.print("Logoff");
                    delay(2000);
                } else {
                    break;
                }
            }
        }
    }

body:
Inside your while loop, __you never change the condition__, running into an infinite while loop.

Further: Your program does not delay until `d` equals `0` or `1`. This can be problematic as `d` can have other values. It is an `int`.

__Plus__, you do a `while` loop while `d` equals `1` and ask, if `d` equals `0` without changing the value of `d` in between. Your `if` would never be true.

I also don't know, what this line should do:

    int d = Serial.read() - '0';

did you mean:

    int d = Serial.read();

I dont't see any sense, to subtract `0` from your the value you read.