body:
    int r = 12;
    int g = 11;
    int b = 10;
    int sw = 4;
    int x;
    int c = 0;

    void setup() {
     pinMode(r, OUTPUT);
        pinMode(g, OUTPUT);
        pinMode(b, OUTPUT);
        pinMode(sw, INPUT);
        pinMode(13, OUTPUT);
    }

    void loop() {
     x = digitalRead(sw);
      if(x==HIGH) {
        delay(250);
        c++;
        if(c==1) {
         digitalWrite(r, HIGH);
           digitalWrite(g, LOW);
           digitalWrite(b, LOW);
           {
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
          }

        }
        else if(c==2) {
         digitalWrite(r, LOW);
           digitalWrite(g, HIGH);
           digitalWrite(b, LOW);
                 {
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
          }
        }
            else if(c==3) {
         digitalWrite(r, LOW);
           digitalWrite(g, LOW);
           digitalWrite(b, HIGH);
                 {
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
          }
        }
            else if(c==4) {
         digitalWrite(r, HIGH);
           digitalWrite(g, HIGH);
           digitalWrite(b, LOW);
                 {
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
          }
        }
                else if(c==5) {
         digitalWrite(r, LOW);
           digitalWrite(g, HIGH);
           digitalWrite(b, HIGH);
                 {
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
          }

        }
                else if(c==6) {
         digitalWrite(r, HIGH);
           digitalWrite(g, LOW);
           digitalWrite(b, HIGH);
                 {
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            digitalWrite(13,HIGH);
            delay (250);
            digitalWrite(13, LOW);
            delay (250);
            c=0;
          }

        }

      }
    }

title: Can I short this code?

Answers: 4

body:
    int r = 12, g = 11,b = 10, sw = 4, x, c = 0;

    void setup() {
        pinMode(r, OUTPUT);
        pinMode(g, OUTPUT);
        pinMode(b, OUTPUT);
        pinMode(sw, INPUT);
        pinMode(13, OUTPUT);
    }

    void loop() {
      x = digitalRead(sw);
      if(x==HIGH) {
        delay(250);
        c++;
        if(c==1)      setRGBandBlink13(HIGH,LOW,LOW,1);
        else if(c==2) setRGBandBlink13(LOW,HIGH,LOW,2);
        else if(c==3) setRGBandBlink13(LOW,LOW,HIGH,3);
        else if(c==4) setRGBandBlink13(HIGH,HIGH,LOW,4);
        else if(c==5) setRGBandBlink13(LOW,HIGH,HIGH,5);
        else if(c==6){
          setRGBandBlink13(HIGH,LOW,HIGH,6);
          c=0;
        }

      }
    }

    void setRGBandBlink13(bool newR,bool newG,bool newB,int times){
      setRGB( newR, newG, newB);
      blinkPin13(times);
    }

    void setRGB(bool newR,bool newG,bool newB){
      digitalWrite(r, newR);
      digitalWrite(g, newG);
      digitalWrite(b, newB);
    }

    void blinkPin13(int times){
      for(int i=0;i<times;i++){
        digitalWrite(13,HIGH);
        delay (250);
        digitalWrite(13, LOW);
        delay (250);
      }
    }

body:
I don't have an appropriate circuit handy for testing, but I've condensed the code a bit and renamed some things to be more readable. Hopefully the result is the same! Importantly, I've changed your `c` to `step` and it is now zero-based, so "step 1" is 0 and "step 6" is 5, etc.

    const int rPin = 12;
    const int gPin = 11;
    const int bPin = 10;
    const int swPin = 4;
    const int pin13 = 13; // Needs a better name!
    const int msDelay = 250;

    int step = 0;

 // By pure luck, your patterns overlap, so they can be condensed like so.
 const byte patterns[13] = {
  // 0         1          2          3          4           5
  HIGH, LOW, LOW, HIGH, LOW, LOW, HIGH, HIGH, LOW, HIGH, HIGH, LOW, HIGH
 };

    void setup()
    {
        pinMode(rPin, OUTPUT);
        pinMode(gPin, OUTPUT);
        pinMode(bPin, OUTPUT);
        pinMode(swPin, INPUT);
        pinMode(pin13, OUTPUT);
    }

    void loop()
    {
        if (digitalRead(swPin) == HIGH)
        {
            delay(msDelay);

            // Write red/green/blue pattern
            int index = step * 2;
            digitalWrite(rPin, patterns[index]);
            digitalWrite(gPin, patterns[index + 1]);
            digitalWrite(bPin, patterns[index + 2]);

            // Blink once for each step (0 through 5)
            for (int i = 0; i <= step; ++i)
            {
                digitalWrite(pin13, HIGH);
                delay(msDelay);
                digitalWrite(pin13, LOW);
                delay(msDelay);
            }

            // Increment or reset step
            step = (step < 5) ? step + 1 : 0;
        }
    }

body:
Make all those ints in a single line.

    int r = 12, g = 11,b = 10, sw = 4, x, c = 0;

body:
This Sketch is way shorter and way better to maintain.
Note that 1/3 (26 out of 78) of the lines are comments.

Note:
Your RGB is able to display 8 states, but only 7 can be reached.
binc - c - RGB
 000 - 0 -
 001 - 1 - R
 010 - 2 -  G
 011 - 3 - RG
 100 - 4 -   B
 101 - 5 - R B
 110 - 6 -  GB
 111 - 7 - RGB - NEVER REACHED

    int r = 12;
    int g = 11;
    int b = 10;
    int sw = 4;
    int c = 0;
    int maxC = 6;
    int minC = 0;

    void setup() {
        pinMode(r, OUTPUT);
        pinMode(g, OUTPUT);
        pinMode(b, OUTPUT);
        pinMode(sw, INPUT);
        pinMode(13, OUTPUT);
    }

    // for  (pulses)-times
    // set  (targetPin) HIGH
    // wait (msDelay)
    // set  (targetPin) LOW
    // wait (msDelay)
    void pulse( int targetPin, int msDelay, int pulses ){
     // count to pulses
     // for each count, set targetPin HIGH and LOW
     // wait msDelay between each state change
     for ( int i = 0; i <= pulses, i++ ){
      digitalWrite( targetPin, HIGH );
      delay( msDelay );
      digitalWrite( targetPin, LOW );
      delay( msDelay );
     }
    }

    // int rgbBinary will set RGB according to its binary value.
    // R ~= BIT_1
    // G ~= BIT_2
    // B ~= BIT_4
    void setRGB( int rgbBinary ){
     // set each LED OFF
     // This is by far more performant than
     // checking which should keep its state.
     digitalWrite( r, LOW );
     digitalWrite( g, LOW );
     digitalWrite( b, LOW );

     // if rgbBinary contains BIT value 1, set R to HIGH
     if ( rgbBinary & 1 ) {
      digitalWrite( r, HIGH) ;
     }
     // if rgbBinary contains BIT value 2, set R to HIGH
     if ( rgbBinary & 2 ) {
      digitalWrite( g, HIGH );
     }
     // if rgbBinary contains BIT value 4, set R to HIGH
     if ( rgbBinary & 4 ) {
      digitalWrite( b, HIGH );
     }
    }

    void loop() {
     // INPUT on SW ?
      if ( digitalRead( sw ) == HIGH) {
       // wait 250ms
        delay( 250 );
        // incement c
        c++;
        // increment RGB status
        setRGB( c );
        // pulse OUTPUT 13 (c)-times
        // starting by HIGH
        // delay 250ms between each HIGH/LOW
        pulse( 13, 250, c );
        // reset (c) on maxC
        if ( c == maxC ){
         c = minC;
        }
      }
    }


body:
My C is rusty, so please forgive this simple problem.

This line works:

`Tft.drawString("Test",200,200,2,WHITE); `

But, this has compile errors:

    String yStr = "Test";
    Tft.drawString(yStr,200,200,2,WHITE);

The function in the library:

    void drawString(char *string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor);

The error is **"no known conversion for argument 1 from 'String' to 'char*'"**.

Conclusion - I need a character array. Here's what I am trying to accomplish.

I have two integers that I would like to display on my Tft screen. For example, 225 and 250 to be displayed as "225,250".

I haven't figured out a way to build the char array for the `drawString()` function.

Assistance would be appreciated.

-----------------------------
Thanks for the quick reply Ignacio.
I tried that, but the compiler still doesn't like it.

Here's how I built the string:

    string stringXY ;
    stringXY += xStr;
    stringXY += ",";
    stringXY += yStr;
    Tft.drawString(stringXY.c_str(),200,200,2,RED);

Error: **invalid conversion from 'const char*' to 'char*' [-fpermissive]**

I am apparently using `c_str()` wrong?

title: I need to build a char array from two integers

Answers: 3

body: Put it in a <a href="https://www.arduino.cc/en/Reference/StringObject">`String`</a> and then use the `c_str()` method to get the associated `char*`.

body:
Many thanks to Ignacio.

I changed the function in the library to:

void drawString(**const** char *string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor);

This fixed the problem and gave me more confidence in my vague understanding of C.

body:
Another option in your situation is to not use `String` at all (which is preferrable for reasons I won't explain here) and exclusively use plain old C strings and their associated functions:

    // Define a string buffer to hold the result, ensure it is long enough
    // to hold "N1,N2". An additional char must be added to terminate the string with 0
    char result[15+1];
    unsigned int N1 = ...;
    unsigned int N2 = ...;
    // Format output as desired
    sprintf(result, "%u,%u", N1, N2);
    // Now you can use result with drawString
    Tft.drawString(result, 200, 200, 2, RED);

`sprintf` is a very powerful formatting function that offers you plenty of options.

Note that I took it for granted that your numbers are `unsigned int`; if these were normal `integer` (possibly negative), you should replace `"%u,%u"` with `"%d,%d"`.


body:
I am trying to write a simple program that will cycle through an array using push buttons. My current version of the program uses if statements and prints lines.

My goal is to have contact information for 4 people stored in an array. I can either have an array of strings per person or make different arrays of strings for the different type of information (ie names, phone numbers).

I would like one push button to cycle through the data in one direction and another push button to cycle through the data in the other direction. This is my code so far using the if statements. I modified the code from a traffic light tutorial hence you will see some of the variables named after colors.

    //------------------------------- Declare variables
    int ledPinOne = 2;
    int ledPinTwo = 3;
    int ledPinThree = 4;
    int ledPinFour = 5;
    int buttonPin = 6;
    int state = 0;
    char user_name_array[32];
    char econ_one_name_array[32];
    char econ_two_array[32];
    char econ_three_name_array[32];

    //------------------------------- Setup
    void setup() {
      Serial.begin(9600);
      //------------------------------ Sets pins for I/O
      pinMode(ledPinOne, OUTPUT);
      pinMode(ledPinTwo, OUTPUT);
      pinMode(ledPinThree, OUTPUT);
      pinMode(ledPinFour, OUTPUT);
      pinMode(buttonPin, INPUT);
      Serial.println("ID");
      Serial.println(user_name_array);
    }

    //------------------------------- Main Program
    void loop() {
      if (digitalRead(buttonPin)) {
        if (state == 0) {
          Serial.println("Athlete");
          Serial.println("John Smith");
          Serial.println("No allergies, no medications");
          Serial.println("  ");
          setLights(HIGH, LOW, LOW, LOW);
          state = 1;
        } else if (state == 1) {
          Serial.println("Emergency Contact - Sister");
          Serial.println("Eliza Smith");
          Serial.println("Cell - 333.888.777");
          Serial.println("  ");
          setLights(LOW, HIGH, LOW, LOW);
          state = 2;

        } else if (state == 2) {
          Serial.println("Emergency Contact - Hermosita");
          Serial.println("Jackie Smith");
          Serial.println("Cell - 777.888.7777");
          Serial.println("  ");
          setLights(LOW, LOW, HIGH, LOW);
          state = 3;
        } else if (state == 3) {
          Serial.println("Emergency Contact - Father");
          Serial.println("Michael Smith");
          Serial.println("Cell - 888.777.777");
          Serial.println("  ");
          setLights(LOW, LOW, LOW, HIGH);
          state = 0;
        }
        delay(1000);
      }
    }

    void setLights(int red, int yellow, int green, int blue) {
      digitalWrite(ledPinOne, red);
      digitalWrite(ledPinTwo, yellow);
      digitalWrite(ledPinThree, green);
      digitalWrite(ledPinFour, blue);
    }

I also have a 4-LED setup. When the button is pushed one of the LEDs turns on and then when the button is pushed again it turns off and turns the second one on and so forth.

Thank you in advance for any help.

**EDIT:**

This question was asked again in a more detailed way and has more answers here:

[https://arduino.stackexchange.com/questions/23857/using-a-button-to-cycle-an-array][1]

  [1]: https://arduino.stackexchange.com/questions/23857/using-a-button-to-cycle-an-array

title: Using buttons with Arrays

Answers: 1

body:
Let's just deal with character strings.

The truth of the matter is that Arduino programming uses the language C.  C is very common and you can search for help in many places.

There are several ways to deal with strings in C.  In this example we are using an array of pointers to strings:

    // let's make our own array of strings
    char *states[] = {
        "California", "Oregon",
        "Washington", "Texas"
    };
    int num_states = 4;

    for(i = 0; i < num_states; i++) {
        printf("state %d: %s\n", i, states[i]);
    }

The output of this code looks like:

    state 0: California
    state 1: Oregon
    state 2: Washington
    state 3: Texas

I grabbed this example from [here][1].

added later...

The method "printf" is normally not used in Arduino land.  So that "for" loop would look more like:

    for(i = 0; i < num_states; i++)
    {
     Serial.println("state ");
     Serial.println(i)
     Serial.println(states[i]);
    }

  [1]: http://c.learncodethehardway.org/book/ex10.html


body:
Below is a reference to a logical level bi-directional converter (aka level shifter) I purchased on Ebay.  I've soldered the 12 pins (6 for each piece) to the level shifter so that it fits on my bread board.

http://www.ebay.com/itm/121868205078?_trksid=p2057872.m2749.l2649&ssPageName=STRK:MEBIDX:IT

This may sound trivial, but I'd like to troubleshoot the level shifter with communication both ways (Rx and Tx) to make sure it's working properly.  I've got a constant 4.85v (5V) going to the HV pin, and a constant regulated 3.24V (3.3V) going to the LV pin, along with ground to both GND pins.  Right now, I'm using pin0 (Rx) and pin1 (Tx) on the Arduino Mega 2560.

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

    void loop() {
      delay(1000);
      Serial.println("Test");
    }

How can I test this level shifter without any fancy components?  How could I write a program to toggle an LED both on LV1 and HV1 pins, by modifying the program above?  Please note, that even though the Arduino runs on 5V, I am not using the Arduino as my HV power source.

EDIT (per comment 3 by @Paul):
==================

Test:

 - Burn blank sketch into Arduino
 - Connect 5V (Arduino 5V) to HV pin
 - Connect GND (Arduino GND) to GND pin on same side as HV pin
 - Connect 3.3V to LV pin
 - Connect GND (from 3.3V power source) to GND pin on same side as LV
   pin
 - Connect Arduino Tx pin to channel 1 (HV1)
 - Connect Arduino Rx pin to channel 2 (HV2)
 - Short channel 1 to channel 2 with jumper wire

When all of this is connected, and I open the Serial Monitor on Arduino IDE, anything I type will echo back exactly what I typed.  And when I disconnect one of these jumpers, it doesn't echo back.  So it seems to work.

title: Test level shifter with Arduino and some data

Answers: 2

body:
You don't need to write any program.

First, note that this is (or at least purports to be) an I2C level shifter. This means that it does *not* actively pull up anything; it only actively pulls down. You are supposed to provide pull-ups somewhere in your circuit.

To test it, pull up HV1 and LV1 with 10K resistors to HV and LV respectively; measure the voltage on both sides to verify you are pulling to ~5V and ~3.3V respectively.

Ground HV1, check that LV1 is low.

Ground LV1, check that HV1 is low.

Ta-dah!

body: @paul i have done some but when i connect channel1 to channe2 via jumper wire arduino stop working and text stop coming on serial monitor.


body:
If UNO is supplied with 9VDC to Power Jack.
**Will it supply power to USB** connector?

title: UNO Power supply to USB

Answers: 1

body:
**No**

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

As you can see in the schematic, the USBVCC is only connected (via a MOSFET) to the 5V line, when the voltage on VIN (barrel jack) is LOW.

If you connect 9V to the power jack, the mosfet will turn of, and disconnect the USB power from the 5V on the UNO.

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


body:
My Code is as follows->

    #include <SoftwareSerial.h>

    SoftwareSerial ESP8266(8,9);

    String inData;
    void setup() {
    ESP8266.println("AT");
    delay(1000);
    ESP8266.println("AT+RST");

    }

    void loop() {
     String cmd = "AT+CIPSTART=\"TCP\",\"";
     cmd += "api.thingspeak.com";  // 184.106.153.149 thingspeak IP address
     cmd += "\",80";
     ESP8266.println(cmd);

     if(ESP8266.find("Error"))
     {
       Serial.println("AT+CIPSTART error");
       return;
    }
    String hostt = "GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA";
    hostt += "\r\n";
    hostt += "Host:api.thingspeak.com";
    hostt += "\r\n\r\n\r\n\r\n\r\n\r\n";
    ESP8266.println(hostt);

    cmd = "AT+CIPSEND=";
    cmd += String(hostt.length());
    ESP8266.println(cmd);

    if(ESP8266.find(">")){
    ESP8266.print(hostt);
    }
    else{
    ESP8266.println("AT+CIPCLOSE");
    // alert user
    Serial.println("AT+CIPCLOSE");
    }
    delay(5000);
    }

Is this the write code? Where am I going wrong?
I am not able to see the required fetched data.
Help me with this.

title: How to Capture Data from a Webpage in Arduino and Display it over Serial Monitor of ESP8266?

Answers: 1

body:
There are two basic things you are doing wrong:

Firstly your HTTP request is wrongly formatted.  You have:

    GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA
    Host:api.thingspeak.com

What it should look like is:

    GET /apps/thinghttp/send_request?api_key=689WYA85WW1VJSBA HTTP/1.0
    Host: api.thingspeak.com:80

Also you only need *one* blank line after your request, not 5 as you seem to have.

Secondly you are not actually doing anything with the data the site is sending you. You make the request with `+CIPSEND=` but then the response, which is in the form `+IPD,<len>:<data>` is completely ignored.  You need to use the SoftwareSerial's `.read()` and associated functions to receive that data into the Arduino so you can actually do something with it - like send it down through Serial.

Tips:

* Look for `+IPD,` first
* Read up to the : and interpret it as a number
* You now now how many bytes to read from the data section
* Read that data
* Do something with it


body:
I am trying to make an operating hours counter with arduino, i started with a basic script to make the arduino work as a stop watch, This is my script:

    unsigned long start=0, finish=0, elapsed=0;

     void setup() {
     Serial.begin(9600);
     Serial.println("Clock START");
     }
     void displayResult(unsigned long elapsed){
       float h,m,s,ms;
       unsigned long over;
       h=int(elapsed/3600000);
       over=elapsed600000;
       m=int(over/60000);
       over=over`000;
       s=int(over/1000);
       ms=over00;
       Serial.print("Elapsed time: ");
       Serial.print(h,0);
       Serial.print("h ");
       Serial.print(m,0);
       Serial.print("m ");
       Serial.print(s,0);
       Serial.print("s ");
       Serial.print(ms,0);
       Serial.println("ms");
       Serial.println();
     }

     void loop() {
       start = millis();
       delay(200);
       Serial.println("Start");
       Serial.println("doing Operations and stuff");
       delay(800);
       finish=millis();
       elapsed=finish-start;
       Serial.println("Ended !!!");
       displayResult(elapsed);

     }

Unfortuantly the arduino compiler blocks at the Uploading part, i tried compiling it at first without uploading, it gave me no warning errors. I tried compiling other scripts they worked, it only blocks for this stop watch code.

Thank you for your help

title: Arduino Blocks at Uploading

Answers: 1

body:
There is a bug in early versions of the Mega2560 bootloader.  It crashes on `!!!` (or enters some other special state that stops uploading happening).

Your string that contains `!!!` will be breaking it:

    Serial.println("Ended !!!");

Simple solution: don't use so many exclamation marks.


body: 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.

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

Answers: 2

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

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).


body:
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?

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

Answers: 2

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


body:
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

title: Send Photo with Arduino Uno

Answers: 1

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


body:
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);
     }

title: Parsing using the ArduinoJson library

Answers: 1

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.


body:
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?

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

Answers: 1

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 ;
    }


body:
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

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

Answers: 1

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 :(


body:
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?

title: Arduino Mega pin conflict

Answers: 1

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.


body:
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

Answers: 4

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"

body:
Note the different capitalization: ESP8266**w**i**f**i vs ESP8266**W**i**F**i. Confusing as it may be, these are actually two completely different libraries.

[ekstrand/ESP8266wifi](https://github.com/ekstrand/ESP8266wifi) is a library that is to be used when you are controlling an ESP8266 running the AT firmware over a serial connection from another microcontroller board such as a more traditional Arduino. The code does not run on the ESP8266.

ESP8266WiFi is a library bundled with the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/readme.rst). It is used for controlling the WiFi functionality of the ESP8266 when you are directly programming the ESP8266.

The WebSocket sketch you were attempting to compile was written for use with the latter library. The WebSockets library can not be used with the ekstrand/ESP8266wifi library or generally any configuration that uses the ESP8266 as a WiFi module running the AT firmware.


body: 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.

title: Can Arduino be used as an FDTI Programmer?

Answers: 1

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.


body:
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.

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

Answers: 2

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.


body:
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?

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

Answers: 3

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

body: i know It's a delayed reply .but it might help some one else.The answer is yes. I powered up esp8266 with ardino 3.3V directly and it works fine for me.


body:
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

title: ESP8266 as WiFi for Arduino

Answers: 2

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.


body:
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

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

Answers: 2

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.


body:
Well this was unexpected. [AVR libc][1] has many the variants of `printf`, including `vprintf`, but is missing `vprintf_P`. Is this really just not present or implemented elsewhere?

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html

title: AVR has no vprintf_P?

Answers: 1

body:
It has `vfprintf_P` and `stdout` is a `FILE`. Why would you want to waste time and space with implementing `vprintf_P` as well?

If you _really_ want it, you can make your own:

    #define vprintf_P(...) vfprintf_P(stdout, __VA_ARGS__)

Incidentally, the source code to `vprintf` looks like this:

    int
    vprintf(const char *fmt, va_list ap)
    {
        return vfprintf(stdout, fmt, ap);
    }

That does exactly the same job as a preprocessor macro - just forwards your request on to the FILE-based function.

It is actually more efficient to use a preprocessor macro than needlessly nesting functions like that - less stack usage, less calls, etc (unless the compiler happens to choose to *inline* that function, which since it is in a library it likely won't).

The non-FILE based functions can be considered simple *wrapper* functions to the FILE-based ones. They are mostly provided for convenience, but are actually completely redundant and can all be replaced with direct calls to the FILE-based variant.  They mostly still exist purely for historical compatibility. And since `_P` is specific to AVR libc there is nothing historical for it to be compatible with.


body:
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.

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

Answers: 1

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


body: 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/

title: Three phase sine wave inverter using Arduino

Answers: 1

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.


body: So we have the tone library, which produces a 50% duty cycle square wave of varying frequency, and `analogWrite()` which produces a fixed frequency wave of varying duty cycle. Is there any way to control frequency and duty cycle at the same time on an Atmega328-based board?

title: How to use the timer to generate a pulse wave of the specified frequency and duty cycle

Answers: 0


body:
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

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

Answers: 2

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.


body:
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

title: ESP8266 Arduino 2.2inch ILI9341 TFT library

Answers: 1

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 :)


body:
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

title: Using a button to cycle an array

Answers: 2

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.


body:
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;
    }

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

Answers: 1

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;
    }


body:
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

title: How to monitor a sensor for specific period

Answers: 2

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);
    }
    }


body:
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);
   }
  }
 }

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

Answers: 1

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.