message:
Suggest me a power source for my Arduino UNO project

I am working on a Project with:

 1. 1 Arduino UNO
 2. 5 micro 9g servos (Only one Working at a time)
 3. 2 small LED bulbs
 4. 1 MicroSD reader module
 5. 1 Speaker

Can I power my Arduino UNO with a common 9v Battery?

I also have in mind to use an external power supply for servos... but what to use?

Please suggest me a perfect power supply system

body:
Unfortunately, the perfect power supply system doesn't exist yet. However, powering an Arduino is simple.  You have to main options 9V for standard "full size" Arduinos (such as the UNO that you mention), although you *could* go for the low voltage 3.3V options.

Covering just the 9V option, from the Power section of [Arduino Uno](https://www.arduino.cc/en/Main/arduinoBoardUno):

> **Power**
>
> The Arduino Uno can be powered via the USB connection or with an
> external power supply. The power source is selected automatically.
>
> External (non-USB) power can come either from an AC-to-DC adapter
> (wall-wart) or battery. The adapter can be connected by plugging a
> 2.1mm center-positive plug into the board's power jack. Leads from a battery can be inserted in the Gnd and Vin pin headers of the POWER
> connector.
>
> The board can operate on an external supply of 6 to 20 volts. If
> supplied with less than 7V, however, the 5V pin may supply less than
> five volts and the board may be unstable. If using more than 12V, the
> voltage regulator may overheat and damage the board. The recommended
> range is 7 to 12 volts.

You should probably also take a look at [Power Supplies][1], in particular the section on [Batteries and cells](http://playground.arduino.cc/Main/IntWithHW-PwrSup#prsoBat), also from the following section [Voltage conversion and regulation](http://playground.arduino.cc/Main/IntWithHW-PwrSup#VoltConv), it states:

> In a very simple scenario, you connect a disposable 9v battery
> (probably one of the (approx) 4cm x 2.5cm x 1.5cm units with two snap
> connectors on one end) to your Arduino, and the Arduino's built in
> voltage regulator takes care of reducing the voltage to a consistent
> 5v or 3.3v, depending on the sort of Arduino you have.

So you have a couple of choices regarding 9V, either the P9 cell

[![P9 9V Battery][2]][2]

or a pack that holds six 1.5V AA or AAA batteries.

You may find this link, [How to run an Arduino (clone) on (AA) batteries for over a year – part 2][3], an interesting read. Here the chap uses four AA batteries, which only gives 6V, to power an UNO:

[![6V Battery Pack and UNO][4]][4]

I have just highlighted some information, you should take the time to read the links fully, and google for more information.

----

Regarding the servo motors, more current may be required. You *can* use the same four AA battery pack, thusly:

[![4-cell battery hold pack with jr style connector][5]][5]

but the capacity of the batteries may leave something to be desired, especially if you use rechargeable batteries (which in today's eco-concious world, you should), so you *may* require something more hefty. A quick [google][6] will show you the options available.

### Addendum

The video [Flite Test : RC Planes for Beginners: Batteries and Safety - Beginner Series - Ep. 7][7] is an extremely useful video tutorial about LiPO batteries for RC projects.

  [1]: http://playground.arduino.cc/Main/IntWithHW-PwrSup
  [2]: https://i.stack.imgur.com/gs3TI.jpg
  [3]: https://hwstartup.wordpress.com/2013/04/15/how-to-run-an-arduino-clone-on-aa-batteries-for-over-a-year-part-2/
  [4]: https://i.stack.imgur.com/n6S5U.png
  [5]: https://i.stack.imgur.com/smgcs.jpg
  [6]: https://www.google.co.uk/search?q=servo battery&tbm=isch
  [7]: https://www.youtube.com/watch?v=K6hGvXxFTFA


sender: user

sender: assistant

body:
Everything @Greenonline said plus...

A 2 Cell Lipo battery is 7.4 V. A modest 500 mAH battery would run your project for several hours, perhaps days. If you're not satisfied with the run time, buy a battery with more mAH, they go well past 5000 mAH! After all, these are the same types of batteries used in all forms of Radio Control Aeromodeling (lots of servos and brushless DC motors).

The Uno can regulate the 7.4 V although you'll need to buy/build a cable to connect the battery to the Uno. I'm not sure how much current the Uno regulator can provide but I've driven two micro servos with mine.

If the servos chatter, hum, are otherwise not working right or if there is smoke coming out of the regulator, you probably need a separate power source for the servos. A BEC like this https://en.wikipedia.org/wiki/Battery_eliminator_circuit is an inexpensive alternate and also a common RC part. :)


body:
I have had a lot of success using an off-the-shelf power bank - they're easy to get, already have charging circuits (from USB), and are at the right voltage (+5V). You can plug the power bank directly into the USB port of the Arduino.

The only problem I've had is that some power banks shut down if there is not enough current being drawn - a resistor from +5V to GND solves that problem (make sure you work out how many watts your resistor is letting through, to make sure it can dissipate the heat - I used a 100Ohm resistor, at 5v; I put "Ohms Law calculator" into google, filled in 5V & 100 Ohm, and found that it needed to be a 1/4 watt resistor - perfect! I also noted that it drew 50 milli amps AKA 0.05 amps. I tried resistors with a higher resistance e.g. 200 Ohm, and the power bank powered down. If your project is drawing more power (continuously!) then you might get away with a higher resistance).

My power bank can supply 1.5 Amps, which should be plenty for your project.


body:
Selecting a power supply involves considering the following:

 **1. Voltage Requirement**

 **2. Current Required**

 **3. Running duration**

 **4. Cost**

**Voltage Requirement:**

From the list of items specified all of your items except the microSD card (which works at 3.3V) works at 5V.

**Current Requirement:**

Arduino UNO: [about 50mA][1]

9G servo motor: [730mA peak][2]

LED 5mm: [20mA*2 = 40mA][3]

microSD Card Reader: [200mA peak][4]

Speaker: [350mA][5]

**Total Current: 1.370 Amps**

**Running Duration:**

Say I want this device to run for 1 hour straight, in order to this I will need a battery supplying 5V 1370mAh and a [1C rating][6]. So if you want your device to run longer you will need to get a battery with a higher capacity (for 2 hours 2740 mAh and so on)

**Cost**

I dont think i need to mention much in this criteria

**Solution 1:**

For these requirements your easiest solution is to use a USB power bank with 2000mAh or more.

On a protoboard solder 1x USB male, 1x USB female, 2x header pins. Solder All the positives together and all the negative together. And now you have a breakout for the power rails from the USB as well.

Power the Arduino via usb, microsd card via the 3.3V on the arduino and the rest via the breakout pins.

**Solution 2:**

Using lipo batteries. Lipo batteries have the advantage of having a large capacity in a small package (or a high power to weight ratio). In order to use this you will need a voltage regulator to get 5V. Please note that as per the calculation you will need a total of 1.37A to power your device at peak, this **cannot** be done via the on board regulator of the Arduino.

In total you will the following components to get this to work:

LiPo battery

Voltage regulator

LiPo Charger

**Solution 3:**

Using Alkaline battery. You can refer to the [Minty Boost][7] tutorial over at Adafruit to learn about this.

**Conclusion:**

If you want a **headache free solution** to your problem, buy a **USB power bank** , but if you want a more **customizable and low cost solution** go for the **LiPo battery**

And if you dont need a portable solution. Go for a wall adapter 5V/2A, thats pretty much every high end mobile phone charger

  [1]: http://gadgetmakersblog.com/arduino-power-consumption/
  [2]: http://www.addicore.com/2pcs-Addicore-SG90-Mini-Servo-p/113.htm
  [3]: https://www.sparkfun.com/datasheets/Components/LED/COM-09590-YSL-R531R3D-D2.pdf
  [4]: http://media.digikey.com/pdf/Data Sheets/M-Systems Inc PDFs/SD Card Prod Family OEM Manual.pdf
  [5]: https://electronics.stackexchange.com/questions/129277/how-many-volts-can-a-1-watt-8-ohm-speaker-take
  [6]: http://www.revolectrix.com/tech_data/lipoCalc/Battery_C_Rating.htm
  [7]: https://learn.adafruit.com/minty-boost/overview


message:
How can I build a simple "Smartwatch" with Arduino Pro Mini and Display?

I want to know how I can build a simple "Smartwatch" with an Arduino Pro Mini and a Display with a size from maybe 1,5" what Display should I use for Touch and color?

I only want simple things like synchonising the time with my Smartphone trough a HC-06 Bluetooth Module.

body:
If your goal is to make a watch you'll need a RTC (Real Time Clock) this can take the form of breakout board, or you can build the circuit yourself. The RTC is needed if you want the mini to display the time. The mini (in fact, most micros) have no internal clock (though they may have a crystal that can simulate time keeping, but this isn't as useful if you want the time)

It sounds like you want an OLED display. They come in watch-like sizes. There are a few small ones. None are touch displays. I have seen larger touch displays. Maybe combine an OLED with a clear capacitive surface?


message:
Uploading a simple sketch takes forever

I am trying to upload this simple sketch into my arduino with a shield I made. It takes forever (note I have the right COM port on)

<!-- language: c -->

      int sensorValue = 0;

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

      void loop(){
         sensorValue = analogRead(A4);
         delay(10000000);
         Serial.println(sensorValue);
         delay(10000000);
      }

body: Are you sure the problem is in the upload time? delay() takes the number of milliseconds you want to wait. In your code, it should take about 3 hours before the Arduino sends some data through the serial port.


body:
If the problem does indeed lie in the upload (see DoubtBearer's answer), then you should turn on verbose output, to see exactly what part of the upload is giving issues.

In your IDE, click File -> preferences; look for the section "Show verbose output during:" and tick both Compilation and Upload.

Re-run your upload, and see what is taking up all the time. If you can't figure it out from that, please post the log (it will appear in the black area at the bottom of the IDE, you should be able to cut & paste).


body:
Check the end of this thread for the [reply by 'Toshibass'][1], [Unbelievable slow compilation of simple sketches](http://forum.arduino.cc/index.php?topic=82527.15)

> I was having same same problem compile took > 3 minutes for small sketch using serial or OTA however I found solution The program that was slowing down compile was IBM's Trusteer .. Rapport which is a fraud prevention program distributed by my bank once I de-installed it, same compile took 10 seconds, now all I need to do is find an alternative or hope IBM produce a fix after I filled in a issue report to them.

It worked for me, the culprit was some software called 'Trusteer'.

  [1]: http://forum.arduino.cc/index.php?topic=82527.msg2817497#msg2817497


body: If you are taking too much time for uploading means there is communication between another device is happening, please remove all TX and RX pins.


body:
I had the same problem. I noticed that the RX & TX LEDs we're not flashing as they normally do when I upload a file. I'm using an older knock off nano.

My solution:
Under Tools> processor.... I switched from the defaulted "ATmega328P" to the "ATmega328P(Old Bootloader)" option. The next upload attempt was quick and successful. Normal flashing RX &TX LEDs during the upload as well. Hope this helps someone.


body:
Try downloading CH340 drivers. You must not have drivers for uploading the code to arduino board and to identify the right COM port.
Download and install the drivers, find the COM port number from device manager and update Tools->Port in your Arduino IDE.


message:
Arduino + 4051 -> noise on certain 4051 pins

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

I am trying to use two `4051` ICs with an Arduino Micro right now. The idea was to have an 16-sensor demo station (8 sensors per `4051`) wherein each `4051` pin selection is controlled by a potentiometer as input. I am new to using MUX's, so I mocked the following up as a quick demo based on [this](http://playground.arduino.cc/Learning/4051) help document via Arduino (it's basically the same), which only uses one `4051` and does not use a potentiometer as selector input. So, I should be able to set the variable `which` to whatever number (0 - 7) to change the sensor selection that shows up at `A2` on the Arduino.

Setting `which` to 0 is fine, but when I have more than two sensors plugged into `4051` and set the selector pin to any other number than 0 there is a strong likelihood that the output that shows up in the `Serial Monitor` is both unresponsive to the selected sensor change and appears to be simply noise (random numbers around 200 or so). I have been trying to isolate where this noise is coming from and am totally stumped. Has anyone had this issue and, if so, any suggestions on how to further diagnose what is happening? I am currently powering everything off of the Arduino `5V`, which I am under the impression should be okay, though I have tried this with external power supplies (`12V at 2A`, for example) and gotten the same results (so I am fairly certain power is not the issue here).

Measuring voltage on pins 2, 3, and 4, I am seeing 1mV on pin 2, 1mV on pin 3, and 0.9mV on pin 4 following the initial spike during upload. When comparing against the Arduino 4051 doc I linked to above, I see that in that file pins 2, 3, and 4 show a Voltage of 2.5V following the initial spike during upload. Any idea what I am doing incorrectly?

    /*
    Sensor Station via MUX

     * code example for useing a 4051 * analog multiplexer / demultiplexer
     * by david c. and tomek n.* for k3 / malmï¿½ hï¿½gskola
     *
     * edited by Ross R.
     */

    int r0 = 0;      //value of select pin at the 4051 (s0)
    int r1 = 0;      //value of select pin at the 4051 (s1)
    int r2 = 0;      //value of select pin at the 4051 (s2)
    int which = 0;   //which y pin we are selecting
    int val;

    void setup() {
      pinMode(A2, INPUT);       // mux1 input
      pinMode(2, OUTPUT);    // s0
      pinMode(3, OUTPUT);    // s1
      pinMode(4, OUTPUT);    // s2
    }

    void loop () {

      which = (0);

      // select the bit
      r0 = bitRead(which, 0);
      r1 = bitRead(which, 1);
      r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

      digitalWrite(2, r0);
      digitalWrite(3, r1);
      digitalWrite(4, r2);

      //Either read or write the multiplexed pin here
      // refactor, this should be digitalWrite with millis or something
      val = analogRead(A2);     // MUX ouputs here

      Serial.print("sensor number ");
      Serial.print(which);
      Serial.print('\t');
      Serial.print("val is ");
      Serial.println(val);

      delay(2);
    }

body:
I have a post about that chip at [74HC4051 multiplexer / demultiplexer](http://www.gammon.com.au/forum/?id=11976).

I made up the circuit shown on my page above with modifications as described below:

[![74HC4051 example][1]][1]

I moved the A/B/C and O/I pins to match your code.

A is the **low-order bit** so pin 11 on the 74HC4051 should go to D2 on the Arduino.

    74HC4051  Arduino   Meaning
        11       D2        A
        10       D3        B
         9       D4        C
         3       A2        O/I

I put a pot on I/O0 (pin 13 on the 74HC4051) and randomly set the other pins to +5 V or Gnd, as shown.

---

In `setup()` I added:

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

    Serial.begin (115200);

I also modified it to automatically sequence through all 8 possible ports, and then stop after 1000 iterations to stop flooding the USB port on my computer. Code is:

    int r0 = 0;      //value of select pin at the 4051 (s0)
    int r1 = 0;      //value of select pin at the 4051 (s1)
    int r2 = 0;      //value of select pin at the 4051 (s2)
    int which = 0;   //which y pin we are selecting
    int val;

    void setup() {
      Serial.begin (115200);
      pinMode(A2, INPUT);       // mux1 input
      pinMode(2, OUTPUT);    // s0
      pinMode(3, OUTPUT);    // s1
      pinMode(4, OUTPUT);    // s2
    }  // end of setup

    unsigned long counter;

    void loop () {

      // select the bit
      r0 = bitRead(which, 0);
      r1 = bitRead(which, 1);
      r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

      digitalWrite(2, r0);
      digitalWrite(3, r1);
      digitalWrite(4, r2);

      //Either read or write the multiplexed pin here
      // refactor, this should be digitalWrite with millis or something
      val = analogRead(A2);     // MUX ouputs here

      Serial.print("sensor number ");
      Serial.print(which);
      Serial.print('\t');
      Serial.print("val is ");
      Serial.println(val);

      delay(2);

      if (++which > 7)
        which = 0;

      if (++counter >= 1000)
        {
        Serial.flush ();
        exit (1);
        }
    }  // end of loop

---

The output from your sketch was as expected:

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

    sensor number 0 val is 781
    sensor number 1 val is 0
    sensor number 2 val is 1023
    sensor number 3 val is 1023
    sensor number 4 val is 0
    sensor number 5 val is 0
    sensor number 6 val is 0
    sensor number 7 val is 1023

I suggest you check that your wiring agrees with mine.

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


message:
Converting Arduino UNO's analog pins to digital I/O

I am working on an Arduino UNO Project and running out of digital pins.

Can I convert the six analog pins to digital I/O and use them to drive servos?

Please suggest me a method

body:
A0 through A5 already have GPIO capability; treat them as you would any other non-PWM pin.

A6 and A7, found in similar boards that use a SMD package, do not have any GPIO capability whatsoever and can only be used for analog input.


message:
Strange comportment of stepper motor while connected to internet

Problem moving a stepper motor after reading a value from a webpage....

I have a project to move a stepper motor from an angle after reading a number from internet; I have a typical 28BYJ-48 stepper with the hardware driver and an arduino + ethernet shield.

I have tested the motor alone with different library and it is working very well, the motor turn correctly to the proper angle and without shaking.

I have also been able to read a specific page with a number on it with the Ethernet shield and library. I am able to light a led whenever a certain value is read from this webpage.

Once I connect the 2 parts, either the stepper motot is vibrating a lot and moving from half the correct angle, either it is only shaking and not moving at all....

Note: I have powered it with an external power source thinking it was because of power issues but it doesn't change anything.....

I don't get it... Why would it work well before the etheret connection an not after?? Maybe it's late and I miss something obvious, but frankly I spent a lot of time looking online and checking my code

Here is my sketch if it anyone could help... thanks a lot in advance, I know it's quite long....but i'm quite desperate :-(

    #include <AccelStepper.h>
    #include <Ethernet.h>
    #include <SPI.h>

    ////////////////////////////////////////////////////////////////////////
    //CONFIGURE
    ////////////////////////////////////////////////////////////////////////

    #define HALFSTEP 8

    // Motor pin definitions
    #define motorPin1  8     // IN1 on the ULN2003 driver 1
    #define motorPin2  9     // IN2 on the ULN2003 driver 1
    #define motorPin3  10     // IN3 on the ULN2003 driver 1
    #define motorPin4  11    // IN4 on the ULN2003 driver 1

    // Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper with 28BYJ-48
    AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
    const int stepsPerRev =  2038;

    byte server[] = { 192,168,0,11 }; //ip Address of the server you will connect to
    String serverIP = "192.168.0.11";

    int port = 8888; // server port

    // if need to change the MAC address (Very Rare)
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // byte ip[] = { 192, 168, 0, 188 }; // case we want to use fixed IP

    //The location to go to on the server
    //make sure to keep HTTP/1.0 at the end, this is telling it what type of file it is
    String webPage = "/index.php HTTP/1.0";

    EthernetClient client;

    char inString[32]; // string for incoming serial data
    int stringPos = 0; // string index counter
    boolean startRead = false; // is reading?
    int ledPin = 5;
    String pageValue;

    //////////////////////////////////////////////////////////////////////////////
    // SETUP
    //////////////////////////////////////////////////////////////////////////////

    // setup the stepper parameters

    void setup() {
      stepper1.setMaxSpeed(3000.0);
      stepper1.setAcceleration(1000.0);
      stepper1.setSpeed(500);

    // start a full rotation ==> this is perfectly working!!

    int steps = degreesToSteps(360);
      stepper1.moveTo(steps);
      stepper1.runToPosition();

       Serial.begin(9600);

       Serial.println("starting communication");

      //Connect the Ethernet Shield by specifying the board's mac and ip address

      if(Ethernet.begin(mac) == 0) {
      Serial.println("Failed to configure Ethernet using DHCP");
       }else{
      Serial.println("Ethernet shield connected & obtained IP address : ");
      Serial.println(Ethernet.localIP());

       //Shield already connected during setup phase, now connect to the webpage and retrieve the value

     //Connect to the server
      if(!connectToServer(server, port, webPage)){
       Serial.println("Failed to connect to server");

            }else{

                   Serial.println("connected to server page");

                   //Read the output value written on the webpage

                  int angle = readPage().toInt();
                  Serial.println(angle);

                  int steps = degreesToSteps(angle);
                  Serial.println(steps);

                  stepper1.moveTo(steps);

                  stepper1.runToPosition();

                  delay(1000);

          //end of success case connection
          }

       }

     //end of setup
     }

    void loop(){}

    ///////////////////////////////////////////////////////////////////////////////////////////
    //Connect to a web page
    ////////////////////////////////////////////////////////////////////////////////////////////

    boolean connectToServer(byte* server, int port, String webPage)
    {
      //connect to the server
      Serial.println("connecting...");

      //port 8888 for our mamp server
      if (client.connect(server, port)) {
        Serial.println("connected");
        client.print("GET ");
        client.println(webPage);
        client.println();
     return true;
      }else{
        Serial.println("connection failed");
        return false;
      }

    }

    ///////////////////////////////////////////////////////////////////////////////////////////
    //Parse a value located between a < and a >
    ////////////////////////////////////////////////////////////////////////////////////////////

    String readPage(){
      //read the page, and capture & return everything between '<' and '>'

      stringPos = 0;
      memset( &inString, 0, 32 ); //clear inString memory

      while(true){

        if (client.available()) {
          char c = client.read();

          if (c == '<' ) { //'<' is our begining character
            startRead = true; //Ready to start reading the part
          }else if(startRead){

            if(c != '>'){ //'>' is our ending character
              inString[stringPos] = c;
              stringPos ++;
            }else{
              //got what we need here! We can disconnect now

              startRead = false;
              client.stop();
              client.flush();
              Serial.println("disconnecting.");
              return inString;

            }

          }
        }

      }

    }

    ///////////////////////////////////////////////////////////////////////////////////////////
    //Convert the degrees into the closest number of steps relative to the step motor model.
    ////////////////////////////////////////////////////////////////////////////////////////////

    int degreesToSteps(float angleDegrees) {
      //return the closest number of steps to accomplish to move the motor for the specified angle

      const float stepsPerDegree = stepsPerRev/360.00;
      int steps = angleDegrees * stepsPerDegree + 0.5;  // we add 0.5 as when converting to an int the floating part is truncated, this allows to round the value to the nearest Int
      return steps;

    }

body:
Pin 11 is used for SPI to communicate with the Ethernet Shield. And pin 10 is used for the ChipSelect.
 So using the ethernet shield will toggle those pins, making the motor shake around.

Try using pins 6, 7, 8, and 9 instead.


message:
Processing error with processing-arduino examples

I have followed the instructions to run the [Arduino processing examples][1] but with no success.

Always `import processing.serial.*;` does not name a type. Which is perhaps a library (processing-arduino) related error.

My sketch is a sketch that comes with processing-arduino library.

I have searched for a long time with no solution. Any suggestion?

Errors:

    arduino_output:28: error: 'import' does not name a type
    arduino_output:30: error: 'import' does not name a type
    arduino_output:32: error: 'Arduino' does not name a type
    arduino_output:34: error: 'color' does not name a type
    arduino_output:35: error: 'color' does not name a type
    arduino_output:37: error: expected unqualified-id before '[' token
    arduino_output.pde: In function 'void setup()':
    arduino_output:42: error: 'size' was not declared in this scope
    arduino_output:45: error: 'Arduino' was not declared in this scope
    arduino_output:45: error: 'println' was not declared in this scope
    arduino_output:50: error: 'arduino' was not declared in this scope
    arduino_output:50: error: expected type-specifier before 'Arduino'
    arduino_output:50: error: expected `;' before 'Arduino'
    arduino_output:58: error: expected unqualified-id before numeric constant
    arduino_output.pde: In function 'void draw()':
    arduino_output:62: error: 'off' was not declared in this scope
    arduino_output:62: error: 'background' was not declared in this scope
    arduino_output:63: error: 'on' was not declared in this scope
    arduino_output:63: error: 'stroke' was not declared in this scope
    arduino_output:66: error: 'values' was not declared in this scope
    arduino_output:66: error: 'Arduino' was not declared in this scope
    arduino_output:66: error: expected unqualified-id before numeric constant
    arduino_output:66: error: expected `)' before numeric constant
    arduino_output:67: error: 'fill' was not declared in this scope
    arduino_output:69: error: 'fill' was not declared in this scope
    arduino_output:71: error: 'rect' was not declared in this scope
    arduino_output.pde: In function 'void mousePressed()':
    arduino_output:77: error: 'mouseX' was not declared in this scope
    arduino_output:80: error: 'values' was not declared in this scope
    arduino_output:80: error: 'Arduino' was not declared in this scope
    arduino_output:80: error: expected unqualified-id before numeric constant
    arduino_output:80: error: expected `)' before numeric constant
    arduino_output:81: error: 'arduino' was not declared in this scope
    arduino_output:81: error: expected unqualified-id before numeric constant
    arduino_output:82: error: expected unqualified-id before numeric constant
    arduino_output:82: error: expected `;' before numeric constant
    arduino_output:84: error: 'arduino' was not declared in this scope
    arduino_output:84: error: expected unqualified-id before numeric constant
    arduino_output:85: error: expected unqualified-id before numeric constant
    arduino_output:85: error: expected `;' before numeric constant

  [1]: http://playground.arduino.cc/Interfacing/Processing

body:
> Note: I am testing this on OS X, so my paths may differ slightly from yours.

I have managed to reproduce your issue, by *incorrectly* copying the `arduino` directory, from the unzipped [processing2-arduino.zip][1] package, to the `libraries` directory under the `Arduino` directory in my home directory, thus

    /Users/user/Documents/Arduino/libraries/arduino

 Then opening the Arduino IDE and running the `arduino_output` example, via the menu, `File -> Sketchbook -> Libraries -> Arduino -> arduino_output`. When I hit the compile button, in the Arduino IDE, the compiler throws up the exact same errors that you describe in your question.

However this is not the correct usage of this package. This package is intended to be used in conjunction with the **Processing** application, *not* the **Arduino IDE**. You should download [Processing][2] and then follow the [instructions][3] again:

>  1. Unzip the library and copy the "arduino" folder into the "libraries" sub-folder of your Processing Sketchbook. (You can find
> the location of your Sketchbook by opening the Processing Preferences.
> If you haven't made a "libraries" sub-folder, create one.)

Thus, on OS X, the path should now be

    /Users/user/Documents/Processing/libraries/arduino

However, as usual, the documentation on the Arduino website leaves a lot to be desired. Pay careful attention to the following paragraph if you are running OS X or Linux:

> Note: if you run Linux, you need to change `Arduino.jar` into
> `arduino.jar`, because Linux is case sensitive and it does not work if
> you don't change this letter (Arduino.jar is in the folder "library"
> of this Processing Library).

So,

    /Users/user/Documents/Arduino/libraries/arduino/library/Arduino.jar

becomes

    /Users/user/Documents/Arduino/libraries/arduino/library/arduino.jar

Relaunch the Processing application. `File -> Examples...`, opens up a window, scroll down to `Contributed Libraries`, open that, open `Arduino (Firmata)`, open the `arduino_output` example. Hit the **Run** button, and after compiling you should see the window below:

[![arduino_output window][4]][4]

HTH.

  [1]: http://playground.arduino.cc/uploads/Interfacing/processing2-arduino.zip
  [2]: https://processing.org/
  [3]: http://playground.arduino.cc/Interfacing/Processing
  [4]: https://i.stack.imgur.com/iO5s6.png


message:
Arduino Bluetooth connection with Android

I am wondering why my Arduino program won't start its sketch to connect a bluesmirf to an android device and send data to the android whenever I use an external power supply. The sketch starts whenever i open the serial monitor, but using the power supply, it wont work.

body:
You'll probably find that you are not supplying enough power to operate the Arduino and the components attached to the Arduino. Your current (Amps) draw is most likely higher than your external power supply can output.

I had this problem when using a 9v battery to power an Arduino with an XBee chip and some LEDs attached. The 9v would be able to power the kit for a while but would then not output enough current to power the Arduino. In the end I had to scrap a few LEDs.

You need to find out how much current your Arduino and its components are using and use a suitable power supply that can output enough current to power your Arduino.

Also remember when you send and receive a packet out of a Bluetooth radio - more current is required than when the Bluetooth radio is idle.


message:
Are static variables in a function bad?

For my code I use a couple of static variables.
But when I search the internet, they seem "evil".

For example: I have a function which will be executed every loop (5ms looptime).
to increase the speed I added some static variables to it.
Is the way I am doing this bad? Are there simple solutions for it?

Code:

    int ProgFormula() {
      static int StartPosition;
      static int DeltaPosition;
      static int LoopTime = 5;
      static int AccelerationLoops;
      static int TotalLoops;
      static int EndOne;

      static float VelocityLoop;
      static float VelocityFactor;

      int Setpoint;

      if (Iteration == -1) {
        StartPosition = PID.ActualPosition;
        DeltaPosition = abs(SetPosition - StartPosition);
        VelocityLoop = Velocity / (1000 / LoopTime);
        TotalLoops = DeltaPosition / VelocityLoop;
        if (TotalLoops <= (AccelerationLoops * 2)) {
          AccelerationLoops = (TotalLoops / 2);
          VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
        }
        else {
          AccelerationLoops = 70;

          VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
        }
        TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
        EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
      }
      else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
        if (StartPosition < SetPosition) {
          Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
        }
        else {
          Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
        }
      }
      else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
        if (StartPosition < SetPosition) {
          Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
        }
        else {
          Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
        }
      }
      else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
        if (StartPosition < SetPosition) {
          Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
        }
        else {
          Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
        }
      }
      else {
        Setpoint = Setpoint;
      }
      return(Setpoint);
    }

Is it better to avoid statics? If so why?

Thanks in advance,
Koen

body:
Any style recommendation is going to be a bit subjective and conditional, but the biggest problem I see here is that the function can only be running one set of variables at a time. What if you wanted to do two of the task your `ProgFormula` function is a part of simultaneously? You have no way to switch the state of those variables between calls.

You could make a struct to store the state that your function modifies, that way the calling code could swap out the state between calls. Or you could wrap it in a class so the calling code can make as many instances as it needs and not worry about the data each owns.

As a side note, [Premature optimization is the root of all evil][1]. The state you are storing is built with a few subtractions and divisions, but the `pow` function your loop sometimes calls may be the part dominating its running time.

  [1]: http://c2.com/cgi/wiki?PrematureOptimization


body:
I made up a test by adding enough to the posted code to get it to compile:

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

    float ActualPosition, SetPosition, Velocity;

    int Iteration;

    int ProgFormula() {

      static int StartPosition;
      static int DeltaPosition;
      static int LoopTime = 5;
      static int AccelerationLoops;
      static int TotalLoops;
      static int EndOne;

      static float VelocityLoop;
      static float VelocityFactor;

      int Setpoint;

      if (Iteration == -1) {
        StartPosition = ActualPosition;
        DeltaPosition = abs(SetPosition - StartPosition);
        VelocityLoop = Velocity / (1000 / LoopTime);
        TotalLoops = DeltaPosition / VelocityLoop;
        if (TotalLoops <= (AccelerationLoops * 2)) {
          AccelerationLoops = (TotalLoops / 2);
          VelocityFactor = (VelocityLoop * 0.5 / AccelerationLoops) / 2;
        }
        else {
          AccelerationLoops = 70;

          VelocityFactor = VelocityLoop * 0.5 / AccelerationLoops;
        }
        TotalLoops = DeltaPosition / VelocityLoop + AccelerationLoops;
        EndOne = (VelocityFactor * pow(AccelerationLoops, 2));
      }
      else if (Iteration >= 0 && Iteration <= AccelerationLoops) {
        if (StartPosition < SetPosition) {
          Setpoint = VelocityFactor * pow(Iteration, 2) + StartPosition;
        }
        else {
          Setpoint = -VelocityFactor * pow(Iteration, 2) + StartPosition;
        }
      }
      else if (Iteration > AccelerationLoops && Iteration <= (TotalLoops - AccelerationLoops)) {
        if (StartPosition < SetPosition) {
          Setpoint = VelocityLoop * Iteration - EndOne + StartPosition;
        }
        else {
          Setpoint = -VelocityLoop * Iteration + EndOne + StartPosition;
        }
      }
      else if (Iteration >= (TotalLoops - AccelerationLoops) && Iteration <= TotalLoops) {
        if (StartPosition < SetPosition) {
          Setpoint = -VelocityFactor * pow((TotalLoops - Iteration), 2) + DeltaPosition + StartPosition;
        }
        else {
          Setpoint = VelocityFactor * pow((TotalLoops - Iteration), 2) - DeltaPosition + StartPosition;
        }
      }
      else {
        Setpoint = Setpoint;
      }
      return(Setpoint);
    }

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

    void loop ()
      {

      }  // end of loop

Disassembling this I got the following assembler:

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

    000000a8 <_Z11ProgFormulav>:
      a8: 6f 92        push r6
      aa: 7f 92        push r7
      ac: 8f 92        push r8
      ae: 9f 92        push r9
      b0: af 92        push r10
      b2: bf 92        push r11
      b4: cf 92        push r12
      b6: df 92        push r13
      b8: ef 92        push r14
      ba: ff 92        push r15
      bc: 0f 93        push r16
      be: 1f 93        push r17
      c0: cf 93        push r28
      c2: df 93        push r29
      c4: 00 91 0c 01  lds r16, 0x010C
      c8: 10 91 0d 01  lds r17, 0x010D
      cc: 8f ef        ldi r24, 0xFF ; 255
      ce: 0f 3f        cpi r16, 0xFF ; 255
      d0: 18 07        cpc r17, r24
    ...
     4ec: cb 01        movw r24, r22
     4ee: df 91        pop r29
     4f0: cf 91        pop r28
     4f2: 1f 91        pop r17
     4f4: 0f 91        pop r16
     4f6: ff 90        pop r15
     4f8: ef 90        pop r14
     4fa: df 90        pop r13
     4fc: cf 90        pop r12
     4fe: bf 90        pop r11
     500: af 90        pop r10
     502: 9f 90        pop r9
     504: 8f 90        pop r8
     506: 7f 90        pop r7
     508: 6f 90        pop r6
     50a: 08 95        ret

    0000050c <setup>:

So that function (ProgFormula) has taken up:

    0x50a - 0xa8 = 1122 bytes

Now by removing the "static" declarations, like this:

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

       int StartPosition;
       int DeltaPosition;
       int LoopTime = 5;
       int AccelerationLoops;
       int TotalLoops;
       int EndOne;

       float VelocityLoop;
       float VelocityFactor;

It now compiles to:

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

    000000a8 <_Z11ProgFormulav>:
      a8: 6f 92        push r6
      aa: 7f 92        push r7
      ac: 8f 92        push r8
      ae: 9f 92        push r9
      b0: af 92        push r10
      b2: bf 92        push r11
      b4: cf 92        push r12
      b6: df 92        push r13
      b8: ef 92        push r14
      ba: ff 92        push r15
      bc: 0f 93        push r16
      be: 1f 93        push r17
      c0: cf 93        push r28
      c2: df 93        push r29
      c4: c0 91 04 01  lds r28, 0x0104
      c8: d0 91 05 01  lds r29, 0x0105
      cc: 8f ef        ldi r24, 0xFF ; 255
      ce: cf 3f        cpi r28, 0xFF ; 255
      d0: d8 07        cpc r29, r24
    ...
     27e: cb 01        movw r24, r22
     280: df 91        pop r29
     282: cf 91        pop r28
     284: 1f 91        pop r17
     286: 0f 91        pop r16
     288: ff 90        pop r15
     28a: ef 90        pop r14
     28c: df 90        pop r13
     28e: cf 90        pop r12
     290: bf 90        pop r11
     292: af 90        pop r10
     294: 9f 90        pop r9
     296: 8f 90        pop r8
     298: 7f 90        pop r7
     29a: 6f 90        pop r6
     29c: 08 95        ret

    0000029e <setup>:

That is now:

    0x29e - 0xa8 = 502 bytes

---

## Conclusion

Adding "static" has made the function over **twice as long**. Presumably it is also slower. After all, those extra instructions have be doing *something*.

>  to increase the speed I added some static variables to it.

Your belief that making variables static increases the speed does not seem to be supported.


body:
> to increase the speed I added some static variables to it. Is the way
> I am doing this bad? ... Is it better to avoid statics? If so why?

I use this technique too ... IMHO it is neither good nor bad.  In a logger, for instance, all the wall clock time stamp information has to be looked up (perhaps time(0)), and formatted at least once in any given second.  I use function static variables to prevent duplicating that effort for the 10's to 100's (or even more on a really fast machine) of log entries that happen in the **same** second.

I suspect your saying "to increase speed" is what the other answers focus on, and many contributors in SE jump on the 'premature optimization' concept. I think you unintentionally misled them.

Maybe your audience would respond more positively to the term **'memoize'** ... this technique avoids some work (when it can).

And, just to be complete - Wikipedia agrees with you:

> In computing, memoization is an optimization technique used primarily
> to speed up computer programs by storing the results of expensive
> function calls and returning the cached result when the same inputs
> occur again.

Note 1. I think memoization implies that there is work that need not be duplicated every time through the function (sometimes only initialization) ... thus there often will be an if-clause to skip over the un-necessary work.

Note 2. static is not the only way to hold onto previous values, but is probably somewhat more appropriate for a function when you do not want a class object (to hold the previous values).

Note 3. 'memoize' has impact because it avoids work, and this speeds up the whole system.


message:
Why I could not read the other sms's except the first SMS?

I have to read the incoming SMS on my GSM module SIM900, and I want to print the sender number and message to the serial monitor.

I first configure the GSM module with AT commands and Response() function will give me the response to AT commands.

as any SMS will be in the following pattern

+CMT: "[Mobile number]", "[Date and Time]>"
   [message body]

So, I first extract +CMT and after that I will take mobile number and at last we have message body. The code I have used is

    char RcvdMsg[200] = "";
    int RcvdCheck = 0;
    int RcvdConf = 0;
    int index = 0;
    int RcvdEnd = 0;
    char MsgMob[15];
    char MsgTxt[50];
    int MsgLength = 0;

    void Config() // This function is configuring our SIM900 module i.e. sending the initial AT commands
    {
        delay(1000);
        Serial.print("ATE0\r");
        Response();
        Serial.print("AT\r");
        Response();
        Serial.print("AT+CMGF=1\r");
        Response();
        Serial.print("AT+CNMI=1,2,0,0,0\r");
        Response();
    }

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

    void loop()
    {
      RecSMS();
    }

    void Response() // Get the Response of each AT Command
    {
        int count = 0;
        Serial.println();
        while(1)
        {
            if(Serial.available())
            {
                char data =Serial.read();
                if(data == 'K')
                {
                    Serial.println("OK");
                    break;
                }
                if(data == 'R')
                {
                    Serial.println("GSM Not Working");
                    break;
                }
            }
            count++;
            delay(10);
            if(count == 1000)
            {
                Serial.println("GSM not Found");
                break;
            }
        }
    }

    void RecSMS() // Receiving the SMS and extracting the Sender Mobile number & Message Text
    {
        if(Serial.available())
        {
            char data = Serial.read();
            if(data == '+'){RcvdCheck = 1;}
            if((data == 'C') && (RcvdCheck == 1)) {RcvdCheck = 2;}
            if((data == 'M') && (RcvdCheck == 2)) {RcvdCheck = 3;}
            if((data == 'T') && (RcvdCheck == 3)) {RcvdCheck = 4;}
            if(RcvdCheck == 4)
            {
                RcvdConf = 1;
                RcvdCheck = 0;
            }

            if(RcvdConf == 1)
            {
                if(data == '\n'){RcvdEnd++;}
                if(RcvdEnd == 3){RcvdEnd = 0;}
                RcvdMsg[index] = data;

                index++;
                if(RcvdEnd == 2){RcvdConf = 0;MsgLength = index-2;index = 0;}
                if(RcvdConf == 0)
                {
                    Serial.print("Mobile Number is: ");
                    for(int x = 4;x < 17;x++)
                    {
                        MsgMob[x-4] = RcvdMsg[x];
                        Serial.print(MsgMob[x-4]);
                    }
                    Serial.println();
                    Serial.print("Message Text: ");
                    for(int x = 46; x < MsgLength; x++)
                    {
                        MsgTxt[x-46] = RcvdMsg[x];
                        Serial.print(MsgTxt[x-46]);
                    }

                    Serial.println();
                    Serial.flush();
                }
            }
        }
    }

The problem of the code is

After receiving first SMS I am getting my mobile number and message body. After that I am only getting the sender number printed to my serial monitor but not the message body.

Where has it gone wrong. I could not understood.

Please help me.......Thanks in advance.

body: It looks like `RcvdEnd` never gets reset back to zero because `RcvdConf` is set to zero when `RcvdEnd` is 2, which means it will never get to 3 and reset it (at least not when you are expecting it to). I'm not sure how many new lines you are supposed to be checking for but the way it is set up now or is looking for two on the first message, and three for every message thereafter. You might want to rework the logic and maybe move where that value gets reset.


body:
                 {
                    MsgTxt[x-46] = RcvdMsg[x];
                    Serial.print(MsgTxt[x-46]);
                }
                 RcvdEnd =0;
                Serial.println();
                Serial.flush();


message:
Arduino Nano with Mac OS Yosemite 10.10

I have an Arduino Nano and I’m trying to use it with Mac OS Yosemite (10.10). However, I’m having issues with the data transfer between the computer and the device. The Arduino is powered (LED is illuminated), however, I can’t upload anything to it. The serial port is not recognised and after installing a multitude of drivers, nothing seems to work.

Is there a specific driver or process I need to follow to enable data transfer?

body:
Setting kext-dev-mode=1 allows unsigned kernel extensions to load, which is not recommended, as it lowers OS X security.

Instead, try the signed 64-bit kernel extension from FTDI here: http://www.ftdichip.com/Drivers/VCP.htm , version 2.3, which does require changing OS security permissions.


body:
From [this blogpost][1] you can [download][2] **signed** macOS driver for CH340. Works fine on Sierra 10.12!

  [1]: https://blog.sengotta.net/signed-mac-os-driver-for-winchiphead-ch340-serial-bridge/
  [2]: http://blog.sengotta.net/wp-content/uploads/2015/11/CH34x_Install_V1.3.zip


message:
Updating MAX7456 library to work with Arduino 1.6.6

I've got [this library][1] for communicating with the [MAX7456 chip][2].

The library is abandoned and the only one I found that actually works, so I'd really like to use it.

----------

It compiles fine with Arduino IDE 1.0.5, but not with Arduino IDE 1.6.6 .

This happens with 1.6.6, I tried to fix it but I only made it worse.

    Arduino: 1.6.6 Hourly Build 2015/07/03 10:26 (Linux), Board: "Arduino Nano, ATmega328"

    Using library SPI at version 1.0.0 in folder: /home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI
    Using library max7456 in folder: /home/t/Dropbox/Arduino/libraries/max7456 (legacy)

    /home/t/Dropbox/Arduino-IDE/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/cores/arduino -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/variants/eightanaloginputs -I/home/t/Dropbox/Arduino-IDE/hardware/arduino/avr/libraries/SPI -I/home/t/Dropbox/Arduino/libraries/max7456 /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp -o /tmp/build4912026784583215357.tmp/sketch/HelloWorld.cpp.o
    In file included from HelloWorld.ino:2:0:
    /home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:40: error: 'prog_uchar' does not name a type
    static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
                                        ^
    /home/t/Dropbox/Arduino/libraries/max7456/max7456.h:228:52: error: ISO C++ forbids declaration of 'table' with no type [-fpermissive]
    static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);
                                                    ^
    Error compiling.

----------

How would one make the library compatible with 1.6.6?

  [1]: https://www.dropbox.com/s/3cp4am1f271odcm/max7456.tar?dl=0
  [2]: https://www.sparkfun.com/datasheets/BreakoutBoards/MAX7456.pdf

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

In the file max7456.h at line 228 change it from:

 static void getCARACFromProgMem(const prog_uchar *table, byte i,charact c);

to:

    static void getCARACFromProgMem(const char *table, byte i,charact c);

---

In the file max7456.cpp at line 484 change it from:

    void Max7456::getCARACFromProgMem(const prog_uchar *table, byte i, charact car)

to:

    void Max7456::getCARACFromProgMem(const char *table, byte i, charact car)

---

Then it compiles OK (under 1.6.4 at least).


message:
Can I use a 6 pin Bluetooth module in a 4 pin socket?

I have a Funduino joystick shield and it features a 4 pin bluetooth socket in the top right hand corner (just above the `D`, `T`, `-` and `+` legends).

[![Joystick Shield][1]][1]

For some reason, on eBay, 6 pin bluetooth modules are cheaper and more common than 4 pin bluetooth modules.

[![Bluetooth Module][2]][2]

The joystick shield's 4 pin socket is labelled `R T - +`. Obviously these correspond with `RXD`, `TXD`, `GND` and `VCC` on the bluetooth module.

I was wondering:

 1. What is the difference between the 4 pin and 6 pin modules?
 2. Can I use a 6 pin module in the four pin socket on the joystick shield?
 3. What is the function of additional `STATE` and `EN` pins on the bluetooth module?
 4. Are these two additional pins necessary as other modules do not have them?

  [1]: https://i.stack.imgur.com/WTA15.jpg
  [2]: https://i.stack.imgur.com/rjTEf.jpg

body:
After some more concerted searching I have found the answer on [Success Using the JY-MCU (linvor) Bluetooth Module][1]:

> The module has 6 pins labeled on the back, but most modules only have
> 4 of those populated with pogo pins.  KEY & STATE seem to be not
> required, as KEY is used for flashing the device and STATE simply
> indicates if the device is awake or not.  So that leaves only GND,
> VCC, TXD, RXD.  Not shown is Pin 11 which is the RESET pin, resetting
> the module when pulled LOW.

So, the answer is apparently yes, and you can buy a cheaper 6 pin module and remove (snip/desolder) the two additional pins.  The `EN` pin is also apparently labelled as `KEY` on some modules.

  [1]: http://www.instructables.com/id/Success-Using-the-JY-MCU-linvor-Bluetooth-Module/


body:
> 1. What is the difference between the 4 pin and 6 pin modules?

The 6-pin modules have more pins, used for other features.

> 2. Can I use a 6 pin module in the four pin socket on the joystick shield?

I don't see why not, as long as you tie/float the other pins appropriately.

> 3. What is the function of additional STATE and EN pins on the bluetooth module?

Whatever the documentation says they do.

> 4. Are these two additional pins necessary as other modules do not have them?

Probably not. But they provide additional functionality.


message:
Building a digital camera?

Does anyone know of a way to DIY a digital camera by buying a sensor and lens and processing the image using an Arduino?

body:
You can buy a camera module for the Arduino, and you can interface it fairly simply.  There are numerous modules around - ask Google, it knows more than me.

But I have yet to work out why people do it.  All you can do with an Uno is to pass the data through to something else like a PC to process the image - so why wouldn't you just use a simple webcam?

The Arduino UNO has 2KB of RAM.  A 24-bit 640x480 image (VGA) requires (640*480*3)/1024 = 900KB to store it in memory.  If you really wanted to process an image on an Uno then you would be limited to (say 8-bit grayscale) 48x32 pixels (1.5KB) which is pretty pointless really.

Even a Due would only allow (again grayscale) around 320x240 (which is better) but nothing colour unless you want to start messing with CLUTs which aren't fun when receiving a truecolour (24-bit) image from a camera.

For this kind of task you are better off with an embedded computer with plenty of RAM such as a Raspberry Pi or maybe a Galileo or something.


message:
Pyserial and Arduino

I am trying to send an integer value from Python to Arduino. The integer value is a position given by a webcam, which will determine how many turns a stepper motor moves.

Arduino:

    #include <AccelStepper.h>
    AccelStepper stepper(AccelStepper::DRIVER,8,9);

    void setup() {
      Serial.begin(9600);
      stepper.setMaxSpeed(1000.0);
      stepper.setAcceleration(700.0);
    }

    void loop() {
      int val = 0;
      if(Serial.available()){
        val = map(Serial.parseInt(), 0, 1280, 0, 551);
        Serial.println(val);
      }
      stepper.runToNewPosition(val);
    }

Python:

    # source: http://www.steinm.com/blog/motion-detection-webcam-python-opencv-differential-images/

    import cv2
    import numpy as np
    import serial
    import time

    def diffImg(t0, t1, t2):
        d1 = cv2.absdiff(t2, t1)
        d2 = cv2.absdiff(t1, t0)
        dif = cv2.bitwise_and(d1, d2)
        return np.fliplr(dif)

    cam = cv2.VideoCapture(0)

    #winName = "Movement Indicator" #camera window
    #cv2.namedWindow(winName, cv2.WINDOW_NORMAL)

    # Read three images first:
    t_minus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
    t = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
    t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)

    h, w = t.shape

    winTest = "Test Window" #test window
    cv2.namedWindow(winTest, cv2.WINDOW_NORMAL)

    thresh = 100

    ser=serial.Serial('/dev/cu.usbmodem1411',9600,timeout=0)
    time.sleep(2)

    while True:

        img = diffImg(t_minus, t, t_plus)

    #    cv2.imshow(winName, img )

        nz = np.transpose(np.nonzero(img>thresh))
        a = 0
        b = 0
        c = 0
        d = 0
        avg=0
        if nz.size>0:
            a,b = nz[0]
            c,d = nz[-1]
            avg = (b+d)/2
            if 0<=avg and avg<=1280:
                print avg
                ser.write(str(int(avg))+" ")

        test = np.zeros((h,w))

        cv2.rectangle(test, ((avg-5),a), ((avg+5),c), (255), -1)
        cv2.imshow(winTest, test )

        # Read next image
        t_minus = t
        t = t_plus
        t_plus = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
        print ser.readline();

        key = cv2.waitKey(10)
        if key == 27:
           cv2.destroyWindow(winName)
           ser.close()
           break

    print "Goodbye"

This works OK but occasionally 'val' will take some ridiculous value, say 7182, and the motor spins out of control. I realize I can check values with an if statement before I actually write to the stepper motor, but I think my problem is with reading and writing to the Arduino.

My other issue is I feel Arduino is not receiving some of the data sent to it via serial connection. This is hard to say, as Serial.print() is slow and mostly doesn't make it through to my terminal before it's already been rewritten.

body:
Mr Gammon's comment about using a faster baud rate is an excellent idea.

You also seem to be sending the number as a string.  Sending the integer as binary data (using python's struct module) would also reduce the amount of data that needs to be sent - significantly for larger numbers.

    import struct

    ...

    ser.write(struct.pack('I',int(avg)))

On the Arduino Side

    uint8_t buffer[4];
    uint32_t position;

    if (my_serial.read(buffer, sizeof(uint32_t)) == sizeof(uint32_t))
        memcpy(&position, buffer, sizeof(uint32_t));

    // alternatively in one step, without error checking
    my_serial.read(&position, sizeof(uint32_t));

This assumes a 32-bit integer is needed.
Maybe you only need an unsigned short - this would halve the amount needed to transmit.


message:
Bluetooth connection and RX ,TX

I have connected a RN-42 bluetooth (TX-D0, RX-D1, VCC-5V, GND_GND) to arduino.The problem is that when I run this code ,nothing happens it just upload to infinite or it doesn't. I am checking with tera term. Is there a problem with the connection of the pins? Also when I pair my android phone to the bluetooth it says paired on the phone but the blue light of the bluetooth doesn't switch on, like it's not connected.

<!-- language: c -->

      #include <SoftwareSerial.h>// import the serial library
       SoftwareSerial Genotronex(1, 0); // TX,RX
       int ledpin=13; // led on D13 will show blink on / off
       int BluetoothData; // the data given from Computer

      void setup() {
      // put your setup code here, to run once:
       Genotronex.begin(9600);
       Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
       pinMode(ledpin,OUTPUT);
      }

      void loop() {
        // put your main code here, to run repeatedly:
      if (Genotronex.available()){
         BluetoothData=Genotronex.read();
       if(BluetoothData=='1'){   // if number 1 pressed ....
      digitalWrite(ledpin,1);
      Genotronex.println("LED  On D13 ON ! ");
       }
      if (BluetoothData=='0'){// if number 0 pressed ....
       digitalWrite(ledpin,0);
       Genotronex.println("LED  On D13 Off ! ");
       }
    }
       delay(100);// prepare for next data ...
     }

body:
As commenter by RSM

The issue you are facing is because you are using pins **0** and **1**

These are used by the arduino for uart.

So for starters please use any pin other that **0** and **1**.  But if you insist that you do need to use these pins,  then you don't need softwareserial you can use the default serial itself, but you will need to disconnect the bluetooth while programming.


body: If you use RX, and TX in default pin then it is not necessary that you should *include SoftwareSerial* library.


body:
The simplest solution to this is to just unplug the Bluetooth module from the TX and RX ports and click to upload. Your sketch will be uploaded and you can plug the pins back.
For a permanent solution use the digital pins aside 1 and 0 because they are the same pins your computer uses to upload your sketch to the Arduino board.


message:
What are the connectors used in the arduino mega?

I am trying to build a shield for an arduino mega.For that i need to know the type of the female connectors that are soldered in the pins of the arduino mega in order to choose the correct male connectors.

body:
Look for male pin header strip, with 0.1 inch (2.54mm) pitch.

In single and dual row form.

Specifically they are:

 - 8x1 ADCL
 - 8x1 ADCH
 - 8x1 PWML
 - 8x1 PWMH
 - 8x1 Communication
 - 6x1 Power
 - 18x2   digital IO (on the side)

Source: [Schematics][1]

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf


message:
Arduino Due and BNO055 address in i2c mode

I have a project where I need to have several IMUs, the BNO055 shuttle board (I explained my project [here][1]), I manage to get the Euler angles from one BNO055 sensor, which have the address 0x29, because I linked the I2C_MODE_ADR_SEL to a HIGH level.

I would like to have another sensor with the address 0x28. As the datasheet says, I must link the I2C_MODE_ADR_SEL to a LOW level (to the GND) the i2c Scanner from the Arduino Playground does not recognize any i2c device.

I don't know how to change my sensor address, can anyone help me with this issue ?

  [1]: https://arduino.stackexchange.com/questions/13756/arduino-due-and-bno055

body:
According to Table 4-7 on page 90 of the [BNO055 datasheet at adafruit.com](http://www.adafruit.com/datasheets/BST_BNO055_DS000_12.pdf), the BNO055 supports three I2C addresses: 0x28 or 0x29 in slave mode (selected by COM3 being low or high, respectively), or 0x40 in the HID-I2C configuration.

According to the diagram on page 2 in file [BNO055_Shuttleboard_Flyer.pdf](http://ae-bst.resource.bosch.com/media/products/shuttleboards/BNO055_Shuttleboard_Flyer.pdf) (Bosch's description of the BNO055 Shuttle Board), COM3 on pin 17 of the BNO055 (or, PSERCOM3) is wired via 0Ω jumper R106 to the middle pin of J102.

If you plan to get data from five different BNO055's, you may need to use a multiplexer (or several I/O's) to set COM3 on one BNO055 board to a different level than on the other four, to select one of the five boards for access.  For example, you could use a 7438 (eg, an MM74HC138 or DM74LS138).  When you set the 7438's address input to `j`, line Yⱼ (from among Y₀ to Y₇) will go low while the the other Yᵢ remain high.  The BNO055 with COM3 attached to Yⱼ then would be the only BNO055 that would respond to I2C address 0x28.

For testing, you could set up several BNO055's and use several separate I/O lines to control several COM3 inputs.  Using separate I/O lines takes five I/O lines for five COM3's, vs three I/O lines using a 7438 multiplexer; saving two lines might not be worth the extra effort of obtaining and using a multiplexer.

Another approach is to use two more Arduino (eg Pro Mini or Micro) units to support separate I2C busses for additional BNO055's.  These auxiliary Arduinos could do some data reduction before sending data (via serial or I2C) to the principal Arduino.

Note, it is not clear to me that using more than one or two BNO055's makes sense.  If the assemblage of BNO055's moves through space more or less as a unit, but with attitudes, roll rates, etc differing between BNO055's, then 3/4 or so of the data from different BNO055's will be the same.  Possibly less-general sensors (eg, without magnetometer) with different I2C addresses could be used instead.


body:
I've built MotioSuit, a mocap suit based on the BNO055 which currently has 9 sensors but could go up to 18.

https://hackaday.io/project/9266-motiosuit

The sensor board and library are open-source and documented in the link, I hope it helps!


body:
Although this is an older question, I believe there may be people still looking for a solution to this problem. Documentation for the BNO055 Shuttle board is pretty thin. I've added a bit of the schematic below.

BNO055 Com3 (pin 17) is presented on pin 22 of the shuttle board (12C_MODE_ADR_SEL). This pin must be connected through a resistor either to shuttleboard pin 4 (SD0, GND) or to shuttleboard pin 5 (SD1). The datasheet makes mention of 2-position jumper J102 which should accomplish this, but there are versions of the Shuttle board that do not include this jumper or any place to mount it. In the photo of the OP's setup (pasted at bottom in case his link goes away) the jumper header would be installed across the three holes adjacent to pin 3 (GND), and jumping the center pin to the left or right-side pin would set the address to 0x028 or 0x029.

If you don't have the jumper, just connect the pins directly: when I connect pin 17 to pin 4 through a 10K resistor, the Arduino "example" scanner does see it at I2C address 0x28.

Personally I like the Adafruit BNO055 board a lot better than the Shuttle -- it has a voltage regulator and a lot of other additions, and it uses 0x028 as its default I2C address.

For those working in the Arduino code environment and wishing to incorporate more than two BNO055 devices and who do not wish to use a multiplexer, I might suggest looking at the Teensy family of 32-bit ARM cortex CPU boards. These are completely code-compatible with Arduino, but offer more than one I2C bus. In fact the Teensy 3.6 (180 MHz!! with 1M Flash, 256K Ram, 4K eeprom, an FPU) offers four* separate I2C Wire interfaces on different ports, which would permit 8 of the BNO055 devices to be used.

I've personally been very happy with the performance and functionality of the Teensy boards when used with multiple BNO055 devices.

[![BNO055 Shuttle Board Pinout][1]][1]
[![The OP's Shuttle Board][2]][2]

  [1]: https://i.stack.imgur.com/DNk9t.png
  [2]: https://i.stack.imgur.com/j2Dzb.jpg


message:
Use the TCS3200 color sensor without the included LEDs

just a quick question. I want to know if it is possible to use the TCS3200 color sensor without the 4 LEDs included on the breakout board. I want to get the sky colors. Is that possible?

body: The photodiodes in the device itself have filters so it should *theoretically* be possible to use it without auxiliary light sources. Note, however, that the green and blue sensors have *two* sensitivity peaks and so using it outdoors without an infrared filter is not advised.


message:
What are the distances between Arduino Mega connectors?

I am trying to build an Arduino Mega shield. For that, I need to know the exact distances between the different connectors.

body:
The pin layout and dimensions of the Mega are as follows:
[![Mega Board layout.][1]][1]

Dimensions are in thousandths of an inch. [Source][2]

  [1]: https://i.stack.imgur.com/a1uUG.png
  [2]: https://blog.arduino.cc/2011/01/05/nice-drawings-of-the-arduino-uno-and-mega-2560/


message:
Can I use analogReadResolution() on an Uno or Leonardo?

I am trying to get a spectrum analyser up and running. I found the following code on [Galileo GEN2 Project - Real-Time Audio Spectrum Analyzer][1]1:

    /*
     *
     * Galileo GEN2 Project - Real-Time Audio Spectrum Analyzer
     * https://communities.intel.com/docs/DOC-23406
     *
     *
     * ERROR: analogReadResolution() ???
     *
     */

    #include <stdint.h>  //For New Arduino
    #include "PCD8544.h"
    #define pin_adc 0
    #include "fix_fft.h"
    char im[128];
    char data[128];
    int analog_value[128];
    int i=0;
    PCD8544 nokia = PCD8544(3, 4, 5, 7, 6);
    // pin 7 - Serial clock out (SCLK) connects Dig3
    // pin 6 - Serial data out (DIN) connects Dig4
    // pin 5 - Data/Cmd. selct. (D/C) connects Dig5
    // pin 4 - LCD reset (RST) connects Dig6
    // pin 3 - LCD chip select (CS) connects Dig7
    void setup() {
      nokia.init();
      nokia.command(PCD8544_DISPLAYCONTROL | PCD8544_DISPLAYNORMAL);
      nokia.clear();
      analogReadResolution(8);
    }

    void show_big_bars(char *spektrum) {
        int spek_for_draw;
        nokia.drawline(10, 15, 10, 39, BLACK);
        for (byte i = 1; i < 64; i++){ // Skip 0 Channel
          // Serial.print(spektrum[i],BYTE);
          spek_for_draw = 1.5*(spektrum[i]); // 0/2.5 ~ 255/2.5
          if (spek_for_draw > 39) spek_for_draw = 39;
          nokia.drawline(i+10, 39 - spek_for_draw, i+10, 39, BLACK);
        }
        //nokia.drawstring(5, 5, "0 09 22 36 49");
        nokia.drawstring(5, 5, "0");
        nokia.drawstring(21, 5, "4");
        nokia.drawstring(37, 5, "8");
        nokia.drawstring(48, 5, "12");
        nokia.drawstring(67, 5, "18");
        nokia.drawstring(5, 0, "Spectrum");
        nokia.drawstring(5, 1,"* 0.1KHz");
        nokia.display(); // Update Screen
        nokia.clear(); // Clear Screen for the animation
    }
    void loop(){
      static long tt;
      int val;
      if (i < 128){
          analog_value[i] = analogRead(pin_adc);
          i++;
       }
       else{
            for (i=0; i< 128;i++){ //Prepare data for FFT
                data[i] = analog_value[i] - 128;
                im[i] = 0;
            }
       //this could be done with the fix_fftr function without the im array.
            fix_fft(data,im,7,0);
       // I am only interessted in the absolute value of the transformation
            for (i=0; i< 64;i++)
                 data[i] = sqrt(data[i] * data[i] + im[i] * im[i]);
       //do something with the data values 1..64 and ignore im
            show_big_bars(data);
            i=0;
       }
    }

When I attempt to compile the above code, I get the error

    Arduino: 1.6.5 (Mac OS X), Board: "Arduino Micro"

    fft_galileo.ino: In function 'void setup()':
    fft_galileo:31: error: 'analogReadResolution' was not declared in this scope
    'analogReadResolution' was not declared in this scope

When I search for the location of `analogReadResolution()` on Google, I repeatedly get the information that it is only available for the Due and Zero. From [Arduino - AnalogReadResolution][2]:

> analogReadResolution() is an extension of the Analog API for the
> Arduino Due and Zero.

I was wondering if I needed to add an `#include` statement but all of the code examples that I found do not have any specific `#include` for the Analogue library.

Also, thinking maybe it is board specific (as the video [Arduino Due error: 'analogReadResolution' was not declared in this scope][3] suggests), I selected the ***Duemilanove*** board (as the ***Due*** is not on offer in my "Board" menu), but I still get the same error. I have even tried the ***Arduino NG or older*** Board menu item, but with the same results.

So, how do I get rid of this compile time error? Or, more poignantly, how can I compile this code for my Uno or Leonardo board.  Should I just comment it out? If I do comment the line out then the code *does* compile, so does this mean that `analogReadResolution()` is not required any longer?

If it isn't required, then why does this Uno specific example, [How to Use ADC in Arduino Uno?][4], state:

> As default we get the maximum board ADC resolution which is 10bits,
> this resolution can be changed by using instruction
> (“analogReadResolution(bits);”). This resolution change can come in
> handy for some cases.

How can the resolution be changed if the method has, indeed, been deprecated?

Also, why do I not have a "Due" in my **Board** menu?

------

1 For completeness `fix_fft.h` and `fix_fft.cpp` can be found on [TJC's github][5] and here is the [PCD8544 Arduino library for Nokia 5510 LCD][6] library. The password for decompressing `Intel_Nokia5110.rar` file is 406.

  [1]: https://communities.intel.com/docs/DOC-23406
  [2]: https://www.arduino.cc/en/Reference/AnalogReadResolution
  [3]: https://www.youtube.com/watch?v=C_cQ7vYTnWw
  [4]: http://circuitdigest.com/microcontroller-projects/arduino-uno-adc-tutorial
  [5]: https://github.com/TJC/arduino/tree/master/sketchbook/libraries/fix_fft
  [6]: http://120.107.171.121/~tywua/sub/ISAR/Intel_Nokia5110.rar

body:
There is no point to having `analogReadResolution()` on AVR devices since that function *only exists* to provide/ensure backwards compatibility with the fixed 10-bit ADC that is found in AVR devices. If you want higher or lower resolution then you will need to perform the appropriate actions manually.

You don't have a Due entry because you haven't installed Atmel SAM support in the Board Manager.


body:
> Also, why do I not have a "Due" in my Board menu?

See:

[![Board manager menu item][1]][1]

Then:

[![Board manager install][2]][2]

---

> I selected the Duemilanove board (as the Due is not on offer in my "Board" menu) ...

The Duemilanove and the Due are completely different boards, with different processors.

  [1]: https://i.stack.imgur.com/EeYBw.png
  [2]: https://i.stack.imgur.com/x4WJF.png


message:
Why is my variable not getting updated?

I have the following snippet of code:

    const unsigned long fiveMinutes = 5 * 60 * 1000UL;
    unsigned long lastCheck = 0 - fiveMinutes;
    unsigned long now = 0;

    void loop() {
      now = millis();
      if ( now - lastCheck >= fiveMinutes ) {
        doStuff();
        lastCheck = now;
      }
    }

The `doStuff()` routine is getting called on every `loop()` iteration, because the value of `lastCheck` isn't getting updated. I thought Icould update global variables inside subroutines, but the behavior I'm seeing says otherwise. What am I doing wrong? (`doStuff()` is defined and works correctly, I'm not posting it here for brevity.)

body:
I modified your code to produce a working example:

    const unsigned long fiveMinutes = 20 * 1000UL;
    unsigned long lastCheck = 0 - fiveMinutes;
    unsigned long now = 0;

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      Serial.println ("Starting.");
      Serial.println (fiveMinutes);
      }  // end of setup

    void doStuff ()
      {
      Serial.println ("Doing stuff");
      }

    void loop() {
      now = millis();
      if ( now - lastCheck >= fiveMinutes ) {
        doStuff();
        lastCheck = now;
      }
    }

I reduced the interval to 20 seconds, and Ignacio Vazquez-Abrams is correct about the initial test, however apart from that, I see "Doing stuff" every 20 seconds.

---

>  I thought I could update global variables inside subroutines ...

You can.

---

Are you sure you didn't have:

    void loop() {
      unsigned long lastCheck;
    ...


message:
lcd.print then dataFile.print

My program is a bit large and I'm worried about stability.

I need to print data to both a file and to my LCD. It's like this:

    if (hour<10) {
        dataFile.print("0");
    }
    dataFile.print(hour, DEC);
    dataFile.print(":");
    if (minute<10) {
        dataFile.print("0");
    }
    dataFile.print(minute, DEC);
    dataFile.print(":");
    if (second<10) {
        dataFile.print("0");
    }

Then

    if (hour<10) {
        lcd.print("0");
    }
    lcd.print(hour, DEC);
    lcd.print(":");
    if (minute<10) {
        lcd.print("0");
    }
    lcd.print(minute, DEC);
    lcd.print(":");
    if (second<10) {
        lcd.print("0");
    }

What is a smart way to make this shorter? Should I write a function to add the leading zero then another that does something like:

    void printboth (thing) {
        dataFile.print(thing);
        lcd.print(thing);
    }

good idea?

body:
You could format the data with snprintf:

    char timestamp[9];
    snprintf(timestamp, 9, "d:d:d", hour, minute, second);
    dataFile.print(timestamp);
    lcd.print(timestamp);

`d` in the snprintf *format* means "print at least 2 digits of this value and pad with leading zeros".


message:
Why does this code execute?

After experiencing failures of my Arduino projects due to low memory, I decided to do some research into it so I could understand better where the problems were. I eventually came to this code:

    void setup() {
      pinMode(13, OUTPUT);

      int len = 5000;
      byte *data = (byte *)malloc(len * sizeof(*data));
    }

    void loop() {
      int timing = 1000;
      delay(timing);
      digitalWrite(13, HIGH);
      delay(timing);
      digitalWrite(13, LOW);
    }
I expected that since my Arduino Uno does not have enough RAM to hold an array of 5000 bytes ([Atmel's information][1] on the Atmega328P shows us it only has 2KB of SRAM), the code in void loop() would not be able to run due to lack of memory. As far as my understanding goes, once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes), there would physically not be enough space left in memory for the variable timing and the LED I attached on pin 13 would not flash on and off at intervals of 1 second.

However, my LED toggles at perfect intervals of 1 second. Why would this occur? Isn't memory allocated by malloc unavailable for use by anything else until free is called on it?

  [1]: http://www.atmel.com/devices/atmega328p.aspx?tab=parameters

body:
If you add a debugging print you will see what is happening:

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

      pinMode(13, OUTPUT);

      int len = 5000;
      byte *data = (byte *)malloc(len * sizeof(*data));

      Serial.print ("data = ");
      Serial.println ((int) data);
    }

Output:

    data = 0

The malloc failed, it returned NULL, the rest of the program proceeded normally.

---

>  once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes)

`malloc` does not return with a partial allocation. It either allocates the amount you requested or none at all.


message:
Detect button on a ground line (reverse eng)

I've found a circuit board that has a couple of circuits (buttons, IR Receiver, LED, USB). The thing is that following the line for interfacing the buttons I came across what seems to be like buttons that are connected only to the ground line of the PCB while the other end is a free pin cable.

Is there a way for the arduino to detect the ground when the button is pressed or a way to detect a short of some kind? There is a smd and a resistor on both buttons.

Circuit:

Main Ground-----Button-----SMD Capacitor-----Resistor(101)-----Free Pin

Thanks in advance!

Edit: Circuit Board

[![Circuit Description][1]][1]

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

body:
It sounds like you might have a PCB with debounced switches on them. One such circuit for debouncing switches looks like this:

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

That circuit and more about switch debouncing can be [found here][2].

A debouncer basically masks the problem of switch "bounce" which is what happens when the contacts get close and the circuit is quickly closed and opened in rapid succession until a firm connection is obtained. Its a natural problem  mechanical switches.

If that's not quite right, maybe you could help us help you better by posting a photo of the board in question.

  [1]: https://i.stack.imgur.com/vVFvF.jpg
  [2]: http://www.ikalogic.com/de-bouncing-circuits/


body: Just connect the ground to the ground on the arduino, and the free pin to a IO pin. Enable the pull-up resistor on that pin using `pinMode(<nr>, INPUT_PULLUP);`. If the button is not pressed, you will read a HIGH. If the button is pressed you will read a LOW.


body:
I did some research on the subjects and I came with a solution: [I borrowed the code from here][1] and made some modifications to fit my needs.

    const int buttonPin = 6;
    const int buttonPin1 = 7;

    int previousReading = HIGH;
    int previousReading1 = HIGH;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(buttonPin1, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop() {
      int reading = digitalRead(buttonPin);
      int reading1 = digitalRead(buttonPin1);

      if (previousReading == HIGH && reading == LOW) {
         Serial.println(HIGH);
      }

      if (previousReading1 == HIGH && reading1 == LOW) {
         Serial.println(LOW);
      }

      previousReading = reading;
      previousReading1 = reading1;

    }

  [1]: http://blog.kennyrasschaert.be/blog/2014/04/01/digital-input-on-an-arduino-using-a-push-button/


message:
Why do only specific arduinos support the keyboard and mouse libraries?

The Arduino website suggests that only three boards are supported for the [Mouse and Keyboard library page][1]:

- Leonardo
- Micro
- Due

What is special about those boards, that the other boards in the Arduino family don't have? I thought they might have the same proceesing chip on them but only two of them do. The CPUs are correspondingly:

- ATmega32u4
- ATmega32u4
- Atmel SAM3X8E ARM Cortex-M3

I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?

So my question is: **what do those three boards have that lets them support those libraries?**

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

body:
Those chips have hardware support built into them to handle the rather strict timing requirements for interpreting (and responding to) USB sequences. You will notice, for example, that on the Arduino Uno there is a *second* chip (the Atmega16U2) which also can handle USB. In fact the chips with a "U" in the name generally can do this.

> I have Nanos, Unos and Duemilanoves. I am out of luck aren't I?

You have a couple of options. Some people reflash the USB chip on their Uno (for example), although personally I think that is a bit fiddly.

Alternatively, there is a library called VUSB (virtual USB) which lets you do some USB on the non USB chips. Google `vusb arduino`.

You need three resistors and two zener diodes to make up the hardware that lets this library do its stuff.


body:
Another option is to use the [PS2Keyboard] library, a PS2 connector and a PS2-to-USB converter.

You will need only two digital pin of your Arduino and have keyboard solution.

[PS2Keyboard]:http://playground.arduino.cc/Main/PS2Keyboard


message:
Use TSL2561 and DS1307 RTC together

I want to use a TSL2561 light sensor and a DS1307 RTC and a couple of other sensors like DS18B20, AS3935, ML8511, MQ135, 433 mhz sender together with an Arduino.
However on Adafruit I read this today (Quote from Adafruit)

> You may be wondering, how is it OK to connect a 3.3V chip like the
> TSL2561 to 5.0V data pins like the Arduino? Isn't that bad? Well, in
> this specific case its OK. I2c uses pullup lines to the 3.3V power
> pin, so the data is actually being sent at 3.3V. As long as all the
> sensors/device on the i2c bus are running on 3.3V power, we're fine.
> However, don't use a 5.0v powered i2c device (like the DS1307) with
> pullups at the same time as a 3.3V device like the TSL2561! If you
> want to use this sensor with a datalogger that uses the DS1307, remove
> any/all of the pullup resistors from the DS1307 SDA/SCL pins. The
> pullups built into the TSL2561 will then be active and keep the
> voltage at 3.3V which is safe for both the RTC and the sensor.

I don't really understand the meaning of this. What am I supposed to do? It tells me to remove the pullup lines on the RTC, but what are they and where can I find them? Are there any other sensors where I have to do this? If I don't remove the pullup lines, will I damage anything? Can someone clarify those things to me?

body:
You can use the DS1307 itself just fine, but you are probably using a breakout board. These boards have (pull-up) resistors on it that will pull-up the I2C lines to 5v, while you only want 3.3v. This will not damage the arduino, but could damage chips like the  TSL2561, that can only handle 3.3v.

[![RTC breakout][1]][1]

On the board you indicated you are using, you need to remove R2 and R3

Other 5v sensor breakout might also have pull-ups to 5v. Easiest way to check, is to connect 5v and ground, and then measure the voltage on the SDA and SCL pins. If it's 5v, then it has pull-up resistors that need to be removed.

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


message:
I would like to control 16 motors with a servo shield

Ok so I've used nicks code and have the code running once ok.... I the noticed however I had a fast 180 sweep and then it returned under control of code. I then noticed the comments wrt pulselen of 1000 being zero degrees and using 1500 as 90 degrees.... Wow so I get a single movement which holds but it doesn't go 90 degrees...

I'm using an Adafruit servo shield.

I can make my servo move. However, I want to stop it at 90 degrees *without* it returning to 0 degrees each time.

What am I missing?

The code I've used is as follows:

<!-- language: c -->

    void setup()
    {
      pwm.begin();
      pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
    }

    void loop()
    {
      for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
      {
        pwm.setPWM(0, 0, pulselen);
      }
      delay(500);
    }

body:
The variable `pulselen` in your code corresponds to the angle you want the servo to turn to. For most servos the `pulselen` is supposed to be a number from 1000 to 2000, where 1000 corresponds to 0 degrees and 2000 corresponds to 180 degrees, but some servos may be different. It's probably safe to assume that you want a value close to 1500.

Of course the servo takes a while to get to its position, so the best approach usually involves changing `pulselen` gradually until you get to the desired position.

Once you get to 90 degrees stop changing `pulselen`. At that point you should still be sending the PWM but keep it at 1500. You'll want to keep sending the PWM signal, or the servo will have no resistance to external forces.


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

The code in `loop` is called repeatedly. Thus it does this:

* Go from SERVOMIN to SERVOMAX very rapidly (I measured 72 ms)
* Pause half a second
* Repeat the above

To make it pause at SERVOMAX you need to either not repeat the loop, or put it all in `setup`, eg.

    #include <Adafruit_PWMServoDriver.h>
    #include <Wire.h>

    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

    #define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
    #define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)
    void setup()
    {
      pwm.begin();
      pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
      for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++)
      {
        pwm.setPWM(0, 0, pulselen);
      }

    }

    void loop()
    {
    }


message:
RDM630 RFID Reader on Beaglebone Black?

I have an RFID reader RDM-630 with these specifications: http://www.seeedstudio.com/depot/datasheet/RDM630-Spec..pdf

Could I connect this to a Beaglebone Black?

body: Found what I was looking for and the answer is yes.


message:
Can I use GPS sensors in a country (India) that doesn't have its own GPS Sattelites?

I am living in India. I want to work on Arduino Projects with GPS Modules. But only a few countries like US, Russia, China etc. have their own GPS satellites. India is working on it. So I am hesitating to buy GPS sensors. Can I work normally with GPS modules in my country as shown in Online projects in my country ?

body: Each of the countries listed has their own *satnav system*. GPS satellites cover the *entire world* and the US government allows *anyone* with a GPS receiver to use it, regardless of where on or above the surface they are located.


message:
Sending "Blink" to pin 12 is causing on-board led to blink?

I recently picked up an [Uno clone][1] and noticed that if pin 12 is set to an output and I run the Blink sketch on it, the built in led (supposedly connected to pin 13) blinks. It's not as bright as it is when I run it on pin 13, but nonetheless it blinks. If I run it on any other pin, nothing happens, which is the behavior I expected with pin 12.

Is this a common issue with arduino boards, the microcontrollers, etc. or did I get a bad board?

Overall the board visibly appears to have solid construction and appears as the one on the site that I linked to.

Lastly as a side note, I'm currently living in India and won't have a problem going back to their factory for a replacement, if it is a bad board. They include a 6 month warranty.

    int ledPin = 12;
    int delayPeriod = 100;

    void setup()
    {
      pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
      digitalWrite(ledPin, HIGH);
      delay(delayPeriod);
      digitalWrite(ledPin,LOW);
      delay(delayPeriod);
      delayPeriod = delayPeriod + 100;
    }

  [1]: http://www.avmicrotech.com/shop/product.php?id_product=123

body:
See https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board

As I state on that page, if pin 13 is set to input the LED may turn on due to being driven by an op-amp. A nearby pin turning on may be enough to cause that effect. Try adding:

     pinMode(13, OUTPUT);
     digitalWrite (13, LOW);

See if that changes the behaviour.


message:
Arduino car on bluetooth remote appears to crash when motors started

I built a Arduino robot car which accepts instructions via bluetooth. The instructions are pretty simple, they tell the car to stop, go forward, reverse, turn left or turn right.

When I have the car powered through the computer USB (ie when I have just uploaded the sketch), all works fine. However, when I run off independent battery power, the arduino seems to restart whenever I give the car an instruction which means the motors have to operate.

I know the sketch is restarting inside the Arduino because the blue tooth terminal displays the startup text which is inside the 'setup' function.

What is going wrong here? What issue am I encountering?

The board is an Arduino UNO with an Arduino Motor Shield attached. The blue tooth and two sonic sensors are attached to the motor shield pins.

Also, I have a 9V battery attached to the motor shield. Plus 4 times 1.5V batteries powering the UNO. Am I screwing up the power at all? Getting too much? Or too little?

body:
it sounds like the motors are pulling down the battery voltage enough to reboot the Arduino; and the USB-port is able to supply enough current without as much voltage drop.

We'd need to see a schematic, but check that the power supplied to your Arduino and power supplied to the motors are completely independent; that the Arduino only supplies current to a switch or a relay in the motors' power circuit but not to the motors themselves.


body:
You seem to be using your heavy-duty batteries for the Arduino and the light-duty 9 V battery for the motor. To me this seems backwards. Also the Vin pin to which you have the 9 V battery connected is by default connected to the Arduino as well. This means that if the motors draw a lot of current it will drag the Arduino's voltage down and it will probably reset (thus cutting power to the motors, and then it reboots).

From the [Arduino Motor Shield page](https://www.arduino.cc/en/Main/ArduinoMotorShieldR3):

> Vin on the screw terminal block, is the input voltage to the motor connected to the shield. An external power supply connected to this pin also provide power to the Arduino board on which is mounted. By cutting the "Vin Connect" jumper you make this a dedicated power line for the motor.

You should cut that jumper so that the Arduino and the motor have dedicated supplies.

Also, arrange better batteries for the motor. You may find you can run the Arduino from the 9 V battery, and then make sure you have enough AA batteries to drive the motors.


message:
What will use less memory, an array or if ... else?

I'm trying to make my sketch smaller. Right now I use an array for the AM/PM part of my time display. My thinking is this makes it easy to change the formatting:

<!-- language: c -->

    char* ampms[]= {"am", "pm"};

    void loop() // run over and over again
    {     //get time from RTC
         getDateDs1307(&second, &minute, &hour);

          //change to 12 hour format.
          if (hour>12) { hr = hour - 12; ampm=1; } else { hr = hour; }

          //add leading 0 for hours
          if (hr<10) { lcd.print("0"); }

          //print hour in 12 hour format.
          lcd.print(hr, DEC);

          lcd.print(":");

          //add leading 0 for minutes
          if (minute<10) { lcd.print("0");}

          //print minutes
          lcd.print(minute, DEC);

          //print am or pm using array.
          dataFile.print(ampms[ampm]);
    }

I could do this instead:

<!-- language: c -->

    void loop() // run over and over again
    {     //get time from RTC
         getDateDs1307(&second, &minute, &hour);

          //change to 12 hour format.
          if (hour>12) { hr = hour - 12; } else { hr = hour; }

          //add leading 0 for hours
          if (hr<10) { lcd.print("0"); }

          //print hour in 12 hour format.
          lcd.print(hr, DEC);

          lcd.print(":");

          //add leading 0 for minutes
          if (minute<10) { lcd.print("0");}

          //print minutes
          lcd.print(minute, DEC);

          //print am or pm using array.
          if (hour>12) { lcd.print("am");} else {lcd.print("pm"); }
    }

No more am/pm array. But, I have to add an if... is one better than the other for memory? Why?

body:
As Ignacio says, if the compiled size is the same both ways, look for something else.  (But note that having the constants in flash memory (program memory) may still use about the same amount of RAM, and typically will take more program space.)

When I compile the code you showed (together with minor additions like declaration of variables) I show the array method using 4 bytes less code and 5 bytes more RAM than the `if` method, so there are tradeoffs.

You can replace the clunky `if` statement and its two `lcd.print`s  with the following:

          lcd.print(hour>12? "am" : "pm");

Note that that line retains the two bugs that your `if` statement has, but it produces them more compactly. :) [One error is that your `if` statement prints `pm` for hours 0 through 12 and `am` for hours 13 through 23.  Another error is that it prints zeroes instead of twelves for the hours after midnight and noon.  More properly, a program should print like 12:xx am during hour 0 of the day, and like 12:xx pm, 1:xx pm, ... 11:xx pm during hours 12 through 23.]

Also note that as Gerben mentions, moving the "am" and "pm" strings into program memory via

    lcd.print(hour>12? F("am") : F("pm"));

saves 6 bytes of RAM.  However, that improvement in RAM usage is offset by 74 additional bytes of program space! The following saves 6 bytes of RAM while increasing program size by only 12 bytes so may be preferable:

    lcd.print(hour>12? 'p' : 'a');
    lcd.print('m');

The following lines of C can replace much of the code you showed.  However, the `printf` library uses about 1300 bytes of program space, so the following compact-source-code approach cannot be recommended unless you are already loading some `printf` functions.  It replaces the lines from `if (hour>12) { hr = hour - 12; } ...` to the end with

    enum { bufsize=8 };
    char buf[bufsize];
    snprintf (buf, bufsize, ":02%cm", hour, minute, hour>12? 'p' : 'a');
    lcd.print(buf);


message:
Arduino Relay Shield

I am wondering if this Arduino Relay Shield design would be good enough to handle 120v 1amp The transistor is a 2n4401. Also The Two capacitors on the other 3 circuits would be going to ground opps its to late for this   [![enter image description here][1]][1]

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

body:
**The critical part is the relay.**

I'd want relays with rated to switch the load and and handle the cold current that the lamp wants.

I also want to see a good creepage clearance distance between digital side and the relay outputs.  Relays which put the common contact between the coil terminals are probably a bad choice here, relays that instead have the contact terminals at one end and the coil terminals at the other make the PCB layout easier.