message:
How can I set 4 Arduino Leonardo PWM-ports between 200Hz and 1kHz?

I've noticed that I can set D9, D10, and D11 to around the timer 1 can be set to ~244Hz. However I need 4 ports that are between 200-1000Hz but I have been unable to figure out how to find the last one. I can't really touch timer 0 as they control millis etc.

body:
According to [Arduino Leonardo][1], you have available for PWM configuration ports numbered 3, 5, 6, 9, 10, 11 and 13. The specifications presented there do not provide the range of the frequency available, but I would expect that if you are able to use 9, 10 and 11, one of the others would fall into place.

  [1]: https://www.arduino.cc/en/Main/arduinoBoardLeonardo


sender: user

sender: assistant

body:
The ATmega32U4 on the Leonardo has 4 timers, named Timer0, Timer1, Timer3 and Timer4. Timer0 would be used for `millis()`.

Timers 1 and 3 are 16-bit timers, and Timer4 is a 10 bit timer.

You can get a wide range of frequencies by changing the prescalers and other factors. A bit would depend on whether you want them to all have the same frequency (but maybe with different duty cycles) or different frequencies. Each timer has two "ports" associated with it, so you can have different outputs - up to a point - for each timer. A given timer can only be in one mode at a time, which limits a bit what its two output ports can be doing at one time.

I have [a page about timers](http://www.gammon.com.au/timers) which is for the Atmega328P, but the Leonardo timers have a lot in common with that. For more details see the [ATmega32U4 datasheet](http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf).

You could get a more detailed answer if you clarified what the exact frequency you want is, what mode (eg. PWM, fast PWM or something else) and whether each output should be the same or different frequencies.

---

According to the [Leonardo product page](https://www.arduino.cc/en/Main/ArduinoBoardLeonardo):

> PWM: 3, 5, 6, 9, 10, 11, and 13. Provide 8-bit PWM output with the analogWrite() function.

So even if you lose two to Timer 0, you should have 5 outputs left (it looks like the "B" side of Timer 1 and Timer 4 share the same pin).


message:
Press the Windows key using "keyboard.press();"

Is it possible to allow an Arduino Leonardo to simulate pressing the Windows key using the `keyboard.press(......);` command?

If so, what is the required value?

body:
Looking at [the list of the HID keyboard codes (page 53)][1], the keys you are looking for have a code of E3 (Keyboard Left GUI) or E7 (Keyboard Right GUI).

Unluckily the `Keyboard::press` function (you can see it [here][2]) does not accept a so high value, since you can only input numbers between 0 and 255 and, in order to send a raw value, you have to send its value plus 136 (which leads to values 363 and 367).

However, looking at the header file, there are two predefined keys called `KEY_LEFT_GUI` and `KEY_RIGHT_GUI`. Maybe these modifier keys behave in exactly the same way.

So my suggestion is to

1. try using one of those values (i.e. `keyboard.press(KEY_LEFT_GUI);` or `keyboard.press(KEY_RIGHT_GUI);`, or use the `keyboard.write(KEY_LEFT_GUI);` to simulate a press on the key instead of you keeping it pressed).
2. If this does not work, create your own library copying the keyboard.cpp and keyboard.h files, calling the class differently and adding the possibility to send the E3 and/or the E7 keys. In this case, you will just need to modify the press function.

Good luck

  [1]: http://www.usb.org/developers/hidpage/Hut1_12v2.pdf
  [2]: https://github.com/arduino-libraries/Keyboard/blob/master/src/Keyboard.cpp


body:
They `Keyboard.press()` command accept [modifiers per the documentation][1]. You may need to do multiple `press()` commands before releasing.

For example, if you want to launch [File Explorer][2] you could use:

    Keyboard.press(KEY_LEFT_GUI);
    Keyboard.press('e');
    Keyboard.releaseAll();

This is equivalent to shortcut keys Win + E.

The modifier `GUI` is what stands in for the "command key" which is the Windows Logo on a PC or *[clover][3]* (⌘) on a Mac.

I don't have any restriction on the higher value on my board ([Pro Micro][4]), as indicated by @frarugi87.

  [1]: https://www.arduino.cc/en/Reference/KeyboardModifiers
  [2]: https://en.wikipedia.org/wiki/File_Explorer
  [3]: https://en.wikipedia.org/wiki/Command_key
  [4]: https://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems#Software-compatibility_only


message:
Send Photo with Arduino Uno

I'm new at Arduino projects. I googled but I couldn't quite get an answer.

I've got:

 - Arduino Uno R3 clone
 - 4 pin push button
 - 3 color RGB LED Module
 - HC06 Bluetooth-Serial Module Card
 - Arduino PIC Camera Module OV7670

In my project, when the button is pushed, the Arduino takes a photo from the camera module and sends it with an HC06 Bluetooth Module to an Android device. And it receives the answer to turn on the Led green or red.

The main problem is how can I capture the photo and send it with bluetooth? I can handle the Android side.

**EDIT 1**

I reviewed that code: [OV7670 FIFO on GitHub][1].

In the "Take Picture" method, I understand that the OV7670 continuously grabs frames and stores them in itself. I send it a signal to load a frame on Data Out pins. (*D0-7*) It loads first 8 bytes on the pins and in Arduinoo, in the for loops for height, width and byte for each pixels, I read in it from *D0-7* and send a signal for next byte array.

But I can't understand how to connect the OV7670 to the Arduino. In code, there are conts called `WRST`, `RRST`, `WEN`, `VSYNC` and `RCLK`. On the OV7670 I've got `SIOC`, `SIOD`, `VSYNC`, `HREF`, `PCLK`, `XCLK`, `D0-7`, `RESET` and `PWDN` pins. How can I connect these pins like in the github link?

By the way here is my OV7670, I read there are different versions of OV7670:

[![OV7670 Camera Module][2]][2]

  [1]: https://github.com/ArduCAM/Arduino/blob/master/OV7670FIFO/OV7670FIFO.ino
  [2]: https://i.stack.imgur.com/f0N9m.jpg

body:
I have looked into something very similar and I think the reason you are finding it difficult to find information is you are viewing the full system.  Break it down into smaller chunks and you will get more chance of finding a match.  So lets look at the camera and then the rest of it.

I think that the reason you can't get an answer for this is that you can't do what you want with what you have.  My research seems to say that the OVO7670 camera needs a separate micro processor and 'special' RAM to work (can't remember what is special about the RAM at the moment).  There is a board that does this called a 'PIXY', but its not cheap.

On the plus side, connecting an Arduino to Android via blue tooth should be quite simple there should be lots of examples on how to set up the Arduino side.  You then need to define to convey your messages between your server an client and I know you aren't asking how to turn a LED on and off from an Arduino. (If you are please see the Example Blink).

Hope that helps

**EDIT**

I think you should have 18 pins on you OV7670.

 1. 3v3 - 3.3v
 2. Gnd - Ground
 3. SIOC - Input - I2C Clock
 4. SIOD - I/O - I2C Data
 5. VSYNC - Output - Vertical Synch
 6. HREF - Output - Horizontal Synch
 7. PCLK - Output - Pixel Clock
 8. XCLK - Input - System Clock
 9. D7 - Output - Data bit 7 (MSB)
 10. D6 - Output - Data bit 6
 11. D5 - Output - Data bit 5
 12. D4 - Output - Data bit 4
 13. D3 - Output - Data bit 3
 14. D2 - Output - Data bit 2
 15. D1 - Output - Data bit 1
 16. D0 - Output - Data bit 0 (LSB)
 17. RESET - Input - RESET - Low to reset
 18. PWDN - Input - Power Down - High to activate


message:
Parsing using the ArduinoJson library

I am trying to parse JSON using the ArduinoJson library. The problem is that I can’t parse www.read() because it’s declared as a char. I think www.read() needs to be a string? How can I convert www.read() into a format that jsonBufffer.parseObject() can understand? Please excuse any lack of terminology. I am new to using JSON.

When I run the code I get to the point where it prints "-------------------------------------” then it does nothing.

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

    // These are the interrupt and control pins
    #define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
    // These can be any two pins
    #define ADAFRUIT_CC3000_VBAT  5
    #define ADAFRUIT_CC3000_CS    10
    // Use hardware SPI for the remaining pins
    // On an UNO, SCK = 13, MISO = 12, and MOSI = 11
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
    ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
    SPI_CLOCK_DIVIDER); // you can change this clock speed

    #define WLAN_SSID       "WLAN_SSID_HERE" // cannot be longer than 32    characters!
    #define WLAN_PASS       "WLAN_PASS_HERE"
    // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
    #define WLAN_SECURITY   WLAN_SEC_WPA2

    #define IDLE_TIMEOUT_MS  300000      // Amount of time to wait (in milliseconds) with no data
    // received before closing the connection.  If you know the server
    // you're accessing is quick to respond, you can reduce this value.

    // What page to grab!
    #define WEBSITE      "wefeel.csiro.au"
    #define WEBPAGE      "/api/emotions/primary/totals"

    StaticJsonBuffer<200> jsonBuffer;

    uint32_t ip;

    void setup(void)
    {
      Serial.begin(115200);
      Serial.println(F("Hello, CC3000!\n"));

      /* Initialise the module */
      Serial.println(F("\nInitializing..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Couldn't begin()! Check your wiring?"));
        while(1);
      }

      Serial.print(F("\nAttempting to connect to "));
      Serial.println(WLAN_SSID);
       if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }

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

      /* Wait for DHCP to complete */
      Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP())
      {
        delay(100); // ToDo: Insert a DHCP timeout!
      }

      /* Display the IP address DNS, Gateway, etc. */
    //  while (! displayConnectionDetails()) {
     //    delay(1000);
    //  }

      ip = 0;
      // Try looking up the website's IP address
      Serial.print(WEBSITE);
      Serial.print(F(" -> "));
      while (ip == 0) {
        if (! cc3000.getHostByName(WEBSITE, &ip)) {
          Serial.println(F("Couldn't resolve!"));
        }
        delay(500);
       }

      cc3000.printIPdotsRev(ip);

    }

    void loop(void)
    {
      char c;
      Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
      delay(300);
      if (www.connected()) {
        www.fastrprint(F("GET "));
        www.fastrprint(WEBPAGE);
        www.fastrprint(F(" HTTP/1.1\r\n"));
        www.fastrprint(F("Host: "));
        www.fastrprint(WEBSITE);
        www.fastrprint(F("\r\n"));
        www.fastrprint(F("\r\n"));
        www.println();
      }
      else {
        Serial.println(F("Connection failed"));
        return;
      }

      Serial.println(F("-------------------------------------"));

      unsigned long lastRead = millis();
      while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
        //Serial.print(www.available());
        while (www.available()) {

          //Serial.print(c);
          //char json[] = www.read();
        }
      }
      c = www.read();
      Serial.print(c);
     JsonObject& root = jsonBuffer.parseObject((char*)c);
     if (!root.success()) {
        Serial.println("parseObject() failed");
        return;
        }

      long love = root["love"];
      long other = root["other"];
      long sadness = root["sadness"];
      long anger = root["anger"];
      long joy = root["joy"];
      long surprise = root["surprise"];
      long fear = root["fear"];

      Serial.println(love);
      Serial.println(other);
      Serial.println(sadness);
      Serial.println(anger);
      Serial.println(joy);
      Serial.println(surprise);
      Serial.println(fear);

      www.stop();
      delay(100);
      www.close();
      delay(200);
     }

body:
There are two `read` methods. One that returns a single character (or error), and one that populates a buffer; you want the latter, with method signature `int read(char* buf, size_t len)` or some such. Read the source.

When allocating the json buffer in `StaticJsonBuffer<200> jsonBuffer;
`, make sure your expected json data fit in 200 bytes.


message:
How to use printf with Arduino's serial ports without an intermediary buffer?

How to use `printf` with Arduino's streams without an intermediary buffer? The following seems unnecessary:

    char buf[256];
    sprintf(buf, ...);
    Serial.print(buf);

Is there a way to connect `HardwareSerial` or `SoftwareSerial` to a libc stream or is there a custom implementation of `printf` that does this?

body:
Sure - here's a Hello, World program that uses printf(). Everything that mentions "uart" is what connects printf() to your output stream. `uart_putchar()` does the actual outputting to ... someplace. That's what you'd modify to direct the C standard output to a different device - SofwareSerial, for instance:

    // Hello, World program using printf()

    #include <Arduino.h>

    static FILE uartout = { 0 };   // FILE struct
    static int uart_putchar(char c, FILE *stream);

    void setup() {
       // For printf: fills in the UART file descriptor with pointer to putchar func.
       fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
       stdout = &uartout;

       Serial.begin(9600);
       printf("Hello, World!\n");
    }

    void loop( void ){
       printf("Elapsed time: %ld\n", millis());
    }

    // uart_putchar - char output function for printf
    static int uart_putchar (char c, FILE *stream)
    {
       if( c == '\n' )
          Serial.write('\r');
       Serial.write(c) ;
       return 0 ;
    }


message:
What would the total current requirements be for these items?

I'm using [5 of those 8mm NeoPixels][1] + a [5V Trinket][2].

I'm trying to get a rough estimate of the current requirements that would have, assuming all 5 NeoPixels were running at full brightness "white" (255 RGB).

I'm voltage-regulated to about 150 mA from the Trinket and my current hunch is that those NeoPixels need more than that, but trying to confirm it.

  [1]: https://www.adafruit.com/products/1734
  [2]: https://www.adafruit.com/product/1501

body: According to the data sheet each LED takes a maximum of 3*20mA, so you are pulling 300mA.  You  are going to need a bigger power supply :(


message:
Arduino Mega pin conflict

I am building a rather complicated model railroad crossing signal and have moved to using the Mega since I need more pins than the Uno. Upon reading the specs of the Mega on the Arduino.cc website I noticed a potential pin conflict, or not, maybe they serve a dual purpose?

> External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2).
>
> I2C: 20 (SDA) and 21 (SCL).

SDA and Interrupt 3 both function on pin 20? Likewise with Interrupt 2 and SCL?

I assume this is true, how/why do they share the same pin?

body:
Lots of things share pins. It's normal. The "how" is that those pins are connected, internally, to multiple bits of the circuitry.

The "why" is simply because if you had a discrete pin for each possible function you would end up with a chip the size of your desk.

Pretty much every single pin on the chip has multiple functions on it.


message:
fatal error: ESP8266WiFi.h: No such file or directory

I used platformio IDE

I did "platformio lib install 1101"
(http://platformio.org/lib/show/1101/ESP8266wifi),

I installed this: http://platformio.org/lib/show/549/WebSockets (follow instructions)

I did similar things to other libraries.

When I click the platformio:build button, it still complains:

> fatal error: ESP8266WiFi.h: No such file or directory fatal error:
>
> ESP8266WiFiMulti.h: No such file or directory fatal error:
>
> ESP8266Webserver.h: No such file or directory

body: Make sure **ESP8266WiFi.h**, **ESP8266WiFiMulti.h**, **ESP8266Webserver.h** files are located in the same directory where your *.uno file present.


body: Have you overridden `lib_dir` in `platformio.ini`? If yes, please remove it.


body:
While Bhushan Patil's answer should work, it would still make future projects tedious. Instead you can add the header files to the hardware library, and use them at will, with the `#include <library>` syntax every other library uses in C/C++.

The PlatformIO IDE has a config file you can modify that tells the IDE where to look for libraries. You could read this file, and determine where to put your header files, such that PlatformIO could find them, or add a location to look for header files in. See this page from the PlatformIO documentation:
http://docs.platformio.org/en/latest/projectconf.html

Beyond that, you could also use the absolute path for the header file (library) you are trying to use, by doing something like

    #include "/home/user/path/to/user/library.h"


message:
Can Arduino be used as an FDTI Programmer?

I would like to program my ESP 8266 WiFi module. But I don't have an FDTI right now is there any way to use Arduino Uno as FDTI Programmer then use ESP without it.

body: Yes. Tie the reset pin on the ISP connector low to keep the ATmega328P in reset, then you can connect pins 0 and 1 to the ESP module to communicate using the Uno's USB-UART bridge. Since the pins are labelled from the perspective of the '328P, connect TX to TX and RX to RX.


message:
My serial Monitor of the Arduino ide does not show up when running Gui?

I have created an gui in python using pyserial to communicate with Arduino but my serial monitor does not show up it says (Serial port busy) whenever I run the gui.

The gui works fine but when I want to see the printed data for that, I am using an external LCD but I was wondering if there was a way to see the data in serial monitor. If not could you explain why? I have no idea whatsoever why is this happening.

body:
If an application is already using the serial port then you won't be able to reopen it.  In this case you Python GUI is communicating with the Arduino over the serial port, so the IDE can't.  Think back to when you are just using the IDE, the serial monitor is closed whenever you upload a new version of the code to the board.

So, how do you solve it.  The simplest answer is to use another serial port for the Python app to talk to the Arduino and leave the default port free for the Arduino IDE/Serial monitor.  Software serial should work, you might need to print to both serial ports from the Arduino, but you can do that by adding another function.

An alternative might be to modify your python app to rebroadcast the debug data to another serial port and then connect to this via hyper terminal.

Hope that helps.


body:
The problem is simple, you are dealing PySerial using the serial communication port arduino, so you can not communicate with Arduino IDE and python at the same time.

**Solution:**

In the program you should print python q values you need, with the Print command, so you'll see in the CMD same as you see in the Arduino serial monitor.


message:
Can I use arduino's 3.3 V output directly to esp8266?

I just bought esp8266 and ftdi usb driver, I want to power the esp8266 with Arduino's 3.3 V output, is that possible?

I saw some tutorial on youtube in that they are suggesting us to use 3.3v regulator ic instead of directly power 3.3 V of Arduino or ftdi driver's 3.3 V output.

If I connect my ftdi or Arduino output directly into esp8266 is there a chance to damage the esp8266?

body: The specs for the Uno say that it does not provide as much current on the 3.3V line as the specs for the ESP8266 requires. You will need to provide another regulator that can supply enough current.


body:
You should search for this data yourself, but since you are saying you are a newbie I'll tell you how to find this.

First of all you should search for a document called "datasheet". On a datasheet the producer writes all the relevant data about his product.

In your case, you should search for the electrical characteristics of the ESP8266. For instance [here][1] you have one of the datasheets. On page 13, there is the "Power consumption" chart, which says that the worst case has a typical current of 170mA. I suggest you to raise it a bit; let's say you need 250mA for the ESP.

Now, the arduino. You should search for the schematic of the board or read the part number of the 3.3V regulator. Since it's easier from the schematic and they released it on the web, you can see that the part number of the 3.3V regulator is LP2985. Searching for it on google will lead you to [the texas instruments webpage][2], with the datasheet. Here you can see that the maximum output current is 150mA, so below the required current. Answer: you can't with arduino.

As for the FT232 cable, you should search for it because there are different models. Search on google and pick the first link pointing to the ftdi website.

As an example, the TTL-232RG has [this datasheet][3]. On page 9 they say that the TTL-232RG-VSW3V3-WE has an output current of 50mA, so you can't use it. The TTL-232RG-VREG3V3-WE, on the other side, has a maximum output current of 250mA, so you can use it.

If you have further questions, just ask here ;)

  [1]: https://cdn-shop.adafruit.com/product-files/2471/0A-ESP8266__Datasheet__EN_v4.3.pdf
  [2]: http://www.ti.com/lit/ds/symlink/lp2985-33.pdf
  [3]: http://www.ftdichip.com/Support/Documents/DataSheets/Cables/DS_TTL-232RG_CABLES.pdf


message:
ESP8266 as WiFi for Arduino

I have a pretty simple project, where some data has to be read from a mySQL server. My idea is to do this with an ESP8266, and then provide that data to the Arduino Mega.

Is this possible or am I going to have to use the ESP8266 itself? I highly doubt that I would have enough pins then.

I read something about AT-commands. But I have no idea how to send those commands to the ESP.

Thanks in advance,

Michidez

body:
Check out ESP-LINK [You can find it here][1]
ESP-LINK is a esp8266 wifi-serial bridge, outbound TCP, and arduino/AVR/LPC/NXP programmer. It has several configuration, one of them allowes uploading new firware ower wifi, or to act as a serial link just like if usb cable is pluged in and serialport viewer is active. The website has great documentation and has one of the slickest configuration interfaces seen on ESP.

  [1]: https://github.com/jeelabs/esp-link


body:
Yes its possible, you can use the ESP8266 as a dumb Wifi to Serial convertor.  Set you Arduino IDE up so you can program the ESP8266 like an Arduino, and then write a simple program to connect to the WIFI network and read the data from the server, then just print it to the default serial console with a special sequence of characters at the beginning of each line, like 'DATA'.

Connect the serial port on the ESP8266 to the Mega, don't forget top cross the RX and TX wires and then write a program on the mega that reads from the serial port you have allocated and only process lines beginning with the special sequence of characters.

Yes you could use the AT commands, but that involves a fair amount of learning. pain and different software, when you already probably have the knowledge that you need.

Some of the later version of the ESP8226 can run at 160MHz and have 1MByte or memory so you might want to hand off some of the data crunching to the ESP.  (But that's a decision for later, once its working).

Hope that helps.


message:
Error on Arduino Code (unknown type name 'LiquidCrystal')

I am using `Arduino IDE 1.6.8` and I am trying to compile the following code [Wheatstone Bridge][1]. I have currently a really weird error:

    unknown type name 'LiquidCrystal'

This error seems to come from the header file:

    // Include the Wheatstone library
    #include <WheatstoneBridge.h>

    // Include the LCD library
    #include <LiquidCrystal.h>

    // Declare external global lcd
    extern LiquidCrystal lcd; <<<Error

I have already installed the `LiquidCrystal` library but I don't know if this trouble is due to the compiler (and the IDE) or something is wrong. The compiler seems to find the right libraries...

  [1]: https://github.com/RobotShop/Wheatstone-Bridge-Amplifier-Shield/tree/master/Examples/strain_gauge_shield_and_lcd_arduino_uno_code

body:
Download the Liquidcrystal.zip file from this link,
[Crystal link][1]

  [1]: http://playground.arduino.cc/Main/LiquidCrystal
Now add that file into documents/Arduino/libraries folder.
Now check if the library is added in the library.
It should probably work.


body:
Using "extern" when instantiating a class is unusual.  We can not tell what your intentions are because this is only part of your code.  However it would be my guess that this code:

    // Declare external global lcd
    extern LiquidCrystal lcd;

Should actually be written like this:

    // Declare external global lcd
    LiquidCrystal lcd((12, 11, 5, 4, 3, 2);

This is making a BIG assumption that you are using an LCD similar to the one used in the HelloWorld example and you have connected it using the same pins!  Comments from the HelloWorld example to help you out:

     * LCD RS pin to digital pin 12
     * LCD Enable pin to digital pin 11
     * LCD D4 pin to digital pin 5
     * LCD D5 pin to digital pin 4
     * LCD D6 pin to digital pin 3
     * LCD D7 pin to digital pin 2
     * LCD R/W pin to ground
     * LCD VSS pin to ground
     * LCD VCC pin to 5V
     * 10K resistor:
     * ends to +5V and ground
     * wiper to LCD VO pin (pin 3)

Background:

Arduino sketches are written mostly in C while the libraries take advantage of C++.  As such the libraries can use a C++ feature called "overloading".  This is where you can have several different functions with different parameters all with the same name. The advantage is that you can call upon slightly different functions (or in this case different classes) simply by altering what is passed.  The LiquidCrystal class has defined all these possibilities:

      LiquidCrystal(uint8_t rs, uint8_t enable,
      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
      uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
      LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
      uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
      LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
      LiquidCrystal(uint8_t rs, uint8_t enable,
      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);

But in none are there no parameters.  That is why the compiler could not find the class in your code.  You needed to match one of the above class types.


message:
What programmer do I select in Arduino IDE for the ATMEL-ICE ISP?

I have been using an AVRISPmkII for many years but recently gave mine away to another hobbiest. I wnated to buy a replacement and have had to buy an ATMEL-ICE ISP as the AVRISPmkII is now unavailable.

Occasionally, I like to program the Arduino Uno from the Arduino IDE using the ISP.

However when I go to select the programmer (from the tools menu), I don't see the ATMEL-ICE in the list.

How do I get Arduino IDE to recognize the ATMEL-ICE ISP?

Note: I am using Arduino IDE v1.6.8.

body:
**As of [V1.8.2][1], the ATMEL-ICE is now included as a programmer in the Arduino IDE.**

The ATMEL-ICE was not available as a in-system programmer (ISP) in version 1.6.8 of the Arduino IDE.

----------

On the 20th of Jan 2017, user facchinm added the ATMEL-ICE to the list of programmers in the IDE, and it was merged into the master on the 8th of Feb. It was [released as a version on the 22nd of March 2017][2].

  [1]: https://www.arduino.cc/en/Main/Software
  [2]: https://github.com/arduino/Arduino/releases


message:
Three phase sine wave inverter using Arduino

I want to design three phase sine wave inverter using Arduino I found this link with circuit diagram and simulation results but he did not provide code. can anyone help me with code http://microcontrollerslab.com/three-phase-sine-wave-inverter/

body:
At the end of the page you are linking to, there is this notice:
"Code for three phase inverter is not free of cost. If you want to purchase code, you can contact me at bilalmalikuet@gmail.com"

If you are Bilal Malik, you should already have the code since you are offering to sell it - unless you want someone here to write it for free so you can sell it afterward.

If you are NOT Bilal Malik, you should not impersonate someone else here.

I am not a huge fan of the concept of intellectual property, but it seems you are trying to do something shady here.


message:
I'm having some undefined references and can't figure out why

Try verifying the code to see the errors.  This is on a arduino nano with a 328 processor.  I put the necessary library in the code.
[Pastebin for code][1]

     #ifndef Pushbutton_h
    #define Pushbutton_h

    #include <Arduino.h>

    #define PULL_UP_DISABLED    0
    #define PULL_UP_ENABLED     1

    #define DEFAULT_STATE_LOW   0
    #define DEFAULT_STATE_HIGH  1

    /*! \brief The pin used for the button on the
     * [Zumo Shield for Arduino](http://www.pololu.com/product/2504).
     *
     * This does not really belong here in this general pushbutton library and will
     * probably be removed in the future. */
    #define ZUMO_BUTTON 12

    class PushbuttonStateMachine
    {
    public:
      PushbuttonStateMachine();
      bool getSingleDebouncedRisingEdge(bool value);
    private:
      uint8_t state;
      uint16_t prevTimeMillis;
    };

    class PushbuttonBase
    {
    public:

      PushbuttonBase();

      // wait for button to be pressed, released, or pressed and released
      void waitForPress();
      void waitForRelease();
      void waitForButton();

      // more complex functions that return true once for each button transition
      // from released to pressed or pressed to released
      bool getSingleDebouncedPress();
      bool getSingleDebouncedRelease();

      // indicates whether button is currently pressed
      bool isPressed();

      // Initializes I/O pin for use as button input.
      // This gets called automatically so normally you will not need to call this,
      // but it might be useful if the pin for the button is in the wrong state.
      virtual void init2() = 0;

    protected:

      virtual bool _isPressed() = 0;

    private:

      PushbuttonStateMachine pressState;
      PushbuttonStateMachine releaseState;
      bool initialized;

      // TODO: move all this init stuff down into Pushbutton
      inline void init()
      {
        if (!initialized)
        {
          initialized = true;
          init2();
        }
      }
    };

    /* \class Pushbutton Pushbutton.h
     * \brief Interface with pushbuttons on dedicated pins.
     *
     */
    class Pushbutton : public PushbuttonBase
    {
    public:

      // constructor; takes arguments specifying whether to enable internal pull-up
      // and the default state of the pin that the button is connected to
      Pushbutton(uint8_t pin, uint8_t pullUp = PULL_UP_ENABLED,
          uint8_t defaultState = DEFAULT_STATE_HIGH);

      virtual void init2();

    protected:

      virtual bool _isPressed();

    private:

       uint8_t _pin;
       bool _pullUp;
       bool _defaultState;
     };

     #endif

    // PIN Configurations #define SEARCH_SPEED 255

    #define echoPin A0
    #define triggerPin 3
    #define rightBackMotor 4
    #define rightMotorSpeed 10
    #define leftMotorSpeed 9
    #define leftForwardMotor 7  //if a motor goes backward swap the number on the FwdPin and BckPin
    #define rightForwardMotor 8   //if a motor goes backward swap the number on the FwdPin and BckPin
    #define leftBackMotor 11
    #define LED 13
    #define leftSensor A1
    #define rightSensor A2
    #define IRdriver 6

    // Robot Configuration Parameters
    // Speed range is -255 -> 255
    #define MAX_SPEED 255
    #define QTR_Threshold 500
    #define ATTACK_DISTANCE 25
    #define BACKUP_DISTANCE 4000
    #define SEARCH_SPEED 255

    // State variables
    bool isBackup = false;
    int backupTimer = 0;
    long distance = 1000;
    Pushbutton button(ZUMO_BUTTON);

    void setSpeed(int speed, int motor);

    void setup() {
       Serial.begin(9600);
       Serial.println("Setup.");

      pinSetup();

       Serial.println("Waiting for button");
    }

    void loop() {
       digitalWrite(IRdriver, HIGH);

      if (button.isPressed()) {
        // if button is pressed, stop and wait for another press to go again
        button.waitForRelease();
        waitForButtonAndCountDown();
     }

      int leftInput = analogRead(leftSensor);
      int rightInput = analogRead(rightSensor);

      if ( isBackup ) {
        backupTimer = backupTimer + 1;
        setSpeed(-MAX_SPEED, 0);
        setSpeed(-MAX_SPEED + 20, 1);
        if (backupTimer >= BACKUP_DISTANCE ) {
          isBackup = false;
          backupTimer = 0;
        }
      } else {
        if ( leftInput <= 500 || rightInput <= 500 ) { // WHITE LINE ABORT!
          //Serial.println("Abort! - "); Serial.println(leftInput); Serial.println(rightInput);
          isBackup = true;
          setSpeed(-MAX_SPEED, 0);
          setSpeed(-MAX_SPEED, 1);
        } else {
          distance = getDistance();
          if ( distance <= ATTACK_DISTANCE ) { // ATTACK!
            Serial.println("Attack!");
            setSpeed(MAX_SPEED, 0);
            setSpeed(MAX_SPEED, 1);
          } else { // search
            // TODO(erh): implement other searching algorithms
            Serial.println("Search");
            setSpeed(SEARCH_SPEED, 0);
            setSpeed(-SEARCH_SPEED, 1);
          }
        }
      }
    }

    void pinSetup() {
      // motors!
      pinMode(leftMotorSpeed, OUTPUT);
      pinMode(rightMotorSpeed, OUTPUT);
      pinMode(leftForwardMotor, OUTPUT);
      pinMode(leftBackMotor, OUTPUT);
      pinMode(rightForwardMotor, OUTPUT);
      pinMode(rightBackMotor, OUTPUT);

       // sonar sensor
      pinMode(LED, HIGH);
      pinMode(triggerPin, OUTPUT);
      pinMode(echoPin, INPUT);

      // qtr light sensor
      pinMode(leftSensor, INPUT);
      pinMode(rightSensor, INPUT);
      pinMode(IRdriver, OUTPUT);
    }

    void setSpeed(int speed, int motor = 0) {
      int speedPin, forwardPin, backPin;
      if ( motor == 0 ) {
        speedPin = leftMotorSpeed;
        forwardPin = leftForwardMotor;
        backPin = leftBackMotor;
      } else if ( motor == 1 ) {
        speedPin = rightMotorSpeed;
        forwardPin = rightForwardMotor;
        backPin = rightBackMotor;
      }

      if ( speed == 0 ) {
        analogWrite(speedPin, 0);
        digitalWrite(forwardPin, LOW);
        digitalWrite(backPin, LOW);
      } else if ( speed > 0 ) {
        digitalWrite(forwardPin, HIGH);
        digitalWrite(backPin, LOW);
        analogWrite(speedPin, speed);
      } else if ( speed < 0 ) {
        digitalWrite(forwardPin, LOW);
        digitalWrite(backPin, HIGH);
        analogWrite(speedPin, abs(speed));
      }
    }

    long getDistance() {
      long duration, distance;
      digitalWrite(triggerPin, LOW);  // Added this line
      delayMicroseconds(2); // Added this line
      digitalWrite(triggerPin, HIGH);
      delayMicroseconds(10); // Added this line
      digitalWrite(triggerPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      return distance;
    }

    void waitForButtonAndCountDown() {
      digitalWrite(LED, HIGH);
      button.waitForButton();
      digitalWrite(LED, LOW);

      for (int i = 0; i < 3; i++ ) {
        Serial.println(i);
        delay(1000);
      }

      delay(1000);
      Serial.println("ATTACK!");
      delay(1000);
    }

  [1]: http://pastebin.com/TbTJQfBn

body:
Your code contains only the header declarations (`.h` file) for those classes. There should also be another file (probably `.cpp`) that actually implements the code for the classes.

What you pasted looks very similar to the `Pushbutton` stuff in [this project on GitHub](https://github.com/pololu/a-star-32u4-arduino-library).

You can look at their `Pushbutton.h` and `Pushbutton.cpp` files to get an idea of what I mean. In fact, you might be able to use those files instead of what you have. I can verify that it does compile, but not whether it works or not.


body:
The error `Undefined reference` is a linker error, which means that the Arduino ecosystem is missing some of the pieces for the build. If you have indeed provided `PushButton.cpp` - whether in a library or not - you need to put a `#include` of `Pushbutton.h` inside the `.ino` file. This tells Arduino that you want to include `PushButton`'s code as well as everything else.

If `Pushbutton.cpp` is inside the same directory as the `.ino` file then that will "just work". If it's elsewhere, you need to tell Arduino.


message:
ESP8266 Arduino 2.2inch ILI9341 TFT library

I recently got one TFT LCD from aliexpress which supports SPI and uses ILI9341.

This is the one.[TFT LCD][1]

I have the ESP8266 EspressoLite 1 board, and I am using ESP8266 Arduino.
[(https://github.com/esp8266/Arduino)][2]

I made the following connection :
 SCK #14, MOSI #13, MISO #12 and CS #4, DC #5,RESET #0

and used the example graphicTest (which is available in the Adafruit_ILI9341-master folder) . I was able to make the display work for a few seconds.
In the graphic test, once the line test starts my ESP8266 gets restarted. This was getting repeated .

In my existing project, I used the following code to just show some messages :

    Adafruit_ILI9341 tft = Adafruit_ILI9341(4, 5, 13, 14, 0, 12);
      tft.begin()
      tft.fillScreen(ILI9341_BLACK);
      tft.setCursor(0, 0);
      tft.setTextColor(ILI9341_GREEN);  tft.setTextSize(4);
      tft.println(message);

The message is shown once a response is sent back from ESP. This works for a couple of times and then it again gets stuck and reboots.

I am not sure whether I am using the optimised library for ESP8266 for this LCD or whether there is any as such.

I read in forums and could see that there were some adafruit libraries in the ESP8266 Arduino but now that it is not available and only some TFT_Touch_Shield_V2 are present.

Has anyone faced the same issue or can tell me a better way to make this display work with ESP8266 Arduino.

Thanks in advance. !!!

  [1]: http://www.aliexpress.com/item/Wholesale-1PC-2-2-Inch-240-320-Dots-SPI-TFT-LCD-Serial-Port-Module-Display-ILI9341/32508607290.html
  [2]: https://github.com/esp8266/Arduino

body:
You did not include any output from the esp8266, but I'm pretty sure what is happening is that the watchdog timer is expiring and resetting your board. This is because the SPI transactions to transfer data to the display are taking too long.

Put the following line in both `setup()` and `loop()` before any display operations happen:

`wdt_disable();`

Needless to say, if you actually *do* need the WDT in your application, you can reenable it after the display operations complete (of course, if you are doing something that depends on the wdt, you already know this!)

Look at the source for the Adafruit library, make sure there are `#ifdef ESP8266` statements there; older versions did not support the 8266.
You may also want to increase the default speed at which the library drives the SPI bus from 8000000. I've gotten it to work at up to 40MHz, with the board flashed at 160MHz of course, and it's a lot faster (unsurprisingly), but if you have long wires or a marginal-quality display, that may fail.

Post pictures :)


message:
Using a button to cycle an array

So. I would like to cycle through an array using a button. My current code goes through if statements when the button is pushed. In each if statement I have a loop to print out a list of strings. I am curious if there is anyway to directly cycle through an array using buttons instead of this indirect route I have taken.

Last question - Is there a way to set the indents in the Arduino IDE to make formatting easier here?

    //------------------------------------------------------------------------------------------------
    // Displays information when a push button is pressed. Also turns on and off a corresponding led.
    // 5/3/2016
    //------------------------------------------------------------------------------------------------

    // declare variables

    char* titles[] = {
      "RELATION",
      "FIRST NAME",
      "LAST NAME",
      "LOCATION",
      "PHONE NUMBER"
    };
    char* user_info[] = {
      "SELF",
      "JOHN",
      "SMITH",
      "FLORIDA",
      "999-888-6666"
    };
    char* econ_one[] = {
      "BROTHER",
      "MICHAEL",
      "SMITH",
      "FLORIDA",
      "999-888-5555"
    };
    char* econ_two[] = {
      "WIFE",
      "EMILY",
      "SMITH",
      "FLORIDA",
      "999-888-4444"
    };
    char* econ_three[] = {
      "SISTER",
      "SOPHIA",
      "ADAMS",
      "NEW YORK",
      "888-777-3333"
    };

    int ledPinOne = 2;
    int ledPinTwo = 3;
    int ledPinThree = 4;
    int ledPinFour = 5;
    int buttonPin = 6;
    int state = 0;
    // setup - set pins

    void setup() {
      Serial.begin(9600);
      pinMode(ledPinOne, OUTPUT);
      pinMode(ledPinTwo, OUTPUT);
      pinMode(ledPinThree, OUTPUT);
      pinMode(ledPinFour, OUTPUT);
      pinMode(buttonPin, INPUT);
      Serial.println("Emergency Contact");
    }

    // main
    void loop() {
      if (digitalRead(buttonPin)) {
        if (state == 0) {
          int x;
          for (x = 0; x <= 4; x++) {
            Serial.println(" ");
            Serial.print(titles[x]);
            Serial.print(" ");
            Serial.print(user_info[x]);
          }
          Serial.println(" ");
          setLights(HIGH, LOW, LOW, LOW);
          state = 1;
        } else if (state == 1) {
          int y;
          for (y = 0; y <= 4; y++) {
            Serial.println(" ");
            Serial.print(titles[y]);
            Serial.print(" ");
            Serial.print(econ_one[y]);
          }
          Serial.println(" ");
          setLights(LOW, HIGH, LOW, LOW);
          state = 2;
        } else if (state == 2) {
          int z;
          for (z = 0; z <= 4; z++) {
            Serial.println(" ");
            Serial.print(titles[z]);
            Serial.print(" ");
            Serial.print(econ_two[z]);
          }
          Serial.println(" ");
          setLights(LOW, LOW, HIGH, LOW);
          state = 3;
        } else if (state == 3) {
          int q;
          for (q = 0; q <= 4; q++) {
            Serial.println(" ");
            Serial.print(titles[q]);
            Serial.print(" ");
            Serial.print(econ_three[q]);
          }
          Serial.println(" ");
          setLights(LOW, LOW, LOW, HIGH);
          state = 0;
        }
        delay(1000);
      }
    }

    // function to turn LEDs on/off

    void setLights(int one, int two, int three, int four) {
      digitalWrite(ledPinOne, one);
      digitalWrite(ledPinTwo, two);
      digitalWrite(ledPinThree, three);
      digitalWrite(ledPinFour, four);
    }

output image

https://www.dropbox.com/sc/fwll0qe7cyye1mt/AAD5vI9buU_X0bl04KXFAQyja

body:
As for your question, your way is (kind of) the best way.

I just saw a problem: when you keep the button pressed you will go on showing. Moreover I really don't like the delay at the end, and if its purpose is just to avoid bounces, well, use the Bounce2 class.

As for the repeated `if`s, I prefer a `switch-case` statement.

I highly suggest you to use the Bounce2 class, though. Here is an example of its usage:

    Bounce debouncer = Bounce();

    void setup()
    {
     ...
     pinMode(buttonPin, INPUT);
     debouncer.attach(buttonPin);
     debouncer.interval(5); // interval in ms
    }

    void loop()
    {
     debouncer.update();
     if (debouncer.rose())
     {
      switch (state)
      {
      case 0:
       {
        int x;
        for (x=0; x <= 4; x++)
        {
         Serial.println(" ");
         Serial.print(titles[x]);
         Serial.print(" ");
         Serial.print(user_info[x]);
        }
        Serial.println(" ");
        setLights(HIGH, LOW, LOW, LOW);
        state = 1;
       }
       break;
      case 1:
      ...
      }
     }
    }

As you can see the class has a `rose` member, which tells you if the button was just pressed (only on the rising edge).

Now, your particular problem can be solved in another way. Since you are repeating the same code for all the cases, you can cycle through two arrays; one stating which is the second array you need to use, the other the lights.

This is an example. Please note that I haven't tested it, so there might be some errors

    char ** second_array[] = { user_info, econ_one, econ_two, econ_three }
    uint8_t lights[][4] { {HIGH, LOW, LOW, LOW},
          {LOW, HIGH, LOW, LOW},
          {LOW, LOW, HIGH, LOW},
          {LOW, LOW, LOW, HIGH},
         }

    void loop()
    {
     debouncer.update();
     if (debouncer.rose())
     {
      int x;
      for (x=0; x <= 4; x++)
      {
       Serial.println(" ");
       Serial.print(titles[x]);
       Serial.print(" ");
       Serial.print(second_array[state][x]);
      }
      Serial.println(" ");
      setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
      state++;
      if (state >= 4)
       state = 0;
     }
    }

Try to use it and then report back if there is some issue ;)


body:
I would recommend using multidemnsional arrays for both your contacts and your light states.

    //------------------------------------------------ declare variables

    char* titles[] = {"RELATION", "FIRST NAME", "LAST NAME", "LOCATION", "PHONE NUMBER"};

    char* econs[][5] = {
      {"SELF", "JOHN", "SMITH", "FLORIDA", "999-888-6666"},
      {"BROTHER", "MICHAEL", "SMITH", "FLORIDA", "999-888-5555"},
      {"WIFE", "EMILY", "SMITH", "FLORIDA", "999-888-4444"},
      {"SISTER", "SOPHIA", "ADAMS", "NEW YORK", "888-777-3333"}
    };

    uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
      {LOW, HIGH, LOW, LOW},
      {LOW, LOW, HIGH, LOW},
      {LOW, LOW, LOW, HIGH},
    };

    int ledPinOne = 2;
    int ledPinTwo = 3;
    int ledPinThree = 4;
    int ledPinFour = 5;
    int buttonPin = 6;
    int state = 0;

    //------------------------------------------------ setup - set pins
    void setup() {
      Serial.begin(9600);

      pinMode(ledPinOne, OUTPUT);
      pinMode(ledPinTwo, OUTPUT);
      pinMode(ledPinThree, OUTPUT);
      pinMode(ledPinFour, OUTPUT);
      pinMode(buttonPin, INPUT);

      Serial.println("Emergency Contact");
    }

    //------------------------------------------------ main
    void loop() {

      if (digitalRead(buttonPin))
      {
        if (state > 3)
          state = 0;

        {
          for (int y = 0; y <= 4; y++)
          {
            Serial.println(" ");
            Serial.print(titles[y]);
            Serial.print(" ");
            Serial.print(econs[state][y]);
          }

          Serial.println(" ");
          setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
        }

        delay(1000);
        state++;

      }

    }

    //------------------------------------------------ function to turn LEDs on/off

    void setLights(int one, int two, int three, int four)
    {
      digitalWrite(ledPinOne, one);
      digitalWrite(ledPinTwo, two);
      digitalWrite(ledPinThree, three);
      digitalWrite(ledPinFour, four);
    }

I haven't tested the above, but it should provide the same result.

As for the second part of your question, there is an autoformat tool in the Tools menu that will auto-indent your code. Ctrl-T will do the same.


message:
Working on a reaction test for the Arduino Uno using an led and an lcd shield

The situation involves some Asm inline practice and a basic circuit. The program turns an LED on after a somewhat random period of time then waits until the button is pressed to report back how many milliseconds it took. This is then printed by the LCD shield. My confusion occurs because after each reset it prints a 1 before the button is pressed, which overlaps returned millisecond value on the screen giving me some false data. I tried to cut the code down so if there is anything else that might be helpful let me know. I think the issue may be in the test reaction time function but am not sure.

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

    /* --------------------------------------------------------------------------------------
      Includes
    --------------------------------------------------------------------------------------*/
    #include <LiquidCrystal.h>   // include LCD library

    /*--------------------------------------------------------------------------------------
      Init the LCD library with the LCD pins to be used
    --------------------------------------------------------------------------------------*/
    LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
    /*--------------------------------------------------------------------------------------
      setup()
      Called by the Arduino framework once, before the main loop begins
    --------------------------------------------------------------------------------------*/

    void setup()
    {
       //button adc input
       pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
       digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
       //lcd backlight control
       digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is high (on)
       pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
       pinMode(3,OUTPUT);                         //d4 is are LED
       //set up the LCD number of columns and rows:
       lcd.begin( 16, 2 );
       //Print some initial text to the LCD.
       lcd.setCursor( 0, 0 );   //top left
       //          1234567890123456
       lcd.print( "LinkSprite  16x2" );
       //
       lcd.setCursor( 0, 1 );   //bottom left
       //          1234567890123456
      // lcd.print( "Btn:" );

        Serial.begin(9600);

     pinMode(2, INPUT);

     }
    /*--------------------------------------------------------------------------------------
      loop()
      Arduino main loop
    --------------------------------------------------------------------------------------*/
    void loop()
    {

          //read the button
         byte result;//  = digitalRead(2);
          asm volatile(
              "ldi %0, 0 \n\t"
              "sbic 0x09, 2 \n\t"
              "ldi %0,1 \n\t"
              "nop \n\t"
              :"=r" (result)
              :
              :
          );
          int t =(random(0, 10000)+1000);
          unsigned long currentM = millis();
          //int t =(random(0, 10000)+1000 +millis());
          while( t < currentM){
          int x = testReactionTime();
           lcd.setCursor( 0, 1 );
         //if (result){
             lcd.print( "on " );
             lcd.setCursor(7,1);
             lcd.print(" ");
             //int x = testReactionTime();
             lcd.print(x,DEC);
             //delay(1000);
             //lcd.print("     ");
          //}else{
            //testReactionTime();
            // delay(random(0, 1000)+1000);
            //lcd.print( x,DEC );
            //digitalWrite(3, LOW);
          }
    //}
    }

    /*
     *  after a random delay call this function to measure their reaction
     *  time in milliseconds
     *  It will immediately turn on a LED (pin 3)
     *  And then start timing the milliseconds until they hit the button (pin 2)
     *
     */
    int testReactionTime()
    {
      int answer;
      //delay(rand());
      asm volatile(
        "ldi �, 0 \n\t"  // initializw anwer to 0
        "ldi �, 0 \n\t"  // answer should be the number of ms until they hit the button
        "sbi 0x0b,3 \n\t"  //turn on the led pin 3
        "ldi r16, 1 \n\t"
        "ldi r17,0 \n\t"
        "movw r26, %0 \n\t"
        "rcall killms%= \n\t"
       "cbi 0x0b,3 \n\t"  //turn on the led pin 3

          "rjmp end%= \n\t" //skip over the routine
          //start of kill millesecond subrouting, need to waste ~16000 clock cycles
          "killms%=:ldi r24, 0x90 \n\t"  //lo8(3984)
          "ldi 25, 0x0f  \n\t"      //hi8(3984)
          "kloop%=: sbiw r24, 1 \n\t"   //2 clocks
           "brne kloop%=   \n\t"       //2 clocks since most times true!!
           "add r26, r16 \n\t"
           "adc r26, r17 \n\t"
           "movw %0, r26 \n\t"
           "sbis 0x09, 2 \n\t"
           "ret       \n\t"
           "rcall killms%= \n\t"
          //end of the kill millesecond loop
          "end%=: nop \n\t"
        :"=r" (answer)
        :
        :"r24", "r25"
        );

      return answer;
    }

body:
Expanding on my comment... I see a few issues in your asm code, not all
as serious as the first one:

1. `killms` is calling itself recursively indefinitely, which should
   overflow your stack. The last `rcall killms%=` should probably be an
   `rjmp`.
2. There is no need to move the answer around between register pairs.
   Just use the compiler-allocated registers instead of `r17:r16`.
3. By `adc r26, r17`, you probably mean `adc r27, r17`.
4. Instead of `add` and `adc`, you could just `adiw`, which saves a
   register pair.

Below is my version of `testReactionTime()`. I tested it on an Uno (with
`Serial` instead of an LCD) and it works fine. The assumptions on the
hardware are:

* The LED is on pin 13 (PB5): it's the built-in LED.
* The button is on pin 2 (PD2), which goes HIGH when the button is pressed.

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

    /*
     * After a random delay, call this function to measure the reaction time
     * in milliseconds. It will immediately turn the built-in LED and then
     * start timing the milliseconds until the user hits the button (pin 2
     * going HIGH).
     */
    int testReactionTime()
    {
        int result, counter;
        asm volatile(
            "    clr %A[result]                      \n" // clear result
            "    clr %B[result]                      \n" // ditto
            "    sbi %[led_port], %[led_bit]         \n" // LED on

            // delay to make the loop 0 last exactly one millisecond
            "0:  ldi %A[counter], lo8(%[iterations]) \n"
            "    ldi %B[counter], hi8(%[iterations]) \n"
            "1:  sbiw %[counter], 1                  \n"
            "    brne 1b                             \n"
            "    nop                                 \n"

            "    sbic %[button_pin], %[button_bit]   \n" // unless button up:
            "    rjmp 2f                             \n" //     we are done
            "    adiw %[result], 1                   \n" // increment result
            "    rjmp 0b                             \n" // loop back
            "2:  cbi %[led_port], %[led_bit]         \n" // done: LED off

            : [result]     "=w" (result)
            , [counter]    "=w" (counter)
            : [led_port]   "I"  (_SFR_IO_ADDR(PORTB))  // LED on PB5
            , [led_bit]    "I"  (5)
            , [button_pin] "I"  (_SFR_IO_ADDR(PIND))   // button on PD2
            , [button_bit] "I"  (2)
            , [iterations] "i"  ((16000 - 8) / 4)
        );
        return result;
    }


message:
How to monitor a sensor for specific period

As noted in earlier posts, I am building a model railroad crossing gate signal, complete with gate arms, flashers and sound. Although I haven't settled on exactly how I am going to implement detection of the train entering the zone, determining when its completely passed the entry sensor, tripped the exit sensor and completely passed the exit sensor to re-open the gate, I am researching using RFID for this now.

My thought is to have an RFID card in every car of all my rolling stock. Therefore, I want to read all the ID's of the cars as they go buy and for this particular need, always store the latest ID in a variable so that once the whole train has passed by, the last ID in the variable SHOULD be the ID of the last car in the train. I would also have a counter incrementing for each unique ID read so I can use that as a secondary check for the exit routine (check that the exit RFID reader gets the same car count as the entry reader). The exit reader would also match its exitTag to the entryTag from the entry reader.

I am implementing a state machine to control all this functionality but the problem lies in the RFID reading, I need a way to determine when the reader has read all the train cars tags. I thought the easiest way to do this was to use the elapsedMillis library and monitor for some interval where no card was read (two seconds? that would be way more than the time between two train cars) and once met, change state.

That is proving more problematic than I thought. Here is my latest attempt.
I also think it might be better if the tag reading method only returned the last tag ID AFTER ITS DETERMINED NO MORE TAGS TO BE READ so that the code in the case statement is not the code that's running continuously.

**Note: I am using the [Adafruit RFID shield][1] and [Mifare Classic 1k S50 IC 13.56MHz RFID][2] cards.**

Any thoughts appreciated

    case CrossingZoneState::CROSSINGZONE_RFIDDETECTED:
  if (crossingZoneEntered == true)
  {
   // only thing we do here is monitor and identify the RFID tags of each car to determine last cars tag id
           //well, this doesnt work
   if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
   {
    //do all the tag reading in here
    tag = IndentifyTag(entryRFIDReader);
    readCount += 1;

    if (tag != priorTag)
    {
     tagCount += 1;
    }
    priorTag = tag;
    timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
   }
   // need to figure out how to determine no more cards are being read and change state and crossingZoneEntered back to false
  }

  if (crossingZoneExited == true)
  {

  }
  break;

IdentifyTags method:

    uint32_t IndentifyTag(Adafruit_PN532 rfidReader)
    {
     uint8_t tagID[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
     uint8_t tagIDLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
     uint32_t rfidCardID = tagID[0];
     boolean success = rfidReader.readPassiveTargetID(PN532_MIFARE_ISO14443A, &tagID[0], &tagIDLength);
     if (success) {
      // Display some basic information about the card for testing
      Serial.println("Found an ISO14443A card");
      Serial.print("  UID Length: "); Serial.print(tagIDLength, DEC); Serial.println(" bytes");
      Serial.print("  UID Value: "); rfidReader.PrintHex(tagID, tagIDLength);

      if (tagIDLength == 4)
      {
       // Mifare Classic card
       rfidCardID <<= 8;
       rfidCardID |= tagID[1];
       rfidCardID <<= 8;
       rfidCardID |= tagID[2];
       rfidCardID <<= 8;
       rfidCardID |= tagID[3];
       Serial.print("Mifare Classic card #");
       Serial.println(rfidCardID);
      }
      Serial.println("");
     }
     return rfidCardID;
    }

Full switch statement:

    switch (state)
 {
 case CrossingZoneState::CROSSINGZONE_CLEAR:
  // only thing we do here is monitor the zone entry sensor
  if (digitalRead(entrySensorPin) == HIGH) {
   crossingZoneEntered = true;
   state = CrossingZoneState::CROSSINGZONE_ACTIVATEGATES;
  }
  break;
 case CrossingZoneState::CROSSINGZONE_ACTIVATEGATES:
  // Do these once: turn on the flashers, put down the arms and turn on the crossing gate bells
  if (didOnce = false)
  {
   // turn on flashers
   // turn on sound
   // lower gate arms
   didOnce = true;
   state = CrossingZoneState::CROSSINGZONE_READENTRYRFID;
  }
  break;
 case CrossingZoneState::CROSSINGZONE_READENTRYRFID:

  // only thing we do here is monitor and identify the rfid tags of each car to determine last cars tag id
  // need to figure out how to determine no more cards are being read and change state
   if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
   {
    //do all the tag reading in here
    entryTag = IndentifyTag(entryRFIDReader);
    readCount += 1;

    if (entryTag != priorTag)
    {
     entryTagCount += 1;
    }
    priorTag = entryTag;
    timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
   }
   else {
    //change state now that entry rfid tag reader is finished
    state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
   }

  break;
 case CrossingZoneState::CROSSINGZONE_OCCUPIED:
  // only thing we do here is monitor the zone exit sensor
  if (digitalRead(exitSensorPin) == HIGH) {
   state = CrossingZoneState::CROSSINGZONE_READEXITRFID;
  }
  break;
 case CrossingZoneState::CROSSINGZONE_READEXITRFID:
  if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
  {
   //do all the tag reading in here
   exitTag = IndentifyTag(entryRFIDReader);
   readCount += 1;

   if (exitTag != priorTag)
   {
    exitTagCount += 1;
   }
   priorTag = exitTag;
   timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
  }
  else {//check tags and count now that entry rfid tag reader is finished
   if (entryTagCount == exitTagCount && entryTag == exitTag)
   {
    state = CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES;
   }
  }
  break;
 case CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES:
  // Do these once: turn off the flashers, raise the arms and turn off the crossing gate bells
  if (didOnce = true)
  {
   // turn off flashers
   // turn off sound
   // raise gate arms
   didOnce = false;
  }
  break;
 case CrossingZoneState::CROSSINGZONE_ERROR:
  boolean success = writeToFileOnSD(modelRRErrorLogFile, "ModelRRXingErrorLog.txt", "error string");
  break;
 }

  [1]: https://www.adafruit.com/products/789?gclid=CjwKEAjw3qu5BRC-0uCw8O6Y5zcSJAA_WtdLfmp0bTa24pF0luhnG0aUBFS01u_KlBpT2bMUmcMNzBoCl0Pw_wcB
  [2]: http://www.ebay.com/itm/400985225679?_trksid=p2057872.m2749.l2649&ssPageName=STRK:MEBIDX:IT

body:
Your algorithm is the probably the problem. Use this entry `case` instead:

    case CrossingZoneState::CROSSINGZONE_READENTRYRFID:

        entryTag = IndentifyTag(entryRFIDReader);
        if (!entryTag) {   // zero is usually returned if no card is detected
            readCount += 1;   // seems u want to count number of reads

            if (entryTag != priorTag) {
                entryTagCount += 1;
                priorTag = entryTag;  // update priorTag
            }
            timeElapsedBetweenCardReads = 0;   /// reset the counter when u read ANY tag; negate the effects of reading a card more than once

        }
        // only check timeout if you didnt read ANY tag at all
        else if (timeElapsedBetweenCardReads >= readerInactiveInterval){
            //change state now that entry rfid tag reader is finished
            state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
        }

        break;

Something similar for the exit:

    case CrossingZoneState::CROSSINGZONE_READEXITRFID:
        exitTag = IndentifyTag(entryRFIDReader);
        if (!exitTag) {   // zero is usually returned if no card is detected
            readCount += 1;   // remember this variable is shared with the other case

            if (exitTag != priorTag) {
                exitTagCount += 1;
                priorTag = exitTag;  // update priorTag
            }
            timeElapsedBetweenCardReads = 0;

        }
        else if ((timeElapsedBetweenCardReads >= readerInactiveInterval) &&
                 (entryTagCount == exitTagCount) && (entryTag == exitTag)){
            //change state now that entry rfid tag reader is finished
            state = CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES;
        }
        break;

And in the OCCUPIED case:

    case CrossingZoneState::CROSSINGZONE_OCCUPIED:
        // only thing we do here is monitor the zone exit sensor
        if (digitalRead(exitSensorPin) == HIGH) {
            state = CrossingZoneState::CROSSINGZONE_READEXITRFID;
            timeElapsedBetweenCardReads = 0;   // reset the counter to prepare for exit case
            priorTag = 0;  // just in case
        }
        break;


body:
Here is a solution I found on one of the forums, I modified/simplified it to suit, but it does what you are after.

I use a cheap MP3 player and small amp that runs all the time with the speaker output switched by a baby relay controlled by the UNO R3 and IR sensors from Ebay, you should be able to convert this for use on your player.

It runs the 4 steps you described.

code attached.
(could not figure out how to get code into a box-very confusing..please enlighten me,,,,and what is a back tick??)

    #include <Servo.h>

    Servo gate1servo;// create servo object to control crossing gate 1
    //ASSUMPTION Gate is down at position gatedownposition and up at position gateuppostion
    Servo gate2servo; // create servo object to control crossing gate 2
    unsigned long previousMillisSERVOSTART=0; //FLASH Millis() setup
    int intervalSERVOSTART = 1000;
    unsigned long previousMillisFLASH=0;  //FLASH Millis() setup
    int intervalFLASH = 250;
    int gateup  =  120;  // servo position for gate up
    int gatedown = 30;
    int gatepos; // variable to store the servo gateposition
    int gp = 120;  // servo position for gate down
    int sensor1 = 5; // IR sensor pin Assumption== Pin goes LOW when train detected
    int sensor2 = 6; // IR sensor pin Assumption== Pin goes LOW when train detected
    int led1 = 10;  // Led 1 pin first alternating flasher
    int led2 = 11;  // Led 2 pin first alternating flasher
    int gates_started = 0; // this says if the crossing is active

    int entering_sensor = 5; //this will tell which sensor was triggered first
    int leaving_sensor = 6; // this will tell which sensor shows train leaving
    int flash_state = 0;

    void setup() {
       Serial.begin(9600);
      gate1servo.attach(3);// attaches the servo on pin 3 to the servo object
      gate2servo.attach(4);// attaches the servo on pin 4 to the servo object
      gate1servo.write(gp);//start assuming no train
      gate2servo.write(gp);//start assuming no train
      pinMode(sensor1, INPUT);
      pinMode(sensor2, INPUT);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      digitalWrite(led1, LOW);// Start with all flashers off
      digitalWrite(led2, LOW);
    }

    void loop() {
        if ((digitalRead (sensor1)==LOW)&& (gates_started==0)) {//read sensor 1, if LOW ...do it
            gates_started = 1;
            leaving_sensor = sensor2;
        }
        if ((digitalRead (sensor2)==LOW)&& (gates_started==0)) {//read sensor 2, if LOW ...do it
            gates_started = 1;
            leaving_sensor = sensor1;
        }
        unsigned long currentMillisFLASH = millis();                                                      // get current time stamp, only need one for all if-statements
        if ((unsigned long)(currentMillisFLASH - previousMillisFLASH) >= intervalFLASH) {// time between button presses
           flash_state = ~flash_state;
           digitalWrite(led1, flash_state);                                           //toggle flash_state
          digitalWrite(led2, ~flash_state);
          previousMillisFLASH = currentMillisFLASH;
      }

      unsigned long currentMillisSERVOSTART = millis();                                                     // get current time stamp, only need one for all if-statements
      if ((unsigned long)(currentMillisSERVOSTART - previousMillisSERVOSTART) >= intervalSERVOSTART) {      // time between button presses
        for(gp = gatedown ; gp <= gateup ; gp++) {                                                          // goes from gatedown  degrees to gateup degrees
          gate1servo.write(gp);                                                                             // tell servo to go to gateposition in variable 'gateposition'
          gate2servo.write(gp);

      previousMillisSERVOSTART = currentMillisSERVOSTART;
     }
     Serial.println(gp);
    }
    }


message:
Serial Communication Between Two arduinos (Asking and Receiving)

Can anyone help? I'm trying to develop two sketches, where data can only be sent when a request is made for it between two arduinos. A simple hello world message can suffice. I tried out the Serial Ascii Call and Response on the arduino IDE but it didn't work for me???. Do find below the code sketches

 //Arduino Sketch 1
 uint16_t alpha;
 uint16_t lambo;
 Banana nanas;    //to hold the Banana object
 uint16_t dataArray[2];
 void Setup(){
  Serial.begin(9600);
  establishContact();
 }

 void loop(){
  alpha=nanas.getRad;
  lambo = nanas.getBars;
  dataArray[0] = alpha;
  dataArray[1] = lambo;
  Serial.write((uint8_t*)dataArray, sizeof(dataArray));
  Serial.flush();   //clear the serial port
 }

 void establishContact()
 {
  if (Serial.available())
  {
   while (Serial.available()  > 0)
   {
    int newByte = Serial.read();
    if (newByte == 'Q')
    {
     Serial.write(newByte);
     Serial.flush();
    }
   }
  }
 }

The sketch for the other arduino is shown below

 //Arduino sketch 2
 static char buffer[2];
 void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  establishContact();
 }
 void loop(){
  if(Serial1.available())
  {
   while(Serial1.available() > 0){
    uint16_t gondola1 = Serial1.read();
    uint16_t gondola2 = Serial1.read();
    uint16_t crixus = gondola2 >> 8;
    crixus = (crixus | gondola1);

    gondola1 = Serial1.read();
       gondola2 = Serial1.read();
    uint16_t mario = gondola2 >> 8;
    mario = (mario | gondola1);
    buffer[0] = crixus;
    buffer[1] = mario;
    Serial.write(buffer, sizeof(buffer);
    Serial1.flush();
   }
  }
 }
 void establishContact(){
  if (Serial.available()){
   uint16_t newByte = Serial.read();
   if(newByte == 'Q')
   {
    Serial.flush();
    Serial.write(newByte);
   }
  }
 }

body:
it is not really easy to follow your code but here is a "hello world" procedure to do an on demand data send between two arduinos:

 * upload this code to arduino uno before you make any connection on pins 0 and 1 of the board:

        /**
         * Code for server side (arduino uno)
         */

        uint8_t data2send = 'A'; //data to send on a received request
        uint8_t incomingByte;

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

        void loop() {
                // send data only when you receive data:
                if (Serial.available() > 0) {

                        // read the incoming byte:
                        incomingByte = Serial.read();

                        if(incomingByte=='Q'){  //if incoming data is the expected request (request code = 'Q' in this example)
                                Serial.write(data2send);
                        }
                }
        }

 * connect:

        UNO  | MEGA
        ------------
        pin0 | pin18
        pin1 | pin19
        GND  | GND

 * upload to arduino mega this code:

         /**
         *  code for arduino mega.
         *
         *  proxy between Serial0 and Serial1
         *
         *  send data to Serial0 to forward it to Serial1.
         *  when data is received from Serial1 it will be forwarded to Serial0.
         */

        void setup() {
                // initialize both serial ports:
                Serial.begin(9600);
                Serial1.begin(9600);
        }

        void loop() {
                // read from port 1, send to port 0:
                if (Serial1.available()) {
                        int inByte = Serial1.read();
                        Serial.write(inByte);
                }

                // read from port 0, send to port 1:
                if (Serial.available()) {
                        int inByte = Serial.read();
                        Serial1.write(inByte);
                }
        }

 * open the mega's serial monitor and send some characters. Check that you receive back data only when you send a 'Q' character.


message:
Time Stamping data on an Arduino and reading it on a Java IDE

Does anyone have an idea on the best way to time stamp an arduino sketch that contains a data packet which is to be read out using a java IDE (IntelliJ) for graphic visualization of the packet. I tried declaring the time variable on the arduino section but having problem unpacking the unsigned long variable in java. Below is a snippet of the arduino code.

                 unsigned long codeTime = 0; //The time the sketch takes to execute
             static unsigned long char dataArray [1]; // a variable to hold both sensor data

             void setup(){
                  Serial.begin(9600);
                  Serial1.begin(9600);
              }
             void state1(){
                 if (Serial1.available()){
                        while (Serial1.available() > 0){
                     codeTime = millis(); //using the millis() instead of micros()
                     //memcpy should copy the whole data into position 0 ????
                     memcpy(&dataArray[0], &codeTime,sizeof(codeTime));
                     uint16_t newByte1 = Serial1.read(); // read in the first byte
                     uint16_t newByte2 = Serial1.read(); //read in the second byte
                     uint16_t dataByte = newByte2 >> 8;
                     dataByte = (dataByte | newByte1);
                     dataArray[1] = dataByte;
                     Serial1.write((uint16_t*)dataArray, sizeOf(dataArray));
                     }
                   }
                  }

                void loop(){
                       state1();
                       Serial1.flush();  //clear the serial port
                       delay(100);
                    }

The question now is how do i unpack the data in java to ensure that the time variable (unsigned long time variable is well unpacked in the correct order)????. The second variable i could easily unpack in java as

                  int variable1 = variable2 >> 8; //as it is a 16 bit integer I shifted
                                                  // the msb/lsb accordingly
                  variable1 = (variable1 | variable2);  // and finally casting it.

body:
There's a number of fundamentally wrong things in your sketch.

    static char buffer[1]; // a variable to hold both sensor data

No - that has room for 1 entry - hence the 1. 1 means 1, not 2.

    buffer[1] = newByte;

No. There is no buffer[1]. You count slices from 0.  buffer[0] exists (the first one) but buffer[1] doesn't.

    buffer[0] = millis;

You aren't calling the function, you are assigning the address of the function. And worse than that, `buffer` is an array of 8-bit values - neither the address of the function, nor the return value from the function (if you were to fix that) would fit in that space - since the return value is an `unsigned long` which is 4 bytes in size.

You need to have at least 5 bytes in your array - four for the time stamp and one for the value you read from serial. Then you place them in to the array in the order you see fit, and read them back in the same order in Java.


message:
What is the proper way to send data through http using sim908?

**Preamble**:

I have a `sim908` shield and I'm trying to send some data periodically to a server using `AT commands`.
For every command, I wait for the response to check if everything is working.
Actually the sketch works but, often, I noticed errors during http request.

**State of the art**:

Here it is the sequence of AT commands (not the entire code) into the loop:

1) Check the Network Registration and, if necessary, wait

    AT+CREG?

2) Set params for GPRS connection (no user or password required)

    AT+SAPBR=3,1,"Contype","GPRS"
    AT+SAPBR=3,1,"APN","web.omnitel.it"

3) Get current bearer

    AT+SAPBR=2,1

4) If bearer == 0,0,0,0 (not assigned) get a new bearer

    AT+SAPBR=1,1

5) Init HTTP

    AT+HTTPINIT

6) Set CID and URL

    AT+HTTPPARA="CID",1
    AT+HTTPPARA="URL","www.someurl.com/service.php?p1=1&p2=2"

7) Execute the HTTP command (POST)

    AT+HTTPACTION=1

8) Close HTTP connection

    AT+HTTPTERM

**Question**:

Why HTTP init (step 5) or HTTP posting (step 7) often fails? What is wrong in this procedure? I'm missing something? There is a way to make the procedure more stable?

Thank you in advance :)

**Important update**:

If occurs an error during sending data via HTTP, is a great idea to renew the bearer (step 4)

**Answers to the comments**:

**a)** Shield has an antenna and it works. If I try to disconnect the antenna, code still  search the network (step 1) untill I reconnect the antenna.

**b)** Some times I have this error initializing HTTP (step 5):

> AT+HTTPINIT

> +CME ERROR: 3

Some times I have only "OK" as response posting data (step 7) instead of:

> +HTTPACTION:1,200,xxx

Or this response:

> +HTTPACTION:1,600,0

**c)** I have error at step 4 (AT+SAPBR=1,1) only if I execute the command when I have yet a bearer. The error in this case is:

> AT+SAPBR=1,1

> +CME ERROR: 3

For this reason I do a check (step 3)

body:
You mention two different error messages.

**1. AT+HTTPINIT fail**

You get +CME ERROR 3. Which means "operation not allowed".

This can be due to an improperly closed HTTP setup.
If you get this error (or just always do before setting up), call `AT+HTTPTERM` to be sure that it's closed.

**2. AT+HTTPACTION=1**

I notice you're trying to do a `POST`message, while your variables are in the URL (which is `GET` style afaik).

I've found a source that states you need to call `AT+HTTPDATA` with apropriate values.

> Tell the module that you will be sending 192 bytes of data and it can timeout after 10 seconds of inactivity.

After that, the device will say `DOWNLOAD`, and you can send the `POST` body.

> After this command you get the DOWNLOAD URC then you can type in 192 bytes of data within 10 seconds. The typed data is filled in a local buffer of the module and is not yet posted to the server. In the post body is the multi part form data which contains the necessary headers and data to post a file with name data.txt with 10 bytes of data.
`AT+HTTPDATA=192,10000`

And after that you can send the `POST` message.

> Execute the HTTP POST command so that the buffer contents are POST to
> the server `AT+HTTPACTION=1 OK`

You will get a return message that states the HTTP code (200 'OK') and the amount of bytes received in the return message.

> `+HTTPACTION:1,200,141`
> This URC means that the data was successfully posted to the server and received 141 bytes of data.
> which is the server response to your HTTP POST

You can use `AT+HTTPREAD` to receive these bytes.

> The below command tells the module that we want to read the received data AT+HTTPREAD The below is the data
> received from the server
> +HTTPREAD:141 Successfully dumped 0 post variables. View it at http://www.posttestserver.com/data/2015/10/07/07.41.291690063480 Post
> body was 0 chars long. OK

(Scroll a fair bit down in the source, the first part is on `HTTP GET`: http://www.raviyp.com/embedded/194-sim900-gprs-http-at-commands)

You could also omit this by using `HTTP GET` since it's somewhat easier.

If all else fails, you can set up a `TCP IP` connection with the GSM module and manually set up the HTTP GET/POST message.


message:
What is the best way to get more RAM for a sound buffer?

**The problem:**

How to extend the memory for a sound buffer (intensively used) if:

 1. SD card library supports only one file open at a time (and I have one open already)
 2. EEPROM chips are able to stand about 100,000 write cycles only (see the datasheets!)
 3. I can't find anything else to buy! (a standard and durable RAM chip that loses its content when switched off would be the best).

About the 2nd point. Let's assume that the chip is 64KB and I want to use half of it for a circular sound buffer (it's small, I know). Let's also assume that a standard MP3 song is 160kbps and it's 3.5 min long. Given that, the EEPROM chip (with 100k write cycles limit) in this condirions will reach its limit after 3.2GB of played sound, which is about 762 songs, 44 hours. That can be reached in a single week! Replacing a chip every week is not an option. I'm not a fan of planned obsolescence...

Do you know any chip that will be right for the job? (and can be bought on eBay and it's affordable?)

**Background:**

I have built a WWW-controlled MP3 and online radio player (using ESP8266 and VS1003) and it's working really great, we're using it whole days, but ESP is not fast enough to handle WWW requests and play MP3 at the same time (especially from SD card), so the sound is paused for about 0.5 - 1 sec every time a www page is served (a really small page! Just basic HTML with a title and a list of file links!). SD card content cannot be cached for generating the pages on the fly (not enough heap memory) and two files cannot be opened at the same time by the SD library (one is open for the currently playing file - if not playing an online stream - and I'm currently closing it during reading and sending of requested html page). So I've got two memory problems: 1. serving the www pages and 2. buffering the online stream (usually not needed, most streams can play on my 4KB buffer without a glitch whole day but some of them are jamming very often - depends on the server). I'm thinking about both caching the pages (so I don't have to read them from SD and my music won't be interrupted) and creating a circular buffer (for live streams) in external memory chip. It does not need to keep the data after cutting the power. I've got about 24KB of heap left in my sketch (max) and it can fall even to about 6KB when a single folder's content is loaded to memory. It's not far away from heap overflow... I need to load at least the current folder (with long filenames).

body:
An FRAM chip?

- Non-volatile (though you don't need that)
- SPI or I^2C available on a breakout board from [Adafruit][1]
- Or roll you own from a bare chip, if you're handy with Surface Mount Devices.

  [1]: https://www.adafruit.com/?q=FRAM&


body: A simple SPI SRAM chip. Available up to 128KB, such as the 23LC1024: http://www.microchip.com/wwwproducts/en/23LC1024


message:
Creating date string for error log

Well, googling didn't do much to help me here and I'm shocked that something I can do in two lines of code in C#

    DateTime dateTime;
    string text = dateTime.ToLongDateString();

is this difficult for Arduino, but how do you get a string version of a date time stamp?

I want the current date and time as a string in this format

>  May 4, 2016 17:15:33

Since I can't use any of the C++ includes, like ctime, I'm not sure how to accomplish this.

body:
You need additional hardware like a RTC for example an [DS1307][1] or on the other hand an arduino/shield with ethernet or wifi so you could get the time by [NTP][2] another option might be DCF77 time via the air - sorry forgot GPS could also be used to get the time .... the rest then should be simple creating a string.

  [1]: https://www.adafruit.com/product/264
  [2]: https://en.wikipedia.org/wiki/Network_Time_Protocol


message:
Error loading Blink sketch in esp01 (esp8266)

I have the esp01 connected the serial port using a usb to ttl serial cable and also using the Arduino UNO as suggested in some tutorials. I can execute AT commands. But loading a sketch from Arduino IDE results in error messages show below. If anyone can help, it would be greatly appreciated. Note the error message:

> serialport_receive_C0: F0 instead of C0

    Build options changed, rebuilding all

    Sketch uses 219,211 bytes (50%) of program storage space. Maximum is 434,160 bytes.     Global variables use 31,416 bytes (38%) of dynamic memory, leaving 50,504 bytes for local variables. Maximum is 81,920 bytes.
          /Users/syedtariq/Library/Arduino15/packages/esp8266/tools/esptool/0.4.8/esptool -vv -cd ck -cb 115200 -cp /dev/cu.usbmodem14221 -ca 0x00000 -cf /var/folders/hx/m49nxmvn0799w816ct3tgsjm0000gp/T/build10f6b721887f9efd16f05460daf22810.tmp/Blink.ino.bin
    esptool v0.4.8 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
 setting board to ck
 setting baudrate from 115200 to 115200
 setting port from /dev/tty.usbserial to /dev/cu.usbmodem14221
 setting address from 0x00000000 to 0x00000000
 espcomm_upload_file
 espcomm_upload_mem
    opening port /dev/cu.usbmodem14221 at 115200
 tcgetattr
 tcsetattr
 serial open
    opening bootloader
    resetting board
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: F0 instead of C0
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: F0 instead of C0
    resetting board
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: FF instead of C0
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: F0 instead of C0
    resetting board
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: F0 instead of C0
    trying to connect
 setting character timeout 0
 done
 setting character timeout 1
 done
 espcomm_send_command: sending command header
 espcomm_send_command: sending command payload
 serialport_receive_C0: F0 instead of C0
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed

body:
The problem is related to the Arduino Uno, seems that you haven’t bypassed the Arduino board (since you need to program the esp you should communicate directly with it).
To do this you need to wire the reset pin of Arduino to the ground (also the GPIO1 of esp should be connected to the ground in order to go in programming mode).


message:
error loading an array of strings

I'm trying to have a user enter a series of strings. This is my code.

this is my error message - cannot convert 'String' to 'char*' in assignment

    char* titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

    void setup() {
     Serial.begin(9600);
     Serial.println("Storing numbers in an array");
    }

    void loop()

    {

    for (int x =0; x < 5; x++)
    {
      if (Serial.available() > 0)

      {
       Serial.println("Enter a word... ");
       titles[x] = Serial.readString();

        Serial.println(" ");
        Serial.println(chartitles[x]);

       }
      }
     }

body:
So, you are confusing the object String of Arduino with a string of C (char array), to solve your problem, I've changed your code in two parts:

    String titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

    void setup(){
      Serial.begin(9600);
      Serial.println("Storing numbers in an array");
    }

    void loop(){
      for (int x = 0; x < 5; x++){
        if (Serial.available() > 0){
          Serial.println("Enter a word... ");
          titles[x] = Serial.readString();
          Serial.println(" ");
          Serial.println(titles[x]);
        }
      }
    }

So, in order to use Seria.readString(), you have to use String objects to receive the data from Serial port:

    String titles[]
Instead of:

    char* titles[]
The second change is related to Serial.println(chartitles[x]), I didn't understand what you mean with this code, so I changed in order to print the String that was read.


message:
Why ModBus RTU Master-Slave Dont Work

I have two mega arduino and want to them communicate with modbus rtu together, i use below link circuit for this :
http://www.microcontroller-project.com/rs485-communication-between-arduino-mega-and-arduino-pro-mini.html

but dont work!! while they work in simple rs485 and without modbus with same above link code !?

my code in modbus mode is based on this forum :
https://forum.arduino.cc/index.php?topic=176142.0

MASTER CODE

        //#include <LiquidCrystal.h>

    #include <SimpleModbusMaster.h>

    /*
       The example will use packet1 to read a register from address 0 (the adc ch0 value)
       from the arduino slave (id=1). It will then use this value to adjust the brightness
       of an led on pin 9 using PWM.
       It will then use packet2 to write a register (its own adc ch0 value) to address 1
       on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
    */

    //////////////////// Port information ///////////////////
    #define baud 9600
    #define timeout 1000
    #define polling 200 // the scan rate
    #define retry_count 50

    // used to toggle the receive/transmit pin on the driver
    #define TxEnablePin 2

    #define LED 9

    // The total amount of available memory on the master to store data
    #define TOTAL_NO_OF_REGISTERS 12

    // This is the easiest way to create new packets
    // Add as many as you want. TOTAL_NO_OF_PACKETS
    // is automatically updated.
    enum
    {
      PACKET1,
      PACKET2,
      TOTAL_NO_OF_PACKETS // leave this last entry
    };

    // Create an array of Packets to be configured
    Packet packets[TOTAL_NO_OF_PACKETS];

    // Masters register array
    unsigned int regs[TOTAL_NO_OF_REGISTERS];
    int In22=22;

    // LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup()
    {
      Serial.begin(9600);
    //  Serial1.begin(9600);
    //Serial.begin(speed,9600);
    // lcd.begin(16, 2);
      // Initialize each packet
      modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0, 5, 0);
    //  modbus_construct(&packets[PACKET2], 1, PRESET_MULTIPLE_REGISTERS, 1, 1, 0);

      // Initialize the Modbus Finite State Machine
      modbus_configure(&Serial1, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

      pinMode(LED, OUTPUT);
    }

    void loop()
    {
      modbus_update();

    //  regs[0] = analogRead(0); // update data to be written to arduino slave
    //regs[1] =In22;
    //  analogWrite(LED, regs[0]>>2); // constrain adc value from the arduino slave to 255
    //  regs[1];
     if (Serial1.available()){
    //regs[1]=In22;
    //if(regs[1]==123){
        Serial.println(regs[0]);
        Serial.println(regs[1]);
        Serial.println(regs[2]);
        Serial.println(regs[2]);
    //}
    //  lcd.setCursor(6, 1);
    //    lcd.print(regs[0]);
    //lcd.print("hgftf");پ
     }
      delay(1000);
    //lcd.clear();

    }

SLAVE CODE

    #include <SimpleModbusSlave.h>

    /* This example code will receive the adc ch0 value from the arduino master.
       It will then use this value to adjust the brightness of the led on pin 9.
       The value received from the master will be stored in address 1 in its own
       address space namely holdingRegs[].

       In addition to this the slaves own adc ch0 value will be stored in
       address 0 in its own address space holdingRegs[] for the master to
       be read. The master will use this value to alter the brightness of its
       own led connected to pin 9.

       The modbus_update() method updates the holdingRegs register array and checks
       communication.

       Note:
       The Arduino serial ring buffer is 64 bytes or 32 registers.
       Most of the time you will connect the arduino to a master via serial
       using a MAX485 or similar.

       In a function 3 request the master will attempt to read from your
       slave and since 5 bytes is already used for ID, FUNCTION, NO OF BYTES
       and two BYTES CRC the master can only request 58 bytes or 29 registers.

       In a function 16 request the master will attempt to write to your
       slave and since a 9 bytes is already used for ID, FUNCTION, ADDRESS,
       NO OF REGISTERS, NO OF BYTES and two BYTES CRC the master can only write
       54 bytes or 27 registers.

       Using a USB to Serial converter the maximum bytes you can send is
       limited to its internal buffer which differs between manufactures.
    */

    #define  LED 9

    // Using the enum instruction allows for an easy method for adding and
    // removing registers. Doing it this way saves you #defining the size
    // of your slaves register array each time you want to add more registers
    // and at a glimpse informs you of your slaves register layout.

    //////////////// registers of your slave ///////////////////
    enum
    {
      // just add or remove registers and your good to go...
      // The first register starts at address 0
      ADC_VAL,
      PWM_VAL,
      HOLDING_REGS_SIZE // leave this one
      // total number of registers for function 3 and 16 share the same register array
      // i.e. the same address space
    };

    unsigned int holdingRegs[HOLDING_REGS_SIZE]; // function 3 and 16 register array
    ////////////////////////////////////////////////////////////

    void setup()
    {
      /* parameters(HardwareSerial* SerialPort,
                    long baudrate,
      unsigned char byteFormat,
                    unsigned char ID,
                    unsigned char transmit enable pin,
                    unsigned int holding registers size,
                    unsigned int* holding register array)
      */

      /* Valid modbus byte formats are:
         SERIAL_8N2: 1 start bit, 8 data bits, 2 stop bits
         SERIAL_8E1: 1 start bit, 8 data bits, 1 Even parity bit, 1 stop bit
         SERIAL_8O1: 1 start bit, 8 data bits, 1 Odd parity bit, 1 stop bit

         You can obviously use SERIAL_8N1 but this does not adhere to the
         Modbus specifications. That said, I have tested the SERIAL_8N1 option
         on various commercial masters and slaves that were suppose to adhere
         to this specification and was always able to communicate... Go figure.

         These byte formats are already defined in the Arduino global name space.
      */

      modbus_configure(&Serial1, 9600, SERIAL_8N2, 1, 2, HOLDING_REGS_SIZE, holdingRegs);

      // modbus_update_comms(baud, byteFormat, id) is not needed but allows for easy update of the
      // port variables and slave id dynamically in any function.
      modbus_update_comms(9600, SERIAL_8N2, 1);

      pinMode(LED, OUTPUT);
    }

    void loop()
    {
      // modbus_update() is the only method used in loop(). It returns the total error
      // count since the slave started. You don't have to use it but it's useful
      // for fault finding by the modbus master.

      modbus_update();
    //  holdingRegs[0] = 123; // update data to be read by the master to adjust the PWM
      holdingRegs[1] = 123; // update data to be read by the master to adjust the PWM
        holdingRegs[2] = 123;
    //    holdingRegs[3] = 123;
    //    holdingRegs[4] = 123;
      //  analogWrite(LED, holdingRegs[PWM_VAL]>>2); // constrain adc value from the arduino master to 255
      delay(1000);
      /* Note:
         The use of the enum instruction is not needed. You could set a maximum allowable
         size for holdinRegs[] by defining HOLDING_REGS_SIZE using a constant and then access
         holdingRegs[] by "Index" addressing.
         I.e.
         holdingRegs[0] = analogRead(A0);
         analogWrite(LED, holdingRegs[1]/4);
      */

    }

body:
I even didn't check the Modbus part of your code but the first think what I found:
You are using the D2 pin for LCD and at the same time as TXEnablePin...


message:
Using two ultrasonic sensors together

, how can I enable one before the other?

body:
You need to tell the sensor to send their pulse using the trigger line.  So triggering isn't a problem.
The problem is that you might get an echo returned on both sensors, but you know which sensor sent the pulse so you can ignore the return that was received by the 'wrong' sensor in your code.
So

    While(1)
    {
      SendPulse(SensorTx1);
      GetEcho(SensorRx1);
      SendPulse(SensorTx2);
      GetEcho(SensorRx2);
    }

Is that what you mean?  If not please can you expand you question?


message:
How to turn two LED's on and off with one button?

I was wondering how to write a code that would do this, WITHOUT using IF and ELSE: when the button is pressed, one LED is on and the other one is off, but when the button is not pressed, the LED that was on turns off and the other one turns on.

body:
Just use the return value of `digitalRead` (which is 1 or 0) as the input to `digitalWrite`:

    int btnVal = digitalRead(3);
    digitalWrite(4, btnVal);      // On when button is HIGH
    digitalWrite(5, 1 - btnVal);  // Off when button is HIGH

Or using boolean instead:

    bool btnVal = digitalRead(3);
    digitalWrite(4, btnVal);      // On when button is HIGH
    digitalWrite(5, !btnVal);     // Off when button is HIGH


body: You could do it with only a `switch`/`case` statement. You do not even need to de-bounce the switch.