# Question
Title: ESP8266 - CIPSEND & external power supply Hangs program
**Updated**:

I connected my esp to external power, the blue light stays on, I start getting garbage data. I used voltage regulator which was giving 3.4v, power supply tested with 1A & 2A.

**Old problem :**

I have been trying to make ESP8266 since my last semester exams & now 2nd semester exams are going on. So i've been trying to make ESP8266 work for very long time. Earlier it was firmware problem, i updated it.

After a lot it worked. I tried many libraries - but none worked, either some are using specific port or some want specific firmware version which is really hard to find & then flash.

I am using telnet to check. When i disable code to send data - i can send data madly, it works & never hangs up. But as i use `AT+CPISEND` after 1-2 read/write - it stops responding.

I am powering using arduino with/out voltage divider. Its firmware - `0020000903`, `AT Firmware v1.5`, 4mb flash size, I changed baudrate to `9600`.

Below is code i worte : ( I intentionally didn't remove comments)

```
#include <SoftwareSerial.
#define DEBUG true

SoftwareSerial esp8266(9,10); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);

  Serial.begin(9600);
  esp8266.begin(9600); // your esp's baud rate might be different

Serial.print("Sending at..");
  sendData("AT",2000,DEBUG);
  //sendData("AT+RST",2000,DEBUG); // reset module
  sendData("AT+CWMODE=1",1000,DEBUG);
 // sendData("AT+CWLAP",1000,DEBUG);
 //sendData("AT+CIOBAUD=9600",1000,DEBUG);
 //sendData("AT+UART=9600,8,1,0,0",1000,DEBUG);
 //sendData("AT+IPR=9600",1000,DEBUG);
 // sendData("AT+CWJAP_DEF=\"mad\",\"agentis47?orBond?\"",15000,DEBUG);
 //sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
  sendData("AT+CIFSR",1000,DEBUG); // get ip address
  sendData("AT+CIPMUX=1",1000,DEBUG); // configure for multiple connections
  sendData("AT+CIPSERVER=1,80",1000,DEBUG); // turn on server on port 80
}

void loop()
{

  if(esp8266.available()) // check if the esp is sending a message
  {

    while(esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    }

    //Serial.println("IPD Search "+(len));
    if(esp8266.find("+IPD,"))
    {

     delay(20); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     esp8266.read(); //skip the comma ','
     //(CIPMUX=0): + IPD, <len>:
     //(CIPMUX=1): + IPD, <id>, <len>: <data>
     int len = (readUntil(":")).toInt();
     if(len>500) len = 500; //prevent extra data we won't be sending more than 500bytes in one go.
     char data[len];

     esp8266.readBytes(data, len);
     //data[len-2]='\0';

      int pinNumber = (data[0]-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
     pinNumber += ((data[1])-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

       digitalWrite(pinNumber, !digitalRead(pinNumber));
    Serial.println(String(len));

     /*Serial.println("===");

     Serial.println("--");
*/
    //cleanBuffer();
    //delay(10);
     //Serial.println("Sendddiddding data");
     //sendData(connectionId,String("OK"));
     //Serial.println("Sent");
     //closeConnection(connectionId);

     //digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

     // make close command
     //String closeCommand = "AT+CIPCLOSE=";
     //closeCommand+=connectionId; // append connection id
     //closeCommand+="\r\n";

     //sendData(closeCommand,1000,DEBUG); // close connection
    }
  }
}

void cleanBuffer(){
  while(esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      Serial.write(c);
    }
}

String sendData(int connectionId, String data){
  //Serial.println("AT+CIPSEND="+String(connectionId)+ ","+String(data.length()));
  //sendData("AT+CIPSEND="+String(connectionId)+ ","+String(data.length()),1000,DEBUG);
  //sendData(data,100,DEBUG);
  //closeConnection(connectionId);
  String webpage = "<h1>Hello</h1>&lth2>World!</h2><button>LED1</button>";

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     webpage="<button>LED2</button>";

     cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id

     sendData(closeCommand,3000,DEBUG);

 /*
  Serial.println("finding prompt");
  if(esp8266.find(">"))    //prompt offered by esp8266
  {
    Serial.println("Sending data");
   // Serial.println("found > prompt - issuing GET request");  //a debug message
    esp8266.println(data);  //this is our http GET request
  }
  else
  {
    closeConnection(connectionId);
    Serial.println("No '>' prompt received after AT+CPISEND");
  }
*/
}

String closeConnection(int connectionId){
    sendData("AT+CIPCLOSE="+String(connectionId),100,DEBUG);
}

String readUntil(String delimiter){
  String response = "";
  char c;
  unsigned int dLen = delimiter.length(),n=0;

    while(esp8266.available()&&(c= esp8266.read())){
      n= (c==delimiter[n])?n+1:0;
      if(n==dLen) break;
      response+=c;
    }
   return response;
}

void sendRaw(String data){
esp8266.print(data);
}

String sendCommand(String command){
  esp8266.print(command); // send the read character to the esp8266
  esp8266.print("\r\n");
  esp8266.flush();
}

String sendData(String command, const int timeout, boolean debug)
{
    String response = "";
    esp8266.print(command); // send the read character to the esp8266
    esp8266.print("\r\n");
    esp8266.flush();
    long int time = millis();

    do
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }while( (time+timeout) > millis());
    if(debug)
    {
      Serial.print(response);
    }
    return response;
}

```

Please help, I am stuck, Is there any other cheaper & better solution ? I am only looking for Wifi.

# Answer
If you are powering it using Arduino 3.3V pin it is no wonder it does not work. ESP8266 uses more power than Arduino can provide. Power pin on arduino is about 50ma. ESP8266 in receive or send mode uses much more and either halts or restarts.

A table of ESP8266 power consumption can be found here
> 1 votes

---
Tags: serial, esp8266
---


# Question
Title: Connection problem with Arduino Mega 2560 and GSM shield ( official M10)
As I don't want to stack the shield over the mega 2560 board, I try to connect only the pins that used for GSM communication. Here are my connection:

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

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

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

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

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

Code I used is from the Examples library, GsmScanNetworks:

```
#include <GSM.h>

// PIN Number
#define PINNUMBER "8888"

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

// Save data variables
String IMEI = "";

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

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

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

  // connection state
  boolean notConnected = true;

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

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

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

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

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

}

```

Questions:

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

EDIT:

GSM shield link

Note for using GSM shield with Mega

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

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

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

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

# Answer
I have done this, and had (some limited) success.

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

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

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

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

---
Tags: arduino-mega, gsm
---


# Question
Title: How would I refactor this code, given how similar most of the lines are?
I have a set of buttons and a set of NeoPixel LEDs. There's lots of very similar constants (`button1pin`, `button2pin`, etc) so there's almost certainly a more efficient way of coding this.

Any ideas?

```
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);

// Buttons
const int button1pin = 3;
const int button2pin = 4;
const int button3pin = 5;
const int button4pin = 6;
const int button5pin = 7;
const int button6pin = 8;
const int button7pin = 9;
const int button8pin = 10;
const int button9pin = 11;

const int led1 = 0;
const int led2 = 1;
const int led3 = 2;
const int led4 = 3;
const int led5 = 4;
const int led6 = 5;
const int led7 = 6;
const int led8 = 7;
const int led9 = 8;

void setup() {
  strip.begin();
  strip.show();

  pinMode(button1pin, INPUT_PULLUP);
  pinMode(button2pin, INPUT_PULLUP);
  pinMode(button3pin, INPUT_PULLUP);
  pinMode(button4pin, INPUT_PULLUP);
  pinMode(button5pin, INPUT_PULLUP);
  pinMode(button6pin, INPUT_PULLUP);
  pinMode(button7pin, INPUT_PULLUP);
  pinMode(button8pin, INPUT_PULLUP);
  pinMode(button9pin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(button1pin) == LOW){
    strip.setPixelColor(led1, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button2pin) == LOW){
    strip.setPixelColor(led2, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button3pin) == LOW){
    strip.setPixelColor(led3, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button4pin) == LOW){
    strip.setPixelColor(led4, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button5pin) == LOW){
    strip.setPixelColor(led5, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button6pin) == LOW){
    strip.setPixelColor(led6, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button7pin) == LOW){
    strip.setPixelColor(led7, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button8pin) == LOW){
    strip.setPixelColor(led8, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button9pin) == LOW){
    strip.setPixelColor(led9, strip.Color(20, 55, 0, 0));
  }

  strip.show();
}

```

# Answer
> 0 votes
```
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);
// The maximum pin number for the buttons
const int MaxButton = 11;
// The value if the pin is not connected to an LED
const int NotConnected = -1;
// The connections from buttons to leds.
const int Connections[MaxButton+1] = {NotConnected, NotConnected, NotConnected, 0, 1, 2, 3, 4, 5, 6, 7, 8};

void setup()
{
  strip.begin();
  strip.show();
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        pinMode(pinNumber, INPUT_PULLUP);
    }
  }
}

void loop()
{
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        if (digitalRead(pinNumber) == LOW)
        {
            strip.setPixelColor(Connections[pinNumber], strip.Color(20, 55, 0, 0));
        }
    }
  }
  strip.show();
}

```

I can't test it, so I have no idea if it works, but it should do.

---
Tags: arduino-uno, adafruit, code-optimization
---


# Question
Title: What does this error mean?? Arduino Due loop warning
I am getting this error on compilation of the code given further below;

> warning: iteration 3u invokes undefined behavior \[-Waggressive-loop-optimizations\]
>
> leds\[XY (x, y)\].r = redarray\[x\]\[y\];
> note: containing loop for(uint8\_t x=0; x \< MatrixWidth; x++){

Code:

```
 // the header files for the RGB data

#include <FastLED.h>
#include "redarray.h"
#include "greenarray.h"   //g data header file (hex or dec)
#include "bluearray.h"   //b data header file (hex or dec)*/

 //matrix parameters

#define MatrixWidth 36 //columns (x)
#define MatrixHeight 1 //rows (y)
#define numled (MatrixWidth * MatrixHeight)

//pin details

#define datapin 7

#define clockpin 8

CRGB leds[MatrixWidth * MatrixHeight];

const bool  MatrixSerpentineLayout = true;

void setup() {

   FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
   FastLED.clear();
         }

void loop() {
   for(uint8_t y=0 ; y<1 ; y++){
     for(uint8_t x=0; x < MatrixWidth; x++){
         leds[XY (x, y)].r = redarray[x][y];
         leds[XY (x, y)].g = 0;
         leds[XY (x, y)].b = 0;

         FastLED.show();
         delay(50);
     }
   }
 }

  uint16_t XY( uint8_t x, uint8_t y)
  {
      uint16_t i;

      if( MatrixSerpentineLayout == true) {
          if( y & 0x01) {
          // Odd rows run backwards
          uint8_t reverseX = (MatrixWidth - 1) - x;
          i = (y * MatrixWidth) + reverseX;
    } else {
         // Even rows run forwards
         i = (y * MatrixWidth) + x;
    }
}
   return i;
}

```

The following is redarray header -

//RED const byte redarray\[3\]\[36\] PROGMEM = { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}

};

How to remove this warning. The redarray is not being read properly by arduino. THe above code should make the 36 LEDs turn off (black) as per the header file. They are randomly lit red... I am totally perplexed!

Plz help if somebody can. Thanks!

# Answer
`MatrixWidth` is 36. `redarray[]` has 3 elements. The compiler has detected that your code will likely blow up on the 4th go through the loop. Make sure your code is accessing the dimensions correctly.
> 2 votes

---
Tags: arduino-due, rgb-led
---


title: split serial.readString() output

text:
# Question
Title: split serial.readString() output
I'm trying to read a string like this one:

```
2;12;42;43;34

```

over a serial connection and split this string afterwards by a ";". So the output would be this array:

```
(2,12,42,34)

```

All the stuff runs on an arduino uno. So I made some code:

```
String read_input;
char read_input_char[20];
char *read_values;

void setup() {

  Serial.begin(9600);
  Serial.setTimeout(10);

}

void loop() {
  if(Serial.available()){
    read_input = Serial.readString();
    read_input.toCharArray(read_input_char, 20);

    read_values = strtok(read_input_char, ";");
    Serial.println(read_values[2]);
  }
}

```

However now instead of outputting the 3rd array element it outputs only an '1'. What's wrong?

# Answer
This is a C question, not an arduino question, but anyway:

From the man page:

```
DESCRIPTION
   The  strtok()  function  breaks a string into a sequence of zero or more nonempty tokens.  On the first call to strtok() the
   string to be parsed should be specified in str.  In each subsequent call that should parse the  same  string,  str  must  be
   NULL.

```

You are only calling `strtok()` once, so it only parses the first value. You need to keep calling it until there is nothing left to parse.
> 2 votes

# Answer
Your code as is checks for a non-empty Serial buffer (the Serial.available() bit), and then reads it all into a String. Be careful doing this, as if this happens to execute part-way through the data arriving, you will get a partial data String. This may be cut off part way through one of your integers.

Also, the String object is very memory-intensive. Maybe not an issue for you, but try to use char arrays, or read directly from the Serial buffer.

In your case, there is a great function that you could use; parseInt().

Details are at; https://www.arduino.cc/en/Serial/ParseInt

More or less, this reads successive chars from the serial buffer, and once digits are encountered, forms an int. This continues until a non-digit char, or a (configurable) timeout. Something like this might do the job for you;

```
int data[10]; // Or however long you need it to be!
int arrayPointer = 0;

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

void loop() {
  if (Serial.available()) {
    int incomingInt = Serial.parseInt();
    Serial.println(incomingInt);
    data[arrayPointer] = incomingInt;
    arrayPointer++;
  }
}

```

Hope this helps!
> 1 votes

---
Tags: serial
---


# Question
Title: Need Help with Switch Case commands/receiver and lcd screen project?
I am doing a project with a receiver and transmitter and i am trying to get a message to print onto the screen. If anybody has any experience with this could you please help! I am trying to use a switch case command and it's not working. **Edit:**

\`

```
#include <LiquidCrystal.h>
#include <VirtualWire.h>
LiquidCrystal lcd(12, 8, 5, 4, 3, 2);
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
void setup()
{
  Serial.begin(9600);
  Serial.println("Device is ready");

  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  lcd.begin(16, 2);

  // Print a message to the LCD.
}

void loop()
{
  if (vw_get_message(message, &messageLength)) // Non-blocking
  {
    switch(message[1])
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("O.O");
      break;
    case 1 :
      lcd.setCursor(0, 1);
      lcd.print("Hi! :)");
      break;
    }
    {
      Serial.print("Received: ");
      for (int i = 0; i < messageLength; i++)
      {
        Serial.write(message[i]);
      }
      Serial.println();
    }
  }
}

```

# Answer
> 1 votes
Too many pieces of the puzzle are missing for us to venture a guess on what is going wrong:

* The output you get (both in the LCD and the serial console)
* The message sent

One thing that strikes me as a potential problem is the

```
switch(message[1])

```

line. If you want to check the first character received, it should be

```
switch(message[0])

```

That said, it would perhaps help you if you tried to split the program into pieces and make sure each one works before advancing to the next. Are you sure the LCD pin connections and initialisation line match? (I know from experience it is very easy to mess up and put the pin numbers in the wrong order). It would help to put the following code right after the lcd.begin line (in your setup() function):

```
  lcd.setCursor(0, 0);
  lcd.print("Initialised!");

```

Now if this line doesn't display correctly, you will know it is the lcd connection/initialisation code that is at fault. Otherwise, you will concentrate on your communication code.

Give us more information and we 'll be able to help more.

---
Tags: programming, arduino-nano, lcd
---


title: Electric interference from cnc spindle

text:
# Question
Title: Electric interference from cnc spindle
I've got a CNC machine and I recently started using a spindle for it. At first it was running smoothly with no issues, but after the first brush pair wore off (I've replaced them later on) it started interfering with the Arduino/gshield and pc monitor. The monitor displays a "no signal" message, although after turning off the spindle or turning it to a low speed the signal comes back. The other problem is that after running a long job, sometimes the gshield disconnects and the job stops midway.

* What part could be causing all this interference?
* How can I shield that part so it stops interfering with other electronics?

I am using the following hardware:

* 600 watt spindle
* 600 watt power supply with variable speed
* the wires from the spindle to the power supply are not shielded, although Ive tried covering them with aluminium foil, not sure if that should be of any benefit, I've read it somewhere so I gave it a try.
* Gshield with Arduino, connected to a Raspberry pi.

All the electronics are within 70 cm radius.

# Answer
> 0 votes
I would guess that arcing in the spindle causes spikes that travel through the power supplies and power wires. One thing you could try is to use a really long extension cord (say 15 meters or more) to power the spindle power supply. You can insert this cord to a different power outlet to gain additional distance.

---
Tags: motor, electronics
---


title: Getting RGB values from camera

text:
# Question
Title: Getting RGB values from camera
I have a camera I'm planning on attaching to an arduino uno, that I want to take pictures and extract the average RGB value from each image.
This is the camera I have, but I've now realized that it takes pre-compressed JPEG images, and so I cannot make use of the data it's giving me.

I realize that an arduino is not the optimal tool to use in this case, but I'm curious as to whether there would be any way to decompress the images and convert them to a format I could use. It does not need to be fast, and I do not need to take the pictures quickly. I have experience with programming but have not done many projects with the arduino, so any help or advice is appreciated.

# Answer
No. The Arduino (or not the "normal" Arduinos) doesn't have enough memory to decompress JPEG.

I made a JPEG decompressor for chipKIT boards the other day, and it uses the absolute bare minimum memory possible, and still comes it at close to 128kB. Far more than any "normal" Arduino board.

You can possibly do it with one of these new-fangled Linux-based Intel boards that are being sold as Arduino these days, but they are not your normal run-of-the-mill Microcontroller but closer to a Raspberry Pi.

Speaking of which, the Raspberry Pi is probably a much better choice than any Arduino board for the kind of thing you are trying to do.
> 1 votes

---
Tags: arduino-uno, programming, data-type
---


# Question
Title: How can I maintain PWM output while still performing other tasks?
I want to generate a PWM signal that I can turn on and off with a button press without using interrupts. Is there a way to keep the PWM output going while running other processes?

# Answer
> 4 votes
PWM just runs once started. It's all managed by a completely separate bit of silicon inside the chip.

Once you have done `analogWrite(...)` the PWM will just keep going until you tell it otherwise.

---
Tags: pwm
---


title: Error saying an included library is not

text:
# Question
Title: Error saying an included library is not
The IDE tells me the included library isn't? I tried restarting the IDE and my computer but it doesn't work. The other libraries work fine it's only with Keyboard that it fails.

My code:

```
#include <Keyboard.h>

int buttonState = 0;

void setup() {
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);

  Keyboard.begin();
}

void loop() {
  buttonState = digitalRead(2);
  if (buttonState == HIGH) {
    digitalWrite(13, HIGH);
    Keyboard.press('A');
  } else {
    digitalWrite(13, LOW);
    Keyboard.releaseAll();
  }
}

```

Error log:

```
Arduino: 1.6.8 (Windows 10), Board: "Arduino/Genuino Uno"

D:\Documents\Test\Test.ino: In function 'void setup()':

Test:9: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
   Keyboard.begin();

   ^

D:\Documents\Test\Test.ino: In function 'void loop()':

Test:16: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
 Keyboard.press('A');

 ^

Test:19: error: 'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?
     Keyboard.releaseAll();

     ^

exit status 1
'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

```

# Answer
> 4 votes
I see you are using an Arduino Uno.

An Arduino Uno cannot act as a USB keyboard - therefore the Keyboard library doesn't exist for it (the file Keyboard.h is seen as being empty).

You can only use Keyboard.h on boards where using Keyboard.h makes any kind of sense, such as the Leonardo.

---
Tags: arduino-uno, library
---


# Question
Title: Enabling keyboard feature on Arduino with CH340G
I've seen here that it is possible to enable keyboard feature on Arduino Uno so it can emulate a keyboard (send keystrokes to computer) like the Leonardo. They do it by updating ATmega16U2 firmware. But I bought a cheap arduino clone that uses CH340G instead of this chip. Is there any way to do the same with this chip? Can this even work on standard arduino uno?

# Answer
> 2 votes
No. That chip can only act as a USB-UART bridge. You could use V-USB to turn the ATmega328P into a low-speed USB device, but the Arduino IDE has no support for that.

---
Tags: arduino-uno, usb, keyboard, atmega16u2
---


# Question
Title: Using Blynk to control stepper motor is jerky
I am using Blynk to try and control a 28byj-48 stepper motor using the ULN2003 driver and an Arduino UNO from my iphone via USB withe the iOS Blynk App.

Without using Blynk, my stepper is smooth and works fine:

```
  #include <Servo.h>
  #include <Stepper.h>

  const int stepsPerMotorRevolution = 32;  //No of steps per internal revolution of motor,
  const int stepsPerOutputRevolution = 32*64; //no of steps per revolution of the output shaft
  const int motorpin1 = 8;                    //Assign motor  pins to Arduino pins
  const int motorpin2 = 9;                    //
  const int motorpin3 = 10;                   //
  const int motorpin4 = 11;                   //

  // initialize the stepper library on pins 8 through 11, Motor rev steps, initialise firing sequence 1-3-2-4
  Stepper myStepper(stepsPerMotorRevolution, motorpin1,motorpin3,motorpin2,motorpin4);

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

  void setup() {
    myStepper.setSpeed(600);
  }

  void loop(){
     myStepper.step(-500);
  }

```

But when I use Blynk, the stepper is so jerky and stutters terribly:

```
  #include <SoftwareSerial.h>
  SoftwareSerial SwSerial(10, 11);
  #define BLYNK_PRINT SwSerial
  #include <BlynkSimpleSerial.h>
  #include <Stepper.h>

  const int stepsPerMotorRevolution = 32;  //No of steps per internal revolution of motor,4-step mode
  const int stepsPerOutputRevolution = 32*64; //no of steps per revolution of the output shaft
  const int motorpin1 = 8;                    //Assign motor pins to board pins
  const int motorpin2 = 9;                    //
  const int motorpin3 = 10;                   //
  const int motorpin4 = 11;                   //

  // initialize the stepper library on pins 8 through 11, Motor rev steps, initialise firing sequence 1-3-2-4 blah blah
  Stepper myStepper(stepsPerMotorRevolution, motorpin1,motorpin3,motorpin2,motorpin4);
  char auth[] = "my auth key here";

  void setup(){
    SwSerial.begin(9600);
    Blynk.begin(auth);
    myStepper.setSpeed(600);
  }

  BLYNK_WRITE(1){
    myStepper.step(param.asInt());
  }

  void loop(){
    Blynk.run();
  }

```

I am using a slider on the app to control the stepper by the way. I am not sure what I am doing wrong, any suggestions?

# Answer
Blynk runs over a network and therefore cannot respond in real-time nor consistently. You could have the Blynk slider control set a local variable which the motor controller would use for motor speed, but the basic motor-drive timing needs to be locally controlled and independent of network operations. The SimpleTimer library is one way; a timer interrupt would be another.
> 1 votes

# Answer
My guess would be you are suffering from a comms latency issue.

1. Are you using a local server or the cloud?
2. Is you iOS device connected over WIFI or 2G, 3G or 4G?
3. Is you device on the same subnet as you iOS device and local server?

I've never used blynk (I might do this weekend though), my best thought as to how to fix it would be to revise your approach. When you are controlling devices over an unpredictable connection (Ethernet) you can't rely of messages to arrive in a certain order or at certain times. You need to tell the device to do something and keep doing it until its done or its told to stop.
So in this case tell the device to rotate clockwise at a certain rate until it travels n degrees or it is told to stop. Now you can't just tell the motor to make 20 turns, because that will make your app unresponsive. What you need to do it tell it to turn 50 steps and then return to the control loop, if no new order has come in it should then go and do another 50 steps, if there is a new order then off it goes with the new task.

Hope that makes sense and helps.
> 0 votes

---
Tags: arduino-uno, stepper
---


title: BMP280 sensor not initializing

text:
# Question
Title: BMP280 sensor not initializing
I am successfully using a BMP280 sensor via SPI connection with an Arduino Uno R3 board. I'm trying to run the same code with the same setup on an Arduino Ethernet. However the sensor is not initializing.

The setup function looks as follows:

```
void setup() {
    delay(1000);
    dht.begin(); // starts DHT sensor
    chk = dht.read(DHTPIN); // reads DHT status
    while ((!bmp.begin()) || (chk != 1) ) {
      // checks DHT and BMP status and shows red LED, in case one of them
      // wasn't found. Loops and resets timeout each time.
      wdt_reset();
      Serial.println("Could not find a valid sensor, check wiring!");
      digitalWrite(RED, HIGH);
      delay(300);
      digitalWrite(RED, LOW);
      delay(1000);
      chk = dht.read(DHTPIN);
    }
}

```

The code only returns the error message and does not initialize the BMP sensor (DHT is fine).

Full code:

```
#include "ThingSpeak.h"
#include <SPI.h>
#include <DHT.h>
#include <Ethernet.h>
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xE5, 0xBF};
IPAddress ip(10,42,0,69);
EthernetClient client;

// --- Libraries --- //
#include <avr/wdt.h> // Watchdog, interrupts and reboots
#include <Adafruit_BMP280.h> // BMP library for BMP280

// --- Constants --- //
// DHT22
#define DHTPIN 7
// BMP280 (SPI)
#define BMP_SCK 13 // Serial clock pin for BMP (10k pullup to +5V)
#define BMP_MISO 12 // SDO, has 10k pullup
#define BMP_MOSI 11 // SDI, no pullup
#define BMP_CS 9 // CS, has 10k pullup
// LEDs
#define RED 5 // pin for LEDs
#define YELLOW 3
#define GREEN 2

unsigned long myChannelNumber = 115634;
const char * myWriteAPIKey = "***"; // removed for privacy reasons
float dht_temp;
float dht_hum;
float bmp_temp; // values from sensors
float bmp_press;
int chk; // DHT status (0 or 1)
int k; // counter variable
int number;
char COLOR;

// --- Initialization --- //
DHT dht(DHTPIN, DHT22); // initializes sensors
Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK);

void setup() {
  wdt_disable(); // disables watchdog for initial communication
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
  pinMode(YELLOW, OUTPUT); // LED pins set as output
  pinMode(RED, OUTPUT);
  digitalWrite(YELLOW, HIGH); // starts yellow LED
  Serial.begin(9600); // begin serial connection with 9600 baud
  delay(500); // delay to get connection and sensors ready
  wdt_enable(WDTO_8S); // start watchdog timeout (4 sec might be too short)
  blink(RED, 3);
  Serial.println(bmp.begin());
  dht.begin(); // starts DHT sensor
  chk = dht.read(DHTPIN); // reads DHT status
  if ((!bmp.begin()) || (chk != 1) ) {
    // checks DHT and BMP status and shows red LED, in case one of them
    // wasn't found. Loops and resets timeout each time.
    wdt_reset();
    Serial.println("Could not find a valid sensor, check wiring!");
    digitalWrite(RED, HIGH);
    delay(300);
    digitalWrite(RED, LOW);
    delay(1000);
    chk = dht.read(DHTPIN);
  }
  Ethernet.begin(mac, ip);
  ThingSpeak.begin(client);
}

// --- Loop --- //
void loop() {
  wdt_reset(); // resets watchdog
  pinMode(GREEN, OUTPUT); // gets green LED ready
  digitalWrite(GREEN, LOW);
  delay(1600); // delay for sensors to be read. In total, at least 2 sec!
  dhtread();
  delay(5000);
  wdt_reset();
  bmpread();
  ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
  delay(5000);
  wdt_reset();
  delay(5000);
}

void blink(char COLOR, int number) {
  for (k = 1; k <= number; k = k + 1) {
    // blinks 3x to show that Arduino rebooted
    digitalWrite(COLOR, HIGH);
    delay(100);
    digitalWrite(COLOR, LOW);
    delay(100);
  }
}

void bmpread() {
  bmp_temp = bmp.readTemperature(); // reads BMP sensor
  bmp_press = bmp.readPressure();
  Serial.println(bmp_temp);
  Serial.println(bmp_press);
  if (bmp_press > 0.0) {
    // if sensor isn't attached, it shows 0.0 or negative pressure.
    // This is used as check criterion
    digitalWrite(GREEN, HIGH); // blinks green for good BMP values
    Serial.println("bmp ok");
    ThingSpeak.setField(3,bmp_temp);
    ThingSpeak.setField(4,bmp_press);
    delay(150);
    digitalWrite(GREEN, LOW);
  } else {
    // if pressure is 0.0 or negative, blink red
    // and print 0.0 to keep formatting
    digitalWrite(RED, HIGH);
    Serial.println("Error, BMP280 missing");
    delay(150);
    digitalWrite(RED, LOW);
  }
}

void dhtread() {
  chk = dht.read(DHTPIN); // checks if connection to DHT sensor is ok (0: no connection, 1: ok)
  if (chk == 1) {
    dht_temp = dht.readTemperature();
    dht_hum = dht.readHumidity(); // reads DHT sensor
    digitalWrite(GREEN, HIGH); // blinks once for successful DHT sensor values
    ThingSpeak.setField(1,dht_temp);
    ThingSpeak.setField(2,dht_hum);
    delay(150);
    digitalWrite(GREEN, LOW);
    delay(100);
  } else {
    // if no connection, blink red instead and print "nan"
    // (keeps formatting ok)
    digitalWrite(RED, HIGH);
    Serial.print("Error, DHT22 missing");
    delay(150);
    digitalWrite(RED, LOW);
    delay(100);
  }
}

```

The problem now is that it seems to initialize (`bmp.begin()` returns 1), but the sensor is still not reading a correct value (either 0.0 for both pressure and temperature, or a large negative pressure and very large temperature (-2602 Pa, 185°C). What might be the problem? I have tried it with another sensor of the same type, same result. Where else can I attach the CS wire to?

# Answer
> 1 votes
The software must be OK, because it runs on the other board, so it has to be a hardware fault. The sensor is OK, because it works on the other board. Assuming the board isn't defective then it must be the way you have connected it.

You haven't included your pin designations. Some Ethernet shields use certain pins and prevent them being used by other devices. Is it possible that this could be the cause of you problems?

---
Tags: sensors, c++, ethernet, spi
---


# Question
Title: Arduino Mousecontroller library doesn't work
I am working on a project with the Mousecontrol library. This causes me a lot of problems with loading the library. I imported the library but it gives me errors everytime. I think it is a mistake in the library folders but I can't seem to figure it out.

```
#include <MouseController.h>

// Initialize USB Controller
USBHost usb;

// Attach mouse controller to USB
MouseController mouse(usb);

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

void loop(){
  usb.Task();
}

void mouseMoved() {
  Serial.print("Move: ");
  Serial.print(mouse.getXChange());
  Serial.print(", ");
  Serial.println(mouse.getYChange());
}

```

I get this error:

```
Arduino: 1.6.0 (Mac OS X), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)"

In file included from /Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/MouseController.h:22:0,
                 from Muis_Bevrijding.ino:1:
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In member function 'virtual void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint32_t, uint32_t, uint32_t, uint32_t, const USB_ENDPOINT_DESCRIPTOR*)':
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:62: error: 'UOTGHS_HSTPIPCFG_PTYPE_INTRPT' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                              ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:93: error: 'UOTGHS_HSTPIPCFG_PTOKEN_IN' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:151: error: 'UOTGHS_HSTPIPCFG_PBK_1_BANK' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: error: there are no arguments to 'UHD_Pipe_Alloc' that depend on a template parameter, so a declaration of 'UHD_Pipe_Alloc' must be available [-fpermissive]
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: note: (if you use '-fpermissive', G++ will accept your code, but allowing the use of an undeclared name is deprecated)
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In member function 'virtual uint32_t HIDBoot<BOOT_PROTOCOL>::Release()':
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:500:54: error: there are no arguments to 'UHD_Pipe_Free' that depend on a template parameter, so a declaration of 'UHD_Pipe_Free' must be available [-fpermissive]
  UHD_Pipe_Free(epInfo[epInterruptInIndex].hostPipeNum);
                                                      ^
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In instantiation of 'uint32_t HIDBoot<BOOT_PROTOCOL>::Release() [with unsigned char BOOT_PROTOCOL = 2u; uint32_t = long unsigned int]':
Muis_Bevrijding.ino:22:1:   required from here
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:500:54: error: 'UHD_Pipe_Free' was not declared in this scope
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h: In instantiation of 'void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint32_t, uint32_t, uint32_t, uint32_t, const USB_ENDPOINT_DESCRIPTOR*) [with unsigned char BOOT_PROTOCOL = 2u; uint32_t = long unsigned int]':
Muis_Bevrijding.ino:22:1:   required from here
/Users/jamiederooij/Downloads/Arduino.app/Contents/Resources/Java/libraries/USBHost/src/hidboot.h:474:178: error: 'UHD_Pipe_Alloc' was not declared in this scope
   pipe = UHD_Pipe_Alloc(bAddress, epInfo[index].deviceEpNum, UOTGHS_HSTPIPCFG_PTYPE_INTRPT, UOTGHS_HSTPIPCFG_PTOKEN_IN, epInfo[index].maxPktSize, 10, UOTGHS_HSTPIPCFG_PBK_1_BANK);
                                                                                ^

```

Thanks a lot for your time!

# Answer
> 1 votes
> # USBHost
>
> ### Compatible with Arduino Due only

source

---
Tags: library, mouse
---


title: Why ModBus RTU Master-Slave Dont Work

text:
# Question
Title: Why ModBus RTU Master-Slave Dont Work
I have two mega arduino and want to them communicate with modbus rtu together, i use below link circuit for this : http://www.microcontroller-project.com/rs485-communication-between-arduino-mega-and-arduino-pro-mini.html

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

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

MASTER CODE

```
    //#include <LiquidCrystal.h>

#include <SimpleModbusMaster.h>

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

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

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

#define LED 9

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

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

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

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

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

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

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

  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();

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

}

```

SLAVE CODE

```
#include <SimpleModbusSlave.h>

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

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

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

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

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

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

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

#define  LED 9

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

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

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

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

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

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

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

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

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

  pinMode(LED, OUTPUT);
}

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

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

}

```

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

---
Tags: arduino-mega, rs485, modbus
---


title: AVR-STL Library

text:
# Question
Title: AVR-STL Library
I have a project that I need to use a vector, I have tried to get several libraries to compile with out luck. The one that has gotten the closest is Andy Brown's AVR-STL. I keep getting the error:

```
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: redefinition of 'void* operator new(size_t, void*)'

```

I am sure that this is a simple fix, I just have no idea how. If this library is no longer viable then can someone else recommend another one?

Here is the code I am trying to compile

```
#include "Arduino.h"
#include "iterator"
#include "vector"
#include "pnew.cpp"

std::vector<int> test;

void setup(void) {

    Serial.begin(57600);
}

void loop(void) {

    test.push_back(1);
    Serial.println("Pushed");
}

```

And the full output:

```
14:57:27 **** Incremental Build of configuration Release for project MegaTesting ****
"C:\\Eclipse\\eclipse\\arduinoPlugin\\tools\\make\\make" all
'Building file: ../.ino.cpp'
'Starting C++ compile'
"C:\Eclipse\eclipse\arduinoPlugin\tools\arduino\avr-gcc\4.8.1-arduino5/bin/avr-g++" -c -g -Os -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10606 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR     -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\cores\arduino" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\variants\mega" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL" -I"C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL\utility" -MMD -MP -MF".ino.cpp.d" -MT".ino.cpp.o" -D__IN_ECLIPSE__=1 -x c++ "../.ino.cpp"  -o  ".ino.cpp.o"   -Wall
cc1plus.exe: warning: C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL\utility: not a directory [enabled by default]
In file included from C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/stl_iterator_base.h:38:0,
                 from C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/iterator:40,
                 from ../.ino.cpp:8:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h: In static member function 'static void _TrivialIterator_concept_specification<_TrivialIterator>::_TrivialIterator_requirement_violation(_TrivialIterator)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h:572:16: warning: typedef '__T' locally defined but not used [-Wunused-local-typedefs]
     value_type __T;
                ^
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h: In static member function 'static void _Allocator_concept_specification<_Alloc>::_Allocator_requirement_violation(_Alloc)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/concept_checks.h:799:39: warning: typedef '_Tp' locally defined but not used [-Wunused-local-typedefs]
   typedef typename _Alloc::value_type _Tp;
                                       ^
In file included from ../MegaTesting.ino:3:0,
                 from ../.ino.cpp:14:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp: In function 'void* operator new(size_t, void*)':
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: redefinition of 'void* operator new(size_t, void*)'
 void* operator new(size_t size_,void *ptr_){
       ^
In file included from ../.ino.cpp:10:0:
C:\Eclipse\eclipse\arduinoPlugin\packages\arduino\hardware\avr\1.6.10\libraries\AVR-STL/pnew.cpp:12:7: error: 'void* operator new(size_t, void*)' previously defined here
 void* operator new(size_t size_,void *ptr_){
       ^
subdir.mk:24: recipe for target '.ino.cpp.o' failed
make: *** [.ino.cpp.o] Error 1

14:57:28 Build Finished (took 600ms)

```

# Answer
It looks like `new` is redefined. I see that you include `cpp` file, that contains *implementation* \- this is rather unfortunate design, but that's how it is done.

Anyway, it seems that this file is already being compiled elsewhere. Have you tried to remove this include? What happens if you remove it?

Apart from that problem, you must be aware that dynamic memory management in such small system yelds risk of memory fragmentation that eventually leads to failed allocations.
> 1 votes

---
Tags: arduino-mega, vector
---


title: How did I burn out this ESP8266 unit?

text:
# Question
Title: How did I burn out this ESP8266 unit?
ESP8266 -\> FTDI -\> USB Mac

I followed the wiring on this page: http://williamdurand.fr/2015/03/17/playing-with-a-esp8266-wifi-module/

I was communicating with it via Serial at 115200. I issued a `AT+UART_DEF=9600,8,1,0,0` and a few seconds later I looked over and it was smoking.

I bought 2 of these. The previous one I had wired to an Arduino Nano running through a logic level converter. That one only returns `Exception (28)` over and over again after issuing that same command.

On both units `AT+GMR` returned:

```
AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0

```

Are these units too hard to use? What did I do to burn it out?

\[UPDATE\]

Answer given was that I fed it 5v instead of 3.3v. Obvious. I didn't think I did but I checked the output of the FTDI and sure enough it was 5.1v. So why does the output on it say 3V3 ? I thought that meant that it was 3.3v...

Should have checked it first.

# Answer
You supplied 5V to a device that only takes up to 3.6V. Heat generated by the excessive power did the rest.
> 2 votes

# Answer
I checkmarked Ignacio's answer because it was correct. But I wanted to leave an answer also as to HOW I supplied 5v when I thought I was supplying 3.3v. Maybe it will help someone else.

The backside of this FTDI module has a jumper to select 3.3 or 5v and the default is set to 5v. I needed to cut the default trace line connecting to 5v and solder my own jumper to switch it to 3.3v. I should have double checked the voltage before powering it up. New ESP01's on order.
> 0 votes

---
Tags: esp8266
---


# Question
Title: Different sensor readings on analog input when connected via USB to self-contained/externally powered
I am building up an electricity monitor using the ACS712 hall effect sensor. I have tested and built the circuit having the Arduino (Nano) connected via USB to my laptop, and have tested/debugged etc., getting expected results.

I've migrated the circuit to be powered from an external 5v power supply via the VIN pin (details—this is not a "wallmart"-style supply). It is supplying a solid 5.01v across the circuit according to multimeter readings—I've tested at multiple points in the circuit. The 5v supply is rated at 700mA, so plenty of head room. The ACS712 is deriving it's power directly from the supply, not the Arduino 5v pin.

I'm running a "calibration" routine that takes readings from the ACS712 (which is measuring AC current) to find the "zero" point (where the AC signal crosses over), which should be the value of half VCC with this sensor—see ACS712 sensor reading for AC current for more detail/background on this. Usually this hovers around 512 (as expected—in the test unit I'm getting 547 when connected to an AC supply).

When I run/test this circuit with the USB connected, I get expected results. When I remove the USB, the calibration routine returns a much higher value (about 650 in the test units) and resultant readings are therefore incorrect. The laptop/test computer is not connected to a power supply during these tests.

When the USB is connected, there is no difference in reading across the VIN, 5V or sensor power pins, so the circuit seems to continue working from the external 5V source. However, I have noted that the 5v output pin on the Arduino drops to about 3.95v when run off the power supply alone, vs 4.7v when powered by USB/both.

When I repeat this test by connecting an external USB power supply to the Arduino USB port (i.e. no serial connection, and removing the laptop from the equation) I get the same results (a higher calibration value and strange readings).

I've read that the analog pin is referenced to the 5V voltage. This suggests that I should be connecting the ACS712 VCC pin to the Arduino 5V—is this the case? (Given the whole circuit is powered from the same power supply, this seemed unnecessary to me, but I'm still pretty new to this whole thing.) The ACS is very sensitive to input voltage fluctuations, so I assumed that I'd be better powering it directly and not relying on the Arduino.

Given that I'm supplying a 5v input, should I be switching from the VIN to the 5v pin? (something I've read you can do, and that the VIN should be for 7v+ supply input only).

Is there anything else that could be causing this discrepancy?

For reference, the calibration and read routines are reproduced below.

```
#define SENSOR_PIN A0
#define ACS_MVPA (100)

double _numSamples = 0;
double _ampsRMSSum = 0;

int16_t acs712Calibrate() {
  uint8_t numReadings = 100;
  int16_t vals[numReadings];

  // collect a sample of readings
  for (uint8_t i=0; i<numReadings; i++) {
    vals[i] = constrain(analogRead(SENSOR_PIN), 0, 1023);
  }

  // Freq doesn't need to be 1024 wide, as the max val
  // from the ACS712 will be limited subset.
  // 20A = 100mV/A = 20*100mV/1000 = ~2v max voltage range
  // 2v / 1024 = 0.0048828125v per increment = ~410 potential increment values
  uint8_t freq[512]{0};
  uint8_t offset = 250;
  // count the frequency of specific readings
  for (uint8_t i=0; i<numReadings; i++) {
    freq[vals[i]-offset]++;
  }

  // work out the most frequent value
  // note that if there is a tie, the lowest value will be used
  uint8_t maxFreq = 0;
  int16_t modeVal = -1;
  for (int i=0; i<512; i++) {
    if (freq[i] > maxFreq) {
      maxFreq = freq[i];
      modeVal = i;
    }
  }

  modeVal = modeVal + offset;

  return modeVal;
}

void avgRead() {
  //debugSerial.println("_sample()");
  // see https://arduino.stackexchange.com/questions/19301/acs712-sensor-reading-for-ac-current for description

  int rVal = 0;
  unsigned long rSquaredSum = 0;

  // 50hz = 20 milliseconds per wavelength
  // if we measure for 100ms we will get 5 cycles
  // 60hz = 16.66667 milliseconds per wavelength, or just over ~6 cycles
  // from what I can tell, either should be sufficient for our purposes
  int sampleDuration = 100;       // 100ms

  // each logical "sample" is actually made up of a 100ms sample
  // for our internal arithmatic, we need to track the number of internal samples
  // not to be confused with _numSamples which tracks the number of times _sample()
  // is called between _log()
  int sampleCount = 0;

  // take samples for 100ms
  uint32_t startTime = millis();
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(SENSOR_PIN) - _config.acs712Zero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum/sampleCount)/1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // in the case of the 20A component is 100 mv/A
  double ampsRMS = voltRMS * (1000/ACS_MVPA);

  _numSamples++; // update the overall sample count
  // add this reading to the summed total(which is averaged before logging)
  _ampsRMSSum += ampsRMS;
}

```

# Answer
In preparing this question, I realised that the answer may lay in the statement "I've read that the analog pin is referenced to the 5V voltage. This suggests that I should be connecting the ACS712 VCC pin to the Arduino 5V—is this the case?"

That made sense to me, so I modified the circuit so that the ACS712 runs off the 5v pin, and I'm now getting around 510 (which is as expected) as a calibration value.

Have tested with both USB connected and unconnected and getting a consistent result.
> 0 votes

---
Tags: sensors, power, usb
---


title: Digital Pin State - Some 1, Some 0

text:
# Question
Title: Digital Pin State - Some 1, Some 0
I'm running a sketch that looks for inputs to digital pins 3, 4, 5, 6, and 7. The gist of the sketch is that it's a digitalRead() from 3-7 with a Serial.println() to the monitor. The odd thing is that without any pins connected I'm seeing "0" on some and "1" on others. I there a reason some will be "0" while other are "1" without anything connected? I imagine that all pins should read "0" until voltage is detected.

Based on my limited experience I draw the conclusion that a pull-up resistor will likely resolve my problem. Thoughts?

# Answer
Yep, in fact I would configure them as INPUT\_PULLUP (which uses a built-in resistor), unless you are actually wiring pull up resistors of your own to them.

Also the Digital pins Tutorial has a bit more info on the modes possible.
> 2 votes

# Answer
The effect you are seeing is the result of floating pins.

Because the inputs are not at any defined voltage level and will 'follow' the voltage applied. So leaving them unconnected with no defined state will make it look as if its picking up stray signals.

Adding a pull-up resistor, or a pull-down resistor will give you a known state, the value can be anything from 4.7kohms to 100kohms. So your conclusion to use a resistor is correct.
> 2 votes

---
Tags: arduino-uno, digital, pull-up
---


# Question
Title: problem in integrating the slave code in attiny 84
I tried the whole process by using two arduino unos.It worked perfectly. Though when i tried to replace the slave uno with attiny 84 uC it showed following errors in compiling.

```
Arduino: 1.6.7 (Windows 7), Board: "ATtiny24/44/84, ATtiny84 @ 1 MHz  (internal oscillator; BOD disabled)"

WARNING: Category '' in library ArduinoJson is not valid. Setting to 'Uncategorized'
C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void setup()':

sketch_may12c:12: error: 'SPCR' was not declared in this scope

   SPCR |= bit (SPE);

   ^

In file included from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/WProgram.h:12:0,

                 from C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/Arduino.h:4,

                 from sketch\sketch_may12c.ino.cpp:1:

sketch_may12c:12: error: 'SPE' was not declared in this scope

   SPCR |= bit (SPE);

                ^

C:\Users\LEGEND\AppData\Local\Arduino15\packages\tiny\hardware\avr\1.0.0\cores\tiny/wiring.h:158:25: note: in definition of macro 'bit'

 #define bit(b) (1UL << (b))

                         ^

sketch_may12c:15: error: 'MISO' was not declared in this scope

   pinMode (MISO, OUTPUT);

            ^

sketch_may12c:22: error: expected unqualified-id before '.' token

   tinySPI.attachInterrupt();

          ^

C:\Users\LEGEND\AppData\Local\Temp\arduino_8a75bcb6a2713182a57eb1014198ceb3\sketch_may12c.ino: In function 'void SPI_STC_vect()':

sketch_may12c:30: error: 'SPDR' was not declared in this scope

 byte c = SPDR;  // grab byte from SPI Data Register

          ^

exit status 1
'SPCR' was not declared in this scope

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

```

# Answer
> 1 votes
You are trying to compile the wrong program for the wrong chip.

The nice thing about the Arduino core library is that it enables you to write code that is portable across various Arduino boards. However, this library provides very limited access to the capabilities of the underlying hardware. Then, it is quite common for users to mix Arduino code with C statements that directly access the hardware registers. Doing this provides full control over the hardware, at the cost of reduced portability.

Just an example from your code:

```
SPCR |= bit (SPE);

```

This line is accessing the control register of the SPI port (SPCR means “SPI Control Register”) in order to set to 1 the bit named SPE (for “SPI Enable”). This is the “bare metal” way of turning on the SPI port.

Now, your problem is that, unlike the ATmega328P powering your Unos, the ATtiny84 does *not* have a hardware SPI port. Thus the line above just makes no sense.

The solution: you have to figure out some other means for your chip to talk SPI. You could emulate it purely in software, but it would certainly be more efficient to use the USI port. The USI (“Universal Serial Interface”) is a multipurpose serial port found in many ATtinies. It can be configured to do SPI, I2C or simplex/half-duplex UART.

Recommended readings:

You may be able to find ready-made libraries for doing this.

---
Tags: arduino-uno
---


title: My Arduino is heating up

text:
# Question
Title: My Arduino is heating up
I am working on a simple Arduino project where I am controlling 5 TowerPro servos. I read that each takes up 2.2 V each so that means the Arduino can only handle about 2 , if using 5V. So far Ive connected 4 with no issues but when I added the 5th the whole thing stopped and the 5V regulator was really hot. That means I don't have enough power and the Arduino is just having a hard time giving not enought volts for all five servos. I just don't know what to do now. Ive tried adding 3 3V battery packs instead of the Arduino but it was smoking. Is there another way to provide the right amount of power for 5 servos without breaking or burning anything!

# Answer
> 2 votes
The voltage regulator on the Arduino is designed to power the logic circuits, and perhaps a few LEDs and other digital devices. It is not designed to power 5 motors.

You haven't specified what *current* they draw - that is the important question, not the voltage.

As the comments under your question have said, you need to power the motors separately from the Arduino, not *through* it. However, connect the *ground wires*, and use the Arduino to control the signal wire to the servos.

The graphic below shows the general idea. For 5 servos even those batteries are probably not enough.

Notice that the power for the motor does not go through the Arduino.

---
Tags: motor, heat, servo
---


title: Arduino Memory Best Practice

text:
# Question
Title: Arduino Memory Best Practice
So I have been diving deep into AVR programming and have seen several different ways of defining constants. I know that some of these methods are from "C" and others are from more modern "C++" methods. So my question here is what is the preferred method?

Method 1:

```
#define MAX_ARRAY_LEN 3

int my_array[MAX_ARRAY_LEN] = {1, 2, 3};

```

Method 2:

```
const int MAX_ARRAY_LEN = 3;

int my_array[MAX_ARRAY_LEN] = {1, 2, 3};

```

In my searches online I have ran across several pages that mention using PROGMEM in the declarations to load the variable into Flash memory instead of SRAM. The thing I am unclear about using PROGMEM is what should be loaded into Flash and what should be loaded into SRAM? Should I be loading all const into Flash? Are there any performance hits using Flash?

## **Edit**

I guess I was not clear on what I was asking. I understand that #define and PROGMEM are not related. My question is there are a couple of methods that can be used to define constants. One is #define (Method 1) and the other is const (Method 2), with the const type comes the PROGMEM, when using Method 2 there are now 2 areas where you can store variables, Flash and SRAM so when do you want to use PROGMEM and when do you want to just leave it, when using method 2? Is there any performance hits when reading from Flash vs SRAM?

I understand that when using method 2 it is now scoped and typed, but are there any other advantages? Are the programs smaller using one vs the other? Are there times that you would want to use one over the other?

# Answer
> 4 votes
(Duplicate of this.)

In your example, neither definition of `MAX_ARRAY_LEN` will use program space nor RAM. If you were to *use* the definition somewhere, it will certainly use program space in the instruction that uses that constant:

```
for (int i=0 i<MAX_ARRAY_LEN, i++)
  Serial.print( my_array[i] );

```

In this case, a CPU instruction will load the constant 3 into a register. So you can say that the 3 "used" a byte in the CPU instruction, and is part of the program size. Most people ignore that, because a loading a *variable* into `i` uses both RAM and program space.

The primary advantage of using `const` instead of `#define` is that the former allows additional compiler type-checking.

C++ has introduced another keyword, `constexpr`, which tells the compiler that an entire expression can be evaluated at compile time and reduced to a single constant value. Read all about it here.

To answer your comment, #define's are not stored anywhere. They are a simple string substituion that happens before the compiler processes the C++ code.

When you build your sketch, the source files are processed in several phases. First, there's a preprocessor phase that consumes all the lines that start with '#'. The results of the preprocessing are sent to the C++ compiler. The compiler will see *all* the included files *inline*, and all #define's will be substituted.

## UPDATE

For example, `#define XXX 3` will cause the preprocessor to replace all occurrences of `XXX` in the C++ file with `3`. The C++ compiler will never see `XXX`, it only sees `3`. You could do a search and replace with your editor, and the C++ compiler would not know the difference. (Well, there are a few more tricks the preprocessor can do for you, but you only asked about defining a numeric constant.) The generated code would be identical.

There is no "global space" for `#define` symbols. There is a "dictionary" in the preprocessor that is used to perform the substitution, but that is ephemeral.

PROGMEM is not related to `#define` or `const` at all. It is an attribute of a variable that indicates it is to be stored in FLASH, not RAM. I think the key is that `#define` is just string substitution, but `const` is a C++ attribute of a C++ variable. All of these are equivalent:

```
#define MAX_ARRAY_SIZE 3
const uint8_t maxArraySize = MAX_ARRAY_SIZE;
int array[ maxArraySize ] = { 1,2,3 };

#define FOO 1,2,3
int array[] = { FOO };
const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

#define MAX_ARRAY_SIZE goofyNameThatMeansNothing
const uint8_t MAX_ARRAY_SIZE = 3;
int array[ MAX_ARRAY_SIZE ] = { 1,2,3 };

#define BAR = { 1,2,
int array[] BAR,3};
#define MAX_ARRAY_SIZE sizeof(array)/sizeof(array[0])

```

I hope that last 2 goofy examples help illustrate what a `#define` is... string substitution.

The PROGMEM attribute is a separate *thing*. It can only be added to C++ variables, and it now requires the variable to also be `const`. Extending the above, you could do this:

```
#define MAX_ARRAY_SIZE 3
const uint8_t maxArraySize = MAX_ARRAY_SIZE;
const int array[ maxArraySize ] PROGMEM = { 1,2,3 }; // a flash array, not RAM

#define FOO 1,2,3
const int array[] PROGMEM = { FOO };
const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

#define MAX_ARRAY_SIZE goofyNameThatMeansNothing
const uint8_t MAX_ARRAY_SIZE = 3;
int array[ MAX_ARRAY_SIZE ] PROGMEM = { 1,2,3 };

#define BAR PROGMEM = { 1,2,
const int array[] BAR,3};
#define MAX_ARRAY_SIZE 14

```

Again, in that last goofy example I used PROGMEM in the `#define BAR`, but it's just some characters as far as the `#define` is concerned. And the last define is just plain wrong, but it will compile.

Because there is no validation of a string substitution, it is usually better to use a `const type var = value;` that can be validated by the compiler, both when it is defined and again when `var` is used in some context.

## UPDATE 2

You say,

> with the const type comes the PROGMEM

Not really. `const` is the "read-only" attribute, and the compiler enforces that.

PROGMEM tells the AVR compiler that, **if storage is required for this variable**, put it in FLASH memory (a special address range) instead of RAM (a different address range). Because of the AVR architecture, you must access FLASH differently, with special instructions. The `avr.pgmspace.h` include file has some routines (macros and inline assembler) for reading from those address spaces.

I emphasized the "storage space required", because the compiler can optimize away the storage. The literal 3 constant `MAX_ARRAY_LEN` does not need any storage space. For this example program:

```
const int MAX_ARRAY_LEN PROGMEM = 3;

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

  Serial.println( MAX_ARRAY_LEN );
}

void loop() {}

```

This is the generated code:

```
  Serial.println( MAX_ARRAY_LEN );
156:    50 e0           ldi r21, 0x00   ; 0
158:    63 e0           ldi r22, 0x03   ; 3
15a:    70 e0           ldi r23, 0x00   ; 0
15c:    82 e2           ldi r24, 0x22   ; 34
15e:    92 e0           ldi r25, 0x02   ; 2
160:    f7 c2           rjmp    .+1518  ; 0x750 <_ZN5Print7printlnEii>

```

The compiler knows that storage is not required. The value "3" is pushed directly onto the stack at program location 0x158. It did not go to RAM nor FLASH (PROGMEM) to load a 3 into a register, and then push that register's value onto the stack.

The compiler knows the value, so it uses the "immediate" form of the instruction to push the 3.

However, for this program:

```
const int MAX_ARRAY_LEN PROGMEM = 3;

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

  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
}

void loop() {}

```

The following code is generated:

```
  e4:   03 00           .word   0x0003  ; ????
     .
     .
     .
  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
 158:   50 e0           ldi r21, 0x00   ; 0
 15a:   64 ee           ldi r22, 0xE4   ; 228
 15c:   70 e0           ldi r23, 0x00   ; 0
 15e:   82 e2           ldi r24, 0x22   ; 34
 160:   92 e0           ldi r25, 0x02   ; 2
 162:   b5 c2           rjmp    .+1386      ; 0x6ce <_ZN5Print7printlnEji>

```

Because I took the address of MAX\_ARRAY\_LEN, the compiler knew that it had to have storage... in order for it to have an address. The compiler dutifully locates it in the program space, at 0xE4. You can see that address being pushed onto the stack at 0x15A.

Without the PROGMEM attribute, the following code is generated:

```
  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
 156:   50 e0           ldi r21, 0x00   ; 0
 158:   60 e0           ldi r22, 0x00   ; 0
 15a:   72 e0           ldi r23, 0x02   ; 2
 15c:   84 e2           ldi r24, 0x24   ; 36
 15e:   92 e0           ldi r25, 0x02   ; 2
 160:   b5 c2           rjmp    .+1386      ; 0x6cc <_ZN5Print7printlnEji>

```

This is a RAM address, 0x200. Long before setup, a 3 is copied from the program space into RAM. It is using both program space *and* RAM.

But this is only because I took the address of MAX\_ARRAY\_LEN. In almost all cases, you will be using these as scalar values. The compiler will not allocate any storage space for them, and the PROGMEM attribute is irrelevant.

You have another question:

> Is there any performance hits when reading from Flash vs SRAM?

Yes. Reading from flash takes twice as many CPU cycles. It's always a juggling act. If you need to squeeze every cycle out, make sure your constants do not even need storage space (i.e., don't take their address). And if it's a PROGMEM array or structure, consider using a cached value (i.e., loaded into a RAM array or structure). Sometimes you don't have a choice. If you are out of RAM, you will have to load them from PROGMEM every time you need them, with a small penalty. RAM, SPEED, SIZE... pick two.

---
Tags: variables, memory
---


title: millis() in a millisecond stopwatch

text:
# Question
Title: millis() in a millisecond stopwatch
I'm making a stopwatch that will measure time between two points.

I want that stopwatch to have a millisecond accuracy.

After the start when someone touch the pad it will show like the time of the touch (15.359) 15 seconds and 359 millis.

I have an arduino uno board. Everywhere I read it says that millis its not reliable, and in a feel tests it seems not very accurate. Also a lot of places say to use a RTC, but every RTC I found and read about it seem to use only second and not milliseconds. Others say to use a 32 KHz crystal, but I'm not sure if it will fix this. Could anyone give some ideas?

The Arduino will only record time, only that, start and get time and subtract and write on the serial and end.

Thanks! **update 1:** thanks Mattia for the edit.

**update2 :** I was making some math, and if the device is on for 8 hours, and i want millisecond precision i need something like 30ppb right? Would this do the job? http://www.digikey.com/product-detail/en/abracon-llc/AOCJYR-12.800MHZ-M5649LF/535-12624-1-ND/4989030

# Answer
The resonator on the Arduino Uno is better than the internal oscillator of the Atmega328p, but still not very precise. Therefore, for accurate measurements, you need to use a better quality crystal. For instance @ 16 MHz. Once you set the correct prescaler in the Arduino, this should give you accurate millis() - as long as the crystal that you're using is accurate.
> 1 votes

---
Tags: time, millis
---


# Question
Title: Detect if multiple variables are the same?
I'm setting a series of variables with: `uint32_t currentLedColor[9]`

What I'd like to check is if certain ones of those are the same.

Basically want to say `if currentLedColor[0] and currentLedColor[1] and currentLedColor[2] are equal`

How would I write that?

# Answer
> 1 votes
You run multiple checks. For example:

```
if (currentLedColor[0] == currentLedColor[1] && currentLedColor[0] == currentLedColor[2]) {
    // do something
}

```

---
Tags: arduino-uno, programming
---


# Question
Title: Can the Arduino interface with USB devices without the USB host shield?
I'm looking to connect various USB-devices to an Arduino Uno (specifically, a gamepad and a webcam, but I'm interested in the general case). Is this possible without using the USB host shield, since the Uno has a USB port and USB-to-serial converter? I could use the shield, but I'm curious if/why it's neccessary.

The Sparkfun website states that:

> The SparkFun USB Host Shield contains all of the digital logic and analog circuitry necessary to implement a full-speed USB peripheral/host controller with your Arduino.

Does the Arduino not already contain this, just needing the proper software (although obviously it's easier to use the already written library for the Host Shield). Or are there hardware limitations?

According to Can a Ethernet USB Dongle be instead of ethernet shield for arduino? (Majenko's answer), it can, in theory, be done with the Due, but not with the Uno. In that case, is this because the Uno uses the ATmega16U2 instead of the FTDI FT232RL for USB communication?

# Answer
First things first you need to learn the basics of how USB works.

In USB there are two main "things": Hosts and Devices.

You have one Host (usually your computer) and many Devices (such as Arduinos, Printers, Scanners, Webcams, WiFi dongles, etc).

Being a host involves knowing about what devices you are going to have attached to you and how to communicate with them. Being a device means just communicating with the host in your own way.

As you can see it is a far more complex job being a host than being a device.

Arduinos are devices. The small USB interface chips they use are very low powered and can only be a device, never a host.

If you want to plug a device into something it has to be a host (note: I am purposely ignoring hubs here).

The Arduino Due uses a far more powerful chip, and that is capable of being a host (using what is known as On-The-Go mode).

To do it with anything less powerful than a Due you require additional hardware that is specifically designed to be a USB host - and that is where the USB host shield comes in. It has a chip that is designed specially to be a USB host so you can plug a device in to it.

None of the chips on the Uno are designed to be a host. They just don't have the power.
> 18 votes

# Answer
No. USB strictly distinguishes between host and device roles. A few chips have functional blocks capable of performing either role, but the 8u2/16u2 are not examples of this.

Typical USB serial converters like the FT232, CP210x, CH340, PL2303, etc are also strictly devices and incapable of being hosts

There are inexpensive host-capable MCUs like the Kinetis KL25Z, but to use them in their cheapest form you would need a different software approach (for example mbed rather than Arduino) and a lot more personal effort. The Teensy-LC is related, but you pay more for the Arduino code loading helper on it than for the MCU that runs your program itself.
> 4 votes

---
Tags: usb
---


title: How to store a function in a constant?

text:
# Question
Title: How to store a function in a constant?
I'm trying to do something to this affect:

`const string first_color = strip.Color(0, 60, 0, 0);`

With the intended outcome being that I could use `first_color` wherever I'd have used `strip.Color(0, 60, 0, 0)` before.

# Answer
> 1 votes
You pretty much need a helper function to do that; a small local function that calls `strip.Color()` with the intended arguments and returns `strip.Color()`'s return value if there is any.

```
int first_color(void)
{
   return(strip.Color(0, 60, 0, 0));
}

```

(assuming `strip.Color()` returns an `int`) which you would call with:

```
value = first_color();

```

If `strip.Color()` is a `void` function, then delete the 'return(' and one ')', fix the definition of first color to be `void` instead of `int`, and of course, don't try to use any return value from `first_color()`.

# Answer
> 0 votes
It sounds like you might want a preprocessor macro:

```
#define FIRST_COLOR strip.Color(0, 60, 0, 0)

```

And then later

```
FIRST_COLOR;

```

This is basically just text substitution at the initial stage of the compilation process. It is somewhat conventional to make macros all caps, but not required. You can also define function-like macros which take arguments.

---
Tags: arduino-uno, adafruit, neopixel
---


# Question
Title: How to use an Arduino Uno + Keyboard Firmware to make a "N Key Rollover" Game Pad
Hello I have flashed my Arduino Uno with USB keyboard firmware from this tutorial http://mitchtech.net/arduino-usb-hid-keyboard/#comment-6786, and I have been successful sending individual key presses but, not when trying to press an hold a key. I am attempting to use this firmware to create a custom Game Pad to USB adapter, the only issue is sending simultaneous keystrokes (not sending them one at a time). If you know how to accomplish this task I would be very happy. The technical term for this is "Key Rollover"

# Answer
> 0 votes
After closer research on this topic I have found the answer to my problem but,thank you to all that have tried to help. In order to do "Key Rollover" I needed to write the additional key states to the remaining values of the buffer array then write the values with Serial.write(buf,8). I can now use my Arduino Uno + My Game Pads as controllers for all my computer games.

# Answer
> 0 votes
You don't want to send random keys do you?

Well consider using the code below as your base. It's using Port Manipulation to read the buttons (Digital 0 to 7).

```
void setup()
{
  Serial.begin(9600);//Start serial connection.
  DDRD = 0b00000000; //Set Data Direction Register of port D to inputs (attach keys to digital pins 0to7;
  delay(200); //Misc delay.
}

void loop()
{
  Serial.write(PIND, 8);    // Send states of PORTD (digital 0 to 7)
}

```

I strongly suggest you use pull-down/up resistors on the buttons also. Adjust your code to the amount of keys you're using, or pull the pins low if not used. To avoid receiving random/floating pin values.

# Answer
> 0 votes
Could you post an example of your updated code? I'm working on a similar project but a complete n00b as far as using the Arduino goes.

---
Tags: arduino-uno, usb
---


# Question
Title: Will Arduino Pro Mini 3.3V run at half the speed of 5V version?
Provided a very simple sketch like this:

```
void loop() {
  digitalWrite(1, !digitalRead(1));
}

```

... should I expect 5V Arduino to run twice as fast as 3.3V, or are there some internal adjustments in place?

Specifically, I'm wondering about Pro Mini and/or Nano boards. The "speed" here is simply the frequency measured on pin `1`.

**edit:**

---

To clarify, I'm wondering if there might be some behind-the-scenes frequency divider that makes sure Arduino code always run at the same physical speed, even if the actual MCUs run on different clocks.

---

Possibly the simplest way of forming this same question: Can the sketch above be used to identify 3.3V Pro Mini boards from 5V versions, with the help of a frequency meter?

# Answer
If the board is running at half the speed (8MHz instead of 16MHz) then everything that isn't based on real time (i.e., millis(), delay() etc) will run at half the speed. It will all take twice as long to do everything.
> 1 votes

---
Tags: arduino-pro-mini, frequency
---


title: 2 Direction Motor

text:
# Question
Title: 2 Direction Motor
Using an Arduino-Nano, I'm trying to make a circuit that will change the direction of a motor based on two inputs. The input from the Arduino will be amplified by a transistor. Here's the code:

```
int rightIn = 2;
int rightOut = 3;
int leftIn = 4;
int leftOut = 5;
int rightVal = 0;
int leftVal = 0;

void setup() {
  pinMode(rightIn, INPUT);
  pinMode(leftIn, INPUT);
  pinMode(rightOut, OUTPUT);
  pinMode(leftOut, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  rightVal = digitalRead(rightIn);
  Serial.println(rightVal);
  leftVal = digitalRead(leftIn);
  if ((rightVal == HIGH) || (leftVal == HIGH)) {
    if (rightVal == HIGH) {
      digitalWrite(rightOut, HIGH);
      digitalWrite(leftOut, LOW);
    }
    if (leftVal == HIGH) {
      digitalWrite(rightOut, LOW);
      digitalWrite(leftOut, HIGH);
    }
  }
  else {
    digitalWrite(rightOut, LOW);
    digitalWrite(leftOut, LOW);
  }
}

```

And the arduino wiring:

* Pins 3 and 5 are attached to the motors power and ground
* Pins 2 ad 4 go to an seprate inputs

# Answer
I think you are mixing up your `rightVal` and `rightIn`, and your `leftVal` and `leftIn`.

```
rightVal = digitalRead(rightIn);
....
if (rightIn == HIGH) {

```
> 0 votes

---
Tags: c++, motor, arduino-nano
---


title: Led blinking in the loop in condition

text:
# Question
Title: Led blinking in the loop in condition
so I will explain what I want to get. I am reading temperature from DS18B20 and showing it on the LCD. I have one LED o pin 3 which is blinking when there is a temp reading and screen update. I have another LED on pin 4 which should lit when temp is more than 25 and less than 30, and I want it to blink when temp is more than 30. What I am getting is a blinking but not like one blink every 10ms but it waits for whole loop to start again to blink. Can I do it separately that this LED will blink indepentantly when condition is true? With set interval for example 10ms which wont be waiting for whole loop.

here is my example code:

```
    #include <OneWire.h>

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

//LiquidCrystal_I2C lcd(0x27, POSITIVE);  // Set the LCD I2C address
OneWire  ds(2);

unsigned long previousMillis = 0;
const long interval = 1000;
int ledState = LOW;
void setup()
{
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);

  lcd.begin(16,2);               // initialize the lcd

}

void loop()

{
  unsigned long currentMillis = millis();

  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius;

  if ( !ds.search(addr)) {
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(850);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;

  digitalWrite(3, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(10);              // wait for a second
  digitalWrite(3, LOW);    // turn the LED off by making the voltage LOW

   lcd.home ();
   lcd.print("Reading 1");
   lcd.setCursor( 0, 1);
   lcd.print("temp:");
   lcd.print(celsius);
   lcd.print("*C");

   if (celsius >= 25 && celsius < 30) {
    digitalWrite(4,HIGH);
   } else if (celsius >= 30) {
blink1();
   } else {
    digitalWrite(4,LOW);
   }

}

void blink1() {
digitalWrite(4,HIGH);
delay(50);
digitalWrite(4,LOW);
}

```

# Answer
> 2 votes
Here try this:

```
#include <OneWire.h>

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

//LiquidCrystal_I2C lcd(0x27, POSITIVE);  // Set the LCD I2C address
OneWire  ds(2);

const long interval = 1000; //İnterval at which to blink(milliseconds)
unsigned long previousMillis = 0;
int ledState = LOW;
void setup()
{
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);

  lcd.begin(16,2);               // initialize the lcd

}

void loop()
{

  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius;

  if ( !ds.search(addr)) {
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(850);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;

   lcd.home ();
   lcd.print("Reading 1");
   lcd.setCursor( 0, 1);
   lcd.print("temp:");
   lcd.print(celsius);
   lcd.print("*C");

   if (celsius >= 25 && celsius < 30) {
    digitalWrite(4,HIGH);
   } else if (celsius >= 30) {
blink1();
   } else {
    digitalWrite(4,LOW);
   }

   unsigned long currentMillis = millis();

   if (currentMillis - previousMillis >= interval) {

     previousMillis = currentMillis;

     if (ledState == LOW) {
       ledState = HIGH;
     } else {
       ledState = LOW;
     }

     digitalWrite(3, ledState);
   }
}

void blink1() {
digitalWrite(4,HIGH);
delay(50);
digitalWrite(4,LOW);
}

```

and also note that i choosed 1000 milliseconds for interval (equal to 1 second) so if you want 10ms as in your first post then change `const long interval` to 10

---
Tags: arduino-uno
---


# Question
Title: Manual TCP connection using WiFi ESP8266 module mistyped command
The command is working fine if I type it directly to the serial interface

```
AT+CIPSTART="TCP","192.168.1.5",1647

```

But if I want to make it automatic and send it whenever I want from inside the code is not working at all.

Used this but it's not working (Serial1 is from the hardware sp)

```
Serial1.println("AT+CIPSTART="TCP","192.168.1.5",1647")

```

Any way to arrange the data?

# Answer
> 2 votes
You need to escape your quotes:

```
Serial1.println("AT+CIPSTART=\"TCP\",\"192.168.1.5\",1647");

```

---
Tags: serial, wifi, esp8266
---


title: what units do Mouse.move() use?

text:
# Question
Title: what units do Mouse.move() use?
When I use Mouse.move() method (https://www.arduino.cc/en/Reference/MouseMove), what are units of xVal and yPos parameters?

# Answer
They're raw HID counts and as such don't have a unit. It is up to the OS to translate them from logical amounts to physical values.
> 1 votes

---
Tags: mouse
---