body:
Hi i'm trying to parse JSON resposne from webserver in my arduino in order to turn on and off a LED light. I'm using the wifi client repeating example to make a get request to my server:

http://arduino.cc/en/Tutorial/WiFiWebClientRepeating

Here is what I get printed back from the serial port

    connecting...
    HTTP/1.1 200 OK
    Date: Sun, 06 Apr 2014 01:14:37 GMT
    Server: Apache
    X-Powered-By: PHP/5.5.10
    Cache-Control: no-cache
    X-Frame-Options: SAMEORIGIN
    Set-Cookie: expires=Sun, 06-Apr-2014 03:14:37 GMT; Max-Age=7200; path=/; httponly
    Connection: close
    Transfer-Encoding: chunked
    Content-Type: application/json

    19
    {"lightstatus":"on"}
    0

How do i parse the JSON portion of this response only so that I can use it to control my LED?

Thanks

title: Parse JSON with arduino to turn on LED

Answers: 4

body:
I'm aware of a few JSON parsing libraries for Arduino.

* [aJSON][1]
* [Arduino JSON Parser][2]
* [JSON Arduino][3]

I've never used any of these but I did do some simple JSON parsing in a project I'm working on so I'll show you how I did that.

NOTE: I'm reading serial data using the software serial library. You'll need to change this code to work for you. This will only work on very simple JSON strings. It's *very* limited but if that's all you're parsing then it'll work.

Example of JSON response from server:

    {"id":"TEST1","lat":"38.56050207","lng":"-121.42158374","total":"3","available":"2"}

First, only read data between curly braces.

    String response = "";
    bool begin = false;
    while (SIM900.available() || !begin) {

        char in = SIM900.read();

        if (in == '{') {
            begin = true;
        }

        if (begin) response += (in);

        if (in == '}') {
            break;
        }

        delay(1);
    }

This code reads data one byte at a time and once it gets an open brace, it starts saving it into `response`. When it gets a closing brace, it ends it. So here's a clear limitation, you can only have one set of opening/closing braces in your string.

Once I have the string, I use `indexOf` and `substring` to extract relevant information:

    start = response.indexOf("id\":\"") + 5;
    end = start + 5;
    nodeId = response.substring(start, end);

This code sets `start` to the beginning of `id":"` + 5 characters in the string. It's +5 because that's how long `id":"` is. So `start` points to `TEST1` in the JSON string. In my system, the ID is always going to be 5 characters long so end is `start + 5`. I then use `substring` to extract that.

Again, before anyone starts down voting me for this horrible solution: if you know exactly what you're working with, and understand the limitations of this code, then this is not a bad solution. It's a solution that gets the job done.

  [1]: https://github.com/interactive-matter/aJson
  [2]: https://github.com/bblanchon/ArduinoJsonParser
  [3]: https://github.com/not404/json-arduino

body:
I have programmed a class that will receive char by char the JSON document. It only will store in memory a few bytes for known JSON structure using a state machine and the results you need. So you can query the class for the results you want and will process the JSON.

Its ideal for your purpose. I have used for connecting to a weather service that returns a json:

    static const char* queries[] = { "list.0.deg", "list.0.weather.0.main"};
    StreamJsonReader jsonreader(queries, 2); // 2 queries
    while(char c  =  read()){
          jsonreader.process_char(c);
    }

    cout << jsonreader.results[0] << endl;
    cout << jsonreader.results[1] << endl;

Check this blog post I just wrote: http://web.biicode.com/blog/big-json-on-arduino.

Source code is [here][1] in Biicode.

  [1]: https://www.biicode.com/lasote/blocks/lasote/stream_json_reader/branches/master

body:
I wrote a parser for the PIC that has very low ram use because it works directly with char pointers and does not build a tree structure. If you ask to get item N of a list, it gives you an actual pointer into the direct JSON file right at the start of item N of the list. Then you can ask what type of object the pointer represents, etc. It's buggy and doesn't support floats and I think has a few other limitations(twas a long time ago) but it's all on github:https://github.com/EternityForest/OpenFortune-fortune-like-text-generator
You'll need to look in libfortune which is part of the C version.

body:
I wrote a simple JSON-RPC library (on top of aJson) with example of how to turn a led on with JSON-RPC procedure call:

 - Code: https://github.com/cloud-rocket/arduino-json-rpc
 - Documentation: http://www.cloud-rocket.com/2014/03/serial-json-rpc-server-arduino/


body:
[This article][1] describes a method to extend the battery life: use a low-power controller to switch on the Arduino only when needed. The author states that this method uses considerably less power than using Arduino's sleep mode.

Are there downsides to this approach? Which variant should I build?(The [TPS61240 variant][2] seems to use something from Circuits@Home that's not available anymore.) **I'd appreciate schematics or links to detailed instructions.**

Background: I'm building a sensor device that's in an environment with no mains power supply. The sensor should wake up eg. hourly, read eg. a temperature sensor, possibly send an SMS and then go back to sleep.

  [1]: http://alanbmitchell.wordpress.com/2011/10/09/design-of-the-extended-battery-life-power-controller-for-the-arduino/
  [2]: http://alanbmitchell.wordpress.com/2011/11/07/arduino-power-controller-with-texas-instruments’-tps61240/

title: Extend battery life with a power-controlling microcontroller?

Answers: 1

body:
Switching off power to the board only makes sense if you're using a full Arduino. Once you strip the Arduino down to the bare MCU and decoupling capacitors (or start with a basic breakout board instead), disabling unused peripherals and sleeping the CPU has much more of an effect since you no longer need to supply power to an external monitor chip.

Naturally this may involve creating your own board for the MCU. Fortunately Atmel has the basics of that covered.


body:
How would I measure resistance over a certain length? In this case the resistance is variable.

What I have in my head is that you would output a certain amount of current from one pin, and measure how much comes back from the other.

I'm not sure if this would work, or how to implement it in code.

I've seen [this forum post](http://forum.arduino.cc/index.php/topic,21614.0.html), but it's not making much sense to me.

How can I measure resistance?

title: Measuring resistance conceptually and in code?

Answers: 1

body:
you cant control current output to a pin BUT you know a pin output 5V (if using a 5V a arduino, 3.3v in other case).

Then what you need is a know resistence resitor, so you can set up a [voltage divider][1] and then read the resulting voltage with an analogRead. That give you a 10bit precision value that you can easily translate to a voltage, and then use the formula on the linked page to find R1 or R2 (depends on how you wired up your know resistor)

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


body:
My high school is entering an ROV competition and for next year's competition we want to try and set it up so that we can control it using a PS4 controller. I have done research and found [this][1] shield for Arduino and [this][2] library that allows you to connect it to an Arduino. I plan to then connect the Arduino to a computer via USB and then send each button press to a Processing program via serial. Would it then be possible to send this from Processing to another Arduino out of the laptop? I'm just wondering how feasible this project is.

We initially had just a single Arduino at the top with the Ethernet shield and took inputs from standard joystick potentiometers. We want to add in using the PS4 controller this year for easier control. We found the USB Host Shield that gives us that capability, but uses the same pins as the Ethernet shield. So we added another Arduino, connecting the laptop as the bridge also allows to have a GUI. The Ethernet is wired, by the way. We need the laptop, it's not just for a bridge.

  [1]: http://www.circuitsathome.com/products-page/arduino-shields/usb-host-shield-2-0-for-arduino-assembled
  [2]: https://github.com/felis/USB_Host_Shield_2.0

title: How do I connect a PS4 controller connected to an Arduino that's connected to a laptop to another Arduino?

Answers: 2

body:
this is possible, but the processig bridge can add a lot of delay if not correctly handled, also wifi has a low range, almost 100m by default hardware.

zigbee module has better range (xbee pro are up to 1km) and are microcontroller friendly, you use the as you are using a serial, they will hide their complexity once you set them up, and this can be done by PC.

That mens less code, that mena less error and more ram/flash/cpu so you can do a smarter robot :)

 zigbee use the serial protocol to communicate, exactly as you do with the pc. Also arduino can use, with the library SoftSerial, any pin as Serial. So you can keep the HardwareSerial to communicate with pc, and any 2 free pin to communicate with the xbee. So you can use the arduino stand alone, only with the controller, and when needed connect the pc. Then arduino can act as a bridge between xbee and pc, so pc can excange data with the rover. But even without pc your project will be fun.
The same apply for bluetoot or 400/800mhz rxtx module, but not for wifi shield

body:
**This project is very simple.** As I understand it, this is your setup:

    +–––––––––––––––––––––––––––––––––––––––––+
    |                                         |
    |  Arduino 1-––––––––––-PS4 Controller    |
    |  |                 (W. Shield attached) |
    |  |USB                                   |
    |  |                                      |
    |  Computer                               |
    |  |                                      |
    |  |[Wireless]                            |
    |  |                                      |
    |  Arduino 2                              |
    |                                         |
    +–––––––––––––––––––––––––––––––––––––––––+
*[Made with ASCIIFlow](http://asciiflow.com)*

If you have a very small range (I'd say 10-20 feet max), I recommend using Bluetooth. The [HC 06 Bluetooth module looks like a good choice](http://www.amazon.com/Arduino-Wireless-Bluetooth-Transceiver-Module/dp/B0093XAV4U/ref=sr_1_1?ie=UTF8&qid=1396918346&sr=8-1&keywords=hc+06+bluetooth+arduino). There's also a less powerful HC05 if I remember correctly. I had one once but accidentally destroyed it before I could connect with a bad soldering job :). The one linked on Amazon luckily comes with a "backplane" already soldered so you just need to attach 5V, GND, and the TX/RX pins to the Arduino, accordingly. Then, you can select the BT module (wherever it appears on your OS; search online for this) and then you can connect to it and add the password 1234. After that, it should function like a normal COM port.

You would connect this to the HC06 to Arduino 2, and wirelessly the HC06 to the computer. The computer would then be connected to Arduino 1, who would receive the PS4 signals, with the shield. You would use Processing to receive the PS4 signals and to send data to the second Arduino board. I'm not an expert on Processing, but I found [this serial library](https://www.processing.org/reference/libraries/serial/Serial.html).

I ***do not*** recommend using Xbee because one Arduino needs to talk to the computer and the other at the same time. That's not practical with the way it's set up on most boards. The OP would need another UART connection, even so the Xbee and the USB to UART chip use the same pins on all standard boards.


body:
I have a LED attached to my Arduino wifi shield that I want to control from my PHP web server.  In terms of communication, should I

1. Make my Arduino a web server and then communicate with PHP web server via HTTP

2. Make my Arduino a web client and receive commands from my PHP web service.  I would parse the JSON response

Also my other question is should I communicate with JSON between my PHP web server or is there a better way to send commands to my LED light?

title: Controlling LED from web server

Answers: 2

body: There's no need for either PHP or JSON. Simply detect when one of two URLs (say, `/led/on` and `/led/off`) has been accessed on the Arduino's web server, change the LED state, and return a 204 response.

body:
The REST protocol is ideal for this and there's a nice Sketch already written, called RESTduino on Github:
[https://github.com/jjg/RESTduino][1]

Basically (and loosely) REST treats a URL as a command.  Quoting from the RESTduino doc's:

"To turn on the LED attached to pin #9 (currently case sensitive!):

    http://192.168.1.177/9/HIGH

This will set the pin to the HIGH state and the LED should light. Next try this:

     http://192.168.1.177/100

This will use PWM to illuminate the LED at around 50% brightness (valid PWM values are 0-255)."

  [1]: https://github.com/jjg/RESTduino


body:
Working on a arduino code, but its C code. Having the problem that I want a variable with int to increase in a loop to run with the url:

    student.cs.hioa.no/~s180343/updatedb.php?verdi=%d

The updatedb.php files takes the parameter and saves it to the database.

    #include <Process.h>
    char buffer[50];
    int val=1200;

    void setup() {
      // Initialize Bridge
      Bridge.begin();

      // Initialize Serial
      Serial.begin(9600);

      // Wait until a Serial Monitor is connected.
      while (!Serial);

      // run various example processes
      //runCurl(val);
      //runCpuInfo();
    }

    void loop() {
      Serial.println("Starting");
      sprintf (buffer, "student.cs.hioa.no/~s180343/updatedb.php?verdi=%d", val);
       val++;
       Serial.println(buffer);
       runCurl();
       delay(5000);
      // Do nothing here.
    }

    void runCurl() {

      // curl is command line program for transferring data using different internet protocols
      Process p;  // Create a process and call it "p"
      p.begin("curl"); // Process that launch the "curl" command
      p.addParameter(buffer); // Add the URL parameter to "curl"

      p.run();  // Run the process and wait for its termination

      // A process output can be read with the stream methods
      while (p.available()>0) {
        char c = p.read();
        Serial.print(c);
      }
      // Ensure the last bit of data is sent.
      Serial.flush();
    }

title: Sending variable in url

Answers: 0


body:
Working on a arduino script where I am right now entering manually the value with the URL, but wondering how to do it with a int in a loop.

This is the url and how it works now:

    student.cs.hioa.no/~s180343/updatedb.php?verdi=25

Code:

    #include <Process.h>

    void setup() {
      // Initialize Bridge
      Bridge.begin();

      // Initialize Serial
      Serial.begin(9600);

      // Wait until a Serial Monitor is connected.
      while (!Serial);
      Serial.println("Ready");

      // run various example processes

    }

    void loop() {
       runCurl();
       delay(10000);
    }

    void runCurl() {
      // Launch "curl" command and get Arduino ascii art logo from the network
      // curl is command line program for transferring data using different internet protocols
      Process p;        // Create a process and call it "p"
      p.begin("curl");  // Process that launch the "curl" command
      p.addParameter("student.cs.hioa.no/~s180343/updatedb.php?verdi=25"); // Add the URL parameter to "curl"
      p.run();      // Run the process and wait for its termination

      // A process output can be read with the stream methods
      while (p.available()>0) {
        char c = p.read();
        Serial.print(c);
      }
      // Ensure the last bit of data is sent.
      Serial.flush();
    }

title: Passing variable in url

Answers: 0


body:
I want to make my Arduino connect via WiFi and then send an email. The idea is very simple, but the problem is that I've never worked with those protocols and other things before. I just wanted something that's already premade, so I would just change the information.

Is there a library or a function that sends the email?

If someone could help me to understand, so I can make it myself, that would be the best.

title: How to send an email with Arduino and a WiFi shield?

Answers: 5

body:
What you're looking for is a **SMTP (Simple Mail Transport Protocol) library**. A Google search finds 2 for the Arduino:

- SMTPClient

  This seems to be a minimal-capability SMTP-only library that piggybacks on top of a connection library.

- FullIP

  This seems to be a full IP package for the Arduino that works with select network devices which includes SMTP capability.

body:
You actually present 2 issues here, which can be handled separately:

- You are concerned about having a WiFi, not an Ethernet shield. This doesnt affect at all for sending emails or any other network stuff. When you have internet connection, it is almost transparent from the programming side. So I recommend first to try your wifi shield connection and configuration as a separate problem, with a more simple task, as a simple HTTP_GET to a known web page. A function like this might help, assuming that you have an instance of WiFiClient (which is a Client), that has been connected (with connect) to the URL and port 80:

        void http_get(Client& www, char website[], char webpage[], int timeout, Stream& stream) {
            if (www.connected()) {
                int n = www.print("GET ");
                www.print(webpage);
                www.print(" HTTP/1.1\r\n");
                www.print("Host: ");
                www.print(website);
                www.print("\r\n");
                www.print("\r\n");
            } else {
                stream.println(F("Connection failed get"));
                return;
            }

            /* Read data until either the connection is closed, or the idle timeout is reached. */
            unsigned long lastRead = millis();
            while (www.connected() && (millis() - lastRead < timeout)) {
                while (www.available()) {
                    char c = www.read();
                    stream.print(c);
                    lastRead = millis();
                }
            }
        }

- The second problem is that you want to send an email. One you have a connection, it doesnt matter if it is wifi or wired. The above recommended libraries (SMTPClient, FullIP) will directly connect to your provider (e.g. gmail) and will request your gmail password, something that is not secure over non secure connections (and those libraries do not seem to provide secure layer), so personally I am not comfortable with that option. I have been using the [temboo][1] service, that allows to send emails, and I have found it to be quite convenient and simple. Furthermore, they also have many other services. The service stores your gmail or whatever provider credentials, and you access the service via a Secret Key and App Password they provide. While this keys might not be fully secure to be sent via non secure layers, at least it only compromises your app in the cloud application, which you might simply manage, and not your full email account. (Disclaimer: I have no relation with temboo, and there might be other similar services for this task, e.g. [Carriots][2], I simply say that I have used them with success for this task and feel it is relatively simple). Your code using temboo, could be something like:

  TembooChoreo choreo(client); // your WiFiClient object

  // Set Temboo account credentials
  choreo.setAccountName(temboo_account);
  choreo.setAppKeyName(temboo_app);
  choreo.setAppKey(temboo_app_key);

  // credential is the name of your gmail profile in temboo
  choreo.setCredential(credential);
  choreo.addInput("MessageBody", body);
  choreo.addInput("Subject", subject);
  choreo.addInput("ToAddress", address);

  //Identify the Choreo to run
  choreo.setChoreo("/Library/Google/Gmail/SendEmail");

  choreo.run();
  choreo.close();

  [1]: http://www.temboo.com
  [2]: https://www.carriots.com/documentation/arduino

body: There may be a problem with sending Email from Arduino, but not where you are expecting it. SMTP protocol is super simple, even Arduino can handle it. But you will need SMTP server somewhere that will talk to your Arduino. SSL connections (as on Gmail) are out of consideration (code to handle the encryption would be too much for Arduino) so you'd have to find mail provider that provides plain SMTP - and there aren't many. If you will set up one yourself, say on your home PC with static IP address, it would be an invitation for spammers and a guaranteed way to get your IP blacklisted by Spamhaus. My advice would be to have Python, PHP or Perl script hosted somewhere that will handle HTTP POST requests from your Arduino and do Email sending. It is safer and simpler.

body:
Sending gmail via SMTP from an Arduino is completely feasible. I am doing it from an Arduino MKR WIFI 1010 using the WIFINina library. I'm  pretty sure that my solution will work on any of the SAMD based Arduinos.

There is a bit o "setting up" to do, but it's not hard.

Check out my solution on my [gitlab repo][1].

Be sure to do the config BEFORE trying to execute the code...
Good luck!
GF

  [1]: https://gitlab.com/gratefulfrog/arduino-wifinina-gmail-smtp

body:
The simplest way to send email from Arduino is to make HTTP request to IFTTT. See [Arduino - IFTTT][1]

  [1]: https://arduinogetstarted.com/tutorials/arduino-ifttt


body:
I am starting a personal project of home automation and I have a raspberry pi and an arduino Uno board.

I want communicate raspberry pi and my arduino where my raspberry should be able to write and read signals to and from arduino.

The distance between them I think its going to be something around 10 to 15 meters.

What do I need for it? what kind of wires or other components I'll need to achieve my goal? I repeat: I do not want to communicate raspberry pi and arduino wirelessly.

Thanks!

title: How can I communicate Raspberry Pi and Arduino (in both ways) using a 10-15m distance wires?

Answers: 1

body:
for length such as this, you should be using protocols that are designed for length, such as:

 * UART,
 * CAN,
 * Ethernet

for UART, you can't of course use a direct connection between the two boards, you need to upgrade the connection and wiring to either rs232 or rs485, using a driver between the arduino pins and the cable.

Though, the simplest solution would be to plug the Arduino on the Raspberry Pi using a lengthy USB cable (or more likely 3 five meters cable), which should work fine as long as you only do serial communication. The USB 2.0 limitation of 5 meters are for "hi-speed" connections, which is not our concern for simple serial data communication.

HTH


body:
I am trying to connect a MPL3115A2 Altitude/Pressure/Temp Sensor Breakout which I bought from Hobbytronics to my Arduino Mega. What I had in mind was (Breakout -> Arduino):

`3.3V -> 3.3 V`
`GND -> GND`
`SDA -> A4`
`SCL -> A5`

The information which I've found so far is very conflicting and I'm not sure whether or not I should be using pull-up or in-line resistors, and if so, what value?

The code which the product page links to also differs, with one stating that the Wire library is unsafe to use with a 3.3V rated sensor due to the internal pull-ups, but the other code uses the Wire library?

If anyone could advise me on how best to use this sensor without frying it, it would be much appreciated!

 - Product information
 - Code

title: Can anyone explain how to use MPL sensor with Arduino MEGA?

Answers: 1

body:
Since the device is 3.3V and the Arduino is 5V, you *will* need a I2C level converter such as the TCA9517. Simply supply the Mega side with 5V and the device side with 3.3V and attach 4.7kohm pull-ups to 5V on the Mega side, and it will convert both SDA and SCL for you. You won't need pull-ups on the device side since it includes pull-ups on the board.

For I1 and I2 (push-pull outputs) you can use either normal level converters or you can use a SN74LVC2G07 along with the pull-ups found on the Mega inputs.


body:
My project is to control car windows using voice recognition. I have successfully controlled some LEDs using the EasyVR Arduino shield using and Arduino MEGA. Now I want to take control of the windows using the CAN-BUS arduino shield.

Because the car that I own doesn't have an OBD-II connector, I am using two Arduinos with two CAN-BUS Arduino shields making one a sender and the other a receiver. How can I program the CAN-BUS Arduino shield to make a simulation of the car's windows?

CAN-BUS shield that I am using: https://www.sparkfun.com/products/10039

Arduino Mega: https://www.sparkfun.com/products/11061

title: How to program a CAN-BUS Arduino shield to control car windows?

Answers: 2

body: the central lock system will close the car doors and close the windows, i think you should build your system with the same idea, dealing with windows motors as normal motor without special commands for the window

body:
What model car do you have?  Most cars do not have the ability to control power windows from the car computer.  Late model cars will have the ability to control the window motors using bidirectional functions on a scan tool.  On any car, the window motors have two wires, if one wire is given power and one ground it will spin if you switch the wire that gets power with the wire that gets ground it spin in the opposite direction.  In my experience the way power windows work are both wires are ground while the switch is in the neutral position and by flipping the switch the switch will disconnect one of the grounds and replace it with a power.  Find a wiring diagram for your car, and look at how the windows are controlled.

Get a 2 relay breakout board such as this one (make sure you check the current ratings):
http://www.amazon.com/SainSmart-2-CH-2-Channel-Relay-Module/dp/B0057OC6D8/ref=sr_1_1?ie=UTF8&qid=1400730995&sr=8-1&keywords=arduino+relay+12v

Connect the ground wire to the normally closed (when no power is applied to the relay this is connected to the output wire) side of both relays and the 12v power to the normally open (when power is applied to the relay this is connected to the output wire)side of both relays.

In order to control the relay breakout board you choose one io pin per relay and set it as an output, then connect those pins to the corresponding pin on the breakout board. Set one of the pins to high (you apply power to one relay) the motor now has a power and a ground connection, set the opposite pin high to spin the other way.

I would place this in the driver side door underneath the window master switches because you can have access to every windows wires as they come out of the master switch.

Some late model cars will have a different set up than the one described, but the window motor will only have two wires (it is just a brushed DC motor) just find the window motor and hookup there.

I hope this helps.


body:
I am trying to create a wireless remote control to control a servo motor via Bluetooth. What all do I need to establish this? I did some research and found the following:

[Tinyduino][1]

[Bluetooth low energy shield][2]

  [1]: https://tiny-circuits.com/products/tinyduino/
  [2]: https://tiny-circuits.com/shop/tinyshield-bluetooth-le/

Would these be enough (in addition to the servo motor) to establish my needs? Any advice on how I would go about coding this? I can research on the specifics but hints on functions to use would be greatly appreciated. Thanks!

I need to be able to control the system wirelessly (may it be Bluetooth or whatever) through a remote control. This remote control could be a push button system or an app on the phone. I do not have this designed yet. I do not know how to make iPhone apps so the best solution for me would be a simple push button on/off switch that can wirelessly tell the servo motor to either turn 90º clockwise or counterclockwise.

The RFDuino suggestion is very helpful, thank you for that. Can anyone recommend a push-button switch (small) that can wirelessly transmit the signal to the servo motor on the device? I hope this clears things up. Thanks!

title: Creating a wireless remote

Answers: 1

body:
I would also check out [RFDuino][1].

Basically it's a finger-tip sized, Arduino compatible, wireless enabled microcontroller, low cost enough to leave in all of your projects.

The RFduino runs Arduino code and can do everything an Arduino can.

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


body: Is there any good way to calibrate the watchdog timer? I'm trying to use it as a time source, even when asleep, but it's woefully inaccurate. Some simple testing showed it loosing 2 minutes every *hour*!

title: Calibrate Watchdog Timer

Answers: 1

body:
Not only is it uncalibrateable, but it's actually pretty rubbish (as you've discovered). If you check the datasheet you'll see that it can vary between about 109kHz and 119kHz, even though its nominal frequency is 128kHz.

With the ATmegaXX8(A/P) you can reconfigure the system to run its CPU off the internal RC oscillator and timer 2 from a crystal across TOSC1/TOSC2 (pins 9/10 [DIP] or 7/8 [TQFP]) by setting ASSR[6:5] to 0b01 and changing the CKSEL[3:0] fuse bits to 0b0010. Take careful note of the warning on AS2 in the datasheet though. If you want to use a watch crystal instead of prescaling the existing crystal on an Arduino board then you'll need some soldering skill as well.

If you need crystal accuracy for the CPU as well then you'll need to move up to an AVR family that has a separate asynchronous timer that can be supplied with a watch crystal, such as the ATmegaXX4(P) (Sanguino) or ATmegaXXX0 (Mega/Mega 2560).


body:
I really hope somebody can help me.

I need help making my code receive updates faster to the parser...I need the received GPS coordinates (Latitude and Longitude) to update 5 or more times a second, currently it locks when stationary. Can somebody help?

code:

    #include <TinyGPS.h>

    /* This sample code demonstrates the normal use of a TinyGPS object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
    */

    TinyGPS gps;
    //SoftwareSerial ss(4, 3);

    static void smartdelay(unsigned long ms);
    static void print_float(float val, float invalid, int len, int prec);
    static void print_int(unsigned long val, unsigned long invalid, int len);
    static void print_date(TinyGPS &gps);
    static void print_str(const char *str, int len);
    //double getCurrentLatitude();
    //double getCurrentLongitude();

    //double cLatitude = 0.0;
    //double cLongitude = 0.0;
    //
    //double getCurrentLatitude(){
    //  return cLatitude;
    //}
    //
    //double getCurrentLongitude(){
    //  return cLongitude;
    //}

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

    //  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
    //  Serial.println();
    //  Serial.println("Sats HDOP Latitude      Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
    //  Serial.println("          (deg)         (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
    //  Serial.println("------------------------------------------------------------------------------------------------------------------------------------------");

      Serial1.begin(9600);
    }

    void loop()
    {
      double flat, flon = 0.0000000000000;
      unsigned long age, date, time, chars = 0;
      unsigned short sentences = 0, failed = 0;
      //static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

    //  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
    //  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
      gps.f_get_position(&flat, &flon, &age);
    //  gps.f_get_position(&cLatitude,&cLongitude, &age);

      //print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);
      //print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);

      float lati = (float)flat;
      float longi = (float)flon;

      Serial.print("     ");
      Serial.print(lati, 8);
      Serial.print(" ");
      Serial.print(longi, 8);
      smartdelay(0);
      //cLatitude = flat;
      //cLongitude = flon;
    //  print_float(getCurrentLatitude(), TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);
    //  print_float(getCurrentLongitude(), TinyGPS::GPS_INVALID_F_ANGLE, 13, 8);

    //  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
    //  print_date(gps);
    //  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
    //  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
    //  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
    //  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
    //  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
    //  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
    //  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);
    //
    //  gps.stats(&chars, &sentences, &failed);
    //  print_int(chars, 0xFFFFFFFF, 6);
    //  print_int(sentences, 0xFFFFFFFF, 10);
    //  print_int(failed, 0xFFFFFFFF, 9);

      Serial.println();

      smartdelay(1000);
    }

    static void smartdelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (Serial1.available())
          gps.encode(Serial1.read());
      } while (millis() - start < ms);
    }

    static void print_float(float val, float invalid, int len, int prec)
    {
      if (val == invalid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartdelay(0);
    }

    /*
        If data is invalid, print out *******
        otherwise print out buffer
    */
    static void print_int(unsigned long val, unsigned long invalid, int len)
    {
      char sz[32];
      if (val == invalid)
        strcpy(sz, "*******");
      else
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartdelay(0);
    }

    static void print_date(TinyGPS &gps)
    {
      int year;
      byte month, day, hour, minute, second, hundredths;
      unsigned long age;
      gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
      if (age == TinyGPS::GPS_INVALID_AGE)
        Serial.print("********** ******** ");
      else
      {
        char sz[32];
        sprintf(sz, "d/d/d d:d:d ",
            month, day, year, hour, minute, second);
        Serial.print(sz);
      }
      print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
      smartdelay(0);
    }

    static void print_str(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartdelay(0);
    }

title: Faster GPS update rate for parser

Answers: 1

body:
I assume you're using TinyGPS which I sourced from https://github.com/mikalhart/TinyGPS

I've recently done a similar thing - just trying to get the gps to work and give me as much data as possible.

The code I used to do this is here:

 #include "TinyGPS.h"

 #define GPS_BAUD 115200
 #define PC_BAUD 115200

 TinyGPS gps;

 int led1 = 13;

 long lat, lon;

 unsigned long fix_age, time, date, speed, course;

 unsigned long chars;
 unsigned short sentences, failed_checksum;

 void setup()
 {
   pinMode(led1, OUTPUT);
   Serial1.begin(GPS_BAUD);
   Serial.begin(PC_BAUD);
   Serial1.println("");
   Serial1.println("Initializing");
   Serial1.println("");
   digitalWrite(led1, HIGH);
   delay(2000);
   digitalWrite(led1, LOW);
   delay(500);
 }

 void loop()
 {
   while(Serial1.available()){
  if(gps.encode(Serial1.read())){
    digitalWrite(led1, HIGH);
    gps.get_position(&lat, &lon, &fix_age);
    gps.get_datetime(&date, &time);
    Serial1.println("");
    Serial1.println("Lat: " + String(lat));
    Serial1.println("Lon: " + String(lon));
    delay(3000);
    gps.stats(&chars, &sentences, &failed_checksum);
    Serial1.println("Chars: " + String(chars));
    Serial1.println("Sents: " + String(sentences));
    delay(1000);
    Serial1.println("Fails: " + String(failed_checksum));
    Serial1.println("");
    delay(1000);
  }
  Serial1.print(".");
   }
 }

I was using an Arduino Mega 2560, but I think you have the same Serial ports on your Due. I connected the TX pin of my GPS ( can't remember the model but I think it was a 10Hz version of this: https://www.sparkfun.com/products/9891 ) to Serial1's RX and I used a small serial 2 row LCD display to output which was connected to Serial1's TX, hence I was using serial1 for both transmitting and receiving. If you remove the delays from the code above the data is read and then written back as fast as possible and while I never measured how many fixes I was seeing per second I'm fairly sure there were at least 5.

The code you want is probably something like this:

 #include "TinyGPS.h"

 #define GPS_BAUD 115200
 #define PC_BAUD 115200

 TinyGPS gps;

 int led1 = 13;

 long lat, lon;

 unsigned long fix_age, time, date, speed, course;

 unsigned long chars;
 unsigned short sentences, failed_checksum;

 void setup()
 {
   pinMode(led1, OUTPUT);
   Serial1.begin(GPS_BAUD);
   Serial.begin(PC_BAUD);
   Serial1.println("");
   Serial1.println("Initializing");
   Serial1.println("");
   digitalWrite(led1, HIGH);
   delay(2000);
   digitalWrite(led1, LOW);
   delay(500);
 }

 void loop()
 {
   while(Serial1.available()){
  if(gps.encode(Serial1.read())){
    digitalWrite(led1, HIGH);
    gps.get_position(&lat, &lon, &fix_age);
    gps.get_datetime(&date, &time);
    Serial.print("    ");
    Serial.print(lat);
    Serial.print(" ");
    Serial.print(long);
  }
   }
 }

As commented by @connor-wolf above you will probably need to change the baud-rate of your communications up because otherwise you the limit of the amount of information you can send/receive per second is probably too low. The baud rate must also match the baud rate of your GPS device. Some GPS devices have an adjustable baud rate.

------

A quick google turned up an average NMEA sentence length of 60 bytes and if I recall correctly you may have 2 or 3 sentences to each fix? (I think the extra sentences contain extra info like satellite counts, and stuff). So assume you need 180 bytes per fix and you want at least 5 fixes per second that would be 900 bytes. In baud that is 900x8 = 7200. So assuming my estimations above are accurate or overestimated then you have enough bandwidth.

I'm not sure however if the Micro transmits/receives over serial while running the other instructions in your code - I would assume not to be safe but it's worth some research. Therefore you have to account for the time the micro spends transmitting and interpreting the data as time in the second that it can't spend receiving the data. Therefore I would suggest that doubling or even tripling the data rate would be a good idea. (as you can see from my example I just set it to as high as the GPS would go.)

Anyway. I hope all that helps.

P.S please forgive if I've used the wrong terminology for fixes/sentences or whatever


body:
I have a Seeed Studio SD card shield (V3) that I am trying to use on my Arduino Due. I am having trouble using the SD examples that come with the Arduino IDE.

They worked fine on my Arduino Uno by setting `chipSelect` to `SS`. Below is the code I used for the Arduino Uno. It is the same as the `CardInfo.ino` in the examples section under SD (except for the `chipSelect`).

CardInfo.ino
<!-- language-all: lang-cpp -->
    /*
      SD card test

     This example shows how use the utility libraries on which the'
     SD library is based in order to get info about your SD card.
     Very useful for testing a card when you're not sure whether its working or not.

     The circuit:
      * SD card attached to SPI bus as follows:
     ** MOSI - pin 11 on Arduino Uno/Duemilanove/Diecimila
     ** MISO - pin 12 on Arduino Uno/Duemilanove/Diecimila
     ** CLK - pin 13 on Arduino Uno/Duemilanove/Diecimila
     ** CS - depends on your SD card shield or module.
       Pin 4 used here for consistency with other Arduino examples

     created  28 Mar 2011
     by Limor Fried
     modified 9 Apr 2012
     by Tom Igoe
    */

    // include the SD library:
    #include <SPI.h>
    #include <SD.h>

    // set up variables using the SD utility library functions:
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    // change this to match your SD shield or module;
    // Arduino Ethernet shield: pin 4
    // Adafruit SD shields and modules: pin 10
    // Sparkfun SD shield: pin 8
    const int chipSelect = SS; //CHANGE HERE!!!!!!!!

    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
      }

      Serial.print("\nInitializing SD card...");
      // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
      // Note that even if it's not used as the CS pin, the hardware SS pin
      // (10 on most Arduino boards, 53 on the Mega) must be left as an output
      // or the SD library functions will not work.
      pinMode(10, OUTPUT);     // change this to 53 on a mega

      // we'll use the initialization code from the utility libraries
      // since we're just testing if the card is working!
      if (!card.init(SPI_HALF_SPEED, chipSelect)) {
        Serial.println("initialization failed. Things to check:");
        Serial.println("* is a card is inserted?");
        Serial.println("* Is your wiring correct?");
        Serial.println("* did you change the chipSelect pin to match your shield or module?");
        return;
      } else {
        Serial.println("Wiring is correct and a card is present.");
      }

      // print the type of card
      Serial.print("\nCard type: ");
      switch (card.type()) {
        case SD_CARD_TYPE_SD1:
          Serial.println("SD1");
          break;
        case SD_CARD_TYPE_SD2:
          Serial.println("SD2");
          break;
        case SD_CARD_TYPE_SDHC:
          Serial.println("SDHC");
          break;
        default:
          Serial.println("Unknown");
      }

      // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
      if (!volume.init(card)) {
        Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        return;
      }

      // print the type and size of the first FAT-type volume
      uint32_t volumesize;
      Serial.print("\nVolume type is FAT");
      Serial.println(volume.fatType(), DEC);
      Serial.println();

      volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
      volumesize *= volume.clusterCount();       // we'll have a lot of clusters
      volumesize *= 512;                            // SD card blocks are always 512 bytes
      Serial.print("Volume size (bytes): ");
      Serial.println(volumesize);
      Serial.print("Volume size (Kbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      Serial.print("Volume size (Mbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);

      Serial.println("\nFiles found on the card (name, date and size in bytes): ");
      root.openRoot(volume);

      // list all files in the card with date and size
      root.ls(LS_R | LS_DATE | LS_SIZE);
    }

    void loop(void) {

    }

Here is a picture of my setup:

![Due with SD card shield][1]

###tl;dr

How do I make this shield work on my Due?

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

title: Using SD card shield on Arduino Due

Answers: 1

body:
![Due Pin description](https://www.theengineeringprojects.com/wp-content/uploads/2018/09/introduction-to-arduino-due-2-1.png)

Looking at the pin configuration, the SPI pins are not in the same location as the UNO. Remove the Shield from Due and use cables to connect to the SPI pins


body:
I have an analog sensor which reads values 0-5v, -75 degrees to 75 degrees. Now I have converted to +75 degrees and -75 degrees format depend on the voltage.

From 2.5v to 5v data is read properly (i.e 0-75 degree), but from 0-2.5v they are negative values -75 degree to 0. In the below image array holding register is reading 65493 and 65491 which are negative value. How do I make it readable format? Since my code is very big, only part of code is pasted.

    #define ID   1

    int Wind_Speed=30;
    int Wind_Kmph=67;
    signed int tracker_des_angle=-45;
    signed int tracker_actual_pos=-43;
    Modbus slave(ID, 0, 0);
    boolean led;
    int8_t state = 0;
    unsigned long tempus;
    // data array for modbus network sharing
    uint16_t au16data[14];

    void setup() {

      // start communication
      slave.begin( 9600 );
      rtcSetup();

      tempus = millis() + 100;
      digitalWrite(13, HIGH );
    }

    void loop() {
      // poll messages
      // blink led pin on each valid message
      state = slave.poll( au16data, 14);
      if (state > 4) {
        tempus = millis() + 50;
        digitalWrite(13, HIGH);
      }
      if (millis() > tempus) digitalWrite(13, LOW );
      calcTime();
      convertUTCtoLocal();

      au16data[0]=local_year;
      au16data[1]=local_month;
      au16data[2]=local_day;
      au16data[3]=wkDay;
      au16data[4]=local_h;
      au16data[5]=local_m;
      au16data[6]=local_s;
      au16data[7]=Wind_Speed;
      au16data[8]=Wind_Kmph;
      au16data[9]=tracker_des_angle;
      au16data[10]=tracker_actual_pos;

      au16data[11] = slave.getInCnt();
      au16data[12] = slave.getOutCnt();
      au16data[13] = slave.getErrCnt();
    }

![Negtive value read][1]

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

title: Negative value conversion for modbus slave

Answers: 0


body:
I am trying to make a small project. Firstly, I want to record voice using a small microphone(electret) for the time button is pressed and on releasing the button, the speaker of my laptop should output the recorded voice or a speaker attached to the arduino should output.

**Note: I don't want to use any shield to do so. Simply Arduino**

title: Mic input and Speaker output using arduino

Answers: 1

body:
Microphone input is easy (ADC). Speaker output is easy (PWM). Both have many, many examples strewn across the Internet.

What happens in between is *not*, and will require external components. You will need at the very least somewhere to store the samples between record and playback. Investigate SPI SRAM large enough to store all the required samples at your chosen sample rate (8 kS/s should be high enough for human speech).


body:
I downloaded the Adafruit_GPS library from Adafruit and I'm trying to compile the example code (due_parsing) but I can't seem to get past this silly error:

    In file included from due_parsing.ino:15:

    /Users/haddad/Documents/Arduino/libraries/Adafruit_GPS/Adafruit_GPS.h:24: fatal error: SoftwareSerial.h: No such file or directory
    compilation terminated.

This is the location in the example Arduino Sketch where `SoftwareSerial.h` is mentioned:

    #ifdef __AVR__
      #include <SoftwareSerial.h>
    #endif

I noticed it's around an `ifdef` guard, so shouldn't it not even matter that I don't have this library?

I went into the .h and .cpp files and commented out the where it called `SoftwareSerial.h`, but I'm still getting that above error.

Does anybody know how to fix this?
I am using Arduino IDE v1.5.5

----------

Update:

I didn't put the library in the library direct on my mac but I'm now getting tons of errors, all the errors are with `SoftwareSerial.cpp`. Is anybody else having similar issues when you go to compile?

title: Why am I getting "fatal error: SoftwareSerial.h: No such file or directory"

Answers: 3

body:
According to your comment:

> after commenting out those ifdef guards, it worked

I would say that is a bug in the **Adafruit_GPS** library.

As a matter of fact, the **DUE** is not using the **AVR** architecture (it uses **ARM**), that explains why `#ifdef __AVR__` in `Adafruit_GPS.h` never passes; but then something else should be done specifically for the DUE (missing `#else` or `#elif`).

After checking on *github*, there is an [issue][1] open for that; unfortunately, as of April 2014, it has not moved for 10 months.

Your best guess would be to go there and try to "reactivate" this issue.

  [1]: https://github.com/adafruit/Adafruit-GPS-Library/issues/14

body: So I went into the interface file (.h) and removed all references to AVR and then went into (.cpp) and removed all references to AVR there as well. It now seems to be working, although sometimes it says "Not supported Architecture ARM" during compilation...very weird

body:
this is a "bug" in the arduino IDE pre-compilation process.
If you turn on the compiling verbositi in thge precerences menu, you will see that arduino has copied all file (with a rater "stupid" code that just look for include) into a temp folder (wiring lib are not copied, but the below still aplly). Until here, ugly but still fine.

Then, it will -force- compilation of every "included" file, one by one, the facto bypassing the #ifdef.. and this is why you get that problem.

Solution is to heavy change the ide so it will force compilation only in the main, and let the compiler include and compile needed libraries.

I still have no idea why every file is forced, but a change like this is really heavy and break-old-code prone..

Newest IDE to bypass this problem (and also some other problem, like depeency) use a "config" file that will tell the IDE if use the AVR or ARM or x86 library, probabily this file is missing and the ide see te lib as only AVR by default.

Double check if it is really usable on DUE


body:
Even on ebay's [website][1] it is mentioned that I can't use 2.4" TFT LCD Shield display on attach to Arduino Mega. The problem is that I bought this shield by mistake. I want to put this shield onto Arduino Mega 2560. Is there a way to combine Mega and 2.4" Display Shield?

note: I tried on my friend's Arduino Uno. Shield is working very good.

note: The photo below is determining my question. The display not runs my Arduino's code. It only runs its LED.

![enter image description here][2]

  [1]: http://www.ebay.com/itm/2-4-TFT-LCD-Shield-Touch-Panel-Display-TF-Reader-For-Arduino-UNO-R2-R3-A137-/390631788477
  [2]: https://i.stack.imgur.com/DGkHU.jpg

        // UTFT_Demo_320x240 (C)2012 Henning Karlsen
    // web: http://www.henningkarlsen.com/electronics
    //
    // This program is a demo of how to use most of the functions
    // of the library with a supported display modules.
    //
    // This demo was made for modules with a screen resolution
    // of 320x240 pixels.
    //
    // This program requires the UTFT library.
    //

    #include <UTFT.h>
    #define ILI9320_16 18
    // Declare which fonts we will be using
    extern uint8_t SmallFont[];

    // Uncomment the next line for Arduino 2009/Uno
    //UTFT myGLCD(UNO_24,A2,A1,A3,A4);   // Remember to change the model parameter to suit your display module!

    // Uncomment the next line for Arduino Mega
    UTFT myGLCD(ILI9320_16,38,39,40,41);   // Remember to change the model parameter to suit your display module!

    void setup()
    {
      randomSeed(analogRead(0));

    // Setup the LCD
      pinMode(A0,OUTPUT);  // for the UNO_SHIELD_1IN1
      digitalWrite(A0,HIGH); // the RD pin must be set high
      myGLCD.InitLCD();
      myGLCD.setFont(SmallFont);
    }

    void loop()
    {
      int buf[318];
      int x, x2;
      int y, y2;
      int r;

    // Clear the screen and draw the frame
      myGLCD.clrScr();

      myGLCD.setColor(255, 0, 0);
      myGLCD.fillRect(0, 0, 319, 13);
      myGLCD.setColor(64, 64, 64);
      myGLCD.fillRect(0, 226, 319, 239);
      myGLCD.setColor(255, 255, 255);
      myGLCD.setBackColor(255, 0, 0);
      myGLCD.print("* Universal Color TFT Display Library *", CENTER, 1);
      myGLCD.setBackColor(64, 64, 64);
      myGLCD.setColor(255,255,0);
      myGLCD.print("<http://electronics.henningkarlsen.com>", CENTER, 227);

      myGLCD.setColor(0, 0, 255);
      myGLCD.drawRect(0, 14, 319, 225);

    // Draw crosshairs
      myGLCD.setColor(0, 0, 255);
      myGLCD.setBackColor(0, 0, 0);
      myGLCD.drawLine(159, 15, 159, 224);
      myGLCD.drawLine(1, 119, 318, 119);
      for (int i=9; i<310; i+=10)
        myGLCD.drawLine(i, 117, i, 121);
      for (int i=19; i<220; i+=10)
        myGLCD.drawLine(157, i, 161, i);

    // Draw sin-, cos- and tan-lines
      myGLCD.setColor(0,255,255);
      myGLCD.print("Sin", 5, 15);
      for (int i=1; i<318; i++)
      {
        myGLCD.drawPixel(i,119+(sin(((i*1.13)*3.14)/180)*95));
      }

      myGLCD.setColor(255,0,0);
      myGLCD.print("Cos", 5, 27);
      for (int i=1; i<318; i++)
      {
        myGLCD.drawPixel(i,119+(cos(((i*1.13)*3.14)/180)*95));
      }

      myGLCD.setColor(255,255,0);
      myGLCD.print("Tan", 5, 39);
      for (int i=1; i<318; i++)
      {
        myGLCD.drawPixel(i,119+(tan(((i*1.13)*3.14)/180)));
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);
      myGLCD.setColor(0, 0, 255);
      myGLCD.setBackColor(0, 0, 0);
      myGLCD.drawLine(159, 15, 159, 224);
      myGLCD.drawLine(1, 119, 318, 119);

    // Draw a moving sinewave
      x=1;
      for (int i=1; i<(318*20); i++)
      {
        x++;
        if (x==319)
          x=1;
        if (i>319)
        {
          if ((x==159)||(buf[x-1]==119))
            myGLCD.setColor(0,0,255);
          else
            myGLCD.setColor(0,0,0);
          myGLCD.drawPixel(x,buf[x-1]);
        }
        myGLCD.setColor(0,255,255);
        y=119+(sin(((i*1.1)*3.14)/180)*(90-(i / 100)));
        myGLCD.drawPixel(x,y);
        buf[x-1]=y;
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some filled rectangles
      for (int i=1; i<6; i++)
      {
        switch (i)
        {
          case 1:
            myGLCD.setColor(255,0,255);
            break;
          case 2:
            myGLCD.setColor(255,0,0);
            break;
          case 3:
            myGLCD.setColor(0,255,0);
            break;
          case 4:
            myGLCD.setColor(0,0,255);
            break;
          case 5:
            myGLCD.setColor(255,255,0);
            break;
        }
        myGLCD.fillRect(70+(i*20), 30+(i*20), 130+(i*20), 90+(i*20));
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some filled, rounded rectangles
      for (int i=1; i<6; i++)
      {
        switch (i)
        {
          case 1:
            myGLCD.setColor(255,0,255);
            break;
          case 2:
            myGLCD.setColor(255,0,0);
            break;
          case 3:
            myGLCD.setColor(0,255,0);
            break;
          case 4:
            myGLCD.setColor(0,0,255);
            break;
          case 5:
            myGLCD.setColor(255,255,0);
            break;
        }
        myGLCD.fillRoundRect(190-(i*20), 30+(i*20), 250-(i*20), 90+(i*20));
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some filled circles
      for (int i=1; i<6; i++)
      {
        switch (i)
        {
          case 1:
            myGLCD.setColor(255,0,255);
            break;
          case 2:
            myGLCD.setColor(255,0,0);
            break;
          case 3:
            myGLCD.setColor(0,255,0);
            break;
          case 4:
            myGLCD.setColor(0,0,255);
            break;
          case 5:
            myGLCD.setColor(255,255,0);
            break;
        }
        myGLCD.fillCircle(100+(i*20),60+(i*20), 30);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some lines in a pattern
      myGLCD.setColor (255,0,0);
      for (int i=15; i<224; i+=5)
      {
        myGLCD.drawLine(1, i, (i*1.44)-10, 224);
      }
      myGLCD.setColor (255,0,0);
      for (int i=224; i>15; i-=5)
      {
        myGLCD.drawLine(318, i, (i*1.44)-11, 15);
      }
      myGLCD.setColor (0,255,255);
      for (int i=224; i>15; i-=5)
      {
        myGLCD.drawLine(1, i, 331-(i*1.44), 15);
      }
      myGLCD.setColor (0,255,255);
      for (int i=15; i<224; i+=5)
      {
        myGLCD.drawLine(318, i, 330-(i*1.44), 224);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some random circles
      for (int i=0; i<100; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        x=32+random(256);
        y=45+random(146);
        r=random(30);
        myGLCD.drawCircle(x, y, r);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some random rectangles
      for (int i=0; i<100; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        x=2+random(316);
        y=16+random(207);
        x2=2+random(316);
        y2=16+random(207);
        myGLCD.drawRect(x, y, x2, y2);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

    // Draw some random rounded rectangles
      for (int i=0; i<100; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        x=2+random(316);
        y=16+random(207);
        x2=2+random(316);
        y2=16+random(207);
        myGLCD.drawRoundRect(x, y, x2, y2);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

      for (int i=0; i<100; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        x=2+random(316);
        y=16+random(209);
        x2=2+random(316);
        y2=16+random(209);
        myGLCD.drawLine(x, y, x2, y2);
      }

      delay(2000);

      myGLCD.setColor(0,0,0);
      myGLCD.fillRect(1,15,318,224);

      for (int i=0; i<10000; i++)
      {
        myGLCD.setColor(random(255), random(255), random(255));
        myGLCD.drawPixel(2+random(316), 16+random(209));
      }

      delay(2000);

      myGLCD.fillScr(0, 0, 255);
      myGLCD.setColor(255, 0, 0);
      myGLCD.fillRoundRect(80, 70, 239, 169);

      myGLCD.setColor(255, 255, 255);
      myGLCD.setBackColor(255, 0, 0);
      myGLCD.print("That's it!", CENTER, 93);
      myGLCD.print("Restarting in a", CENTER, 119);
      myGLCD.print("few seconds...", CENTER, 132);

      myGLCD.setColor(0, 255, 0);
      myGLCD.setBackColor(0, 0, 255);
      myGLCD.print("Runtime: (msecs)", CENTER, 210);
      myGLCD.printNumI(millis(), CENTER, 225);

      delay (10000);
    }

title: 2.4" TFT LCD Shield isn't working on Arduino Mega

Answers: 4

body:
You need to compare the pins' functions between your Mega and your friend's Uno. Then you need to make those electrical connections happen. I talk about this a little in the "pin locations" section of [my answer here][1].

This requires "hacking". Something needs to be done to reroute those physical connections. I normally use an intermediate shield to translate pins as needed. There was a shield specifically made for this purpose but I couldn't find it. [Maybe this one would work][2]?

  [1]: https://arduino.stackexchange.com/questions/462/which-are-the-competitors-of-the-arduino-boards/476#476
  [2]: http://www.dfrobot.com/index.php?route=product/product&path=123_124&product_id=990#.U071vPldX_M

body:
A way to proceed is to create a spreadsheet showing the pin positions used by this board, and the Arduino shield signals they plug into. Next to these, you need columns showing the actual signals on the ATMega2560 (for Mega2560) and ATMega328 (for Uno) that these shield pins attach to. You can get this info from the Uno and Mega2560 schematic drawings.

In a quick look, it seems that the Arduino shield pin names for Uno and Mega are the same: for example, shield pin '0' (digital zero) is in the same location on both boards, and likewise for other pins.

However, on the Uno digital-0 attaches to ATMega328 Port D bit 0, while on the Mega2560, it attaches to ATMega2560 Port E bit 0. And things get more obtuse with digital 2..7.

Now, when twiddling bits individually using digitalWrite(pin, value), the Arduino library no doubt takes care of translating to the appropriate port/bits that need to be set for the ATMega chip and Arduino board that's in use. However, libraries that use lower-level functions (especially if they need to write entire bytes to ports, as a fast LCD library might) will need to take their own steps to make this translation.

So... first step is to determine whether there is a separate LCD driver library for Mega2560.

Next, investigate whether the library you have has initialization code that is supposed to determine what board it's running on (and is your board included?), or requires you to set some flag to tell it what board is in use.

Failing that, you _could_ create a mess of jumpers or some other wiring scheme to jumper the Mega's ATMega2560's signals so that it's wired up like a Uno would be. It's not clear that this is possible, since some of ATMega2560's Port D is not even wired to a header.

Or you could look at the source code for the library and see what it's actually doing, and what it would need to do different to operate the ATMega 2560 pins that the shield does connect to.

body:
Have you checked out the Library homepage? [Henning Karlsen's library page][1]

  [1]: http://www.henningkarlsen.com/electronics/library.php?id=51

He has made a user manual for the library. There is also a reference to what pin goes where in the requirements document.

body:
I just happened to buy the same LCD Shields a few days ago, looking for a library to use it with a MEGA 2560 board I found https://github.com/Smoke-And-Wires/TFT-Shield-Example-Code which supports both **UNO** and **MEGA** boards.

Usage is very, simple if we want to use it for **MEGA** we should change the header `#include "uno_24_shield.h"` in **SWTFT.cpp** to `#include "mega_24_shield.h"`

**Description (useful for adding suppport for the shield in other libraries):**

Incompatibility comes from different Port mappings for Arduino pin-out between Mega and UNO.

in **UNO** LCD shield will be connected through:

    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | LCD Data Bit  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |  0  |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | Digital pin # |  7  |  6  |  5  |  4  |  3  |  2  |  9  |  8  |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | Uno port/pin  | PD7 | PD6 | PD5 | PD4 | PD3 | PD2 | PB1 | PB0 |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+

in **MEGA** it will be connected through:

    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | LCD Data Bit  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |  0  |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | Digital pin # |  7  |  6  |  5  |  4  |  3  |  2  |  9  |  8  |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+
    | MEGA port/pin | PH4 | PH3 | PE3 | PG5 | PE5 | PE4 | PH6 | PH5 |
    +---------------+-----+-----+-----+-----+-----+-----+-----+-----+


body:
I am new to using Arduino Yun and I would like to know if it is possible to run a command from the Arduino sketch in order to make (probably, through the Bridge Library) Linino to execute a HTTP Request to a remote server. Then I would like to know if it is possible to use the returned values in that Arduino sketch.

In other words, I would like to delegate the task of retrieving values from the web to the Linux side and the usage of the retrieved data to the sketch.

If it is possible, how to do that?

title: It is possible to program Linino to send HTTP requests and then use the returned values in sketch?

Answers: 1

body:
Take a look at [Bridge example][1] or [TemperatureWebPanel example][2]: you see you can receive kind of "commands" and react "doing things".

Then take a look at [HTTP Client example][3], where you delegate an HTTP call to the linux side.

Now mix the two: you can make HTTP calls after receiving a command from outside your Yun.

A short test can be done by cutting and pasting the examples above.

  [1]: http://arduino.cc/en/Tutorial/Bridge
  [2]: http://arduino.cc/en/Tutorial/TemperatureWebPanel
  [3]: http://arduino.cc/en/Tutorial/HttpClient


body:
I am new to using Arduino Yun and I would like to know if it is possible to run an entire script on the Linux side. In my case the script should execute a HTTP request to a remote server, parse the subsequent HTTP response and return some value that then can be used in the Arduino sketch.

If it is possible, what I have to do? For example, how should I write and run script files? what programming language should I use? where I should put those script files on the Linux side?

title: It is possible to run an entire script on the Linux side? If so, how, what and where to do that?

Answers: 1

body:
Arduino Yun ships with python pre installed. You can copy python scripts from your pc to the yun with `scp` (or WinSCP or `putty`, if you're on windows). Once copied, just run it using Process from your sketch. As they are scripts, program name is `python` and the path to your script is its first argument (you can do that in a different way, but that would require some linux magic, which I suggest to postpone if you're new to it).

Other pre installed options include [lua][1] and bash. Other languages such as ruby, erlang and php are available as optional packages.

  [1]: http://www.lua.org/


body:
I wanted to use either Arduino Mega or Uno as a form of an interface between me and the computer. I want to apply it to the following scenario; if I press a button on a circuit board I want it to trigger an action on my computer, like scroll down.

How can I achieve this? How would the code look like and what programs would I need to translate from Arduino to Windows?

title: Use an Arduino as a user interface for the computer

Answers: 3

body:
You can do that easily with a few of the Arduino boards that have built-in USB communications support.

You find that feature on Leonardo, Micro, Esplora and Due boards. You also find that on some Arduino compatible boards like the Adafruit Flora.

Simply plug the Arduino USB port to your computer and the Arduino will behave like a keyboard. Then you can program your sketch to perform what you want with your buttons. Check the Arduino  [mouse and keyboard library][1].

  [1]: http://arduino.cc/en/Reference/MouseKeyboard#.Uxt6yuddVTY

body:
Arduino Yun, Leonardo, Esplora and Due have  the ability to appear as a native Mouse and/or Keyboard to a connected computer by use of the [Mouse and Keyboard libraries][1].

Here's an example of how you would use SWITCH3 on the Esplora to active PAGE UP on your keyboard.

    if (!Esplora.readButton(SWITCH_3)) {
      Keyboard.press(KEY_PAGE_UP)
      delay(100);
      Keyboard.releaseAll();
      }

[Here's an example][2] of using the Esplora to control the Keyboard and Mouse to control the Flight Simulator option of Google Earth.

If you want to use the Uno it's more difficult but it can be done by sending data from the Uno to a Python program running on the PC. The Python program uses the pywin library to control windows.

[Here's a fully worked out Instructable][3] on how to do it.

  [1]: http://arduino.cc/en/Reference/MouseKeyboard#.Uxt-kIWzBzw
  [2]: http://www.instructables.com/id/Arduino-Esplora-Flight-Simulator/
  [3]: http://www.instructables.com/id/Flight-Simulator-with-Arduino-and-Python/

body:
For the sake of completeness, on the more traditional boards where the USB interface is not implemented from the main "sketch" processor, there are three other potential possibilities:

 - Use the (USB) serial data interface, and have software on the host computer which accepts commands over that.  Obviously, the downside is requiring installation of something on the host system - installation which may require admin privileges or even disabling code signing requirements in some cases (especially if it is to inject the data into the host operating system as if it came from a keyaboard)

 - On boards such as the Uno and comparable-generation Mega which use a secondary ATmega "u" series part as a USB-serial converter, this chip can be reprogrammed to act instead as a keyboard.  That could make loading sketches tricky - though it might be possible to come up with a dual-mode firmware that could switch roles under control of an external hardware or software signal.

 - The main ATmega "sketch" processor can generally implement a "not quite compliant, but workable" *approximation* of a low-speed USB interface *in software* on arbitrary I/O pins with some external matching/protection componenets.  A USB keyboard is a common demo application of that.


body:
I am trying to access my Arduino Yun from the internet, and it's not quite working. I have correctly port forwarded the port 5555 from the router to the Yun (verified I am able to access my many other NAT'd resources).

I can access the Yun from my internal network.

In the Arduino sketch I have this (among many other things). Mainly taken from example sketches.

    #include <Bridge.h>
    #include <HttpClient.h>
    #include <YunServer.h>
    #include <YunClient.h>

    YunServer server;

    void setup {
       // Listen for incoming connections on port 5555
       server.noListenOnLocalhost();
       server.begin();
    }
Is `server.noListenOnLocalhost();` the right one to use to access from the outside world?

title: Accessing Arduino Yun from Internet

Answers: 1

body:
Well, I'm not familiar with the Yun, but the first thing that stands out is the missing

    Bridge.begin();

line apparently needed to initialize the Bridge library that you use.

And you do have something like

    YunClient client = server.accept();

and "more" in the main loop (or a function where applicable) of your code, right ?

And yes, `noListenOnLocalhost()` is the correct function for serving external clients.


body:
I'm working with an Adafruit LSM303DLHC Accelerometer Sensor hooked up to an Arduino.  I've downloaded the appropriate libraries to make it work and uploaded the example sketch "accelsensor.pde".  I then placed my sensor at rest on a flat surface and obtained the following acceleration vector values on average, in units of meters per second:

    X: -0.24  Y: -0.71  Z: 10.47

At rest, each of these three values fluctuate approximately +-0.04 on average.

As I see it, the values are off a bit.  At rest, the X and Y components should hover closer to 0m/s^2 while the Z component should be closer to 9.8m/s^2.

What is the best way to compensate for this biased measurement?  Should I simply add back the average observed bias?  Or is there a more robust method to calibrate the sensor values?

title: Calibrating Accelerometer Sensor

Answers: 2

body:
there are varius calculation.

At the end of the day, if take a point in every position (under no acceleration), you should end up with a sphere, or matematically speacking, wthe lenght of the vector should be equal to gravity, so `sqrt(x*x+y*y+z*z) = G` or, to do less computing `x*x+y*y+z*z = G*G` (same apply for magnetometer, but using local magnetic force, or gyroscope, using a know-speed rotation like a LP player)

To create that spere you have to take many point, and find a multiplicator (or function) for each axes. That is particualary important when one axes has differnet precision of others, you are `linearizing` the axis output, and then `normalizig` its value relative to others axes.

Once you have corrected the vector lenght to have a spere, you should look at the offset of the sphere; if its `center` point is not on the `origin` point 0,0,0 then the differece between `center` and `origin` is the correction you talk about. This is offset correction.

Also many (well, all) sensor are affected on their temperature; many claim to be "thermocompensated", that means this difference is less evident due to some some sort of hardware and/or software filtering.

body:
To get rid of the fluctuation, you could always try a moving average. It isn't hard to modify the `Smoothing` example (under `File->Examples->1. Analog->Smoothing`) to accept accelerometer values.

As for the slight offset in the X & Y values, that is probably because your sensor isn't sitting perfectly flat.


body:
I was playing with getting my servos to be on dedicated power, separate form the Arduino entirely, but obviously controlled by the Arduino. I originally had the ground of the Arduino joined with the `-` of the battery, but to my surprise my Arduino continued to control the servos when I remove the ground wire entirely from the Arduino.

I was under the impression that all electricity must form a complete circuit, and be a closed loop. But my Arduino can obviously send a signal to a component that has no return path to itself.

I feel like I'm missing something fundamental about a electricity. So my question is:

**Why does this work?**

![arduino setup][1]

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

title: How can Arduino control with a servo with only one wire?

Answers: 1

body:
The return signal is probably the other wire's servo. This only works when the control pulses to both servos are not in sync. Pull one signal wire off the breadboard and both servos will stop working.

You need to interconnect grounds or you will get strange effects sooner or later.


body:
Running Ubuntu 12.04.4 LTS (64 bit) I try to upload my code to the Arduino Due through the Native port. I have tried both the `bossac` that ships with the Arduino IDE (which is a modified version of BOSSA), and the master BOSSA branch.

Running this command:

    sudo ./bossac -p /dev/ttyACM0

I get this error:

    No device found on /dev/ttyACM0

However, it works perfectly inside the Arduino IDE.

What can the problem be?

title: Why does command line BOSSA not recognize Arduino Due?

Answers: 3

body:
from the IDE's menu you can activate the verbose upload (and compile) mode, that will print all the command executed; Probabibly what you miss is the necessity to open the serial at 1200baud, that will trigger the reboot and consequent bootloader's start ont DUE chip, and bossac need to find the bootloader. see [autoReset][1]

edit: i've now a pc with a physical Serial, so i've tryed to upload in verbose mode:

    Sketch uses 10,380 bytes (1%) of program storage space. Maximum is 524,288 bytes.
    Forcing reset using 1200bps open/close on port /dev/ttyS0
    /home/xxx/arduino-1.5.6-r2/hardware/tools/bossac -i -d --port=ttyS0 -U false -e -w -v -b /tmp/build8035422101690460839.tmp/sketch_apr14a.cpp.bin -R
as you can see he is resetting the board by opening the serial at 1200, forcing the bootloader to start. You have to do the same on your script befor launching bossac. How this can be done depends on your OS

Please note that the reset is triggered by the 8u2 chip used as USB to serial adapter on the arduino board, so bypassing it by connecting through tx/rx pin (like using your own conversor, like in my example with hardware serial) won't work unless you do a manual reset at the right time

  [1]: http://arduino.cc/en/Guide/ArduinoDue#toc4

body:
Easiest way I've found to do this purely from the terminal:

    stty -f /dev/cu.usbmodemfa121 1200;stty stop /dev/cu.usbmodemfa121;./bossac -i -d --port=tty.usbmodemfa121 -U false -e -w -v -b Blink.cpp.bin -R

Swap out the serial device for whatever /dev you are using; in Linux you may have to sudo to get direct access to the device.
This is assuming you are in the directory where bossac lives and your .bin file is there too. Adjust to suit your needs.
If using the native USB port you should change -U to *true*

body:
The Arduino CLI uses a slightly different version of bossa from the one that is on master:

https://github.com/shumatech/BOSSA/tree/arduino

On Linux, I was able to do the following:

    $ git clone git@github.com:shumatech/BOSSA.git
    $ cd BOSSA
    $ make bin/bossac -j4
    $ stty -F /dev/ttyACM0 1200
    $ ./bin/bossac --port=/dev/ttyACM0 --force_usb_port=true -e -w -v -b /path/to/my/firmware.bin -R

(I got the answer from [this Arduino forum thread][1].)

  [1]: https://forum.arduino.cc/index.php?topic=150195.0


body:
I've hooked up two ultrasonic sensors to my breadboard and I also got a 5v motor installed. I also got the diode installed and the usual set up. I can easily control the motor with one sensor.

But what I'm trying to do is I want the motor to run at let's say 100 once I start it up:

- The first sensor should be used to slowly slow down the motor when an object is placed in front of it
- The second sensor should be used to slowly speed up the motor when an object is placed in front of it

**I do not want the speed to return to 100 once the object is removed.** It should remain at the same speed according to which sensor was used. (Tell me if I have to clarify anything in the comments)

Code

    int motorPin = 9;
    int trigPin = 13;
    int echoPin = 12;
    int trigPin2 = 5;
    int echoPin2 = 4;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(trigPin2, OUTPUT);
      pinMode(echoPin2, INPUT);
      pinMode(motorPin, OUTPUT);
    }

    void loop() {
      int duration, distance;
      digitalWrite (trigPin, HIGH);
      delayMicroseconds (1000);
      digitalWrite (trigPin, LOW);
      duration = pulseIn (echoPin, HIGH);
      distance = (duration/2) / 29.1;
      if (distance < 20) {  // Distance from sensor
        analogWrite (motorPin, 50);
      } else {
        int duration, distance;
        digitalWrite (trigPin2, HIGH);
        delayMicroseconds (1000);
        digitalWrite (trigPin2, LOW);
        duration = pulseIn (echoPin2, HIGH);
        distance = (duration/2) / 29.1;
        if (distance > 20) {  // Distance from sensor
          analogWrite (motorPin, 150);
        }
        if  (distance > 20) {  // Distance from sensor
          Serial.println("Out of range");
        } else {
          Serial.print(distance);
         Serial.println(" cm");
        }
        delay(500);
      }
    }

title: How do I use 2 ultrasonic sensors to control a 5v motor?

Answers: 1

body:
This is *very* simple using the **[`map()` instruction](http://arduino.cc/en/reference/map).** Here's the code you would use (feel free to modify values:

    int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);

So if both sensors gave equal values, they would offset each other. To make it still work if an object is removed, you could just use the last `distance`/`distance_2` value and update the other.
****
One issue with this approach is, if the line of transformation of the object is *not* perpendicular to the line of the pings, the value will go:
> 10 → 11 → 12 → 13 → 14 → 15 → 16 → 17 → 18 → 19 → 20 → [Out of range]

**I've added some pretty animations to show you what I mean:**

Perpendicular:

Collinear:

****
As I understand, this is what you want:

    int motorPin = 9;
    int trigPin = 13;
    int echoPin = 12;
    int trigPin2 = 5;
    int echoPin2 = 4;
    int postdist = 112;
    int postdist2 = 112;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(trigPin2, OUTPUT);
      pinMode(echoPin2, INPUT);
      pinMode(motorPin, OUTPUT);
    }

    void loop() {
      //First Read
      int duration, distance;
      digitalWrite (trigPin, HIGH);
      delayMicroseconds (1000);
      digitalWrite (trigPin, LOW);
      duration = pulseIn (echoPin, HIGH);
      distance = (duration/2) / 29.1;
      int ltol = postdist - 5;
      int htol = postdist + 5;
      if (distance > 20 || !(distance > ltol && distance < htol)) {  // Distance from sensor
        Serial.println("Out of range");
        distance = postdist;
      }
      //Second Read
      int duration2, distance2;
      digitalWrite (trigPin2, HIGH);
      delayMicroseconds (1000);
      digitalWrite (trigPin2, LOW);
      duration2 = pulseIn (echoPin2, HIGH);
      distance2 = (duration2/2) / 29.1;
      int ltol2 = postdist2 - 5;
      int htol2 = postdist2 + 5;
      if (distance2 > 20 || !(distance2 > ltol2 && distance2 < htol2)) {  // Distance from sensor
        Serial.println("Out of range");
        distance2 = postdist2;
      }
      //Math:
      Serial.print("Distances-1: ");
      Serial.print(distance);
      Serial.print(" cm 2: ");
      Serial.print("Distances-1: ");
      Serial.print(distance2);
      Serial.println(" cm");
      postdist = distance;
      postdist2 = distance2;
      int speed = 112 + map(distance, 0, 20, 0, 112) - map(distance2, 0, 20, 0, 112);
      if(speed < 60) {speed = 60;} //Modify 60 to meet your needs for minimum threshold
      analogWrite (motorPin, speed);
      Serial.print("Motor Speed: ");
      Serial.println(speed);
      delay(500);
    }

**Changelog:** forgot to edit `postdist`/`postdist2` at end of cycle, added minimum threshold, prevent very small changes in voltage to keep voltage stable and prevent noise.


body:
So I've got a waveform that's high for 16ms and low for 2ms repeating forever. I need to recreate that and offsets of that waveform time exactly on a different pin. Right now, I've got an interrupt on the rising edge for the 16ms low/high transistion, and delayMicroseconds() that determines the offset and duration of the high and low pulses. Trouble is, I'm not sure the code I have is as fast and accurate as it could be. And the replicated waveform seems to shift through the full period of the original one. I need it to be locked in.Any suggestions?
Here is the code:

     //3 is interrupt for Timing
    //4 through 11 are Time dependent receivers
    //3-11 Pins 12-19
    char incomingByte = 0;

    int pins[9] =
    {
      3,4,5,6,7,8,9,10,11
    };

    void timing()
    {
      //Serial.println("This is a 0ms Event");
     // if(Serial.available() > 0)
     // {
        incomingByte = Serial.read();
        Serial.print("I received");
        Serial.println(incomingByte);

         pinMode(10, OUTPUT);
         digitalWrite(10, HIGH);
         delayMicroseconds(16000);
          digitalWrite(10, LOW);
          delayMicroseconds(2000);
          digitalWrite(10, HIGH);
     }
    //}

    void setup() {
      // put your setup code here, to run once:

    for(int i=0;i<8;i++)
    {
      pinMode(pins[i], INPUT);
    }
    pinMode(3,INPUT);
    attachInterrupt(1,timing,RISING);

    //Begins Serial
    Serial.begin(115200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    }

Here's the waveform I'm trying to duplicate:

![Desired Waveform][1]

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

title: Replicate a Waveform Exactly with An Arduino Uno

Answers: 2

body:
If you're looking to speed your code up I would recommend not using `digitalWrite` or `Serial`. When using digitalWrite it can take quite a few unneeded clock cycles to turn the pin on or off, as a replacement I would suggest looking into using [port manipulation][1].

Example of turning a pin on or off with a preprocessor macro using port manipulation

    #define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
    #define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

Using port manipulation in your code:

    #define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
    #define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

    void timing()
    {
        //incomingByte = Serial.read(); // If needed uncomment, but it's slow
        //Serial.println(incomingByte); // If needed uncomment, but it's slow

         // Set pinMode in setup()
         DIGITAL_WRITE_10_HIGH();
         delayMicroseconds(16000);
         DIGITAL_WRITE_10_LOW();
         delayMicroseconds(2000);
         DIGITAL_WRITE_10_HIGH();
     }

  [1]: http://arduino.cc/en/Reference/PortManipulation

body:
This code is wrong in many ways.

first of all, `timing()` is execute inside an interrupt, this mean that while it is running, all other interrupt and timer stop (delayMicroseconds works because it does not rely on timer, but on know instruction execution time). That mean you have to keep the interrupt funzion faster as possible, or bad things may and will happen. (microseconds still work because it is based on know instruction duration in loop)

For example, Serial is interrupt driven; this may cause a race condition that will freeze the code.

As far as i can understand pin 3 may be a button (in that case you need to apply some antibounce code, just look at the signal create by pressing a button with your oscilloscope to see what happen), so you can just make a digitalRead every loop, if true do your code. So you will keep `timing()` out of interrupt.

`pinMode()` only needs to be set once, in `setup()`. Also, `digitalRead()` is really slow: operating directly on the register is a lot faster! see [port manipulation][1]

but in your case i would delete all precendent code and do some math to use an ad-hoc PWM, so you will be almost code free and because it will be almost all done by hardware, precision and possible granularity will increase, see [secret of arduino PWM][2]

  [1]: http://arduino.cc/en/Reference/PortManipulation
  [2]: http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM


body:
I'm currently trying to build an Arduino robot controlled via a wifi connection. I have an Arduino Mega running as a client and it successfully connects to the server on LAN via the Adafruit cc3000 wifi board. However instead of grabbing the contents of the JSON file and printing it to serial, I'm just getting a 100 continue response. While this means I'm doing something right, I don't know what to do next in order to grab the data I need. Do I need to get the 100 message then respond with the GET request, or is there a way that I can GET the data straight away?

Thank you all in advance. Here is the Arduino code I have so far:

    #include <Adafruit_CC3000.h>
    #include <ccspi.h>
    #include <SPI.h>
    #include <string.h>
    #include "utility/debug.h"
    #include <stdlib.h>

    // These are the interrupt and control pins
    #define ADAFRUIT_CC3000_IRQ 3  // MUST be an interrupt pin!
    #define ADAFRUIT_CC3000_VBAT 5 // Apparently these can be any two pins
    #define ADAFRUIT_CC3000_CS 10  // But I wouldn't change these...
    // Use hardware SPI for the remaining pins (On a Mega 2560, SCK = 52, MISO = 50, and MOSI = 51)
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2);

    #define WLAN_SSID "VM540258-2G"
    #define WLAN_PASS "XXXXXXXX"
    #define WLAN_SECURITY WLAN_SEC_WPA2

    String readString = String(100); //string for fetching data from address
    uint32_t ip = 3232235523; // This translates into the ip address we need
                              // 323223552X; 192.168.0.X

    void setup(){
      Serial.begin(115200); //Can also work at 9600

      //Initialise CC3000 module
      Serial.println(F("\nInitializing CC3000..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Couldn't begin()! Check your wiring?"));
        while(1);
      }
      //Connect to the Wireless Access Point
      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }

      Serial.println(F("Connected!"));

      Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP()) { //Obtain IP addeess
        delay(100);
      }

      while (! displayConnectionDetails())
      {
        delay(1000);
      }
    }

    void loop(){
      Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);

      if (client.connected()) {
        client.println("GET /project-test/state.json HTTP/1.0"); //Make a request for state.json
        client.println(""); //Mandatory blank line?
        if (client.available()){
          char c = client.read();
          Serial.print(c);
          //read char by char HTTP request
          if (readString.length() < 100) {
           //store characters to string
           readString += c;
          }
        }
      }
      //Once we have obtained the data, disconnect from the server
      client.close();
      Serial.println(readString);
      delay(1000);
    }

    bool displayConnectionDetails(void)
    {
      uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

      if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
      {
        Serial.println(F("Unable to retrieve the IP Address!\r\n"));
        return false;
      }
      else
      {
        Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
        Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
        Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
        Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
        Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
        Serial.println();
        return true;
      }
    }

The initial JSON file I'm using contains the following:

    {"speed_left":null,"speed_right":null,"direction_left":null,"direction_right":null}

And the serial output I get when I run the Sketch:

    Initializing CC3000...
    Started AP/SSID scan

    Connecting to VM540258-2G...Waiting to connect...Connected!
    Request DHCP

    IP Addr: 192.168.0.7
    Netmask: 255.255.255.0
    Gateway: 192.168.0.1
    DHCPsrv: 192.168.0.1
    DNSserv: 192.168.0.1

    Connect to 192.168.0.3:80
    100

    Connect to 192.168.0.3:80
    100
ad infinitum

title: TCP communication between Arduino client and server

Answers: 3

body:
you are missing the `HOST` header in the request, so the server tell you to `100 CONTINUE` you request.
Also yes, the final empty row IS mandatory

for example, to ask `www.example.com/index.html`

    GET /index.html HTTP/1.1
    Host: www.example.com

body:
I'm going to guess that it's a problem with your server not expecting an HTTP/1.0 request.  I note the following from RFC 1945 about the response codes:

> 9.1  Informational 1xx
>
>   This class of status code indicates a provisional response,
>   consisting only of the Status-Line and optional headers, and is
>   terminated by an empty line. HTTP/1.0 does not define any 1xx status
>   codes and they are not a valid response to a HTTP/1.0 request.
>   However, they may be useful for experimental applications which are
>   outside the scope of this specification.

I'd recommend changing your request to be HTTP/1.1 compliant (with a Host: header as suggested by @lesto)

body:
Okay, I have a better answer, again done without testing.

If I look at the BNF for an HTTP-message from the RFC, it indicates that the message body is terminated by a blank line.

So, you actually need 2 CRLFs (i.e. 2 blank lines).  The first one separates the headers from the body of the HTTP request.  You don't actually have a message body (which is fine, it is optional).  But, you'll need another CRLF to terminate the (blank) body.

Since you only sent one blank line, the server is sending you the continue status codes, prompting you to finish sending your message (i.e. the message body).

So, try adding another client.println("");


body: I want to make a simple circuit which returns the time/delay between two, consecutive loud sounds (i.e, a mic reading of ~600) coming from a speaker. I have set up and ADMP 401 microphone for this purpose. How do I measure the time it takes for this application?

title: How do I use the timers on an Arduino Uno R3?

Answers: 2

body:
Your question is probably not as simple as it may seem.

One approach I would use if I was to address this same problem would consist in:

1. converting the analog output of the mike into a digital value (based on a threshold to determine)
2. connect this digital signal to one Arduino pin that can trigger an interrupt when its level changes

Let's first start with the easy part: Arduino program.

Let's say we have a digital signal that raises to 1 as soon as a sound of too high amplitude is captured by the mike; it shall stay 1 as long as the sound does not reduce amplitude enough. We will connect this signal to Arduino pin 3; then we can use `attachInterrupt()` to have a function called whenever this pon level raises to 1:

    volatile static bool started = false;
    volatile static unsigned long timing = 0;
    volatile static bool finished = false;

    void loud() {
        if (started) {
            timing = micros() - timing;
            started = false;
            finished = true;
        } else {
            timing = micros();
            started = true;
            finished = false;
        }
    }

    void setup() {
        pinMode(3, INPUT);
        attachInterrupt(1, loud, RAISE);
    }

    void loop() {
        if (finished) {
            // Do something with timing
        }
    }

Now the hardest part: electronics!

A first issue we have to deal with is related to the fact that the raw mike signal will have same wave shape as the sound it captures, this wave has a frequency that can vary between 10Hz (bass) and 20KHz (treble).

Indeed, if we convert the mike analog output to a logical value (`1` when the analog value is above a threshold we'll call `Vt`, `0` when it is under `Vt`) fast enough, then, if the environmental sound as an amplitude above `Vt`, the logical input connected to your Arduino will oscillate at the same frequency as the sound! This would make our efforts pointless as you would measure the period of the sound wave instead of the elapsed time between two distinct sound bursts.

That means that we should probably first "smoothen" the analog sound signal in order to avoid disturbance of its frequency.

Hence point 1 will have to deal with these 2 aspects:

- smoothen analog input value
- compare smoothened value with `Vt` threshold and provide a logical value from this comparison

Comparison can rather easily be performed by an [op-amp][1] used as a comparator.

However, the main difficulty you may have with an op-amp is the need for a symetric voltage supply (e.g. +5V/-5V) although it is possible to use a single supply but that raises further limitations (outside the scope of my answer).

Smoothening the signal is potentially more complex, although it can be done with a simple capacitor, because smoothening the signal generally means weakening it, thus you would lose the initial amplitude of the sound signal.

So how can we deal with that?

A [Schmitt trigger][2] is probably a good solution for this problem but further experiment will be needed to confirm that.

  [1]: http://en.wikipedia.org/wiki/Operational_amplifier
  [2]: http://en.wikipedia.org/wiki/Schmitt_trigger

body:
When you mentions "loud sounds (i.e, a mic reading of ~600)" I'm guessing that means you've successfully connected the mic to an ADC input and you are referring to analog readings, right?  (If not you may need to clarify).  I won't worry about scaling or offset biasing the inputs, assuming you have that part down and you can test the Analog input to detect loudness.

If your Arduino can be dedicated to making this measurement (ie: doesn't need to do anything else while doing it), then the simplest solution might be a loop comparing the ADC input with some threshold you have determined, and using micros() to check the time different.  The micros() function has only 4 uS resolution, but the loop time will add more time than that anyway, and actually the limited bandwidth of your audio signals (speaker and mic both) will make any microsecond level measurement suspect anyway.  So the simple loop might be as accurate as you need.

For example:

    const int THRESHOLD = 600; // adjust
    const int MINDELAY = 1000;  // adjust

    long
    takeMeasurement() {
        while(analogRead(A4) < THRESHOLD); // wait for first trigger
        long start = micros();
        delayMicroseconds(MINDELAY); // let first noise die down
        while(analogRead(A4) < THRESHOLD); // wait for second trigger
        return micros() - start;
    }

You would call this function when you were ready to take a measurement.  To keep the loop time short (when it's waiting for a loud sound), it has no timeout, so it won't return until it does detect two loud sounds.  Depending on your need, you might need to change that and have an escape from the loops.  There are several ways that might be done:

* test for micros() exceeding some timeout within the loop

* decrement a counter in the loop and exit if it goes to zero (or if the sound is detected)

* test a flag (volatile byte) in the loop, which gets set by a timer interrrupt

Which is best depends on other aspects of your overall design.