# Question
Title: How to write RFID data using the RFID-RC522 chip
I have got this library+code example from a friend, to read RFID numbers using the RFID-RC522 chip:

RFID.ino

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

/**
* RFID pins
* MOSI: Pin 11 / ICSP-4
* MISO: Pin 12 / ICSP-1
* SCK: Pin 13 / ISCP-3
* SS: Pin 10
* RST: Pin 9
*/

RFID rfid(10, 9);
unsigned char prevNum[] = {0,0,0,0,0};

void setup()
{
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
}

void loop() {
    if (rfid.isCard()){
        if (rfid.readCardSerial() && (
            rfid.serNum[0] != prevNum[0]
         or rfid.serNum[1] != prevNum[1]
         or rfid.serNum[2] != prevNum[2]
         or rfid.serNum[3] != prevNum[3]
         or rfid.serNum[4] != prevNum[4]
        )){
          Serial.println(rfid.serNum[0]);
          Serial.println(rfid.serNum[1]);
          Serial.println(rfid.serNum[2]);
          Serial.println(rfid.serNum[3]);
          Serial.println(rfid.serNum[4]);

          prevNum[0] = rfid.serNum[0];
          prevNum[1] = rfid.serNum[1];
          prevNum[2] = rfid.serNum[2];
          prevNum[3] = rfid.serNum[3];
          prevNum[4] = rfid.serNum[4];
        }
    }
}

```

RFID.h

```
/* RFID.h - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * Based on code Dr.Leong   ( WWW.B2CQSHOP.COM )
 * Created by Miguel Balboa (circuitito.com), Jan, 2012.
 */
#ifndef RFID_h
#define RFID_h

#include <Arduino.h>
#include <SPI.h>

/******************************************************************************
 * Definitions
 ******************************************************************************/
#define MAX_LEN 16   // Largo m�ximo de la matriz

//MF522 comando palabra
#define PCD_IDLE              0x00               // NO action; Y cancelar el comando
#define PCD_AUTHENT           0x0E               // autenticaci�n de clave
#define PCD_RECEIVE           0x08               // recepci�n de datos
#define PCD_TRANSMIT          0x04               // Enviar datos
#define PCD_TRANSCEIVE        0x0C               // Enviar y recibir datos
#define PCD_RESETPHASE        0x0F               // reajustar
#define PCD_CALCCRC           0x03               // CRC calcular

//Mifare_One  Tarjeta Mifare_One comando palabra
#define PICC_REQIDL           0x26               // �rea de la antena no est� tratando de entrar en el estado de reposo
#define PICC_REQALL           0x52               // Todas las cartas para encontrar el �rea de la antena
#define PICC_ANTICOLL         0x93               // anti-colisi�n
#define PICC_SElECTTAG        0x93               // elecci�n de tarjeta
#define PICC_AUTHENT1A        0x60               // verificaci�n key A
#define PICC_AUTHENT1B        0x61               // verificaci�n Key B
#define PICC_READ             0x30               // leer bloque
#define PICC_WRITE            0xA0               // Escribir en el bloque
#define PICC_DECREMENT        0xC0               // cargo
#define PICC_INCREMENT        0xC1               // recargar
#define PICC_RESTORE          0xC2               // Transferencia de datos de bloque de buffer
#define PICC_TRANSFER         0xB0               // Guardar los datos en el b�fer
#define PICC_HALT             0x50               // inactividad

//MF522 C�digo de error de comunicaci�n cuando regres�
#define MI_OK                 0
#define MI_NOTAGERR           1
#define MI_ERR                2

//------------------ MFRC522 registro---------------
//Page 0:Command and Status
#define     Reserved00            0x00
#define     CommandReg            0x01
#define     CommIEnReg            0x02
#define     DivlEnReg             0x03
#define     CommIrqReg            0x04
#define     DivIrqReg             0x05
#define     ErrorReg              0x06
#define     Status1Reg            0x07
#define     Status2Reg            0x08
#define     FIFODataReg           0x09
#define     FIFOLevelReg          0x0A
#define     WaterLevelReg         0x0B
#define     ControlReg            0x0C
#define     BitFramingReg         0x0D
#define     CollReg               0x0E
#define     Reserved01            0x0F
//Page 1:Command
#define     Reserved10            0x10
#define     ModeReg               0x11
#define     TxModeReg             0x12
#define     RxModeReg             0x13
#define     TxControlReg          0x14
#define     TxAutoReg             0x15
#define     TxSelReg              0x16
#define     RxSelReg              0x17
#define     RxThresholdReg        0x18
#define     DemodReg              0x19
#define     Reserved11            0x1A
#define     Reserved12            0x1B
#define     MifareReg             0x1C
#define     Reserved13            0x1D
#define     Reserved14            0x1E
#define     SerialSpeedReg        0x1F
//Page 2:CFG
#define     Reserved20            0x20
#define     CRCResultRegM         0x21
#define     CRCResultRegL         0x22
#define     Reserved21            0x23
#define     ModWidthReg           0x24
#define     Reserved22            0x25
#define     RFCfgReg              0x26
#define     GsNReg                0x27
#define     CWGsPReg              0x28
#define     ModGsPReg             0x29
#define     TModeReg              0x2A
#define     TPrescalerReg         0x2B
#define     TReloadRegH           0x2C
#define     TReloadRegL           0x2D
#define     TCounterValueRegH     0x2E
#define     TCounterValueRegL     0x2F
//Page 3:TestRegister
#define     Reserved30            0x30
#define     TestSel1Reg           0x31
#define     TestSel2Reg           0x32
#define     TestPinEnReg          0x33
#define     TestPinValueReg       0x34
#define     TestBusReg            0x35
#define     AutoTestReg           0x36
#define     VersionReg            0x37
#define     AnalogTestReg         0x38
#define     TestDAC1Reg           0x39
#define     TestDAC2Reg           0x3A
#define     TestADCReg            0x3B
#define     Reserved31            0x3C
#define     Reserved32            0x3D
#define     Reserved33            0x3E
#define     Reserved34                0x3F
//-----------------------------------------------

class RFID
{
  public:
    RFID(int chipSelectPin, int NRSTPD);

    bool isCard();
    bool readCardSerial();

    void init();
    void reset();
    void writeMFRC522(unsigned char addr, unsigned char val);
    void antennaOn(void);
    unsigned char readMFRC522(unsigned char addr);
    void setBitMask(unsigned char reg, unsigned char mask);
    void clearBitMask(unsigned char reg, unsigned char mask);
    void calculateCRC(unsigned char *pIndata, unsigned char len, unsigned char *pOutData);
    unsigned char MFRC522Request(unsigned char reqMode, unsigned char *TagType);
    unsigned char MFRC522ToCard(unsigned char command, unsigned char *sendData, unsigned char sendLen, unsigned char *backData, unsigned int *backLen);
    unsigned char anticoll(unsigned char *serNum);
    unsigned char auth(unsigned char authMode, unsigned char BlockAddr, unsigned char *Sectorkey, unsigned char *serNum);
    unsigned char read(unsigned char blockAddr, unsigned char *recvData);
    unsigned char write(unsigned char blockAddr, unsigned char *writeData);
    void halt();

    unsigned char serNum[5];       // Constante para guardar el numero de serie leido.
    unsigned char AserNum[5];      // Constante para guardar el numero d serie de la secion actual.

  private:
    int _chipSelectPin;
    int _NRSTPD;

};

#endif

```

Using the code I have now I can read RFID data, and read them via the Serial monitor. Now, if I want to write RFID numbers to a card, can I do this with this library, or what other library should I use that is capable of writing?

# Answer
The library you refer to is called RFID by Miguel Balboa. It is equipped with several examples showing you how to read and write data. Check them out.

If you are looking for some more background information on what happens when you write data on a tag, check out the first video of of the MakeCourse of the University of South Florida.

At 21:30 it explains how to write data.
> 1 votes

---
Tags: library, spi, rfid
---


# Question
Title: Converting a char* with numbers to a double is giving me 0.0 in return
I recently made a thread where I read BLE data that has three different numbers/values. The data changes but it typically looks something like this: `0,5` `-0,1` `0`

I successfully store the three numbers in a unique char\* but when I try to convert the char\* to a double I get the value 0.0 in return.

This is my code:

```
        while (tok)
        {
            if (currentRow == 0)
            {
              currentRow = currentRow +1;
              double a = atof(tok);
              Serial.println (a);
            }

            else if (currentRow == 1)
            {
              currentRow = currentRow+1;
              double b = strtod(tok, NULL);
              Serial.println (b);
            }

            else {
              currentRow = 0;
              double c = atof (tok);
              Serial.println (c);
            }

            tok = strtok(NULL, " ");
        }

```

# Answer
> 1 votes
The value that was being sent used a comma "," instead of a dot "." that was needed in order to convert the number.

---
Tags: c++
---


title: Issue with IF statement

text:
# Question
Title: Issue with IF statement
The program plays a random mp3 file from an Adafruit mp3 breakout board. The trigger to play the song is a sharp IR sensor. Basically to play a file you pass your hand over the sensor and it plays the full track. If you want to stop the file playing pass your hand over again and it switches it to an off mode.

I wrote a `while` statement using `millis()` to keep track of time. I would like for the songs to keep playing for a defined time or if you pass your hand over it, it stops playing the music.

Right now it's only playing a single file. It appears that the if statement I have in the while loop is being ignored. The program goes straight to break when the file is played.

```
//----------------------------------------------------------
// MUSIC PLAYER
// vonderasche
// 3/26/2017
//----------------------------------------------------------

// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
#include <SharpIR.h>

// constants
#define ir A4
#define model 1080
#define TRIGGER_PIN  5
#define ECHO_PIN     6
#define MAX_DISTANCE 200

// These are common pins between breakout and shield
#define DREQ 3
// VS1053 Data request, ideally an Interrupt pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define CARDCS 4 // Card chip select pin
// These are the pins used for the breakout example
#define BREAKOUT_DCS 8
// VS1053 Data/command select pin (output)
// used to be pin 8
#define BREAKOUT_RESET  9 // VS1053 reset pin (output)
#define BREAKOUT_CS     10 // VS1053 chip select pin (output)

Adafruit_VS1053_FilePlayer musicPlayer =
// create breakout-example object!
Adafruit_VS1053_FilePlayer(BREAKOUT_RESET, BREAKOUT_CS, BREAKOUT_DCS,     DREQ, CARDCS);

SharpIR SharpIR(ir, model);

int state = 1;
const unsigned long onTimer = 1200000;

/// File listing helper
void printDirectory(File dir, int numTabs) {
  while (true) {
    File entry = dir.openNextFile();
    if (!entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i<numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

// random seed function
int rNumbers(int rNum) {
  randomSeed(analogRead(3));
  rNum = random(1, 10);
  return rNum;
}

// play a certain file
void playFile(int rNum) {
  switch (rNum) {
    case 1:
      Serial.println(F("Playing track 001"));
      musicPlayer.startPlayingFile("track001.mp3");
      break;
    case 2:
      Serial.println(F("Playing track 002"));
      musicPlayer.startPlayingFile("track002.mp3");
      break;
    case 3:
      Serial.println(F("Playing track 003"));
      musicPlayer.startPlayingFile("track003.mp3");
      break;
    case 4:
      Serial.println(F("Playing track 004"));
      musicPlayer.startPlayingFile("track004.mp3");
      break;
    case 5:
      Serial.println(F("Playing track 005"));
      musicPlayer.startPlayingFile("track005.mp3");
      break;
    case 6:
      Serial.println(F("Playing track 006"));
      musicPlayer.startPlayingFile("track006.mp3");
      break;
    case 7:
      Serial.println(F("Playing track 007"));
      musicPlayer.startPlayingFile("track007.mp3");
      break;
    case 8:
      Serial.println(F("Playing track 008"));
      musicPlayer.startPlayingFile("track008.mp3");
      break;
    case 9:
      Serial.println(F("Playing track 009"));
      musicPlayer.startPlayingFile("track009.mp3");
      break;
    case 10:
      Serial.println(F("Playing track 010"));
      musicPlayer.startPlayingFile("track010.mp3");
      break;
    }
  }

void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit VS1053 Simple Test");
  if (!musicPlayer.begin()) {
    // initialise the music player
    Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
    while (1);
  }
  Serial.println(F("VS1053 found"));
  if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1); // don't do anything more
  }
  // list files
  printDirectory(SD.open("/"), 0);
  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(30, 30);
  // Timer interrupts are not suggested, better to use DREQ interrupt!
  //musicPlayer.useInterrupt(VS1053_FILEPLAYER_TIMER0_INT);
  // timer int
  // If DREQ is on an interrupt pin (on uno, #2 or #3) we can do background
  // audio playing
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT); // DREQ int
}

void loop() {
  // calls random number function
  int randomNumber;
  // takes distance measurment
  float distance = (SharpIR.distance() / (2.4));
  static enum { ON, OFF } state;
  // if distance range is between certain values switch the state
  if (distance > 1 && distance < 12) {
    switch (state) {
      case ON:
        {
        unsigned long previousMillis = millis();
        unsigned long currentMillis = millis();
        while ((currentMillis - previousMillis) < onTimer) {
          Serial.println("inside while loop");
          randomNumber = rNumbers(randomNumber);
          // calls random number function
          playFile(randomNumber); // plays music file
          float distance2 = (SharpIR.distance() / (2.4));
          delay(1000);
          //breaks timer if hand swipe
          if (distance2 > 2 && distance2 < 8) {
            Serial.println("Break");
            break;
          }
          currentMillis = millis();
        }
        state = OFF;
      }
      break;
    case OFF:
      {
      Serial.println("Triggered Off");
      musicPlayer.stopPlaying();
      state = ON;
      }
      break;
    }
  };
}

```

# Answer
> 1 votes
There's probably a good chance that when you trigger the ON state by placing your hand close to the sensor, the while loops runs and hits the if statement before you have moved your hand out of the trigger distance.

I see the delay of 1 second before the if, however, you take the reading of the IR sensor before the delay.

Try the delay before reading the sensor:

```
        ...
        playFile(randomNumber);  // plays music file

        delay(1000); // let the user move their hand
        float distance2 = (SharpIR.distance() / (2.4));

        //breaks timer if hand swipe
        if (distance2 > 2 && distance2 < 8)
        {
        ...

```

If you wanted to remove the delay function (highly recommended) after playing the file, set the state to something like PLAYING.

Then in the PLAYING state switch case you first wait for an IR reading that there is no hand present (allowing the user to finish moving their hand away), set a flag that you are ready to detect the hand. Then if that flag is true and the IR sensor reads a hand, then you can move to the OFF state.

You can add a second condition to the PLAYING state to test for elapsed time as well.

# Answer
> 1 votes
The intent of some of your code isn't clear, and the description “The program goes straight to break when the file is played” looks wrong – it appears that at least one `delay(1000)` will occur between start and break, so perhaps you mean that about a second after playing starts, it breaks.

If so, here is a possible explanation of that behavior:

1. At the beginning of `loop()`, you say `distance = (SharpIR.distance() / (2.4));`
2. Suppose that results in a value between 2 and 8. Then the `if` condition `(distance > 1 && distance < 12)` will be true, so the body of the `if` will execute.
3. `state` initially is `ON` (`state` is static, and per §6.7.9.10 of the N1570 C++ spec, apparently gets initialized to 0, which corresponds to `ON`) and will be `ON` after each execution of the `OFF` case in `loop()`.
4. When `state` is `ON`, we proceed into the `ON` case of the `switch`, set some variables to current time, then use a few microseconds to serial-print and call `rNumbers()` and `playFile()`. Then `distance2 = (SharpIR.distance() / (2.4));` sets `distance2` to about the same value read a few microseconds earlier into `distance`; as we supposed earlier, a number between 2 and 8.
5. With `delay(1000)`, the program sits for a second doing nothing and paying attention to nothing.
6. The `(distance2 > 2 && distance2 < 8)` condition for the next `if` is true, so program prints "Break", breaks out of the `while`, turns off `state`, breaks out of the `switch`, exits `loop()`, enters `loop()`, etc.

However, now that a second has gone by, the Sharp sensor shouldn't be reading a gesture. If it is, that will allow the `OFF` case to execute and call `musicPlayer.stopPlaying()`.

---

Note, issue the `randomSeed(analogRead(3))` call only once, and do so within `setup()`. Calling it within each `rNumbers()` call is going to give you non-random numbers.

---
Tags: arduino-uno
---


title: High-range obstacle detection system

text:
# Question
Title: High-range obstacle detection system
I am making a high-range and fast obstacle detection system.

The HC-04 is too slow for that, other sensors don't have the range, and Lidar is too costly.

Any idea how to make a long range (more than 10 m) high-speed obstacle detection system?

# Answer
You can Use PIR Sensor which is Cost Effective and covers upto 10 Meters
> 0 votes

---
Tags: arduino-uno, sensors, proximity
---


# Question
Title: What does this notation stands for? Wire.read() <<8 | Wire.read()
I'm using the Arduino's site test code for getting raw values from a MPU-6050 accelerometer + gyro. In the loop, there are this lines for getting the next data from its registers:

```
Wire.requestFrom(MPU_addr, 14, true);  // request a total of 14 registers

AcX = Wire.read()<<8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read()<<8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read()<<8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read()<<8 | Wire.read();  // 0x41 (TEMP_OUT_H)   & 0x42 (TEMP_OUT_L)

GyX = Wire.read()<<8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read()<<8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read()<<8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

```

Hex numbers indicates, of course, the address of each register. However, I can't get how, if the first instruction only requests from the MPU\_addr (constant), it changes to the consecutive registers. Is it that `<<8|` makes something like a sum or a logic OR to switch the register to read?

Regards!

# Answer
> 5 votes
Just adding a couple of points to Michel Keijzers's answer.

The expression `Wire.read() << 8` takes the value returned by `Wire.read()`, which is an `int`, and shifts it 8 bits to the left, which is equivalent to multiplying by 256. If you are using a 32-bit microcontroller (e.g. an Arduino Due), this is safe. However, most Arduinos are based on an 8-bit AVR chip. On them, an `int` is 16-bits and can only hold values up to 32767. If the initial value is larger than 127, then the bit shift causes a signed integer overflow, which in C and C++ is *undefined behavior* (read: “illegal operation”). It is *likely* that everything runs fine and you get the expected result, but it is unwise to ever rely on undefined behavior in C or C++.

The proper way to do the shift is to cast the initial value to an unsigned data type, which is always safe v.s. overflows, and then do the shift, like in

```
((uint16_t) Wire.read()) << 8

```

You may omit the outer parentheses if you know your operator priorities.

The second point is about the already mentioned fact that the order of the reads is not specified. The simplest fix is to do one read per statement, as in:

```
AcX = (uint16_t) Wire.read() << 8;  // first read MSB
AcX |= Wire.read();                 // then LSB

```

It is worth noting that the first statement has an implicit cast from `uint16_t` (the result of the shift) to `int16_t` (the type of `AcX`). This can also overflow if the shifted value is larger than 32767. However, an overflow happening during a conversion in *not* undefined, but rather *implementation defined behavior*. This means that the authors of the compiler must decide and document what happens. Arduino code is usually compiled by gcc, and the gcc docs document this behavior as

> *The result of, or the signal raised by, converting an integer to a signed integer type when the value cannot be represented in an object of that type (C90 6.2.1.2, C99 and C11 6.3.1.3).*
>
> For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.

This is exactly what we want here, and since it is the most efficient choice on a two’s complement architecture, it seems unlikely that another compiler would make a different choice.

# Answer
> 2 votes
1 \<\< 3 means the value 1 shifted 3 times to the left. So 1 in binary is 0000001, shifted left 3 places is 00001000. And 0001101 \<\< 3 will be 1101000.

The | command is a logic or (where bits will be 1 if one of the bits is 1, e.g. 001100 | 001001 = 001101.

Probably every Wire.read() gives the next byte. For the first line: Acx = Wire.read() \<\< 8 | wire.read() means one (mostly the first byte) is read, it is shifted to the left one byte and the other (mostly next byte) read is placed in the right. So it results in the first two read bytes to be positioned in AcX. It is semantically the same as Wire.read() * 256 + Wire.read(), but normally a bit shift is easier for a computer, same as | and the + operator.

---
Tags: i2c, accelerometer, gyroscope
---


# Question
Title: Sending a string to arduino and is not reacting to it
I am trying to move servos with a VR headset, I am using the Unreak 4 Arduino Plugin, but that is not the problem. I send the rotation Y and Z from the headset, convert them to int and then send them together as an int separated by commas. Here's what it does: It gets the rotation Z, it converts it to int, then it converts it to String, I add a comma at the end of the String, then I add the rotation Y after the comma, and it returns me: "rotationZ","rotationY" (the values between " are the numbers sent by Unreal to arduino), these results may come in negative or positive value.

Then inside arduino I have this code:

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

Servo servo1;
Servo servo2;  // Crea un Objeto servo

int angle = 10;
int posicion = 10;    // Variable de la posicion del servo

String user_input1;

int r;
int g;

void setup()
{
  Serial.begin(9600);
  servo1.attach(2);  // Selecionamos el pin 2 como el pin de control para el servo
  servo2.attach(3);  // Selecionamos el pin 2 como el pin de control para el servo

  servo1.write(0);
  servo2.write(0);

  Serial.setTimeout(5);
}

void loop()
{
  if (Serial.available() > 0)
    {
  String firstValue  = Serial.readStringUntil(',');
 // String first = Serial.readString(); //next character is comma, so skip it using this
  String secondValue = Serial.readStringUntil(',');
//  String second =  Serial.readString();

   r = firstValue.toInt();
   g = secondValue.toInt();
    }
  if (r < 0)
  {
    r = r * -1;
  }

  if (g < 0)
  {
    g = g * -1;
  }

  Serial.println(r);
  Serial.println(g);

  servo1.write(r);
  servo2.write(g);

}

```

As you can see, it gets the numbers between the commas and then it converts them to int, and then it applies to the servos which are in pins number 2 and 3 (yes, everything is plugged in correctly), which it should then move them acordingly the position of the VR headset, I've also tried to make them always receive positive results but still doesn't work. I have searched over the internet on how to separate a string divided by commas and I still don't know if it's correctly done.

EDIT: I also tried to input the numbers in the console manually, and it gets them right and moves the servos but it still doesn't work with the VR. I also added Serial.setTimeout(5) to try if it works that way.

Thanks in advance for reading this bunch'o text about my problem.

# Answer
> I also tried to input the numbers in the console manually, and it gets them right and moves the servos but it still doesn't work with the VR.

This implies that the problem is in the code sending the data. Get a terminal emulator program and hook that up to the code generating the data from the VR headset (you will need 'local echo' turned on). I suspect you will see the headset is not writing the data in the format you expect. Also it will let you capture a real sample of data that you can feed into you program to generate a repeatable test.

If this isn't the fault, then please can you post the a few lines of data so we can see whats wrong.
> 1 votes

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


# Question
Title: How to reset the arduino uno after 5 seconds?
I am using this code.. But everytime after one rfid tag is read by the reader, I have to manually press the reset button on the arduino before scanning the next tag. I want to do this operation after every 10 or 20 seconds from one tag scanning without manually pressing the reset button. What changes I have to make to this code??

```
/*
* source: http://www.electroschematics.com/11301/arduino-rfid-reader-rc522-access-control-system/
* Read a card using a mfrc522 reader on your SPI interface
* Pin layout should be as follows (on Arduino Uno):
* MOSI: Pin 11 / ICSP-4
* MISO: Pin 12 / ICSP-1
* SCK: Pin 13 / ISCP-3
* SS: Pin 10
* RST: Pin 9
*/

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

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

#define SS_PIN 10
#define RST_PIN 9

RFID rfid(SS_PIN,RST_PIN);

int startAlarm = false;
int resetAlarm = 2;
int relay = 6;
int alarm = 8;

int serNum[5];

int cards[][5] = {
  {00,162,227,135,198} // card 1

};

bool access = false;

void setup()
{
  // Setup size of LCD 20 characters and 2 lines
  lcd.begin(20,2);    //------------------------------------------------------
  // Back light on
  lcd.backlight();  //---------------------------------------------------------

  lcd.setCursor(0,0);         //----------------------------------------------
  lcd.print("SCAN your ID");   //------------------------------------------------

    Serial.begin(9600);
    SPI.begin();
    rfid.init();
    pinMode(resetAlarm, INPUT);
    pinMode(relay, OUTPUT);
    pinMode(alarm, OUTPUT);
    digitalWrite(relay, HIGH); // or LOW if you have a regular relay------------------------------(ALREADY CHANGED)
    attachInterrupt(0, reset_alarm, LOW);
}

void loop()
{

    if(rfid.isCard()){

        if(rfid.readCardSerial()){
            Serial.print(rfid.serNum[0]);
            Serial.print(",");
            Serial.print(rfid.serNum[1]);
            Serial.print(",");
            Serial.print(rfid.serNum[2]);
            Serial.print(",");
            Serial.print(rfid.serNum[3]);
            Serial.print(",");
            Serial.print(rfid.serNum[4]);
            Serial.println("");

            for(int x = 0; x < sizeof(cards); x++){
              for(int i = 0; i < sizeof(rfid.serNum); i++ ){
                  if(rfid.serNum[i] != cards[x][i]) {
                      access = false;
                      break;
                  } else {
                      access = true;
                  }
              }
              if(access) break;
            }

        }

       if(access){
          Serial.println("Welcome!");
          startAlarm = false;
          digitalWrite(relay, LOW); // HIGH with regular relay (I have already changed the code)  //------------------------------
          lcd.setCursor(0,0);   //----------------------------------------------------------------------------------------------
          lcd.print("Access Granted");  //-------------------------------------------------------------------------------------------
          delay(3000);
          lcd.clear();
          lcd.setCursor(0,0);         //----------------------------------------------
          lcd.print("SCAN your ID");   //------------------------------------------------
             //---------------------------------------------------------------
       } else {
           Serial.println("Not allowed!");
           startAlarm = true;
           digitalWrite(relay, HIGH);  // LOW with regular relay (I have already changed the code)----------------------------------
           lcd.setCursor(0,0);         //------------------------------------------------------------------------------------
           lcd.print("Invalid Access ");        //------------------------------------------------------------------------------------
           delay(3000);
           lcd.clear();                            //--------------------------------------------
           lcd.setCursor(0,0);         //----------------------------------------------
           lcd.print("SCAN your ID");   //------------------------------------------------

       }
    }

    if(startAlarm) {
       digitalWrite(alarm, HIGH);
    } else {
      digitalWrite(alarm, LOW);
    }

    rfid.halt();

}

void reset_alarm(){
    startAlarm = false;
}

```

# Answer
> 1 votes
I would think the rfid library would be able to read multiple cards in a row... however I'm not familiar with it.

Here is an answer from a similar question about how to initiate a hardware reset with software using the watchdog timer - https://arduino.stackexchange.com/a/1478/31106 :

> The SoftReset library makes it easy. Although it is not difficult to implement directly. Shown below..
>
> ```
> #include <avr/wdt.h>
> ...
> setup() {
>
>   ...
>   MCUSR = 0;  // clear out any flags of prior resets.
>   ...
>
> ```
>
> then when desired...
>
> ```
> ...
> wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
> for(;;) {
>   // do nothing and wait for the eventual...
> }
> ...
>
> ```

# Answer
> 1 votes
This may not be your only issue, but I think you are using `sizeof()` wrongly. This 'function' returns the number of bytes occupied by a variable or type OR the number of bytes occupied by an array.

So

```
1 == sizeof(char)
6 == sizeof ("Hello")  // Because of the trailing null
2 == sizeof(int)
int cards[][5] = {
                  {00,162,227,135,198} // card 1
                 };
10 == sizeof (cards)

```

So you line that says `for(int x = 0; x < sizeof(cards); x++){` is happening 10 times, not once.

Personally I would never use sizeof to measure the size of an array, but if you have to then you need to do this:

```
size = sizeof (cards) / sizeof (int)

```

---
Tags: arduino-uno
---


# Question
Title: Pre-heat time required for MQ-5 gas sensor
The datasheet of MQ5 sensor says, it requires a pre-heat of 24 hours. Does this mean that it needs to be powered on for 24 hours consecutively before usage? Some other websites (e.g. http://www.circuitstoday.com/interfacing-mq5-lpg-sensor-to-arduino) say that 15 minutes pre-heat would suffice. Could someone clarify this issue? Thanks.

# Answer
> 6 votes
> Does this mean that it needs to be powered on for 24 hours consecutively before usage?

No, it just means that typical performance data in the datasheet has been measured after 24h. So, if you want to be within specification you must observe that 24h preheating time.

Does it mean you can't use the sensor before those 24h? Absolutely not. Given the small size of the sensor, thermal equilibrium will be almost surely reached within 30 min. And it would probably take just a few minutes to be within +/- X % of the specification (you can only know by actually measuring how much time does the output need to stabilise, which you should do).

At the end, **the time to wait for thermal stabilisation of the sensor (preheating time) will depend on your application**.

Only if you want a very accurate measure of gas concentration, you will need to wait those 24h (and also have a good calibration of your sensor, as well as means to compensate other environmental factors like temperature, humidity, etc.). But if you wanted to do this kind of measurement you probably won't be using a MQ-5 sensor anyway.

**EDIT:**

Take a look at this excellent technical note from Figaro Sensors to better understand the preheating time. It ISN'T a burn-in time *per se*, but a stabilisation time whose duration depends on several factors.

# Answer
> 6 votes
Please be clear when you mean the one time only pre-heat and when you mean turning the sensor on to take a measurement.

It is a electrochemical sensor and it needs time to burn-in. During those 24 hours, the impedance of the sensor changes a lot. After those 24 hours it can be used in a normal way and it will return consistant values.

The pre-heat should be done just once. I mean: just once in the lifespan of the sensor. After buying it, you should run the pre-heat. When the manufacturer writes in the datasheet that the pre-heat time is 24 hours, then you should do 24 hours. I suggest to connect the sensor in a normal way, with 'A' en 'B' pins connected and with the load resistor, and keep it on for 24 hours. Maybe it is already stable after a few hours, but keep it on for 24 hours to be sure.

To take a measurement, the sensor needs time to warm up. About 5 minutes might be okay. I think that 2 minutes is definitely too short.
When the sensor is always at room temperature, and the time to warm up is always the same, then the measurement is relative accurate and can be compared with other measurements. That means that when the sensor is mostly turned off to save power, only a few minutes to warm up can be used. However, I would start with at least 5 minutes.

\[**EDIT**\] The datasheets and other information from the manufacturers use the term "pre-heat" in different ways. The Technical Note in the link by @EnricBlanco uses the term "preheating" only for the "one-time-only" heating after storage to make the sensor more stable, as far as I can tell. Although it is not "one-time-only", it should be applied after storage or changing conditions as well. @EnricBlanco, try a very cheap MQ gas sensor (which is probably not preheated in the factory) and see how the impedance changes a lot during the first hours of preheating, and becomes stable after a few hours.

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


# Question
Title: LED fade with LDR sensor depending on the light
I need help on a project. I just started to experiment with arduino 2 weeks ago and I am building a lamp that react to movement and interactions. So the idea is; when there is nobody in the room, the light stay white. And when there is someone, it turns orange and I want it to « breathe » (fade function).

I am using a LDR sensor to make it happen and so far my code looks like:

```
int LDRvalue = 1;
int RedLED = 9;
int GreenLED=10;
int BlueLED=11;
int pinLDR = A0;

void setup()
{
pinMode(RedLED, OUTPUT);
pinMode(GreenLED, OUTPUT);
pinMode(BlueLED, OUTPUT);
Serial.begin(9600);

}
void loop()
{
LDRvalue = analogRead(pinLDR);
Serial.print("valeur ldr: ");
Serial.println(LDRvalue);

int colour = map(LDRvalue, 0, 1023, 0, 255);
Serial.print("valeur mappe: ");
Serial.println(colour);

if(LDRvalue >= 1023)
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 255);
analogWrite(BlueLED, 255);
delay(1000);
}

else if((LDRvalue >= 800) & (LDRvalue < 1023))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 255);
analogWrite(BlueLED, 255);
delay(1000);

}

else if((LDRvalue >= 600) & (LDRvalue < 800))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 105);
analogWrite(BlueLED, 0);
delay(1000);

}
else if((LDRvalue >= 300) & (LDRvalue < 600))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 35);
analogWrite(BlueLED, 0);
delay(1000);
}

else if((LDRvalue >= 150) & (LDRvalue < 300))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 15);
analogWrite(BlueLED, 0);
delay(1000);

}

else if((LDRvalue >= 0) & (LDRvalue < 150))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 0);
analogWrite(BlueLED, 0);
delay(1000);
}

delay(1);

}
void color(int red, int green, int blue)

{
analogWrite(RedLED, red);
analogWrite(GreenLED, green);
analogWrite(BlueLED, blue);
}

```

The code is working for the light changes depending on the human presence. But I don’t know how to make it fade and breathe when it turns orange.

Could you help me to make it happen ?

# Answer
While some parts of your code don't make much sense to me, the breathing led code is easily searchable on the internet, with one of the first results being:

```
#include <math.h>
#define ledPin 11
int i=0;
int breathe_delay = 15;   // delay between loops
unsigned long breathe_time = millis();
void setup() { }
void loop() {
  nonBlockingBreath();  // call the nonblocking function
  // yourOtherCodeHere();
}

void nonBlockingBreath() {
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float val = (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
    // this is the math function recreating the effect
    analogWrite(ledPin, val);  // PWM
    i=i+1;
  }
}

```

As you can see the code above works for monochromatic LEDs only, so my advise is to combine the code above with a conversion from HSL to RGB, like RGBConverter library, specifically the `hsvToRgb` function.

This way your version of the `nonBlockingBreath` function will become:

```
byte[3] rgb;
void nonBlockingBreath() {
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float value= (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
    hsvToRgb(hue, saturation, value, rgb);
    analogWrite(RedLED, rgb[0]);  // PWM
    analogWrite(GreenLED, rgb[1]);  // PWM
    analogWrite(BlueLED, rgb[2]);  // PWM
    i=i+1;
  }
}

```

Obviously you will have to set the `hue` and `saturation` variables accordingly to the tonality of orange you wish to *breath*.
> 1 votes

---
Tags: arduino-uno, programming, sensors, c++, led
---


# Question
Title: Random data sending integers between two Arduinos
I'm trying to do something seemingly simple, but I'm running into difficulties. I want to send about 5 separate integers between two Arduinos over software serial. I have written the following, but I rarely get the two numbers on the receiving end - they're usually garbled or in the wrong order. I'm sure that I'm missing something obvious, but I can't work it out no matter how hard I try. Any help would be greatly appreciated.

Sender:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

int val, val2;

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

void loop()
{
  val = 123;
  val2 = 456;
  if(mySerial.read()=='#')
  {
    mySerial.write(highByte(val));
    mySerial.write(lowByte(val));
    delay(3);
  }
  if(mySerial.read() == '~')
  {
    mySerial.write(highByte(val2));
    mySerial.write(lowByte(val2));
    delay(3);
  }
}

```

Receiver:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

byte val;
byte low, high;

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

void loop()
{
  mySerial.write('#');
  byte h = mySerial.read();
  byte l = mySerial.read();
  int y = word(h, l);
  delay(2);
  mySerial.write('~');
  byte h2 = mySerial.read();
  byte l2 = mySerial.read();
  int z = word(h2, l2);

  Serial.println(y);
  Serial.println(z);
  Serial.println();
}

```

# Answer
You need to add a delay to the Receiver software immediately after you send the `#` and the `~` characters.

```
void loop()
{
  mySerial.write('#');
  delay(8);    // <<<<<<<< Line added
  byte h = mySerial.read();
  byte l = mySerial.read();
  int y = word(h, l);
  delay(2);
  mySerial.write('~');
  delay(8);    // <<<<<<<< Line added
  byte h2 = mySerial.read();
  byte l2 = mySerial.read();
  int z = word(h2, l2);

  Serial.println(y);
  Serial.println(z);
  Serial.println();
}

```

The delay is needed so the microcontroller has enough time to send the character out of the serial port, have it processed by the other side and then the new data sent back.

Using 9600 baud, the time for each bit is around 104 microseconds. So a byte of data sent will take about 1.04 milliseconds. One byte sent + processing time + 2 bytes back is about 4 milliseconds. Adding a bit of margin, 8 ms delay would be a good value to use.

Using `if (mySerial.Available() > 0)` will not work on its own unfortunately, as Matt's answer suggests. What would happen is that you send the first `#` and then immediately it would check for any data recieved. From the calculation above we know it would take about 4 ms to get data back. So it just skips the if statement and goes onto the 2ms delay and then sending the `~`. It then checks if serial is available. By this time the first response 'may' be back, so if it is, it then saves the data into `h1` and `l1`. It then finishes the serial prints and loops back to the beginning. In this time the second response has come back, so after it sends `#` for the second time, the response to the `~` gets saved into `h` and `l`. This will continue forever.
> 0 votes

# Answer
You are being too impatient.

The receiver needs to wait until there is some data available. `if (mySerial.Available() > 0)`. So before every read add that line and it should work.
> 1 votes

---
Tags: arduino-uno, communication, softwareserial
---


title: PWM generation using Arduino uno

text:
# Question
Title: PWM generation using Arduino uno
How to obtain four PWM outputs at 100 kHz using an arduino uno board? The requirement is that all four PWM outputs should have controllable duty ratios individually.

# Answer
> 2 votes
In a comment to Dmitry Grigoryev’s answer you wrote:

```
void setup()
{
    TCCR2A = 0x23;
    TCCR2B = 0x09;
    OCR2A = 159;
    pinMode(3, OUTPUT);
}

void loop()
{
    OCR2B = 80;
}

```

It seems you already have the solution to your problem: that's exactly the way to do it!

Well, there is a catch: since you are using `OCR2A` to define the period of your timer, this means you are left with a single PWM channel, where the duty cycle is controlled by `OCR2B`. Given that the Arduino Uno has only three timers, it would seem you can only have up to three PWM channels at 100 kHz.

But there is a solution. Timer 1 has a feature the other timers don't have: you can define its period using using the input capture register `ICR1` instead of `OCR1A`. This leaves you both output compare registers available for PWM. For this you have to set the timer into waveform generation mode 14, i.e. fast PWM with TOP = ICR1. Now you can have your four channels, with Timer 0 driving pin 5, Timer 2 driving pin 3, and Timer 1 driving pins 9 and 10.

Some caveats:

* As already pointed out by Dmitry Grigoryev, your PWM resolution is slightly reduced.
* By reconfiguring Timer 0, you loose the Arduino Timekeeping function `millis()`, `micros()` and, `delay()`. You could write your own ISR to count the overflows of some other timer, but it would be called every 10 µs: even if it is very short it would eat a non-trivial fraction of your CPU power.

# Answer
> 2 votes
You can't squeeze 100kHz out of an Arduino without a major software rewrite (at which point you will be using an AtMega chip rather than Arduino). `analogWrite` defaults to ~500Hz and can be boosted to 62.5kHz on some Arduino models, and only for 2 pins. Other PWM pins are capped at 31.4kHz.

You can achieve 100kHz PWM by toggling pins manually and busy-waiting, but you won't be able to do anything else during this. Or you can make use of interrupts, which is a big leap from Arduino ecosystem as I already said.

---
Tags: pwm
---


# Question
Title: Creating a library of C++ classes for Arduino; How to #include "Arduino.h", "WProgram.h"?
I've written 6 C++ classes on the CLion IDE to be used on Arduino. One of these classes uses a C++ library called "Adafruit\_PWMServoDriver.cpp" provided by Adafruit to use the PWM driver they sell. I'm trying to test my code in a main.cpp, but upon building my code, I noticed that "Adafruit\_PWMServoDriver.cpp" has the following code:

```
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

```

Naturally, I copied Arduino.h from the Arduino installation folder to my C++ project header directory. But for reasons I don't know, ARDUINO is apparently not greater than or equal to 100, so it attempts to include "WProgram.h." Because I cannot find this header file, I changed my code to only attempt to include Arduino.h.

```
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "Arduino.h"
#endif

```

However, Arduino.h itself includes several header files, and I am not sure where I can find all the find them, or if it is even necessary to try to do so. I need to get my test code running, so I don't want to directly test it in the Arduino IDE yet. What can I do to overcome #include Arduino.h and #include WProgram.h?

# Answer
The libraries from Adafruit and elsewhere *assume* you are using the Arduino IDE. If you choose not to use that you will have difficulties compiling your own code. The header files you ask about are in the IDE download. You can always grab a copy of that and put the appropriate .h files into your "include" search path.

> However, in my io.h file, there is a long list of #if defined (AVR\_various\_names).

Well, do a test compile using the Arduino IDE, using "verbose compiling" and see what defines are generated for your particular board (which you haven't mentioned). There won't be that many of them. Then you can put that on the build commands for your IDE.

> Or can I avoid all this and somehow create C++ classes independently?

You can create C++ classes inside the Arduino IDE. I don't see how this relates to your other issues.

---

The Arduino IDE basically generates build commands for avr-g++ - it isn't some horrible beast you should avoid using.
> 2 votes

# Answer
The `#if defined (AVR_<various_names>)` you see here have nothing to do with Arduino: this is the avr-libc trying to import the IO register definitions for the AVR chip you are using. Whenever you compile an AVR program, you pass the option `-mmcu=<mcu-name>` to avr-gcc, and it automatically defines the proper macro. For example, the Arduino Uno is built around an ATmega328P. Programs for the Uno must then be compiled with `-mmcu=atmega328p`, which makes the compiler define `__AVR_ATmega328P__`, which directs the avr-libc to `#include <avr/iom328p.h>`, which contains all the IO register definitions for that chip.

As for the `ARDUINO` macro, this one is defined by the Arduino IDE to be the version of you Arduino installation, without the dots. For example, if you downloaded the core files from Arduino 1.8.2, then you should compile with `-DARDUINO=182`.

Also, you should avoid copying all the library headers to your project, and instead use the proper `-I` options. And don't forget to tell the compiler your clock frequency with `-DF_CPU=...`, as it is needed by some avr-libc and Arduino stuff.

In the end, you will see you need quite a lot of compiler options to properly compile Arduino code. The easiest way to do it is definitely to use the Arduino IDE, as it handles all this for you. If you don't like the IDE (understandable...), you could try Arduino Builder, which should be entirely compatible. If you want to compile from just a Makefile, I recommend you take a look at Sudar Muthu’s Arduino Makefile.
> 1 votes

---
Tags: c++, library, adafruit
---


title: Problem on Arduino Interrupt and RTC

text:
# Question
Title: Problem on Arduino Interrupt and RTC
I am doing an experiment. In this experiment I want to start the RTC by presing the external Push Button which is connected with Aquino's pin 2 and take varites of action according to Time. For interrupt I have made a ISR and in this interrupt I wrote my main logic. But this things is not working. The schematics is

and The code is

```
`include <Wire.h>
#include "RTClib.h"
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 9);

RTC_DS1307 rtc;
int k = 0;
int led =13;
int pin =2;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
 lcd.begin(16, 2);
 rtc.begin();
 Serial.begin(11520);
 pinMode(led,OUTPUT);
 pinMode(pin,INPUT);
 attachInterrupt(0, Time  , LOW);
  // Print a message to the LCD.
  if (! rtc.begin()) {
    lcd.print("hello, world!");
    while (1);
}

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }
}
void loop()
{}

void Time()
   {
    {DateTime now = rtc.now();
    lcd.setCursor(0, 0);
    lcd.print(now.year(), DEC);
    lcd.print("/");
    lcd.print(now.month(), DEC);
    lcd.print("/");
    lcd.print(now.day(), DEC);
    lcd.print(" ");
    lcd.print(daysOfTheWeek[now.dayOfTheWeek()]);
    int c = now.second();
    lcd.setCursor(0, 1);
    lcd.print(c);
    if(c==58)
      {
        k=k+1;
        lcd.setCursor(5, 1);
        lcd.print(k);
        if(k==4)
          {
            digitalWrite(led,HIGH);
            k=0;
          }
     }

    }}`

```

please help me.

# Answer
Well, for example Arduino's `delay` needs interrupts to be working and as you may not know it's disabled inside of `ISR` handler.

Never ever use anything like `while (1)`, `delay(1000)` and so on inside of `ISR`! And also do not reenable interrupts either! Set a simple `volatile` flag and use it inside of `loop` function instead.

Basically something like this:

```
constexpr int8_t button = 2;
volatile bool      flag = false;

void setFlag() {
  flag = true;
}

void setup() {
  pinMode(button, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), &setFlag, FALLING);
}

void loop() {
  if (flag) {
    // it's running, you can do something here

    // and you can reset the flag here either
  }
  //delay(100); // if needed
}

```
> 3 votes

---
Tags: arduino-uno, interrupt, rtc
---


# Question
Title: Why are there two sets of tools and bootloaders in the Arduino IDE?
After digging around on a separate problem, I found that `avrdude`, `avr-gcc` and some more tools can be found in two different locations:

```
(1): C:\Program Files\Arduino\hardware

(2): C:\Users\<user>\AppData\Local\Arduino15\packages\arduino

```

These two folders also both contain similar copies of the `hardware` directory where all the bootloader hex-files and source code is stored:

```
(3): C:\Program Files\Arduino\hardware\arduino\avr

(4): C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.17

```

I say similar because the `bootloaders\caterina` folder in (4) contains quite a few hex-files that are missing in (3).

When burning a bootloader, looking at verbose output from the Arduino IDE reveals that hex-file and executable of avrdude from (2) are used, not (1).

What is the reason for this? My guess would be that location (1) is deprecated, but why choose to put stuff like this into Appdata in the first place?

# Answer
> 1 votes
Arduino IDE comes with a "platform" (the arduino AVR) in the Arduino\hardware folder.
Then you can add/upgrade platforms with the boards manager.
These will be installed in C:\Users\\AppData\Local\Arduino15\packages.
The reason for this is that Arduino IDE wants to be able to "work out of the box". If they did not deliver the platform inside the installation/zip a "installation finishing" job needs to run after opening the Arduino IDE.

---
Tags: arduino-ide, bootloader, avrdude
---


# Question
Title: Run 5V/2.3W water pump on Arduino Pro Mini 5V
I want to build up my automatic water pump with an arduino pro mini 5v and a 5v usb water pump (2.3 W). As I understand, I cannot power the pump directly through the vcc pins of the board, right? Would it be possible to place a female USB Port in my system to power the board and the pump through a relay on the board? What would be an appropriate circuit diagram?

# Answer
> 1 votes
> As I understand, I cannot power the pump directly through the vcc pins of the board, right?

This is from the Arduino Pro Mini schematic:

Note that the maximum current output is 150 mA. On the other hand, your pump needs 2.3 W / 5 V = 460 mA \> 150 mA. So your understanding is right: **you can't power the pump directly through the Vcc pins of the board**.

> Would it be possible to place a female USB Port in my system to power the board and the pump through a relais on the board? What would be a appropriate circuit diagram.

There are lots of extremely cheap, commercially available, opto-isolated 5V relays modules in aliexpress and the like.

I'd recommend one like this because it allows you to have separate supplies for the relay coil and for the input diode in the opto. That will help you to avoid problems related to having "different" 5V levels due to dropout in the Pro Mini regulator.

Module picture:

Module schematic:

Module connectivity:

* VCC --\> VCC from the Pro Mini.
* JD-VCC --\> V+ from the power supply (same as RAW input to the Pro Mini).
* COMMON --\> V+ from the power supply.
* NO (normally open) --\> connect it to the 5V rail of the USB pump.
* NC (normally closed) --\> leave it unconnected.
* Be sure to connect all grounds together.
* I'd also recommend adding an additional decoupling capacitor close to the RAW pin of the Pro Mini, to protect the regulator from voltage spikes caused by switching-off inductive loads like the relay coil and the pump motor.

**NOTE:** take into account that the relay module can draw up to an additional 80-100 mA of current. Take that into account in your power/current budget.

# Answer
> 1 votes
Hi Florian you can take power from USB fro both Arduino and the water pump.This is the schematic you have asked for your project. An arduino Pin can give maximum 20mA current that's why we need a limit resister to limit the current below 20mA and also this current should be such a way that it can drive the switching transistor. So the challenging thing is choosing the correct resister I have taken the value 1K So the current at Arduino Digital pin is Current I = 5V/1k = 5mA which is below of 20mA and sufficient to drive the Transistor. you can use BC548 transistor also.

simulate this circuit – Schematic created using CircuitLab

---
Tags: power, usb, arduino-pro-mini, relay, current
---


title: Can Bus Shield Not Receiving Data

text:
# Question
Title: Can Bus Shield Not Receiving Data
I am trying to connect my Arduino Uno board with SeeedStudio Can Bus Shield to my 2006 325i BMW. After compiling and uploading the example program by SeeedStudio, the serial monitor returns "Can Bus Shield Init ok!"

```
// demo: CAN-BUS Shield, receive data with check mode
// send data coming to fast, such as less than 10ms, you can use this way
// loovee, 2014-6-13

#include <SPI.h>
#include "mcp_can.h"

// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

void setup() {
  Serial.begin(115200);
START_INIT:
  if(CAN_OK == CAN.begin(CAN_500KBPS)) {
  // init can bus : baudrate = 500k
    Serial.println("CAN BUS Shield init ok!");
  } else {
    Serial.println("CAN BUS Shield init fail");
    Serial.println("Init CAN BUS Shield again");
    delay(100);
    goto START_INIT;
  }
}

void loop(){
  unsigned char len = 0;
  unsigned char buf[8];
  if(CAN_MSGAVAIL == CAN.checkReceive()) {
    // check if data coming
    CAN.readMsgBuf(&len, buf);
    // read data,  len: data length, buf: data buf
    unsigned char canId = CAN.getCanId();
    Serial.println("-----------------------------");
    Serial.println("get data from ID: ");
    Serial.println(canId);
    for(int i = 0; i<len; i++) {
      // print the data
      Serial.print(buf[i]);
      Serial.print("\t");
    }
    Serial.println();
  }
}

```

So I get the initialize statement returned but I'm not receiving any data. It seems like the `if(CAN_MSGAVAIL == CAN.checkReceive())` statement isn't executed. I found my vehicle's Can high and Can low wires and inserted them into my Can Bus Shield. So I'm not sure if it's a code problem or if the wires aren't transmitting the data to the shield. Any help would be great.

# Answer
It may be a dumb question, but are you sure your car CAN bus is 500kbps?
Have a look at this: pdfLink
Maybe try different speeds? 100kbps maybe?

Also, look at the schematics of your shield? Is the bus termination resistor soldered on the board?
> 2 votes

# Answer
Make sure to cut the P1 trace (see the link below) and also to connect GND from the OBD-2 to the shield/Arduino. There are two ground pins on the OBD-2 port, Signal and Chassis Ground. I went with Signal GND, but allegedly they are linked anyways.

This guide helped me a lot.
> 0 votes

---
Tags: arduino-uno, serial, can-bus
---


# Question
Title: Performing multiple Wire.writes() - does endtransmission slow things down?
Here's a question for anyone knowledgeable of the ways of I2C.

I'm curious about sending multiple writes to a device and was looking at the code for a MPU9250 module.

There is a nice library that compiled straight off the shelf by Kris Winer here.

In one of his code examples he makes multiple calls to a function called writeByte():

```
// Wire.h read and write protocols
void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
{
    Wire.beginTransmission(address);  // Initialize the Tx buffer
    Wire.write(subAddress);           // Put slave register address in Tx buffer
    Wire.write(data);                 // Put data in Tx buffer
    Wire.endTransmission();           // Send the Tx buffer
}

```

here is a (truncated) example of the code calling writeByte():

```
void initMPU9250()
{
  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00);
  delay(100);

  writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
  delay(200);
  writeByte(MPU9250_ADDRESS, CONFIG, 0x03);
  writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04);
  .
  .
  .
  etc
}

```

My question is why call Wire.endtransmission() each time your sending I2C to the same device? I can see one reason straight off the bat which is you may need to call delay after your write() - but in cases where you do not need to call delay, wouldnt it be faster to do something like:

```
Wire.beginTransmission(address);
Wire.write(data1);
Wire.write(data2);
Wire.write(data3);
Wire.write(data4);
Wire.endTransmission();

```

at least when it's possible?

# Answer
No, `Wire.endTransmission()` doesn't "slow things down". It is, however, critical to the operation of the Wire library.

When you do a Wire transaction all the data you send is first buffered in an internal array. Only when you call `Wire.endTransmission()` does that data actually get sent out. The actual `Wire.endTransmission()` doesn't add anything extra to the transmission though.

In your example you are sending a total of 5 bytes (address + 4 data bytes) plus start/ACK/stop bits. In general most devices require you to send specific numbers of bytes in a specific order - the most common being a register address followed by the content of that register. That means 3 bytes. Any more bytes after that in the same transaction will either be ignored or would overwrite the first bytes.

Some devices though would allow `<address><value><address><value>` to be sent, thus removing the need for the repeated I2C address byte for the device each time. Many won't though.

Other devices (most notably flash memory or SRAM chips) would allow you to do *page mode* accesses, which would be `<address><data1><data2>...<dataN>` where the `address` would automatically increment for each data byte. Again, some may, some won't.

It is entirely down to the device you are sending data to as to whether you are able to batch together multiple blocks of data, and the form that batching has to be in if it is supported at all. So you should look in the datasheet for the device to see just what it can support.
> 4 votes

---
Tags: i2c
---


title: Serial data is not sent on interrupt

text:
# Question
Title: Serial data is not sent on interrupt
I have a short program which should receive data, use this data to turn on/off an LED, and send data when a button is pressed. It is deployed on a Digispark board. The button is connected to `INT0` port (PB2). The interrupt works, but data is not send. Receiving data works fine.

What am I missing here?

```
#include <SoftSerial.h>

#define RxD 1
#define TxD 0
#define out 3
#define btn 2
#define testled 4

SoftSerial blueToothSerial(RxD, TxD); //RX, TX
volatile int buttonState = 0;

void setup() {
  pinMode(out, OUTPUT);
  pinMode(btn, INPUT);
  pinMode(testled, OUTPUT);
  setupBlueToothConnection();
  digitalWrite(out, HIGH);
  digitalWrite(testled, HIGH);
  attachInterrupt(0, intrpt, CHANGE);
}

void loop() {
  char newVal;
  if(blueToothSerial.available()){
    newVal = blueToothSerial.read();
    if (newVal == '1') {
      digitalWrite(out, HIGH);
    } else {
      digitalWrite(out, LOW);
    }
  }
}

void intrpt() {
  buttonState = digitalRead(btn);
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(testled, HIGH);
  } else {
    // turn LED off:
    digitalWrite(testled, LOW);
    blueToothSerial.println("0");
  }
}

void setupBlueToothConnection() {
  blueToothSerial.begin(9600);
  blueToothSerial.print("\r\n+STWMOD=0\r\n");
  blueToothSerial.print("\r\n+STNA=HC-05\r\n");
  blueToothSerial.print("\r\n+STOAUT=1\r\n");
  blueToothSerial.print("\r\n+STAUTO=0\r\n");
  delay(2000);
  blueToothSerial.print("bluetooth connected!\n");
  delay(2000);
  blueToothSerial.flush();
}

```

**EDIT**

Serial data is sent fine. The above code works. On Windows I can see the data are coming, but not on OS X.

# Answer
> 1 votes
If you are handling interrupts then you need to keep the code as quick and simple as possible. I suspect that in this case calling `blueToothSerial.println` is what's causing the problem. It may well be calling an operation that an ISR can't call and so it fails and your code doesn't write the data you expect it to.

All I ever do in ISRs is set flags and then get the 'normal' code to handle changes to the flags. Personally I wouldn't do the digitalWrites within the ISR. Have two volatile variables, one for the pin state and one when sending a message is required and handle those in your `loop()`.

---
Tags: serial, bluetooth, interrupt
---


# Question
Title: WiFiEsp not working on Software Serial, working fine on Hardware Serial
**What I want to achieve**

I want to connect to my wifi network using Arduino UNO and ESP8266 using `WiFiEsp.h` library over \`SofwareSerial, since UNO doesn't have additional H/W serial.

**What I am able to do already**

I have a Mega, which I am able to connect to my wifi network(using ESP8266) using its hardware serial (RX1 and TX1), I've been following up this code example. Though it has code to deal with both cases( when H/W serial is present and when it's not) It doesn't seems to work on Software Serial on UNO, works perfectly on MEGA's H/W serial. I have made a little change in code as to set the Serial1 baudrate to `115200` as this seems to be supported by my ESP's firmware (1.54)

**ERROR**

`[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module`

**What I've tried**

1. Tried running Software Serial on MEGA on pins 10,11 and 6,7 (Rx,Tx) (Same Error).
2. Swapping Rx,Tx :P
3. Changing pins to 10,11 instead of 6,7 on UNO
4. Switching Baudrate to 9600 on UNO (no help)

Yeah, Not much, but it seems so straight forward I can't figure out what could go wrong. It seems like it can't communicate to ESP, but why?

# Answer
If you're going to talk to your ESP at 9600 baud - and that's about the upper limit for SoftwareSerial - you need to first change the ESP board's baud rate to 9600 baud. It is probably at 115200 right now.

You can do that with either kind of serial. Even though SoftwareSerial can't receive at 115200, it can usually transmit (Uno -\> ESP) that fast. You need to send it the command:

```
AT+UART_DEF=9600,8,1,0,0

```

If you do it with SoftwareSerial, the reply coming back from the ESP after changing its baud will be garbled because your serial terminal will still be listening at the faster speed. So at this point, change the speed of your terminal and send the command:

```
AT

```

The ESP should respond with

```
OK

```

If it does - and it probably will - you're all set and can continue using it at 9600 baud. If not, go back to 115200 baud on your serial terminal and try it again. (I've never had to do it twice).

Update:

> I tried sending AT commands @ 115200, Its actually sending and receiving back well at 115200. Is this normal ?

With hardware serial, yes. The Uno's hardware UART can probably go at up to 4x that! But I've never had any luck receiving with SoftwareSerial at 115200; the most I could count on was 9600.
> 7 votes

---
Tags: serial, esp8266, softwareserial
---


title: Control/switching of headphone audio

text:
# Question
Title: Control/switching of headphone audio
I need to do some simple line control of audio out from a phone, 3.5mm TRS. I would have preferred to use transistors, but the voltage drop on an already fairly weak signal makes it unusable. Also not sure about negative voltage from collector to emitter. Essentially I need to switch the line on/off. How can I do this while not introducing noise or signal loss (K.I.S.S.) - I haven't checked if optocouplers are without voltage drop, but in any case they're probably overkill. Ask for clarification if needed.

# Answer
> 0 votes
Settled on a CMOS bilateral switch (4002). Thanks for the input.

# Answer
> 0 votes
My first thought was what about relays. I've done a quick search and found this http://www.geofex.com/article\_folders/relays/relays\_for\_switching\_audio\_signa.htm and this https://electronics.stackexchange.com/questions/110750/is-it-possible-to-turn-an-audio-signal-on-off-using-a-solid-state-relay so maybe it's not such a stupid idea, but like optocouplers it probably is a bit OTT.

---
Tags: arduino-pro-mini, audio
---


# Question
Title: Standalone ATMEGA328: Verification mismatch on random byte on -subsequent- uploads only
I have an Arduino Pro Mini as an ISP programmer with the ArduinoISP sketch running on it (19200 baud), and an addition in boards.txt that has a 'Standalone ATMEGA328 8MHz Internal' entry that specifies 8MHz and a bootloader file, along with some other things.

I'm trying to upload a simple blink sketch to an ATMEGA328 (not 328p, though the issue persists with that board as well) with no external components (internal clock)

## The Problem

I can flash the bootloader no problem. I can also upload code the first time just fine. The problem is when I try to upload any different code *after* the first time, it gives a verification mismatch error at a seemingly random byte, complaining that 0xsomebody != 0xsomeotherbyte (also seemingly always different). This usually causes the sketch the stop working, and the LED to behave erratically.

## IDE Verbose Outputs

Verbose output for burning the bootloader

Verbose output for first upload of simple sketch: basically Blink.ino

Verbose output for second upload of modified sketch: changed first delay to 1200 (side note: uploading an identical sketch doesn't give the verification mismatch error)

Verbose output for sufficiently different sketch (four digital writes, ie heartbeat example)

## The Sketch

```
void setup() {
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(6, HIGH);
  delay(1100);
  digitalWrite(6, LOW);
  delay(400);
}

```

## Bootloader Files

This is the boards.txt entry that I'm using:

```
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=19200

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

```

I've added this entry to `Users/me/Local/Arduino/packages/arduino/hardware/avr/1.6.17` as well as `Program Files(x86)/hardware/arduino/avr`

Here's the HEX file for the bootloader incase that's useful as well

## The Programmer

Here's a schematic of the programmer:

The solder jumper 'CAP1' is soldered closed.

And the connections to the ATMEGA328

simulate this circuit – Schematic created using CircuitLab

And lastly, a photo of the setup:

Thanks in advance

# Answer
I got some help from someone today. I oversaw a small detail when using the Arduino IDE with an ISP programmer: Hold shift when uploading to target the MCU at the end of the line rather than the MCU in the programmer.

So yeah, I hold shift when clicking upload and everything works great now. Sometimes it's the simplest things you'd never expect.
> 1 votes

---
Tags: arduino-ide, atmega328, bootloader, arduino-pro-mini
---


title: if condition does not work

text:
# Question
Title: if condition does not work
I'm trying to connect two Arduinos according to the example in Example

I added a bit of debug prints so the code looks like:

```
#include <Wire.h>

// Include the required Wire library for I2C<br>#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
  // Define the LED pin as Output
  pinMode (LED, OUTPUT);
  // Start the I2C Bus as Slave on address 9
  Wire.begin(9);
  // Attach a function to trigger when something is received.
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
  Serial.println(x);
}

void loop() {
  //If value received is 0 blink LED for 200 ms
  Serial.print("x = '");
  Serial.print(x);
  Serial.println("'");
  if (x == '0') {
    Serial.println("Do 0");
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
  //If value received is 3 blink LED for 400 ms
  if (x == '3') {
    Serial.println("Do 3");
    digitalWrite(LED, HIGH);
    delay(400);
    digitalWrite(LED, LOW);
    delay(400);
  }
}

```

The strange thing is, the terminal gives the following information:

```
...
x = '2'
x = '2'
x = '2'
x = '2'
x = '2'
x3= '3'
x = '3'
x = '3'
x = '3'
x = '3'
...

```

However, I never see the expected "Do 3" lines. Why is that? I assume if (x == '3) would return true when x = '3'?

Also I see the x3 = '3'instead of x = '3'... now I print x also while an event is received, but are those in two different threads since the expected text would be "3x = '3'") or "x = '3'3"

# Answer
Following code is printing value of integer as string.

```
int x = 0;
...
Serial.print("x = '");
Serial.print(x);
Serial.println("'");

```

It prints `x = '3'` for numeric value 3. But ASCII value for character '3' is actually 51.

And about the second issue - `reveiveEvent` is called from receive ISR asynchronously, so it's completely random when the main code gets interrupted. Btw printing anything inside of ISR is quite tricky. If the output buffer is full or will be filled up inside of ISR, everything gets deadlocked as it needs ISRs enabled.
> 2 votes

---
Tags: arduino-uno, terminal
---


# Question
Title: Differences between a real and clone Arduino uno?
Today I got my clone Arduino and connected it to my real Arduino and they both work. (UPDATE: The Arduino noted as real Arduino probably also is not a real Arduino; however both work fine).

However, I see some differences and wonder if these are good or bad:

My questions

1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.

2) At number 2 are 4 holes without any explanation. What is the function?

3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.

4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

# Answer
> 2 votes
The best help is the schematics for the clone.

> 1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.

Lower left on the schematics is the 12 MHz crystal. It is for the CH340G (USB-UART chip).

> 2) At number 2 are 4 holes without any explanation. What is the function?

Lower middle is the pins X1. They are extra signals from the USB-UART chip (CTS, DSR, R and DCD).

> 3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.

Upper right on the schematics are the extra pins. This might be handy.

> 4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

The original has an extra ISP pins (ICSP1) for the ATmega16U2. See the schematics. The clone has the new layout I2C signals extending beyond pin 13.

---
Tags: arduino-uno, clones
---


# Question
Title: How do I connect Arduino directly to MySQL server using the URL?
I started a project with my Arduino Mega 2560 that gets some values from sensors. I'm using MySQL Connector, https://launchpad.net/mysql-arduino, and this library allows me to connect to a server using the IP address, and it worked on localhost.

This is the code:

```
/* Setup for all libraries */
#include <SPI.h>
#include <Ethernet.h>
#include <sha1.h>
#include <mysql.h>
#include <OneWire.h>

/* Setup for Ethernet Library */
byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xB3, 0x05 }; // MAC address must be unique; this is the Ethernet shield address
IPAddress server_addr( 177, 156, 122, 113 ); // Server addr

/* Setup for all others variables */
int DS18S20_Pin = 2; // Temperature sensor
float temperature;
float placasTensao;
float placasCorrente;
float geradorEolicoTensao;
float geradorEolicoCorrente;
float bateriaTensao;
float bateriaTemp;
float correnteSaidaControlador;
float correnteSaidaConsumo;

OneWire ds(DS18S20_Pin);  // On digital pin 2

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

/* Setup for connection and all variables of the database */
char user[] = "";
char password[] = "";
char INSERT_SQL[1000];
char temperature_convt[10], placasTensao_convt[10], placasCorrente_convt[10], geradorEolicoTensao_convt[10],
     geradorEolicoCorrente_convt[10], bateriaTensao_convt[10], bateriaTemp_convt[10], correnteSaidaControlador_convt[10],
     correnteSaidaConsumo_convt[10];

void setup(){
  Ethernet.begin(mac_addr);
  Serial.begin(9600);
  delay(1000);
}

void loop(){
  temperature = getTemp();
  convert(temperature, temperature_convt);
  snprintf(INSERT_SQL, "INSERT INTO data.data VALUES (%s, 1, 1, 1, 1, 1, 1, 1, NULL)", temperature_convt);
  sendData();
  delay(20000);
}

// Convert a float variable to string
void convert(float data, char *value){
  dtostrf(data, 7, 3, value);
}

// Saves all data on database
void sendData(){
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)){
    delay(500);
    Serial.println("Starting SQL!");
    Serial.println(INSERT_SQL);
    my_conn.cmd_query(INSERT_SQL);
    Serial.println("Query Success!");
    my_conn.disconnect();
    Serial.println("\n");
  } else {
    Serial.println("Connection failed!");
    Serial.println("Make sure all cables are properly connected!\nIf they are, restart the Arduino!\n");
  }
}

// Returns the temperature from one DS18S20 in degree Celsius
float getTemp(){
  byte data[12];
  byte addr[8];
  if (!ds.search(addr)) {
      // No more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }
  ds.reset();
  ds.select(addr);
  ds.write(0x44,1);
  // Start conversion, with parasite power on at the end
  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad
  for (int i = 0; i < 9; i++) { // We need 9 bytes
    data[i] = ds.read();
  }
  ds.reset_search();
  byte MSB = data[1];
  byte LSB = data[0];
  float tempRead = ((MSB << 8) | LSB); // Using two's complement
  float TemperatureSum = tempRead / 16;
  return TemperatureSum;
}

```

Now, how can I connect to a server using the URL? Is there a library like MySQL Connector that allows me to use the URL instead of the IP address?

All I want is to do exactly the same thing that I'm doing with MySQL Connector, but using the URL of the server instead of the IP address.

# Answer
> 0 votes
The easiest, just git 'er done, way would be to do an nslookup on the domain, get the IP address and just hard code that into your source. It's not the most robust solution, as it's possible for the IP address to change over time. However, it's highly likely the IP address won't change frequently.

```
> nslookup google.ca
Server:     64.59.144.93
Address:    64.59.144.93#53

Non-authoritative answer:
Name:   google.ca
Address: 216.58.193.67

```

If you need it to be more robust, you would need the Arduino to perform the dns lookup to resolve the IP address. This looks like it would do the job:

https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/src/Dns.h

# Answer
> 0 votes
You are using DHCP, so this step might be optional. Specify your network addresses (actually we want to specify DNS only but have to specify IP in 2nd argument, so likely have to specify gateway and subnet too):

```
IPAddress dns_addr( 8, 8, 8, 8); // GOOGLE DNS server, could be any DNS
IPAddress gateway_addr( , , , );   // put your gateway addr
IPAddress ip_addr( , , , );   // put your IP addr
IPAddress subnet( , , , );   // put your subnet mask

void setup(){
                  Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, subnet);...

```

Now you could modify **Connector::mysql\_connect** method (or create new method) as follows (only function declaration is changed, body is not):

```
boolean Connector::mysql_connect(/*IPAddress server*/const char *server, int port, char *user, char *password)
{
  int connected = 0;
  int i = -1;

  // Retry up to MAX_CONNECT_ATTEMPTS times 1 second apart.
  do {
    delay(1000);
    connected = client.connect(server, port);
    i++;
  } while (i < MAX_CONNECT_ATTEMPTS && !connected);

  if (connected) {
    read_packet();
    parse_handshake_packet();
    send_authentication_packet(user, password);
    read_packet();
    if (check_ok_packet() != 0) {
      parse_error_packet();
      return false;
    }
    print_message(CONNECTED);
    Serial.println(server_version);
    free(server_version); // don't need it anymore
    return true;
  }
  return false;
}

```

Modify the header file also:

```
boolean mysql_connect(/*IPAddress server*/const char *server, int port,
                                 char *user, char *password)

```

Now you can supply URL:

```
if (my_conn.mysql_connect("http:\\www.mysqlserver.com", 3306, user, password))...

```

---
Tags: arduino-mega, c++, arduino-ide, ethernet, datalogging
---


title: Using an Arduino on a motorcycle

text:
# Question
Title: Using an Arduino on a motorcycle
I want to use the Arduino to control various electronics on my motorcycle. I would need to power the Arduino with the motorcycle battery. So the question is, when the motorcycle is running the alternator will be putting out something like 13v to the battery. So can I still just connect the battery directly to the vIn and ground to power it?

# Answer
> 2 votes
Accordly to Arduino Technical Specs:

-Input Voltage (recommended) 7-12V

-Input Voltage (limit) 6-20V

https://www.arduino.cc/en/main/arduinoBoardUno

Another Arduino thread: https://forum.arduino.cc/index.php?topic=22676.0

I would say a better choice is to use another battery power supply just for Arduino. Is is easy to install, easier to handle and more verstile unless you really needs to use your motorcycle battery. And if you want or need to read your motorcycle battery just use a portable voltage meter plugged onto Arduino with no need to use your vehicle battery to power it.

# Answer
> 0 votes
Just add a rectifier diode or two before the vin input. This gives you a 0.7V drop per diode for large currents, for small currents the LDO won't overheat anyway...

---
Tags: arduino-uno
---


# Question
Title: When writing to SD card the file has all gibberish how do I fix it?
I am working on a class project where I am using a Teensy 3.5 with a Prop Shield with sensor attached that will be loaded into a rocket that I will launch and gather data from the altitude, pressure and temperature sensors and then read into an array and then dump at the peak of the height and when it hits the ground. I believe I have everything working when I test the code but when I open up the txt file I get what looks to be ASCII code but I don't know how to fix it.

Below is the code:

```
//import statements
#include <SD.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_MPL3115A2.h>

// global variable declarations
Adafruit_MPL3115A2 baro = Adafruit_MPL3115A2();

int seconds = 0;
int secondsPerTick = 0;
int counter = 0;
double pressure[15];
double heightA[15];
double temperature[15];
File myFile;
int tempNum;
const int chipSelect = BUILTIN_SDCARD;

//test to make sure program uploaded
void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit_MPL3115A2 test!");
  while (!Serial){
}

  if (! baro.begin()) {
    Serial.println("Couldnt find sensor");
   return;
  }

if (!SD.begin(chipSelect)) {
    Serial.println("initialization failed!");
    return;
  }

while ( seconds < 5 ){

              double pascals = baro.getPressure();
              pressure[counter] = pascals;
              Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

             double altm = baro.getAltitude();
              heightA[counter] = altm;
              Serial.print(altm); Serial.println(" meters");

             double tempC = baro.getTemperature();
              temperature[counter] = tempC;
              Serial.print(tempC); Serial.println(" *C");
              tempNum ++;

              secondsPerTick++; //increments seconds per tick
              if(secondsPerTick == 3){  //if its 3 reset "secondspertick" and increments "seconds"
                secondsPerTick = 0;
                seconds++;
              }
              counter++;

 }

myFile = SD.open("Sensor4.txt", FILE_WRITE);

   if(myFile) {
    Serial.print("Writing to file...");

    //cycle through the array and store it in the SD card
    myFile.write("Pressure Recordings(going up): ");
    for(int i=0; i< 15; i++){
      myFile.write(pressure[i]);
      }
    Serial.println('\n');

       //header for the height sensor recordings
   myFile.write("Height Recordings(going up): ");
    //cycle through the array and store it in the SD card
    for (int j = 0; j <15; j ++){
     myFile.write(heightA[j]);
    }
    Serial.println('\n');

    //header for the temperature sensor recordings
    myFile.write("Temperature Recordings(going up): ");
    Serial.println('\n');
    //cycle through the array and store it in the SD card
    for (int k = 0; k <15; k++){
     myFile.write(temperature[k]);
    Serial.println('\n');
   }

    // close the file:
    myFile.close();
    Serial.println("done.");
    }
   else {
    // if the file didn't open, print an error:
    Serial.println("error opening sensor_recordings.txt");
  }

     //as the rocket descends
while ( seconds > 5 ){

              double pascals = baro.getPressure();
              pressure[counter] = pascals;
              Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

              myFile.write(pressure[counter]);

             double altm = baro.getAltitude();
              heightA[counter] = altm;
              Serial.print(altm); Serial.println(" meters");

             double tempC = baro.getTemperature();
              temperature[counter] = tempC;
              Serial.print(tempC); Serial.println(" *C");
              tempNum ++;

              secondsPerTick++; //increments seconds per tick
              if(secondsPerTick == 3){  //if its 3 reset "secondspertick" and increments "seconds"
                secondsPerTick = 0;
                seconds++;
              }
              counter++;

 }

myFile = SD.open("Sensor4.txt", FILE_WRITE);

   if(myFile) {
    Serial.print("Writing to file...");

    //cycle through the array and store it in the SD card
    myFile.write("Pressure Recordings(going down): ");
    for(int i=0; i< 15; i++){
      myFile.write(pressure[i]);
      }
    Serial.println('\n');

       //header for the height sensor recordings
   myFile.write("Height Recordings(going down): ");
    //cycle through the array and store it in the SD card
    for (int j = 0; j <15; j ++){
     myFile.write(heightA[j]);
    }
    Serial.println('\n');

    //header for the temperature sensor recordings
    myFile.write("Temperature Recordings(going down): ");
    Serial.println('\n');

    //cycle through the array and store it in the SD card
    for (int k = 0; k <15; k++){
     myFile.write(temperature[k]);
    Serial.println('\n');
   }

    // close the file:
    myFile.close();
    Serial.println("done.");
    }
   else {
    // if the file didn't open, print an error:
    Serial.println("error opening sensor_recordings.txt");
  }
 }

void loop() {

```

Here is what gets printed to the txt file:

> €€€ƒ€ƒ‚ƒ€€„~ƒ‚€€€€ƒ€ƒ‚ƒ€€„~ƒ‚€ƒ‚‚‚„‡€„ƒ„……ƒ‚ƒ„Pressure Recordings: ƒ‚‚‚„‡€„ƒ„……ƒ‚ƒ„ Height Recordings: 10010110010101111000Temperature Recordings: Å……ƒƒ…€€ƒ‡‚w Pressure Recordings: Å……ƒƒ…€€ƒ‡‚w
> Height Recordings: 000010100010111 Temperature Recordings: Pressure Recordings: Å……ƒƒ…€€ƒ‡‚w Height Recordings: 000010100010111 Temperature Recordings: Pressure Recordings: Ã‡…„†…„…„ˆ†„„€† Height Recordings: 000000000000000 Temperature Recordings: Pressure Recordings: Ã‡…„†…„…„ˆ†„„€† Height Recordings: 000000000000000 Temperature Recordings: Pressure Recordings: Â†‰†‡…††‰…‰ˆˆ…ˆ Height Recordings: 000000000000000 Temperature Recordings: Pressure Recordings: Â†‰†‡…††‰…‰ˆˆ…ˆ Height Recordings: 000000000000000 Temperature Recordings: Pressure Recordings(going up): ÀŽ‘ŽŒŽŽHeight Recordings(going up): ///000/0/0/0///Temperature Recordings(going up): Pressure Recordings(going down): ÀŽ‘ŽŒŽŽHeight Recordings(going down): ///000/0/0/0///Temperature Recordings(going down): Pressure Recordings(going up): ½–™––•˜–••š™š—™Height Recordings(going up): ///////////////Temperature Recordings(going up): Pressure Recordings(going down): ½–™––•˜–••š™š—™Height Recordings(going down): ///////////////Temperature Recordings(going down):

I also don't know how I can get the data to be formatted to where it reads like:

Pressure(going up):----

Altitude(going up):---

Temperature(going up):---

Pressure(going down):----

Altitude(going down):---

Temperature(going down):---

# Answer
You should convert double to String with this kind of code:

```
char[9] stringval;
dtostrf(doubleval, 8, 4, stringval);

```

where 8 is presicion and 4 is number of digits after point.

More info: http://forum.arduino.cc/index.php?topic=282250.0
> 1 votes

---
Tags: arduino-uno, sd-card, teensy
---


# Question
Title: How to code water flow sensor and solenoid valve?
I want to know if it is possible to put a boundary or limit to the volume that passes through a water flow sensor, and close the pipe using a solenoid valve.

Example: I only want 400 ml of water to pass, so when the water flow sensor reads how much water has passed in the pipe, if 400 is reached, the solenoid will close the pipe.

Sorry for my bad English, it is not my first language. I'm hopping that someone can help me out.

# Answer
> 2 votes
hello @kaisar Great you have not mentioned which flow sensor are you using. I am assuming that you are using flow sensor YF-S201 or YF-S401(Hall Effect).You have to do Little calculation for measuring water flow. In order to measure the quantity of water being passed in particular time through the water flow sensor it was first passed through the water flow sensor which was taken as input interface in the flow. Formulas are applied in order to measure the number of rotations/pulses in a minute of rotation.

Here I have determined flow rate by change in velocity of water. Velocity depends on the pressure that forces the through pipelines. As the pipe’s cross-sectional area is known and remains constant, the average velocity is an indication of the flow rate. The basis relationship for determining the liquid’s flow rate in such cases is

**Q=VxA**, where **Q** is flow rate/total flow of water through the pipe, **V** is average velocity of the flow and A is the cross-sectional area of the pipe

**Calibration Factor** = *The hall-effect flow sensor outputs pulses per second per litre/minute of flow.(check your datasheet) here I have taken 4.5.*

**Flow Rate(litres/minute)** = *((1000.0 / Total time) x Pulse Count) / calibration Factor*

**Flow Rate(MilliLitres/Second)** = *(Flow Rate / 60) x 1000*

There you have to calculate the total water flow in a given time by adding flow rate for each second. There after you have check your set point value(400ml)..if condition satisfied you you can turn off your Solenoid valve.

and the code is

```
int sensorInterrupt = 0;  // interrupt 0
int sensorPin       = 2; //Digital Pin 2
int solenoidValve = 5; // Digital pin 5
unsigned int SetPoint = 400; //400 milileter

/*The hall-effect flow sensor outputs pulses per second per litre/minute of flow.*/
float calibrationFactor = 4.5; //You can change according to your datasheet

volatile byte pulseCount =0;

float flowRate = 0.0;
unsigned int flowMilliLitres =0;
unsigned long totalMilliLitres = 0;

unsigned long oldTime = 0;

void setup()
{

  // Initialize a serial connection for reporting values to the host
  Serial.begin(9600);
  pinMode(solenoidValve , OUTPUT);
  pinMode(sensorPin, INPUT);
  digitalWrite(sensorPin, HIGH);

  /*The Hall-effect sensor is connected to pin 2 which uses interrupt 0. Configured to trigger on a FALLING state change (transition from HIGH
  (state to LOW state)*/
  attachInterrupt(sensorInterrupt, pulseCounter, FALLING); //you can use Rising or Falling
}

void loop()
{

   if((millis() - oldTime) > 1000)    // Only process counters once per second
  {
    // Disable the interrupt while calculating flow rate and sending the value to the host
    detachInterrupt(sensorInterrupt);

    // Because this loop may not complete in exactly 1 second intervals we calculate the number of milliseconds that have passed since the last execution and use that to scale the output. We also apply the calibrationFactor to scale the output based on the number of pulses per second per units of measure (litres/minute in this case) coming from the sensor.
    flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

    // Note the time this processing pass was executed. Note that because we've
    // disabled interrupts the millis() function won't actually be incrementing right
    // at this point, but it will still return the value it was set to just before
    // interrupts went away.
    oldTime = millis();

    // Divide the flow rate in litres/minute by 60 to determine how many litres have
    // passed through the sensor in this 1 second interval, then multiply by 1000 to
    // convert to millilitres.
    flowMilliLitres = (flowRate / 60) * 1000;

    // Add the millilitres passed in this second to the cumulative total
    totalMilliLitres += flowMilliLitres;

    unsigned int frac;

    // Print the flow rate for this second in litres / minute
    Serial.print("Flow rate: ");
    Serial.print(flowMilliLitres, DEC);  // Print the integer part of the variable
    Serial.print("mL/Second");
    Serial.print("\t");

    // Print the cumulative total of litres flowed since starting
    Serial.print("Output Liquid Quantity: ");
    Serial.print(totalMilliLitres,DEC);
    Serial.println("mL");
    Serial.print("\t");
    If (totalMilliLitres =< 400)
    {
      SetSolinoidValveON();
    }
    else{
      SetSolinoidValveOFF();
        }

// Reset the pulse counter so we can start incrementing again
    pulseCount = 0;

    // Enable the interrupt again now that we've finished sending output
    attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
  }
}

//Insterrupt Service Routine

void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

void SetSolinoidValveON()
{
  digitalWrite(solenoidValve, HIGH);
}
void SetSolinoidValveOFF()
{
  digitalWrite(solenoidValve, LOW);
}

```

# Answer
> 1 votes
Using a YF201 you cannot measure less than 1 litre / minute or more than 30 l/m. (ref http://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/)

The device sends a pulse for every 2.25ml that flows through it. All you needs to do is take the amount you want to let through (400ml) and divide that by 2.25ml and you get 177.8 pulses. So once your Arduino counts 178 pulses then you trigger the valve to close.

Its not going to be very accurate, because unless the valve closes instantly there will be a bit of an overshoot. and you have to measure in units of 2.25ml.

---
Tags: arduino-mega
---


# Question
Title: Using SIMCOM SIM800 as a Bluetooth SPP Client
I just bought a SIM800 module for my Arduino project and I found that I supports Bluetooth too. I have already worked with HC-05 and my Android phone.

I tried to play with this module and able to connect it successfully with my Android mobile. I am able to make a call using it, accept a call, etc. But when I tried to send text data using it (in SPP mode), I ran into problem.

I have an app called Bluetooth Terminal in my mobile with which I use to communicate with my HC-05. But with SIM800, I can't connect.

I have read all the AT commands which are used to make a SPP connection. Here's a screenshot of the PuTTy terminal where I tried to make the connection:

As you can see in the image, whenever I try to call

> AT+BTGETPROF=1

It never returns to me. I also tried the command with my Bluetooth visible in the mobile, but still no result.

Whenever I try to run the command or

> AT+BTCONNECT=1,4

My SIM800 goes into state 2 and I have to manually reset it.

Can someone please help me with this problem? I just want to use my SIM800 as a SPP client/server so that I can exchange text data with my Android APP.

Thanks in advance.

# Answer
By default i see that the Android handset i used did not have SPP profile enabled. You need to open a App which enables the SPP profile to be advertised. Then after that you can get that in AT+BTGETPROF list. I made a tutorial for this, Have a look here,

https://youtu.be/zdQb8r2xRK8

and

http://www.raviyp.com/embedded/215-sim800-series-bluetooth-at-commands
> 1 votes

---
Tags: bluetooth, android
---