body:
I'm new to Arduino, but I have this idea for a game I would like to build.

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

What would be the best way to achieve that?

Priorities:

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

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

title: Detect my position

Answers: 2

body:
Whether it's outdoor proof or not depends on the housing where you put your electronics.

For position tracking, there are basically 2 ways:

1. GPS

2. Acceleration sensors

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

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

Luckily, for position tracking on a straight line, there's another solution:

3. [use a ultrasonic sensor][1]

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

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

Edit:

It could be worth considering the following alternative:

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

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


body:
Anybody had worked with ESP8266 to post data to RESTful web service? I was trying but it's not posting anything. Tried with a test server:

http://www.posttestserver.com/
<!-- language-all: lang-cpp -->

    Serial.println("\nSetting AT+CIPSTART");
    String client_conn = "AT+CIPSTART=\"TCP\",\"";
    client_conn += SERVER;
    client_conn += "\",";
    client_conn += PORT;
    Serial.println(client_conn);
    Serial2.println(client_conn);
    delay(3000);
    while (Serial2.available() > 0) {
        c = Serial2.read();
        Serial.print(c);
        if(c=='\n\r' || c == '\r\n')
        Serial.println('\n\r');
    }

It showed me that it got connected
Now I created POST string

    String data = "{JSONBODY}";
    String post = "POST /post.php HTTP/1.0\r\n";
    post += "Host: posttestserver.com\r\n";
    post += "Content-Length: ";
    post += data.length();
    post += "\r\n";
    post += data;

Transmitting data

    Serial2.print("AT+CIPSEND=");
    Serial2.println(post.length());
    delay(1000);
    if(Serial2.find(">")) {
        Serial2.println(post);
        while (Serial2.available() > 0) {
            c = Serial2.read();
            Serial.print(c);
            if(c=='\n\r' || c == '\r\n')
                Serial.println('\n\r');
        }
        delay(5000);
        Serial2.flush();
        delay(5000);
    }

Returned nothing
Closing connection

    delay(1000);
    Serial2.println("AT+CIPCLOSE");
    while (Serial2.available() > 0) {
        c = Serial2.read();
        Serial.print(c);
        if(c=='\n\r' || c == '\r\n')
            Serial.println('\n\r');
    }
    delay(5000);
    Serial2.flush();

Connection closed

But It returned nothing. posttestserver returns data path where it stored.

title: RESTful API with ESP8266 and arduino mega

Answers: 0


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

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

Thank you in advance

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

title: Read signal from USB mouse on an Arduino ?

Answers: 1

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


body:
I have made two libraries and one test program.I have made my custom uart library.first i have included all functions for printing in single uart library file.but then i have made print library for printing functions only.my files are listed below.i have not posted my code directly so it can be read separately.

[**uart.h**][1]

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

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

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

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

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

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

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

>Test.cpp

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

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

and i get this error..

>Error

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

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

title: Can't use base class and derived class functions

Answers: 1

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

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

    virtual void write(unsigned char data) = 0;

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

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

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


body:
I followed a couple tutorial on how to receive and send IR codes to control air conditioner the receiving part is working fine and I copied the IR data of the remote control but the problem I am having is sending these codes via IR led can't seem to get it to work can someone help me please.

This the code to send the date via IR LED

    #include "IRremote.h"
    IRsend irsend;
    void setup()
    {

    Serial.begin(9600);
    }

    int khz=38; //NB Change this default value as neccessary to the correct modulation frequency
    // ON and 2O C° with 1 FAN heat
    unsigned ON[] ={4400,4300,550,1600,550,500,600,1550,550,1600,550,500,550,550,550,1550,550,550,550,500,550,1600,550,500,600,500,550,1550,600,1550,600,500,550,1550,600,500,550,500,600,500,550,1600,550,1550,550,1600,550,1600,550,1550,600,1550,600,1550,550,1600,550,500,550,550,550,500,550,550,550,500,550,550,550,1550,550,550,550,500,550,1600,550,500,550,550,550,500,550,1600,550,500,600,1550,600,1550,550,500,600,1550,550,1600,550,1550,600};
    unsigned OFF[] ={4350,4350,550,1550,550,550,550,1600,500,1600,550,550,500,550,550,1600,550,550,500,550,550,1600,500,550,550,550,500,1600,550,1600,550,500,550,1600,550,550,500,1600,550,1600,550,1600,550,1600,550,500,550,1600,550,1550,550,1600,550,550,500,550,550,550,500,550,550,1600,500,550,550,550,500,1650,500,1600,550,1600,550,500,550,550,550,500,550,550,550,500,550,550,550,500,550,500,600,1550,550,1600,550,1600,500,1650,500,1600,550};

    void loop() {

    irsend.sendRaw(ON, sizeof(ON)/sizeof(int), khz);
    delay(5000);
    irsend.sendRaw(OFF, sizeof(OFF)/sizeof(int),khz);
    delay(5000);
    }

The problem is my A/C doesn't detect IR codes.

title: Control air conditioner using Arduino

Answers: 0


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

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

title: print data after being plugged back into USB

Answers: 1

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


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

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

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

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

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

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

    unsigned long lastTime = millis();

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

      Serial.begin(9600);
    }

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

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

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

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

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

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

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

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

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

title: PIR motion sensor stuck in a loop

Answers: 1

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


body:
I have accidentally implemented a program that imitates the click of the mouse.

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

Can I solve this problem?

title: How to avoid that my arduino clicks eternally?

Answers: 1

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

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


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

HERE is my code:

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

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

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

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

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

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

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

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

      lastButtonStateA = buttonStateA;
      lastButtonStateB = buttonStateB;
     }

title: Arduino UNO button LED brightness vary

Answers: 2

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

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

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

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

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

        analogWrite(ledPin, currentBrightness);
    }

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

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

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

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

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


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

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

title: SFML Packet and Arduino

Answers: 1

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

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


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

I wrote the following code who works perfectly:

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

    #define DHTTYPE DHT11
    #define DHTPIN 13      // Digital

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

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

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

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

    void loop() {
      delay(2000);

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

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

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

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

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

    }

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

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

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

title: LiquidCrystal_i2c and Pin 2

Answers: 2

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

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

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

---

I withdraw that suggestion.

---

Can you please try saving some RAM?

Use the F macro with your prints, eg.

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

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

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


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

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

title: MQTT for GSM/GPRS sheild

Answers: 3

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

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

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

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

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

**Functionalities:**

**Auto connect**

 - Automatically connect to TCP and to MQTT server.

**connect function**

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

**OnConnect CallBack function**

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

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

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

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

**subscribe function**

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

**OnMessage CallBack function**

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

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

 - Inside this, you can write your custom code.

**unsubscribe function**

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

**disconnect function**

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

**Keep Alive**

 - You can specify your KeepAlive duration while initializing.

 - Ping requests are sent and received automatically.

**Subscribe Publish examples are also provided.**

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


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

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

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

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

title: DS1302 as a counter/count-up timer

Answers: 2

body:
Do you mean only accumulate during powered/driving, or also during standing still?

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

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

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

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


body:
I am working on a keypad password lock system based on arduino UNO. I have used the password library from Arduino's website.

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

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

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

Kindly tell me a solution to fix this.

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

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

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

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

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

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

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

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

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

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

Regards
Fawad

title: Exiting from one loop and get ready for another

Answers: 1

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

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

    password1.append('1');

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

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

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

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

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

        if (keypad.getState() == PRESSED)

which would be easier to read.


body:
I am using [this tutorial](https://github.com/tavendo/AutobahnPython/tree/master/examples/twisted/wamp/app/serial2ws) to connect an Arduino Yun with a browser using Autobahn.

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

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

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

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

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

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

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

Answers: 1

body:
Partial answer: to send more information than just a single byte, it is possible to run:

    # python
    payload = "Here is a longer string"

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


body:
I'm using the DYP-ME007TX sensor with arduino uno.
The output from this sensor comes in packets of 4-bytes:

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

Data is in MILLIMETERS

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

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

title: How to read bytearray from arduino pin in arduino sketch

Answers: 1

body:
I found the answer from forum.arduino.cc
There is a sketch

    #include <SoftwareSerial.h>

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

    SoftwareSerial mySerial(PING_RX_PIN, PING_TX_PIN);

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

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

      mySerial.begin(9600);
    }

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

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


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

title: Arduino does not work on battery

Answers: 4

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

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

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

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

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

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

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


body:
WM8731 codec was successfully interfaced with Atmega328 like variants in Arduino. It was first done successfully by Open music labs who are the makers of the breakout board for WM8731. Taking this library as reference another library was developed for atmega2560 Arduino and it also works fine. But now I am trying to get it work with Arduino Due which unlike other AVR micro-controllers in the Arduino family is an ARM. I found some useful code.It compiles well and is able to communicate with the WM8731 codec in I2C. I will post the original library and also explain in parts how the code for Due is built.

Original library is here:
http://cdn.sparkfun.com/datasheets/Dev/Arduino/Shields/AudioCodecNew.zip

My code split looking at the AudioCodec.h file.
<!-- language-all: lang-cpp -->

    #include <Wire.h>
    #include <SPI.h>

    #define LINVOL 23
    #define RINVOL 23
    #define LHPVOL 121
    #define RHPVOL 121
    #define ADCHPD 0
    #define SIDEATT 0
    #define SIDETONE 0
    #define DACSEL 1
    #define BYPASS 0
    #define INSEL 0
    #define MUTEMIC 1
    #define MICBOOST 0
    #define SAMPLE_RATE 44

    volatile boolean l;

    unsigned int temp = 0,temp1=0;
    int temp_spi[4];
    int m1[301],m2[301];
    //TC1 ch 0
    int left_in,right_in,left_out,right_out;
    void TC0_Handler()
    {
    TC_GetStatus(TC0, 0);

        temp = random(65535);
        //temp = left_out;
        //temp1 = right_out;
        temp_spi[0] = SPI.transfer(10,highByte(temp),SPI_CONTINUE);
        temp_spi[1] = SPI.transfer(10,lowByte(temp),SPI_CONTINUE);
        temp_spi[2] = SPI.transfer(10,highByte(temp),SPI_CONTINUE);
        temp_spi[3] = SPI.transfer(10,lowByte(temp),SPI_LAST);
        //left_in - (temp_spi[0]<<8)|temp_spi[1];
        //right_in = (temp_spi[2]<<8)|temp_spi[3];
        /*Serial.println("Hello");
        Serial.println(temp_spi[0]);
        Serial.println(temp_spi[1]);
        Serial.println(temp_spi[2]);
        Serial.println(temp_spi[3]);*/
    }

    void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq, uint32_t     frequency) {
        pmc_set_writeprotect(false);
        pmc_enable_periph_clk((uint32_t)irq);
        TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4);
        uint32_t rc = VARIANT_MCK/128/frequency; //128 because we selected TIMER_CLOCK4 above
        TC_SetRA(tc, channel, rc/2); //50% high, 50% low
        TC_SetRC(tc, channel, rc);
        TC_Start(tc, channel);
        tc->TC_CHANNEL[channel].TC_IER=TC_IER_CPCS;
        tc->TC_CHANNEL[channel].TC_IDR=~TC_IER_CPCS;
        NVIC_EnableIRQ(irq);
    }

    void AudioCodec_init() {
        randomSeed(analogRead(0));
        SPI.begin(10);
        SPI.setBitOrder(MSBFIRST);
        SPI.setClockDivider(10,21); // select to ss pin 10, 4 MHz
        SPI.setDataMode(10,SPI_MODE0);

        // setup i2c pins and configure codec
        // the new Wire library has trouble with 0x00, so (uint8_t) is added
        // To change the Wire interface speed, go to:
        // <path_from_arduino>\hardware\arduino\sam\libraries\Wire\Wire.h
        // and change the parameters TWI_CLOCK, RECV_TIMEOUT and XMIT_TIMEOUT
        // to the desire frequency.
        int temp_wire1;
        int temp_wire2;

        Wire.begin();
        Wire.beginTransmission(0x1a);
        Wire.write(0x0c); // power reduction register
        Wire.write((uint8_t)0x00); // turn everything on
        temp_wire1 = Wire.endTransmission();

        Wire.beginTransmission(0x1a);
        Wire.write(0x0e); // digital data format
        Wire.write(0x03); // 16b SPI mode
        temp_wire2 = Wire.endTransmission();

        //Serial.println(temp_wire1);
        //Serial.println(temp_wire2);

        Wire.beginTransmission(0x1a);
        Wire.write((uint8_t)0x00); // left in setup register
        Wire.write((uint8_t)LINVOL);
        Wire.endTransmission();

        Wire.beginTransmission(0x1a);
        Wire.write(0x02); // right in setup register
        Wire.write((uint8_t)RINVOL);
        Wire.endTransmission();

        Wire.beginTransmission(0x1a);
        Wire.write(0x04); // left headphone out register
        Wire.write((uint8_t)LHPVOL);
        Wire.endTransmission();

        Wire.beginTransmission(0x1a);
        Wire.write(0x06); // right headphone out register
        Wire.write((uint8_t)RHPVOL);
        Wire.endTransmission();

        Wire.beginTransmission(0x1a);
        Wire.write(0x0a); // digital audio path configuration
        Wire.write((uint8_t)ADCHPD);
        Wire.endTransmission();

        Wire.beginTransmission(0x1a);
        Wire.write(0x08); // analog audio pathway configuration
        Wire.write((uint8_t)((SIDEATT << 6)|(SIDETONE << 5)|(DACSEL << 4)|(BYPASS << 3)|(INSEL << 2)|(MUTEMIC << 1)|(MICBOOST << 0)));
        Wire.endTransmission();

        Wire.beginTransmission(0x1a);
        Wire.write(0x10); // clock configuration
        #if SAMPLE_RATE == 88
          Wire.write(0xbc);
        #elif SAMPLE_RATE == 44
          Wire.write(0xa0);
        #elif SAMPLE_RATE == 22
          Wire.write(0xe0);
        #elif SAMPLE_RATE == 8
          Wire.write(0xac);
        #elif SAMPLE_RATE == 2
          Wire.write(0xce);
        #endif
        Wire.endTransmission();

        Wire.beginTransmission(0x1a);
        Wire.write(0x12); // codec enable
        Wire.write(0x01);
        Wire.endTransmission();

    }

    void setup(){

        pinMode(2,INPUT);
        pinMode(10,OUTPUT);
        Serial.begin(115200);
        Serial1.begin(9600);
        Serial.println("Hello");
    AudioCodec_init();
    startTimer(TC0, 0, TC0_IRQn, 2000); //startTimer(TC1, 0, TC3_IRQn,   44100); //TC1 channel 0, the IRQ for that channel and the desired frequency
    }

    void loop(){
    //Serial.println("Hello");
    /*for(int i =0;i<300;i++)
    {
    m1[i]=map(analogRead(0),300,800,-400,400);
    m2[i]=map(analogRead(1),300,800,-400,400);
    }*/
    //for(int j =0;j<300;j++)
    //{
    /*Serial1.print("a");
    Serial1.print(m1[j]);
    Serial1.print("b");
    Serial1.print(m2[j]);*/
    //Serial1.println(left_in);
    Serial.print(temp_spi[0]);
    Serial.print(" ");
    Serial.print(temp_spi[1]);
    Serial.print(" ");
    Serial.print(temp_spi[2]);
    Serial.print(" ");
    Serial.println(temp_spi[3]);
    //Serial1.println("c");
    //Serial.println("In loop");
    //h23}
    }

So on atmega328 the clockout from the WM8731 was give to T1 pin and on atmega2560 timer 5 was used and clockout was attached to pin T5. I am just starting with Due and I dont know much about ARM but I set the code to TC0,TC0 timer and pin 2.

As described here in this link:
http://forum.arduino.cc/index.php?topic=130423.0

Some how the SPI part in this code and the timer is not working as I cannot get any voice out from the codec.I am also printing the temp_spi[x] variables over serial port and all of them are just zeros all the time. Could some one help me make this code work with the codec? The code compiles fine for Due in the arduino IDE.

title: Interfacing WM8731 code to Arduino Due

Answers: 0


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

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

Having said that, these approaches came up:

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

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

Answers: 3

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

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

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

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


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

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

title: How to start Arduino programming?

Answers: 1

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

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

> Is one Arduino device required for each Arduino project?

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

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

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

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

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

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

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


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

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

Example:

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

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

title: Determine XBee Packet Route

Answers: 1

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

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


body:
   i am having a problem while sending sms from arduino to a specific number. cell phone getting sms but every time it gets same unicode -" Ü " . plz help us

    //--------------------------
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3);

    void setup()
    {
        mySerial.begin(115200);
        mySerial.print("\r");
        delay(1000);
        mySerial.print("AT+CMGF=1\r");
        delay(20000);

        mySerial.print("AT+CMGS=\"+91..........\"\r");

        delay(20000);
        mySerial.print("Hello!\r");   //The text for the message
        delay(10000);
        mySerial.write(0x1A);  //Equivalent to sending Ctrl+Z
    }

    void loop()
    {

    }

title: sim 900 sending wrong sms -" Ü " to mobile phone from arduino

Answers: 0


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

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

The Output looks like this:

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

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

**Arduino Sketch:**

    int srr[8];

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

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

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

**Processing**

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

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

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

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

title: Arduino processing serial comunication - losing data?

Answers: 1

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

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

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

    if (content == 60) {

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

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

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

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

If you take a moment to read the [documentation on Serial Read](http://www.arduino.cc/en/Serial/Read) you will see this:

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

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

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


body:
How can I convert a string like the following:

    "pinMode(2, INPUT_PULLUP)"

    or

    'Keyboard.print("Hello world")'

into actual code that the Arduino can act on?

title: Convert a Serial string to a sketch command on Yun?

Answers: 3

body:
You can't - not directly.

There are two things you can do:

1. Build your "command" into a sketch and compile it, then upload it in to the Yun's AVR chip.  The compiling will have to be done on your PC, and the HEX file uploaded to the AVR (you can do it directly through the Yun's web interface).

2. Don't send sketch code, but send pre-defined instructions like "Turn on pin 3" which your sketch then interprets.  That could be as simple as two bytes "P3" for instance.  It's entirely up to you how you craft that.

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

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

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

There are probably many others.

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

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


body:
So sanity check for a potential project.

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

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

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

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

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

title: Sanity check with potential project. IoT with a dishwasher

Answers: 2

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

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

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

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

R series = (Vsource - V_opto_LED) / I_opto.
eg 12V source, 2V opto_LED (typical), 1 mA (should be enough for logiclevel signal.)
R = (12-2) / .001 A = 10/.001 = 10 k Ohm.

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

Ask if more information wanted.


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

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

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

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

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

title: How can I create a power rail on my Arduino shield?

Answers: 2

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

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

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


body:
Not sure if this is the right place to post this.

I have an Arduino Due I'd like to start using. I've been using Unos, Megas etc no problem. The newer IDEs have removed the Due support. I've been trying to install Due support through the Board Manager, but it just says there is an error downloading the files.

Is there a way to manually install the board support for the DUe, or must it be done automatically, connecting through the internet?

---

UPDATE

When I open the Boards Manager, I get :

`Error downloading http://downloads.arduino.cc/packages/package_index.json`

and when I try to install Due support, I get :

`Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2`

I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can't change that. I have tried to allow the IDE past the Windows Firefall, but that has not changed anything.

I have manually downloaded _sam-1.6.4.tar.bz2_ and extracted the contents to _C:\Arduino\arduino-1.6.5\hardware\arduino\sam_ (I had to manually create the _sam_ folder). With this, I can see the options of Arduino Due Native USB Port and Arduino Due Programming Port when selecting the board, and when I look for it in the Ports, it can recognise the board at the port (eg "COM5 (Arduino Due (Programming Port))" ). When I try to compile anything, I get the error message :

`Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-none-eabi-g++" (in directory "."): CreateProcess error=2, The system cannot find the file specified`

Any other idea as to how I can install the Due? Is there an option for a manual installation? The same happens with Libraries Manager (I don't get a connection), so I guess, the same can be applied to that.

---

UPDATE 2

Question has been answered:
https://github.com/arduino/Arduino/issues/3358

Many thanks to Federico Fissore!

title: Manual Arduino Due Installation

Answers: 1

body:
I had the same problem described above.
Error downloading http://downloads.arduino.cc/packages/package_index.json

I solved the problem, just deleting the temporary file: "package_index.json.tmp"


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

Koen

EDIT
This setup delivers a 16-bit resultion

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

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

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

title: Increase PWM bit resolution

Answers: 2

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

You cannot increase the resolution of the 8-bit timers. You can,
however, put the 16-bit timer in 16-bit mode, instead of the 8-bit mode
used by the Arduino core library. This will give you two 16-bit PWM
channels, with a reduced frequency of 244 Hz (maximum). You will
probably have to configure the timer yourself, and will not benefit from
the easy to use `analogWrite()` function. For details, see the section
on Timer 1 in in the [ATmega328P
datasheet](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf).

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

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

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

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

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

And here is an example sketch illustrating its use:

    void setup() {
        setupPWM16();
    }

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

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

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

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

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

More comment can be made if needed. Ask if interested.


body:
All cables tested and work:

    SCL - A5
    SDA - A4
    VCC - 5V
    GND - GND

I'm using an Arduino Nano board and an I2C display - I've tried everything to get it to work and I'm now convinced it's a hardware fault. Using the Arduino I2C address scanner, it is unable to find a device, even though it is wired correctly (I've checked multiple times).

[![Nano and I2C display][1]][1]

This is the code I used, [i2c_scanner][2], and this output:

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

... is all I get.

Any suggestions, or is my board output fried?

  [1]: https://i.stack.imgur.com/6qAFF.jpg "Nano and I2C display"
  [2]: http://playground.arduino.cc/Main/I2cScanner

title: Can't detect I2C displays with Arduino Nano

Answers: 3

body:
You seem to have two issues here:

 - As already pointed out, you have the white wire connected to the wrong pin on the Arduino
 - Also, **you need to solder the headers on the Arduino.** There is no solder on the pins, which means that there is no connection. You need to solder those headers on; it looks like you just set the Arduino on top, which won't work with headers

body: Check the solder jumper on the display. Note the example code is for one address, but two addresses are supported. Try the other address in code, or solder the LCD address pads to select the address to match the code. I had the same problem, the printed address on the LCD solder pads is just the last address bits that make the difference.

body: I had the same problem, with a lot of time lost, I tried to give current from another source, (an Arduino one) is all works, I think these Nano clones have some bugs on output voltages, to be checked. Anyway, so it worked.


body:
I know that the ADC on the Arduino Due has a clock speed from 1 MHz to 20 MHz. I have two questions: 1. What is the default clock speed when I run a sketch, and 2. How can I change it? (I am using Arduino 1.6.4.)

The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)
![enter image description here][1]

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

title: How to slow ADC clock speed to 1MHz on Arduino Due?

Answers: 2

body:
You can change the prescaler (`ADCSR` register). Lowest scaler is 2, so it can never run at 20mHz. Also Atmel recommends a max ADC clock of 1MHz.

Arduino sets the ADC clock to 125 KHz (prescaler of 128)

So to match Arduino, you should select a prescaler of 8 ( set bits `ADPS1` and `ADPS0`)

body:
The atod clock is set in the mode register. The clock is 42MHz/(PRESCAL#+1). One way of setting it is the use ADC->ADCMR = ADC_MR_PRESCAL(PRESCAL#), where PRESCAL# is some integer.  These symbols are defined in component_adc.h in the Arduino source code.
 In the AVR data sheet, the recommended clock is MIN=1MHz, MAX=20 MHZ, corresponding to numbers between 41 and 1. Look in the data sheet, section 43.


body:
I am doing a project using Arduino Uno and ADXL 345.
I am quite new to this and I came across this post  in the link" : https://www.sparkfun.com/tutorials/240. Here, a user had posted the below question in the forum.

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

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

Thanks

title: Relationship between baud rate and the frequency of vibration read using ADXL

Answers: 1

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

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

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

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

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

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


body: I want to make a toy car that follows a black line on the ground by using two sensor on the left and right sides of the car both pointing down. The sensor converts the light into a voltage that I will use to make the car turn left or right. I know that I can use batteries, but I am still very curious to find out if I could use my iPhone to power an Arduino because I also want to make a case with different sensors in it, and it would be thinner if I didn't have to put a 9V battery in the case.

title: Can I power a LilyPad with an iPhone lightning port?

Answers: 3

body:
If the phone has an accessible battery you could conceivably use the battery terminals to power a device such as Arduino. However, I think current smartphone batteries have complex monitoring circuits so this wont work.

If it doesn't, you'd be looking at using the USB/charger port on the phone.If your phone supports USB On-The-Go, I know that it allows phones to act as USB hosts, and according to USB-OTG specifications, the host must be able to supply at least 8mA of current between 4.4V and 5.25V.

If that's enough for you it could work.

body:
Try to look at the pinout of the lightning port and create your own breakout. Then you can try taking power from the iPhone. ![Apple's Lighting port pinout][1]

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

body:
For those coming here from Google.

**The short answer is:**

Yes you technically can, but it wont be dirt cheap or very pretty depending on your wallet and tastes/requirements.

**Longer answer:**

I was researching the same thing. The problem is that Lightning connector is fairly complicated, and before it will start giving you power it requires software authentication by a chip that is built into the cable. That said you can use the USB camera connection kit or you can buy one of the IK Multimedia mini usb cables:

http://www.ikmultimedia.com/products/cat-view.php?C=spareparts

I have had success trying to tap into their cable for iRig Pro cause I happen to have one, and it gives out solid 3.3V on one of the pins which is good enough for my Arduino Mini Pro. But I would vouch that their full blown mini usb cable should be supplying regular 5V.


body:
I would like to connect my Arduino Uno to a telephone line in order to answer a call, record a sequence of [DTMF tones](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling), generate a DTMF tone in response, and hang up.

The telephone line uses a standard [RJ11 connector](https://en.wikipedia.org/wiki/Modular_connector#RJ11_wiring). When a [touch-tone phone](https://en.wikipedia.org/wiki/Push-button_telephone#Touch-Tone) is connected to the line, it receives one of two rings:

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

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

How would I go about connecting my Arduino to the telephone line? Is there a shield designed for this purpose? I know I can use the [`tone()` function](http://www.arduino.cc/en/Tutorial/Tone) to generate the DTMF tones, but I'm assuming I would need to perform some form of [Discrete Fourier transformation](https://en.wikipedia.org/wiki/Discrete_Fourier_transform) in order to "read" the DMTF tones from the other end of the line.

Any suggestions would be appreciated.

title: Connecting an Arduino to a telephone line?

Answers: 2

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

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

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

  [1]: http://hackaday.com/2011/10/20/detecting-dtmf-tones-from-scratch/

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

![Ref Design][1]

Another popular design floating on the internet is below:

![popular design][2]

There are pre-build modules available from [futurelec][3] :

![module][4]

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

![encoder][5]

  [1]: https://i.stack.imgur.com/PcIHu.png
  [2]: https://i.stack.imgur.com/8uwXd.gif
  [3]: http://www.futurlec.com/Mini_MT8870.shtml
  [4]: https://i.stack.imgur.com/ZGJcL.jpg
  [5]: https://i.stack.imgur.com/xhE7V.png


body:
I have an old land line phone that I want to connect to my Arduino.  Then I would like to write a program that can decipher the touch-tone button presses (which are a combination of two tones) so that the Arduino can react to specific key presses and numeric sequences.  My final goal is to make the Arduino play specific messages when the user enters in codes.  I am really not sure even where to begin.

Thanks for the hardwares fixes for this problem, but if possible, I am looking for a softwares solution.

This will be used to make a telephone (with an attached Arduino) that will play a series of conversations when specific codes are dialed.

title: Can do I make an Arduino program that can decipher telephone touch tones?

Answers: 3

body:
It is possible to decode DTMF tones with only a few common external components. The trick is to turn the analog audio into a digital signal, and then check the timing between the leading and trailing edges in order to figure out which tone is present.

First, create a 1.1V bias using a voltage divider. This bias will connect to both a capacitor that is coupling the audio, as well as one of the analog inputs. **Note that phone lines have high voltages on them at times, and you must have both isolation and voltage clamping in place before connecting a device to one.**

Second, enable the analog comparator in the MCU. See the "Analog Comparator" section of the MCU datasheet for details. Configure the non-inverting input to connect to the internal bandgap reference, the inverting input to connect to the analog input chosen earlier, and the output to connect to the input capture facility.

Third, configure the input capture facility in the MCU. See the "16-bit Timer/Counter1 with PWM" section of the datasheet, with particular emphasis on the "Input Capture Unit" subsection. Note that there is no way to trigger the input capture on "any" edge, therefore you will need to either flip the capture edge select bit each time, or you will need to detect the tone from only one set of edges. Also note that you will need to use the overflow interrupt to increment your explicit "high bytes" counter in case the edges to be detected appear on opposite sides of the overflow.

Now that all that is done, all that remains is to compare the timing detected by the input capture with your internal table of timings and select the appropriate tone from that. But that's the easy part.

body:
DTMF is actually two non-harmonically related frequencies transmitted at the same time as opposed to a single frequency tone that can be measured with the above process, hence Dual-Tone-Multi-Frequency:

![DTMF Frequency to Code table][1]

You can use the Rohm BU8872 series devices which decodes the 4 x 4 multi tone combinations directly into a 4 bit digital result per the grid above.  This also works the same way in the Mitel MT8870 series devices (I think they were bought by Microsemi).  These have digital filtering which pick out the two signals and some devices can even do single tone detection.

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

body:
As John Taylor said, DTMF is not a single tone but two tones transmitted simultaneously, which select the digit from a two-dimensional grid. (*Dual* tone multi-frequency). This allow 16 possible combinations from only 8 distinct tones.

There are chips available specifically for the task of decoding DTMF, but it's always nice to try and find a one-chip solution.

There are two solutions that I can think of:

 - [ArduinoFFT][1] - a **Fourier transform** is an operation that splits a time-based signal into its frequency components. If you control the ADC directly instead of via the Arduino library, it is easily fast enough to sample a DTMF signal. Once you've done the FFT you just need to find the peaks in the output, which will tell you the tones that are present.
 - If you put the signal through the analog comparator and **count the rate of zero-crossings** (use an interrupt with a routine that increments a number, you may miss some if you just poll the pin), the rate of crossings should be **unique for each tone combination**. Counting for e.g. 10 ms and looking up the closest match from a table you've pre-measured should give reliable decoding, and is a slightly less brute-force approach than an FFT.

That said, you won't be able to beat a dedicated chip (although I personally think this way is much more fun.)

Happy hacking!

 [1]: http://wiki.openmusiclabs.com/wiki/ArduinoFFT


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

title: Using Multiple Serial Ports with arduino nano

Answers: 3

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

I hope that helped.

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

body:
You can use [SoftwareSerial][1] library in order to instantiate a second (soft) serial port.

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

  [1]: http://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: http://www.arduino.cc/en/Reference/SoftwareSerial#Example


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

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

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

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

title: How can I add some additional 5 volt power

Answers: 1

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

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

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

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


body: I would like to play a wav file (spoken words) from my Arduino.  I do not want to add a sound shield.  Is there a way to play a sound through an output pin?  The quality does not have to be great.

title: Is there a way to play sounds from an Arduino without using a sound shield?

Answers: 6

body: The PCMAudio example shows how to play audio data via PWM. Note that you will need to access the MCU at a low level in order to do this; the Arduino libraries don't provide enough control over the hardware.

body:
Yes, you can - see http://www.instructables.com/id/Simple-Wav-Player-Using-Arduino/

Space is quite limited, unless you use an SD card.

body: I helped someone with a similar question. The results are in my github repo at https://github.com/linhartr22/count. This example uses the PWM library and includes a reference to the article I used to learn how to convert audio files to MP3 with proper settings for the PWM libary. It plays audio through an 8 ohm speaker or a piezo buzzer connected directly to the Arduino.

body:
Yes, I did a project yesterday to play recorded voice.
You don't need a speaker module.

Just connect the speaker via a resistor to one of Arduino PWM output. Then Connect a micro-sd card module. Format your micro-sd card with FAT32 Option.

Use Sample wave converter to convert your sound files and select the options as 16,000Hz Mono 8Bit. You are all done. Use [tmrpcm][1] library. It's all easy.

  [1]: https://github.com/TMRh20/TMRpcm/wiki

body:
old post but still a good question...

Here is a tutorial for playing 8 bit 33khz audio using the Adafruit M0 Express. You can play ~60 seconds of audio from the 2MB onboard flash through the 10bit Analog out pin.
https://github.com/hydronics2/SamdAudio

two other audio board solutions that offer near 16bit quality...

 - Adafruit's circuit python boards [itsbyitsyM0][1], [M4][2], feather M0. Same as above but using the circuit python interface instead of Arduino.

 - [teensy3.2][3], teensy3.5, teensy3.6 (you can play out using the Analog pin without the audio shield but the audio shield has a nice 1/8" jack

[Teensy Tutorial][4]

[Adafruit tutorial][5]

  [1]: https://www.adafruit.com/product/3727
  [2]: https://www.adafruit.com/product/3800
  [3]: https://www.adafruit.com/product/2756
  [4]: https://www.pjrc.com/teensy/td_libs_Audio.html
  [5]: https://learn.adafruit.com/circuitpython-essentials/circuitpython-audio-out

body: @Hoytman i think this arduino library can help you a lot https://sensorium.github.io/Mozzi/


body:
I've got an [Arduino V3+][1] and need to find the correct PIN number for its RX and TX-pin on the FTDI-connector.

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

**Why I need these numbers:**

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

    #include <SoftwareSerial.h>

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

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

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

![enter image description here][2]

  [1]: https://store.3drobotics.com/products/arduimu-v3
  [2]: https://i.stack.imgur.com/ySSNf.png

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

Answers: 1

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

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

Here is the FTDI connector connections from the schematic:

![FTDI][1]

Here is the pinout of the FTDI cable

![FTDI Cable][2]

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

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

**EDIT:**

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

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

![port][4]

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

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

  [1]: https://i.stack.imgur.com/8WX32.png
  [2]: https://i.stack.imgur.com/rdsaD.png
  [3]: http://www.arduino.cc/en/Reference/SoftwareSerial
  [4]: https://i.stack.imgur.com/fitkg.png


body:
I have replaced /www folder on the Yun (backing it up first), how do I make it so the Yun will redirect to the new index.html? It, right now, gives `Access to this resource is forbidden` when I go to *yun-name-here*.local

Edit: I guess it's relevent to add I can do it fine with *yun-name-here*.local/index.html meaning it works. The real question is how to make it so I don't need to type /index.html (HURRAY LAZINESS!)

Edit II: It's [Kittens game][1]

  [1]: http://bloodrizer.ru/games/kittens/

title: How to make the Yun allow access to a resource

Answers: 0