# Question
Title: Arduino Uno - How to write personal data in NTAG213 using RFID-RC522
I am trying to write some data in NTAG213 sticker with this code:

```
#include <SPI.h>
#include <MFRC522.h>

constexpr uint8_t RST_PIN = 9;     // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 10;     // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

// Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
   return;
}

// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
  return;
}

Serial.print(F("Card UID:"));    //Dump UID
for (byte i = 0; i < mfrc522.uid.size; i++) {
   Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
   Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.print(F(" PICC type: "));   // Dump PICC type
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));

byte buffer[34];
byte block;
MFRC522::StatusCode status;
byte len;

 Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
 // Ask personal data: Family name
 Serial.println(F("Type Family name, ending with #"));
 len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
 for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

 block = 1;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("PCD_Authenticate() success: "));

 // Write block
 status = mfrc522.MIFARE_Write(block, buffer, 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("MIFARE_Write() success: "));

 block = 2;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }

 // Write block
 status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("MIFARE_Write() success: "));

 // Ask personal data: First name
 Serial.println(F("Type First name, ending with #"));
 len = Serial.readBytesUntil('#', (char *) buffer, 20) ; // read first name from serial
 for (byte i = len; i < 20; i++) buffer[i] = ' ';     // pad with spaces

 block = 4;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }

 // Write block
 status = mfrc522.MIFARE_Write(block, buffer, 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 5;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
   }

   // Write block
   status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
   if (status != MFRC522::STATUS_OK) {
     Serial.print(F("MIFARE_Write() failed: "));
     Serial.println(mfrc522.GetStatusCodeName(status));
     return;
   }
   else Serial.println(F("MIFARE_Write() success: "));

   Serial.println(" ");
   mfrc522.PICC_HaltA(); // Halt PICC
   mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
}

```

With the tag and card included in the module (RC522) this code works fine:

With the NTAG213 sticker the code doesn't work:

I need to write data in this stickers, how can I do that?

# Answer
> 2 votes
The one that comes with RC552 is MiFare Classic 1K

And the programming running is for the same.

Ntag213 is MiFare Ultralight C, which requires different type of programming..

Try this one

```
/* mifare ultralight example (25-02-2018)
 *
 *   RFID-RC522 (SPI connexion)
 *
 *   CARD RC522      Arduino (UNO)
 *     SDA  -----------  10 (Configurable, see SS_PIN constant)
 *     SCK  -----------  13
 *     MOSI -----------  11
 *     MISO -----------  12
 *     IRQ  -----------
 *     GND  -----------  GND
 *     RST  -----------  9 (onfigurable, see RST_PIN constant)
 *     3.3V ----------- 3.3V
 *
 */

  #include <SPI.h>
  #include <MFRC522.h>

  #define SS_PIN          10
  #define RST_PIN         6

  MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
  MFRC522::StatusCode status; //variable to get card status

  byte buffer[18];  //data transfer buffer (16+2 bytes data+CRC)
  byte size = sizeof(buffer);

  uint8_t pageAddr = 0x06;  //In this example we will write/read 16 bytes (page 6,7,8 and 9).
                            //Ultraligth mem = 16 pages. 4 bytes per page.
                            //Pages 0 to 4 are for special functions.

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  Serial.println(F("Sketch has been started!"));
  memcpy(buffer,"HELLO WORLD! ;-)",16);
}

void loop() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
    return;

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
    return;

  // Write data ***********************************************

  for (int i=0; i < 4; i++) {
    //data is writen in blocks of 4 bytes (4 bytes per page)
    status = (MFRC522::StatusCode) mfrc522.MIFARE_Ultralight_Write(pageAddr+i, &buffer[i*4], 4);
    if (status != MFRC522::STATUS_OK) {
      Serial.print(F("MIFARE_Read() failed: "));
      Serial.println(mfrc522.GetStatusCodeName(status));
      return;
    }
  }
  Serial.println(F("MIFARE_Ultralight_Write() OK "));
  Serial.println();

  // Read data ***************************************************
  Serial.println(F("Reading data ... "));
  //data in 4 block is readed at once.
  status = (MFRC522::StatusCode) mfrc522.MIFARE_Read(pageAddr, buffer, &size);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Read() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  Serial.print(F("Readed data: "));
  //Dump a byte array to Serial
  for (byte i = 0; i < 16; i++) {
    Serial.write(buffer[i]);
  }
  Serial.println();

  mfrc522.PICC_HaltA();

}

```

---
Tags: arduino-uno, rfid
---


# Question
Title: The code is working fine with Arduino Uno but not with NodeMCU
I uploaded program MPU6050\_DMP6\_Multiple.ino (https://github.com/eadf/MPU6050\_DMP6\_Multiple/blob/master/MPU6050\_DMP6\_Multiple.ino) to Arduino Uno and it works fine. When I upload the very same code to NodeMCU 1.0 board in Arduino IDE I have this message from the compiler :

Errors :

```
Arduino: 1.8.5 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 4M (3M SPIFFS), v2 Prebuilt (MSS=536), Disabled, None, 115200"

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\Pera\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\Pera\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Pera\Documents\Arduinogttp\libraries -fqbn=esp8266:esp8266:nodemcuv2:CpuFrequency=80,FlashSize=4M3M,LwIPVariant=v2mss536,Debug=Disabled,DebugLevel=None____,UploadSpeed=115200 -ide-version=10805 -build-path C:\Users\Pera\AppData\Local\Temp\arduino_build_960938 -warnings=none -build-cache C:\Users\Pera\AppData\Local\Temp\arduino_cache_811066 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.xtensa-lx106-elf-gcc.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2 -prefs=runtime.tools.mkspiffs.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\mkspiffs\0.2.0 -prefs=runtime.tools.esptool.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.12 -verbose C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\Pera\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\Pera\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Pera\Documents\Arduinogttp\libraries -fqbn=esp8266:esp8266:nodemcuv2:CpuFrequency=80,FlashSize=4M3M,LwIPVariant=v2mss536,Debug=Disabled,DebugLevel=None____,UploadSpeed=115200 -ide-version=10805 -build-path C:\Users\Pera\AppData\Local\Temp\arduino_build_960938 -warnings=none -build-cache C:\Users\Pera\AppData\Local\Temp\arduino_cache_811066 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.xtensa-lx106-elf-gcc.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2 -prefs=runtime.tools.mkspiffs.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\mkspiffs\0.2.0 -prefs=runtime.tools.esptool.path=C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.12 -verbose C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino
Using board 'nodemcuv2' from platform in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0
Using core 'esp8266' from platform in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0
Detecting libraries used...
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "nul"
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev\I2Cdev.cpp" -o "nul"
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire\Wire.cpp" -o "nul"
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master\MPU6050.cpp" -o "nul"
Generating function prototypes...
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -ffunction-sections -fdata-sections -w -x c++ -E -CC -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\tools\xtensa-lx106-elf-gcc\1.20.0-26-gb404fb9-2/bin/xtensa-lx106-elf-g++" -D__ets__ -DICACHE_FLASH -U__STRICT_ANSI__ "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/lwip2/include" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0/tools/sdk/libc/xtensa-lx106-elf/include" "-IC:\Users\Pera\AppData\Local\Temp\arduino_build_960938/core" -c -w -Os -g -mlongcalls -mtext-section-literals -fno-exceptions -fno-rtti -falign-functions=4 -std=c++11 -MMD -ffunction-sections -fdata-sections -DF_CPU=80000000L -DLWIP_OPEN_SRC -DTCP_MSS=536 -DARDUINO=10805 -DARDUINO_ESP8266_NODEMCU -DARDUINO_ARCH_ESP8266 -DARDUINO_BOARD="ESP8266_NODEMCU" -DESP8266 "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\variants\nodemcu" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev" "-IC:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire" "-IC:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master" "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp" -o "C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp.o"
In file included from C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/Arduino.h:244:0,

             from C:\Users\Pera\AppData\Local\Temp\arduino_build_960938\sketch\OrigMPU6050.ino.cpp:1:

C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/pgmspace.h:16:51: error: __c causes a section type conflict with __c

#define PSTR(s) (extension({static const char __c[] PROGMEM = (s); &__c[0];}))

                                               ^

C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:38:76: note: in definition of macro 'FPSTR'

#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))

                                                                        ^

C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:39:34: note: in expansion of macro 'PSTR'

#define F(string_literal) (FPSTR(PSTR(string_literal)))

                              ^

C:\Program Files (x86)\Arduino\examples\14.Experiment\OrigMPU6050\OrigMPU6050.ino:225:20: note: in expansion of macro 'F'

 Serial.println(F("FIFO overflow!"));

                ^

C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/pgmspace.h:16:51: note: '__c' was declared here

#define PSTR(s) (extension({static const char __c[] PROGMEM = (s); &__c[0];}))

                                               ^

C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:38:76: note: in definition of macro 'FPSTR'

#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))

                                                                        ^

C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/WString.h:39:34: note: in expansion of macro 'PSTR'

#define F(string_literal) (FPSTR(PSTR(string_literal)))

                              ^

C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master/DeathTimer.h:45:22: note: in expansion of macro 'F'

     Serial.print(F("S:")); Serial.println(time % 60);

                  ^

Using library I2Cdev in folder: C:\Users\Pera\Documents\Arduinogttp\libraries\I2Cdev (legacy)
Using library Wire at version 1.0 in folder: C:\Users\Pera\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\libraries\Wire
Using library MPU6050_DMP6_Multiple-master in folder: C:\Users\Pera\Documents\Arduinogttp\libraries\MPU6050_DMP6_Multiple-master (legacy)
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

```

I am not so good in programming to understand what I can do to solve the problem ! I'd like to use NodeMCU with two MPU6050 and I need help !

# Answer
> 0 votes
It is an issue in esp8266 Arduino core. It is hard to explain, but here is a workaround for you:

In MPU6050\_Wrapper.h change word `__FlashStringHelper` to `char` for function `halt` to be `void halt(const char* errMessage = NULL)`.

In DeathTimer.h remove `#include <Arduino.h>`.

In sketch add before includes `#define F(s) s` to hide the F macro.

---
Tags: nodemcu
---


# Question
Title: threshold voltage level and blinking problem
I am using arduino pro mini 3.3 V,8 Mhz.vcc of the this arduino is coming from AC-DC converter with regulator 3.3 volt.I am listening analog data from voltage divider approximately 250 milivolts.

I want to basically,If analog voltage will reach 250 milivolts then led on.Otherwise led off.I am using avarage 100 ms for voltage data.

But,I have seen led on blinking for threshold voltage.Such as,The voltage level is changing 248-254.led on,led of,led on...I don't want to blink.

What can you do in such situations?Voltage level and slightly variable voltage?

Thanks

# Answer
> What is the sensetive ac voltage stabilization method coming from voltage divider and it contains noise filter capacitor and take avarage?

Calculating an average by using 3/4 of the current average and 1/4 of the new measurement (exponential average) works well for me in a lot of situations. You can adjust the constants as you see fit, as long as they add to 1.0. I use powers of 2 and shifting for maximum performance:

```
// Exp. average: 3/4 old avg + 1/4 new data, with rounding
int16_t xpavg(int16_t newdat, int16_t avg){

   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}

```
> 1 votes

# Answer
As Jot mentioned in his comment you can write code to follow a hysteresis. This means, that the LED is only turned on, when the analog value is a bit above the threshold, and only turned off, when it's a bit below the threshold. You can see this behavior in Schmitt Triggers, which work that way (though they are getting the hysteresis via a corresponding electrical circuit, not through code). You wrote, your voltage readings are noisy in the range of about 10mV.

Depending on how your current code is structured, you can reach this goal by using if statements:

```
if( value > threshold + margin ){
    digitalWrite(LED_pin, HIGH);
} else if( value < threshold - margin ) {
    digitalWrite(LED_pin, LOW);
}

```

You can choose a good value for margin (this depends on the desired behavior). Start with a margin of 7mV (which should filter out the noise of 10mV) and change it, until it works as intended.
> 0 votes

---
Tags: arduino-uno, arduino-ide, voltage-level
---


# Question
Title: (Arduino Uno) Is my code for a follow the sun project valid? We want the motor to stop when both photoresistors have the same amount of light
```
int RlightPin=0;  //pin for right Photoresistor
int LlightPin=1;  //pin for left Photoresistor
int TranslateAnalogR=0;
int TranslateAnalogL= 1;
#include <Servo.h> //Servo library.
int pos=90; //Declare and initialize the variable pos.
int servoPin=9; //Servo connected to pin 9
int servoDelay=10; //Time motor waits before working again.
Servo myArms; //Servo object called myArms

void setup() {
Serial.begin(9600); //Start serial communication.
pinMode(7,OUTPUT);
pinMode(servoPin,OUTPUT);
myArms.attach(servoPin);

}

void loop() {

Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.
TranslateAnalogL=analogRead(LlightPin);  //Read the left photoresistor value

if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop
myArms.write(pos); // sets the servo position according to the scaled value
delay(servoDelay);// waits for it to get to the position

}

if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal
for (pos=0; pos>=40; pos=pos+1)  {
  myArms.attach(servoPin);
  myArms.write(pos); //send servo to pos
  if(TranslateAnalogR=TranslateAnalogL){
  myArms.detach();}
}
}

if(TranslateAnalogL=!TranslateAnalogR && TranslateAnalogL>TranslateAnalogR){    //If Photoresistor L is not equal to R and higher than R move until equal
for (pos=0; pos>=40; pos=pos-1){
   myArms.attach(servoPin);
   myArms.write(pos); //send sevo to pos
   if(TranslateAnalogL=TranslateAnalogR){
   myArms.detach(); }

}
}

}

```

# Answer
There are many issues with this code:

```
pinMode(7,OUTPUT);

```

What is this pin for? Why do you set it to `OUTPUT` and then never actually output anything? If the pin is in use, you should declare a constant for it, like

```
const int fooPin = 7;

```

and then use the constant instead of the bare number 7.

```
Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

```

`analogRead()` is a slow function, and it is quite inefficient to do the analog to digital conversion twice. You can instead

```
TranslateAnalogR = analogRead(RlightPin);
Serial.println(TranslateAnalogR);

```

As a matter of style, I would remove the comments. Commenting code is generally considered a good practice, as long as the comments tell something non obvious, like giving the “big picture” or the rationale for doing something in a particular way. Paraphrasing in English what the code already says in C++ is useless.

```
Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
//...
Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.

```

You won't know what value corresponds to the left and what value corresponds to the right. I would instead do something like:

```
Serial.print("L: ");
Serial.print(TranslateAnalogL);
Serial.print(", R: ");
Serial.println(TranslateAnalogR);

```

Then:

```
if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop

```

You mean `==`.

```
if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal

```

The first test is redundant. If R\>L, then obviously R≠L.

```
    for (pos=0; pos>=40; pos=pos+1)  {
        myArms.attach(servoPin);
        myArms.write(pos); //send servo to pos
        if(TranslateAnalogR=TranslateAnalogL){
            myArms.detach();
        }
    }

```

This is a very contrived way of searching the optimum. Normally you attach the servo once and keep it attached all the time. Then you adjust the position until you see the same illumination on both LDRs. This way you keep track of the correct position and you need not redo the whole angle scan every time. Also, this will not work for three reasons:

1. You mean `TranslateAnalogR==TranslateAnalogL` rather than `TranslateAnalogR=TranslateAnalogL`
2. `TranslateAnalogR` and `TranslateAnalogL` are not updated within the loop, you need to explicitly perform an analog read.
3. The loop will run too fast for the servos to follow the requested positions.

Later:

```
    for (pos=0; pos>=40; pos=pos-1){

```

The loop is backwards. You probably mean

```
    for (pos=40; pos>=0; pos=pos-1){

```

---

Here is my take at this, completely untested:

```
#include <Servo.h>

// Pinout.
const int PIN_LDR_R = 0;  // right photoresistor
const int PIN_LDR_L = 1;  // left photoresistor
const int PIN_SERVO = 9;  // servo

const int SERVO_DELAY = 20; // time motor waits before working again

int pos = 90; // servo position in degrees
Servo servo;  // servo object

void setup() {
    Serial.begin(9600);
    pinMode(PIN_SERVO, OUTPUT);
    servo.attach(PIN_SERVO);
}

void loop() {
    // Read and report light levels.
    int level_L = analogRead(PIN_LDR_L);
    int level_R = analogRead(PIN_LDR_R);
    Serial.print("L: ");
    Serial.print(level_L);
    Serial.print(", R: ");
    Serial.println(level_R);

    // Adjust the servo position.
    if (level_R > level_L && pos < 180)
        ++pos;
    if (level_R < level_L && pos > 0)
        --pos;

    // Update the servo.
    servo.write(pos);
    delay(SERVO_DELAY);
}

```

A few things worth noting:

* Constants are qualified as `const` (it helps the compiler optimize and catch bugs) and spelled in full caps (a common stylistic convention).
* The servo position is adjusted step by step, one degree per loop iteration. No need to perform a full scan every time.
* The program does not do anything special when the light levels are equal, because in that case there isn't actually much to do.
* I increased the delay between servo updates to 20 ms, as the serial communication alone can take close to 19 ms per iteration.
* You may want to add some hysteresis in order to avoid the servo jitter when it has found the optimum.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Mega attachInterrupt on pins 18 or 19 require EIFR bit set first (to clear it)?
Experimenting with external interrupts on a Mega. Pins 2 and 3 work with standard

`attachInterrupt(digitalPinToInterrupt(iPin),ISR,FALLING);`

coding and call my ISR. With pins 18 and 19 I had to add

```
EIFR = 4;

```

for pin 19, and

```
EIFR = 8;

```

for pin 18 before calling attachInterrupt(...) to get them to work. Why?

BTW, I'll add this table that I filled in by trial and error for anyone interested in Atmel (AVR) external interrupt numbers to Arduino external interrupt numbers (I won't list the AVR chip pin numbers)

```
AVR INT      5 .  4 .  3 .  2 .  1 .  0
EIFR (Dec)  32 . 16 .  8 .  4 .  2 .  1
Arduino Pin  3 .  2 . 18 . 19 . 20 . 21
Arduino INT  1 .  0 .  5 .  4 .  3 .  2

```

I know writing a 1 to the EIFR bit for the appropriate interrupt clears the interrupt. When I reset the Arduino without clearing interrupts on pins 2 and 3 it's fine. If I don't clear 18 and 19 after a reset, it throws the interrupt right away. (Yes, I should OR the EIFR with the bit I want to change but I'm just playing) Didn't try 20 and 21 because I'm using them for comm.

# Answer
> 2 votes
It's not that pins 18 or 19 are faulty, you are just lucky the other ones worked.

As I mention on my page about interrupts* you are recommended to always write 1 to the appropriate EIFR bit before enabling interrupts because it (the interrupt condition) may have been set in the past.

I checked the source for `attachInterrupt` in the file WInterrupts.c and there is no mention of the EIFR register, therefore `attachInterrupt` never affects that register.

---

* Also see my answer: How do interrupts work on the Arduino Uno and similar boards?

---
Tags: arduino-mega, interrupt
---


# Question
Title: How do I keep track of the time passed in this code? (PCR machine)
I am desperate need of help with my code. It is meant to be a biology project (a pcr machine) and I struggle with inplementing a time tracker. Everytime the cyclus goes to a function, I need it to save that exact time, and then lt it run for a certain amount of time (this variable is given in a parameter). So help is really really appreciated.

```
//variabelen

#include <Adafruit_MAX31855.h>

int maxSO =  4;
int maxCS = 5;
int maxSCK = 6;

Adafruit_MAX31855 thermocouple(maxSCK, maxCS, maxSO);

int fan = 9; //connected to transistor base
int temp;
int tempMin = 18;   //variable to check if the thermocouple is connected
int tempMax = 100;   //never exceed this temperature
int fanSpeed;
int RelayP = 3; //still got to check if it is 3 or 4
int cyclusamount = 3; //still got to add a button

//cyclussen op één rij
float DENTEMP = 94;
float ANTEMP = 62;
float EXTEMP = 72;

//tijden op een rij
unsigned int INITDENTIME = 53000;
unsigned int DENTIME = 33000;
unsigned int ANTIME = 33000;
unsigned int EXTIME = 33000;
unsigned int ENDEXTIME = 42000;

unsigned long timer1 = 0;
unsigned long timer2 = 0;
double temp;
double MaxTempIncrease = 2;

//int cycles = 0;
int phase = 0;
int a = 0;
int g = -1;
int phaseOfCyclus = 0;
int timesArray[] = [33000, 33000, 33000];
int tempsArray[] = [94, 62, 72];
int cycluscounter = 0;

const unsigned long startTime;
unsigned long startMillis;

void setup() {
  Serial.begin(9600);
  delay(500);
  pinMode(fan, OUTPUT);
  digitalWrite(fan, LOW);
  pinMode(RelayP, OUTPUT);
  digitalWrite(RelayP, LOW);
  delay(5500);
}

void loop() {
  //eerst is er een delay, na de delay zal a springen op a=1
if(a == 0) {
    delay(1000);
    a++;
  }

//wanneer a=1 geldt dan zal de temperatuur stijgen naar 94 graden, wanneer dit is bereikt wordt  a=2 en phaseOfCyclus=1
else if(a == 1){
     raiseTemp(DENTEMP);
  }

//wanneer a=2 geldt dan zal de temperatuur stabiel worden gehouden (dus 94 graden) voor de initiatie-stap duur, dat is ongeveer rond de 4minuten
//wanneer deze tijd is verstreken dan wordt a=3 (en phaseOfCyclus=1 (nog steeds))
else if(a == 2) {
    holdTemp(DENTEMP, INITDENTIME);
  }

else if(a == 3) {

//De eerste fase van één cyclus in de PCR machine begint met 94 graden voor 30 seconden.
//de functie raiseTemp heeft 1 parameter en die wordt verkregen door het eerste getal uit de tempsArray
//Is dit volbracht, dan wordt phaseOfCyclus=2
if(phaseOfCycles = 1) {
  raiseTemp(tempsArray[1];
}

//de temperatuur wordt dan weer stabiel gehouden, de twee parameters geven de tijdsduur en de temperatuur van de fase waarin de cyclus van de pcr machine zich bevind
//is dit volbracht en was phaseOfCyclus=2, dan wordt phaseofcyclus=3
else if (phaseOfCyclus = 2) {
  holdTemp(tempsArray[1], timesArray[1]; //hoort 0

}

//dan zal de temperatuur afkoelen tot een bepaalde temperatuur, als dit is volbracht -> als phaseofcyclus=3 dan wordt phaseofcyclus=4
else if (phaseOfCyclus = 3) {
  cooldown(tempsArray[2]; //hoort 1
}

//de temperatuur wordt weer stabiel gehouden, voor 30 seconden en als phaseofcyclus is 4 dan phaseofcyclus=5
else if (phaseOfCyclus = 4) {
  holdTemp(tempsArray[2], timesArray[2]; //hoort 1

}

//dan zal de temperatuur verder afkoelen tot een bepaalde temperatuur, als dit is volbracht -> als phaseofcyclus=5 dan wordt phaseofcyclus=6
else if (phaseOfCyclus = 5) {
  cooldown(tempsArray[3]; //hoort 2
}

//de temperatuur wordt weer stabiel gehouden, voor 30 seconden en als phaseofcyclus is 5 dan phaseofcyclus=6
//bij één hele cyclus zal holdtemp 3x worden aangeroepen, elke keer als dit dus 3x gebeurt dan zal de cyclusamount +1 in hoeveelheid toenemen
//als de cyclusamount niet gelijk is aan het aantal cyclussen dat iemand wil uitvoeren dan zal -> phaseofCyclus = 1
//is dit wel groter of gelijk aan het aantal cyclussen dat iemand wil uitvoeren dan zal -> a =4  (als a = 3 en phaseofcyclus = 6)
else if (phaseOfCyclus = 6) {
  holdTemp(tempsArray[3], timesArray[3]; //hoort 2
}}

//dan zal de extending temperatuur stabiel worden gehouden en als de tijd is verstreken dan zal a = 5 worden en zal de lcd zeggen dat de cyclus is volbracht
else if (a == 4) {
   holdTemp(EXTEMP, 42000);
  }
else if(a == 5) {
  digitalWrite(fan, LOW);
  digitalWrite(RelayP, LOW);
  Serial.println("Cyclus completed");
}
}

void raiseTemp(double y) {
  double prevTemp = thermocouple.readCelsius();
  temp = thermocouple.readCelsius();

if (temp < tempMin) {
   Serial.println("is the thermocouple connected???");
  }

while (temp < y) {
    int waittime = min(650, ((650*(y-temp))));
    digitalWrite(RelayP, HIGH);
    delay(waittime);
    digitalWrite(RelayP, LOW);
    temp=thermocouple.readCelsius();

if(temp >= y) {
    if(phaseOfCyclus = 1) {
      phaseOfCyclus = 2;
      a = 3;
    }
    else if (phaseOfCyclus = 0){
      phaseOfCyclus++;
      a = 2;
    }
      // break; //wat doet dit precies?
    }

if((y-temp) < 1) {
      do  {
        prevTemp = temp;
        delay(250);
        temp = thermocouple.readCelsius();
      }
      while(temp > prevTemp);
    }

if(temp >= TempMax)
     break;

else {
      prevTemp = temp;
   }

   while ((temp-prevTemp) >= MaxHeatIncrease) {
     prevTemp = temp;
     Serial.print("HEATING UP TOO FAST! ");
     delay(1000);
     temp = thermocouple.readCelsius();
     Serial.println(temp);
   }

   while(temp >= y) {
     delay(1000);
     Serial.print("DANGER DANGER DANGER");
     Serial.println(temp);
   }
}}

void holdTemp(double phaseTemp, double duration) {
  g++;
  z = phaseTemp;

  startMillis = millis();
  unsigned long whatitneedstobe = startTime + duration;
  //startMillis < whatitneedstobe

  if(timegone < duration){
        temp = thermocouple.readCelsius();
      if(temp < z) {
        digitalWrite(RelayP, HIGH);
        delay(90);
        digitalWrite(RelayP, LOW);
      }
      else if (temp > (z+0.5)) {
        digitalWrite(fan, HIGH);
        delay(90);
        digitalWrite(fan, LOW);
        //or
        //fanSpeed = map(temp, tempMin, y, 32, 255);
        //analogWrite(fan, fanSpeed);
      }
     delay(210);
     timegone = millis() - startTime;
     }

  else {
    if(phaseOfClus = 1) {
      a = 3;
    }
    else if(phaseOfCyclus = 2) {
      phaseOfCyclus = 3;
    }
    else if(phaseOfCyclus = 4) {
      phaseOfCyclus = 5;
    }
    else if(g == 3) {
    g = 0;
    cycluscounter++;
    if(cycluscounter < cyclusamount) {
      a = 3;
      phaseOfCyclus = 1;
    }
    else(cycluscounter >= cyclusamount {
      a = 4;
    }
  }
  else if(a = 4) {
    a = 5;
  }
    }
  }

void cooldown(double c) {
  unsigned long startTime = millis();
while ((temp = thermocouple.readCelsius()) > (minTemp+0.75)) {
    digitalWrite(fanPin, HIGH);
    delay(300);
   }
   digitalWrite(fanPin, LOW);
if(thermocouple.readCelsius() == c){
  if(phaseOfCyclus = 3) {
    phaseOfCyclus = 4;
  }
  else if(phaseOfCyclus = 5) {
    phaseOfCyclus = 6;
  }
}
}

```

# Answer
> 2 votes
If you want the `holdTemp()` function to run for a specified duration, you can write it like this:

```
void holdTemp(double phaseTemp, unsigned long duration) {
    unsigned long start_time = millis();
    while (millis() - start_time < duration) {
        // whatever...
    }
}

```

Note that if you use `delay()` inside the function, the time spent in it may get longer than the requested duration, by as much as the duration of the delay.

---
Tags: arduino-uno
---


title: Interfacing MPU6050 with Arduino uno

text:
# Question
Title: Interfacing MPU6050 with Arduino uno
What is the meaning of "volatile bool mpuInterrupt = false; " in Arduino Program interfacing MPU6050?

# Answer
> 1 votes
The i2cdevlib has that declared in this file: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/examples/MPU6050\_DMP6/MPU6050\_DMP6.ino

That is the "dmp" example.
Inside the MPU-6050 sensor is a "dmp" and a FIFO buffer. The "dmp" is a processing unit that collects the sensor data, does some calculations and puts the data in the FIFO buffer. After that the Arduino is signalled with a interrupt.

In the Arduino, in the interrupt routine, the flag 'mpuInterrupt' is set. In the loop() that flag is checked and the amount of data in the FIFO buffer is read. When there is enough data, that data is read and used in the sketch.

Since the variable 'mpuInterrupt' is used in a interrupt routine and in the loop(), it is made 'volatile'. That tells the compiler that the variable can change at any moment, so the compiler can keep that in mind when creating binary code for the loop().

---
Tags: arduino-uno, interrupt, mpu6050
---


# Question
Title: Voltage meter ADC + serial: Bytes lost during communication
I want to make a simple digital voltage monitor. So I have a sketch:

```
void setup() {
  Serial.begin(115200);
}

void loop() {
  int val = analogRead(A4);     // read the input pin
  val = 1;
  byte buf[4];
  buf[0] = 0;
  buf[1] = 0;
  buf[2] = val & 255;
  buf[3] = (val >> 8) & 255;
  Serial.write(buf, 4);             // report voltage value
}

```

When I tried to read serial buffer on PC host, I noticed that sometimes 1 byte can be lost, which lead to shifts and headache. How should the streaming be done?

---

PS.

* host os: win7 x64;
* language: c/c++
* com port library: CSerial

---

Loop is as follows:

```
typedef int32_t sample_t;
while (true) {
    int nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(sample_t));
    size_t numRead = nBytesRead / sizeof(sample_t);
    if (numRead > 0)
        std::cout << "read: " << numRead << " samples\n"; // Calculate average here!
}

```

# Answer
With help in a comments I've managed to deal with the task myself.

First of all, as @Majenko pointed out, I was dealing with some multi-byte data. So I need some control character, that separates packets. I choose hex output with '\n' delimeter as control character - that served good. I was able to read 3.5 to 5k packets per second (with voltage reading) from serial on the host.

Second improvement, credited to @Jot, is to stack some sequential values right in arduino, before sending.

Alongside with increasing sampler frequency that could be very good.

```
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

void setup() {
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  Serial.begin(115200);
}

void loop() {
  int val = 0;
  for( int i = 0; i < 32; ++i )
    val += analogRead(A0);
  Serial.print(val, HEX);
  Serial.print("\n");
}

```

at the host recieve side, some simple conversion could be done:

```
#include "Serial.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

// sample to voltage
double s2v(int sample) {
    return 5.0 * (static_cast<double>(sample) / 1024);
}

int main() {
    std::ofstream ofs("test.csv", std::ios::out | std::ios::ate);

    size_t comPort = 3;
    size_t baudRate = 115200; // 57600;

    CSerial serial;
    if (serial.Open(comPort, baudRate))
    {
        std::cout << "COM" << comPort << " opened @" << baudRate << "bit/s\n";

        // serial recv buffer
        size_t bufSize = 1048576;
        auto lpBuffer = new char[bufSize];

        // accumulator
        size_t nVals = 0;
        int nAcc = 0;

        // timer
        __time64_t destTime;
        __time64_t destTime2;
        _time64(&destTime);

        while (true) {
            SleepEx(10, false); // care of 100% cpu core usage, poll serial port lazily
            size_t nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(lpBuffer[0]));

            //parse buffer:
            size_t cvtPtr = 0;
            for (size_t i = 0; i < nBytesRead; ++i) {
                if (lpBuffer[i] == '\n') {
                    try {
                        lpBuffer[i] = '\0';
                        auto val = std::stoi(lpBuffer + cvtPtr, nullptr, 16);
                        nAcc += val;
                        nVals++;
                    }
                    catch (...) {
                        // ignore, or warn that serial recieved junk/empty packet
                    }
                    cvtPtr = i + 1;
                }
            }

            //check if doom had come!
            _time64(&destTime2);
            if ((destTime2 - destTime) > 0) {
                auto fVoltage = ( s2v(nAcc) / 32 ) / nVals;
                std::cout << fVoltage << "\t(" << nVals << " ksps)\n";
                ofs << destTime << "," << fVoltage << "," << nVals << "\n";
                if((destTime % 30 ) == 0) // care of disk, write only once in 30 seconds
                    ofs.flush();
                destTime = destTime2;
                nVals = 0;
                nAcc = 0;
            }
        } // while
    } // if opened
    return 0;
}

```

That gives voltmeter with high precision, about ±0.5mV, that is updated every second.

Also! It was stated about 10bit adc, 5.0V/1024 = 4.88mV, but i got some subthreshold oscillations in vivo, adding samples up. So you are wrong, noise can be attenuated and resolution can be artificially pumbed up, in a trade for increased sampling time. Here is 14bit ADC built on top of 10bit ADC: . Its photovoltaic cell in a dark street, oscillations are caused by cars' front lights. Timescale is 1000 seconds per grid div
> 0 votes

---
Tags: serial, adc, analog-sampling
---


# Question
Title: Calculate burden resistor value of current transformer and measure ac current with arduino
I Want to measure AC current with current transformer but i dont know exact value of burden resistor or calculation formula...i want to measure current of borewell pump. company specified pump as 1.5Hp power.

# Answer
There is no "You need X resistor for Y transformer". The resistor you choose depends on what current range you are working with and what voltage range you want that to be expressed as.

That transformer is a 100:5 (or more properly a 20:1) ratio. That means for every 20A going through it you get 1A out.

That output current is then passed through a burden resistor and you measure the voltage across that resistor.

If you are, for example, working with sensing up to 1A current then the maximum current you'd get out of it would be 1/20A, or 50mA. If you want that to be expressed reliably within the range of a 5V ADC then you would:

1. Work from the mid-range of the ADC as 0V to give ±2.5V (assuming AC)
2. Calculate the resistor that gives 2.5V across it when 50mA is passed through it
3. Pick the next-lowest common resistor value.
4. Reverse the calculation to get the voltage range you now have.

In this example, R=V/I, so 2.5/0.05 = 50Ω. 50Ω resistors aren't common, but 47Ω ones are, so you'd pick that.

Then reversing it gives V=IR = 0.05 * 47 = ±2.35V

Give it a 2.5V offset to the ADC and you can now read points on a sinewave between 0.15V and 4.85V at 1A sensed current.
> 4 votes

---
Tags: arduino-uno, electricity
---


# Question
Title: Command through Serial monitor does not properly work in Arduino
I am executing a function in Arduino by giving String input to the serial monitor.

The issue here is when I enter `SHOW$`, the function `showData()` works but when I enter the same `SHOW$`, it doesn't gets called. I want to call the function `showData()` every time i enter the `SHOW$` text into the serial console.

My question here is to what mistake I am doing here, and what is the solution for this.

```
String strReq = "";
char inChar = 0;

void setup() {

  Serial.begin(9600);

}

void loop() {

  while (Serial.available())
  {
    inChar = Serial.read();

    if (inChar == '$') {

     Serial.println(" Received String :");
     Serial.print(strReq);

     if (strReq.equalsIgnoreCase("SHOW"))
       showData();

     Serial.flush();
     strReq = "";

    } else {

      strReq = strReq + inChar;
    }
  }
}

void showData() {
  Serial.print("Showing Information");
}

```

# Answer
> 0 votes
The solution was to use String.trim() function. Thanks guys for giving a quick reply on the question.

# Answer
> 1 votes
The root of your problem seems to be not knowing what `Serial.flush()` does.

It pre-Arduino 1.0.0 times `Serial.flush()` used to clear any data in the serial's RX buffer. It would throw it away. In your code that would throw away the line ending `\r\n` that is sent along with the command.

However in Arduino 1.0.0 it was changed to instead block execution until all bytes had been sent out of the Serial TX buffer. This was deemed more useful, and a replacement to the original functionality is very easy to implement if needed.

This change was not widely documented, but it is mentioned in the manual:

> Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)

So with `Serial.flush()` acting like it does in current versions, you would get a different string the second time around. You would see:

```
SHOW$
\r\nSHOW$
\r\nSHOW$

```

and so on.

You have come up with a "fix", which uses `String::trim()` to discard any leading and trailing non-printable characters, which removes the line-endings from your subsequent strings. However it would be far better to ignore them in the first place and not need to do the trimming.

The simplest way would be to only add characters to your string if they are printable:

```
if (inChar == '$') {
 Serial.println(" Received String :");
 Serial.print(strReq);
 if (strReq.equalsIgnoreCase("SHOW"))
   showData();
 Serial.flush();
 strReq = "";
} else if (inChar >= ' ') { // << Only add if a space or above
  strReq = strReq + inChar;
}

```

A simple change, but one which then means you're not having to add the extra processing of trimming unwanted characters from the string.

---
Tags: arduino-uno, serial, string, serial-data
---


# Question
Title: 2.8 inch tft LCD displays / Max Brightness / Startup White Screen / mirror text for Head Up Display Usage
hi does anyone know how to

1) set Max Brightness
2) change the start up splash screen from being white to black
3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

The code from the sketch may answer some of your tecnical question re the environment i am working with

```
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library

#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0

```

# Answer
> 1) set Max Brightness

You set the brightness of the backlight (usually) using PWM.

> 2) change the start up splash screen from being white to black

That's not a splash screen. That's just the back light being on before the screen is initialised. Just don't turn on the back light until you need it.

> 3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

Either do it in software (tricky) or look at the MADCTL (many have it called that) register in the datasheet. The library probably won't support it, but it's part of how it deals with display rotation, so you could examine that function and compare it with what's in the datasheet (hint: 180° rotation is actually flipping both the X and Y axis).
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: noisy output lines when waking up from a sleep
Using code similar to these examples from AVR

https://www.microchip.com/webdoc/AVRLibcReferenceManual/group\__avr\__sleep.html

my program causes my Adafruit Feather 32u4 to often sleep. When the firmware has nothing to do it will sleep about 75% of the time. Typically after several hours of operation there will be corruption on the LCD display. The elapsed time to the corruption is not deterministic.

When it sleeps or wakes up from sleep I believe the processor sends garbage to the LCD module via the SPI (serial) lines. I have no oscilloscope to observe this but the problem seems to be removed if I comment out the sleep code.

A description of the Adafruit ST7565 LCD module is at this link

https://www.adafruit.com/product/250.

My Arduino setup code relevant to sleeping is this:

```
cli(); // atomic operation begins here
WDTCSR = bit(WDCE) | bit(WDE); // enter a very brief change mode
WDTCSR = bit(WDP2); // prescaler without reset mode, 1001 means 8 seconds, 0101 means 0.5 seconds, 0100 means 0.25 seconds, 0011 means 0.125 seconds
WDTCSR = bit(WDIE); // use interrrupt mode because we do not want an WDT triggered reset
sei(); // global interrupt enable
set_sleep_mode(SLEEP_MODE_PWR_DOWN);

```

My sleep code in the Arduino loop is adapted from the AVR webpage and is invoked if the firmware is not busy, is as follows:

```
cli(); // atomic operation begins here
sleep_enable();
sei();
sleep_cpu();
sleep_disable();

```

The watchdog ISR for when it wakes up is an empty function, as follows:

```
ISR(WDT_vect) // need this to avoid a reset
{ // no code here
}

```

I have a little bit of other evidence that some lines are uncontrolled when the processor wakes up. The evidence comes from my rotary encoders. I see false encoder activity sometimes when the processor wakes up and I eliminated this problem by putting some "debounce code" in the watchdog ISR. I also make sure the encoder lines use the processor's internal pull-up resistors. Note that I already have debounce code for the encoders for the purpose of doing actual debouncing of the activity of actually touching the encoders. The additional "debounce code" in the watchdog ISR is for the situation in which I am not even touching the encoders but the processor is waking up and the lines are noisy. The encoder "debounce code" is not shown in the watchdog ISR code snippet because it's not relevant to my LCD problem.

The pull-up and debounce remedy for encoder input lines is not applicable to my LCD problem because the LCD involves output lines.

Edit: I tried to solve it by setting high the active low chip select of the LCD before sleep and then reverting the line upon waking up (in the watchdog ISR). This had the effect of making the display very sluggish. I update the display once per second and it seemed to be updating only once every 2 or 3 seconds. I have not analyzed whether my "direct intervention" is incompatible with the Adafruit library for this LCD.

The LCD library: https://github.com/adafruit/ST7565-LCD

The boards are as pictured. The encoder board has 2 encoders wired up and 2 encoders unused. The encoder board sits on a 3mm thick piece of foam and is clamped to the desk. The breadboard is attached to the desk via the double sided foam tape that seems to be standard on this item.

Addendum: Given Nick Gammon's answer, I will run with the following to see if the problem is eliminated. Since the corruption is not deterministic, it may take many hours or days before I form an opinion.

```
  cli(); // atomic operation begins here
  WDTCSR = bit(WDCE); // enter a brief change mode
  WDTCSR = bit(WDIE) | bit(WDP2); // 1001=8s, 0101=0.5s, 0100=0.25s, 0011=0.125s
  sei(); // global interrupt enable
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

```

After less than 10 hours there was corruption on the LCD. I will test with the following.

```
  cli(); // atomic operation begins here
  WDTCSR = bit(WDCE) | bit(WDE); // enter a brief change mode
  WDTCSR = bit(WDIE) | bit(WDP2); // 1001=8s, 0101=0.5s, 0100=0.25s, 0011=0.125s
  sei(); // global interrupt enable
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

```

The above still failed after several hours.

# Answer
```
WDTCSR = bit(WDCE) | bit(WDE); // enter a very brief change mode
WDTCSR = bit(WDP2); // prescaler without reset mode, 1001 means 8 seconds, 0101 means 0.5 seconds, 0100 means 0.25 seconds, 0011 means 0.125 seconds
WDTCSR = bit(WDIE); // use interrrupt mode because we do not want an WDT triggered reset

```

Your code above is not doing a WDT interrupt every 0.25 seconds as you appear to be wanting, because you assign (not OR) in the third line. That means WDP0/WDP1/WDP2?WDP3 will all be zero which means the watchdog will fire every 16 ms.

> This had the effect of making the display very sluggish.

I'm not totally surprised, if you interrupt every 16 ms.

---

> I have a little bit of other evidence that some lines are uncontrolled when the processor wakes up.

The lines should remain what they were set to when the processor sleeps. It wouldn't be very useful to sleep if the processor started outputting random junk while asleep. I can't comment further as I can only see part of your code.
> 2 votes

---
Tags: spi, adafruit, avr, sleep
---


# Question
Title: Flashing ATmega8U2 using another Arduino
I have an Anduino Uno R1 and the ATmega8U2 on. It does not respond correctly. How can I use another Arduino Uno R3 in order to reinstall the correct firmware? What I want to avoid it to solder the resistor because I am not very good with the soldering iron.

As fas as I understand there are some pins close to the AREF pin that can be used in order to attach a programmer. Also how can I temporally attach them without the need of a soldering iron? On the R1 the pins are just some exposed metal. How can I connect to them?

Also, if I load into the other Arduino the programmer, then how can I load the firmware using GNU/Linux into the ATmega8U2?

# Answer
There is an official guide. Arduino as ISP and Arduino Bootloaders

But you need to add the 2x3 ISP pin header since some of the signals isn't available on D0-D13 or any other pins.
> 1 votes

---
Tags: arduino-uno, usb, isp, programmer
---


title: Voltage sensor Calibration

text:
# Question
Title: Voltage sensor Calibration
We had used a voltage sensor unit to measure the voltage of the odroid board using an Arduino Uno. wWhen I uploaded the sketch and got the output, the value which was being displayed was around 4.7 to 4.9V, but when I measured the top of the voltage sensor module using a multimeter, it had a stable voltage of 5.08V. Is their any particular reason why this is happening?

Voltage sensor module

```
int analogInput = A0;
float vout = 0.0;
float vin = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
int value = 0;
void setup() {
pinMode(analogInput, INPUT);
  Serial.begin(9600);
  Serial.print("DC VOLTMETER");
}
void loop() {
  // read the value at analog input
value = analogRead(analogInput);
vout = (value * 5.0) / 1024.0;
vin = vout / (R2 / (R1 + R2));
Serial.print("INPUT V= ");
Serial.println(vin, 2);
delay(500);
}

```

# Answer
Multimeters are designed to provide a stable response. It would be averaging the readings.

As far as the difference in voltage reading, if you are using the Arduino board as is the default is to assume a reference voltage for the A/D as being 5.0 volts.(for your calculations) That may not be the case. Also there may be a tolerance issue on the measurement board, but I think the reference for the A/D on the Arduino is the bigger issue.
> 1 votes

---
Tags: arduino-uno, sensors, voltage
---


title: Upload data to MAX 7219

text:
# Question
Title: Upload data to MAX 7219
I have the following code to write data on MAX7219 for light up a 8x8 LED Matrix:

```
for (i = 0; i < 8; i++)
{
    CLK = LOW;
    DIN = temp & MSBIT >> i;
    CLK = HIGH;
}

```

The thing is, sadly, I just know that the code line `(DIN = temp & MSBIT >> i;)`, must be exactly like that, otherwise the LED´s won't show the expected, but I don't understand how it works...

Please, I really need explanation because I'm stuck....

Note: variable "temp" is always a hexadecimal number like `0x20`, and `"MSBIT" = 0x80`.

# Answer
> 0 votes
You have to send 16 bits to load data. The first 8 are the register the data goes into, 0 to 15, the next 8 are the data to be displayed. Registers 1-8 are the data that gets displayed, the others are used to set up: intensity, display test, normal/shutdow, decode/no decode mode, and number of digits/columns connected (such as 4 digits, or 8 for an 8x8 matrix).

In Arduino, I use hardware SPI to send data to MAX7219 - SCK, MOSI, and SS.

```
digitalWrite (ssPin, LOW);
SPI.transfer(addressRegister); // 0 to 15
SPI.transfer(dataToLoad);
digitalWrite (ssPin, HIGH);

```

Do that for each register. The control registers only need to be written once. In Arduino, that is usually in setup(). Intensity might be changed later for brightness (0 to 15 as valid data).

In loop(), use the above to update your display for the 8 display data registers (1-8).

---
Tags: max7219
---


# Question
Title: 5V 10A 4 channel relay to 2 lights15W light in series in 220V AC supply
I am trying to setup my first relay module with live environment. I have attached the relay module image below.

Which I am using to control 4 devices in my switch board as follows:

1. Fan (working fine),
2. 6w celling LED panel (2 connected in series) (Working fine)
3. 15w celling LED panel (2 connected in series) (Sometimes work sometimes don't)
4. Spotlights 3 lights in series and some LED strips connected to it (Sometimes works sometimes don't.).

I have cut one wire which is connected to main normal mechanical switch WHICH IS NOT A HOT WIRE its just the another wire connected to the button.

But I am not sure why its not working? Do I need to connect neutral to the another end of the relay. As I have only 2 wires connected to the relay for each of the switches. Here is a screenshot of specifications 15watt LED panel which is connected to my house, if this can help to understand better.

If I connect Neutral on the first pin of relay and when I close the relay switch, do the current will go into the neutral wire as well?

If I keep my 3w spotlights ON or more then 3-4 hours and try to close the relay on connected to it. The relay LED light for that connected relay goes OFF but the light don't. Seems like the mechanical relay is not getting enough power to move the mechanical relay off.

I want to know why this is happening? And how can I solve this issue? Attaching a neutral (earth) wire will help to reduce this? But if connect neutral to first (off side of relay) pin, then will get the current?

Any suggestions will be helpful. Also I added 3.3v from NodeMCU to VCC (instead of jumper) pin. But that is also not helpful.

# Answer
You need to connect Vin from NodeMCU (Raw 5V from USB) to Vcc on the relay board.

And as stated in the comments, the relay need 5V for operating reliable.

In has the same problem, two LEDs and a resistor. To enhance it would be to replace the indicator LED (DS1-4) with a wire.

2 x LEDS á ~1.8V and a resistor á ~1.4V = 5 Volt.

1 x LED á ~1.8V and a resistor á ~1.4V = 3.2 Volt.
> 0 votes

---
Tags: esp8266, nodemcu, relay
---


# Question
Title: Question on how "f" value is calculated in converting Morse Code to laser audio from this tutorial
I am working on this tutorial,

https://www.hackster.io/SURYATEJA/morse-code-communication-using-laser-module-both-ea1b01

and the author created a "Send" and "Receive" code for encoding and decoding Morse code. He created the "Send" code with the entire alphabet A-Z, but his receive code only has 9 letters.

I thought I could easily add in the missing characters, and even add in numbers, but I am stuck.

His code has 2 values to decode the morse - "a" and "f"

In his receive code he has a value "f" that is supposed to be calculated by the number of spaces, but I cannot see how he comes up with his result.

For example, this is his sending code for "a"

```
    case 'a':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;

```

Then this is the receive code;

```
if(a==4 && f==10) {   Serial.print("a");

```

I understand the value of 4 for "a", but I cannot understand the value of 10 for "f"

"a" is calculated by assigning a value of 1 for a dot and 3 for a dash and adding the values (in this case one dot and one dash, 1+3 = 4)

He explains how to calculate "f" here in his tutorial, but I still don't understand.

2. When the LASER falls on the LDR, the value goes beyond 1000, and then it will enter into a loop.
3. Now quantize the values i.e. if the value goes beyond 1000, then assign it as '1', otherwise assign it as '0'.
4. Inside a loop, calculate the number of '1's and '0's. Set the counters 'a' and 'f'. Count the number of '1's and store it in 'a' and similarly count the number of '0's and store it in 'f' respectively.
5. Now check the specific values of 'a' and 'f' respectively. Each character will have different set of 'a' and 'f'. The matching value will be displayed.

That seems to indicate; Laser on = Over 1000 = 1 Laser off = Under 1000 = 0

So for the letter a, I only see 2 times the laser goes off, not 10.Minof formatting changes

# Answer
> 2 votes
This is not a good tutorial. The receiver works by assuming 14 `dotLen` time periods for each character. There is a loop that runs 14 times, with a 200ms delay between each iteration. If the laser is detected, then `a` is incremented, otherwise `f` is incremented. This means that the sum of `a` and `f` is always 14, and the case where `a==0` means nothing was transmitted. The incomplete receiver code shows only 10 options for received characters and leaves out `a==5` (which would be `R` or `U`), but does define 1 through 10 otherwise.

The receiver code does not differentiate between dots and dashes, it only counts the number of `dotLen` transitions where light is detected. This is not Morse Code.

The receiver code cannot distinguish between `S` (dot-dot-dot) and `T` (dash) because they both have 3 `dotLen` value. Same for `A` (dot-dash) vs. `N` (dash-dot).

If you want to understand decoding morse code, this is not a good tutorial to follow. It does not decode morse code, and I cannot see how it would work even with it's companion transmitter program.

---
Tags: serial, arduino-ide, serial-data, data
---


title: Serial.write printing blank values

text:
# Question
Title: Serial.write printing blank values
I've got an Adafruit Bluefruit NRF52 hooked up to the Adafruit BNO055 9-axis orientation sensor, but when I use Serial.write to send the data, serial monitor displays blank values only. The scroll bar drops so something I definitely appearing, it just seems to be empty.

Serial.print works fine, but I cannot use this for my application, as it uses too much memory.

I'm gathering 3 axis of absolute orientation plus 3 axis of acceleration (6 floats in total) plus a three digit number representing the calibration of each sensor.

Each line should look something like

```
303 68.69   4.19    -2.19   -0.12   0.14    -0.40

```

My code:

```
void displayCalStatus(void)
{

  uint8_t system, gyro, accel, mag;
  system = gyro = accel = mag = 0;
  bno.getCalibration(&system, &gyro, &accel, &mag);

  /* Display the individual values */
  Serial.write(gyro);
  Serial.write(accel);
  Serial.write(mag);
  Serial.write("\t");
}

void loop()
{
  imu::Vector<3> accel = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL);

  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  displayCalStatus();

  /* Display the floating point data */
  Serial.write(event.orientation.x);
  Serial.write("\t");
  Serial.write(event.orientation.y);
  Serial.write("\t");
  Serial.write(event.orientation.z);
  Serial.write("\t");

    /* Display the floating point data for Linear Acceleration */
  Serial.write(accel.x());
  Serial.write("\t");
  Serial.write(accel.y());
  Serial.write("\t");
  Serial.write(accel.z());
  Serial.write("\n");
}

```

# Answer
**Problem 1:**

You wish to send/display on the *Serial Monitor* the `int` and `float` values generated by your sensor, but `Serial.print()` uses too much memory.

**Solution 1:**

Optimize your sketch to use less memory.

---

**Problem 2:**

`Serial.write()` doesn't cause the values to show up on Serial Monitor, but *something* is getting sent, because I see scrolling activity.

**Solution 2:**

`Serial.write()` sends raw bytes, whereas `Serial.print()` converts a variable to a string (or series of ASCII bytes) and sends that string. For example, `Serial.write(65)` sends `A` to the Serial Monitor because the ASCII value of `A` is `65`; `Serial.print(65)` sends `65` to the Serial Monitor because it converts the numeric value `65` into a string containing the character `6` and the character `5`, and sends that string to Serial Monitor.

The Serial Monitor expects only ASCII data. You are using Serial Monitor for development/debugging, but your final application does not require ASCII, only to transmit the numbers.

`Serial.write()` comes in a few forms. One is `Serial.write(val)` which sends a single byte (named `val`, of type `byte` or compatible). Another is `Serial.write(buf, len)` which sends a series of `len` bytes, starting at the address of memory pointed by by `buf`. (This is often when `buf` is an array of bytes, so `buf` points to the first element of the array.)

If you wanted to send the 4 bytes of a `float` using `Serial.write()`, you could call:

```
Serial.write(&(event.orientation.x), sizeof(event.orientation.x);

```

As an alternative, you can use *bit shifting* to send one byte at a time of the 4-byte float:

```
Serial.write((byte)((event.orientation.x & 0xFF000000) >> 24);
Serial.write((byte)((event.orientation.x & 0x00FF0000) >> 16);
Serial.write((byte)((event.orientation.x & 0x0000FF00) >>  8);
Serial.write((byte)((event.orientation.x & 0x000000FF)      );

```

On the receiving end, you need to reconstruct your float by doing the reverse.

But you have multiple 4-byte values to send, in rapid repeating loop, so what happens if your receiver and transmitter get out of sync? Then you might want to put in a "flag" value to indicate the start of a sequence of data and a different flag for the stop of a sequence of data. What happens if your start or stop "flag" value actually shows up as one of the bytes you send as part of a real data byte? Then you need to find some way to modify the "real" data so that it's not to be construed as a flag.

This looks to be getting complicated now? Fortunately, these problems have existed and been solved for decades. Unfortunately, there is no consensus on the best or right way.

I did a quick search and found this arduino library that facilitates packet-based serial communication:

https://github.com/bakercp/PacketSerial

Perhaps that can help you take a bundle of numbers and send them reliably to some other system. I don't know that library in particular, and there are probably others that do something similar. This one claims to be compatible with the PySerial, COBS, and SLIP modules for dealing with packetized serial data communications.
> 1 votes

---
Tags: serial, bluetooth
---


# Question
Title: Assign and control Digital pin from String
Here is modified version of Blink example

```
#define D8  13

String p = "D8";

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(D8, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  byte pin[2];
  p.getBytes(pin, sizeof(pin));

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

```

D8 defined above is a byte of length 2. So LED turns on/off if I mention D8 on digitalWrite(D8, HIGH). Similarly I am getting the same byte D8 from `String p = "D8"`, and converting it into byte of length 2, but assigning `pin` to digitalWrite(pin, HIGH/LOW) doesn't works. Has anyone tried something similar before ? any help would be appreciated :)

# Answer
C and C++ programs get compiled in multiple passes through various programs/steps. One of the first is the *C Preprocessor*, which handles the `#define` *preprocessor directive*.

It's basically a big find/replace function. After the preprocessor is done, anywhere you had `D8` outside of a string literal, would have the value `13`. It's not a variable or a string -- it's simply the number 13.

But the `String` `p`, which has content `"D8"` doesn't get replaced by the `#define` directive because it's part of a string, and the preprocessor doesn't modify strings in that way.

Also, `p` converted to a `byte` array of length 2 does not have anything like `13` as the value. It has `0x44` and `0x38` (or, in decimal, `68` (ASCII `'D'`) and `56` (ASCII `'8'`)). Disregarding that `digitalWrite()` and `pinMode()` do not accept byte arrays, only bytes, you are passing in a byte that doesn't represent pin 13.

If you want to assign the pin via a string, then you would need to use programming to examine the string and pick the right byte value, and each possible value would have to be explicitly enumerated and checked for.
> 1 votes

---
Tags: arduino-uno, led, string, convert
---


title: Lines not pulsed fast enough (?))

text:
# Question
Title: Lines not pulsed fast enough (?))
Should this code pulse the PB3 and PB4 pins (MOSI and MISO of an Arduino Uno) at 2ms interval ?

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

int main(void)
{

//  for (byte i = 0; i < 32; i++)
//    pinMode(i, INPUT);

  DDRB |= (1 << PB4);
  DDRB |= (1 << PB3);
//  pinMode(PB4, OUTPUT);
  while (1)
  {
    PORTB &= ~(1 << PB4);
    PORTB &= ~(1 << PB3);
  //  digitalWrite(PB4, LOW);
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//    delayMicroseconds(10000);
    delay(1);
    PORTB |= (1 << PB4);
    PORTB |= (1 << PB3);
  //  digitalWrite(PB4, LOW);
//    delayMicroseconds(10000);
    delay(1);

  }
}

```

If used for SPI MOSI can do 1 MHz just fine - so my logic analyzer says. MISO would not behave when used by SPI. MISO works in other non-SPI scenario: I am able to use the Arduino for in-system programming other AVR boards.

But the code above pulses neither MISO nor MOSI, as pointed out by the same logic analyzer in the same setup. Should it?

**update**

There has been some issue with the board. Changed it and all works fine now, regardless of using `int main()` alone or also calling `init()` as per @Majenko 's answer

# Answer
The code *content* works fine while compiled as an Arduino program - that is, using the proper `setup()` and `loop()` structure:

```
void setup() {
    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
}

void loop() {
}

```

However the same code will *not* work when using it in `main()`. This is simply because `delay()` will never work. Normally `main()` calls `init()` which then configures TIMER0 to generate the `millis()` and `micros()` count used for the `delay()` functions.

So either use `setup()` and `loop()` instead of `main()`, or make your program call `init()` before anything else:

```
int main() {

    init();

    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
    return 0;
}

```
> 2 votes

---
Tags: arduino-uno, spi, avr, isp
---


title: Not receiving data from NRF24L01

text:
# Question
Title: Not receiving data from NRF24L01
I'm trying to send data from one Arduino board to another using **NRF24L01** connect to the two ends of the two Arduino boards. The **Tx** blinks in the transmitting end(Arduino board 1) but the receiving end(Arduino board 2) is not getting any value from it. Here is my code.

Transmitting end (Arduino board 1)

```
#include <SPI.h>
#include "RF24.h"

RF24 myRadio(0, 1);
byte addresses[][6] = {"0"};

struct package
{
    int id = 1;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "Geographic coordinates";
};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openWritingPipe(addresses[0]);
    delay(1000);
}

void loop()
{
    myRadio.write(&data, sizeof(data));

    Serial.print("\nPackage:");
    Serial.print(data.id);
    Serial.print("\n");
    Serial.println(data.longitude);
    Serial.println(data.latitude);
    Serial.println(data.text);
    data.id = data.id + 1;
    data.longitude = data.longitude + 0.1;
    data.latitude = data.latitude + 0.1;
    delay(1000);
}

```

Receiving end (Arduino board 2)

```
#include <SPI.h>
#include "RF24.h"

RF24 myRadio(7, 8);
struct package
{
    int id = 0;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "empty";
};

byte addresses[][6] = {"0"};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openReadingPipe(1, addresses[0]);
    myRadio.startListening();
    delay(1000);
}

void loop()
{

    if (myRadio.available())
    {
       while (myRadio.available())
       {
           myRadio.read(&data, sizeof(data));
       }
        Serial.print("\nPackage:");
        Serial.print(data.id);
        Serial.print("\n");
        Serial.println(data.longitude);
        Serial.println(data.latitude);
        Serial.println(data.text);
    }

}

```

This is how i connected the Arduino and NRF24L01

Any reason why im not getting the the data from the transmitting end?

# Answer
Check the reading and writing pipe addresses.

First, the default is `0xE7E7E7E7E7` for pipe 0 (RX\_ADDR\_P0) and `0xC2C2C2C2C2` for pipe 1 (RX\_ADDR\_P1), see the data sheet. Check that the transmitter (TX) address is the same as the receiver (RX) pipe address.

Secondly, you should not set the pipe address to `0x0` even if that's common between the TX and RX. This note comes from the data sheet:

> Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate
> 2 votes

---
Tags: arduino-uno, nrf24l01+
---


title: Arduino Nano PWM frequency

text:
# Question
Title: Arduino Nano PWM frequency
I have been using an Arduino Nano as a PWM controller for a heating element.

I am currently using **D11** (PB3). I could change, although all pins with PWM are in use, and would require a re-write and re-wire.

This produces a signal at ~490Hz, but I would like to experiment with changing this to a higher frequesncy.

I gather it its possible to vary the frequency by changing the divisor from its default 64.

My sketch uses Uses http://playground.arduino.cc/Main/SevenSegmentLibrary and calls millis() - will changing PWM divisor impact on either of these?

NOTE I have read the `setPwmFrequency` documentation, but find "disrupts the normal operation" unhelpful - I am actually after some explanation of the concrete effect. I only use `millis()` to time button presses and flash a LED, which are not time critical

*Please keep in mind that changing the PWM frequency changes the Atmega's timers and disrupts the normal operation of many functions that rely on time (delay(), millis(), Servo library).*

I have been doing some further study. http://playground.arduino.cc/Code/PwmFrequency states *Changes on pins 3, 5, 6, or 11 may cause the delay() and millis() functions to stop working.*

Other references say 3, 11 use `timer 2` so **do they affect `millis()` or not** as other references claim `timer 0` is used for these.

# Answer
I don't know where this misinformation comes from... The answer is **no**, reconfiguring Timer 2 does **not** affect `millis()` nor `delay()`, as these functions rely on Timer 0. AFAIK the Arduino core does not use Timer 2 at all. But note that there may be other Arduino or third party libraries that rely on Timer 2.

You can see here the source code of `millis()` and `delay()`.

As MITU RAJ correctly states in his answer, the PWM signal on pin 11 is provided by Timer 2, so you can use it safely.
> 2 votes

# Answer
Depends on the pin you used for the PWM.

***Arduino UNO/NANO specs say following things:***

The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.

The base frequency for pins 5 and 6 is 62500 Hz.

The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64, 256, and 1024.

The divisors available on pins 3 and 11 are: 1, 8, 32, 64, 128, 256, and 1024.

PWM frequencies are tied together in pairs of pins. If one in a pair is changed, the other is also changed to match.

Pins 5 and 6 are paired on timer0.

Pins 9 and 10 are paired on timer1.

Pins 3 and 11 are paired on timer2.

**Changes on pins 3, 5, 6, or 11 may cause the delay() and millis() functions to stop working. Other timing-related functions may also be affected.**
> 2 votes

# Answer
The answer is **NO**, changing the PWM divider for pin 11 will not affect the `millis()` function (nor `delay()`).

---

**Explanation:**
The Arduino Nano uses the ATMega328P microcontroller, same as the Arduino Uno.

Pin 11's PWM is controlled by Timer 2. By default Timer 2 has a prescale of 64 (ie. setting 0x04). The base frequency of Timer 2 is 31372.55 Hz resulting in a frequency of 490.2 Hz (ie. 31372.55/64 = 490.1961).

On the other hand, the microsecond timer (ie. the one used by `millis()`, `micros()`, `delay()` and `delayMicroseconds()`) is controlled by Timer 0.

So changing the prescaler of Timer 2 will not affect `millis()`.

It will however change the PWM frequency of Pin 3.

---

**Back to your question:**
The possible PWM frequencies of Pin 11 (higher than 488 Hz) are:

31373 / 32 = 980.4 Hz
31373 / 8 = 3921.6 Hz
31373 / 1 = 31373 Hz

Where 32, 8, 1 are the prescaler.
Which equates to a setting value of 0x03, 0x02 & 0x01 respectively.

Add this line of code:

```
TCCR2B = TCCR2B & 0b11111000 | setting;

```

Where `setting` is the value of the setting for the respective prescaler.

```
============================================
|| Frequency [Hz] || Prescaler || Setting ||
============================================
|| 31373.55       || 1         || 0x01    ||
|| 3921.57        || 8         || 0x02    ||
|| 980.39         || 32        || 0x03    ||
|| 490.20         || 64        || 0x04    ||
|| 245.10         || 128       || 0x05    ||
|| 122.55         || 256       || 0x06    ||
|| 30.64          || 1024      || 0x07    ||
============================================

```

Source code: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c
> 2 votes

---
Tags: pwm
---


title: Count fuel liters with Arduino

text:
# Question
Title: Count fuel liters with Arduino
We have created a fuel sensor in our lab with Arduino in order to get fuel data from vehicles. Regarding the code below, I receive an error

> PARSE ERROR: 'attachInterrupt': this function needs to be defined.

Could you please advice?

```
int pin = 2;
volatile unsigned int pulse;
float volume = 0;
float flow_rate =0;
const int pulses_per_litre = 2000;
int count_pulse;

void setup()
{
    Serial.begin(9600);
    pinMode(pin, INPUT);
    attachInterrupt(0, count_pulse, RISING);

}

void loop()
{
    pulse=0;
    interrupts();
    delay(1000);
    noInterrupts();

    Serial.print("Pulses per second: ");
    Serial.println(pulse);

    flow_rate = pulse * 1000/pulses_per_litre; //

    Serial.print("FUEL FLOW rate: ");
    Serial.print(flow_rate);
    Serial.println(" milliliters per second");

    volume = volume + flow_rate * 0.1; //Time Interval is 0.1 second

    Serial.print("Volume: ");
    Serial.print(volume);
    Serial.println(" milliliters");
}

void count_pulse()
{
pulse++;}

```

# Answer
You have declared `count_pulse` as a variable and NOT as function prototype.

```
int pin = 2;
volatile unsigned int pulse;
float volume = 0;
float flow_rate =0;
const int pulses_per_litre = 2000;

void count_pulse(); \\ <--- Function prototype

void setup()
{
    Serial.begin(9600);
    pinMode(pin, INPUT);
    attachInterrupt(0, count_pulse, RISING);
}

```
> 1 votes

# Answer
Just initialize `pulse` to zero in its definition at line 2.

The message "'pulse': used without being explicitly initialized" is due to the count\_pulse() function: The compiler can't analyze the run-time behavior of the code, nor your intentions. Some interrupts could arrive before loop() runs, so in fact, `pulse` could very well get incremented without having been initialized. You may not care about and can discard the first few readings, but the compiler doesn't (and shouldn't!) guess that.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding
I have a Arduino Nano (Sainsmart) that I'm trying to upload a sketch to. Under the Arduino IDE, the device selected was `Arduino Nano w/ ATmega328`.

However uploading the sketch gives me the error

```
avrdude: stk500_recv(): programmer is not responding

```

I tried both USB ports (`/dev/tty.usbserial` & `/dev/cu.usbserial`) but the same error persist. The Arduino is connected to a Macbook Air via the USB cable, and the `PWR` LED indicator light on the Arduino is turned on and the `L` indicator LED blinks. There was no problem uploading to a Arduino Uno.

Retried after installing the latest FTDI drivers (MAC OSX, x64, v2.2.18, FTDIUSBSerialDriver\_10\_4\_10\_5\_10\_6\_10\_7.mpkg) from http://www.ftdichip.com/Drivers/VCP.htm. However that did not help.

What could have gone wrong?

# Answer
This error message basically shows up for any communication problem, so by itself, it is not all that instructive. The Arduino Nano is supposed to have auto-reset, but maybe your clone does not? In that case, you'd have to press the reset key on the board just before starting an upload.
> 6 votes

# Answer
Know this is old but I ran onto it during my search for Nano(V3)'s not uploading so thought might help someone else. Problem is the bootloader - Arduino IDE BUT I Found an easy solution (right under my nose).

I realized that my nano's had been uploading just fine then I had finally updated the Arduino AVR Boards from 1.6.20 to 1.6.21. I didn't think there was any problems because it still showed my Nano and ATmega328 etc in the board manager after the change.

But the new boards manager has a new ATmega328 processor choice for the Nano. I changed processor: In the Arduino IDE select `TOOLS` \> `PROCESSOR` \> pulldown menu from ATmega328P to `"ATmega328P (Old Bootloader)"`.

Since then, I have uploaded many programs to several different Nano's V3 (Prolofic interace Chipset) without issue.
> 78 votes

# Answer
I was having the same problem and got the same error message. Turns out these boards don't come with a bootloader preinstalled. If you have some jumper wires and another working arduino you can use this tutorial to install the bootloader and it should work great, mine did at least! :)
> 6 votes

# Answer
Having a similar issue with my `Sainsmart Nano`.

Under `Preferences` check "Show verbose output during \[x\] upload, then when uploading, you should get a red trace like this:

```
avrdude: Version 5.11, compiled on Sep  2 2011 at 18:52:52
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/johannes/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/tty.usbserial-A403MRTP
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]

```

You'll notice a little "pause" just before the first line of `avrdude: Send: 0 [30] [20]`. Try uploading again and have you finger ready on the physical reset button of your `Nano`. *Just the moment before the first `avrdude: ...` appears, press the reset button.*

When you succeed, you'll see the screen filling with all sort of gibberish, and ending something like this after a few seconds:

```
[78] . [00] S [53] h [68] o [6f] u [75] l [6c] d [64]   [20] b [62] e [65]   [20] 0 [30] x [78] 4 [34] 9 [39] D [44] 4 [34] . [00] . [01] . [00] . [00] . [00] . [02] . [00] . [03] . [00] . [04] . [00] . [00] . [00] . [00] . [00] . [e6] . [06] . [b5] . [06] n [6e] . [06] w [77] . [06] . [8c] . [06] . [9d] . [06] . [00] . [00] . [00] . [00] . [02] . [0d] . [aa] . [0d] . [95] . [0c] . [c9] . [0c] . [a9] . [0c] . [f2] . [0c] . [00]
avrdude: Recv: . [10]
# | 100% 3.71s

avrdude: verifying ...
avrdude: 8824 bytes of flash verified
avrdude: Send: Q [51]   [20]
avrdude: Recv: . [14]
avrdude: Recv: . [10]

avrdude done.  Thank you.

```
> 5 votes

# Answer
I recently had the same issue with 3 Nano boards I just purchased from Amazon. I can confirm that the suggested fix (changing to "old bootloader") solved my problem.

I think the main problem is the upload speed. The "old bootloader" version successfully uploads at 57600, but the default "new" version tries to upload at 115200 and fails.
> 4 votes

# Answer
Did you remember to tell the IDE that the board type is a Nano?

`Tools` -\> `Board` =\> `Arduino Nano ...`

This gets me every time I swap between my Nano and Uno.
> 3 votes

# Answer
I also had that error message. I think there are many possible causes, so I haste to specify my special case.

I have a hackintosh with OS X Yosemite 10.10.2, Arduino software 1.0.6 and Funduino UNO. Uploading the example for Serial.write() succeeded the first time. Thereafter most uploads failed. Even when the upload succeeded the serial monitor would not always show output.

This seemed to me to be due to miscommunication on the USB port. I had to repeatedly reset the funduino, unplug and replug the USB cable or even restart the system. When replugging the USB cable sometimes my system would freeze.

By googling I found a solution to "Inserting USB device causes Mavericks 10.9.1 to freeze". Answer no 12 on tonymacx86.com basically instructs you to remove GenericUSBXHCI.kext from /System/Library/Extensions.

I am happy to report that after removing this kext I have no problems uploading the example and monitoring the output. Because I don't need to replug the USB cable I don't know whether this solves my system freeze. I'm not even sure it was a system freeze, because my system may only have become unresponsive to my USB keyboard and mouse.
> 2 votes

# Answer
Had same issue and solution was as follows:

* identified my arduino as CH340/ATmega168P (written on PCB)
* went to IDE and picked from list not UNO but "Arduino Pro or Pro Mini"
* when this option is selected new menu "Processor" selection is available (just under Board selection)
* selected my processor ATmega168P there and upload worked like a charm!
> 2 votes

# Answer
The Arduino IDE version 1.8.5 gave the same error every time I tried to connect it to my OSEPP Nano. I tried with multiple nano boards with different versions of the IDE. I had the board set to "Arduino Nano".

The solution was: **Instead of Nano choose Arduino/Genuino Uno**. This worked for me.
> 1 votes

# Answer
If this doesn't work you will have to use spi to program the nano. You'll need to look up the connection and use a uno since it has a serial chip at16u2 with a driver that recognizes all atmel products. After connections setting uno as a programmer by flashing the uno as isp set the programmer as Arduino as isp and flash the chip. Double check. The benefit is it is less error prone than uart and has better timing but is a hassle to wire up. Good Luck
> 0 votes

# Answer
That problem, ocurred to me when I upgraded the Arduino IDE. I solved it by changing the processor to "old"

Tools-\>Processor-\>"ATmega328P (old bootloader)" thanks!!!!
> 0 votes

# Answer
Ok. I had the same `programmer is not responding` error on Arduino Nano on Atmel MEGA168PA, USB chip: CH340G. Macbook Pro under macOS 10.14.2.

It hand Blink example installed and the port wasn't visible in the list.

I was trying to figured out, whats wrong and connected my **Arduino Due** through the programming port. After 2 attempts the sketch was uploaded... Then I connected the Nano back, the port was visible this time (actually two of them: `/dev/cu.wchusbserial14120` and `/dev/cu.usbserial-14120`) and guess what, the upload had been successful!

Magic!
> 0 votes

---
Tags: programming, serial, uploading, sketch, arduino-nano
---


# Question
Title: How do you remove dependencies from a library?
I'm writing a library for a project i created, but it depends on the Neopixel library from adafruit. I want to remove this dependency and have my library be a stand-alone library.

Is there a way to run a ws2811 chip without the neopixel or similar library?

# Answer
> 1 votes
The Adafruit Neopixel library is licensed under GPL v3. You can fork a copy of this library into your own code and modify it to suit your own requirements, but if you distribute your code, your compiled project, or a product containing the library or any portion of it, you must ensure you follow the rules of the license by which the library is governed. Those terms of license may include release of the source code if you use any portion of the licensed library in a product. Opinions differ on the exact meaning of GPL v3 with libraries.

You should be able to copy the library into your own codebase and strip out the color-specific routines, put in your own application-specific data-setting routines, but use the same underlying protocol implementation.

---
Tags: library, neopixel
---