# Question
Title: Getting an Arduino Uno and MKR zero to communicate
I'm very new to Arduino and especially the forum so please let me know if I am on the wrong topic or anything.

Anyways let me get straight to the point. I am working on a school project where I need to create a robot head that can move and talk using the Arduino Uno. I have the speech files as a .wav and from what I gathered you need an sd card reader connected to the Uno to read .wav files. So I purchased the Arduino MKR Zero, but after I got the board I realized that it is a standalone board, not a file reader for the Uno. This project is due next week so I need to figure out how to make the MKR Zero read the files and play them off the speakers but have it timed and programmed off the Uno. Is this possible with the hardware I have?

Here is a picture of my setup:

# Answer
> 0 votes
Let the MKR Zero play the wav files. It has DAC on A0 and AudioZero library to play wav files from SD card.

You can use Serial communication to command the Zero from Uno. In Uno use hardware Serial or create SoftwareSerial to send commands to Serial1 of MKR Zero. You can then test the MKR first with commands sent from Serial Monitor.

---
Tags: arduino-uno, audio, speaker
---


# Question
Title: PIR sensor and sleep (interrupt) on Mega2560
So I was starting to gain some knowledge on the PIR sensor and how to let the Arduino 'sleep' while there is no movement detected by the PIR.

I found the following code somewhere and looked fairly simple. So I thought I would give it a try and grabbed my Mega2560, a LED and a PIR sensor.

While it was seeming to work at first sight, the Arduino is doing the opposite from what I was expecting. It turns off the LED and the Arduino when there is movement, instead of turning off the Arduino when there is NO movement. As I said before, it is doing pretty much the inverse.

Probably an easy solution, but can't figure it out on my own.

The code:

```
#include <avr/sleep.h>

int wakePin = 2;                 // pin used for waking up
int led = 13;

void wakeUpNow() {
}

void setup() {
  pinMode(wakePin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();          // enables the sleep bit in the mcucr register
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
    digitalWrite(led,LOW);
    sleep_mode();            // here the device is actually put to sleep!!
    // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
    digitalWrite(led,HIGH);
}

void loop() {
  sleepNow();     // sleep function called here
}

```

Thanks in advance.

**EDIT**

Adapted the code to the following and seems to work now. When motion is detected by the PIR it turns on the LED on pin 13; when no motion is detected, the LED is turned off.

Two questions still remain:

1) How can I be sure that the Arduino really sleeps now?

2) When the Arduino just entered sleep, it takes a couple of seconds (+/- 6s) before it can pick up another motion. Can I get a faster detection or another 'sleep' or 'powersave' method that lets the Arduino react faster to motion?

```
#include <avr/sleep.h>

const int wakePin = 2;                 // pin used for waking up
const int led = 13;

int wakeVal = 0;
int wakeState = LOW;

void wakeUpNow() {

}

void setup() {
  Serial.begin(9600);
  pinMode(wakePin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  //attachInterrupt(0, sleepNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();          // enables the sleep bit in the mcucr register
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
    sleep_mode();            // here the device is actually put to sleep!!
}

void disSleep(){
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
}

void loop() {
  wakeVal = digitalRead(wakePin);
  if (wakeVal == HIGH){

    disSleep();

    digitalWrite(led,HIGH);
    delay(1000);

    if (wakeState == LOW){
      Serial.println("Motion detected");
      wakeState = HIGH;
    }
  }
  else{
    digitalWrite(led,LOW);
    delay(1000);

    if (wakeState == HIGH){
      Serial.println("Motion stopped - Going to Sleep Mode !");
      wakeState = LOW;
      delay(1000);

      sleepNow();     // sleep function called here
    }
  }
}

```

# Answer
This is a problem with the Arduino Mega board. On the Mega, D2 is not INT0 as it is on the Uno. It's INT4. There's a footnote in the spec sheet that says only level interrupt is supported. That means you can't use RISING, FALLING or CHANGE. Your only choice is to use LOW. So the Arduino will be woken up when the motion turns OFF, not on. That's why it's backward. If you use an Uno instead of a Mega, you can use RISING and it will work as you think it should.
> 2 votes

---
Tags: arduino-mega, sensors, interrupt, sleep
---


# Question
Title: Reset I2C connection with arduino as slave
I am currently using I2C serial communications with arduino as slave and raspberry pi as the master. I am sending sensor data from arduino to raspberry pi. I need to reset the I2C connection once the sensor readings cross a threshold. I tried setting the TWCR =0 but it throws a Error 121 Remote I/O error on the raspberry pi when I do that. I also read that one way is to set TWCR =0, but for this I need to execute the Wire.begin(), Wire.onRequest(), and Wire.onReceive() again. Can you please tell me how to run these again since they are put in setup function. Does it mean I need to restart the Arduino program again? Or can I put these in void loop()? Thanks for the help.

# Answer
> 2 votes
You have a misconception about how I2C works. Unlike Serial (UART) I2C is a strictly master-slave interface. The slave cannot do anything without the master, since only the master controls the clock. Thus you don't need to reset the I2C interface to stop the transmission from the slave to the master.

When the master requests data from the slave the following happens: First the master sends the address of the targeted slave, including the direction bit set for "reading from slave". The slave with this address reacts with an acknowledgement (ACK) and start to transmit one byte. This byte get's acknowledged by the master. When the master decides, that it has received enough data, it does not acknowledge (NACK), which let's the slave stop it's transmission. Then the master sends a STOP condition to stop the I2C transmission.

I don't know, how you implemented the I2C communication on the Pi. Normally, when you initiate a read transaction from the master, you provide a number of bytes, that you want to request from the slave. The I2C module/library will then request data from the slave, until is has received all the requested bytes.

Thus you don't need to reset the I2C connection on the Arduino. The master totally controls the communication. When you end the transmission on the master, the slave cannot send further data.

Setting TWCR to zero in the middle of transaction will disrupt the I2C communication protocol. Thus you get an error on the Pi, that states an error in the I2C communication protocol. Just use the correct implementation of the I2C protocol to end the transmission correctly.

---
Tags: arduino-uno, i2c, raspberrypi
---


# Question
Title: MKR GSM 1400 Works only when connected to computer
My MKR GSM 1400 works fine when connected to a computer (powered USB) and after opening a serial connection to it. It does not when I plug it into a power supply. My power supply is a 5V 3A with a USB adapter.

```
void setup() {
  // put your setup code here, to run once:
  //...
  while (!Serial);
  //...
}

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

```

# Answer
> 5 votes
If your sketch on an Arduino with native USB doesn't run if not connected to USB, always first check if you didn't forget to disable a dependence on `Serial`. A common error is a `while (!Serial) {}` endless loop in setup().

---
Tags: mkr-gsm-1400
---


# Question
Title: Sparkfun CCS811 Air Quality Sensor is just not working
I have an Arduino Uno board and a SparkFun ccs811 sensor. I tried to reproduce the howto from the SparkFun homepage (https://learn.sparkfun.com/tutorials/ccs811-air-quality-breakout-hookup-guide?\_ga=2.45231532.967238096.1560976781-258902726.1560976781), including the error states part.

I uploaded one picture of the wiring (updated). I also tried to use an alternative hardware connection with SDA to A4 and SCL to A5, as mentioned in the code comments (see homepage).

However, it is just not working, and I always get this error code in the serial monitor `beginCore exited with: I2C_ERROR`

Here is my code (without the top comment block):

```
#include <Wire.h>

#include "SparkFunCCS811.h" //Click here to get the library: http://librarymanager/All#SparkFun_CCS811

#define CCS811_ADDR 0x5B //Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 mySensor(CCS811_ADDR);

void setup()
{
Serial.begin(9600);
Serial.println("CCS811 Basic Example");

Wire.begin(); //Inialize I2C Harware

//It is recommended to check return status on .begin(), but it is not
//required.
CCS811Core::status returnCode = mySensor.begin();
Serial.print("beginCore exited with: ");
switch ( returnCode )
{
case CCS811Core::SENSOR_SUCCESS:
 Serial.println("SUCCESS");
 break;
case CCS811Core::SENSOR_ID_ERROR:
 Serial.println("ID_ERROR");
 break;
case CCS811Core::SENSOR_I2C_ERROR:
 Serial.println("I2C_ERROR");
 break;
case CCS811Core::SENSOR_INTERNAL_ERROR:
 Serial.println("INTERNAL_ERROR");
 break;
case CCS811Core::SENSOR_GENERIC_ERROR:
 Serial.println("GENERIC_ERROR");
 break;
default:[enter image description here][2]
 Serial.println("Unspecified error.");
}

if (returnCode != CCS811Core::SENSOR_SUCCESS)
{
Serial.println(".begin() returned with an error.");
while (1); //Hang if there was a problem.
}
}

void loop()
{
//Check to see if data is ready with .dataAvailable()
if (mySensor.dataAvailable())
{
//If so, have the sensor read and calculate the results.
//Get them later
mySensor.readAlgorithmResults();

Serial.print("CO2[");
//Returns calculated CO2 reading
Serial.print(mySensor.getCO2());
Serial.print("] tVOC[");
//Returns calculated TVOC reading
Serial.print(mySensor.getTVOC());
Serial.print("] millis[");
//Simply the time since program start
Serial.print(millis());
Serial.print("]");
Serial.println();
}

delay(10); //Don't spam the I2C bus
}

```

# Answer
You need to solder those headers to the breakout. Just inserting them into the plated-through-holes doesn't give a reliable connection.
> 5 votes

---
Tags: arduino-uno, sensors, i2c
---


# Question
Title: Trying to create a delay function whilst performing other functions, using Timer.h libraries. Arduino uno
I am having a compilation error saying invalid useof template-name 'Timer without an argument list.

# Answer
Read, play with, and understand the Arduino **BlinkWithoutDelay** basic example. *Understand* means learn that it does not only apply to blinking, but to any time related action without blocking the main loop().

It's better learning the basics than using libraries in a wrong way.
> 0 votes

---
Tags: arduino-uno, timers, functions
---


# Question
Title: Arduino Micro + W5500 module from AliExpress
Got this module from Aliexpress

W5500 Ethernet Network Modules For Arduino TCP/IP 51/STM32 SPI Interface 3.3V 5V I/O MCU

... and trying to hook this up to my proto Aduino Micro as thus:

```
Micro -> W5500 module

5V (J6.6) ->  5V   (I noted that it has a linear regulator to 3V3 on the W5500 board)

IO11 (J5.16) -> RST ... (I connected it to Pin 11 so that I can do a manual reset, to see if it made a difference, it didn't)

IO10 (J5.15-> SCS

SCLK (J6.1) -> SCLK

MISO (J6.2)-> MISO

MOSI (J5.1)-> MOSI

GND (J6.4)-> GND

```

I then used a modified version of WebServer to test the functioning of the module:

```
/*
  Web Server

 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 modified 02 Sept 2015
 by Arturo Guadalupi

 */

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

int counter = 0;
const int W5500_RESET_PIN = 11;     // the number of the pushbutton pin

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xED, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 2, 177);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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

  // Reset the W5500 module
  pinMode(W5500_RESET_PIN, OUTPUT);
  digitalWrite(W5500_RESET_PIN, HIGH);
  digitalWrite(W5500_RESET_PIN, LOW);
  delay(100);
  digitalWrite(W5500_RESET_PIN, HIGH);
  delay(100);

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {

  if (counter > 0) counter--;
  else
  {
    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());
    counter = 10000;
  }

  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");
          }
          client.println("</html>");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

```

The code runs ok, and as you can see I'm printing out debug comms and monitoring using TeraTerm on the USB virtual port. However I'm seeing this output:

```
server is at 222.237.190.239

server is at 222.237.190.239

server is at 222.237.190.239

server is at 222.237.190.239

server is at 222.237.190.239

server is at 222.237.190.239

```

So ... the IP address didn't take, and needless to say that the webpage didn't show up when I typed in the IP address 192.168.2.177.

I've tried two identical W5500 modules so far and the problem persists for both in a consistent way. I've looked on the scope and I can see the SCLKs shooting across in 4 lots of clock bursts per each SCS low going pulse, with both the MISO and MOSI lines showing what appears to be "data" ... :)

The W5500 module itself has a power LED which is lit, the 5V is correctly regulating down to 3V3 and the 3V3 pin of the W5500 chipset IC appears to be connected. Both the LEDs on the ethernet balun appears to be turned on and blinking some of the times.

So ... erm ... help? ... what am I doing wrong? What else should I check?

2017-10-08 Update: Tried Ethernet2 library update from github adafruit ethernet2 libary.

But getting compiling errors now: Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Micro"

```
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Hemon\Documents\Arduino\libraries -fqbn=arduino:avr:micro -vid-pid=0X2341_0X8037 -ide-version=10612 -build-path C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983 -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose Z:\Quantum Sensing Limited\Consulting Work\Arduino\WebServer\WebServer.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Hemon\Documents\Arduino\libraries -fqbn=arduino:avr:micro -vid-pid=0X2341_0X8037 -ide-version=10612 -build-path C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983 -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose Z:\Quantum Sensing Limited\Consulting Work\Arduino\WebServer\WebServer.ino
Using board 'micro' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
WARNING: Category 'Device' in library ParPrinter is not valid. Setting to 'Uncategorized'
WARNING: Category 'Device' in library Radar is not valid. Setting to 'Uncategorized'
Detecting libraries used...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\sketch\WebServer.ino.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\sketch\WebServer.ino.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\sketch\WebServer.ino.cpp" -o "nul"
Using cached library dependencies for file: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src\SPI.cpp
Using cached library dependencies for file: C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Dhcp.cpp
Using cached library dependencies for file: C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Dns.cpp
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet2.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\EthernetClient.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\EthernetServer.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\EthernetUdp.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\EthernetUdp2.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Twitter.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\utility\socket.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\utility\w5100.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\utility\w5200.cpp" -o "nul"
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\utility\w5500.cpp" -o "nul"
Generating function prototypes...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\sketch\WebServer.ino.cpp" -o "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino10/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\sketch\WebServer.ino.cpp" -o "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\sketch\WebServer.ino.cpp.o"
Compiling libraries...
Compiling library "SPI"
Using previously compiled file: C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\libraries\SPI\SPI.cpp.o
Compiling library "Ethernet"
Using previously compiled file: C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\libraries\Ethernet\Dhcp.cpp.o
Using previously compiled file: C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\libraries\Ethernet\Dns.cpp.o
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=10612 -DARDUINO_AVR_MICRO -DARDUINO_ARCH_AVR  -DUSB_VID=0x2341 -DUSB_PID=0x8037 '-DUSB_MANUFACTURER="Unknown"' '-DUSB_PRODUCT="Arduino Micro"' "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\micro" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI\src" "-IC:\Program Files (x86)\Arduino\libraries\Ethernet\src" "C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp" -o "C:\Users\Hemon\AppData\Local\Temp\arduino_build_838983\libraries\Ethernet\Ethernet.cpp.o"
C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp: In member function 'int EthernetClass::begin()':

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp:26:3: error: 'W5500' was not declared in this scope

   W5500.init();

   ^

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp:37:5: error: 'W5100' was not declared in this scope

     W5100.setIPAddress(_dhcp->getLocalIp().raw_address());

     ^

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp: In member function 'void EthernetClass::begin(IPAddress, IPAddress, IPAddress, IPAddress)':

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp:72:3: error: 'W5100' was not declared in this scope

   W5100.init();

   ^

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp: In member function 'int EthernetClass::maintain()':

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp:158:9: error: 'W5100' was not declared in this scope

         W5100.setIPAddress(_dhcp->getLocalIp().raw_address());

         ^

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp: In member function 'IPAddress EthernetClass::localIP()':

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp:174:3: error: 'W5100' was not declared in this scope

   W5100.getIPAddress(ret.raw_address());

   ^

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp: In member function 'IPAddress EthernetClass::subnetMask()':

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp:181:3: error: 'W5100' was not declared in this scope

   W5100.getSubnetMask(ret.raw_address());

   ^

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp: In member function 'IPAddress EthernetClass::gatewayIP()':

C:\Program Files (x86)\Arduino\libraries\Ethernet\src\Ethernet.cpp:188:3: error: 'W5100' was not declared in this scope

   W5100.getGatewayIp(ret.raw_address());

   ^

Using library SPI at version 1.0 in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI
Using library Ethernet at version 1.0.4 in folder: C:\Program Files (x86)\Arduino\libraries\Ethernet
exit status 1
Error compiling for board Arduino/Genuino Micro.
Invalid version found: 0.1.03
Invalid version found: 0.1.04
Invalid version found: 0.1.06
Invalid version found: 0.1.04
Invalid version found: 0.1.07
Invalid version found: 0.1.02
Invalid version found: 0.1.09
Invalid version found: 0.1.00
Invalid version found: 0.1.05
Invalid version found: 0.1.01
Invalid version found: 0.1.06
Invalid version found: 0.1.01
Invalid version found: 0.1.04
Invalid version found: 0.1.07
Invalid version found: 0.1.04
Invalid version found: 0.1.03
Invalid version found: 0.1.03
Invalid version found: 1.2.03
Invalid version found: 0.1.03
Invalid version found: 0.1.08
Invalid version found: 0.1.04
Invalid version found: 0.1.05
Invalid version found: 0.1.05
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.01
Invalid version found: 0.1.09
Invalid version found: 0.1.03
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.06
Invalid version found: 0.1.03
Invalid version found: 0.1.04
Invalid version found: 0.1.06
Invalid version found: 0.1.04
Invalid version found: 0.1.07
Invalid version found: 0.1.02
Invalid version found: 0.1.09
Invalid version found: 0.1.00
Invalid version found: 0.1.05
Invalid version found: 0.1.01
Invalid version found: 0.1.06
Invalid version found: 0.1.01
Invalid version found: 0.1.04
Invalid version found: 0.1.07
Invalid version found: 0.1.04
Invalid version found: 0.1.03
Invalid version found: 0.1.03
Invalid version found: 1.2.03
Invalid version found: 0.1.03
Invalid version found: 0.1.08
Invalid version found: 0.1.04
Invalid version found: 0.1.05
Invalid version found: 0.1.05
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.01
Invalid version found: 0.1.09
Invalid version found: 0.1.03
Invalid version found: 0.1.00
Invalid version found: 0.1.00
Invalid version found: 0.1.06

```

Any ideas?

# Answer
Solved it ... needed to create a new Ethernet2 folder and copy the Ethernet2 library files into it, and now it works great! The Ethernet2 library is a stand alone and different library to the Ethernet one.
> 1 votes

# Answer
For the W5500 chip use the Ethernet2 library. It can be can be found and installed in Library Manager in Arduino IDE.

UPDATE 2018: The Arduino Ethernet library version 2.00 now supports W5200 and W5500.
> 1 votes

# Answer
beside any other coding and library issues: IP Groups are seperated by DOT not comma! If lucky, the interpreter ist Syntax-tollerant. Your Observation for the IP xx.xx.xx.139 could be the indication of the software trying to solve the issue semi-effectively.
> -1 votes

# Answer
Change the MISO & MOSI Signal between Micro & W5500 module, now it works with both Etherenet2 & Ethernet Libs. btw Ethernet2 is better see ram.
> -1 votes

---
Tags: ethernet
---


title: Connecting MPU6050 to Arduino Lilypad

text:
# Question
Title: Connecting MPU6050 to Arduino Lilypad
To preface, I am very new to Arduino and I watched this video on YouTube.

It shows how you can build a motion controlled car with Arduino and I decided to make this for my school project.

One thing I am having difficulty with is connecting the MPU6050 to the Lilypad. In the video he doesn't really show much of it and just sticks it onto the board.

However, do I need to solder the MPU6050? Where do I solder the pins the underside or the top. Do I need to align the pins with that of the Lilypad?

Sorry if it's a stupid question I genuinely don't know.

The current condition of our lilypad:

What it's supposed to look like:

If you see the images, in addition to the yellow light of the MPU 6050 and the red light of the HC 05, the red light of the Lilypad is also supposed to light up like the second picture, however in ours, only the MPU 6050 and the HC 05 lights up and not the Lilypad.

# Answer
> 0 votes
Since you seem to need some orientation, I will explain a few things, to get you started.

The MPU6050 is a device, that communicates through the I2C interface. It uses 2 communication lines (SCL for the clock and SDA for the data). To use is with the Lilypad, you have to connect those two lines, Vcc (5V) and Ground. If you look at a pinout diagram, you can identify, which of the pads are SDA and SCL on the Lilypad.

It is up to you, if you connect the mentioned lines via soldering or by other means. Normally you would solder connecting wires between the MPU6050 and the Lilypad. If you want the MPU to be removable, you can solder a cable with a pin header (for example female) to the Lilypad and the according pins to the MPU (for example a male pin header). That way, you could also stick the MPU to the board and remove it again if necessary. How you are doing it is not important, as long as the electrical contact is good.

---

There are also a lot of tutorials and ready to use libraries for the MPU6050 on the net. newbie already posted a link to a tutorial. Also Adafruit has a library on github with examples, that explain how to use it. That way you should be able to get started with your project.

Good luck!

---
Tags: sensors, hardware, mpu6050, hc-05
---


title: How do arrays work?

text:
# Question
Title: How do arrays work?
It's been days now I'm trying to figure out how arrays work in Arduino IDE. For better understanding, I assembled some pieces of code I found here and there to write this sketch:

```
#define arrayLength(x) (sizeof(x) / sizeof(int)) //array size

typedef struct {
  int note;
  int duration;
} BUZZER_NOTE ;

class Buzzer {

  public:

    BUZZER_NOTE notes[];  //-- Funny how the same declaration tried below DOES work if it's inside a class

};

void setup() {

  Serial.begin(9600);

//  BUZZER_NOTE notes[];  //-- Compilation error:

  int *bob;               //-- Declaring this way, shows no compilation errors, but prints out strange values
//  int bob[];            //-- Compilation error: "storage size of 'bob' isn't known"

  int bob1[] = {10, 20};
  int bob2[5] = {10, 20, 30, 40, 50};
  int bob3[] = {60, 70, 80};

  bob[0] = 10;
  bob[1] = 20;
  bob[2] = 30;
  bob[3] = 40;
  bob[4] = 50;
  bob[5] = 60;
  bob[6] = 70;   //-- No matter how many indexes I create, it will always show lenght of 2

  test(1);       //-- Calls the first function below, as expected
  test({1});     //-- Also calls the first function below, when the second one (with the array parameter) is expected

  test(bob);     //-- Length: 1 (expected 5); Size: 2 (?????) ; First Element: 163 (expected 10);
  test(bob1);    //-- Length: 1 (expected 2); Size: 2 (?????) ; First Element: 10  (ok);
  test(bob2);    //-- Length: 1 (expected 5); Size: 2 (?????) ; First Element: 10  (ok);
  test(bob3);    //-- Length: 1 (expected 3); Size: 2 (?????) ; First Element: 60  (ok);

}

void loop() {
}

void test(int a) {
  Serial.println("Called int function");
  Serial.println();
}

void test(int a[]) {
  Serial.println("Called array function");
  Serial.print("Length: ");
  Serial.println(arrayLength(a));
  Serial.print("Size: ");
  Serial.println(sizeof(a));
  Serial.print("First Element: ");
  Serial.println(a[0]);
  Serial.println();
}

```

The code above prints out these lines:

```
Called int function    // as expected

Called int function    // expected array function

Called array function  // as expected
Length: 1              // expected 5
Size: 2
First Element: 163     // expected 10

Called array function  // as expected
Length: 1              // expected 5
Size: 2
First Element: 10      // as expected

Called array function  // as expected
Length: 1              // expected 3
Size: 2
First Element: 10      // as expected

Called array function  // as expected
Length: 1              // expected 5
Size: 2
First Element: 60      // as expected

```

My goal for now is to achieve something like this:

```
int bob[]; // this gives a compiler error: "storage size of 'bob' isn't known"
bob = {10, 20, 30, 40};

test(bob);

void test(int arr[]) {
  for (int i = 0; i < FIND_ARR_LENGTH_SOMEHOW; i++) {
    Serial.print("Index i: ");
    Serial.println(arr[i]);
}

```

Question: How can I declare an array without mention its size, fill it up with as many indexes I want, then pass it to a function that will be able to process all the contents?

I know I could declare an array and keep its length to pass as a second parameter, but there must be a way to get an array length.

Thanks in advance.

# Answer
> ```
> BUZZER_NOTE notes[];  //-- Funny how the same declaration tried below DOES work if it's inside a class
>
> ```

It doesn't really. C++ language prohibits that. It is just a non-standard quirk of GCC compiler used by Arduino IDE, which happens to support C-style *flexible array members* in C++ code.

> ```
> //  BUZZER_NOTE notes[];  //-- Compilation error:
>
> ```

Of course. You are not allowed to use *incomplete types* in object definitions. And an array of unspecified size is an incomplete type. A widely used exception from this rule is an `[]` array declared with an *initializer*. In that case the array size is assumed to be implicitly specified by the initializer.

> ```
> int *bob;               //-- Declaring this way, shows no compilation errors, but prints out strange values
>
> ```

Of course. This is not an array at all. It is a pointer. And it doesn't point anywhere. It is invalid. You are not allowed to even access such pointer.

> ```
> //  int bob[];            //-- Compilation error: "storage size of 'bob' isn't known"
>
> ```

See above.

> ```
>  int bob1[] = {10, 20};
>  int bob2[5] = {10, 20, 30, 40, 50};
>  int bob3[] = {60, 70, 80};
>
> ```

These are properly declared arrays. As I said above, the `[]` declaration is allowed since you are declaring your array with an initializer.

> ```
> bob[6] = 70;   //-- No matter how many indexes I create, it will always show lenght of 2
>
> ```

This does not make any sense at all. You cannot "create indexes" in an array. Array size is fixed at the point of declaration. There's no way to shrink or expand it, there's no way to "create" or "remove" indexes.

But in this example `bob` is not even an array. It is a pointer. And since it is a garbage pointer that doesn't point anywhere, you are not allowed to access it with *any* indexes.

Once you make your `bob` to point to some valid block of memory, you will be able to access it as `bob[3]` and such, as long as you stay withing the bounds of that block of memory.

> ```
> test({1});     //-- Also calls the first function below, when the second one (with the array parameter) is expected
>
> ```

Several mistakes here.

Firstly, you second function does not have "array parameter". In parameter declarations `int a[]` is equivalent to `int *a`. It is a *pointer* parameter, not an array parameter.

Secondly, since the beginning of times in C and C++ you could use a scalar value in `{}` to initialize a scalar object

```
int a = { 42 }; /* <- this has always been legal in C and C++ */

```

So, the first function is obviously a candidate in this case. The rules of C++ language dictate that `{1}` initializer can be used as an initializer for an `int` value or `std::initializer_list<int>` object, but for a pointer. Which is why the first function is called.

You can force it to produce a temporary array through array-type alias and functional-cast syntax

```
using ARR = int[];
test(ARR{1});

```

but in GCC you will run into a GCC bug preventing you from forming pointers and references to temporary arrays (Clang will accept it).

> ```
> void test(int a[]) {
>   ...
>   Serial.print("Length: ");
>   Serial.println(arrayLength(a));
>
> ```

This makes no sense. This "array length" trick

```
#define arrayLength(x) (sizeof(x) / sizeof(int))

```

only works with *arrays*. Your `a` inside `test` is not an array. It is a pointer. It is completely pointless to apply this `sizeof` trick to a pointer.

> My goal for now is to achieve something like this:
>
> ```
> int bob[]; // this gives a compiler error: "storage size of 'bob' isn't known"
> bob = {10, 20, 30, 40};
>
> ```

Not possible. When defining an array, you always have to specify a fixed compile-time size. And arrays in C and C++ are not copyable, not assignable. If you want to copy data between arrays, you have to either do it manually, element by element, or use a library-provided routine that does the same.

`{}`\- initializers can be used with arrays, but only at the point of declaration. Not later. You can do something like

```
using A = int[5];
A a;
std::memcpy(a, A{1, 2, 3, 4, 5}, sizeof(A));

```

but this will run into the same GCC bug I mentioned above.

On a related note: standard library provides `std::array` template - a thin wrapper for raw arrays. `std::array` objects are copyable and assignable through a pretty much the same syntax as you used

```
std::array<int, 5> a;
a = { 1, 2, 3, 4, 5 };

```

But they are still arrays of fixed compile-time size.

> ```
> void test(int arr[]) {
>   for (int i = 0; i < FIND_ARR_LENGTH_SOMEHOW; i++) {
>
> ```

Not possible. Your `arr` is a pointer. It is not possible to extract "array size" information for a pointer, since that information simply does not exist. If you want to "FIND\_ARR\_LENGTH\_SOMEHOW" you have to either develop your own convention for finding that length or simply pass that length to the function through a separate parameter.
> 3 votes

# Answer
This is more of a general programming question, but since there are some special pitfalls for microcontrollers/Arduinos I will answer the question.

> How can I declare an array without mention its size, fill it up with as many indexes I want, then pass it to a function that will be able to process all the contents?

Short answer: You cannot. An array has always a fixed size, that cannot be changed during the lifetime of the array.

Long answer: Though every array has it's fixed size, you can create new arrays with a size, that is not known at compilation time. For this you would need dynamic memory allocation like done with the `new` keyword:

```
BUZZER_NOTE *notes = new BUZZER_NOTE[x];

```

with the size of the new array `x`. `notes` is here a pointer to the array (actually a pointer to the first element of the array). If you don't know, how to deal correctly with pointers, you should google for a tutorial about it, there are plenty on the web. So, if your defined array is full and you want to add more elements, you have to define a new array with bigger size, copy the old content and delete the old one (actually that is what happens inside the `String` class).

To actually get the easy way of adding more elements, without copying the whole content, a C++ programmer would use a linked list. This defines an element class, that contains a variable for the content of the element and a pointer to the next element in the list. So to iterate through the linked list, you would start at the first element and follow the pointers through the list to the end. (Again you can read more about this concept on the web)

**BUT:** You should not use any of these things on an Arduino, especially not on the ones with very limited RAM (like Uno, Nano, ...). When you do dynamic memory allocation, memory fragmentation will happen. Take the example from above. You have a dynamically allocated array with your data. Now you want to store more data. You define a new and bigger array. For the simplicity of explanation, it will be allocated directly after the first array in the memory. You copy the content and delete the first array to free the memory. Now there is free space in your memory with the size of the first array. Now you want to again add more data, so you define a new and bigger array. This array cannot fit into the free space at the start, since the space to not big enough. This memory space is now dead, because it cannot be used for your data.

In real cases, you would allocate and delete variables with varying sizes throughout your sketch. This leads to the point, that you will get many holes in your memory, which are too small to fit your data in. On a PC this is not a big problem, since you have a lot of RAM and the OS can reorganize the data to fit better. But on the Arduino you have only very limited RAM and no OS, so you quickly run out of RAM. Your sketch will stop to work at that point, since there is no usable memory left on the device.

You instead should go the harder way and just use fixed arrays, that are big enough to hold the biggest amount of data, that you expect.

---

And since AnT didn't cover this completely:

```
bob[6] = 70;

```

This line cannot work correctly for 2 reasons: First you only declared `bob` as a pointer, but this pointer does not point to a valid memory address. You would have to create a corresponding array with the `new` keyword as shown above, or let it point to an existing array. Currently you try to write to an invalid or random memory address.

Secondly the compiler cannot know, how many items the array has, that `bob` should point to. This is just not an information, that the compiler has. So it will not prevent you from writing higher indices, than are in the array. But effectively the memory write either fails, because the address of the non-existent element is invalid, or you will overwrite data from some other variables --\> Very dangerous! It is your responsibility to ensure, that you don't write data, where it does not belong.

And keep in mind, that microcontrollers don't have something like exceptions. Thus some things, that would through an exception on a PC will stop the microcontroller from working, or it will just do the crazy stuff, that you told him to do (where accessing memory outside of the array would through a runtime error on the PC).
> 1 votes

# Answer
Ok, after reading and reading the answers and links about my question, I ended up using a function as suggested. Something like:

```
void foo(char* myArray, int size) {}

```

But I ended up finding another solution to the problem, which is a little more complicated:

```
#define arrayLen(x) (sizeof(x) / sizeof(x[0]))

char myArray[64] = "my array test with a long value in it";

void setup() {

  Serial.begin(9600);
  while (!Serial);

  // IMHO, it would be nice if the compiler would accept these two sintaxes
//  myArray = "my array test with a long value in it";
//  "my array test with a long value in it".toCharArray(myArray, 64);

  Serial.print("Value before: ");
  Serial.println(myArray);
  Serial.print("Size before: ");
  Serial.println(arrayLen(myArray));

  String temp;
  temp = myArray;

  foo(temp);

  Serial.print("Value after: ");
  Serial.println(myArray);
  Serial.print("Size after: ");
  Serial.println(arrayLen(myArray));

}

void loop() {}

void foo(String str) {
  for (int i = 0; i < str.length(); i++) {
    Serial.print("Index ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(str.charAt(i));
  }
}

```

I know I have a bad habit to use Strings instead of array of chars (coming from other languages), but in this example, memory limitation issues won't be significant because the String will be freed from memory after execution of setup() and foo().

There is another thing I would like to share (not directly related to my previous question), that I believe could be useful for other people. This little sketch shows how to use the same String technique to manipulate the contents of a char array, passed by reference to an external function. Here it goes:

```
#define arrayLen(x) (sizeof(x) / sizeof(x[0]))

char myArray[64] = "my array test with a long value in it";

void setup() {

  Serial.begin(9600);
  while (!Serial);

  Serial.print("Value before: ");
  Serial.println(myArray);
  Serial.print("Size before: ");
  Serial.println(arrayLen(myArray));

  String temp;
  temp = myArray;

  foo(temp);
  temp.toCharArray(myArray, 64);

  Serial.print("Value after: ");
  Serial.println(myArray);
  Serial.print("Size after: ");
  Serial.println(arrayLen(myArray));

}

void loop() {}

void foo(String &str) {
  str = "abcde";
}

```

Results (just as expected):

```
Value before: my array test with a long value in it
Size before: 64
Value after: abcde
Size after: 64

```

It may look awful to the eyes of a C++ programmer, but hey, it works!

Thanks again for all the answers/comments.
> 1 votes

# Answer
The C arrays are tricky and they're described in every C tutorial. The other answers adresses mistakes / questions in comments, but none of them shows how it can be done:

```
struct BuzzNote {
  int note;
  int duration;
};

const BuzzNote melody[] = {
  {10, 200}, { 45, 300}, {90, 200}, // ...
};

void test(BuzzNote const * arr, size_t len) {
  for (size_t i = 0; i < len; ++i) {
    Serial.print(i);
    Serial.print(". ");
    Serial.print(arr[i].note);
    Serial.print(' ');
    Serial.println(arr[i].duration);
  }
}

// using template for determining size of array
// (and as a bonus it won't work with plain pointers)
template<typename T, size_t size>
size_t GetArrLength(T(&)[size]){return size;}

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

void loop() {
  test(melody, GetArrLength(melody));
  delay(10000);
}

```

I'm using template version of getting array length (it won't compile with pointers, as pointer isn't array).

And this version stores data in RAM (and waste it). If you don't have spare space in ram, you'll have to dig into PROGMEM variables/arrays. But it's the quest for another day :D
> 0 votes

---
Tags: variables, ide, class, pointer, functions
---


title: How to read voltage using ADS1115

text:
# Question
Title: How to read voltage using ADS1115
I'm very new to this. I found this tutorial.

But it don't explain how to read voltages higher than Arduino 5V. I have connected a 100K ohm resistor to positive and 10K ohm to negative of my 24V power supply.

I need some guidance for writing the code for this specific ADC, please.

# Answer
As KIIV mentioned you need to do the math:

Use this online voltage divider calculator to calculate your maximum input.

* Keep in mind you shouldn't exceed Arduino 5V.
* Use a multimeter to measure the resistors actual resistance.
* Do the math for your example assuming R1 is exactly 100K and R2 10K you have to multiple the voltage by 11.
* remember any error is going to multiple by 11 too, so make sure the first reading is accurate/stable.

ADS1115 is actually 15bit which will give you resolution of 32768, with default PGA setting you get: `6.144 / 32768 = 0.0001875V` per bit.

```
Voltage = (your ADC reading) * 0.0001875V;
Voltage = Voltage * 11;

```

Take a look at This question/answer to see how I did reduced Arduino ADC noise, some steps can be done for ADS1115 as well.
> 0 votes

---
Tags: c++, voltage-divider
---


title: Privacy of a program

text:
# Question
Title: Privacy of a program
I have created a algorithm and using arduino harware, and I don't want that users of my hardware could read or copy the Program so is there any security code or something that I could use. But I must access it whenever I needed to. It should be like admin and users.

# Answer
> 1 votes
The code that's sent to Arduino is "compiled" which means it's changed from human readable form to a binary data that can be understood by the processor. The "code" you wrote remains on your computer only.

This itself is a way of encryption since it's impossible to retrieve the original source code from that binary data. That data can only be "decompiled". This is a process that takes the binary data and converts it automatically into a human readable code, but it's not the same code that you originally made. It doesn't have comments, and logical variable names. This makes it also hard to understand.

Decompilation is usually to difficult and time consuming to even bother doing that unless your hardware is a lock on a vault with million dollars inside. If that's the case don't use Arduino, but instead use a custom designed chip with cryptographic key built inside the hardware.

---
Tags: programming
---


title: KY-040 rotary encoder skipping steps

text:
# Question
Title: KY-040 rotary encoder skipping steps
Yesterday I asked a question about de-bouncing this rotary encoder and Jsotola suggested that I should use a method like This to detect the previous state and then do the counting. using that method each turn is counting twice in one turn so I came up with my version of de-bouncing the rotary encoder:

```
int s1, s2;
int count = 0;
boolean right = 0;
boolean left = 0;
int rotary = 0;
unsigned long timer = 0;
unsigned int bounce = 50;

void setup() {
  Serial.begin(9600);
  pinMode(6, INPUT);
  pinMode(7, INPUT);

}

void loop() {

  s1 = digitalRead(6);
  s2 = digitalRead(7);
  if (s1 == 1 && s2 == 1) {
    right = 0;
    left = 0;
    rotary = 0;
  }
  if (s1 == 0 && s2 == 1) {
    left = 1;
  }
  if (left == 1 && (s1 == 0 && s2 == 0)) {
    rotary = 2;
  }
  if (s1 == 1 && s2 == 0) {
    right = 1;
  }
  if (right == 1 && (s1 == 0 && s2 == 0)) {
    rotary = 1;
  }

  if (rotary == 1) {
    if ((millis() - timer) > bounce) {
      count++;
    }
    right = 0;
    left = 0;
    timer = millis();
  }
  if (rotary == 2) {
    if ((millis() - timer) > bounce) {
      count--;
    }
    right = 0;
    left = 0;
    timer = millis();
  }
  Serial.print(s1);
  Serial.print(s2);
  Serial.print(", ");
  Serial.print(count);
  Serial.println(" ");
  delay(15);
}

```

The code is working just fine. When turning the rotary this are the steps that I get:

`10-00-01 < (11) > 10-00-01`

problem is if I turn the knob quickly rotary encoder will skip one or two steps like: `01-01-01 < (11)` or `10-00-00 < (11)`.

This problem exist in all methods/libraries (I tested them all), is there anyway to fix this with software/hardware or this rotary encoder is just junk and I should get a better one?

---

Another method of de-bouncing as Jsotola requested:

```
 int pinA = 3;  // Connected to CLK on KY-040
 int pinB = 4;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.print ("Rotated: ");
     if (bCW){
       Serial.println ("clockwise");
     }else{
       Serial.println("counterclockwise");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

```

# Answer
> 2 votes
I applaud you for your tenacity with the "debouncing" idea, but there is an excellent library for this rotary encoder, and the author has also written an article about it: Ben Buxton - rotary encoders done properly. Here is a link to his library: GitHub - buxtronix.

I’ve used an older version of the library before with interrupts, and it worked perfectly for my application. I see the author has updated the library and has 2 example sketches; one uses interrupts, and the other uses polling. I tried both of them today on an Uno and I was very impressed with the polling sketch’s performance. It seemed to equal that of the interrupt method.

If you take the important bits out of the library files, then add them to a sketch, you can see how little code it takes for this "method" of processing the encoder’s output. Here is a test sketch with the library bits in it.

```
#define R_START 0x0
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6
#define DIR_NONE 0x0
#define DIR_CW 0x10
#define DIR_CCW 0x20

const byte pin1 = 5;  // DT
const byte pin2 = 6;  // CLK
int state = R_START;
int counter = 0;

const unsigned char ttable[7][4] = {
  // R_START
  {R_START,    R_CW_BEGIN,  R_CCW_BEGIN, R_START},
  // R_CW_FINAL
  {R_CW_NEXT,  R_START,     R_CW_FINAL,  R_START | DIR_CW},
  // R_CW_BEGIN
  {R_CW_NEXT,  R_CW_BEGIN,  R_START,     R_START},
  // R_CW_NEXT
  {R_CW_NEXT,  R_CW_BEGIN,  R_CW_FINAL,  R_START},
  // R_CCW_BEGIN
  {R_CCW_NEXT, R_START,     R_CCW_BEGIN, R_START},
  // R_CCW_FINAL
  {R_CCW_NEXT, R_CCW_FINAL, R_START,     R_START | DIR_CCW},
  // R_CCW_NEXT
  {R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 0x30;
}

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){
  unsigned char result = process();
  if(result == DIR_CW){
    counter++;
    Serial.println(counter);
  }
  else if(result == DIR_CCW){
    counter--;
    Serial.println(counter);
  }
}

```

Heres a simplified sketch (It works the same but I didn't like the hex numbers and I don't use define):

```
const byte pin1 = 5;  // Connected to DT on KY-040
const byte pin2 = 6;  // Connected to CLK on KY-040
int state = 0;
int counter = 0;

const unsigned char ttable[7][4] = {
  {0, 2, 4, 0},
  {3, 0, 1, 0 | 16},
  {3, 2, 0, 0},
  {3, 2, 1, 0},
  {6, 0, 4, 0},
  {6, 5, 0, 0 | 32},
  {6, 5, 4, 0},
};

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){

  unsigned char result = process();

  // Clockwise rotation.
  if(result == 16){
    counter++;
    Serial.println(counter);
  }

  // Counter clockwise rotation.
  else if(result == 32){
    counter--;
    Serial.println(counter);
  }

}

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 48;
}

```

---
Tags: rotary-encoder
---


# Question
Title: Running many devices on 5V pin. How to provide external power
I'm using my Arduino DUE 5V pin to power a lot of sensors and I'm worried about the drop in current.

I'm powering the board using the USB port. Is this the correct way or is there a different way of powering the board to make sure the current drop is limited as much as possible?

Thanks in advance.

# Answer
> 1 votes
There is a maximum current you can use from the 5V pin(s), so it is good to split the current going into the Arduino.

You can use a breakout board for a USB, connect the USB to the breakout board, connect it both to the Arduino, and in parallel to the sensors; meaning the current used for the sensors is not going through the Arduino. You might need 2 break out boards, one for the input USB, one for the output USB.

Note there is a maximum current for USB too.

---
Tags: power, arduino-due, current
---


title: Obtain retained MQTT message

text:
# Question
Title: Obtain retained MQTT message
I’m using ESP8266 with Arduino code. Each device posts a ‘state’ and an ‘avail’ messages for a specific topic.

I wish to be able to read those retained messages and not only right after connecting and subscribe to MQTT broker.

**EDIT 1** \- Clarifications

1. I'm using Raspberry Pi Zero W as a MQTT Broker ( Local ).
2. When device boots, it changes its state from `offline` to `online`, but a different process checks periodically if state is `offline` or `online` for current device and **others** on the network.
3. it is not same as when subscribing to a retained topic, that you get the state at that specific time.
4. Storing chage of state in a variable, is one way to do it, but is there a different way ?

# Answer
Once a message has passed through an MQTT broker there is not a way to retrieve it from the broker.

Consider instead deciding upon the action at the time the message is received by the subscriber. If this decision needs to be made at a later time consider storing the state in the of the payload of the message on the subscriber.

Also consider running Node-RED. If the platform running the MQTT broker can support Node-RED (such as a Raspberry Pi), it turns out to be convenient to run both on the same computer. Node-RED contains nodes (graphical programming blocks) which can subscribe to and publish to MQTT topics. By connecting other nodes to these, the topic and payload can be manipulated. Of interest is an option within the Output MQTT node. Here you can select Retain True. This page explains how this option works:

> Once you have sent a retained message to a topic, all subscribers will receive that message when they subscribe.
>
> To clear a previously retained topic from the broker, send a blank message to that topic with the retain flag set.
> 1 votes

---
Tags: esp8266, mqtt
---


# Question
Title: Using a scrolling text in OLED Adafruit_SSD1305
I have been in internet for the past week looking for a way of programming a scrolling text (either left or right) using Adafruit\_SSD1305 but I only find scrolling commands for Adafruit\_SSD1306. Has anyone tried this before? I really need help on this

# Answer
> 1 votes
The SSD1305 hardware apparently *does* include scrolling support (SDD1305 datasheet - see section 10) but apparently the Adafruit driver didn't implement it. But The SSD1306 looks so similar to the SSD1305, that if the SSD1306 software driver won't work with it "out of the box" (worth a try!), you could probably compare the two software drivers and back-implement that feature into the the 1305 driver yourself.

---
Tags: c++
---


# Question
Title: Serial Commmunication between two arduino
I want to send the voltage magnitude received on an analog pin of atmega328Pu to another arduino uno using Serial communication pins TX and RX and display the value on the receiver arduino's Serial monitor.

Transmitter Arduino Code:

```
void setup()
{

  Serial.begin(9600);

  pinMode(A0, INPUT);

}

void loop()

{

  int voltage=analogRead(A0);

  Serial.println(voltage);

}

```

Receiver Arduino Code:

```
void setup()

{

  Serial.begin(9600);

}
int incomingByte = 0;

void loop()
{
if (Serial.available() > 0) {
    incomingByte = Serial.read();
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
}

}

```

Problem: Now the Problem I am facing is that Serial Monitor of Receiver arduino does not shows anything, it remains blank. Please analyse this system help me in finding out the best way to get around this problem?

# Answer
1. Connect the grounds of the two Arduinos together. Their serial transmitters and receivers need the same voltage reference.
2. `pinMode(A0, INPUT);` is not needed. pinMode() only affects the digital part of the pin driver. (But it probably isn't doing any harm, either).
3. The transmitter Arduino will be sending 1, 2, 3, or 4 ASCII bytes - the digits 0-9, representing the D/A result, 0 - 1023. In decimal, those digits will look like 48, 49, ..., 57 (for a '0', '1', ... '9', respectively). So the receiving Arduino will be handling characters, not numbers. It needs to collect all of the characters, then repeat them onto it's terminal output.
> 2 votes

# Answer
The problem is that a serial connection usually connects two devices, in your case it's three (sensor arduino, receiving arduino and your pc).

To get around this you have to use an additional software serial on different pins on the receiving arduino (unfortunately the atmega328 has only one hardware serial interface). As long as you don't have to send anything from pc to the receiving arduino and from the receiving arduino to the sensing one you could try to simply disconnect the wire receiving-TX to sensing-RX and see if it works. In this latter case you could actually get rid of the receiving arduino at all.

Edit: another important point was mentioned in JRobert's answer: grounds of devices communicating with each other must **always** be connected!
> 3 votes

---
Tags: serial, communication
---


# Question
Title: How can I connect to an Arduino using WiFi?
I'm working on building a solar powered, Arduino based weather station. The weather station consists of a temperature sensor and a photoresistor, and I plan to add an anemometer in the future. I would like to connect the weather station to my wireless network so that I can retrieve the sensor data from my computer without having to run wires (I live in a rental).

What are the different options for connecting the Arduino to WiFi? I've looked at ethernet shields, WiFi shields, and something called Xbee, but I don't understand what each of them are for.

I also have a wireless home router that I could use. Is it possible to connect my Arduino Uno to the router via the routers ethernet or USB port and then receive data from and send commands to the Arduino wirelessly over my home network? If so, how would this be accomplished?

I currently have a bare Arduino Uno.

# Answer
> 30 votes
You have a few options for connecting your Arduino to the network/Internet.

## Ethernet

Something like the Arduino Ethernet Shield allows you to plug in an Ethernet cable from the wall or router into your Arduino. Obviously, the main limitation is that your device is now tethered by the cable. For outdoor use, I wouldn't do this.

## WiFi

The Arduino WiFi Shield allows you to connect to your home WiFi network. This is just like the Ethernet except its now wireless.

The ESP8266 is a cheaper alternative that, with the default firmware, has the same functionality as the WiFi Shield. Be careful that you power it with 3.3V and not 5V as the rest of the Arduino. It also uses 3.3V logic levels so don't connect the Arduino's TX pin directly to the ESP's RX pin; use a voltage divider.

## RF

If you have a lot of sensors or other devices that need to communicate with each other, the best option is usually an RF module. You have many options here, XBee being one of them. Check out the Sparkfun XBee Buying Guide to look at all the options available. And that's just XBee. There are many other wireless options available, at all sorts of prices.

The thing with RF is that none of these will connect to the Internet. You will have all your devices communicate with each other or a base station, which will then be connected to the network by either a WiFi or Ethernet module.

## Wireless Router Serial

Depending on what kind of wireless router you use, you can have the Arduino communicate directly with it and use that as your connection to a network.

# Answer
> 5 votes
# Marry OpenWrt and your Arduino

Get a small OpenWrt-capable router like "TP-Link TL-WR703N", flash it with the current stable version of OpenWrt and connect your Arduino to the router's USB port.

This solution ist half or less of the cost of WiFi-shields and has far more power.

...and cheaper as a YÙN.

Smart home automation webserver on OpenWRT router WR703N interfaced to Arduino, compared to Raspberry Pi and Ubuntu may be a starting point to read about this and your favorite search engine will find many more links about marrying WR703N and Arduinos...

(!) Please see https://arduino.stackexchange.com/a/1754/653 too....

# Answer
> 4 votes
ESP8266 is a cheap 5$ wifi module with UART, SPI connectivity. This can be integrated with Arduino seamlessly either through the stock firmware using AT commands, or by writing custom firmware using the SDK provided and GIPO available. For more reference http://www.esp8266.com/

# Answer
> 3 votes
I've been working with xbee on the arduino and raspberry pi for a few months now. Whilst it does have it's issues and quirks, it is a great tool in the communication chain. It's not perfect but given the mesh side of it, for me it reaches further than my wifi and can even be more reliable (my raspberry pi with wifi occasionally drops out, however the connected xbee continues to function in the background.

Specifically in my case it allows for a serial connection between my devices (being several arduinos, a raspberry pi (coordinator) and my mac (used primarily for monitoring but also occasionally injecting serial data)). In this case it's perfect. It doesn't allow internet access or access beyond the xbee framework, but that suits me perfectly since implementation is as simple as Serial.print and Serial.read with no Ethernet overhead.

# Answer
> 2 votes
I use Spark Core which is a very easy to use Arduino programming platform. This platform was built on the primus that WiFi should be easy to use and cheap. Can even program the Spark Core from anywhere, any time.

# Answer
> 2 votes
You could try a Arduino Yun, it is like a Uno but it has a WiFi directly on the board.

There is a part in the "Guide to the Arduino Yún" called "Configuring the onboard WiFi", that describes how to configure the WiFi.

# Answer
> 1 votes
What you want is pretty easy to do, and the code exists already. But the way I invision it, you won't connect the sensor Arduino to your wifi. Instead, you'll use another Arduino as your gateway like this:

Sensor Arduino: Located outside, connected to temperature sensor, wind speed, rain gauge?

Gateway Arduino: Located inside, w/ Wiznet 5001 ethernet shield

The Sensor Arduino and Gateway Arduino talks to each other using a VERY easy to use wireless transceiver, nRF24L01+. The wireless modules are $3 each, and the library for use is very mature. All the sensor data is easily communicated to the Gateway using this library.

The Gateway Arduino w/ the ethernet acts as a webserver, enabling any computer in your local network to open up a page and view current conditions. Look at this page for the Arduino code: http://arduino.cc/en/Tutorial/WebServer

You want to also save historical temperature/wind speed information right? This is the best part! The Gateway Arduino can push data to a service like Xively, a free web-based data collection service that also gives you a nifty way to visualize/graph your data. There is a little hiccup with using the Wiznet along with the nRF24L01 module. The wireless module and ethernet shield both use the same bus to communicate, so take a look at this blog to see how you can use both at the same time:

http://www.heald.ca/content/arduino-ethernet-nrf24l01-and-pachubecosmxively

Xively also lets you make that data public or private, so you can chose to contribute your weather station data to the community.

Some other notes: I like nRF24L01+ modules because they're dirt cheap. Xbee modules cost more than the Arduinos themselves. You can keep adding nRF24L01+ modules around the house once you establish a gateway. The same cost problem exists with wifi shield - expensive.

# Answer
> 1 votes
If you want a cheaper alternative to add WiFi capabilities to Arduino look at ESP WiFi shield.

It works great with WiFiEsp library. Programming model is exactly the same as Arduino WiFi Shield

# Answer
> 0 votes
Check ESP8266 wifi module , it's a cheap module and can be controlled using any microcontroller by AT commands , also it's Soc so you can use it standalone .

# Answer
> 0 votes
Using the ESP8266 AT cmd set is difficult and error prone. Suggest you reflash the ESP8266-01 as a UART-WiFi bridge as described here ESP8266 Wifi Add on for Arduino Made Simple

Note that setup also lets you re-configure your wifi settings without re-programming the ESP8266-01

# Answer
> 0 votes
Using the ESP8266 sield is error prone, requires an update that needs to be flashed, some soldering required, and it's not appropriate for a production environment. Also, there are issues with the power supply because you need to have a *separate* 3.3V power supply. It's 2016 (!) and there are a bunch more options available now.

"The UNO WiFi board is the Arduino UNO with integrated WiFi." http://www.arduino.org/products/boards/arduino-uno-wifi

and

"The Star Otto is the first Arduino board featuring the STM32F469 processor with WiFi." http://www.arduino.org/products/boards/arduino-star-otto (Actually, as of October, it's still not available, "Coming Soon").

Please note these two boards are from the **OTHER** Arduino organization.

# Answer
> 0 votes
After several trials & errors in my IoT project, I would recommend working on ESP32 over ESP8266(and also Arduino Uno & Nano), **except if you know very well the scope of your project.**

Advantages of ESP32 over ESP8266:

1. Bigger RAM, ESP8266: 32KB instruction & 80 KB user data, ESP32: 520 KB

I'm working on an IoT project and trying to authenticate the device on GCP using a certificate. The root certificate of GCP is already about 120 KB, so it does not fit into ESP8266. There are alternatives but that complicates things.

2. ESP32 has bluetooth & ESP8266 not

Well at some point of your IoT project you might want bluetooth to connect your device with your phone ...

3. Some versions of ESP32 has integrated ports for the camera (search ESP32 CAM)

With ESP8266 you can surely use a camera but that will involve more coding & wiring and potentially worse performance.

And at last, I tried to wire a wifi chip with Arduino Uno & Nano but I encountered some bugs and problems with the AT commands. Thus now I'm quite happy with ESP32 because everything is integrated.

---
Tags: arduino-uno, wifi, xbee
---


# Question
Title: Arduino code to control 4 led's from 4 buttons
This is my very first arduino sketch and it's causing me a bit of a headache. Sounds so simple really all I want the sketch to do is digitalread from one of 4 digital input pins and then digitalwrite to one of 4 output pins in essence. So that when button 1 is pressed LED 1 lights up, button 2 pressed led 2 lights up and so on. I've added a serial write so I could check that the buttons are actually working when pressed.

The code I've written:

```
const int buttonPin1 = 7;     // number of pushbutton 1 pin
int buttonState1 = LOW;       // set the default variable value for pushbutton1 status
const int ledPin1 =  6;       // number of the LED 1 pin
const int buttonPin2 = 8;     // number of pushbutton 2 pin
int buttonState2 = LOW;       // set the default variable value for pushbutton2 status
const int ledPin2 =  9;       // number of the LED 2 pin
const int buttonPin3 = 4;     // number of pushbutton 3 pin
int buttonState3 = LOW;       // set the default variable value for pushbutton3 status
const int ledPin3 =  5;       // number of the LED 3 pin
const int buttonPin4 = 2;     // number of pushbutton 4 pin
int buttonState4 = LOW;       // set the default variable value for pushbutton4 status
const int ledPin4 =  3;       // number of the LED 4 pin

void setup() {                  // Set Pins to Outputs Or Inputs
  pinMode(buttonPin1, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin1, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin2, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin2, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin3, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin3, OUTPUT);     // initialize the LED pins as an outputs:
  pinMode(buttonPin4, INPUT);   // initialize the pushbutton pins as an inputs:
  pinMode(ledPin4, OUTPUT);     // initialize the LED pins as an outputs:
  Serial.begin(9600);           // initialize serial communication at 9600 baud
}

void loop() {

buttonState1 = digitalRead(buttonPin1);  // read current states of the pushbutton value:
  buttonState2 = digitalRead(buttonPin2);  // read current states of the pushbutton value:
  buttonState3 = digitalRead(buttonPin3);  // read current states of the pushbutton value:
  buttonState4 = digitalRead(buttonPin4);  // read current states of the pushbutton value:

// check if the pushbutton is pressed buttonState# == HIGH/LOW
  // if pressed change buttonState == HIGH to turn on ledPin#
  // else if buttonState == LOW then digitalWrite(ledPin#, LOW) Keeps Led off.

if (buttonState1 == HIGH) {    //check buttonState
digitalWrite(ledPin1, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin1, LOW);   // turn LED off:
}
Serial.println(buttonState1); //Print buttonState to serial
if (buttonState2 == HIGH) {   //check buttonState
digitalWrite(ledPin2, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin2, LOW);   // turn LED off:
delay(10);
}
Serial.println(buttonState2); //Print buttonState to serial
if (buttonState3 == HIGH) {   //check buttonState
digitalWrite(ledPin3, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin3, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState3); //Print buttonState to serial
}
if (buttonState4 == HIGH) {   //check buttonState
digitalWrite(ledPin4, HIGH);  //if HIGH turn LED on:
} else {
digitalWrite(ledPin4, LOW);   // turn LED off:
delay(10);
Serial.println(buttonState4); //Print buttonState to serial
}

```

The Leds all have a common GND and the buttons all have a common GND. Buttons are connected to +5V & Input pin# so one terminal has got two wires, Led's are connected to digital output pins then resistor and straight to GND. What happens is that ALL of the LED's come on when any one of the 4 buttons in pressed.

I've attempted to edit some of the code in the example sketches to get this to work.

Can anyone suggest anything that I'm doing wrong? Or ammend the code sp that I can see where I'm going wrong.

# Answer
> 1 votes
It is likely you have connected the switches incorrectly. Normally, people use single poll single throw (SPST) switches connected to 5 volts and the input pin of the Arduino. This will pull the input pin to 5 volts when the switch is closed. Then, to pull the input pin to ground when the switch is open, people add a large resistor between ground and the same processor pin.

Almost any large resistor will work here. Consider using 10K ohms (10,000 ohms) or there abouts.

Of course, if you are using a 3 volt Arduino, do not connect the switch to a 5 volt source. Instead connect it to a 3 volt source.

Alternatively, a pull up resistor inside the processor, if available, can be activated. Look at this arduino.cc web page. There this sample code shows how to activate the processor's pull up on pin number 2:

```
pinMode(2,INPUT_PULLUP);

```

Because not all processors have a "pull up" feature on all input pins & because the range of internal to the processor pull up resistances can vary (for example 50,000 ohms to 150,000 ohms), it may be more useful and universal to use an external pull up resistor.

# Answer
> 1 votes
Get rid of the external resistors, use the internal pullup resistor.

In setup():

pinMode (pinX, INPUT\_PULLUP);

Wire the button between input pin pinX and Gnd, then test for a LOW to see if the button is pressed in loop():

if (digitalRead (pinX) == LOW){ // button is pressed

// do something

}

else { // button is not pressed

// do something else

}

# Answer
> 0 votes
I would suggest taking the resistor/s off the switches, so the button connects to digital inputs to the 3v/5v line. Then use 470ohm resistors for the leds(to limit the current) on the digital outputs.

---
Tags: arduino-uno, arduino-ide, led, button
---


# Question
Title: IOT-GA6 gsm module Arduino +CME error 58
I've recently bought a IOT-GA6 gsm module . I want to use it to send an mms but doesn't work. The SMS and call work. When I execute the void function (mms) the monitor shows the error message +CME EYROR:58. Does anybody know what this means and how to solve it?

this is my code

```
include SoftwareSerial.h
include SD.h

define  CS    4

SoftwareSerial A6Module(2, 3);

File dataFile;

int i;

unsigned char data=0;

void setup()
{
  pinMode(PWR,OUTPUT);
  pinMode(CS,OUTPUT);

  A6Module.begin(115200);
  Serial.begin(115200);

  digitalWrite(PWR,LOW);
  delay(10);

  digitalWrite(PWR,HIGH);
  delay(10);

  if (!SD.begin(CS)) Serial.println("initialization failed!");
  else Serial.println("initialization done.");
}

void loop()
{
  if(Serial.available())
  {
    while(Serial.available())
    {
      data=Serial.read();
      Serial.write(data);
      Serial.println("\n");
    }
    //data=0;
  }

  if(Serial.available())
  {
    data=Serial.read();
  }

  if(data=='1')
  {
    A6Module.println("AT+CGMI\r"); //Manufacturer identification
  }

  if(data=='2')
  {
    A6Module.println("AT+CGMM\r"); //Model identification
  }

  if(data=='3')
  {
    A6Module.println("AT+CGMR\r"); //Software version
  }

  if(data=='4')
  {
    A6Module.println("AT+CGSN\r"); //IMEI number
  }

  if(data=='5')
  {
    A6Module.println("ATD+21369682909;\r"); //Calling
  }

  if(data=='6')
  {
    A6Module.println("ATH\r"); //Hang Up
  }

  if(data=='7')
  {
    A6Module.println("AT+CMGF=1");
    delay(2000);
    A6Module.print("AT+CMGS=\"+213696829093");
    A6Module.print(char(34));  // "
    A6Module.print(char(13));  // CR
    A6Module.print('\r');  // hex equivalent of newline
    delay(2000);
    A6Module.print("A6 test message");
    delay(500);
    A6Module.println (char(26));  //ctrl_z
  }

  if(data=='8')
  {
    A6Module.println("AT+CMGR=1\r"); //Read message
  }

  if(data=='9')
  {
   A6Module.println("AT+CMGD=1,0\r"); //Delete message
  }

  if(data=='s') sendMMS();
  data=0;
}

void sendMMS()
{
  A6Module.print("AT+CMMSINIT");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSCURL=\"http://mms.itelcel.com/servlets/mms\"");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSCID=1\r");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSPROTO=\"148.233.151.240\",8080");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSSENDCFG=6,3,0,0,2,4\r");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+SAPBR=3,1,\"CONTYPE\",\"MMS\"\r");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+SAPBR=3,1,\"APN\",\"mms.itelcel.com\"");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+SAPBR=1,1");
  delay(4000);
  if(A6Module.available())

  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+SAPBR=2,1");
  delay(4000);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSEDIT=1");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSDOWN=\"PIC\",19293,2000000,\"test.jpg\"\r");
  delay(1000);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }

  dataFile=SD.open("test.jpg");
  i=0;
  if(dataFile)
  {
    while(dataFile.available())
    {
      data=dataFile.read();
      if(data<0x10) Serial.print("0");
      Serial.print(data,HEX);
      i++;
      if((i%40)==0) Serial.println();
      A6Module.write(data);
    }
    dataFile.close();
  }
  else
  {
    Serial.println("error opening test.jpg");
  }

  delay(1000);
  A6Module.print("AT+CMMSRECP=\"+213696829093");
  delay(100);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSVIEW\r");
  delay(2000);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSSEND\r");
  delay(2000);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSEDIT=0\r");
  delay(2000);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
  A6Module.print("AT+CMMSTERM\r");
  delay(2000);

  if(A6Module.available())
  {
    while(A6Module.available()) Serial.write(A6Module.read());
  }
}

```

# Answer
The Arduino Uno does not support the maximum current requested by GA6, try an external source for the gprs module of at least 6V using common ground between the gprs module and the arduino.
> 1 votes

---
Tags: arduino-uno, c++, c, sketch, compilation-errors
---


# Question
Title: Arduino Due 16U2 Programming Port Documentation
Are there any documentation or whatsoever on what the 16U2 does when trying to program the Sam3X in Arduino Due?

I reallynwant to know what's wrong with my made up board but can't get pass the No Device Found problem.

Been searching it but I can't find any. I can't understand the hex file burned on the MCU.

# Answer
The 16u2 is merely acting as a usb to UART adapter. You can just as well use an ft232 or other serial adapter.

Of course the 16u2 needs firmware installing on it in order to function. That firmware is available (possibly bundled with the ide, or for download, not sure at the moment).
> 0 votes

---
Tags: arduino-due
---


# Question
Title: Pin Mappings from Arduino Metro M4 Express Board to SAMD51
After looking through the internet, I coudln't find any document (not in the datasheet, no nice graphics on google image searches) that showed the mapping between the Arduino breakout board and the SAMD51. Does such a mapping exist?

I'm answering my own question below, but perhaps someone knows of a better table.

# Answer
> 1 votes
Edit: Since writing my answer, I found this Google Sheet that does a much better job.

Arduino has some schematics on their website. Here's an image I used to build the following list below.

There are in this format: Arduino Pin | SAMD51 Pin | SAMD51 Description

## Analog

```
A0  3   PA02/EINT2/AIN0/VOUT0
A1  14  PA05/I5/AIN5/VOUT1/SERCOM0.1
A2  15  PA06/I6/VREFC/AIN6/SERCOM0.2
A3  13  PA04/I4/VREFB/AIN4/SERCOM0.0
A4  11  PB08/I8/AIN2/SERCOM4.0
A5  12  PB09/I9/AIN3/SERCOM4.1

```

## Digital

```
D0  44  PA23/I2C/I7/SERCOM3.1 +5/SOF/I2SFS1
D1  43  PA22/I2C/116/SERCOM3.0+5.1/I2SDI
D2  40  PB17/SERCOM5.1/I2SMCK0
D3  39  PB16/I0/SERCOM5.0/I2SCK0
D4  26  PB13/I13/SERCOM4.1/I2SMCK1
D5  27  PB14/I14/SERCOM4.2/PCC8
D6  28  PB15/I15/SERCOM4.3/PCC9
D7  25  PB12/I12/SERCOM4.0/I2SCK1
D8  42  PA21/I5/SERCOM3+5.3/I2SDO
D9  41  PA20/I4/SERCOM3+5.2/I2SFS0
D10 37  PA18/I2/SERCOM1+3.2
D11 38  PA19/I3/SERCOM1+3.3
D12 36  PA17/I2C/I1/SERCOM1.1+3.0
D13 35  PA16/I2C/I0/SERCOM1.0+3.1
GND
AREF    4   PA03/I3/VREFA/AIN1
SDA 63  PB02/I2/AIN14/SERCOM5.0
SCL 64  PB03/I3/AIN15/SERCOM5.1

```

## SPI

```
MOSI    29  PA12/I12/I2C/SERCOM2.0+4.1
SCK 30  PA13/I13/I2C/SERCOM2.1+4.0
MISO    31  PA14/I14/SERCOM2+4.2

```

---
Tags: pins, port-mapping
---