body:
As I don't want to stack the shield over the mega 2560 board, I try to connect only the pins that used for GSM communication. Here are my connection:

Pin 3 on Mega <==> Pin GSM Rx on Shield

Pin 10 on Mega <==> Pin GSM Tx on Shield

Pin 4 on Mega <==> Pin 4 on Shield

Pin 5V on Mega <==> Pin Vin on Shield

Pin GRD on Mega <==> Pin GRD on Shield

Code I used is from the Examples library, GsmScanNetworks:

    #include <GSM.h>

    // PIN Number
    #define PINNUMBER "8888"

    // initialize the library instance
    GSM gsmAccess;     // include a 'true' parameter to enable debugging
    GSMScanner scannerNetworks;
    GSMModem modemTest;

    // Save data variables
    String IMEI = "";

    // serial monitor result messages
    String errortext = "ERROR";

    void setup()
    {
      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("GSM networks scanner");
      scannerNetworks.begin();

      // connection state
      boolean notConnected = true;

      // Start GSM shield
      // If your SIM has PIN, pass it as a parameter of begin() in quotes
      while(notConnected)
      {
        if(gsmAccess.begin(PINNUMBER)==GSM_READY)
          notConnected = false;
        else
        {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      // get modem parameters
      // IMEI, modem unique identifier
      Serial.print("Modem IMEI: ");
      IMEI = modemTest.getIMEI();
      IMEI.replace("\n","");
      if(IMEI != NULL)
        Serial.println(IMEI);
    }

    void loop()
    {
      // scan for existing networks, displays a list of networks
      Serial.println("Scanning available networks. May take some seconds.");
      Serial.println(scannerNetworks.readNetworks());

        // currently connected carrier
      Serial.print("Current carrier: ");
      Serial.println(scannerNetworks.getCurrentCarrier());

      // returns strength and ber
      // signal strength in 0-31 scale. 31 means power > 51dBm
      // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
      Serial.print("Signal Strength: ");
      Serial.print(scannerNetworks.getSignalStrength());
      Serial.println(" [0-31]");

    }

Questions:

 1. After opening the serial port, only a line "GSM network scanner" is read. Seems that the program is stuck on`gsmAccess.begin(PINNUMBER)`, how shall I fix that?
 2. Is it a must that I shall supply 5V 2A power to the shield seperately in order for the shield to work? (with connection mentioned above, the ON led light on the shield does turns on with an orange light)
 3. For the PINNUMBER defined in the program, my SIM has default PIN 8888. I checked with a mobile phone that the SIM card does work. But my phone shows that the SIM card is not locked with PIN. So shall I define the PIN as 8888 for ''?

EDIT:

[GSM shield link][1]

[Note for using GSM shield with Mega][2]

*** And yes! The shield did work when stacked! (Orginally I don't want to bend pin 2...but...unnh...stacking and bending out pin 2 did work)

*** Tried the examples "GSMScanNetwork" and "SendSMS", works fine. But for "GsmWebServer", an IP address is shown, but when I enter the IP address on my browser, chrome/ie says they cannot find the IP address.....Any clues?

*** And does the status LED on the GSM board have anything to do with power? It goes on and off and on and off.....

*** For question 1 & 3, PINNUMBER is set to ''. Worked fine.

  [1]: http://arduino.cc/en/Guide/ArduinoGSMShield
  [2]: http://arduino.cc/en/Guide/GSMShieldLeonardoMega

title: Connection problem with Arduino Mega 2560 and GSM shield ( official M10)

Answers: 1

body:
I have done this, and had (some limited) success.

A couple of your connections are wrong;
Connect both the pin 7s on the shield and MEGA, not the pin 4s. Pin 7 is the reset pin - I think that GSM.begin resets the shield before doing anything. This might help with Q1.

Make sure that you use the regulated 5V output on the MEGA, and not the Vin to power your shield. Vin is whatever voltage is connected to the MEGA power socket, and could damage your shield. I personally have not noticed any difference when powering the MEGA+Shield from USB or external 12V supply.

I had problems with interference when I used wires to connect shield to MEGA. The stacking seems to have reduced this problem, but not eliminated it by any means...

The GSM Web server is unlikely to work except maybe from within your SIM provider's own network. Some of the limitations are mentioned here;
https://www.arduino.cc/en/Tutorial/GSMToolsTestWebServer


body:
This is first time programming with Ethernet shield . I want to test the web server application with my Arduino. I have an Arduino Uno, Ethernet shield, and a potentiometer. Below code being uploaded.

Question are:

 - Currently I am using LAN connection to configure. How to configure it? Is internet required for below application?
 - How do I check the output?
 - Is there any software where i can make customized tags?
 - I have values coming from the serial port to be monitored on webserver. Can someone share how to monitor it?

![Manually configured for windows 7][1]
![After config][2]
![][3]

[Ethernet shield][4]

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

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192,168,1,177);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);

    void setup() {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
       while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // listen for incoming clients
      EthernetClient client = server.available();
      if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("");
              // output the value of each analog input pin
              for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                int sensorReading = analogRead(analogChannel);
                client.print("analog input ");
                client.print(analogChannel);
                client.print(" is ");
                client.print(sensorReading);
                client.println("
");
              }
              client.println("");
              break;
            }
            if (c == '\n') {
              // you're starting a new line
              currentLineIsBlank = true;
            }
            else if (c != '\r') {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            }
          }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        Serial.println("client disconnected");
      }
    }

  [1]: https://i.stack.imgur.com/De3WX.jpg
  [2]: https://i.stack.imgur.com/HDDWk.jpg
  [3]: https://i.stack.imgur.com/yDM0O.jpg
  [4]: http://arduino.cc/en/Main/ArduinoEthernetShield

title: Ethernet shield programming

Answers: 1

body:
You need to determine what the network address is of the LAN you have connected the arduino to. A router can often give you this information. Alternatively you can connect a computer to the same network and look at the computers network settings (this varies depending on what OS you use). Then you have determine what IP address is available on that network. You will enter this in the ip variable in your example.

The internet is not required for your application, however you do need the arduino to be connected to a LAN and another device (probably a standard computer) to invoke the arduinos server behaviour.

To test that it works, you can open an internet browser on the second device and type in the IP address that you have configured for the arduino into the address bar.


body:
I need to plot serial data from Arduino.

I require support for:

 1. Various data formats (e.g. signed, unsigned, 8 bits, 16 bits);
 2. Plots several data on the same axes;
 3. Exports / Imports file data.

As plotting serial data from Arduino is a common need, my question is:
What programs/utilities are available for plotting serial data from Arduino that meet the needs above?

What are the advantages / disadvantages of the method you have suggested?

title: Serial data plotting programs

Answers: 21

body:
Responding to my own question here.. I use Bridge Control Panel as mentioned.

Advantages: Lots of Features.

Disadvantages: Tricky to setup and very poor syntax/error reporting.

To use:
You need to write the Arduino Data over the Serial Port one byte at a time. For an int data type that would look as follows:

    // RX8 [h=43] @1Key1 @0Key1
    Serial.print("C");
    Serial.write(data>>8);
    Serial.write(data&0xff);

In Bridge the command to Read Data is:

    RX8 [h=43] @1Key1 @0Key1

RX8 is the read command
[h=43] means the next valid byte is "C" in ASCII
then the High Byte of Key1
then the Low Byte of Key1

It looks like this in Bridge:

![enter image description here][1]

![enter image description here][2]

  [1]: https://i.stack.imgur.com/wO2vf.png
  [2]: https://i.stack.imgur.com/BBQqC.png

body:
I use [Matplotlib][1] for any plotting I need to do.

It's not arduino specific in any way, but it is a very excellent *Python* plotting toolkit.

I've built a number of applications that plot data from a variety of microcontrollers in real-time to a graph, but that was really more of a two-step process: 1. Get data from device into computer, 2. plot realtime data.

Really, I think you should break your question into two parts:

 - How do you get data from an Arduino/Any serial device into a computer easily.
 - What is a good plotting library that is easy to use.

  [1]: http://matplotlib.org/

body:
[GnuPlot](http://www.gnuplot.info/)

 Advantages: It's very flexible, scriptable, and freely available.

Disadvantages: A bit complex to learn (but I figured out how to get started in a few minutes, and quite functional in an hour or two), runs in a terminal window (if you consider that a disadvantage).

Something I found very useful was to script it to reload my terminal program's logfile periodically so i got a dynamic graph as my experiment progressed.

![Image of GnuPlot][1]

Edit: Here is the GnuPlot script that plots it:

    #!/usr/local/bin/gnuplot -rv
    # Note reverse video here ^^^   til I find a way to put it in the script

    # gpFanCtl - Plots DiffThermo fan controller data (aloft, alow, Tdiff, fan-state).
    # $Id: gpFanCtl,v 1.8 2014-04-28 09:40:51-04 jrobert Exp jrobert $

    set terminal x11 1 noraise
    set xtics 3600
    set mxtics 4
    set xdata time

    set ytics 1 nomirror
    set mytics 2

    set y2range [0:3]
    set y2tics 1
    set my2tics 4

    set grid
    set ylabel 'Temperature, degC'
    set y2label 'Tdiff, degC' textcolor rgb '#00CD63'

    cd '/Users/jrobert/Desktop'
    plot "Logfile.txt" using ($0*4):1 title "Aloft" with lines lc rgb "red",\
         "Logfile.txt" using ($0*4):2 title "Alow" with lines lc rgb "#3982FF",\
         "Logfile.txt" using ($0*4):3 title "Tdiff" with lines lc rgb "#00CD63" axis x1y2,\
         "Logfile.txt" using ($0*4):4 title "Fan" with lines lc rgb "orange" axis x1y2;
    pause 4
    refresh
    reread

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

body:
You can use [MATLAB Student Edition][1],
this can save your time for further analysis, too.
You can just open the COM port in MATLAB and plot the received signal and/or save the signal in the workspace or whatever. MATLAB makes everything easy!

  [1]: http://www.mathworks.com/academia/student_version/

body:
I made an equivalent tool in python that print real time data from ADXL345 accelerometer.
https://github.com/mba7/SerialPort-RealTime-Data-Plotter

may be it will be helpful for someone

![enter image description here][1]

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

Just choose the serial com and speed and sent a serial data on the following format:

- 3 inputs, every input is a 2 bytes (Two's complement )
- 6 bytes seperated by a space
- the packet is a string terminated by '\n'

Could be easily adapted to change this format

body:
You can try **[serialchart](https://code.google.com/p/serialchart/)**. It's pretty strait forward program. It does exactly what you asked. The only disadvantage is that it requires data in CSV format (does not meet first point).

Screenshot from project page:

![example](https://i.stack.imgur.com/7I9kA.png)

body:
While I haven't used it myself, ["rqt_plot"][1] running on the PC seems to be a popular way to plot data on a PC that comes over a serial port from an Arduino running a sketch that includes the [rosserial_arduino][2] library or the [ros_arduino_bridge][3] library.

* [Arduino Oscilloscope Tutorial][4]
* [rosserial arduino][5]
* [visualize everything using rqt_plot... my first arduino micro ros project][6]
* "7/24: Now that I have the Arduino set up using Kessel, I can [visualize the data better using ROS tools][7]"
* etc.

  [1]: http://wiki.ros.org/rqt_plot
  [2]: http://wiki.ros.org/rosserial_arduino
  [3]: https://github.com/hbrobotics/ros_arduino_bridge
  [4]: http://wiki.ros.org/rosserial_arduino/Tutorials/Arduino Oscilloscope
  [5]: http://answers.ros.org/question/28548/rosserial-arduino/
  [6]: http://defendtheplanet.net/2014/05/21/ultrasonic-sensor-hc-sr04-as-a-ros-range-publisher/
  [7]: http://bdml.stanford.edu/Main/NikhilLeleSummer

body:
There are some good applications for visualizing the serial data, including:

 - [MegunoLink][1] ($39.95; [Lite][2] free) - plotting, logging, programming, reporting and more.

   [![MegunoLink][3]][1]

 - [Electric UI][4] ($80; free for students) - cross platform, fully featured code based GUI framework for hardware.

   [![Electric UI][5]][4]

 - [MakerPlot][6] ($59) - digital & analog plotting, monitoring, custom interfaces and more.

   [![MakerPlot][7]][6]

 - [ArduinoPlot][8] (free) - simple plotting.

   [![ArduinoPlot][9]][8]

 - [arduino-plotter][10] (free) - easy, light-weight plotting with support for all primitive types

   [![arduino-plotter][11]][10]

 - [Bridge Control Panel][12] (free) - logging, plotting, and more.

   [![Bridge Control Panel][13]][12]

 - [RealtimePlotter][14] (free) - 6 channels data plotting.

   [![RealtimePlotter][15]][14]

 - [SimPlot][16] (free) - 4 channel plotting.

   [![SimPlot][17]][16]

 - Arduino Serial Plotter (free) - built in [Arduino Editor][18] under *Tools > Serial Plotter*.

   [![Arduino Serial Plotter][19]][18]

(This is a community wiki, you can expand the list.)

  [1]: https://www.megunolink.com/
  [2]: https://www.megunolink.com/megunolink-lite/
  [3]: https://i.stack.imgur.com/YLakU.png
  [4]: https://electricui.com/features
  [5]: https://electricui.com/web_static/plot_examples.gif
  [6]: http://www.makerplot.com/
  [7]: https://i.stack.imgur.com/Nsmeb.jpg
  [8]: https://github.com/gregpinero/ArduinoPlot
  [9]: https://i.stack.imgur.com/jdTmK.png
  [10]: https://github.com/devinaconley/arduino-plotter
  [11]: https://www.dropbox.com/s/2mtg5ig7lyrrffi/plotter_preview.gif?raw=1
  [12]: https://www.infineon.com/cms/en/design-support/tools/programming-testing/psoc-programming-solutions/
  [13]: https://i.stack.imgur.com/rQjHY.jpg
  [14]: https://github.com/sebnil/RealtimePlotter
  [15]: https://i.stack.imgur.com/3okhi.png
  [16]: https://github.com/infomaniac50/projectsimplot/releases
  [17]: https://i.stack.imgur.com/YqoOn.jpg
  [18]: https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-serial-plotter
  [19]: https://docs.arduino.cc/f155cf7066d171d7b88b80f3c921e7b1/potentiometer_plotter.gif

body:
CSV format is most versatile for any data (signed/unsigned, various size and precision).

Cross-platform (written in Java/Scala) tool [Scsvlog][1] can receive/parse CSV strings from serial port / socket, show values and draw charts (up to 8).

  [1]: https://github.com/tardigrade888/scsvlog

body:
You can try out the software I developed for that propose. It's aimed to be easy to use. See [SerialGraphicator][1] - Open Source Free Serial Port Client capable of graph values that are received in JSON format.

  [1]: https://github.com/newtonis/SerialGraphicator/

body:
Almost useful. It needs:

 1. logging serial data to a file OR
 2. graphing from a file and updating every xxx milliseconds.

[Live Graph][1] is a better option and I use it in conjunction with [Tera Term][2] which gets the data via the USB/serial link (and saves it to a log file which then Live Graph polls).

Live Graph is slightly buggy when caching data and I haven't found a way to set a moving window to display results. Also, showing multiple graphs requires manual scaling, but in spite of all this, it's still very useful. It's written in java so you'll need the JRE. I prefer this over having to install python like some of the other graphing programs do. another downside is that it opens 4 different windows, which is a pain when I want to flip between it and Tera Term.

I've yet to find software that's

 1. An executable (.EXE) so it has no external reliance
 2. Includes a terminal emulator or serial data logger
 3. Logs serial data
 4. Graphs multiple items from a CSV
 5. Allows for CSV AND tab-delimited data (which is way easier to read as it scrolls along while *simultaneously* monitoring the graph.
 6. Allows setting of different scales for each overlaid graph without having to scale everything to [0..1] or setting a multiplier, i.e. allowing setting an [y0..y1] range for each item graphed.

  [1]: http://live-graph.sourceforge.net/
  [2]: https://ttssh2.osdn.jp/index.html.en

body:
Nobody had mentioned Processing which is super versatile. You can do a lot more than just plotting but if that's all you want to do you can use the gwoptics library; hook up Arduino and Processing as directed [here][1].

  [1]: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing

body:
You might be interested in `Telemetry` [See on Github](https://github.com/Overdrivr/Telemetry) . It is a communication protocol, highly simple to use, with a clean interface, that enables bidirectionnal communication with Arduino/Mbed devices.

If you don't want to read this long post, see [*A walkthrough of all the awesome features in it*][4]

The power of this library comes from the desktop command line interface (that requires **no** programming skills in python).

It is able to open high-performance plots (much higher that what can be done with matplotlib) **just by typing a command**.

The protocol supports **complexes data structures**. For now **arrays** and sparse arrays can be send from the embedded board.

The plots opened from the command line interface understand the type of data, and for arrays, rather than plotting each sample versus time, sample will be plotted against its own index.

In a near future, it is planned to add **support for spatial coordinates** (xyz data), that will allow you to plot immediately spatial data. Once, again the plots will figure everything out, plot your data in 2D or 3D space and you can focus on developping your app.

I believe those features are simply **unique** for such a project.

Pytelemetry CLI [![PyPI version](https://badge.fury.io/py/pytelemetrycli.svg)](https://badge.fury.io/py/pytelemetrycli)
---------------

Once installed with `pip`, the command line can be started with

    pytlm

Then you can `connect`, `ls`(list) received topics, `print` data received on a topic, `pub`(publish) on a topic, or open a `plot` on a topic to display received data in real-time

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

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

# Get started
[Wiki][3]

*PS : I am the author.*

I developed it because I could not find a solution that would allow me to:

 - write quickly PC scripts to control an Arduino
 - debug quickly
 - plot complex data (not just a time varying value)

all of the above without using proprietary solutions or bloated GUIs.

Using this library, the time to setup a communication between Arduino and PC went from usually half a day to 5 minutes.

  [1]: https://i.stack.imgur.com/Exo7a.png
  [2]: https://i.stack.imgur.com/q3rvr.png
  [3]: https://github.com/Overdrivr/Telemetry/wiki
  [4]: https://github.com/Overdrivr/Telemetry/wiki/Awesome-features-overview

body:
I know this is a very old question, but I recently created a mac application that solves this problem very well. You can find more information about it on www.bloonapp.com. There are some demo videos on the website that you can check out.[![enter image description here][1]][1]

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

body:
I know you were probably after more advanced GUI output, but I managed to replicate a task that one would normally do with an oscilloscope:
[![Arduino Serial Plotter output][1]][1]

using the serial plotter in the Arduino IDE and an ADC module you can get for $3 on eBay. I admit it's a bit crude, but it might be worth playing with the tool for a while, before you invest in Python/Matlab/ect level solutions. It was exceedingly easy to use. It would not take much to add SD card recording to the process.

See: [https://edwardmallon.wordpress.com/2016/08/15/using-the-arduino-uno-as-a-basic-data-acquisition-system/][2]

  [1]: https://i.stack.imgur.com/VhOIW.jpg
  [2]: https://edwardmallon.wordpress.com/2016/08/15/using-the-arduino-uno-as-a-basic-data-acquisition-system/

body:
[SerialPlot][1] (free).  It does everything you require and much more.

Other features:

 - Zoom in on data
 - Click on datapoints to see values
 - Send commands back to Arduino
 - Adjust total number of points plotted
 - Ability to show each channel in its own autoscaled plot
 - Interprets binary, ASCII and custom packets
 - Demo mode lets you play with features

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

  [1]: https://hackaday.io/project/5334-serialplot-realtime-plotting-software
  [2]: https://i.stack.imgur.com/xvQlV.png

body:
[Telemetry Viewer][1]

Advantages:

 1. Easy to use
 2. Intuitive and flexible UI
 3. Open Source and free
 4. Different types of Graphs
 5. Very fast graph update rate

Disadvantages:

 1. Stopped development
 2. Binary data format is not complete yet.
 3. Primitive graph controls like zoom, screenshot and ...
[![enter image description here][2]][2]

  [1]: http://www.farrellf.com/
  [2]: https://i.stack.imgur.com/Y1FBk.png

body:
[SVisual][1] Monitoring and recording of signals for Arduino and not only.

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

[Video example][3]

[Download (free)][4]

  [1]: https://github.com/Tyill/SVisual
  [2]: https://i.stack.imgur.com/bvRwg.gif
  [3]: https://www.youtube.com/watch?v=wlvArf7h6lE
  [4]: https://github.com/Tyill/SVisual/releases
  [5]: https://i.stack.imgur.com/aZW07.gif

body:
[Serial Plotter][1] is a simple program that I've made with Electron that receives data in the following format:
`data1,data2,timestamp;` and converts it into a realtime chart.

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

  [1]: https://github.com/ItayRosen/Serial-Plotter
  [2]: https://i.stack.imgur.com/ab7to.png

body:
I am using processing.org for serial plotting from Arduino. It was the only app I could find that allowed me to make real histograms ( e.g. a million events in a hundred bins) and display various info numbers in addition to mean sigma for each channel. Two major problems:
A) it turned out to be based on Java with no unsigned bytes
B) synch ig with input required circular buffer and markers in the data. ( high speed, no handshake)

body:
[HITIPanel][1] Serial data plotting and recording. You can zoom in/out, pan, export data to text or excel file, or import external data from text files. Come with a user interface to control and monitor the hardware.

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

[![enter image description here][3]][3]

  [1]: https://hitisoftware.com/arduino-serial-plotter/
  [2]: https://i.stack.imgur.com/loS8z.jpg
  [3]: https://i.stack.imgur.com/f2D5W.jpg


body: I am trying to connect a 2 cell 7.4 volt LiPo battery into my motor shield. I am a beginner at robotics so I am not sure if I just connect the battery, via a connector of some sort, into the motor shield itself or do I use some 22 AWG wire and connect it via that way. Sorry if that sounds confusing.

title: How to connect a 2 cell LiPo batter to Arduino Motor Shield?

Answers: 2

body:
From the Motor Shield page,

> 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 Arduino's board power jack on which the motor shield is mounted or by **connecting the wires that lead
> the power supply to the Vin and GND screw terminals, taking care to
> respect the polarities.**

So they provide the screw terminals for a battery, you should be able to insert two wires from your battery/pack into the terminals. If your battery has a connector on it, you'll need to either cut it off or find an adapter.

**Be extra careful:** if you have exposed leads from your battery and they touch, it'll get extremely hot and possibly catch fire.

body:
it is up to you.
Welded cable is better, but you will probably need a connector, so you should take care to use low-ipendance one that can hadle your current need, like `bullet connector` used by RC toys.

Also the battery should have a `discarge current` higher that the maximum current used by the engine: normaly this can be calculated by the discarge factor (labeled as 'C' on the hobbyst battery) multiplied by the capacity in Ah o the battery. Pay attention to this as this can damage the battery and alco cause lipo-fire, witch cannot pulled off with just water, you need an extinguer. (this is what happen when you short-circuit the + and -)


body:
I will be using an Arduino as a bridge between a computer high-level Java client and some low-level hardware computing units (e.g. other Arduinos). I need to find a solution to **periodically** communicate in **both** ways. It should be possible to send digital, analog inputs to the PC and receive digital, analog outputs from the PC via serial.

I have very specific requirements for my project to work:

 1. Lowest possible latency in both ways. High latency would cause
    instability of controlled systems.

 2. Extremely constant, possibly user-defined update period. Varying
    sample rate would cause inaccuracies in the control.

I need a very fast solution possible for update frequency of 100 Hz and higher.

So far I have tried to send data via Firmata to my java client using time interrupt.

    ISR(TIMER1_COMPA_vect) {
      Firmata.sendAnalog(analog, analogRead(analog));
    }

The messages however don't come at a very constant rate and are sometimes held up for twice the sample period or more which is unnaceptable. For higher frequencies this happens even more often. I suspect some kind of a buffer. Do you have any idea where should I look for bottlenecks? Would it be benefiting to design my own communication protocol and ditch Firmata?

EDIT: Look at the attached [diagram ][1]. Blue lines are "inputs", green lines "outputs". Right now I am trying to design the "Arduino (Bridge)"
![enter image description here][2]

  [1]: https://i.stack.imgur.com/9K9L8.png
  [2]: https://i.stack.imgur.com/fAmud.png

title: What's the fastest way to periodically communicate via serial?

Answers: 3

body:
> Lowest possible latency in both ways. High latency would cause instability of controlled systems.

the fact that you are using a not-real-time OS introduce a lot of unpredictable latency, the use of a visrtual machine over that os then add a bit more.
Fast communication can be obtained increasing the baudrate, that will decrease the latency between the sample and the elaboration.
Also sending RAW data instead of string will be faster (no convertion AND less byte send), and finally decreasing the overhead caused by the protocol.

For example Firmata by default use a low baudrate AND will add a lot of overhead to send WHAT kind of operation is doing. Writing your own communication protocol is better.

For example: analogRead use 10bit, so you may send a raw int, 2 byte, 16bit, so 6 bit are lost.. or you can "compress" with a bit of bitwise operation 4 read (40 bit) into 5 byte (40bit, no bit loss) instead of 8(int size * 4)!

AnalogRead is a really slow operation by default on arduino (~200us), but can be faster if you set up a lower prescaler (attention, lower prescaler means less ADC precision. at prescaler 16 guaranteed precision is 8bit, if my memory is good)

> Extremely constant, possibly user-defined update period. Varying sample rate would cause inaccuracies in the control.

On the PC side, if you need micro/nano second precision you need a `real time os`, newest linux kernel add a new special schedule but i think is still hard to find documentation. If less precision is ok, just use a timer.

On the arduino side, using a hardware timer is the best way, see [LeOS][1] for a nice scheduler on arduino

Please note HardwareSerial on the arduino side use interrupt to send data, so using it inside an ISR (like you are doing now or with LeOS) is really usafe and deadlock prone.
Also ISR will "slow down" each others, as they cannnot be executed parallel; and analogRead is a realtivly slow operation..
I would use timer to set up a flag, and in the loop if i see the flag, start the analogread, Serial.write and finally Serial.flush (to be sure to not fill Serial buffer, causing a lot of trouble on the arduino reprogrammation reset)

  [1]: http://www.leonardomiliani.com/2012/leos-un-semplice-so-per-arduino/?lang=en

body: I have had great success removing serial from such an example and setting up a closed network and then Ethernet enabling all the arduino devices. I then have a DCHP and SNTP server in the closed network. The PC etc are all in the closed network. I then setup a MQTT server (see www.mosquitto.org) and use the arduino PubSub library on the arduino. I get extremely short round trips with pretty consistent response times and this has the advantage that multiple sources can publish or subscribe to the data steams created. The SNTP server is used so that all the devices get the same time reference to use and I time stamp all messages and can then work out message sequence etc even if they are physically delayed slightly by an Ethernet collision! although in a closed network this is minimized.

body:
could you be more specific with your question ?
From what I understood:

 - you have a client java program acting as the "brain" of your system
 - your control is time sensitive. You have a PID or other regulation loop running on the pc
 - you have or plan to have multiple arguing boards on your system and you need to communicate with them.
 - you are dealing with analog IOs

## bridging ##
If you want to stick to serial port,you have to use RS485 or RS422. Those can work as a bus. Protocol on top of that can be Modbus.
Note that this has a higher latency and you need at least 2 serial ports on your bridge

I2C. Lower latency 2 wires bus. Command oriented,runs at 400 kHz. So you have plenty of time to send/receive data

SPI even lower latency as bytes are sent as stream .arduino mega has 5 pins for it. Note that you have to deal with the addressing yourself in this case.

Arduino like many micro controllers is bad as doing many tasks at the same time like for the bridging case. I would avoid using an arduino in this case

## latency ##

As already answered, ADC conversion takes time and you cannot nest interrupt.
Your minimum latency can be computed from the specifications of the arduino.
The maximum latency is a value you fix yourself.
Knowing the amount of time to send one byte on the communication port,
You can decide between options like

 - run the AD conversion in a loop outside interrupt, put the value inside a variable and do the communication a synchronously inside an interrupt
 - run the AD conversion interrupt based and the communication in the main loop of operation

## conclusions ##
Don't do hardware in the loop using a PC. The latency and lack of strict timing possibilities worsened by the use of java make it a dead end with your current setup.

Use a stronger micro controller like an AVR32 with USB running the brain of your system.
You can also use a raspberries pi or a beaglebone. Those runs "standard" Linux distributions and so you can use a PC like approach.

In any case guidelines are :

 - try to stay as close to the micro controller as possible and avoid abstraction libraries and OSes
 - don't use a pc for hardware in the loop
 - try to make your task run a synchronously as much as possible
 - keep your interrupt routines as small as possible


body:
I have made a simple Arduino program that uses a potentiometer to dim a LED.

This program also makes a second LED blink.

Finally, I have added a button that controls a third LED; this part of my program does not work: the 3rd LED is always lit as the button always reads HIGH.

Here is the code:

    //sensePin is wired up to the FSR
    int sensePin = 2;

    //this is wired up to an LED
    int ledPin = 9;

    //Wired up to a button
    int inputPin = 1;

    int val = 0;

    //I was broed so added the default Blink
    int ledPinX = 13;

    //Wired up to a second LED
    int ledPinY = 7;

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      pinMode(inputPin, INPUT);
      pinMode(ledPinX, OUTPUT);
      pinMode(ledPinY, OUTPUT);
      val = digitalRead(inputPin);
    }

    void loop() {
      if (val == HIGH){
        //This should ask "If your button is pressed, then do the code below
        digitalWrite(ledPinY, HIGH);
        //but for some reason the light is always on. I've tried it with more than one button
      }
      else if(val == LOW){
        digitalWrite(ledPinY, LOW);
      }
      int value;

      /*
     The rest of this stuff works. Well, it did before adding in the button. Now the FSR acts as a digital input. Please help.
       */
      value = analogRead(sensePin) / 4;
      analogWrite(ledPin, value);
      digitalWrite(ledPinX, HIGH);
      delay(500);
      digitalWrite(ledPinX, LOW);
      delay(500);
    }

What did I do wrong in this code?

EDIT:: diagram and pic at: instagram.com/p/m3AmHWmp4e

title: Why does my wired button always read HIGH?

Answers: 3

body: You read the button once, in `setup()`. The function is not called every time the variable's value is read, only when the line is executed and the variable assigned to. Move the `digitalRead()` call and assignment into `loop()`, before you check the variable's value.

body:
The main problem with your code is that you read the button state **only once** at the beginning of your program in `setup()`, so it keeps the initial value forever.

You should modify `loop()` as follows:

    void loop() {
      digitalWrite(ledPinY, digitalRead(inputPin));
      ...
    }

You can also remove the `val` variable, it is totally useless here; then you must also simplify `setup()`:

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
      pinMode(inputPin, INPUT);
      pinMode(ledPinX, OUTPUT);
      pinMode(ledPinY, OUTPUT);
      // val = digitalRead(inputPin);
    }

body:
Pin 1 is used for the serial output and can't be used if you enable serial using `serial.begin(9600)`.

Change button to pin 2.


body:
I've succeeded to get an Arduino to work with a pressure sensor.

What I want to do is

 - when I put pressure on the sensor, after 5 minutes the led lights on.
 - it starts over again if there's no pressure on the sensor.

Here's the program:

    // FSR is verbonden met analoog 0
    int fsrAnalogePin = 0;
    // De LED is verbonden met pin 11 (pmw pin)
    int LEDpin = 11;
    // De analoge waarde van de fsr spanningdeler
    int fsrWaarde;
    // De helderheid van de led tussen 0 en 255
    int LEDhelderheid;

    void setup() {
        // start de serial monitor
        Serial.begin(9600);
        pinMode(LEDpin, OUTPUT);
    }

    void loop() {
        fsrWaarde = analogRead(fsrAnalogePin);
        // print ‘Analoge waarde’
        Serial.print(“Analoge waarde = “);
        // print de fsrwaarde op de monitor
        Serial.println(fsrWaarde);

        // maak van getallen tussen 0 en 1023 getallen tussen 0 en 255
        LEDhelderheid = map(fsrWaarde, 0, 50, 0, 255);
        analogWrite(LEDpin, LEDhelderheid);
        delay(100);
    }

I've got this for the pressure sensor... now I need to combine it with 5 minutes and the led lights on when it's reached that 5 min of pressure.

i managed to do this but it aint enough...

    unsigned long currentTime;
    unsigned long startTime;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      currentTime = millis();
      startTime = currentTime;
    }

        void loop() {
      currentTime = millis();
      // put your main code here, to run repeatedly:
      Serial.println(currentTime);
      delay(1000);

      if(currentTime-startTime > 6000) {
    Serial.println("1 minuut voorbij");
    startTime = currentTime;
      }
    }

title: Arduino time(milli) and pressure sensor

Answers: 2

body:
The very simplest way - not necessarily the best way - is something like:

>     Keep re-reading the pressure sensor until it senses pressure;
>     Read millis(), add 300000 (# of msec in 5 min) to it's value, and store that;
>     Keep re-read millis() until it returns a number >= to that stored value;
>     Read the pressure sensor;
>     If it senses pressure,
>       turn on the alarm;
>       do nothing, forever;
>     Otherwise, start over again;

It isn't the best way, because the Arduino does nothing else for the 5 minutes until the final sensor check. But as you're learning, you probably don't need it to do anything else - for now. When that time comes, there are better ways than dedicating your processor to watching the clock. But this will get you started, and you may figure out some of those ways on your own, by then. Good luck!

Update: I realized my answer does not account for the possibility that pressure is released from the sensor and reapplied some time later, if both occur within the 5 minute wait. How you treat that situation will depend on the needs of your application (which I'm guessing is for you to learn to work with time and physical data). I'll leave that as a further exercise for you.

body:
Try this:

    unsigned long pressureOnTime; //millis() time when pressure switch is first turned on

    const unsigned long ledOnAfterTimeThreshold = 300000; //5 minutes * 60 sec * 1000 mSec
    int pressureThreshold = 1; //minimum analog reading from pressure sensor considered to be "on"

    const int fsrAnalogePin = 0;
    const int ledPin = 11;

    int ledState = LOW;
    int pressureState = LOW;

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

    void loop() {
     checkPressureSwitch();

     //do other stuff here
    }

    void checkPressureSwitch() {
     if( analogRead(fsrAnalogePin) >=  pressureThreshold )
     {
      handlePressureOn();
     }
     else
     {
      handlePressureOff();
     }

     digitalWrite(ledPin, ledState);
    }

    void handlePressureOn() {
     if ( pressureState == LOW )
     {
      //pressure switch was off, but is now on
      pressureOnTime = millis();
      pressureState = HIGH;
     }

     else if ( millis() - pressureOnTime >= ledOnAfterTimeThreshold )
     {
      ledState = HIGH;
     }
    }

    void handlePressureOff() {
     ledState = LOW;
     pressureState = LOW;
    }


body:
I'm planning to build a device that would read some sensor data and send it via GPRS, eg. once per day. (Not that original, yeah.) But my problem is choosing a GSM/GPRS shield.

The official shield has a [**nice interface for doing an HTTP POST/GET**][1]. OTOH, the shield seems to be sold out (and would be quite expensive anyway).

There seem to be other shields available, but their code examples tend to look [**quite hacky**][2]: the device waits for an arbitrary moment and then hopes that the server is done. That's IMO both inefficient or unreliable.

My question: which GSM/GPRS shield would you recommend, with these features:

a sane library w/ examples, such as the official one

an external antenna

bonus: a competitive price

another bonus: hopefully a "real" shield, so no soldering required and a few pins still easily usable for the sensors.

  [1]: http://arduino.cc/en/Guide/ArduinoGSMShield#toc10
  [2]: http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0#A_Simple_Source_Code_Examples

title: Which shield to use for GPRS?

Answers: 4

body:
That library should work with pretty much anything that has the M10 module on it.

I only have experience with the SIM900 modules. Found the cheapest one on EBay.

While interfacing with these things can be a challenge at first, you really just need to read the manual for all the AT commands and execute them. I've written a couple of functions that may help:

Note: you may safely replace all instances of `DEBUG_PRINT` and `DEBUG_PRINTLN` with `Serial.print` and `Serial.println`.

    SoftwareSerial SIM900(7, 8);

    /*
        Sends AT commands to SIM900 module.

        Parameter   Description
        command     String containing the AT command to send to the module
        timeout     A timeout, in milliseconds, to wait for the response

        Returns a string containing the response. Returns NULL on timeout.

    */
    String SIMCommunication::sendCommand(String command, int timeout) {
        SIM900.listen();
        // Clear read buffer before sending new command
        while(SIM900.available()) { SIM900.read(); }

        SIM900.println(command);

        if (responseTimedOut(timeout)) {
            DEBUG_PRINT(F("sendCommand Timed Out: "));DEBUG_PRINTLN(command);
            return NULL;
        }

        String response = "";

        while(SIM900.available()) {
            response.concat((char)SIM900.read());
            delayMicroseconds(500);
        }

        return response;
    }

    /*
        Waits for a response from SIM900 for <ms> milliseconds

        Returns true if timed out without response. False otherwise.
    */
    bool SIMCommunication::responseTimedOut(int ms) {
        SIM900.listen();

        int counter = 0;
        while(!SIM900.available() && counter < ms) {
            counter++;
            delay(1);
        }

        // Timed out, return null
        if (counter >= ms) {
            return true;
        }
        counter = 0;
        return false;
    }

body:
I would recommend the official [Arduino GSM shield][1].

  [1]: http://arduino.cc/en/Main/ArduinoGSMShield

body:
I ended up ordering an [**Elechouse board**][1] which uses the M10 chip. Found one on eBay for 59 USD. It appears to work fine with the official library.

As the manual says, it must be given external power - the USB cable isn't enough!

  [1]: http://www.elechouse.com/elechouse/images/product/GSM_shield/GSM-GPRSModule.pdf

body:
LinkitOne - ok not a shield but rather a compatible Arduino controller board with built-in GSM/GPRS/GPS/Wifi. comms library doesn't have as many diagnostic methods as e.g. the Adafruit one, but it was easy to setup and reliable. Main downside of the LinkitOne was that it uses a different processor from Arduinos so many of the Arduino libraries aren't compatible e.g. for I2C devices.

Adafruit Fona SIM808 2G Shield version. shield layout but stackable headers have to be bought and soldered seperately. Default pinouts work with Uno, but mods required for Mega. Library has lots of handy diagnostic methods (battery voltage, signal strength, etc). worked with giffgaff prepaid SIM but not vodafone for some reason. SMS worked ok. I could connect to GPRS but getting html from a website didnt' work.

DFRobot SIM808 GPS/GPRS/GSM Shield - Pre wired wirth stackable shield connectors, instructions to upload code and run the device are convoluted and vague. I Wasn't even able to get a basic connection to the Arduino to work. Either the library is very buggy or my device was faulty.

SEEEDStudio 113030009 GPRS Shield with Antenna and External SIM Holder V3.0 I'll probably tets this next..

Official Arduino GSM board DISCONTINUED

Sparkfun GSM/GPRS Module - SM5100B DISCONTINUED


body:
I'm trying to program a little bit in Arduino, but I'm stuck with probably something trivial.

This is what I have:

    char ang[3], lat[9];
    dtostrf(GPS.angle, 3, 0, ang);
    dtostrf(GPS.latitude, 9,5, lat);

    Serial.println(lat);
    Serial.println(ang);
    Serial.println("-------");

I would expect the following in the serial monitor:

    5111.60160
    267
    -------

But instead, I'm getting this:

    5111.60160
    2675111.60160
    -------

So it looks like the `ang` holds both the angle and the latitude....

Why is this happening? And how can I solve this?

My goal is to make one big string, comma separated, from the data stored in `GPS`

title: strange behaviour of dtostrf()

Answers: 1

body:
Your arrays are both too short for the strings they're meant to hold. In particular, ang has three digits and only three bytes. The string-terminator, NUL, ends up in the 1st byte of lat. Since you generated the ang string first, lat over-wrote ang's NUL character, effectively getting appended to ang.

The lat string will need at least (10+1) bytes; ang will need (3+1) bytes, counting only the actual data in your question.

I make it a habit to declare string arrays just as I wrote the sums above, to make it clear that I've counted both the contents and the NUL byte, so:

> char ang[3+1], lat[10+1];

I doubt that you need to specifically add the NUL terminator; it would quite unusual (counter-conventional) for a C/C++ function that generates a string to leave off the terminator (except in a few special cases).

Try increasing just your array sizes first; it'll probably work.


body:
I have a [Mega board][1] and a [GSM shield][2]. I'm using Arduino's example "TestWebServer". The serial monitor shows that the GSM is connected, and returns a IP.

However, the IP is always 10.X.X.X. Isn't that a internal network IP address? How should I get the SIM cards IP? Thanks!

  [1]: http://arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: http://arduino.cc/en/Main/ArduinoGSMShield

title: GSM library getIPaddress returns local network address 10.X.X.X

Answers: 1

body: The SIM card does not have an IP address. When the data connection is made to your GSM APN it is assigned an IP in a similar way to DHCP. Often the address is the same after the first connection as the service provider will link that to your SIM for audit purposes. If you setup a private APN then you can arrange to have specific range allocated to your SIM card(s). This is normally only done for security of volume reasons.


body: I have been using only Arduino Uno. Now I am about to buy Mega. But a question rises. Are those 4 Serial Ports of Mega controlled still through one usb cable?

title: Arduino Mega's 4 Serial Ports?

Answers: 1

body: No. If Arduino ATmega microcontroller supports more than a single UART, then only the first one is available through the standard USB connection. Other UARTs use their own pins that you have to connect to on the board. Mind you these pins are TTL logic serial and need a converter for RS232 or similar. It is possible to use a second (third, ...) TTL-serial to USB cable to access the port on your PC.


body:
I am using Arduino Yun and I would like to disable it to work as Access Point. That is, I don't want that it is displayed in the list of available networks.

Then I would like to set and use it (separately) in the following scenarios:

a) Arduino Yun connected just over a given Wi-Fi network (Ethernet connection disabled).

b) Arduino Yun connected just over Ethernet (Wi-Fi connection disabled).

How can I make it?

**Note**: In my previous attempts I tried to customize and/or disable someway the Wi-Fi connection (through the LuCI panel) in order to reach what I am looking for but in all of these cases [I had to restore my Arduino Yun][1] from scratch because it did not work anymore.

  [1]: http://playground.arduino.cc/Hardware/Yun#restoring_a_yun

title: How to disable Arduino Yun to work as Access Point and set it to work as needed?

Answers: 1

body:
Yun expects wifi to be working and, if it's not, it will reboot itself after 60 seconds and return in access point mode.

In order to disable this check, edit file `/etc/rc.local` and turn `wifi-live-or-reset` into `#wifi-live-or-reset` (with a starting `#`).

Once done, use LuCI (the advanced configuration panel) to configure network interfaces.


body:
I'm looking to find a suitable board for a robot I'm developing (it'll involve computer vision, else I'd be using my Arduino Micro) and I've come across two possibilities: [The Intel Galileo][1] and the [Arduino Tre][2].

Now as I understand it, the Intel Galileo has a 400MHz Quark processor, whilst the Arduino Tre has 2 processors, an onboard 16MHz standard ATmega32u4 with the Arduino bootloader and then another 1GHz TI processor with Linux installed on it.

However, I'm not sure of the differences between both products, as price estimates appear to place them at approximately the same price (around $70) and the Intel Galileo doesn't appear to have any real advantage over the Arduino Tre (except for a full x86 instruction set).

Does anyone have any information on comparison of the two boards so I can make a better informed decision?

  [1]: http://store.arduino.cc/index.php?main_page=product_info&products_id=522
  [2]: http://arduino.cc/en/Main/ArduinoBoardTre

title: What are the main differences between the Arduino Tre and the Intel Galileo?

Answers: 1

body:
## Biggest difference IMHO: Tre hasn't been released yet!
Besides that, there are a few different things that you should compare. Not much is available about the Tre as of now, but I'll update this post when it's released.

****
## *Basic Specs:* [First sub-bullet is TRE, second Galileo; better spec in bold]
 - Microcontroller:
  - Texas Instrument Sitara AM3359AZCZ100 (ARM Cortex-A8) (**1 GHz,** 32 bit), Atmel ATmega32u4 (16 MHz, Secondary, found on Leonardo)
  - Intel® Quark SoC X1000 (400 MHz, 32 bit)
 - RAM:
  - 512 MB SRAM (2.5 KB ATmega32u4)
  - 512 MB SRAM
 - Pins
  - **14 Digital 5V, 7 of which are PWM, 6 analog 5V (additional 6 multiplexed) (32u4); 12 Digital 3.3V, 4 of those are PWM (Sitara)**
  - 14 5V digital, 6 of those are PWM, 6 analog 5V
 - Networking:
  - Ethernet 10/100
  - Ethernet 10/100
 - USB port:
  - 1 USB as slave, 4 USB host ports
  - Up to 128 devices as host, 1 USB slave
 - Video
  - **HDMI (1920x1080), LCD header**
  - None that I can find
 - Audio
  - HDMI, stereo analog audio input and output
  - None that I can find
 - MicroSD card
  - Yes
  - Yes
 - PCIe Slot
  - No
  - **Yes**

Sources (I combined a bunch of data for this): [Galileo](https://arduino.cc/en/ArduinoCertified/IntelGalileo) & [Tre](https://arduino.cc/en/Main/ArduinoBoardTre)
****
**Conclusion:** If you need a board before the Tre comes out, which seems to be soon (Spring 2014), Galileo is your only option. Other than that, the Tre seems to be better all around in most aspects, minus the PCIe slot. I can't comment on power, but it seems like the Tre will be able to supply 4x the power per pin than the Galileo. The Galileo is getting older, and it doesn't seem like the Galileo can provide full Linux support like the Tre will.

Personally, I'd wait for the Tre. The *only* thing I can think that the Galileo would be better for would be either a.) lower power usage or b.) the PCIe slot for a WiFi adapter that works decently. The second one could be solved by [doing a common WiFi router hack](http://www.instructables.com/id/Cheap-and-Easy-Arduino-Wi-Fi-Hack/0).

If you need a lot of processing power without the need of low latency, you should conciser sending data to a computer to process.

>

[Source](https://arduino.cc/en/uploads/Main/ArduinoTre_LandingPage.jpg)
>

[Source](https://arduino.cc/en/uploads/ArduinoCertified/IntelGalileo_fabD_Front.jpg)


body:
I have built my own ATTiny programmer, but made a bit of a mistake along the way - I didn't align the headers properly, and now instead of them plugging into pins 10, 11, 12 and 13 as per the ArduinoISP example - they now plug into pins 8, 9, 10 and 11.

If I use some jumper cables to wire the pins to match the ArduinoISP example, it all works fine, meaning the wiring on the actual board is OK, however, I want to be able to just plug my board I have made straight in, and thus need to get the bootloader burning and the uploading to work via pins 8, 9, 10 and 11 instead.

I have tried modifying the example myself by replacing the references to RESET, MOSI, MISO and SCK with my own pin numbers, but this doesn't seem to suffice. When I try to burn the bootloader now, I get the following error:

    avrdude: stk500_program_enable(): protocol error, expect=0x14, resp=0x50
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

    avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51

If I try to upload a sketch using my version which has the custom pin numbers, I get this error:

    avrdude: stk500_getsync(): not in sync: resp=0x00

The wiring of my programmer is the same as can be found here: http://highlowtech.org/?p=1706 except I want the programmer sketch to work with different pins.

Thanks

title: Changing pins used in ArduinoISP example

Answers: 2

body:
You can't change the pins.

ArduinoISP uses the SPI interface on pins 10-13 which is provided by the underlying AVR hardware.

body:
As a practical matter, you're much better off correcting things so you're using the original pins, which correspond to hardware SPI.

However, it's not terribly hard to implement SPI in software (at a lower performance, of course):

    static uint8_t
    SPITransfer(uint8_t out)
    {
        uint8_t in = 0;
        for (int i=0; i<8; ++i) {
            digitalWrite(MOSI, (out & 0x80) != 0);
            out <<= 1;
            digitalWrite(SCK, HIGH);
            in = (in << 1) | digitalRead(MISO);
            digitalWrite(SCK, LOW);
        }
        return in;
    }

There are several SPI modes, but this implements the one used for ISP.


body: I'm trying to make my first library for Arduino and want to use a servo object in my library. How can I do this?

title: How do I initialize a servo object in my own library?

Answers: 3

body:
**This is a simple solution.** All you need to do is declare a *global variable* (i.e. make it accessible everywhere in your sketch), and then add some additional code to "share" the servo between the different parts of the code.

## Code you need:

**Your library:**

    Servo servoname;
    void foo() {
      //Some code here!
    }

    void bar() {
      //More code here!
    }

The methods `foo()` and `bar()` are irreverent to the code, you just need to declare it.

**Your library header file (`name.h`):**

    extern Servo servoname;
All you need to do then is import your new library and use `servoname`. You will have to still call `servoname.attach([pin]);` before you can use the servo, but then you just need to use the servo.

*[Source](https://stackoverflow.com/questions/1045501/how-do-i-share-variables-between-different-c-files)*

body:
If your question is about **including library A inside library B and then including library B in your main program**, then you need to be aware of a limitation of Arduino IDE (discussed in [this answer][1] to a similar question).

Arduino IDE (at least 1.0.x, I have not checked with 1.5) for an obscure reason will not include libraries included by other libraries.

The only way to work around this issue is to include ALL libraries (direct **and** indirect) in your main program file (`.ino` file):

    // Needed by library "B"
    #include "A.h"
    // Needed by your program
    #include "B.h"

    void setup() {
        // You can use B stuff here
    }

    void loop() {
        // You can use B stuff here
    }

Another workaround is to trash Arduino IDE and use a better (I mean a real) IDE: many good options have been discussed in [this question][2].

  [1]: https://arduino.stackexchange.com/questions/322/why-do-i-need-to-include-libraries-used-in-other-libraries/328#328
  [2]: https://arduino.stackexchange.com/questions/40/what-are-the-other-ides-for-arduino

body:
This should give you an idea of how to create a custom library which you can use in your project. I actually compiled it with Arduino IDE 1.0.5 on Mac OsX.
I did not run it on an Arduino board, but have similar code in a production project, that works just fine.

Start a new Arduino sketch, name it as you like.

Go to the folder where you saved that file.

Add a new file called MyServoLib.h parallel to your main project file.

In your main file, include the servo library from Arduino and your custom library like so:

    #include <Servo.h>
    #include "MyNewLib.h"

If you close and reopen your project, it the Arduino IDE will automatically load your custom library file as well.

Copy the following simple stub code into your custom library file:

    #ifndef MY_SERVO_LIB_H__
    #define  MY_SERVO_LIB_H__

    #include <Servo.h>
    #include <Arduino.h>

    class MyServoLib
    {
    public:

      MyServoLib()
        : _servoPin(9)
        , _attached(false)
      {}

      void attach()
      {
        if (_attached)
          return;

        _attached = true;
        _servo.attach(_servoPin);
      }

      void detach()
      {
          if (! _attached)
              return;

          _attached = false;
          _servo.detach();
      }

      void setPin(int pin){
        _servoPin = pin;
      }

    private:

      bool _attached;
      Servo _servo;
      int _servoPin;

    };

    #endif

Your main file should look like this:

    #include <Servo.h>
    #include "MyNewLib.h"

    // use your custom lib here
    MyServoLib myServo;
    int MyServoPin = 5;

    void setup(){

      pinMode(MyServoPin, OUTPUT);
      myServo.setPin(MyServoPin);
      myServo.attach();

      // your additional setup code here
    }

    void loop(){

      // your main code here

    }

That's it!

Upload it to an Arduino board and give it a try. The servo won't move, but it should get powered on.


body:
I am planning on making a simple stopwatch with:

 - A display
 - One or two additional buttons to start the stopwatch and stop the stopwatch and
   maybe reset it.

The problem is that it has to be as small as possible.
With all those different Arduino boards out there, I don't know which one I should buy (mini, micro, nano, ...).

I am not sure how many pins I need for the LCD since I have read that in fact not all pins are mandatory for the LCD. I have done something earlier with an LCD and I found the pot meter for the LCD contrast level a bit of waste of space. Could I just replace it with a certain resistor or something?

How many pins in the end would I need and which board would be fitting for this little project?

title: Arduino stopwatch, which board to use?

Answers: 1

body:
**By that [photo](http://arduino.cc/en/uploads/Tutorial/LCD_bb.png) you posted, you pretty much answered a decent part of your question.** You'll need six pins for the LCD, and one or two for the button. That means that you need a *total* of 8 pins. That Uno pictured has 20 (analog can act as digital, too).

As far as the boards, if you feel comfortable with some extra work, I'd recommend an ATtiny. From what I can find, it seems like you can drive a LCD with a 44 or an 84 (similar, but the 84 is more powerful).

>

*[Source for image and how to program chip](http://highlowtech.org/?p=1695)*. I'm not going to go into the details for this method, as the link has the necessary files...
****
That's the smallest way to do this*, however, if you want to use a real Arduino board, then I'd recommend the Micro for a few reasons.

First of all, it has the newer ATMEGA32u4 chip, found on the Leonardo. I do *not* recommend the Mini because, although it's the smallest of the three, it doesn't feature on board USB. You would have to buy another adapter to program it. If you're already using a breadboard, the extra 2cm (or so) is worth not having to spend *more* to buy both of those components. The Nano is the equivalent of the Mini, only with USB. Also, the Nano and the Micro are roughly the same size, one a little bit longer and one a little bit wider.

However, the Nano and Micro are roughly the same as far as processing power, so I'd recommend that, if you can get one significantly cheaper, to go with that. It doesn't really matter that much.

*If you're building this on a breadboard, it won't be smaller. If you're transferring to a PCB, then you should use an ATtiny.
****
As far as the pot goes, I'd recommend getting a *trimmer* with an equivalent value. Some of them are very small, as I have one that fits on the USB connector part of my thumb drive. They need a screwdriver to adjust, but I would recommend it. I've had issues moving it from a dark room to in the sun and not being able to see it clearly. Spend the two cents and the 2 cm2 and have an opportunity to change it if needed.

For the battery, I would recommend any rechargeable battery (under ~3.5V) **if and *only* if** you add a proper chip to not waste energy in the conversion. I talked about this in [this post](https://arduino.stackexchange.com/questions/665/powering-arduino-with-solar-panels/667#667).


body:
I'm using an arduino UNO, and i want to turn a motor a set number of revolutions, i'm trying to read the clicks of the encoder which has a resolution of 360 clicks/ revolution, my logic is that i count the number of clicks until i get to the desired number which represents the the number of revolutions * the resolution of the encoder:

1 revolution ==> 360 clicks
5 revolutions ==> 360*5 (desired number)

i'm a beginner with arduino so here is my code:

    volatile int counter=0;
    int motor=5;  // motor is connected to pin 5

    void setup(){
      pinMode(motor,OUTPUT);
      attachInterrupt(0, count,RISING); // attaching encoder on interrupt 0
    }

    void loop(){
      while(counter< 360*5){
        analogWrite(motor,255);
      }
    }

    void count(){
      counter++;
    }

This code is not working at all, how can i fix it?

title: Turning a DC motor a set number of Rotations using an encoder

Answers: 2

body:
You never tell the motor to stop.

    void loop(){
       while(counter< 360*5){
         analogWrite(motor,255);
       }
       analogWrite(motor, 0); //add something like this or whatever could stop it
       //you may want to disable the counter now too
    }

However, even with that change you are likely a long way from having a working, or at least reliable system - see other issues in my comment on the question.

body:
Since the Encoder resolution is high, the Arduino Uno misses some pulses hence you could not get the accurate reading from it. You could use the hardware quadrature decoder in Arduine Due board which can easily read the encoder values.

Here is a code which can only be executed in arduino Due to Read one quadrature encoder.
https://arduino.stackexchange.com/questions/28268/how-to-configure-2nd-quadrature-decoder-io-pins-in-arduino-ide


body:
I have wind speed sensor that can measure max speed upto 30 m/s with analog out put 0-5v. I have simple code calling from the loop. When I put the wind speed average code, the web server is not working and it just hangs. If I comment out web server it's working fine. Let me know What makes my web server hang or not get connected. Is there any way I can change average taking code?

**Working code should like below:**

    if wind speed exceed 30 m/s
       mode =stow
    else
       mode =track

 My code. And how can write average of windload of day to SDcard

    #include"wind.h"
    #include"mode.h"

    float sampleAverage(void)
    {
      float accumulator = 0;
      for (int i = 0; i < SAMPLE_COUNT; i++)
      {
        accumulator += sample[i];
      }
      return accumulator / SAMPLE_COUNT;
    }

    void Wind_calc()
    {

      static unsigned long lastSampleTime = 0;
      unsigned long currentTime = millis();

      // check if time for new reading
      if (currentTime - lastSampleTime >= SAMPLE_RATE)
      {
        lastSampleTime = currentTime;
        int sensorValue = analogRead(SENSOR_PIN);
        float voltage = sensorValue * (5.0 / 1023.0);
        /* Serial.print("voltage: ");
         Serial.println(voltage);*/
        // add the newest reading at the oldest pointer
        sample[sampleIndex] = voltage;
        // advance to next index which is now oldest
        sampleIndex++;
        // check for and handle rollover
        if (sampleIndex == SAMPLE_COUNT)
        {
          sampleIndex = 0;
        }
        // the sample array now contains the last ten readings
        // sampleIndex now points to the oldest reading
        // it will be replaced with the newest next time

        float average = sampleAverage();
        /*Serial.print("average:");
         Serial.println(average);*/
        Wind_Speed = (6 * average);
        Wind_Kmph = 3.6 * Wind_Speed;
        /*    Serial.print("Wind_Speed:");
         Serial.print(Wind_Speed);
         Serial.println("m/s");

         Serial.print("Wind_Exceed_count:");Serial.println(Wind_Exceed_count);Serial.println(".................");
         Serial.print("Wind_Kmph:");
         Serial.print(Wind_Kmph);
         Serial.println("KMPH");
         */
        if((Wind_Speed>4.0)&&(Stow_flag==0))
        {
          Wind_Exceed_count=Wind_Exceed_count+1;

          //Serial.println("Wind_Exceed_count");Serial.print(Wind_Exceed_count);
          if(Wind_Exceed_count<5)
          {
            Stow_flag=0;
          }
          else
          {
            Stow_flag=1;
            MODE=STOW;
          }

        }
        else
        {
          Redo_Wind_calc();
        }

      }

    }

    void Redo_Wind_calc()
    {
      //  Serial.println("Wind_Exceed_count");Serial.print(Wind_Exceed_count);
      if(Wind_Speed>4.0 &&Stow_flag==1)
      {
        Wind_Exceed_count=Wind_Exceed_count+1;
        if(Wind_Exceed_count<=10)
        {
          MODE=STOW;
        }
        else
        {
          MODE=TRACK;
          Wind_Exceed_count=0;
          Stow_flag=0;
        }

      }
    }

    void loop()
    {
     Wind_calc();
    webcontrol();
    }

    void webcontrol()
    {

    //Web control function are defined here

    }

title: Analog average sample wind speed sensor

Answers: 1

body:
What arduino board is being used? I find that some webserver code takes up a lot of the SRAM and in an UNO this leaves very little space for other code.

To save SRAM use the F macro on all the Serial.print statements that have quoted text. i.e:

    Serial.print("Some text you want output");
This takes up SRAM when running. 1 byte per letter and space.

    Serial.print(F("Some text you want output"));
This takes up no SRAM as it is stored in program space and is makes a big difference.

Search for a `freeRam()` and use that in debugging your sketch to see how much free space you have.

Relevant question: [What can I do if I run out of Flash memory or SRAM?][1]

  [1]: https://arduino.stackexchange.com/questions/221/what-can-i-do-if-i-run-out-of-flash-memory-or-sram


body: I have a complex requirement that uses a number of libraries that depend on timing I.e. OneWire. When using the official GSM shield on a mega, it loads a version of software serial to talk to the GSM. I want to make it use a spare hardware serial port on the MEGA for more timing stability. How should I modify the GSM library to (optionally) auto detect a MEGA and then use a nominated serial port. I am happy to jumper the correct pins from the mega serial hardware port to the bent outwards pins 2 and 3 of the GSM shield ( pin 2 is already bent out if you use a MEGA anyway).

title: Can the official arduino GSM shield library be changed to work with hardware serial on mega

Answers: 1

body:
Before we start, note that it might not be the right pinout for the GSM shield to use a hardware serial port on the Mega. Beware of some nasty wiring.

Poking around on Github, I found [this is the directory for the GSM library](https://github.com/arduino/Arduino/tree/db8cbf24c99dc930b9ccff1a43d018c81f178535/libraries/GSM). Ladies and gentlemen, it's time to <strike>break something important</strike> get our hands dirty! Draw your  chairs close for a tale of touching code you shouldn't touch!

Click on the `src` folder to open it up. When I first opened this up, I was somewhat scared by the number of files. However, I had a plan:

 1. Find the name of the SoftwareSerial instance. I'm guessing that they would use only one object to do this to prevent redundancy. In addition, I'm going to guess that most serial data is handles though a single file, but I'll have to confirm this.
 2. Remove instances of the SoftwareSerial Object.
 3. Clean up any remaining issues with the "port"

After more poking around, I noticed that the library actually uses [a unique version of the SoftwareSerial library](https://github.com/arduino/Arduino/blob/db8cbf24c99dc930b9ccff1a43d018c81f178535/libraries/GSM/src/GSM3SoftSerial.h), so it will be even *harder* to do this. Yay us! On the upside, we know exactly what code to replace. Fasten your seatbelts, this is about to get pretty nasty.

Okay, take a step back here and figure out *what* we want to modify. First of all, it's a *terrible* idea to modify the libraries directly in the directory that the Arduino IDE uses.

So, if you were to make a copy from the `src` folder for the GSM library into the Arduino "libraries" folder, it wouldn't be enough. The Arduino IDE would get confused when there would be two identical header files to use. You will need to rename the *main header file* and use just that one instead to include into your projects. In addition, most of the files in the library probably reference that file, so make sure to rename any references within the library to that one file. A quick CTRL + SHIFT + F on the Atom text editor will search the entire project I'm working on. I'm not entirely sure if a folder name would mess up the Arduino IDE, but it'd be a good idea to rename the folder to whatever your library is called, at least for readability purposes.

Before we continue, let's make sure that the library still compiles without us playing with the code. Import the new library into a basic GSM example sketch and see if it compiles and works normally.

It compiles? Great. Let's go on!

The file that does serial is the `GSM3SoftSerial.cpp` file. Without actually porting it, I can't give you a ton of advice here. Look through and see when variables are created, used, and modified. If you're not sure, [I'm in chat sometimes: feel free to ask there on minor questions and ping me with @AnnonomusPenguin][1] or leave a comment on this post.

I'd also advise to leave everything in there that you're not sure of, make sure it works with hardware serial, and line by line start removing that variable and see if anything breaks. A great too for this would be to use a tool like Git/Github (or other version control software) to help you revert changes that broke something or to see, overall, what you've changed.

So, after replacing the code inside the functions (finalWrite, the ISRs, and the begin/clear seem like the ones you should touch), compile the code and see if it works!

  [1]: http://chat.stackexchange.com/rooms/8489/pin-13


body:
I have set up Eclipse to compile for the Arduino Due using all the tools shipped with the Arduino IDE 1.5.6-r2. It compiles without errors, but when uploaded, the Arduino does nothing, and isn't recognized on the computer. It then has to be reset manually using the erase and reset buttons.

There is one static library (ArduinoDueCore) consisting of the Arduino library (`core`), and other code (Atmel found in `lib`). The other Eclipse project is the TestProject. It contains one file blinking an LED on pin 13. All the files from the Arduino library are there.

This is the output from Eclipse compiling the library itself: (excerpt of only one of each type of command)

    18:31:36 **** Build of configuration Release for project ArduinoDueCore ****
    make all
    Building file: ../src/lib/variants/arduino_due_x/variant.cpp
    Invoking: ARM Sourcery Linux GCC C++ Compiler
    arm-none-eabi-g++ -DUSB_PRODUCT="Arduino Due" -DARDUINO=156 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/lib/variants/arduino_due_x/variant.o.lst" -fno-exceptions -fno-rtti -w -c -g -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -MMD -MP -MF"src/lib/variants/arduino_due_x/variant.d" -MT"src/lib/variants/arduino_due_x/variant.d" -mcpu=cortex-m3 -mthumb -o "src/lib/variants/arduino_due_x/variant.o" "../src/lib/variants/arduino_due_x/variant.cpp"
    Finished building: ../src/lib/variants/arduino_due_x/variant.cpp

    Building file: ../src/lib/libsam/source/adc.c
    Invoking: ARM Sourcery Linux GCC C Compiler
    arm-none-eabi-gcc -DARDUINO=156 -DARM_MATH_CM3 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PRODUCT="Arduino Due" -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/lib/libsam/source/adc.o.lst" -w -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -std=c99 -MMD -MP -MF"src/lib/libsam/source/adc.d" -MT"src/lib/libsam/source/adc.d" -mcpu=cortex-m3 -mthumb -o "src/lib/libsam/source/adc.o" "../src/lib/libsam/source/adc.c"
    Finished building: ../src/lib/libsam/source/adc.c

    Building file: ../src/core/USB/HID.cpp
    Invoking: ARM Sourcery Linux GCC C++ Compiler
    arm-none-eabi-g++ -DUSB_PRODUCT="Arduino Due" -DARDUINO=156 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/core/USB/HID.o.lst" -fno-exceptions -fno-rtti -w -c -g -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -MMD -MP -MF"src/core/USB/HID.d" -MT"src/core/USB/HID.d" -mcpu=cortex-m3 -mthumb -o "src/core/USB/HID.o" "../src/core/USB/HID.cpp"
    Finished building: ../src/core/USB/HID.cpp

    Building file: ../src/core/cortex_handlers.c
    Invoking: ARM Sourcery Linux GCC C Compiler
    arm-none-eabi-gcc -DARDUINO=156 -DARM_MATH_CM3 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PRODUCT="Arduino Due" -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/core/cortex_handlers.o.lst" -w -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -std=c99 -MMD -MP -MF"src/core/cortex_handlers.d" -MT"src/core/cortex_handlers.d" -mcpu=cortex-m3 -mthumb -o "src/core/cortex_handlers.o" "../src/core/cortex_handlers.c"
    Finished building: ../src/core/cortex_handlers.c

    18:31:39 Build Finished (took 2s.811ms)

Here is the project itself:

    18:33:42 **** Build of configuration Release for project TestProject ****
    make all
    Building file: ../src/TestProject.cpp
    Invoking: ARM Sourcery Linux GCC C++ Compiler
    arm-none-eabi-g++ -DARDUINO=156 -DUSB_PRODUCT="Arduino Due" -DARDUINO_SAM_DUE -D__SAM3X8E__ -DARDUINO_ARCH_SAM -Dprintf=iprintf -DF_CPU=84000000L -DUSB_MANUFACTURER="Unknown" -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/TestProject/src" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -Os -ffunction-sections -fdata-sections -Wall -fno-exceptions -fno-rtti -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -g -w -MMD -MP -MF"src/TestProject.d" -MT"src/TestProject.d" -mcpu=cortex-m3 -mthumb -o "src/TestProject.o" "../src/TestProject.cpp"
    Finished building: ../src/TestProject.cpp

    Building target: TestProject.elf
    Invoking: ARM Sourcery Linux GCC C++ Linker
    arm-none-eabi-g++ -T"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x/linker_scripts/gcc/flash.ld" -L"/home/kim/workspace_juno/ArduinoDueCore/Release" -Wl,-Map,TestProject.map -lm -lgcc  -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--gc-sections -mcpu=cortex-m3 -mthumb -o "TestProject.elf" -Wl,--start-group  ./src/TestProject.o   -lArduinoDueCore -Wl,--end-group
    Finished building target: TestProject.elf

    make --no-print-directory post-build
    /home/kim/arduino-1.5.6-r2/hardware/tools/g++_arm_none_eabi/bin/arm-none-eabi-objcopy -O binary TestProject.elf TestProject.bin

    Invoking: ARM Sourcery Linux GNU Create Listing
    arm-none-eabi-objdump -h -S TestProject.elf > "TestProject.lst"
    Finished building: TestProject.lst

    Invoking: ARM Sourcery Linux GNU Print Size
    arm-none-eabi-size  --format=berkeley TestProject.elf
       text    data     bss     dec     hex filename
      10396      24    1188   11608    2d58 TestProject.elf
    Finished building: TestProject.siz

    18:33:43 Build Finished (took 308ms)

Here is the upload command: (removed `readWord`, `go`, `write` and `writeWord` lines)

    -i -d --port=ttyACM0 -U true -e -w -v -b ${project_loc}/Release/${project_name}.bin -R

    Set binary mode
    chipId=0x285e0a60
    Connected at 921600 baud
    Erase flash
    Write 10420 bytes to flash

    [                              ] 0% (0/41 pages)
    [=======                       ] 24% (10/41 pages)
    [==============                ] 48% (20/41 pages)
    [=====================         ] 73% (30/41 pages)
    [============================= ] 97% (40/41 pages)
    [==============================] 100% (41/41 pages)
    Verify 10420 bytes of flash

    [                              ] 0% (0/41 pages)
    [=======                       ] 24% (10/41 pages)
    [==============                ] 48% (20/41 pages)
    [=====================         ] 73% (30/41 pages)
    [============================= ] 97% (40/41 pages)
    [==============================] 100% (41/41 pages)
    Verify successful
    Set boot flash true
    Device       : ATSAM3X8
    Chip ID      : 285e0a60
    version()=v1.1 Dec 15 2010 19:25:04
    Version      : v1.1 Dec 15 2010 19:25:04
    Address      : 524288
    Pages        : 2048
    Page Size    : 256 bytes
    Total Size   : 512KB
    Planes       : 2
    Lock Regions : 32
    Locked       : none
    Security     : false
    Boot Flash   : true
    CPU reset.

TestProject.cpp:

    #include "Arduino.h"

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

    void loop() {
        digitalWrite(13, HIGH);
        delay(50);
        digitalWrite(13, LOW);
        delay(950);
    }

title: How to compile code for the Arduino Due?

Answers: 1

body:
Using 1.5.6-r2 with Eclipse cause the Due to hung in Default_Handler function after entering main and polling a few times for the next SysTick gettin passed.

Some weak symbol declarations are done twice (i.e. the SysTick_Handler function definitions). They appear to overwrite each others weak alias depending on the link time usage of the objects. All declarations (not only the failing SysTick_Hanlder) from cortex_handler.c are getting overwritten by weak symbol redeclaration inside startup_sam3xa.c.

This commit seems to already address a weak symbol definition problem.
https://github.com/arduino/Arduino/commit/65f00a69c74ca0def8d7f1d7597327945a04a33f

For now, to fix it. Just comment out the part in startup_sam3xa.c with the weak symbol declaration regarding the vectors. Lines 53 to 129.

It should also work to just remove the file completely.
The startup handler code and vector map should be provided by gcc arm built-in libraries instead.


body: I want to add CO2 measuring feature to my room weather station. Can someone please recommend a CO2 sensor easy to integrate with Arduino?

title: CO2 sensor for arduino

Answers: 5

body:
You could try the [K30 CO2 sensor][1]. There is also a guide using it to make an arduino CO2 detector [here][2].

I've also seen people use the MG-811 module, you can buy them from dfrobot.com . There is also good documentation for how to use the MG-811 with arduino [here][3].

  [1]: http://www.co2meter.com/products/k-30-co2-sensor-module
  [2]: http://www.openhomeautomation.net/wireless-co2-sensor-arduino/
  [3]: http://www.spencerpages.com/wiki/index.php?title=MG811_Carbon_Dioxide_(CO2)_Sensor

body:
How about this one? http://cgi.ebay.de/ws/eBayISAPI.dll?ViewItem&item=380915024016&ssPageName=STRK:MESE:IT
The MG-811 is highly sensitive to CO2 and less sensitive to alcohol and CO.

body:
This one:
http://sandboxelectronics.com/?product=mg-811-co2-gas-sensor-module

They also got a nice demo code there.
Here is a wiring scheme if you use the demo without modification:

1. Red - 5V
2. Black - GND
3. Yellow - Analog input 0
4. Green - Digital I/O 2

The easeir integration ever

body:
Based on hands-on time with CCS811 CO2 sensors, I would recommend against them. They tend to drift high, sometimes way high, and then come back to their senses and provide reasonable readings when reset.

I've tried two batches of CJMCU-811 sensors, purchased months apart (hoping to get a different manufacturing lot), and they were all rubbish.

body:
This worked well for me on a colour screen. A small delay for the sensor and a long burn (24hrs) required. But easy KIWI

    #include <XTronical_ST7735.h> // Hardware-specific library
    #include <SPI.h>
    #include <Adafruit_GFX.h>    // Core graphics library
    #include <sSense-CCS811.h>
    #include <dht.h>

    #define SERIAL_SPEED  9600

    #define TFT_SCLK 13         // SPI clock
    #define TFT_MOSI 11         // SPI Data
    #define TFT_CS   10         // Display enable (Chip select), if not enabled will not talk on SPI bus
    #define TFT_RST   9         // Display reset pin, you can also connect this to the Arduino reset
                                // in which case, set this #define pin to -1!
    #define TFT_DC     8
    CCS811 ssenseCCS811;
    Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS,  TFT_DC, TFT_RST);
    dht DHT;

    #define DHT11_PIN 7

    void setup()
    {
      DebugPort.begin(SERIAL_SPEED);
      delay(5000);
      Serial.println("s-Sense CCS811 I2C sensor.");
      if(!ssenseCCS811.begin(uint8_t(I2C_CCS811_ADDRESS), uint8_t(CCS811_WAKE_PIN), driveMode_1sec))
        DebugPort.println("Initialization failed.");
      tft.init();   // initialize a ST7735S chip,
      tft.setRotation(0);
      tft.fillScreen(ST7735_GREEN);
      tft.setTextColor(ST7735_RED);
      tft.setCursor(0, 30);
      tft.setTextSize(1);
    }

    void loop()
    {
      ssenseCCS811.setEnvironmentalData((float)(21.102), (float)(57.73));  // replace with temperature and humidity values from HDC2010 sensor
      int chk = DHT.read11(DHT11_PIN);
      if (ssenseCCS811.checkDataAndUpdate())
      {

        tft.fillScreen(ST7735_GREEN);
        tft.setCursor(10,10);
        tft.print("CO2 ppm  ");
        tft.print(ssenseCCS811.getCO2());
        tft.setCursor(10,40);
        tft.print("tVOC ppb ");
        tft.print(ssenseCCS811.gettVOC());
        tft.setCursor(10,70);
        tft.print("Temp C   ");
        tft.print(DHT.temperature);
        tft.setCursor(10,100);
        tft.print("Humid %  ");
        tft.print(DHT.humidity);

      }
      else if (ssenseCCS811.checkForError())
      {
        ssenseCCS811.printError();
      }

      delay(2000);
    }


body:
I am building an early prototype, proof of concept, network monitoring tool.  A big part of it uses localization of a Smartphone.  It seems that the best way to do this is using RSSI from multiple points.  I plan to do this using several Arduino Fios with Xbee WiFi (S6B) cards.

My current setup has a network running from my smartphone (it is running DHCP) with a laptop monitoring all the traffic on the network.

What I need is for my Fio Xbees to dump the RSSI of the "access point" (Smartphone) onto the network so my laptop can pull the data.

Thus, to/from is not important as far as the packet is concerned, I just need the data dropped on the "wire" for my laptop to later parse, which is good because Serial.print* sends out a broadcast to 255.255.255.255:fffff.

I can make my devices broadcast any integer, but when I go into AT mode nothing aside from the initial DHCP handshake gets put on the wire.  Any ideas?

<!-- language: c -->

    void setup() {
      Serial.begin(9600);
      Serial.flush();
      delay(1000);//enter AT mode start
      Serial.print("+");//AT
      Serial.print("+");//AT
      Serial.print("+");//AT
      Serial.flush();
      delay(1000);//enter AT mode finish
      while(Serial.available()>0){
        Serial.write(Serial.read());
      }

    }

    void loop(){
      Serial.println("ATDB");

      while(Serial.available()>0){
        Serial.write(Serial.read());
      }
      delay(750);//3/4 a sec
    }

Note, `Serial.println("ATDB");` should cause the xbee to drop the RSSI on the wire; see
[XBee_WiFi_AT_Commands.pdf](http://examples.digi.com/wp-content/uploads/2012/06/XBee_WiFi_AT_Commands.pdf)
at digi.com.

The three "+"s at the start are how you move the device into AT mode; see
[Digi_International_90002124_G.pdf](http://www.mouser.com/pdfdocs/Digi_International_90002124_G.pdf) at mouser.com.

Once again what I am trying to do is get the collected RSSI information dropped onto a wifi connection from multiple xbee WiFi S6B equipped Fios.

title: XBEE WiFi S6B RSSI for Smartphone localization

Answers: 1

body:
Just incase anybody stumbles onto this page googling, I am posting my solution below (I *think* it will work for any xbee radio)

Basically for some reason the RSSI values are getting nulled out before I can read them, both in my API mode tests and AT commands.  I'm not convinced that there is not some way around this in API mode at least, but it is irrelevant for my current purpose.

What I did was wire pin 6 on the xbee to a digital pin on the Arduino (I used 7) then use a pulse detector to find the period of the wireless signal coming in.

    int pin = 7;
    unsigned long period;

    void setup(){
      Serial.begin(9600);
      pinMode(pin, INPUT);
      Serial.println("Getting started");
    }

    void loop(){
      delay(100);
      period = pulseIn(pin, HIGH);
      Serial.println(period);

    }

It is not perfect, but for now it works, might help someone else in the future.


body:
So I've tried this a few times and I always get the same issue. When I try to run the sweep example the servo goes round 180 degrees but only in steps. Anyone know a way to fix this?

The servo I'm using is a **Tower Pro Micro Servo 9G SG90**

    // Sweep
    // by BARRAGAN <http://barraganstudio.com>
    // This example code is in the public domain.

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
                    // a maximum of eight servo objects can be created

    int pos = 0;    // variable to store the servo position

    void setup()
    {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop()
    {
      for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
      {                                  // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
    }

Video: http://vidd.me/A40

title: My Servo Won't Sweep Smoothly

Answers: 6

body:
It looks like your sketch runs in slow motion.

Check if you wrote delay(150) or have an additional delay in your loop.
Check twice and - just to make sure - upload the corrected sketch again.

**Edit:**
If possible, test with another servo and even test with another Arduino board.

body:
In electronics, as usual in situations where a cricuit is misbehaving and we don't understand why, a solution that generally works is to add a **decoupling cap** between `+5V` and `GND`.

In your case, I would put at least **220uF**; that would ensure two things:

- the voltage used to control the servo never drops
- the voltage brought to Arduino by the USB does not drop either (which would have very bad impact on the Arduino, probably resetting it)

Electrolytic caps are a **must-have** for every electronics hobbyist (and professional as well, of course).

You can read more about decoupling capacitors on [Wikipedia][1].

**Edit:**

According to @gwideman comment, it seems that using a decoupling capacitance **above 10uF** in a USB 2.0 device would violate USB specs and ***may damage*** the USB host controller on the computer.

I was not aware of this limitation but I have already used decoupling capacitance up to 100uF in my circuits and never got any issue with my USB computer port.

It might be due to extra electronics on the Arduino board that would "isolate" USB power from Arduino +5V anf d GND pins, I don't know (**that should probably be the topic of a specific question**); or maybe I have just been lucky all this time...

  [1]: http://en.wikipedia.org/wiki/Decoupling_capacitor

body:
I've experienced same behavior with this type of servos. In my case it was easier to spot since Arduino frequently rebooted when servo was approaching the boundaries of the swing - so it was clear it was consuming too much power, and USB port was unable to deliver that.

Cheap dedicated 9V 1A AC/DC converter usually solves the problem. But if you can't wait for one to get delivered, get an iPad USB charger (nowadays everyone has it or has a neighbor/friend who has one). It is rated 10W, and it doesn't suffer from voltage drops even under high loads. Power your setup from it, and if you'd see it moves smoothly, you will have your answer.

body: The program is faulty. 1) No servo can react to a command in 15 milliseconds. Delay should be more like 500 milliseconds (.5 seconds). 2) The for loops are not designed to work together. The 1st loop feeds a value of 181to the second loop which is designed to start with a value of 180. The 2nd loop feeds a value of -1 back to the first loop, which is designed to start with a value of 0.

body:
give a 9v supply +ve terminal to Vin and -ve ground.
since the arduino board cannot supply enough power to the servo, this will provide
this worked for me and workin just fine

body:
I tested your code, nothing wrong with it.
Maybe it is power supply issue.
1. Don't use USB to power servo, it can make current spike when it move rapidly.
2. Use proper supply for servo. High current and use large capacitor to deal with current spike.


body:
Is it possible to connect these two shields to my Arduino Uno? After a research on the internet, I discovered that they use some of the same pins. Even so, is it still possible for me to connect the LcdKeypad and the ArduinoWifi on my Arduino Uno? (the LCD would be on top)

Here are the pic of the shields, and some information:

[LDC KEYPAD][1]

[Arduino WIFI][2]

WiFi shield info:

> The Arduino communicates with the processor WiFi shield with the microSD card by SPI
> (Eurotherm the ICSP bus) that is on pins 11, 12
> and 13 at Uno. The pin 10 is used to select the HDG104 and pin 4 to
> the microSD card(i dont need the pin 4 cause i wont use SD). These pins can not be used
> for input and output. The
> digital pin 7 is used for initialization of the communication protocol
> between the shield and Arduino WiFi and should not be used.

LCD info:

> This shield we will have to use the following sequence to initialize
> the library LiquidCrystal:
> LiquidCrystal lcd (8,9,4,5,6,7);

As you guys have noticed, there is the pin 7 on both shields that I need to use. How would it work? Can I do this? If i can't, is there any solution that I can expand my pins that would not result buying a Mega?

I still have to connect two INFRA-RED sensors and a motor (using pins 0, 1, and 2). I don't know if i can connect on the pins TX and RX (they seem to work).

  [1]: http://www.robotshop.com/media/catalog/product/cache/1/image/325x325/9df78eab33525d08d6e5fb8d27136e95/a/d/adafruit-rgb-lcd-keypad-shield-kit-arduino-i2c.jpg
  [2]: http://ktjjnx9q5vgx99fk.zippykid.netdna-cdn.com/wp-content/uploads/2013/06/arduino-wifi-shield.jpeg

title: ArduinoUno+LcdKeypad+ArduinoWifi=Pins Problems

Answers: 1

body:
**So here are your needs:**

 - WiFi, which uses pins 4, 10, 11, 12, 13. I know you said that you don't need pin 4 since no SD, but because that pin switches on/off the SD card, if you use it at all. Note: As Connor Wolf points out, it's not really relevant when there's no SD card. If you're facing problems with the Ethernet shield using the LCD additionally, you might have to reroute pin 4.
 - LCD, which uses pins 4, 5, 6, 7, 8, 9. The standard Arduino LCD library can use any pins, but your shield is hard wired to use those. As mentioned before, you can reroute them if you want to. Below is the method for rerouting pins.

****
## Rerouting pin 7 (you need to do this!):

 - Bend pin 7 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
 - Use `LiquidCrystal lcd(8,9,3,5,6,2);` if you're rerouting pin 4, or `LiquidCrystal lcd (8,9,4,5,6,2);` in your code if you're not rerouting
 - Attach a jumper between the pin 7 on the header of the WiFi shield and the pin 7 on the Arduino Uno
 - Attach a jumper between the pin 2 of the WiFi shield (or the Uno, if that's easier) and the pin 7 of the LCD using the free space of the pin bent above it.

This will isolate pin 7 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 2 on your Arduino to pin 7 on the LCD shield.
****
## Rerouting pin 4 (optional):

 - Bend pin 4 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
 - Use `LiquidCrystal lcd(8,9,3,5,6,2);` in your code
 - Attach a jumper between the pin 4 on the header of the WiFi shield and the pin 4 on the Arduino Uno
 - Attach a jumper between the pin 3 of the WiFi shield (or the Uno, if that's easier) and the pin 4 of the LCD using the free space of the pin bent above it.

This will isolate pin 4 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 3 on your Arduino to pin 4 on the LCD shield.
****
For number of pins, you should be fine. You can use pins 0 and 1 (TX/RX) **as long as you aren't connecting to the computer or any other UART device**  (i.e. using the `Serial()` library). Don't forget you can use the analog pins as digital pins by referencing them as `A0` to `A5`.