title: Arduino Modbus RTU VFD control

text:
# Question
Title: Arduino Modbus RTU VFD control
I need help with this code:

```
/**
*  Modbus master example 1:
*  The purpose of this example is to query an array of data
*  from an external Modbus slave device.
*  The link media can be USB or RS232.
*
*  Recommended Modbus slave:
*  diagslave http://www.modbusdriver.com/diagslave.html
*
*  In a Linux box, run
*  "./diagslave /dev/ttyUSB0 -b 19200 -d 8 -s 1 -p none -m rtu -a 1"
* This is:
* serial port /dev/ttyUSB0 at 19200 baud 8N1
* RTU mode and address @1
*/

#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[16];
uint8_t u8state;

/**
*  Modbus object declaration
*  u8id : node id = 0 for master, = 1..247 for slave
*  u8serno : serial port (use 0 for Serial)
*  u8txenpin : 0 for RS-232 and USB-FTDI
*               or any pin number > 1 for RS-485
*/
Modbus master(0,0,2); // this is master and RS-232 or USB-FTDI, PIN 9 PARA INDICAR QUE TRASMITO

/**
* This is an structe which contains a query to an slave device
*/
modbus_t telegram;

unsigned long u32wait;

void setup() {
 master.begin( 9600 ); // baud-rate at 19200
 master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
 u32wait = millis() + 1000;
 u8state = 0;
}

void loop() {
 switch( u8state ) {
 case 0:
   if (millis() > u32wait) u8state++; // wait state
   break;
 case 1:
   telegram.u8id = 1; // slave address
   telegram.u8fct = 5; // function code (this one is registers read)
   telegram.u16RegAdd = 0; // start address in slave
   telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read
   //telegram.au16reg = au16data; // pointer to a memory array in the Arduino

   // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 05 00 00 FF 00 -> START
   // 01 -> SLAVE (VFD OMRON)
   // 05 -> WRITE COIL
   //  00 00 -> ADDRESS COIL
   // FF 00 -> VALUES TO WRITE IN COIL FOR RUN

   telegram.au16reg[0] = 0;
   telegram.au16reg[1] = 0;
   telegram.au16reg[2] = 0;
   telegram.au16reg[3] = 0;
   telegram.au16reg[4] = 0;
   telegram.au16reg[5] = 0;
   telegram.au16reg[6] = 0;
   telegram.au16reg[7] = 0;

   telegram.au16reg[8] = 1;
   telegram.au16reg[9] = 1;
   telegram.au16reg[10] = 1;
   telegram.au16reg[11] = 1;
   telegram.au16reg[12] = 1;
   telegram.au16reg[13] = 1;
   telegram.au16reg[14] = 1;
   telegram.au16reg[15] = 1;

   master.query( telegram ); // send query (only once)
   delay(3500);

   telegram.u8id = 1; // slave address
   telegram.u8fct = 6; // function code (this one is registers read)
   telegram.u16RegAdd = 1; // start address in slave
   telegram.u16CoilsNo = 4; // number of elements (coils or registers) to read
   //telegram.au16reg = au16data; // pointer to a memory array in the Arduino
   //telegram.au16reg = 0000000111110100;

   // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 06 00 01 01 F4 -> CHANGE FQ
   // 01 -> SLAVE (VFD OMRON)
   // 06 -> WRITE IN REGISTE
   // 00 01 -> REGISTER ADDRESS
   // 01 F4 -> VALUE TO WRITE IN THE REGISTER TO CHANGE THE MOTOR FREQUENCY

   telegram.au16reg[0] = 0;
   telegram.au16reg[1] = 0;
   telegram.au16reg[2] = 0;
   telegram.au16reg[3] = 0;
   telegram.au16reg[4] = 0;
   telegram.au16reg[5] = 0;
   telegram.au16reg[6] = 0;
   telegram.au16reg[7] = 1;

   telegram.au16reg[8] = 1;
   telegram.au16reg[9] = 1;
   telegram.au16reg[10] = 1;
   telegram.au16reg[11] = 1;
   telegram.au16reg[12] = 0;
   telegram.au16reg[13] = 1;
   telegram.au16reg[14] = 0;
   telegram.au16reg[15] = 0;

   master.query( telegram ); // send query (only once)
   delay(3500);
   telegram.u8id = 1; // slave address
   telegram.u8fct = 5; // function code (this one is registers read)
   telegram.u16RegAdd = 1; // start address in slave
   telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read
   //telegram.au16reg = au16data; // pointer to a memory array in the Arduino

   // PARA EL VARIADOR OMRON MX1: MODBUS RTU 01 05 00 00 00 00 -> STOP
   // 01 -> ESCLAVO (VARIADOR OMRON)
   // 05 -> ESCRIBIR EN UNA BOBINA
   // 00 00 -> DIRECCION DE LA BOBINA
   // 00 00 -> VALOR A ESCRIBIR EN LA BOBINA PARA STOP

   telegram.au16reg[0] = 0;
   telegram.au16reg[1] = 0;
   telegram.au16reg[2] = 0;
   telegram.au16reg[3] = 0;
   telegram.au16reg[4] = 0;
   telegram.au16reg[5] = 0;
   telegram.au16reg[6] = 0;
   telegram.au16reg[7] = 0;
   telegram.au16reg[8] = 0;
   telegram.au16reg[9] = 0;
   telegram.au16reg[10] = 0;
   telegram.au16reg[11] = 0;
   telegram.au16reg[12] = 0;
   telegram.au16reg[13] = 0;
   telegram.au16reg[14] = 0;
   telegram.au16reg[15] = 0;
   master.query( telegram ); // send query (only once)
   delay(3500);
   u8state++;
   break;
 case 2:
   master.poll(); // check incoming messages
   if (master.getState() == COM_IDLE) {
     u8state = 0;
     u32wait = millis() + 100;
   }
   break;
 }
}

```

I've managed to send RUN command to VFD but i can't (so far) send the change frequency command "01 06 00 01 01 F4" + CRC check.

When I connect logic analyzer with modbus rtu decoder, it shows "Device ID:'1' Function Write single coil ('5') Addr: '0' value: '65280' Chksum: '14988'.

The problem is that it pass only 1 telegram (array of packets) for command "RUN" but no the two others. Any help will be appreciated.

This is the link for VFD Omron MX: https://industrial.omron.us/en/media/I570-E2-02B\_3G3MX2\_UsersManual\_tcm849-112721.pdf

TIA

# Answer
> 1 votes
You should update the comments and remove unused settings like the count fields for request with one value (function 5 and 6).

au16reg are the data to be send. ignore the binary format from the example.

To send a value of the coil or register set the value to telegram.au16reg\[0\].

For the Modbus message protocol see for example the Wikipedia article.

---
Tags: modbus
---


# Question
Title: How to add additional millisecond delay to microsecond delay generator
I am trying to make a delay generator. I already found an excellent example in Generating a short pulse after a delay that works in the range from ~5-32767 microseconds (it is limited by a 16 bit microsecond counter divided by 2).

How would I go about extending that range into the millisecond range (say up to 1s or so)? Since this example is interrupt-based, adding delay() statements do not really seem to work.

I have also tried changing the timer prescaler, but then the jitter is also scaled up in an unacceptable way.

This is the code I have now. Send commands via the arduino serial console, D500 for 500µs delay, L100 for a 100µs long pulse. Letters M and N change the prescaler.

```
uint16_t pulse_delay = 10; //half-microseconds
uint16_t pulse_length = 10;
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
long read_value = 0;
long ms_delay = 0;

void printvals() {
  Serial.print(F("Delay: "));
  Serial.print(pulse_delay / 2);
  Serial.println(F(" µs"));
  Serial.print(F("Length: "));
  Serial.print(pulse_length / 2);
  Serial.println(F(" µs"));
}
long getcommandvalue(String inputstring) {
  inputString.remove(0,1);
  return inputString.toInt();
}
void setup(){
  pinMode(8, INPUT);
  pinMode(9, OUTPUT);
  TCCR1A = 0;
  TCCR1B = _BV(ICNC1)  //input capture noise cancel
      | _BV(ICES1) //positive edge
      | _BV(CS11); // /8 prescaler
  TIMSK1 = _BV(ICIE1); //enable input capture interrupt
  Serial.begin(9600);
  inputString.reserve(200);
  Serial.println(F("RDY"));
  printvals();
}
void loop(){
  if (stringComplete) {
      switch(inputString.charAt(0)) {
        case 10: //\n (Newline; Line Feed)
          // previous line ending was CRLF, so now LF was carried to the next string
          break;
        case 63: //?
          //print current vales
          printvals();
          break;
        case 68: //D (Delay)
          read_value = getcommandvalue(inputString);
          if (read_value >= 1) {
            pulse_delay = 2 * read_value;
            printvals();
          }
          break;
        case 76: //L (Length)
          read_value = getcommandvalue(inputString);
          if (read_value >= 1) {
            pulse_length = 2 * read_value;
            printvals();
          }
          break;
        case 77: //M (additional prescaling)
          TCCR1B = _BV(ICNC1)  //input capture noise cancel
            | _BV(ICES1) //positive edge
            | _BV(CS10) // 64 prescaler
            | _BV(CS11); // /8 prescaler
          break;
        case 78: //N (8x prescaling)
          TCCR1B = _BV(ICNC1)  //input capture noise cancel
            | _BV(ICES1) //positive edge
              | _BV(CS11); // /8 prescaler
          break;
        case 79: //O
          ms_delay = getcommandvalue(inputString);
          // I don't know where to execute this ms_delay
          break;
      }
      inputString = "";
      stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:Z
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if ((inChar == '\n') or (inChar == '\r')) {
      stringComplete = true;
    }
  }
}

ISR(TIMER1_CAPT_vect){
  TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
  TIFR1 = _BV(OCF1A);  // clear interrutp flag
  TIMSK1 |= _BV(OCIE1A); //enable match interrupt
  OCR1A = pulse_delay; //pulse begin time

  TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                        //the interrupt isn't run immediately
}
ISR(TIMER1_COMPA_vect){
  TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
  TCCR1A = _BV(COM1A1); //clear OC1A on match
  OCR1A = pulse_delay + pulse_length;
}

```

# Answer
You could count timer compare matches. The following illustrates the principle, maybe not accurate as written but I am sure the counter loop will be precise enough for your needs, considering you want to use an Arduino. Depending on the time resolution you want, you may be able to run other code while the software counter is active.

The following can count to several seconds, depending on values of `OCR1A` and `counter_target`.

```
unsigned int state, pulse_delay;
byte counter[3]={0,0,0}; // 24 bit counter, you can make it longer in principle

byte counter_target[3]={0,0,0}; // defines length of delay you want

void setup(){
state=0;
TCCR1A=0;
TCCR1B=0;
}

void loop(){
switch (state){
case 0: // idle state machine // you other code here
counter_target[0]=0; // For example
counter_target[1]=0;
counter_target[2]=1; // corresponds to (1+65536)*pulse_delay/clock_scaler
// when you are ready to start counting
state=1;
break;

case 1: // setup timer
counter[0]=0; // Zero the 24-bit counter
counter[1]=0;
counter[2]=0;
OCR1A = pulse_delay; // number of pulses to count = 1+OCR1A
OCR1B = OCR1A+1;
ICR1  = OCR1A+1;    // Just to make sure these don't cause compare match
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
state=2;
TCCR1A = B00000011; // Fast PWM mode 15 on UNO, OCR1A=TOP
TCCR1B = B00011001; // Clock prescaler 1
break;

case 2: // Counting up
loop_until_bit_is_set(TIFR1,OCF1A);
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
counter[0]+=1; // Increment counter by 1
if(counter[0]==0x00){counter[1]+=1;
if(counter[1]==0x00){counter[2]+=1;}} // etc

if(counter[0]==counter_target[0] && counter[1]==counter_target[1] && counter[2]==counter_target[2]){state=0;}  // Check if we have reached the target delay
break;

}
}

```
> 1 votes

---
Tags: interrupt, timers, sleep
---


# Question
Title: I have downloaded the library but not sure what went wrong
```
C:\Users\Dray98\AppData\Local\Temp\arduino_modified_sketch_819854\sketch_jun09a.ino:2:29: fatal error: Adafruit_Sensor.h: No such file or directory

 #include <Adafruit_Sensor.h>

                             ^

compilation terminated.

Multiple libraries were found for "DHT.h"
 Used: C:\Users\Dray98\Documents\Arduino\libraries\DHT_sensor_library
 Not used: C:\Users\Dray98\Documents\Arduino\libraries\DHT-sensor-library-master
Using library DHT_sensor_library at version 1.3.0 in folder: C:\Users\Dray98\Documents\Arduino\libraries\DHT_sensor_library
exit status 1
Error compiling for board Arduino/Genuino Uno.

```

# Answer
When you encounter a `No such file or directory` error it usually means you need to install the library that contains the missing file (in this case Adafruit\_Sensor.h).

Ideally the documentation for the code you are trying to compile will have instructions for installing dependencies.

Sometimes the author did not make the effort to write this documentation and you'll need to go searching for the missing library.

Many Arduino libraries are in the Library Manager index, which makes them quite easy to install:

### Library Manager installation

1. (In the Arduino IDE) Sketch \> Include Library \> Manage Libraries.
2. Wait for the download to finish.
3. In the "Filter your search..." box, type your search query, in this case "adafruit unified sensor abstraction layer" would get you the one correct result but with a little searching through the results of a more general search like "adafruit sensor" will get you there also.
4. Scroll through the search results to find something that looks correct (in this case "Adafruit Unified Sensor by Adafruit"), then click on it.
5. Click "Install".
6. Wait for installation to finish.
7. Click "Close".

If you don't find the library you need in Library Manager you'll need to spend some time with your favorite search engine. Once you find the library and download it you'll need to install it.

### .ZIP Installation

1. (In the Arduino IDE) Sketch \> Include Library \> Add .ZIP Library
2. Select the downloaded file (must be a .zip).
3. Click "Open".

The above installation instructions require the .zip file to have a specific folder structure. In some cases the library author has not been kind enough to provide the correct folder structure. If you get a "Zip doesn't contain a library" error message then you will need to do a manual installation of the library.

### Manual Installation

1. Unzip the downloaded file
2. Browse through the unzipped folder until you find the library folder. This will either have a library.properties file and/or a .h file.
3. Copy the library folder to `{Sketchbook folder}/libraries`. You can find the sketchbook folder in the Arduino IDE at **File \> Properties \> Sketchbook location**. You will need to restart the Arduino IDE before the examples sketches for manually installed libraries will appear under the **File \> Examples** menu.
> 2 votes

# Answer
Your problem is, that you haven't installed the `Adafruit_Sensor.h`, which is a dependency of Adafruits DHT library. The README on Github for the DHT library also states this:

> You must have the following Arduino libraries installed to use this class:
>
> ```
> Adafruit Unified Sensor Library
>
> ```

You can find the `Adafruit_Sensor.h` here at Github. Install it in your libraries folder. You can refer to the answer from per1234 for instructions on installing libraries.

--

The second part in your error output is not really an error. As others stated before, the IDE only tells you, which version of the DHT library it uses. If you want to have multiple version in your libraries folder, you will have to make sure, that you always use the correct one. If they are identical, you can delete one of them, if you want to. The outcome would not be any different, except for that the IDE doesn't have to tell you, which library it uses.
> 1 votes

# Answer
Have you installed the Adafruit\_Sensor library correctly? If not, at top of IDE, click Include Library \> and see if it's in the list and click it, if not, go to top of list and click Manage Libraries..., search for and click on it.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Is it possible to setup a CAN-BUS Arduino Shield to communicate with SocketCAN for UNIX?
I have an Arduino + SparkFun CAN shield, and I was hoping to set it up to work with candump on an Ubuntu system. Is this doable, or is candump made specifically for raspberry Pi's?

# Answer
Yes. Normally you would write a linux kernel driver to communicate with your device (arduino) following your own protocol, but SocketCAN provides by default a way to interface with Lawicel dongles, whose communication protocol is publicly available: CANUSB / CAN232 protocol.

Many people have built arduino sketches that implement this protocol so you can use your arduino with SocketCAN in Linux (candump, cansniff...) as if it were a Lawicel dongle.

You may find this useful:

https://github.com/autowp/arduino-canhacker

https://github.com/kahiroka/slcanuino
> 2 votes

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


# Question
Title: DT-06 WIFI. How to program with Arduino Uno
I have a DT-06 wireless WiFi. I can connect using my phone but I cannot access 192.168.4.1/status.html or /wifi\_set.html like in the tutorial

I put this module in wiring with Arduino Uno on 5v. I notice that the LED is low lighting until I put pin state in GND. Then I get full power red led. I put RX module to TX Arduino and TX module to RX Arduino but i can not access it using Arduino.

How can I program this module or how can I access? Any tutorial links are welcome.

Thanka. Sorry for my English.

L.E.

Module RX - Arduino TX Module TX - Arduino RX Module VCC - Arduino 5v Module GND - Arduino GND Module STATE - GND

My module has a red led on it. This led is low lighting until i put pin STATE in GND. After that the red led is full lighting.

After i put VCC and GND i can "see" my module using my phone wireless connection

# Answer
Are you wiring it to Arduino pins 0 & 1? These are hard-wired to the other processor on the Arduino board that handles USB to/from your PC. There may be interference with the DT-06 unless you disconnect from your PC after upload. But then you'll need an alternate source of power to the Arduino.

You can pick another pair of pins and use the SoftwareSerial library (up to 9600 baud) to talk to the DT-06. Make sure Arduino and the DT-06 use the same baud-rate. You may have to experiment to find what baud-rate the device has now, in order to set it to 9600.

Update:

> Do i have to use any resistence?

Two sites I looked at described the DT-06 voltage requirement as: "Working voltage: 4.5V~6.0V, TTL working voltage: 3.3V (compatible with 5.0V);", so you should be OK without voltage divider resistors.

> And what settings to make in arduino IDE before uploading code?

You won't need to change your IDE to upload code to the Uno.
> 1 votes

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


# Question
Title: What is corrrect the way to find roll, pitch, yaw?
I have an MPU9250. I have calculated accelerometer, gyroscope, magnetometer. But I want to know how to caclulate roll yaw pitch. I have searched on Google. I found many answer

```
roll  =  (atan2(-Accel_Y, Accel_Z)*180.0)/M_PI;
pitch =  (atan2(Accel_X sqrt(Accel_Y*Accel_Y + Accel_Y*Accel_Y))*180.0)/M_PI;

```

source: https://theccontinuum.com/2012/09/24/arduino-imu-pitch-roll-from-accelerometer/

```
   accelerationX = (signed int)(((signed int)rawData_X) * 3.9);
   accelerationY = (signed int)(((signed int)rawData_Y) * 3.9);
   accelerationZ = (signed int)(((signed int)rawData_Z) * 3.9);
   pitch = 180 * atan (accelerationX/sqrt(accelerationY*accelerationY + accelerationZ*accelerationZ))/M_PI;
   roll = 180 * atan (accelerationY/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;
   yaw = 180 * atan (accelerationZ/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;

```

source: https://engineering.stackexchange.com/questions/3348/calculating-pitch-yaw-and-roll-from-mag-acc-and-gyro-data

```
  Accroll = atan2( accy / (accy^2 + accz^2) )
  Accpitch = atan2( accx / (accx^2 + accz^2) )

```

source: http://franciscoraulortega.com/pubs/Algo3DFusionsMems.pdf

```
 Accroll = atan2(accy, accz)
 Accpitch = atan2( -accx, sqrt(accy^2 + accz^2) )

```

source:https://www.nxp.com/docs/en/application-note/AN3461.pdf

What is the correct way to find roll yaw pitch?

# Answer
For a stationary accelerometer sensing the acceleration of gravity, I see "dead zones" when the Pitch, Yaw or Roll axes are parallel or close to parallel to the gravity vector.

Likely this is why accelerometers are used in conjunction with gyroscopes.

Refer to this NXP (aka Motorola, Freescale & Qualcomm) document for an in depth discussion regarding the necessary math. Note the section regarding "Regions of Instability".

Also, refer to this class and this class from rutgers.edu which work students through a project using an Arduino and an accelerometer in the 1st class then adds a gyroscope in the 2nd class to improve the response.

(Added Later)

The rutgers.edu links don't appear to work anymore and this link has been suggested as an alternative.
> 1 votes

---
Tags: accelerometer
---


# Question
Title: Communication between Genuino Zero and Arduino Uno using UART
I want to make my Arduino Uno and Genuino Zero communicate using UART. My Genuino Zero is the transmitter and the receiver is the Arduino Uno.

For the Arduino Uno, I am using the SoftSerial library. I have uploaded the transmitter and receiver codes.

My connection is as below:

> Genuino Zero (RX) pin 0 ---------------- Arduino Uno pin 11
>
> Genuino Zero (TX) pin1 ---------------- Arduino Uno pin 10
>
> Ground ---------------------------------- Ground

The Arduino Uno's pin 10 is Rx and pin 11 is Tx, using SoftSerial.

The transmitter transmits 'a'. The receiver receives 'a' and turns a LED on. My problem is that on the receiver, I am not getting anything.

My code is here:

https://www.dropbox.com/s/4w8o2h2k4zs0it5/transmitter.txt?dl=0 https://www.dropbox.com/s/d50uizoz3iove9w/receiver.txt?dl=0

-------------------receiver---------------------

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

/* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

/* Use a variable called byteRead to temporarily store
   the data coming from the computer */
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);
   mySerial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  char a[8];
  /*  check if data has been sent from the computer: */
  if (Serial.available()) {
    /* read the most recent byte */
    byteRead = Serial.read();
    Serial.print("rushin\r\n");
    /*ECHO the value that was read, back to the serial port. */
    if(byteRead == 0x61) {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.write(byteRead);
    }
  }
  if (mySerial.available()) {
    /* read the most recent byte */
    byteRead = mySerial.read();
    mySerial.print("rushin\r\n");
    /*ECHO the value that was read, back to the serial port. */
    if(byteRead == 0x61) {
      digitalWrite(LED_BUILTIN, HIGH);
      mySerial.write(byteRead);
     }
  }
}

-------------------transmitter----------------------------------

/*
  DigitalReadSerial
 Reads a digital input on pin 2, prints the result to the serial monitor
 This example code is in the public domain.
 */

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 7;
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println("a");
  delay(1000);
  // delay in between reads for stability
}

```

# Answer
Your Arduino Zero transmitter code transmits to the USB Serial ('Serial') only. If you want it to transmit to the serial comm on pin 0 and pin 1, you must have it write to Serial1. (Check variants.cpp file ) you will see that Serial1 is uses SERCOM0 which is on pin 0 and 1.

So, Your code should look like this (noitce "Serial" is replaced with "Serial1"):

```
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial1.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial1.println("a");
  delay(1000);
  // delay in between reads for stability
}

```
> 1 votes

---
Tags: uart
---


# Question
Title: How much low analog voltage can Arduino uno read?
Today I was playing around with arduino analog voltage ranges, the error in output with respect to a digital multimeter started to happen when the reading was around 0.0014volts. How much low an arduino can read?

# Answer
> 4 votes
The Arduino Uno uses a processor containing a 10 bit ADC. This means the ADC can resolve (if we do not consider noise) 2 to the 10th or 1024 voltage levels between zero and the voltage supplied to the Arduino Uno at the AREF pin. There is a good explanation of the AREF pin in this stackexchange.com question / answer. It is common practice to supply the AREF with voltages lower than the positive rail the processor is operating at to improve resolution of expected lower voltages. For example, if you do not expect to measure voltages higher than 3.3 volts on a 5 volt Arduino, use the 3.3 volt supply as a reference. Relative to using a 5 volt reference, using a 3.3 volt reference decreases your granularity from 0.00489 to 0.00322 volts per step.

Of course there is a lot of noise in most ADC circuits. Finding the average of many ADC readings helps mitigate this problem. Consider using exponential averaging.

# Answer
> 0 votes
You divide your reference voltage by 1024. That tells you what the step size is. The smallest you can measure is an ADC reading of 1. So for say a 5V reference that works out to 0.00488V

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


# Question
Title: Long freezes at the beginning of sd card transfer
I am creating an accelerometer data logger that writes data to sd card. After some sort of "warm-up" everything works perfectly for at least ~15 minutes (which is what I have tested so far).

However, during the first few seconds there are some pretty long freezes of the File.write() function (180 ms instead of 50us for normal writes!) which I can identify on an oscilloscope (see picture below, signal low after starting high indicates File.write() phases) and which I can also see in the data if I include in them a milis() timestamp.

Since RAM on the Atmega328 is limited, there is also tight limits to the amount of sensor data I can buffer (I am using an interrupt for transfer from the sensor, where I can store the data to a buffer and thus bridge the shorter sd card delays).

I stripped down my code to the absolute bare bones, just writing nonsense data instead of those from the accelerometer. What could be the reason for these freezes? The data rate is the same during the whole run. Isn't the sd card electrically or logically initialized after SD.begin()? It doesn't seem to be a problem with erasing flash memory blocks because it only occurs in the beginning. Even if I restart the application a second time (after staying electrically on all the time) it already shows no freezes anymore. Whereas if I unplug/plug power, the freezes in the beginning reappear.

**And most importantly: how can I solve it?**

Of course I could write the dummy data before receiving the start button. But how many? Does it depend on sd card type? Does it depend on cpu or spi clock frequency? I want a robust solution that doesn't break when I use another type of sd.

Code:

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

const int chipSelect = 10; // chip select of the sd card
const int pushButton = 9; // this is where the start button is (on a pulldown resistor)
const int debugPin = 1; // a line used for displaying a debug bit on the oscilloscope

const int bufferSize = 14;
byte buffer[bufferSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; // for the test just dummy values

String fileName = "accellog.raw";

void setup()
{
  pinMode(pushButton, INPUT);
  pinMode(debugPin, OUTPUT);

  if (!SD.begin(chipSelect))
  {
    // on error stop execution
    for(;;);
  }
}

void loop()
{
  // wait for the start button to be pressed
  while (digitalRead(pushButton) == HIGH);
  delay(100); // debounce delay
  while (digitalRead(pushButton) == LOW);

  // remove old file on sd card
  if (SD.exists(fileName)) SD.remove(fileName);

  File dataFile = SD.open(fileName, FILE_WRITE);

  if (dataFile)
  {
    // Debugging: indicate start of whole data transfer on an oscilloscope
    digitalWrite(debugPin, HIGH);

    int lastMillis = millis();

    for (long i=0; i<10000; i++)
    {
      // wait until millis changes in order to get SD writes at
      // whole millisecond boundaries (some cycles may get lost,
      // however, during lengthy SD writes)
      int tempMillis = millis();
      while (tempMillis == lastMillis)
      {
        tempMillis = millis();
      }
      lastMillis = tempMillis;

      // Debugging: indicate file access times by sending 0 to the DSO
      digitalWrite(debugPin, LOW);

      dataFile.write(buffer,bufferSize);

      // Debugging: indicate end of file access on DSO
      digitalWrite(debugPin, HIGH);
    }

    // Debugging: indicate end of whole data transfer
    digitalWrite(debugPin, LOW);

    dataFile.close();
  }
  else
  {
    // on error stop execution
    for (;;);
  }
}

```

# Answer
As a temporary workaround I have come to the following procedure:

I inserted a function that writes a certain amount of bytes into a dummy file, closes it and finally deletes it, all during setup().

This does indeed seem to cure the freezes if (in my scenario) I write at least 6 blocks (512 bytes each, i.e. total 3072 Bytes). Remarkably there were always exactly 6 freezes visible in my oscilloscope plots. I don't even remotely know what the meaning of this magic number 6 could be...

Just to have some additional safety in case I choose a different type of sd card (and this workaround becomes permanently temporary...), I have decided to write 16 kB into the dummy file. This is ~5 times as much as the empirical minimum value (3 kB) and is still pretty fast so that I don't notice any significant startup delay after power-up.

This empiric approach is still unsatisfactory though, and certainly a piece of mediocre engineering. So I won't mark my answer as accepted, to leave the chance for someone else to give a more well-founded answer.

```
void writeAndEraseDummyFileToEliminateFreeze()
{
  if (SD.exists("dummy")) SD.remove("dummy");
  File dummyFile = SD.open("dummy", FILE_WRITE);
  int n = 16384/recordSize+1; // write 16kB in chunks of recordSize (just because we have that buffer already
  for (int i=0; i<n; i++)
  {
    // buffer values are uninitialized, but who cares, we'll dispose of them anyway
    dummyFile.write(buffer,recordSize);
  }
  dummyFile.close();
  SD.remove("dummy");
}

void setup()
{
  // ...other things I have been already doing...

  writeAndEraseDummyFileToEliminateFreeze();
}

```
> 1 votes

---
Tags: sd
---


title: Arduino 3rd party cores

text:
# Question
Title: Arduino 3rd party cores
I am trying to use Arduino platform.txt to run some extra pre-processing on my Arduino codes.

As far as I can understand the best way to do that is to use prebuild hooks as mentioned below https://github.com/arduino/arduino/wiki/arduino-ide-1.5-3rd-party-hardware-specification

I am using the hooks as follows

```
recipe.hooks.sketch.prebuild.1.pattern=echo {source_file} sketch pret;
recipe.hooks.sketch.prebuild.2.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

```

This is the output I get for the hooks

```
echo "{source_file}" sketch pret;
{source_file} sketch pret;
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -c -g -Os -w -std=gnu11 -ffunction-sections -fdata-sections -MMD -flto -fno-fat-lto-objects -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   {includes} "{source_file}" -o "{object_file}"
avr-gcc: error: {includes}: No such file or directory
avr-gcc: error: {source_file}: No such file or directory
avr-gcc: fatal error: no input files
compilation terminated.

```

The {source\_file} variable is used in a compilation reciep as follows

```
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}"

```

and the recipe runs as follows

```
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10804 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino" "-I/Users/vinayakjoshi/Library/Arduino15/packages/boltiot/hardware/avr/1.0.0/variants/boltduino" "-I/Users/vinayakjoshi/Documents/Arduino/libraries/boltiot-arduino-helper-update-dev/src" "-I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/src" "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp" -o "/var/folders/kp/9gnp402j7_nfb1qpqpdkxgcr0000gn/T/arduino_build_658970/sketch/CommandHandler.ino.cpp.o"

```

As you can see, in a standard recipe, the variable {source\_file} and other such definitions are correctly replaced. But in the hooks, this is not happening.

I want to know whether it is possible to get the value of the {source\_file} variable to be used with the hooks, so that I can do some extra pre-processing with it. And if it is, how can I do it.

P.S. IDK what tag has to be used. I couldn't find platform.txt or 3rd party cores. I used the Arduino-IDE tag, as this question definitely asks how the IDE works.

# Answer
It looks like those properties are only expanded in:

* `recipe.cpp.o.pattern`
* `recipe.S.o.pattern`
* `recipe.c.o.pattern`
* `recipe.preproc.includes`
* `recipe.preproc.macros`

They are not expanded in any of the hook recipes.

This actually makes sense for `{source_file}` with the current build system because the hooks are not run before and after the compilation of each file but rather before and after the entire sketch compilation, so even if that property was expanded it could only give you an arbitrary filename, perhaps the first file to be compiled in the prebuild hook and the last in the postbuild hook, but that leaves all the other filenames inaccessible so it really wouldn't do much good. See related issue report.

If you're actually trying to use `{source_file}` to get the preprocessed sketch file, that's accessible from any recipe as `{build.path}/sketch/{build.project_name}.cpp`.

As for `{includes}`, it seems like an unnecessary restriction for that property to only expand in specific recipes. If you can present a good case for this behavior being changed, it might be worth opening a feature request to see what the Arduino developers will think.
> 2 votes

---
Tags: arduino-ide
---


# Question
Title: How to receive data via Bluetooth on an Arduino 101?
The Arduino 101 came out recently, and it has built-in "Bluetooth Low Energy" capabilities. The tutorials and code examples that can be found for the 101 all seem to be about *transmitting* data, but I can't find anything about *receiving* data. I've tried to go through the source code of the CurieBle library to find some hints, but I feel a little overwhelmed/lost. Could someone point me to a code example which demonstrates how to do this?

Context: I was previously using an HC-05 module paired with an Arduino Nano in order to receive data. In this case it is quite easy to connect the HC-05 to the Nano's digital pins and receive data like so:

```
#define RxD 7 // This is the pin that the Bluetooth (BT_TX)
              // will transmit to the Arduino (RxD)
#define TxD 8 // This is the pin that the Bluetooth (BT_RX)
              // will receive from the Arduino (TxD)

SoftwareSerial blueToothSerial(RxD,TxD);

void setup() {
  blueToothSerial.begin(9600);
  Serial.begin(9600);
  // Allow Serial communication via USB cable to computer
  pinMode(RxD, INPUT);
  // Set up the Arduino to receive INPUT from the HC-05 on Digital Pin 7
  pinMode(TxD, OUTPUT);
  // Set up the Arduino to send OUTPUT to the HC-05 on Digital Pin 8
}

void loop() {
  char recvChar;
  while(1) {
    if(blueToothSerial.available()) {
      recvChar = blueToothSerial.read();
      Serial.print("Read character: ");
      Serial.println(recvChar);
      // Print the character received to the Serial Monitor
    }
  }
}

```

Is there equivalent, and equally simple, code available, which would do the same thing via the BLE built into the Arduino 101?

# Answer
> 2 votes
According to the Arduino Callback LED tutorial, you can use the dedicated library to access the BLE features of the board. All the Curie Libraries are covering the new Arduino/Genuino 101 embedded characteristics . In your case you must incluse the CurieBLE.h and configure the bluetooth service with Read/Write access.

Have a look to this page for a complete sample.

# Answer
> 0 votes
It seems the 101 only supports Bluetooth LE stack and not the full Bluetooth stack including RFCOMM, virtual com port. This means there is no proper supported way, but it seems people are working on workarounds.

https://forum.arduino.cc/index.php?topic=370123.0

# Answer
> 0 votes
It's possible to using HC-05 with Intel 101.

I worked on the pin 0, 1, as the Serial1 class.

---
Tags: bluetooth
---


title: DT-06 program using arduino uno

text:
# Question
Title: DT-06 program using arduino uno
I'm working to program DT-06 wireless wifi module.

And right now when i'm trying to program i get the following error message : espcomm\_send\_command: can't receive slip payload data

Module RX - Arduino RX

TX - TX

VCC - 5v

GND - GND

Right now i can upload black program to arduino and send serial AT commands to my module and alson getting response.

How can i program ?

Thx

Appendix:

# Answer
Just program it like you would program a normal ESP8266.

The documentation is here:

The datasheet provides the schematic of the module

So SW2 is the reset button and "SW1" is the "FLASH" button. To enter the bootloader mode in which the ESP8266 can be programmed, you first have to hold down the "FLASH" button then press "RESET" once.

For programming you would ideally get a 5V USB-UART adapter make the connections

* VCC to 5V (it has a regulator to generate the actually needed 3.3V)
* GND to GND
* EN to 5V (e.g. via a pullup)
* TXD to RX of UART adapter
* RXD to TX of UART adapter

After the ESP is in the bootloader mode as described above, you can just program it normally through the Arduino IDE. Follow the instructions at https://github.com/esp8266/Arduino to install the ESP8266-Arduino core in the board manager.

Refer to the similiar procedure:
> 0 votes

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


# Question
Title: How to expand an Arduino when using a TFT display shield?
I am really new to this Arduino stuff. I can't figure out one of my problems on my own.

I am using this 2.4 TFT display shield on an Arduino Uno. It works fine so far: I have coded a little sketch for it that displays a start button and after tapping that it shows random colors.

Now I would like to connect a circuit with jumper cables that are used as sensors. When I touch one of the jumper cables the light connected will turn on.

The problem I have now is that this specific circuit is using an other Arduino because my first Arduino is already 'full' because the TFT shield is taking up all pins.

How can I resolve my problem? Is it possible to Stack Arduinos? Is it possible to connect those Arduinos somehow? Thanks in advance!

# Answer
> 2 votes
As I can read your link, the shield is using D2-D8 and A0-A3, leaving some pins unused. So some Arduino pins are still free to use, just the shield is in the way to get connected there.

So there are some possible ways:

* brutally solder some wires to the shield unused pins from front side and use that wires to connect where you want (sensors, breadboard, universal PCB, ...)
* brutally solder some wires to arduino bottom on unused pins, then continue as mentioned
* create intermediate shield (there are many, which allow you connect to arduinou on bottom and stack antother shield on top, draw your wires from there (and maybe even put some circuities on the middle shield, if you want (something like this https://www.aliexpress.com/item/UNO-Prototype-DIY-shield-kit-for-Arduino-UNO-Universal-Extend-Board-UM-UNO/32555004112.html or any "arduino universal shield"

https://www.indiegogo.com/projects/ardushield-most-universal-shield-for-arduino-ever#/ works excelently across arduinos and other shields/breadboards ...

or anything along this lines ... http://shieldlist.org/sunhayato/universal

---

As for other part of question - It is possible to connect more arduinos, there are so much different ways, that it is hard to write here all - choose one, that would suit you best. (anyway you would need some access to some pins anyway )

# Answer
> 1 votes
Ok, your problem seems to be that you have run out of pins. Currently you are using an Arduino Uno. I would go out and buy an Arduino Mega.

Alternatively you could use the analog inputs as digital inputs.

**Arduino Uno**
Digital I/O Pins **14** (of which 6 provide PWM output)
Flash Memory 32 KB (ATmega328P) of which 0.5 KB used by bootloader

**Arduino Mega**
Digital I/O Pins **54** (of which 15 provide PWM output)
Flash Memory 256 KB of which 8 KB used by bootloader

---
Tags: arduino-uno, tft
---


title: Powering a water pump with nodemcu

text:
# Question
Title: Powering a water pump with nodemcu
I want to use a nodemcu to water my plants. I connected a pump with a 2N2222 transistor (I know i should add a diode and a pull down on the gate). The pump is DSL370 and when it is off i measure 4.4V on the Vin pin while using a 2A charger connected to the USB port. When the pump is active, the vin voltage drops to 4.1V and the LCD becomes hard to read. I measured the current the pump uses and it is 300mA. What is the reason for the voltage drop? I thought the charger should be able to handle it.

# Answer
> 1 votes
Your charger may be able to handle 300mA, but you're pulling that power through your Arduino and that isn't good. The pump should have a separate power supply, or at least be powered in parallel with the Arduino. Don't pull power for a motor from the Vin pin unless you just want to destroy the Arduino.

---
Tags: esp8266, power, nodemcu
---


# Question
Title: Write and read operation via synchronous serial port (Arduino Uno + ADNS2610)
# 1.Preliminaries

I have optical sensor ADNS2610 (see datasheet here) which I plug in to Arduino Uno R3 board.

It is possible either to read from either to write to the sensor. Here is what datasheet says (p. 12):

> **Write Operation**
>
> Write operations, where data is going from the microcontroller to the ADNS-2610, is always initiated by the microcontroller and consists of two bytes. The first byte contains the address (seven bits) and has a “1” as its MSB to indicate data direction. The second byte contains the data. The transfer is synchronized by **SCK**. The microcontroller changes **SDIO** on falling edges of **SCK**. The ADNS-2610 reads **SDIO** on rising edges of **SCK**.
>
> **Read Operation**
>
> A read operation, meaning data that is going from the ADNS-2610 to the microcontroller, is always initiated by the microcontroller and consists of two bytes. The first byte that contains the address is written by the microcontroller and has a “0” as its MSB to indicate data direction. The second byte contains the data and is driven by the ADNS-2610. The transfer synchronized by **SCK**. **SDIO** is changed on falling edges of **SCK** and read on every rising edge of **SCK**. The microcontroller must go to a High-Z state after the last address data bit. The ADNS-2610 will go to the High-Z state after the last data bit. Another thing to note during a read operation; **SCK** needs to be delayed after the last address data bit to ensure that the ADNS-2610 has at least 100 μs to prepare the requested data. This is shown in the timing diagrams below (See Figures to 23).

# 2 Arduino program

`WriteRegister` and `ReadRegister` functions are borrowed (though slightly modified) from OptiMouse project by zapmaker.

## 2.1 SetAddress function

This function writes the first byte: data direction (MSB) and address of a register (seven bits) which user intents to read from or to write to.

```
void ADNS2610::SetAddress( uint8_t address, DataDirection direction ) const
{
    pinMode( sdioPin, OUTPUT );

    /*Specify data direction:
     *MSB = 0   ===>   read operation
     *MSB = 1   ===>   write operation*/
    switch( direction )
    {
        case( toSensor ) :
            address |= 0b10000000 ;
            break;
        case( fromSensor ) :
            address &= ~0b10000000 ;
            break;
    }

    for( uint8_t mask = 0b10000000; mask; mask >>= 1 )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sdioPin, address & mask );
        digitalWrite( sckPin, HIGH );
    }

    /*Wait for 100 microseconds between address write operation
    *and read data operation (see p.15 of the datasheet)*/
    delayMicroseconds( 100 );
}

```

## 2.2 ReadRegister function

```
uint8_t ADNS2610::ReadRegister( uint8_t address ) const
{
    SetAddress( address, fromSensor );

    uint8_t data = 0;

    /*Read data from a register*/
    pinMode( sdioPin, INPUT );
    for( int i = 7; i >= 0; i++ )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sckPin, HIGH );

        data |= ( digitalRead( sdioPin ) << i );
    }

    /*Wait for 0.25 microseconds between read and either
     *read or write operations (see p.15 of the datasheet)*/
    delayMicroseconds( 1 );

    return data;
}

```

## 2.3 WriteRegister function

```
void ADNS2610::WriteRegister( uint8_t address, uint8_t data ) const
{
    SetAddress( address, toSensor );

    /*Write data to a register*/
    for( uint8_t mask = 0b10000000; mask; mask >>= 1 )
    {
        digitalWrite( sckPin, LOW );
        digitalWrite( sdioPin, data & mask );
        digitalWrite( sckPin, HIGH );
    }

    /*Wait for 100 microseconds between write and either
    *read or write operations (see p.15 of the datasheet)*/
    delayMicroseconds( 100 );
}

```

# 3.Discussion

## 3.1 Write operation

According to the datasheet

> ... The microcontroller changes **SDIO** on falling edges of **SCK**. The ADNS-2610 reads **SDIO** on rising edges of **SCK**.

And this is how I understand the code (see sec. 2.1):

```
digitalWrite( sckPin, LOW );//create a falling edge
digitalWrite( sdioPin, address & mask );//change SDIO on falling edge
digitalWrite( sckPin, HIGH );//create a rising edge (ADNS reads here)

```

Two questions here:

1. The first line in the above creates a falling edge only if the previous state of **SCK** was `HIGH`, doesn't it? So would it be better to have the following:

```
digitalWrite( sckPin, HIGH);
digitalWrite( sckPin, LOW );//create a falling edge
digitalWrite( sdioPin, address & mask );//change SDIO on falling edge
digitalWrite( sckPin, HIGH );//create a rising edge (ADNS reads here)

```
2. On figure 20 (see sec. 1, Write operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration? I know that ATMega328p has frequency 16 MHz, so it seems that time between two operations could be less than 250 ns. Am I right?

## 3.2 Read operation

According to the datasheet

> **SDIO** is changed on falling edges of **SCK** and read on every rising edge of **SCK**. The microcontroller must go to a High-Z state after the last address data bit. The ADNS-2610 will go to the High-Z state after the last data bit

And this is how I understand the code (see sec. 2.2):

```
digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
digitalWrite( sckPin, HIGH );//create a rising edge

data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

```

Three questions here:

1. The first line in the code above creates a falling edge only if the previous state of **SCK** was `HIGH`, doesn't it? Would it be better to have the following:

```
digitalWrite( sckPin, HIGH);
digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
digitalWrite( sckPin, HIGH );//create a rising edge

data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

```
2. On figure 23 (see sec. 1,Read operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration?
3. How do I set the microcontroller into High-Z state after the last address data bit?

# Answer
> 3 votes
**Question 1**

> The first line in the code above creates a falling edge only if the previous state of SCK was HIGH, doesn't it? Would it be better to have the following:
>
> ```
> digitalWrite( sckPin, HIGH);
> digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
> digitalWrite( sckPin, HIGH );//create a rising edge
>
> data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge
>
> ```

If you start from Cycle one.. **Yes**. Looking at the read cycle waveform, SCLK should be high before initiating a read or write request and after completing the communication.

**Question 2**

> On figure 23 (see sec. 1,Read operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration?

```
Here is the code for digital write function
void digitalWrite(uint8_t pin, uint8_t val)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *out;

    if (port == NOT_A_PIN)
        return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER)
        turnOffPWM(timer);

    out = portOutputRegister(port);

    uint8_t oldSREG = SREG;
    cli();

    if (val == LOW) {
        *out &= ~bit;
    }
    else {
        *out |= bit;
    }

    SREG = oldSREG;
}

```

**Please do not give any delay.** the above DigtalWrite function will take 1000's of ns of delay already. it is sufficient.

**Question 3:**

> How do I set the micro controller into High-Z state after the last address data bit?

I would do the following. Configure the pin which you want to **set to high impedance** as **input pin**. You can always change it to output mode before you want to use it again.

---
Tags: serial, c++
---


title: Connecting HC-06 and LM35

text:
# Question
Title: Connecting HC-06 and LM35
Hello I am trying to send temperature data via bluetooth using the HC-06 module. Since TXD and RXD only allow 3.3V I have divided the circuit into two like the below image. Is this method correct? or is there a better way to connect both two?

Any help is appreciated.

# Answer
> 1 votes
As mentioned by chrisl, you cannot use HC-06 as a `master` device. Its firmware restricts it to behave only as a slave. So even if you are able to process the analog data from `LM 35`, you won't be able to send it using `HC-06`. It would be better if you go for `HC-05` module and try the command `AT+ROLE: x` (x = 1 for master/0 for slave) to get the job done.

Coming to the 3v3 voltage constraint, I would suggest you to go for any Zener diode (in reverse biased mode) with `3.3V Reverse breakdown voltage`. You can check the circuit for this here and order it from this link. If this is not possible anyhow, then you can also go for `LM1117 3V3`, but I would personally suggest you to go for zener diode. Comment back if you need any help in future.

---
Tags: arduino-uno, hc-06, lm35
---


# Question
Title: Does delay() pause the counting of millis()?
If I add a delay for a few seconds, and then will the value given by millis () be equal just before and after delay?

Or to put it in other words, does the internal clock of Arduino stop during delay?

# Answer
No, I cannot check it (no Arduino at hand), but afaik the clock always keeps counting, so if you perform a delay of 1 second, and diff millis() just before and after, it will be (slightly over) 1,000 (ms).

Note however, that the use of delay is discouraged and it is better to check millis() to perform the next state/command instead of a delay which prevents doing other tasks meanwhile. But the (internal) timer always keeps running.

Only during some deep sleep mode it might stop, but than a delay will not work neither. And when interrupts are disbled (see remark of Chris Stratton below).
> 2 votes

# Answer
Delay uses millis. It just waits examining millis until a certain time has passed.

Millis is driven by an interrupt. The only thing that stops it working is another interrupt (you can only have one interrupt executing at once), which is why you can't use delay in an interrupt.
> 3 votes

---
Tags: millis, oscillator-clock
---


# Question
Title: Detect if Serial1 and Serial2 are defined, at compile time
I have my library that uses `Serial`, `Serial1` and `Serial2` to establish various logging scenarios. Library user would define the config at class constructor, using simple byte constants like 0, 1 and 2.

Problem is, `Serial1` and `Serial2` are not available in all board types. So when I compile my code (that compiles fine on Mega) on Uno, I get error `'Serial1' was not declared in this scope`.

So I figure I need to adjust my code with preprocessor directive like `#if defined`, in order to include some code only if Serial1 is defined. But it wouldn't work, because Serial1 is defined later, at compile-time. So what is the accepted way to do this?

# Answer
HardwareSerial.h in Arduino AVR boards core defines HAVE\_HWSERIALX

example

```
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

```
> 8 votes

# Answer
Consider the approach used here in the ArduinoBoardManager project at github. The file ArduinoBoardManager.h uses conditional compiling to determine the correct code to compile based on processor type. A similar approach can be used to asses if certain hardware peripherals such as serial ports were available based on processor type.

```
#if defined(__AVR_ATmega328P__) // uno, fi
  // Code compatible with an Arduino Uno
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  // Code compatible with an Arduino Mega
#endif

```
> 1 votes

---
Tags: serial, c-preprocessor
---


# Question
Title: Connecting Arduino ethernet shield (ip address - 0.0.0.0)
I need some help to connect my arduino uno R3 and ethernet shield. I don't have a mac address with my shield so I'm using this one: byte mac\[\] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

The Ethernet controller on the Ethernet shield is W5100 and I don't use SD card.

I have receiver module wich receives data from transmitter and I want to save it in database, but there is issue related to the connection. When I print the Ethernet.localIP i observed only 0.0.0.0.

This is the IP address of my local network - char server\[\] = "192.168.0.106"

You can find my code below:

```
  #include <Wire.h> // use Wire library for protocol i2c (A4 = SDA & A5 = SCL)
  #include <VirtualWire.h> // use Virtual library for decode signal from Rx module
  #include <SPI.h>
  #include <Ethernet.h>

  EthernetClient client;
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  char server[] = "192.168.0.106";

  int humidity=0;
  int temp=0;
  int pressure=0;
  char MsgReceived[21];

  void setup()
  {
     Serial.begin(115200);
     Ethernet.begin(mac);

     Serial.println(Ethernet.localIP());

    // Bits per sec
    vw_setup(2000);
    // set pin for connect receiver module
    vw_set_rx_pin(3);
    // Start the receiver PLL running
    vw_rx_start();

  }
  void loop()
  {
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  //Taking the data from the control base
  if (vw_get_message(buf, &buflen))
  {
    int i;
    // Message with a good checksum received, dump it.
    for (i = 0; i < buflen; i++)
    {
      // Fill Msg Char array with corresponding
      // chars from buffer.
      MsgReceived[i] = char(buf[i]);
      //Serial.print(MsgReceived[i]);
    }

    sscanf(MsgReceived, "%d,%d,%d",&humidity, &temp,&pressure); // Converts a string to an array
    lcd_display();
    memset( MsgReceived, 0, sizeof(MsgReceived));// This line is for reset the StringReceived

    Serial.print("Temperature = ");
    Serial.print(temp);
    Serial.println(" *C");
    Serial.print("Pressure = ");
    Serial.print(pressure);
    Serial.println(" Pa");
    Serial.print("humidity = ");
    Serial.print(humidity);
    Serial.println(" %");

if (client.connect(server, 80)) {
   Serial.println("CONNECTED");
   client.print( "GET /diplomna/Arduino/add_data.php?");
   client.print("temperature=");;
   client.print( temp);
   client.print("&&");
   client.print("humidity=");
// change this to a print rather than println
   client.print( humidity );
// add a leading space in this println
   client.println( " HTTP/1.1");
// add a second cr/lf here to denote end of header
   client.println();
   client.println( "Connection: close\r\n" );

   while(client.connected()) {
      while(client.available()) {
        char ch = client.read();
        Serial.write(ch);
      }
    }
   client.stop();
   Serial.println("DISCONNECTED");
   }
 else {
   // you didn't get a connection to the server:
   Serial.println("-> connection failed/n");
 }
   delay(10000);
  }
  }

```

You can find the serial monitor output below:

0.0.0.0 Temperature = 26 \*C Pressure = 997 Pa humidity = 57 % -\> connection failed/n

I also tried to execute the following example code (DhcpAddressPrinter) and the results are the same - 0.0.0.0

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

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

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

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for (;;)
      ;
  }
  // print your local IP address:
  printIPAddress();
}

void loop() {

  switch (Ethernet.maintain())
  {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");

      //print your local IP address:
      printIPAddress();
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");

      //print your local IP address:
      printIPAddress();
      break;

    default:
      //nothing happened
      break;

  }
}

void printIPAddress()
{
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }

  Serial.println();
}

```

Serial monitor output: Failed to configure Ethernet using DHCP

I also tried to set the ip address of the shield to be 192.168.137.1 and made the following update: Ethernet.begin(mac); ===\> Ethernet.begin(mac,ip); The results are the same.

Could you please help me to debug this issue. Thanks in advance!

Regards, SK

# Answer
> 2 votes
> from comments: " I use straight connection cable to connect the ethernet shield to my laptop and I use wifi network. "

This is the problem. Connect to router.

The direct Ethernet connection may require the use of a cross-over cable and the PC probably doesn't have a DHCP server for the Ethernet interface, so you should set an IP address for the network interface and in the Arduino sketch.

see this SO question

# Answer
> 1 votes
The first thing you should do is disconnect or disable all devices from the Arduino except the network card then run your tests again, if they work (which I doubt) then the problem is a hardware resource clash, for which you will need to read the datasheets.

I suspect the problem you have is more fundamental, do you have a DHCP server on your network?

The first example doesn't specifically mention DHCP, but the second example makes the same call top `Ethernet.begin()` and seems to expect the call to have configured the NIC via DHCP.

So my advice would be to look at the API for the NIC and see what you need to do to statically configure you IPv4 settings. Also you might need to bone up on IPv4 addresses and net masks, because the addresses you mentioned won't be able to communicate unless you have some special routing gear (it could be I read the question wrong).

Hope that helps.

---
Tags: arduino-uno, ethernet-shield
---


# Question
Title: How to display a number using SevSeg library on 4 digit 7 segment LED display
I am getting error with this. It is displaying those segments which are not to be displayed, i.e., `3.141` is dark and other segments are red.

```
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

```

# Answer
> 2 votes
There are two main types of seven segment display:

* Common Anode
* Common Cathode

The *common* refers to the fact that one end of the LEDs within a digit are linked, and need to be connected to either Vcc or GND, depending on the type of the display (see below). The other end of each led (one per segment) is used to switch them on, and it is these that go to the Arduino pins, or LED controller.

### Common Anode

The common end is connected to the **Vcc** line. If you wish to light a segment, then the input pin for that segment needs to be pulled `LOW`.

Source: Four multiplexed 7-segment COMMON ANODE LED

### Common Cathode

The common end is connected to the **GND** line. If you wish to light a segment, then the input pin for that segment needs to be pulled `HIGH`.

---

It sounds as if you have the logic inverted, so the wrong segments are lit, when they should be dark, and vice versa.

Either that, or you need to invert the logic in your code, and for example if you are currently pulling a pin `LOW` to light up a segment, then you need to change your code to pull the pin `HIGH`.

---

**Image sources:**

Electronics-Tutorials

Common Anode/Cathode 7-segment displays

# Answer
> 0 votes
You could try the following:

```
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

```

---
Tags: arduino-uno
---


# Question
Title: Arduino Nano off 9V : is there any change to output?
I'm building a test circuit on an Arduino Nano that consists of a simple 220 Ohm resistor and an LED on pin D2 which is routed back to GND (ground).

It's as simple as this:

It's running a very simple program to blink the LED on and off. It all works while connected to the USB port. I know the USB port provides 5V.

Now I want to run it my Nano and circuit from a 9V battery. The datasheet says that you can run the Nano on 6V -12V by connecting it to pin 30 (VIN). Of course, I know I'll have to add a line from GND back to the (common) battery ground also.

When I do that, the voltage on the OUTPUT pin (D2) will never be higher than 5V though, right?
I should not expect any change in output voltage even though I'm changing voltage that is powering the Nano, correct?

# Answer
> 2 votes
It looks like VIN connects to a LM2940, 5 volt regulator, so the voltage on the OUTPUT pin (D2) will never be higher than 5V.

---
Tags: arduino-nano, pins, voltage
---


# Question
Title: Multiple VL6180X distance sensors interactive problem
I am trying to use a VL6180X distance sensor and an Arduino Uno board for individual sensor doing individual distance sensing. This sensor follows the I2C protocol. Since for the same type of sensor, the I2C protocol says that they would all have the same address, I am thinking about using the chip enable pin (`GPIO00`) on the sensor chip to toggle sensor when doing the distance measuring.

I am able to update the address of the sensor group now. But I think to obtain individual results from different sensors on the Arduino serial monitor, right now I can only do one time setup sensor thing (like I couldn't update and toggle around different sensors). Once I started to do that, the results from the serial monitor were wrong. Any advice how I can continue to toggle around the sensor and make them work using the GPIO00 pin?

The code I'm using is:

```
#include <Wire.h>
#include <VL6180X.h>
#define Address1 0x20
#define Address2 0x22
#define Address3 0x24

VL6180X sensor;

int pin2 = 2;
int pin3 = 3;
int pin4 = 4;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  pinMode(pin2,OUTPUT);
  pinMode(pin3,OUTPUT);
  pinMode(pin4,OUTPUT);
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,HIGH);
  sensor.init();
  sensor.configureDefault();
  sensor.writeReg(VL6180X::SYSRANGE__MAX_CONVERGENCE_TIME, 30);
  sensor.writeReg16Bit(VL6180X::SYSALS__INTEGRATION_PERIOD, 50);
  sensor.writeReg16Bit(VL6180X::INTERLEAVED_MODE__ENABLE,0);
  sensor.setTimeout(500);
  sensor.stopContinuous();
  delay(300);
  sensor.startInterleavedContinuous(100);
}

void loop() {
  hello2();
  delay(1000);
}

void hello1(){
  sensor.setAddress(0x29);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address1);
  sensor.writeReg(0x212,Address1);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,LOW);
  digitalWrite(pin4,LOW);
  Serial.print("Ambient 1: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 1: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
  digitalWrite(pin2,HIGH);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,HIGH);
}

void hello2(){
  sensor.setAddress(0x52);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address2);
  sensor.writeReg(0x212,Address2);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,LOW);
  digitalWrite(pin3,HIGH);
  digitalWrite(pin4,LOW);
  Serial.print("Ambient 2: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 2: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
}

void hello3(){
  sensor.setAddress(0x52);
  Serial.println(sensor.readReg(0x212),HEX);
  sensor.setAddress(Address3);
  sensor.writeReg(0x212,Address3);
  Serial.println(sensor.readReg(0x212),HEX);
  Serial.println();
  digitalWrite(pin2,LOW);
  digitalWrite(pin3,LOW);
  digitalWrite(pin4,HIGH);
  Serial.print("Ambient 3: ");
  Serial.print(sensor.readAmbientContinuous());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.print("\tRange 3: ");
  Serial.print(sensor.readRangeContinuousMillimeters());
  if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
  Serial.println();
  sensor.writeReg(0x212,0x52);
}

```

Any help would be appreciated!

# Answer
You can use an I2C multiplexer (TCA9548A). One I2C input can be output to one of the eight I2C outputs.

It has 8 configurable addresses, so you can connect 64 I2C devices with the same address by using 8 multiplexer chips.
> 1 votes

# Answer
You are using only one VL6180 object and then changing its address repeatedly. In your setup(), since all the sensors are enabled and have the same address, you're sending init commands to all of them; I'm not sure what will happen (multiple ACK/NACKs?), but it's probably not a good thing. Your hello() functions actually changes the address of all the sensors (twice?), if the commands even work, and then enables only one to read from. A host of undefined problems is expected.

To fix this, you have to do all the config and address changes in setup():

* Before setup(), create 3 VL6180 objects: `sensor1`, `sensor2`, `sensor3`
* In setup(), enable ONLY ONE sensor, and call all the sensor initialization commands on one of the objects you created (sensor1, maybe), as usual. Then call `setAddress()` on that sensor object to change its address to a unique one. This object is now tied to the physical sensor which has been enabled; all future operations related to that sensor, must be done on this object.
* Then, disable this first sensor, and enable another and repeat the same steps as before on another object (sensor2), making sure to make each sensor's address unique. This way, you configure only one sensor at a time.
* After configuring all three, you can now use their respective objects to get readings in loop().
> 0 votes

# Answer
I believe, if I have read this Multiple VL6180x in a design right, then you can change the I2C addresses of the sensors. You need to hold all the sensors in reset then send it the change ID message. I'm not sure if it is permanent or you have to do it each power up.

Does that help?
> 0 votes

---
Tags: i2c, pins
---


# Question
Title: How to determine hardware/software compatibility?
Currently, I'm using Greiman's SdFat Library with Adafruit's Data logging Shield.

I'm thinking about switching to the Adafruit micro SD Card Breakout. I imagine that it will work as both products are made by Adafruit, and the board schematics *look* similar. However, I don't know what to look at to be sure they are the same.

Is it enough that they both use the HC4050M chip, or is there something else that I need to be aware of?

Short of buying one and testing it. What do I need to look at to verify that these two boards will work with the library?

# Answer
The HC4050M is just used for logic level translation (SD cards are 3.3V devices). It is "enough" that you are talking to an SD card using an SD card library. The SD card is really all the hardware there is - everything else is just interfacing fluff - completely transparent to the software.
> 1 votes

---
Tags: shields, hardware
---


# Question
Title: Controlling two-pole contactor using Arduino
I am working with Packard C230C contactor to develop own EVSE. For a simple start i just want to toggle contactor using Arduino. OpenEVSE is already doing it. Just want to know how do they do it and some circuit explanation.

Reference : OpenEVSE Setup

# Answer
Get solid state relays that have a operating voltage of 5V and can switch Mains AC
> -1 votes

---
Tags: power, relay, mosfet
---


title: TLC5917 Electrical Characteristics

text:
# Question
Title: TLC5917 Electrical Characteristics
I am using an Arduino Uno to communicate over SPI to 3 cascaded TLC5917 chips corresponding to the Red, Green and Blue rows of an RGB LED Matrix. I am using direct output IO from the Arduino to power the columns.

Now I intend to use multiplexing to avoid drawing too much current at once, although it could still potentially be quite alot (`3 x 8 x 20ma`).

I have managed to display a full white screen using multiplexing with quite a high brightness, however this should not be possible to my knowledge.

Looking at the data sheet I found that at both at 3V and 5V the Output Voltage is rated at `Vdd - 0.4` for Voh (Voltage High Level Output). This means that at 5V the minimum output voltage should be 4.6V and at 3V it should be 2.6V.

Disabling multiplexing and simply writing to the registers and columns, and then measuring the voltage shows `2.5V, 2.8V and 1.8V` for different colors. This contradicts the data sheet.

The circuit contains no resistors except from GND to REXT using a 680Ohm Resistor. The Arduino is powered over USB.

(http://www.ti.com/lit/ds/symlink/tlc5917.pdf)

Why is the Voltage so low, should it not be higher given the data sheet? Am i reading the correct attribute? How can my Arduino manage to drive so many LEDs (albeit through LED Drivers)?

What can I do to make this circuit more electronically safe and stable?

# Answer
The concepts of HIGH and LOW, and thus the voltages associated with those concepts, apply only to logic signals.

LED drivers are *not* logic signals - they are *constant current sinks*. The voltages you are measuring are the forward voltages of the LEDs.
> 3 votes

---
Tags: arduino-uno, led, rgb-led
---


# Question
Title: Is there any version of arduino that can do something like serial interruption?
I am using an Arduino to control servo MX18A by serial, and trying to use computer to communicate with the Arduino by another serial to send commands to Arduino and change the servo control mode. Once the computer send a message to Aruduino, I hope it could response in time because may be there is something emergency like the servo being out of control ,under which circumstance I have to change the control strategy in time.

However, it seems like Arduinos like UNO, MEGA does not have serial interruption, so once the message from computer comes, it could not response in time.

I know that judging `serial.available()` in every loop is one solution, but in my different servo control strategy there are many time delays, `for` loops and `while` loops, which means that I have to put `serial.available()` in every time delay or `for` loops, making the code hard to write and maintain.

# Answer
It is not a case of "An Arduino" that can do serial interupts. *All* Arduino boards have serial interrupts, but they are already used to receive the data and store it in a buffer for you to consume when you have the time.

The Arduino API does not define any serial interrupt handling routines. That kind of thing is designed to be handled internally by the API code, not by the user. That's the whole point of the Arduino API - to abstract away such technicalities from the user.

If you want to use the serial interrupt yourself you will have to write your own serial handling code.

Or write your code in such a way that serial interrupts aren't needed.
> 2 votes

# Answer
Why not use a timer to check if any data is in the serial buffer every say 2 seconds. The DUE has interrupts available on ALL pins so that could be a viable alternative solution. You shouldn't use blocking code anyway, e.g. whiles and delays.
> -1 votes

---
Tags: serial, interrupt
---


# Question
Title: Specified folder/zip file does not contain a valid library
I am trying to use this library. But when I try to import the .zip file (of the directory) downloaded from GitHub, Arduino IDE says "Specified folder/zip file does not contain a valid library"

# Answer
That's because it contains *two* libraries, and the IDE doesn't know how to handle that.

Because of this repository structure, you will need to do a manual installation.

Extract the zip file manually and copy the `libraries` folder into your Arduino sketchbook folder. You can find the location of your sketchbook folder in the Arduino IDE at **File \> Preferences \> Sketchbook location**.
> 3 votes

---
Tags: library
---


# Question
Title: How to improve response time of this sound operated LED?
I have written the following code for lighting an LED on a clap ( using sound sensor) that I have connected via a resistance of 330 OHM on pin number 4.

However, when I clap once, close to the sound sensor, it does not lights the LED. But it only lights the LED if I provide prolong exposure to sound ( more than 6 seconds) on the sound sensor.

How can I improve this , so that even if I clap once for a seconds duration, the LED glows?

```
int soundSensor=10;
int LED=4;

void setup()
{
 Serial.begin(9600);
 pinMode(soundSensor,INPUT);
 pinMode(LED,OUTPUT);
}

void loop()
{
  int SensorData=digitalRead(soundSensor);
  if(SensorData==1)
  {

     digitalWrite(LED,HIGH);
  delay(3000);

     Serial.println("LOUD, LOUD");
     delay(1000);
  }
    else
  {

     digitalWrite(LED,LOW);
     Serial.println("SLOW, SLOW");
     delay(1000);
  }
 }

```

# Answer
> 6 votes
I think the problem is in the times you check the sensor. If you clap exactly when you check it will glow even if clapped for 1 ms, but if it checks in between two claps it doesn't detect it.

So check more often (reduce the delays) and check for so many sound detections within one second.

Or, as JRE below proposes, use an interrupt, this is even better but needs a bit more programming skills. Still interrupts are used a lot in microcontroller programming so it is worthwhile to check into this.

# Answer
> 5 votes
Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input (like clapping).

Using the attachInterrupt() function is the way to go here!

https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

# Answer
> 3 votes
Depending on sensor , simple modification with series diode to detect impulse and hold decaying slow with say 0.01uF to and 10 MOhm to 0V will detect 1st time and stretch pulse ~ 0.01u\*10M =0.1s

---
Tags: led, sound
---


title: Is my HC-SR04 sensor broken?

text:
# Question
Title: Is my HC-SR04 sensor broken?
I am extremely new to Arduino and electrical engineering, and the project I am attempting involves a ultrasonic sensor. I am using the HC-SR04 with the Elegoo Mega2560 Arduino board. A few days ago I was able to print out the distance correctly with an Arduino library, but after adding a h-bridge, 2 motors, and 2 9-volt batteries, the sensor didn't seem to work properly. I went back to a simple circuit with only the HC-SR04, and the distance readouts were all over the place. No matter what, the distance stayed between 90 and 120, mainly staying in the 110s. These numbers seemed to have no correlation with the actual distance. I even tried to calculate the distance myself in case there was something wrong with the library.

I have the VCC pin on the HC-SR04 connected to the 5v on the Arduino, the GND pin connected to the GND pin on the Arduino, the Trigger pin connected to pin 50 on the Arduino, and the Echo pin on the Arduino connected to pin 52 on the Arduino. The Arduino is connected to my computer through USB.

Here is my sketch for printing out the distance without a library:

```
const int triggerPIN = 50;  //these are digital pins on the Arduino board
const int echoPIN = 52;     //I'm sure these pins aren't broken because I never used them before now

long duration;
int distance;

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

    pinMode (triggerPIN, OUTPUT);
    pinMode (echoPIN, INPUT);

    delay(1000);
}

int getDistance () {
    digitalWrite (triggerPIN, LOW);
    delayMicroseconds (2);

    digitalWrite (triggerPIN, HIGH);
    delayMicroseconds (10);
    digitalWrite (triggerPIN, LOW);

    duration = pulseIn (echoPIN, HIGH);
    distance = duration * 0.034 / 2;

    Serial.println (distance);
}

void loop() {
    getDistance ();  //I tried putting the code directly in the loop function with the same result
}

```

I am afraid that I broke either a part of the Arduino board or the sensor when I was fiddling around with the two batteries. Is it possible to break a HCSR04 sensor by connecting two much voltage to the VCC pin on the sensor? If so, how should I prevent this in the future? I know that the working voltage for a HCSR04 is 5V, does this mean it needs at least 5V or no more than 5V? I wanted to know for sure that it was broken and not an error on my part before I bought a new one. Thanks in advance!

# Answer
The code that you have provided for the distance calculation is fine according to me. There is a high chance that you might have damaged your HC-SR04, Ultrasonic sensor.

As you have asked about how to prevent this from happening in the future, I would suggest that you should use a voltage regulator in the circuit, LM7805, it restricts the output voltage to 5V - just matching your ultrasonic sensor's operating voltage as it works perfectly at 5 Volts.
> 0 votes

# Answer
I guess the main problem is a serial printing. It always bother the system mainly the analog reading. It's quiet good for check some sub result while you programing (what the return value from a method etc) but not good to test your project result. In this case the distance measurement. Try a different way, put some led into the circuit and if the distance over 10cm switch on first, if over 20 cm switch on the second and so on. Or write the result on an lcd panel, or 8x8 led.
> 0 votes

# Answer
A major functional difference between the code in your question and the usual ping sensor example is that your code repetitively measures as fast as it or the output stream will allow.

In contrast, the normal example has a `delay(100)` after each measurement cycle. This allows 1/10th of a second time for any longer room echoes to die out, and thus avoid confusing new measurements.

While that might not be your immediate or only problem, it is generally a good idea not to try to take sonar measurements so closely spaced in time that they could overlap.

Should your sketch also need to do other things, instead of a blocking `delay()` you can check the elapsed time and only take a new sonar measurement once a certain amount of time has passed; in the meantime your program can continue with any other critical operations.
> 0 votes

---
Tags: programming, sensors, power, pins, hc-sr04
---


# Question
Title: Visual Studio for Arduino - Deep Search Issue
Finally got some time to play with my Arduino. I downloaded the Arduino editor and wrote a quick sketch which worked fine.

I then downloaded the Visual Studio extension from VisuaMicro. I configured it to point towards my Arduino directory, which in my case is : C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE\_1.8.10.0\_x86\__mdqgnx93n4wtt

I created a new Arduino project and copied the same sketch it. When I try to build it I get errors as below:

```
Compiling debug version of 'Sketch1' for 'Arduino/Genuino Uno'
Build Folder:
file:///C:/Users/bbbsb/AppData/Local/Temp/VMBuilds/Sketch1/uno/Debug
Additional Defines: VM_DEBUG;VM_DEBUG_ENABLE
1;VM_DEBUG_BANDWIDTH_THROTTLE_MS 50;VM_DEBUGGER_TYPE_HARDWARESERIAL
0;VM_DEBUGGER_TYPE_SOFTWARESERIAL 1;VM_DEBUGGER_TYPE_FASTSERIAL
2;VM_DEBUGGER_TYPE_USB 3;VM_DEBUGGER_TYPE_TEENSY 4;VM_DEBUGGER_TYPE_UART
5;VM_DEBUGGER_TYPE_USART 6;VM_DEBUGGER_TYPE_USBSERIAL
7;VM_DEBUGGER_TYPE_TTYUART 8;VM_DEBUGGER_TYPE_NET_CONSOLE
9;VM_DEBUGGER_TYPE_Uart 10;VM_DEBUGGER_TYPE_COSA
11;VM_DEBUGGER_TYPE_CDCSerialClass 12;VM_DEBUGGER_TYPE_HARDWARESERIAL1
13;VM_DEBUGGER_TYPE_HARDWARESERIAL2 14;VM_DEBUGGER_TYPE_HARDWARESERIAL3
15;VM_DEBUGGER_TYPE_NET_UDP 16;VM_DEBUGGER_TYPE_USBAPI
17;VM_DEBUGGER_TYPE_SERIALUSB 18;VM_DEBUGGER_TYPE
VM_DEBUGGER_TYPE_HARDWARESERIAL;VM_DEBUG_BREAKPAUSE;
Architecture Tools:
file:///C:/Program%20Files/WindowsApps/
ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/
Api: 1.1706.25-9.061
Sketch Book: file:///C:/Users/bbbsb/Documents/Arduino
Sketch Include Paths
Core Include Paths
Include Path     file:///C:/Program%20Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/cores/arduino
Include Path     file:///C:/Program%20Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/variants/standard
Searching for libraries ...
"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11  -
DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805  -
DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
Access is denied
Preprocess: "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11 -
DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805 -
DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
Object reference not set to an instance of an object

An error was encountered during the 'Deep Search' library discovery process.

```

Debug build failed for project 'Sketch1'

I've obviously not setup something correctly but cnnot work out what? Any ideas?

# Answer
If I remember well, you have to "import" the libraries for your project from within Visual Micro.
> 1 votes

# Answer
I had the same problem and just tried it as per1234 suggested: installed the full windows version (not the windows app version), configured the VS extension accordingly and now it builds (same code).
> 1 votes

---
Tags: arduino-uno, visualstudio
---


# Question
Title: Analog inputs showing value even there is nothing connected to it
After watching something weird on the serial monitor I wrote a simple code to monitor the analog pin input values. There was nothing connected to the analog pins still they where showing decimal representation of some analog values.

the code is

```
float ana [] = {A0,A1,A2,A3,A4,A5};
float dec [6];

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

void loop()
{
  for(int i = 0; i<6 ; i++)
  {
    dec[i] = analogRead(ana[i]);
    Serial.println(dec[i]);
    delay(1000);
  }
}

```

How is this even possible?

this is the output result

# Answer
Your input is floating if nothing is connected. It is reading whatever random noise it happens to pick up. That's what it is supposed to do. For it to read 0 it would need to be connected to ground. Google "floating input" for more info.
> 2 votes

---
Tags: arduino-uno, analogread
---


# Question
Title: How to measure room light without LEDs interfering?
I'm trying to measure the light in a room with a simple circuit: a phototransistor connected in series with a resistor. An LED strip changes brightness according to the brightness level in the room.

The problem here is that the phototransistor also picks up the light from the LEDs. It is not an option using an IR phototransistor because I also need to measure the light from the room's light bulbs. Also, because of the device's casing, I need the sensor to be surrounded by the LED strip. Finally, I tried turning off the LEDs before measuring does not seem to work, as either the Arduino or the sensor is too slow, to turn off, perform the measurement, and turning back on the LEDs, without a human eye perceiving it.

Is there any standard or well known solution to this problem?

I will appreciate any help you can provide.

**Additional Information**

The LED strip is the WS2812B. The phototransistor I'm using operates between 420 nm and 1130 nm, with peak sensitivity around 850 nm.

Furthermore, to specify the functionality I'm trying to achieve: whenever the room is dark, I want the LEDs to be not too bright. If the room is too bright, I want the LEDs to shine brighter as well.

# Answer
> 1 votes
Normally you should be able to switch LEDs off, make a measurement and switch LEDs back on without a noticeable delay. Brightness variation is noticeable below 100Hz, which translates to 10ms period.

What you need is a photodiode with fast response time (under 0,1ms or so, though there are devices responding in nanosecond range). Phototransistors and LDRs are considerably slower.

LEDs response time is in single-digit microseconds even for white LEDs, and RGB LEDs are even faster. Below is a response of typical LEDs to a 200ns pulse:

Regular `AnalogRead` takes about 0.1ms (and, again there are faster alternatives), so you can easily achieve kHz measurement frequencies where brightness variation is completely unnoticeable.

# Answer
> 0 votes
What you can try is to use a color sensor. Since you know the color of the LEDs you control, if the color sensor picks up a different color, you know it is because of other light.

Since this is not full proof (ambient color might be exactly as the LED color), you can check color differences (also with a non color sensor). If it differes without you changing the LED, you know there is ambient light (either increasing/decreasing).

It also will help if you put the sensor in a tube which is in a different direction than the LEDs to prevent as much as possible picking up the light from the sensors if possible.

(if you don't have color sensors you can use a normal sensor with some colored plastic above/around it).

---
Tags: sensors, led-strip
---