# Question
Title: Storing byte array from serial and converting to a floating point number
I have tried getting my Arduino to communicate with another device, to no avail. The command A, when sent via serial to the device, triggers it to respond with 8 binary bytes with the first 4 representing a floating point number, and the final 4 representing a floating point number. The command only has to be sent once a second, and the aim is to store the 8 incoming bytes in an array, and convert them into their respective floats.

```
unsigned long previousMillis = 0;
const long interval = 1000;
char incomingByteA[8];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial1.begin(9600);
  while(!Serial1);
}

void loop() {
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval){
    //1 second timer
    previousMillis = currentMillis;
    Serial1.write('O');
    //Send command 'A' to device *noting Serial1 not Serial
    for(int n = 0; Serial1.available() < 8; n++) {
    incomingByteA[n] = Serial1.read();
    //Add each consecutive byte to an array until all 8 bytes have been added
  }
  float x;
  float y;
  ((byte*)&x)[3] = incomingByteA[0];
  //Convert first four bytes into a float
  ((byte*)&x)[2] = incomingByteA[1];
  ((byte*)&x)[1] = incomingByteA[2];
  ((byte*)&x)[0] = incomingByteA[3];
  ((byte*)&y)[3] = incomingByteA[4];
  //Convert final four bytes into a float
  ((byte*)&y)[2] = incomingByteA[5];
  ((byte*)&y)[1] = incomingByteA[6];
  ((byte*)&y)[0] = incomingByteA[7];
  Serial.println(x, 4);
}
}

```

However, when I do `Serial.println(x);`, it returns "nan". And if I try to do `Serial.println(incomingByteA[2]);`, it returns "?".

The following is the floating point format as per the device protocol:

31: sign of mantissa, 1=negative. 30-23: exponent, biased by 128. 22-0: mantissa, 24 bits, MSB hidden and always=1.

The mantissa is normalized, 24 bits with the MSB hidden. The MSB is always assumed to be 1, therefore only 23 bits are needed to store the mantissa. The exponent is biased by 128; i.e. a 128 value represents an exponent of zero. A 129 value is an exponent of 1. Example: if the exponent has a 131 value (+3), the number is 2^3 * (mantissa). The mantissa is always less than one, and greater than or equal to 1/2. The number zero is stored as four zero bytes.

I am confident that it is not a fault with the hardware and for what it's worth, I am using a Leonardo. I would like to get the code down pat before I stress about hardware issues. What is this code not doing properly, if at all?

Thanks in advance.

# Answer
Two things I see wrong:

> Serial1.write('O'); //Send command 'A' to device \*noting Serial1 not Serial

No, you send `O` not `A`... ???

> for(int n = 0; Serial1.available() \< 8; n++)

While there are less than 8 bytes available in the buffer read one.

Erm... The buffer starts off empty - empty is less than 8. It remains empty (always less than 8) until a byte *finally* arrives. Then it's still less than 8. I can't really see this ever working, and your array will overflow instantly and clobber the entirety of the rest of your RAM. I guess it finally finished when the serial object itself gets clobbered and `available()` returns some garbage number. In the meantime your array is just full of nothingness.

You need to completely rewrite that whole section. The simplest way is to wait *until* there are 8 bytes in the buffer (which will take some time - serial is *slooooow*):

```
while (Serial1.available() < 8);

```

You now have 8 bytes available to read, so you can go ahead and read them.

A better way is to look to see if there is *at least* one byte available, then read it into the right place in your array - and keep count of how many bytes you have read:

```
int n = 0;
while (n < 8) {
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

```

Of course, it's better to add some form of timeout in there too - so if nothing arrives soon enough your program doesn't lock up - or if you miss a byte it doesn't get completely out of sync. Also purging your read buffer before sending the command can help to prevent sync issues:

```
// Purge any old data
while (Serial1.available()) {
    Serial1.read();
}

Serial1.write('A');

int n = 0;
uint32_t start = millis();
while (n < 8) {
    // 1 second timeout
    if (millis() - start > 1000) {
        break;
    }
    if (Serial1.available()) {
        incomingByteA[n++] = Serial1.read();
    }
}

if (n == 8) {
    // We got the data - do something with it
} else {
    // It timed out
}

```

Now when it comes to converting to a pair of floats there's better ways than your byte-wise manipulation. For instance, you could use a union:

```
union FloatPair {
    struct {
        float a;
        float b;
    };
    char bytes[8];
} __attribute__((packed));

FloatPair data;

```

Now you can use:

```
data.bytes[n]

```

to access the memory directly, and

```
data.a;
data.b;

```

to access the float values.

You can also do something similar with casting:

```
struct FloatPair {
    float a;
    float b;
};

FloatPair data;

char *bytes = (char *)&data;

```

`bytes` is now a byte-wise view of the memory used by a pair of floats.

You can even work the other way around:

```
char data[8] __attribute__((aligned(4)));

```

The aligned attribute will force the address of the array to be on a 4-byte boundary. Not important for a little 8-bitter, but vital if you ever port to a 32-bit MCU since a float always has to be on a 4-byte boundary, so a good habit to get into.

Now you can map floats into that memory space:

```
float *a = (float *)(&data[0]);
float *b = (float *)(&data[4]);

```

and access the floats as `*a` and `*b`. The `*` dereferences the pointers back into real numbers.

One thing to note: these methods all depend on the endianness of your data matching the endianness of your MCU - if they differ then you will have no choice but to do it all with manual byte-wise mapping.
> 2 votes

# Answer
Thank you Majenko for your fast help!

I believe that the code is now alright. I will look at using the union method this weekend. For now, however, this is the final code.

```
 byte incomingByteA[8];

 void setup() {
 // put your setup code here, to run once:

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

 }

 void loop() {

 // Purge any old data
 while (Serial1.available()) {
 Serial1.read();
 }

 Serial1.write('A');

 int n = 0;
 uint32_t start = millis();
 while (n < 8) {
 // 1 second timeout
 if (millis() - start > 1000) {
    break;
 }
 if (Serial1.available()) {
    incomingByteA[n++] = Serial1.read();
 }
 }
 float x;
 float y;
 if (n == 8) {
 ((byte*)&x)[3] = incomingByteA[0];                             //Convert first four bytes into a float
 ((byte*)&x)[2] = incomingByteA[1];
 ((byte*)&x)[1] = incomingByteA[2];
 ((byte*)&x)[0] = incomingByteA[3];

 ((byte*)&y)[3] = incomingByteA[4];                             //Convert final four bytes into a float
 ((byte*)&y)[2] = incomingByteA[5];
 ((byte*)&y)[1] = incomingByteA[6];
 ((byte*)&y)[0] = incomingByteA[7];

 Serial.println(x);
 } else {
 // Some timeout response
 }

 }

```

What I find odd, is that Serial.println(x); returns "8.00" followed by several, random lines of "0.00". Yet Serial.println(x); returns just "0.00". I am simply putting this down to the device I am trying to communicate with though.

Harry
> 0 votes

---
Tags: serial, arduino-leonardo, array, float
---


# Question
Title: Leonardo clone being recognized by Windows as a broken Linino One - wtf?
I'm running a Velleman VMA103, which is advertised as a clone of the Leonardo. Both use the 32u4 chip, and the pinout is exactly the same. However, when I plug it in, the drivers do something weird.

For about 5 seconds after pressing reset, the Arduino IDE will recognize the Leonardo on COM9, and the Windows device manager will show "Arduino Leonardo bootloader" then, the COM9 device will disappear and a device will be shown in the Other Devices tab as a LININO ONE, with no drivers installed. How is this possible?

I've reinstalled the IDE, no help there.

# Answer
> 0 votes
USB associates a driver, and thus what it calls a device, with the VID and PID that the device announces. Arduino PIDs are in a horrible mess, and there are many different devices that use the same PID. On top of that you have other makers also using the same VID/PID pairs and providing their own re-named Arduino driver files for their devices.

And then of course you have the problem that it is down to the firmware ("sketch") installed on the Leonardo that determines what VID and PID is shown to the computer.

So you have a set of possible scenarios - the main two being:

1. You have a driver installed that identifies the VID/PID pair of the Leonardo as something else
2. You have firmware installed in the Leonardo that gives the wrong VID/PID pair for your drivers

Check 2 first by installing the Blink example into the Leonardo (you can still upload firmware since it goes to bootloader mode at first as you have seen). If it changes the shown driver then you had some broken firmware installed. If it doesn't then you may be running a patched installation of the Arduino AVR core that gives a different default VID/PID pair, or you may just have the wrong board selected in the menu.

If you still have trouble then uninstall whatever driver is associated with the detected device and reinstall the official Arduino drivers that come with the IDE.

You can also delete the IDE and its associated downloaded packages and reinstall the latest version to ensure that you don't have strange patches and settings in there corrupting things.

---
Tags: arduino-leonardo, bootloader
---


# Question
Title: Reading 4 to 20ma pressure sensor using uno
I have a OsiSense™ XMLP pressure sensor that I want to read from my Arduino uno. This is the circuit I am looking at building for measure 4 to 20 milliamp.

I've read online to find out how to build the circuit. Can you tell me if it is correct?

Also I dont understand why it works and I'm hoping you can correct my thinking. Following ohms law we want to leave 5v when 20 milliamps goes through the circuit. We know the voltage on the circuit is a constant 24 volts (short cable runs) and we know the maximum current is 20 milliamps so my maths says :

Resistance = Voltage / I (current)

We need to leave 5 volts for the Arduino to read when the sensor is at maximum pressure so we subtract 5 from 24.

Resistance = 19 / 20 milliamp

So the resistor to select to give us a maximum of 5 volts is a 0.95 Kilohms resistor. I dont see where the 250 ohm resistor comes in? please help.

# Answer
To read a current with the Arduino you first have to convert that current to a voltage - and you do that by passing it through a resistance. The voltage dropped across that resistance as the current changes is what interests you.

simulate this circuit – Schematic created using CircuitLab

For a 4-20mA current you need to choose a resistance that gives voltages that are within the 5V range that an Arduino can read.

The biggest voltage drop across the resistor will occur when the current is at maximum (20mA) so you can use that to calculate a good resistor value to use:

```
R = V/I = 5 / 0.02 = 250

```

And for the same resistance at minimum current:

```
V=IR = 0.004 × 250 = 1

```

So across the resistor you would get between 1V (4mA) and 5V (20mA).

250Ω resistors aren't that common, so a more common value would be used instead - such as the commonly available 220Ω. Substituting the 250Ω for a 220Ω would give voltages:

```
@20mA: V=IR = 0.02 × 220 = 4.4V
@4mA:  V=IR = 0.004 × 220 = 0.88V

```

Both comfortably within the Arduino's range and also gives a bit of wriggle room in case of any small over-current conditions.

It can also be good to protect the analog input of the Arduino with a resistor + zener diode to prevent damage in the case that the resistor fails / becomes disconnected and you get the full output voltage applied direct to the Arduino:

simulate this circuit
> 4 votes

---
Tags: arduino-uno, sensors, resistor, pressure
---


# Question
Title: Multiple random Fire2012 sequence in same strip
I am trying to simulate 4 flickering flames on a single LED strip.

The ws2812b strip has 60 LEDs. I cut and chained it into 4 chunks of 15 LEDs. Each chunk has a random Fire2012 sequence, however the entire sequence seems to start and stop at the same time, and therefore they all look extremely similar.

What is the best way to overlap the fire sequences so that timing looks different for each chunk?

Here is my code so far...

```
#include <FastLED.h>

#define LED_PIN     5
#define COLOR_ORDER GRB
#define CHIPSET     WS2812B

#define NUM_CHUNKS           4
#define NUM_LEDS_PER_CHUNK   15
#define NUM_LEDS NUM_CHUNKS * NUM_LEDS_PER_CHUNK

#define BRIGHTNESS  80
#define FRAMES_PER_SECOND  30

#define gReverseDirection false

CRGB leds[NUM_LEDS];

void setup() {
  delay(3000); // sanity delay
  FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness( BRIGHTNESS );
}

void loop()
{
  // Add entropy to random number generator; we use a lot of it.
  // random16_add_entropy( random());

  // Get LED Chunks
  for(int i = 0; i < NUM_CHUNKS; i++){
    //random16_add_entropy( random());
    Fire2012(i); // run simulation frame
  }

  FastLED.show(); // display this frame
  FastLED.delay(1000 / FRAMES_PER_SECOND);
}

// Fire2012 by Mark Kriegsman, July 2012
// as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY
////
// This basic one-dimensional 'fire' simulation works roughly as follows:
// There's a underlying array of 'heat' cells, that model the temperature
// at each point along the line.  Every cycle through the simulation,
// four steps are performed:
//  1) All cells cool down a little bit, losing heat to the air
//  2) The heat from each cell drifts 'up' and diffuses a little
//  3) Sometimes randomly new 'sparks' of heat are added at the bottom
//  4) The heat from each cell is rendered as a color into the leds array
//     The heat-to-color mapping uses a black-body radiation approximation.
//
// Temperature is in arbitrary units from 0 (cold black) to 255 (white hot).
//
// This simulation scales it self a bit depending on NUM_LEDS; it should look
// "OK" on anywhere from 20 to 100 LEDs without too much tweaking.
//
// I recommend running this simulation at anywhere from 30-100 frames per second,
// meaning an interframe delay of about 10-35 milliseconds.
//
// Looks best on a high-density LED setup (60+ pixels/meter).
//
//
// There are two main parameters you can play with to control the look and
// feel of your fire: COOLING (used in step 1 above), and SPARKING (used
// in step 3 above).
//
// COOLING: How much does the air cool as it rises?
// Less cooling = taller flames.  More cooling = shorter flames.
// Default 50, suggested range 20-100
#define COOLING  55

// SPARKING: What chance (out of 255) is there that a new spark will be lit?
// Higher chance = more roaring fire.  Lower chance = more flickery fire.
// Default 120, suggested range 50-200.
#define SPARKING 60

void Fire2012(int chunk)
{
// Array of temperature readings at each simulation cell
  static byte heat[NUM_LEDS_PER_CHUNK];

  int startLed = NUM_LEDS_PER_CHUNK * chunk;
  int endLed = NUM_LEDS_PER_CHUNK * chunk + NUM_LEDS_PER_CHUNK;

  // Step 1.  Cool down every cell a little
    for( int i = 0; i < NUM_LEDS_PER_CHUNK; i++) {
      heat[i] = qsub8( heat[i],  random8(0, ((COOLING * 10) / NUM_LEDS_PER_CHUNK) + 2));
    }

    // Step 2.  Heat from each cell drifts 'up' and diffuses a little
    for( int k= NUM_LEDS_PER_CHUNK - 1; k >= 2; k--) {
      heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
    }

    // Step 3.  Randomly ignite new 'sparks' of heat near the bottom

    if( random8() < SPARKING ) {
      int y = random8(7);
      heat[y] = qadd8( heat[y], random8(160,255) );
    }

    // Step 4.  Map from heat cells to LED colors
    for( int j = 0; j < NUM_LEDS_PER_CHUNK; j++) {
      CRGB color = HeatColor( heat[j]);
      int pixelnumber;
      if(gReverseDirection) {
        pixelnumber = (endLed - 1) - j;
      } else { //0 15
        pixelnumber = startLed + j;
      }
      leds[pixelnumber] = color;
    }
}

```

# Answer
```
#include <FastLED.h>

 #define LED_PIN     5
 #define COLOR_ORDER GRB
 #define CHIPSET     WS2811
 #define NUM_LEDS    (kMatrixWidth * kMatrixHeight)
 #define FRAMES_PER_SECOND 60
 //////////////////////////////////////////////////////
 const uint8_t kMatrixWidth  = 15;
 const uint8_t kMatrixHeight = 4;
 const bool    kMatrixSerpentineLayout = true;
 //////////////////
 int BRIGHTNESS = 250;

//////////////////////////////////////////////////
bool gReverseDirection = false;

CRGB leds[NUM_LEDS];

void setup() {
Serial.begin(115200);
Serial.println("*** Inicialization");
///////////////////////////////////////////////
delay(3000); // sanity delay
FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS);
FastLED.setBrightness( BRIGHTNESS );
}
/////////////////////////////////// end setup

void loop()
{

 Fire2012();
 FastLED.show(); // display this frame
 FastLED.delay(1000 / FRAMES_PER_SECOND);
 FastLED.setBrightness( BRIGHTNESS );
 }

 void Fire2012()
 {
  int COOLING = 90;
  int SPARKING = 100;
   // Array of temperature readings at each simulation cell

    static byte heat[kMatrixWidth] [kMatrixHeight];

    // Step 1.  Cool down every cell a little
    for (int n = 0; n< kMatrixHeight; n++)
   {

     for ( int i = 0; i < kMatrixWidth; i++) {
       heat[i][n] = qsub8( heat[i][n],  random8(0,
       ((COOLING * 10) / (kMatrixWidth)) + 2));
       }

       // Step 2.
      for ( int k = (kMatrixWidth- 1); k >= 2; k--) {
      heat[k][n] = (heat[k - 1][n] + heat[k - 2][n] +
      heat[k - 2][n] ) / 3;
      }

       // Step 3.
      if ( random8() < SPARKING ) {
       int y = random8(3);
       heat[y][n] = qadd8( heat[y][n], random8(160, 255) );
      }
     }

  // Step 4.  Map from heat cells to LED colors

for ( int i= 0; i < kMatrixWidth; i++) {
  for (int j = 0; j < kMatrixHeight; j++) {

    CRGB color = HeatColor(heat[i][j]);
    leds[XY(i, j)] = color;

     }
   }

 }

   /////////////
    uint16_t XY( uint8_t x, uint8_t y)
    {
    uint16_t i;
    if ( kMatrixSerpentineLayout == false) {
    i = (y * kMatrixWidth) + x;
    }
    if ( kMatrixSerpentineLayout == true) {
    if ( y & 0x01) {
     // Odd rows run backwards
     uint8_t reverseX = (kMatrixWidth - 1) - x;
     i = (y * kMatrixWidth) + reverseX;
     } else {
    // Even rows run forwards
      i = (y * kMatrixWidth) + x;
     }
    }

    return i;

   }/////

```
> 1 votes

# Answer
Instead of calling the function on all 3 chunks back to back in the for loop and then only doing show() after you've updated all three chunks, break it up a little and put a little delay between them.

```
    byte i = 0;

    void loop(){
       Fire2012(i);
       FastLED.show();
       FastLED.delay(1000 / NUM_CHUNKS / FRAMES_PER_SECOND);
       i = (i + 1) % NUM_CHUNKS;
    }

```

You could even make the delay a little bit random if you wanted to.
> 0 votes

---
Tags: rgb-led
---


title: 4 digit 7-segment display

text:
# Question
Title: 4 digit 7-segment display
What happends if I turn on all LEDs at the same time in an 4 digit 7 segment display? that would be 32 LEDs turned on at once, wouldn't that exceed the 200ma MAX for the arduino output?

# Answer
The key point is that if you do that, you're doing it wrong.

Typically a multi digit display is time multiplexed, such that you use a common set of segment lines to activate the pattern on each digit in turn, therefore at any one time only at most 7 (or 8 counting the decimal point) segments should actually be on.

Then in terms of the common connection which selects a given digit, this will indeed typically have to source or sink more current than an MCU I/O pin is typically rated to handle, so it's best if the common connection is driven by an external transistor or FET.

Other options of course include mutli-digit LED display drivers, or lower power display technologies like LCDs.

That said, if a software bug briefly means everything is on, chances are the chip will survive. But hopefully this only happens to "engineering units" - you do want to make sure that *production* units don't suffer this at some point in the programming process or something like that (though that's not all that likely, as typically all I/Os become inputs with at most a weak pullup).
> 1 votes

# Answer
These typically use 12 GPIO pins (4 for the digits, 8 for the segments/dot).

Each GPIO pin controls one digit and/or segment at a time.

The normal 'maximum' LED current is 20 mA. For the digits, 8 segments * 20 mA = 160 mA which is below 200 mA.

However, maybe there are LED displayed which use more current. In that case, you have yourself to make sure not all segments are lit at the same time (by fastly alternating the LEDs, or using less current).
> 0 votes

# Answer
They will turn on, likely with slightly uneven brightness - the LEDs internal resistance and the pins limited current drive will act like the current limiter.

The actual current will depend on the supply voltage, led used and the mcus drive capabilities.

For a red 4 digit 7 seg on an atmeha8, I got less than 10ma at 2,5v and 20ma at 3.3v, with the LEDs multiplexed.

Edit: some quick math.

Say that the current through each led segment is I. And the gpio resistance is R.

Each common digit has 8 I current through it, and each segment has 4 I. Some math later,

I = (Vcc - Vf) / (12 R) where Vcc is the supply voltage and Vf is the LEDs forward voltage (1.9v for a typical red led). The gpio resistance varies from 50+ ohm to 30+ ohm, higher at lower voltage.

Plus in 3.3v and 2.7v you get total current of 30 to 75ma for all digits.

I'm going to measure mine later.

edit: about 25ma (total current = mcu + led) at 2.5v and 50ma at 3.3v. the mcu consumes 2-3ma approximately.

the brightness is fairly even amongst the leds if you don't look too closely.
> 0 votes

---
Tags: arduino-uno, 7-segment
---


title: Arduino analog pins not working

text:
# Question
Title: Arduino analog pins not working
I am having a problem with pins of Arduino Uno. I have connected a LED to one of the analog pins (A0), and I want to light up the LED with different intensinty.

```
int ledPin = A0;
void setup() {
 // put your setup code here, to run once:
 pinMode(ledPin,OUTPUT);

}

void loop() {
 // put your main code here, to run repeatedly:
 analogWrite(ledPin,500);
}

```

The point is that even if I change the value of analogWrite, the LED lights up always with the same intensity.

# Answer
analogWrite deals with PWM pins, those are digital pins. See https://www.arduino.cc/en/Reference/AnalogWrite

So connect the LED to one of the PWM pins and change the sketch accordingly. On the Uno those are pins 3, 5, 6, 9, 10, and 11.

The analog pins A0 - A5 are input pins. The value is read using the analogRead(pin) function.
> 3 votes

---
Tags: arduino-uno, pins
---


title: Merging arduino code

text:
# Question
Title: Merging arduino code
I have a project where we need to create a virtual cane for blind people and it will have 3 functions:

* Pressure button when pressed will connect to an android phone through HC-06 Bluetooth modulo to an app that I developed and will can to someone that I defined
* Temperature sensor that is attached to a buzzer that will buzz if the temperature is higher than 40 Degrees
* Ultrasonic sensor attached to and vibration motor that will vibrate if there is any object less than 70 cm from the person.

When I combine the code from the ultrasonic and the temperature sensor, everything works fine, when I add the bluetooth code, nothing works, anyone see the problem? Or could you show me the problem and solveit?

Code without Bluetooth:

```
int DHT11_PIN=8;
dht DHT;
int buzzer=6;
int trigPin=3;
int echoPin=2;
int motor=7;

void setup(){
  Serial.begin(115200);
  pinMode(DHT11_PIN,INPUT);
  pinMode(buzzer, OUTPUT);
  delay(5000);

  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motor, OUTPUT);
  delay(5000);
}

void loop(){
  Stemperature();
  Sultrassom();
}

// sensor de tempratura e Buzzer-------------------------------
void Stemperature(){
  digitalWrite(buzzer,LOW);
  DHT.read11(DHT11_PIN);
  float t=DHT.temperature;
  Serial.print("Temperature = ");
  Serial.println(t);

  if (t>40){
    digitalWrite(buzzer,HIGH);
    {tone(6,100,20);
    delay(1);
    noTone(1);
    delay(1);
    }
    delay(1000);
    Serial.print("ON T=");
  }else{
    digitalWrite(buzzer,LOW);
    Serial.print("OF T=");
  }
}

//Sensor de Ultrassom e Motor vibração-----------------
void Sultrassom(){
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) * 0.0340;
  Serial.println(distance);

  if (distance < 70){ // se a distância for menor que 70 cm o motor vibra
    digitalWrite(motor,HIGH);// quando a distância for menor que 70 cm
    Serial.print("MOTOR ON=");
  }else{
    digitalWrite(motor,LOW);// quando a distância for maior que 70 cm
    Serial.print("MOTOR OFF=");
  }
  delay(5);
}

```

Bluetooth Code:

```
const int buttonPin = 4;     // the number of the pushbutton pin
boolean buttonState;         // variable for reading the pushbutton status

void setup(){
  Serial.begin(9600);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  buttonState = LOW;
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if(buttonState == HIGH) {
    // send char 1 via Bluetooth:
    Serial.println("1");
    delay(20000);
    while (0);
  }
}

```

# Answer
> 1 votes
In the bluetooth loop you use:

```
delay(20000);
while (0);

```

This means you first wait 20 seconds, and while(0) does not do anything (unuseful instruction).

Actually, this results when the button is pressed, it starts the loop again, but you have to merge both codes into one.

I would add the sending of the serial command in the code above, remove the while and see what happens. If you need some delay for debouncing reaons for the button, implement a decent deboucing algorithm instead of the delay of 20000.

And why there are two }} at the end?

# Answer
> 0 votes
The following code is not tested in any way. It should give you some help, to detect the problems. First you used the same Serial connection for your PC and the Bluetooth module, which leads to problems. Second, you had some delays, which seemed useless. Third your `noTone()` function didn't matched the right pin. Also I added an Interrupt for the Button. It could be, that your DHT reading need the same Interruptprotection, which I added to the Usonic measurment. Last but not least I replaced your Pin definitions to make it more readable.

```
// New Include for the bluetooth connection
#include <SoftwareSerial.h>
#include <dht.h>

#define DHT11PIN        8
#define BTRXPIN         10                    // Pay attention to your wiring
#define BTTXPIN         11
#define BUZZERPIN       6
#define TRIGGERPIN      5                     // Changed, to keep an interrupt Pin free !!!
#define ECHOPIN         4                     // Changed, to keep an interrupt Pin free !!!
#define MOTORPIN        7
#define BUTTONPIN       2                     // Changed to an interrupt Pin

dht DHT;
SoftwareSerial bluetooth(BTRXPIN, BTTXPIN);

void setup(){
  Serial.begin(9600);                         // Only once
  bluetooth.begin(9600);                      // Serial connection for the bluetooth module
                                              // Check your needed Baudrate
  pinMode(DHT11PIN,  INPUT);
  pinMode(BUTTONPIN, INPUT);
  pinMode(ECHOPIN,   INPUT);
  pinMode(TRIGGERPIN, OUTPUT);
  pinMode(BUZZERPIN,  OUTPUT);
  pinMode(MOTORPIN,   OUTPUT);
  digitalWrite(BUZZERPIN, LOW);

  attachInterrupt(digitalPinToInterrupt(BUTTONPIN), buttonISR, RISING); // I did not pay attention to bouncing here!!
  // I see no need for 5sec delay, so i cut it out
}

void loop(){
  temperatureMeasure();
  ultraSonicMeasure();
  delay(2000);                                  // 2 sec delay, so it won't measure all the time.
}

float temperatureMeasure(){                     // Added return types
  DHT.read11(DHT11_PIN);
  float t = DHT.temperature;
  Serial.print("Temperature = ");
  Serial.println(t);

  if (t > 40){
    tone(BUZZERPIN,100);
    delay(20);
    noTone(BUZZERPIN);
    Serial.print("ON");
  }else{
    noTone(BUZZERPIN);
    Serial.print("OFF");
  }
  return temperatureMeasure;
}

long ultraSonicMeasure(){
  long duration{0};
  long distance{0};
  noInterrupts();
  digitalWrite(TRIGGERPIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGERPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGERPIN, LOW);

  duration = pulseIn(ECHOPIN, HIGH);
  interrupts();
  distance = (duration/2) * 0.0340;
  Serial.println(distance);

  if (distance < 70){
    digitalWrite(MOTORPIN, HIGH);
    Serial.print("MOTOR ON");
  }else{
    digitalWrite(MOTORPIN, LOW);
    Serial.print("MOTOR OFF");
  }
  return distance;
}

// Called when button is pressed
void buttonISR(){
  bluetooth.println("1");                         // Would be better, to put this outside of the ISR, but is is only on character.
}

```

---
Tags: arduino-nano, bluetooth, temperature
---


title: Arduino IDE lost board connection

text:
# Question
Title: Arduino IDE lost board connection
**Board**: Arduino Leonardo

**IDE version**: 1.6.5(also tried with 1.8.3)

Try **Arduino Web Editor** as well

The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.

Everything was OK, but after one deploy happened thing, that I described.

If it help: I connect OLED display and use it with OLED\_I2C library. Sketch contains one `cpp` and one `h` file.

I'm already fully reinstall USB drivers with Arduino USB as well

# Answer
> 2 votes
> The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.

Yes, that's normal. That's the bootloader running, and it's during that 5-7 second window that you can upload a new sketch.

Under normal circumstances the IDE will automatically reboot the board for you so the upload time window coincides with the IDE's attempt to upload a new sketch. However under some circumstances it can't, so you have to do it manually by pressing the reset button at the right time.

Also on Windows you may find that you have a different COM port for programming as you do when a sketch is running (Windows is retarded like that, you see). The IDE tries to do some magic to identify the correct COM port to use, but you have to first have the correct "sketch mode" COM port selected so it can first reboot the board into the bootloader, at which point it tries to do its magic to work out the correct COM port to use by looking to see which COM port (if any) has just appeared since rebooting.

So, in short: if the IDE can't reboot the board for you then do it manually, but note that *timing is vital*. Press the reset button a few moments *before* `avrdude` runs. It may take practice.

---
Tags: arduino-leonardo
---


# Question
Title: Arduino Yún as ISP to program Attiny - why is the sketch not working after successful upload?
I want to use an Arduino Yun as ISP to program an Attiny85. I have soldered a shield following the circuit that is depicted in many sites. You can see it in this page.

I have included a LED with a 1k resistor in series connected between pin 5 (PB0) and ground so that I can monitor.

I have setup my sketch environment (Arduino 1.6.12) with the definitions of the Attiny so that I can select this board (Attiny85) with it's associated parameters.

I have defined in Arduino 1.6.12 the board in this way:

* Board: "ATtiny25/45/85"
* Processor: "ATtiny85"
* Clock: "Internal 1MHz"
* Port: "192.168.1.109 (Arduino Yún)"

I use this port instead of the serial USB port as I had many issues with the serial USB port.

I have started with the Blink sketch modifying it to use pin0 The sketch is this one:

```
// the setup function runs once when you press reset or power the board
int LED = 0;  //0 para Attiny
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED, HIGH);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```

The output of the sketch loading in verbose mode is this one:

```
El Sketch usa 672 bytes (8%) del espacio de almacenamiento de programa. El máximo es 8.192 bytes.
Las variables Globales usan 9 bytes (1%) de la memoria dinámica, dejando 503 bytes para las variables locales. El máximo es 512 bytes.
/usr/bin/run-avrdude /tmp/sketch.hex -v -pattiny85

avrdude: Version 6.1, compiled on Apr  8 2016 at 15:56:17
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : unknown
         Using Programmer              : linuxgpio
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       1024    8      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : linuxgpio
         Description     : Use the Linux sysfs interface to bitbang GPIO lines
         Pin assignment  : /sys/class/gpio/gpio{n}
           RESET   = ~18
           SCK     =  11
           MOSI    =  27
           MISO    =  8

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e9587
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified
avrdude: reading input file "0xD8"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xD8:
avrdude: load data hfuse data from input file 0xD8:
avrdude: input file 0xD8 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xFB"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xFB:
avrdude: load data efuse data from input file 0xFB:
avrdude: input file 0xFB contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "/tmp/sketch.hex"
avrdude: writing flash (672 bytes):

Writing | ################################################## | 100% 0.40s

avrdude: 672 bytes of flash written
avrdude: verifying flash memory against /tmp/sketch.hex:
avrdude: load data flash data from input file /tmp/sketch.hex:
avrdude: input file /tmp/sketch.hex contains 672 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.57s

avrdude: verifying ...
avrdude: 672 bytes of flash verified

avrdude done.  Thank you.

```

What looks pretty normal for me. When the load is ongoing, I see the 1st thing that puzzles me: LED connected to pin 5 (PWM0) doesn't blink quickly. I have tested the polarity of the LED with a +5V connected to the physical pin of the chip and 0V connected to GND and it lights.

The second thing that puzzles me is that I get exactly the same output when I remove the programming shield (no Attiny at all) and I click on upload and the output is the same. Is the Arduino IDE caching this output?

When I put the "programmed" Attiny in a breadboard and I power it and connect one LED to port 5, it doesn't blink as per the Blink sketch.

I am quite a newby with Arduino and ATtiny85. I only wan to be able to program this ATtiny85 with my Arduino Yún

What am I doing wrong? Could you give some light to this darkness?

# Answer
> 1 votes
It's not programming a non-existent ATtiny, it's quite explicitly stating in the output that it is programming an ATmega32u4 - and that would be the "Arduino" part of the YUN.

It's not clear that the YUN is really intended to ISP other targets.

If you can get serial communication to the ATmega32U4, you could try to find a compatible variation of the ISP sketch to load on that, and in turn use it to program an ATtiny.

Or you could try to define a different set of programming pins, but this may be tricky.

Essentially, what you are trying to do is a bit unusual, and will likely require investing some real time in understanding the existing / available mechanisms enough to adapt them to a fairly unique goal.

Otherwise, just get an Uno or similar and use that to ISP your ATtiny.

---
Tags: attiny, attiny85
---


# Question
Title: Is it possible to obtain %0.05 duty cycle at 1hz in arduino?(a 500us square pulse at 1 sec period)
I have a system which requires me to obtain different duty cycles at different frequencies. But using the analogWrite() does not allow me to obtain a value lower than 1/255 duty cycle. I need to obtain lower duty cycle values for 1Hz

# Answer
> 2 votes
Expanding from my comment. This is an attempt to generate that signal with Timer 1. ~~No time to test it now...~~ **Edit**: tested, works as advertised.

```
/*
 * Configure Timer 1 to generate a slow, low duty cycle PWM signal.
 * Output pin = digital 9 = PB1 = OC1A.
 */

const float PWM_PERIOD  = 1.0;     // 1 s
const float PULSE_WIDTH = 500e-6;  // 500 us

/*
 * With a 16 MHz clock and this prescaler, the resolution is 16 us and
 * the maximum period is 1.048576 s.
 */
const uint16_t TIMER_PRESCALER = 256;
const float F_TIMER = F_CPU / TIMER_PRESCALER;

void setup()
{
    // Configure Timer 1.
    DDRB  |= _BV(PB1);    // set PB1 = OC1A as output
    ICR1   = round(PWM_PERIOD * F_TIMER) - 1;
    OCR1A  = round(PULSE_WIDTH * F_TIMER) - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(WGM11);  // fast PWM mode, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS12);   // clock at F_CPU/256 = 62.5 kHz
}

void loop() {}

```

# Answer
> 2 votes
Sure - if you program it to.

1. Turn on an output.
2. Wait for 500µs less the amount of time it took to turn on the output
3. Turn off the output
4. Wait for 0.9995 seconds minus the amount of time it took to turn off the output
5. Go to 1.

You would probably find using the `micros()` function easiest to get the timing right - in exactly the same way as the `BlinkWithoutDelay` example in the IDE.

Also direct port manipulation may be of benefit to make things as fast as possible.

# Answer
> 0 votes
Sure. Two easy way to do it.

1. 0,05 percent is 1:2000. So modify timer settings to produce a pen of the desired frequency and duty cycle.
2. Use timer interrupt: either the overflow or compare match interrupt. In the first case, load the timer with -duty cycle and -(period - duty) to produce a wave form of duty cycle / period.

The same can be done using compare match as well: just advance the match point alternately.

edit: to show how it can be done with compare match, here is what I have:

```
#define PR_PWM          (F_CPU / 256 / 10)      //period for the pwm waveform
#define PR_ON           (PR_PWM * 25 / 100)         //prescaler at 256:1, 25% duty cycle
#define PR_OFF          (PR_PWM - PR_ON)            //pin off period, to achieve 1Hz
//end hardware configuration

//global defines

//global variables

//timer1 ch a compare match isr
ISR(TIMER1_COMPA_vect) {
    static char pr_index=0;     //0->PR_ON, 1->PR_OFF

    //clear the flag  -  done automatically
    //advance to the next match point
    if ((pr_index++ & 0x01) == 0) {
        OCR1A += PR_ON;
        IO_SET(PWM_PORT, PWM);  //set the pin on
    } else {
        OCR1A += PR_OFF;
        IO_CLR(PWM_PORT, PWM);  //clear the pin
    }

}

```

for this demo, we tried to generate a 25% duty cycle pwm with a period of 100ms. Here is the output of that code.

The follow changes the duty cycle to 0.05%:

```
#define PR_ON           (PR_PWM * 0.05 / 100)           //prescaler at 256:1, 0.05% duty cycle

```

and the corresponding output is:

Now, there are other ways to do it, for example, with higher resolution, or more precision, ..., but at the cost of more coding.

But the basic concept is the same.

hope it helps.

edit2: for those brave souls, the isr can be simplified to:

```
OCR1A += (pr_index++&0x01)?PR_OFF:PR_ON;  //advance the match point
IO_FLP(PWM_PORT, PWM);  //flip the pwm pin

```

---
Tags: arduino-uno, pwm, analogwrite
---


# Question
Title: Reading pressure sensor using Arduino analog
I'm using a Arduino Uno to read pressure and I want to know if I have wired/coded the sensor correctly. I'm not sure I'm getting the correct readings (it could be the right readings - I just want to check I have done everything right). The sensor I am using is an OsiSense™ XMLP pressure sensor that reads between 0 and 100 bars and gives out a 0v (zero bars) to 10v (100 bars) charge. Due to the Arduino Uno only being capable of reading up to 5 volts, I've used a voltage divider to reduce the maximum voltage the Arduino receives to 5v.

I've attached a hand-written diagram. Let me know if you need any more information. I've attached the wiring and also the code.

```
/*
  ReadAnalogVoltage from a OsiSense XMLP presure sensor

  Reads an analog input on pin 0, converts it to voltage and then bar pressure, and prints the result to the Serial Monitor and also MQTT.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).

  Todo
  Static ip. set it to request IP from network
  Work out best way to average readings

*/

#include <SPI.h>  //Serial Peripheral Interface (SPI)
#include <Ethernet.h>  //  These libraries are designed to work with the Arduino Ethernet Shield (Ethernet.h)
#include <PubSubClient.h>  // This library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT

// sets the MAC address and IP address for the network
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192,34,98,221);  // IP Address of the client
IPAddress server(192,34,98,201); // The IP address of the MQTT server

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

void setup() {
  Serial.println("Begin setup");
  Ethernet.begin(mac, ip);
  // Note - the default maximum packet size is 128 bytes. If the
  // combined length of clientId, username and password exceed this,
  // you will need to increase the value of MQTT_MAX_PACKET_SIZE in
  // PubSubClient.h

  // connects to MQTT and says hello world.  Probably change this later on to something more appropriate
  if (client.connect("ArdRigTest")) {
    client.publish("outTopic","Ard Rig Test");
    client.subscribe("inTopic");
  }
  // start serial port
  Serial.begin(9600);
}

void loop() {
  // Note - the default maximum packet size is 128 bytes. If the
  // combined length of clientId, username and password exceed this,
  // you will need to increase the value of MQTT_MAX_PACKET_SIZE in
  // PubSubClient.h

  // read the input on analog pin 0:
  int sensorValue1 = analogRead(A0);
  delay(2); // read twice with small delay to get accurate reading.
  int sensorValue2 = analogRead(A0);

  Serial.println(sensorValue2);
  //Test code. using map function
  int MapBarPressure;
  MapBarPressure = map(sensorValue2, 0, 1023, 0, 100);
  if (client.connect("ArdRigTest" )) {
    client.publish("MapBarPressure",String(MapBarPressure).c_str());  //logs the pressure of the RigTest
    client.subscribe("MapBarPressure");
  }
  delay(100); // Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)
  client.loop();
}

```

Thanks in advance.

# Answer
You can use `map`, ref. : https://www.arduino.cc/en/Reference/Map

> Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.
> 1 votes

# Answer
If you need to use fractional pressure values, then the formula is

```
float MapBarPressure;
MapBarPressure = sensorValue2 / 10.24;

```

This was obtained by seeing that the maximum reading from `AnalogRead(A0)` is `1024`, which corresponds to 5V on A0 (and which also means 10V output from the sensor.) If you read `1024` from A0, it means you are measuring 100bar, so

```
bar = (A0 / 1024) * 100

```

Alternatively, you could maintain 1 decimal place of accuracy in bar if you keep with `int` values:

```
int MapDeciBarPressure;
MapDeciBarPressure = map(sensorValue2, 0, 1023, 0, 1000);

```

Then your variable is holding "tenths of bar" (deciBar) and you only convert it to bar by dividing by 10.0 (not 10, which is an int, but 10.0, which is a float and does floating point math and returns a float response.)

One other note: you write:

```
// read the input on analog pin 0:
int sensorValue1 = analogRead(A0);
delay(2); // read twice with small delay to get accurate reading.
int sensorValue2 = analogRead(A0);

```

Just reading twice doesn't gain accuracy -- you have to average the values:

```
int sensorValAvg = (sensorValue1 + sensorValue2) / 2;

```

Then, use sensorValAvg for your less noisy value.

**Edit:** Also, make sure you connect all ground lines together, both from the sensor and the Arduino!
> 1 votes

# Answer
**About accuracy.**

I assume you have read @edgar-bonet about connecting the GND's.
I assume you understand the other answer to calculate the pressure. I would write it like this:

```
// This is for the DEFAULT 5V analog reference.
// v = the voltage at the pin in Volts.
// p = the pressure in bar.
// Note that 'bar' is the pressure relative to the
// normal atmospheric pressure at that moment.
float v = (float) analogRead(A0) / 1024.0 * 5.0;
float p = v / 5.0 * 100.0;

```

The `analogRead` uses default the 5V as reference.

That means that if the project is powered by a USB cable, the 5V could vary between 4.5 and 5.0 V. That 10% difference will be seen in the resulting calculated pressure. In that case you can not measure more accurate than 10%.

If the project is powered with a power supply to the power barrel jack, then the resulting accuracy depends on the accuracy of the voltage regulator on the Arduino board.

The analog reference can be set with `analogReference`.
The internal voltage reference of the Arduino Uno is 1.1V. That is reasonably stable, but it depends a little on the voltage of VCC and the temperature. The main problem is that it is different for each Arduino Uno, and it can be between 1.0 and 1.2 V. Therefor you have to measure it, and use the measured value in the calculation in the sketch.

The input range is between 0V and the analog reference. Therefor you have to adjust the voltage divider to get 0..10V down to 0..1.1V. You could try: R1 = 100k and R2 = 10k.

```
const int pressureSignalPin = A0;

void setup()
{
  analogReference( INTERNAL);
}

void loop()
{
  // v = the voltage at the pin in Volts.
  // p = the pressure in bar.
  // Note that 'bar' is the pressure relative to the
  // normal atmospheric pressure at that moment.
  // The "(100.0 + 10.0) / 10.0" is the factor by the voltage divider
  // with 100k and 10k.
  // Measure the AREF pin, and fill the value in for "1.10".
  float v = (float) analogRead(A0) / 1024.0 * 1.10;
  float p = v * ((100.0 + 10.0) / 10.0);
}

```
> 0 votes

# Answer
Everything is just fine.

All you have to do is to provide the common ground (0 potential) to your Arduino and your Sensor.

The problem here is that they might be on a different potential.

So just connect the ground of your 5 volts and 24 volts together and everything will work perfectly.
> 0 votes

---
Tags: sensors, voltage, pressure, calculation
---


# Question
Title: Arduino Serial Communication Between 2 Uno
I'm trying to get two arduino uno to communicate. The slave reads a temp sensor as an analog value, then converts it to degrees C, then sends that value to the master, the master then prints the value to the serial monitor. This is the code I have thus far.

for the slave

```
const int tempPin = A0;

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

  void loop() {

   //read sensor data to a variable
   float volt = analogRead(tempPin) * 0.004882814;
   float degC = (volt - 0.5) * 100.0;
   Serial.println(degC);

   delay(2000); //Not to flood serial port
  }

```

this is the code for the master

```
float tempC;
void setup(){
  Serial.begin(9600);
  delay(2000);
 }

  void loop() {
 /**  check if data has been sent from the computer: */
 while (Serial.available()) {
 /* read the most recent byte */
    tempC = Serial.read();     //now byteRead will have latest sensor
                              // data sent from Arduino1

    Serial.println(tempC);
  }
}

```

My issue is that I am reading on the serial monitor 4 different 2 integer values

# Answer
Your slave is sending an array of characters and your master is reading the ASCII values of those characters.

If you send 25.43, `Serial.println` will send 7 characters `2`, `5`, `.`, `4`, `3`, carriage return and a newline.

The master will read them as 50, 53, 46, 52, 51, 13 and 10. Your code then prints:

```
50.00
53.00
46.00
52.00
51.00
13.00
10.00

```

On your master, the `loop()` should look like:

```
void loop() {
  if (Serial.available()) {
    char c = Serial.peek(); // just look at the next character on the serial buffer
    if (c == '\r' || c == '\n') // ignore the carriage return and newline characters
      Serial.read(); // remove the character from serial buffer by reading it
    else {
      tempC = Serial.parseFloat(); // read and parse the string representing the float value
      Serial.println(tempC);
    }
  }
}

```
> 1 votes

---
Tags: arduino-uno
---


title: I2C requesting more than one byte

text:
# Question
Title: I2C requesting more than one byte
I got an Arduino Uno set up as an I2C master to an ATtiny85 slave, using the Wire (Master) and TinyWireS (Slave) libraries.

Communication works well. I have been able to keep the network running correctly for hours. However, I have not been able to let the master request more than a single byte from the slave.

Using the code below the master asks for 4 bytes from the slave, but in my serial console I get only an actual value for the first bytes. The next three bytes read 255.

How can I request multiple bytes from the slave, using the Wire library?

---

Master (Arduino Uno)

```
#include <Wire.h>

#define I2C_MASTER_ADDR 0x04
#define I2C_SLAVE_ADDR 0x05

int pollInterval = 700;//Milliseconds
unsigned long lastPoll = 0;

void setup()
{
  Wire.begin(I2C_MASTER_ADDR);  // join i2c bus
  Serial.begin(115200);
  Serial.println("Setup complete");
}

/*
 * The main loop
 */
int i = 0;

void loop()
{

  //Writing to the slave
  if( (millis()-lastPoll) > pollInterval)
  {
    Wire.beginTransmission(I2C_SLAVE_ADDR);
    Wire.write(0x01);//Register to start at
    switch(i)
    {
      case 0:
        Wire.write(255);
        Wire.write(0);
        Wire.write(0);
        i++;
        break;
      case 1:
        Wire.write(0);
        Wire.write(255);
        Wire.write(0);
        i++;
        break;
      case 2:
        Wire.write(0);
        Wire.write(0);
        Wire.write(255);
        i = 0;
        break;
    }
    Wire.endTransmission();

    delay(1);//Dont let the slave panic

    //Set the register pointer back to 0x01, preparing for a read
    Wire.beginTransmission(I2C_SLAVE_ADDR);
    Wire.write(0x00);//Register to start at
    Wire.endTransmission();
    delay(1);//Dont let the slave panic

    //Get values from the three registers up from 0x01
    Wire.requestFrom(I2C_SLAVE_ADDR, 4);//Request N bytes
    while (Wire.available())
    {
      uint8_t next_byte = Wire.read();
      Serial.print(next_byte);Serial.print(" ");
    }
    Serial.println("\n");

    lastPoll = millis();
  }//End if time to poll again

}//End loop

```

Slave - ATTiny85

```
#include <EEPROM.h>
#include <TinyWireS.h>
#include <Bounce2.h>
#include <WS2812.h>
#ifdef __AVR__ //Which will be true for ATtiny85
  #include <avr/power.h>
#endif

#define I2C_SLAVE_DEFAULT_ADDR 0x05
#define BUTTON_DEBOUNCE 5//Debounce milliseconds

#define NEOPIXEL_PIN  1
#define BUTTON_PIN    3

#define NUMPIXELS     1

/*
 * I2C Registers
 *
 * Register map:
 * 0x00 - Button state
 * 0x01 - led value red
 * 0x02 - led value green
 * 0x03 - led value blue
 *
 * Total size: 4
 */
const byte reg_size = 4;
volatile uint16_t i2c_regs[reg_size];

/*
 * Internal variables
 */
cRGB value;
volatile boolean led_needs_update = false;
volatile byte reg_position;

/*
 * Initialize instances/classes
 */
Bounce button = Bounce();
WS2812 led(NUMPIXELS);

void setup()
{
  //Start I2C
  //uint8_t _device_addr = EEPROM_DATA::get_device_addr();
  TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
  TinyWireS.onReceive(i2cReceiveEvent);
  TinyWireS.onRequest(i2cRequestEvent);

  //Start Led
  led.setOutput(NEOPIXEL_PIN);
  value.b = 255; value.g = 0; value.r = 0;
  led.set_crgb_at(0, value); //Set value at LED found at index 0
  led.sync(); // Sends the value to the LED

  //Start Button
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  button.attach(BUTTON_PIN);
  button.interval(BUTTON_DEBOUNCE);

}

void loop()
{
  button.update();

  if(led_needs_update)
  {
    led_update();
    led_needs_update = false;
  }

  if(button.fell())
  {
    i2c_regs[0x00] = true;
  }
  if(button.rose())
  {
    i2c_regs[0x00] = false;
  }

  // This needs to be here for the TinyWireS lib
  TinyWireS_stop_check();

}

/*
 * I2C Handelers
 */
void i2cReceiveEvent(uint8_t howMany)
{
    if (howMany < 1)
    {
        return;// Sanity-check
    }

    reg_position = TinyWireS.receive();
    howMany--;
    if (!howMany)
    {
        return;// This write was only to set the buffer for next read
    }

    while(howMany--)
    {
        //Store the recieved data in the currently selected register
        i2c_regs[reg_position] = TinyWireS.receive();

        //Proceed to the next register
        reg_position++;
        if (reg_position >= reg_size)
        {
            reg_position = 0;
        }
    }
    led_needs_update = true;
}//End i2cReceiveEvent()

void i2cRequestEvent()
{
    //Send the value on the current register position
    TinyWireS.send(i2c_regs[reg_position]);

    // Increment the reg position on each read, and loop back to zero
    reg_position++;
    if (reg_position >= reg_size)
    {
        reg_position = 0;
    }
}//End i2cRequestEvent

/*
 * Helper functions
 */
void led_update()
{
  cRGB val;
  val.r = i2c_regs[0x01];
  val.g = i2c_regs[0x02];
  val.b = i2c_regs[0x03];
  led.set_crgb_at(0, val);
  led.sync(); // Sends the value to the LED
}

```

# Answer
> 1 votes
This is another case where the Arduino documentation is horribly incomplete to the point of being useless, and you must refer to the source code itself.

Presuming your TinyWire library works like the ordinary Arduino Wire, you need to use the two-argument form of the write method:

```
size_t TwoWire::write(const uint8_t *data, size_t quantity)

```

So your handler would probably look like this

```
void i2cRequestEvent()
{
    TinyWireS.write(i2c_regs, sizeof(i2c_regs));
}

```

However, you're also going to need to change your definition to an 8-bit type, rather than the 16-bit one you surprisingly had

```
volatile uint8_t i2c_regs[reg_size];

```

If you really do need to use a 16-bit type, then you'll need to either double the transfer size (since both processors are AVRs you won't hit any byte order issues) or first copy the values that you care about to a byte buffer.

---
Tags: arduino-uno, i2c, attiny85
---


# Question
Title: How to Jump from one loop to another while executing
For my program I have to sense 3 inputs (`A1`, `A2` and `A3` in Arduino). If any one or two or more signals become zero (low), it goes in different case as per below program.

However, I want to reset the Arduino when all signals become high again. Therefore I have to again write another program `loop2()`.

So how can I exit from one loop and get into another loop. If I have to use `goto`, please tell me how to use it?

The Arduino program given below.

```
const int analogPin1 = A1;
const int analogPin2 = A2;
const int analogPin3 = A3;
const int ledPin = 13;
const int ledPin2 = 7;
const int  thresold = 400;
unsigned int x1,x2,x3,fault = 0;

void setup()
{
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
}

void Config()
{
    delay(1000);
    Serial.print("ATE0r");
    Response();
    Serial.print("ATr");
    Response();
    Serial.print("AT+CMGF=1r");
    Response();
    Serial.print("AT+CNMI=1,2,0,0,0r");
    Response();
}

void Response()
{
    int count = 0;
    Serial.println();
    while(1)
    {
        if(Serial.available())
        {
            char data =Serial.read();
            if(data == 'K'){Serial.println("OK");break;}
            if(data == 'R'){Serial.println("GSM Not Working");break;}
        }
        count++;
        delay(10);
        if(count == 1000){Serial.println("GSM not Found");break;}

    }
}

void loop()
{
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);

    if (analogValue1 < thresold)
    { x1=1;
        fault=x1;
    }
    if (analogValue2 < thresold)
    {  x2=x1+3;
        fault=x2;
    }
    if (analogValue3 < thresold)
    {  x3=x1+x2+5;
        fault=x3;
    }

    switch(fault)
    {
    case 1:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("PHASE 1 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        loop2();
        break;

    case 3:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 4:
        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("1 AND 2 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 5:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("AT+CNMI=2,2,0,0,0");
        break;

    case 6:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("1 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 8:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("2 AND 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    case 10:

        digitalWrite(ledPin, HIGH);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("ALL 3 HAS GONE");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        break;

    default:
        x1,x2,x3,fault=0;
        digitalWrite(ledPin, LOW);
        break;

    }

    x1,x2,x3,fault=0;
    digitalWrite(ledPin, LOW);
    do
    {
        int analogValue1 = analogRead(analogPin1);
        int analogValue2 = analogRead(analogPin2);
        int analogValue3 = analogRead(analogPin3);
    }
    while ( analogValue1 < thresold || analogValue2 < thresold || analogValue3 < thresold );

}

do
{
    int analogValue1 = analogRead(analogPin1);
    int analogValue2 = analogRead(analogPin2);
    int analogValue3 = analogRead(analogPin3);
}
while (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));

}

void loop2()
{
    if (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th))
    {

        digitalWrite(ledPin, HIGH);
        Serial.begin(9600);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919512700997\"\r");
        delay(1000);
        Serial.print("Nikunjsinh2");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);
        Serial.print("\r");
        delay(1000);
        Serial.print("AT+CMGF=1\r");
        delay(1000);
        Serial.print("AT+CMGS=\"+919712554766\"\r");
        delay(1000);
        Serial.print("Nikunjsinh2");
        delay(1000);
        Serial.write(0x1A);
        delay(1000);

        do
        {
            int analogValue1 = analogRead(analogPin1);
            int analogValue2 = analogRead(analogPin2);
            int analogValue3 = analogRead(analogPin3);
        }
        while (( analogValue1 > th) && (analogValue2 > th) && (analogValue3 > th));
    }
}

```

# Answer
> 1 votes
It is clear from your question you intuitively know this program will not perform as desired. Simply put, if you do not check all states during every loop, you can not possibly react to all possibilities. Therefore you can only have 1 loop. Get rid of the other loops.

> ...but i want to reset arduino when all signal becomes again high...

This statement identifies what is missing. You need a temporal aspect to the loop in order to "remember" that all signal(s) were not high on the previous loop and now in the current loop they are all high.

Programmers commonly refer to this feature as a Finite State Machine. A way to "remember" what state the loop was in the last time it was executed. And a way to know what state(s) is(are) next possible.

If all you need to remember is that not all 3 inputs were high the last time through the loop, your state machine only needs the one value. And that value only needs to be a zero or one.

---
Tags: arduino-uno
---


title: Sending data by nRF24L01 with Arduino

text:
# Question
Title: Sending data by nRF24L01 with Arduino
Can I send data using nRF24L01 with Arduino through multiple pipes? As by using the RF24 library, I can send data through just one pipe and receive on the 6 pipes that nRF24L01 has.

# Answer
Yes, but the nRF24L01 can only transmit one message at at time, since it only has one buffer.

So roughly speaking, for each message

1. Set the transmit pipe address (if different than the last one)
2. Send data
3. Wait for completion (and ack or failure, if in that mode)
> 1 votes

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


# Question
Title: Need help with sending Arduino data to web page with ESP8266
I am developing a system that reads data from an LM35 temperature sensor and forwards it to a web page using an Arduino Uno and a ESP8266 WiFi Module. The data flow is as follows:

`LM35 --> Arduino Uno --> ESP8266 (Having a web server) --> Webpage`

The Uno sends data to the ESP8266 every `SAMPLE_RATE` seconds (4 seconds in my example) but the ESP8266 keeps updating the web page as it is a dynamic web page running AJAX. The problem is that I can see the data updating only once in a while (I assume when the 4 second delay aligns with the instant when the ESP8266 updates the value on the web page).

How can I make it so that even if The Uno doesn't send new values (during the 4 second gap), the ESP8266 keeps updating the web page with the old values? I have tried numerous times but have failed. Here is my code so far:

ARDUINO SIDE:

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

//a Header for the Filtering Algorithm

//*******************************************************************/
//#include "Filter.h"
//*******************************************************************/

//Set RESET PIN for ESP8266

//*******************************************************************/
#define RST_PIN_ESP8266 13
//*******************************************************************/

//Define Baud rate for Serial Communication and ESP8266 Software Serial
//*******************************************************************/
#define SERIAL_BAUD_RATE 9600
#define ESP8266_SOFT_SERIAL_BAUD_RATE 9600
//*******************************************************************/

//LM35 Temperature sensor used for this code
//*******************************************************************/
#define LM35 A0
//*******************************************************************/

//Define Sensor sampling rate
//*******************************************************************/
#define SAMPLE_RATE 4000
//*******************************************************************/

//Code Features . . Uncomment to enable
//*******************************************************************/
//#define LM35_RAW_DEBUG
//#define TEMP_READ
//#define PRINT_DEBUG
#define MEASURE_SALINE
//*******************************************************************/
//ESP8266 Software Serial Object
//*******************************************************************/
SoftwareSerial ESP8266_Serial(6,7);
//*******************************************************************/

//Global Variables
//*******************************************************************/
float tempC;
long rawValue = 0, initCount = 0;
int initRawValue = 0, i, START_VALUE = 0;
int SALINE_STARTED = 0, SALINE_IN_PROGRESS = 1, SALINE_EXHAUSTED = 2;
int saline_status_flag = 0;
String finalMSG;
//*******************************************************************/

//Needed objects for time counting and filtering
//*******************************************************************/
unsigned long StartTime = millis();
//ExponentialFilter<int> ADCFilter(5, 0);
//*******************************************************************/

void setup() {
  long rawValue = 0, initCount = 0;
  int initRawValue = 0, i;
  //Set up Serial Communication
  Serial.begin(SERIAL_BAUD_RATE);
  ESP8266_Serial.begin(ESP8266_SOFT_SERIAL_BAUD_RATE);
  pinMode(RST_PIN_ESP8266, OUTPUT);
  Reset_ESP8266();
  while(ESP8266_Serial.available()) {
    getIP();  // Obtain IP for ESP8266
  }
  delay(1000);
  //Increase accuracy
  analogReference(INTERNAL);
  //Start Sensor Calibration
  #ifdef MEASURE_SALINE
    Serial.print(". . . CALIBRATING SYSTEM . . .\n");
    #ifdef PRINT_DEBUG
      Serial.println("\n\nTime Elapsed  :\n\n");
    #endif

    here:
    unsigned long currentTime = millis();
    unsigned long elapsedTime = currentTime - StartTime;

    #ifdef PRINT_DEBUG
      Serial.println(elapsedTime);
    #endif

    if(elapsedTime < 20000) {
      initCount++;
      rawValue += analogRead(LM35);
      #ifdef PRINT_DEBUG
        Serial.println(rawValue);
      #endif
      goto here;
    }
    currentTime = 0;
    elapsedTime = 0;
    rawValue = rawValue / initCount;
    //Averaging from 5000 sensor samples
    initRawValue = rawValue;
    START_VALUE = initRawValue;
    Serial.println("\n. . . CALIBRATION COMPLETE . . .");
    Serial.print("\nInitial Raw LM35 Value  : ");
    Serial.print(START_VALUE);
    Serial.print("\n\n");
    Reinitialize_Variables();
    delay(2000);

    #ifdef PRINT_DEBUG
      Serial.println("\nLM35 Sample Count:\n");
      Serial.println(initCount);
    #endif

  #endif
  initCount = 0;

  #ifdef LM35_RAW_DEBUG
    Serial.println("\n. . . STARTING LM35 DEBUG READING . . .\n\n");
  #endif

  #ifdef MEASURE_SALINE
    Serial.println("\n. . . STARTING SALINE MONITORING. . .\n\n");
  #endif
}

void loop() {
  #ifdef MEASURE_SALINE
    Measure_Saline();
  #endif

  #ifdef LM35_RAW_DEBUG
    rawValue = analogRead(LM35);
    Serial.println(rawValue);
  #endif

  #ifdef TEMP_READ
    Read_Temp();
  #endif

  Reinitialize_Variables();
}

void Measure_Saline() {
  int dont_print_flag = 0;
  unsigned long StartTime = millis();
  //Take readings (SAMPLE_RATE times) and average them
  here:
  unsigned long currentTime = millis();
  unsigned long elapsedTime = currentTime - StartTime;

  #ifdef PRINT_DEBUG
    Serial.println(elapsedTime);
  #endif

  if(elapsedTime < SAMPLE_RATE) {
    initCount++;
    rawValue += analogRead(LM35);
    #ifdef PRINT_DEBUG
      Serial.println(rawValue);
    #endif
    goto here;
  }
  currentTime = 0;
  elapsedTime = 0;
  rawValue = rawValue / initCount;

  #ifdef PRINT_DEBUG
    Serial.print("initCount  : ");
    Serial.print(initCount);
  #endif
  if(saline_status_flag != SALINE_EXHAUSTED) {
    if(rawValue < START_VALUE) {
      saline_status_flag = SALINE_STARTED;
    } else if(rawValue == START_VALUE) {
      saline_status_flag = SALINE_IN_PROGRESS;
    } else if(rawValue > START_VALUE) {
      START_VALUE = rawValue;
      delay(1000);
      rawValue = analogRead(LM35);
      delay(10);
      if(rawValue > START_VALUE) {
        saline_status_flag = SALINE_EXHAUSTED;
        dont_print_flag = 1;
        Serial.print(rawValue);
        Serial.print("  Saline bottle EXHAUSTED\n");
        finalMSG = (String(rawValue) + " EXHAUSTED\n");
        ESP8266_Serial.println(finalMSG);
      }
    }
    //Saline Therapy Ongoing
    if((saline_status_flag == SALINE_STARTED || saline_status_flag == SALINE_IN_PROGRESS) && dont_print_flag == 0) {
      Serial.print(rawValue);
      Serial.print("  Saline Therapy IN PROGRESS\n");
      finalMSG = (String(rawValue) + " IN PROGRESS\n");
      ESP8266_Serial.println(finalMSG);
    } else if(saline_status_flag == SALINE_EXHAUSTED && dont_print_flag == 0) {
      //Saline Exhausted
      Serial.print(rawValue);
      Serial.print("  Saline bottle EXHAUSTED\n");
      finalMSG = (String(rawValue) + " EXHAUSTED\n");
      ESP8266_Serial.println(finalMSG);
    }
    START_VALUE = rawValue;
  } else {
    Serial.print("  Saline bottle EXHAUSTED\n");
    finalMSG = (String(rawValue) + " EXHAUSTED\n");
    ESP8266_Serial.println(finalMSG);
  }
  delay(200);
}

void Read_Temp() {
  rawValue = analogRead(LM35);
  tempC = rawValue * 0.48828125;
  tempC = rawValue / 9.31;
  Serial.println(tempC);
  delay(2000);
}

void Reinitialize_Variables() {
  initCount = 0;
  rawValue = 0;
  initRawValue = 0;
  i = 0;
}

void getIP() {
  Serial.println(ESP8266_Serial.readStringUntil('\n'));
}

void Reset_ESP8266() {
  pinMode(RST_PIN_ESP8266, OUTPUT);
  digitalWrite(RST_PIN_ESP8266, HIGH);
  // (RST_PIN_ESP8266 = 1 -> RESET = 0 so ESP8266 RESET FALSE)
  delay(1000);
  digitalWrite(RST_PIN_ESP8266, LOW);
  // (RST_PIN_ESP8266 = 0 -> RESET = 1 so ESP8266 RESET TRUE)
  delay(1000);
  digitalWrite(RST_PIN_ESP8266, HIGH);
  // (RST_PIN_ESP8266 = 1 -> RESET = 0 so ESP8266 RESET FALSE)
  delay(50);
}

```

ESP8266 side:

```
/*
 * This Code is for the ESP8266 WiFi Module. It builds a website running AJAX (Asynchronous JavaScript and XML)
 * which allows this webpage to update itself without having to refresh itself which may not be resource friendly
 */

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

#define DEVICE_ID 1

ESP8266WebServer server(80);
const char* ssid="COLDSPOT";  // WiFi Access Point to connect to
const char* password="1234567890"; // Password for the Access Point
String webSite,javaScript,XML;

void buildWebsite() {
  buildJavascript();
  webSite = "<!DOCTYPE HTML>\n";
  webSite += javaScript;
  webSite += "<BODY onload='process()'>\n";
  webSite += "<h1 align='center'><BR>SALINE MONITORING:<BR><h1>\n";
  webSite += "STATUS = <A id='runtime'></A>\n";
  webSite += "</BODY>\n";
  webSite += "</HTML>\n";
}

void buildJavascript() {
  javaScript = "<SCRIPT>\n";
  javaScript += "var xmlHttp=createXmlHttpObject();\n";
  javaScript += "function createXmlHttpObject(){\n";
  javaScript += " if(window.XMLHttpRequest){\n";
  javaScript += "    xmlHttp=new XMLHttpRequest();\n";
  javaScript += " }else{\n";
  javaScript += "    xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');\n";
  javaScript += " }\n";
  javaScript += " return xmlHttp;\n";
  javaScript += "}\n";
  javaScript += "function process(){\n";
  javaScript += " if(xmlHttp.readyState==0 || xmlHttp.readyState==4){\n";
  javaScript += "   xmlHttp.open('PUT','xml',true);\n";
  javaScript += "   xmlHttp.onreadystatechange=handleServerResponse;\n"; // no brackets?????
  javaScript += "   xmlHttp.send(null);\n";
  javaScript += " }\n";
  javaScript += " setTimeout('process()',1000);\n";
  javaScript += "}\n";
  javaScript += "function handleServerResponse(){\n";
  javaScript += " if(xmlHttp.readyState==4 && xmlHttp.status==200){\n";
  javaScript += "   xmlResponse=xmlHttp.responseXML;\n";
  javaScript += "   xmldoc = xmlResponse.getElementsByTagName('response');\n";
  javaScript += "   message = xmldoc[0].firstChild.nodeValue;\n";
  javaScript += "   document.getElementById('runtime').innerHTML=message;\n";
  javaScript += " }\n";
  javaScript += "}\n";
  javaScript += "</SCRIPT>\n";
}

void buildXML() {
  XML = "<?xml version='1.0'?>";
  XML += "<response>";
  XML += DataFromArduino(); //incoming data from Arduino. It means it is the value of mapping function.
  XML += "</response>";
}

String DataFromArduino() {
  String coming;
  if(Serial.available()) {
    while(Serial.available()) {
      coming = Serial.readStringUntil('\n');
      delay(1);
    } // it is getting via serial port.
    return coming;
  } else {
    return coming;
  }
}

void handleWebsite() {
  buildWebsite();
  server.send(200,"text/html",webSite);
}

void handleXML() {
  buildXML();
  server.send(200,"text/xml",XML);
}

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid,password);  //trying to connect the modem
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  WiFi.mode(WIFI_STA);
  Serial.println("\n\n. . . BOOTING ESP8266 . . .\n");
  Serial.print("DEVICE ID : ");
  Serial.print(DEVICE_ID);
  Serial.print("\n");
  Serial.print("CONNECTED TO ACCESS POINT :  ");
  Serial.println(ssid);
  Serial.flush();
  Serial.println(WiFi.localIP());
  //it is sending the IP to Arduino's port. So I can see the IP on Serial Monitor
  Serial.flush();
  server.on("/", handleWebsite);
  //it is all about setting of server.
  server.on("/xml",handleXML);
  server.begin();
}

void loop() {
  server.handleClient();
}

```

Please note that I have already changed the baud rate of the ESP8266 to 9600. I am using THIS ESP8266 Module.

# Answer
If you take the variable `String coming` out of the function `DataFromArduino()` and make it a global variable (by adding it to the line after String website1). That way it will store its value between calls to `DataFromArduino()` and return the same result if it has had nothing new.
> 0 votes

---
Tags: arduino-uno, esp8266, lm35
---


title: Help with arduino float

text:
# Question
Title: Help with arduino float
I am having trouble with this code:

```
#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

int button_pin=5;
int button_state;
void setup()
{
  Serial.begin(115200);

  // Initialize MPU605
  while(mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  pinmode(button_pin,INPUT)
}

void loop()
{
  int button_state=digitalRead(button_pin)

  timer = millis();

  // Read normalized values
  Vector norm = mpu.readNormalizeGyro();

  // Calculate Pitch, Roll and Yaw
  pitch = pitch + norm.YAxis * timeStep;
  roll = roll + norm.XAxis * timeStep;
  yaw = yaw + norm.ZAxis * timeStep;

  // Output raw
  Serial.print(" Pitch = ");
  Serial.print(pitch);
  Serial.print(" Roll = ");
  Serial.print(roll);
  Serial.print(" Yaw = ");
  Serial.println(yaw);

  // Wait to full timeStep period
  delay((timeStep*1000) - (millis() - timer));
}

```

But when I add this code at the end:

```
If (pitch <=90 && pitch => 15 && button_state =(HIGH))
{
}

```

I keep getting this error:

> error: lvalue required as left operand of assignment

I know the issue is about the pitch part of the if. I just need to know how to fix it.

# Answer
You have two declarations of button\_state. This won't cause a problem because the scoping rules will mean inside loop you are using the local one and everywhere else you are using the global one. Personally I would remove the global one since you aren't using it.

As mentioned in the comments you have mistyped the `If` keyword (but I think this is just on here not in you code) and you have used an assignment statement rather than a equivalence (= instead of ==).

Since you have tagged it as code review here are some minor points you might want to consider.

If a value doesn't change then you could mark it as `const`, this doesn't make much difference to the compiler, it already knows, but it will help you when you come back to the code next week. So: `const int button_pin = 5;`

If you only use a `const int` value **once** you might be better `#defining` it (more than once a const value *should* produce smaller code). The pre-processor (part of the compile process) will replace the defined name with the value, but you have easier to read and maintain code. So: `#define button_pin 5`

If you `#define` an int then **always** enclose the value in brackets to protect it from "arithmetic issues" (I can't think of a better way of describing it). So: `#define button_pin (5)`
> 1 votes

# Answer
The first thing I noticed was that you had a capital `I` in your if-statement.

Secondly, `button_state =(HIGH)` should be `button_state == HIGH`. A single `=` sign means that you are assigning a value to the variable on the left - in this case `button_state`. It is a common mistake that I have made many times.

Also, because it is a boolean comparison, you can simplify the statement by removing the `== HIGH` leaving just `button_state`.

This would then change the if-statement to the following:

```
if ((pitch <= 90) && (pitch => 15) && button_state)

```

I have added extra parentheses for clarity/readability but they're technically not needed.

---

In addition to what Code Gorilla has already stated in his answer and a few additional semi-colons, your code should look something like this:

```
#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

const int button_pin = 5;

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

  // Initialize MPU605
  while(mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  pinmode(button_pin,INPUT);
}

void loop()
{
  int button_state = digitalRead(button_pin);

  timer = millis();

  // Read normalized values
  Vector norm = mpu.readNormalizeGyro();

  // Calculate Pitch, Roll and Yaw
  pitch = pitch + norm.YAxis * timeStep;
  roll = roll + norm.XAxis * timeStep;
  yaw = yaw + norm.ZAxis * timeStep;

  // Output raw
  Serial.print(" Pitch = ");
  Serial.print(pitch);
  Serial.print(" Roll = ");
  Serial.print(roll);
  Serial.print(" Yaw = ");
  Serial.println(yaw);

  if ((pitch <= 90) && (pitch => 15) && button_state)
  {
      // Code goes here
  }

  // Wait to full timeStep period
  delay((timeStep*1000) - (millis() - timer));
}

```
> 1 votes

# Answer
In the if statement:

```
if (pitch <=90 && pitch => 15 && button_state =(HIGH))

```

you assign a new value to button\_state, which is illegal.

This should read:

```
if (pitch <=90 && pitch => 15 && button_state == HIGH)

```
> 0 votes

---
Tags: code-review, coding-standards
---


title: The sensors don't send correct data

text:
# Question
Title: The sensors don't send correct data
I try to make a weather station, but I don't understand why it doesn't work. I had tried to read a lot of the sensors but I doesn't find my errors.

The code:

```

 #include "DHT.h"
 #include "SFE_BMP180.h"
 #include "Wire.h"
 #include "MQ135.h"
 #include "SPI.h"
 #include "Adafruit_GFX.h"
 #include "Adafruit_ILI9341.h"

#define DHTPIN 2
 #define DHTTYPE DHT11
 DHT dht(DHTPIN, DHTTYPE);

SFE_BMP180 bmp180;
 double PresionNivelMar=1013.25;

int UVOUT = A3;
 int REF_3V3 = A1;

#define PIN_MQ135 A0
 MQ135 mq135_sensor = MQ135(PIN_MQ135);

#define TFT_DC 9
 #define TFT_CS 10
 Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

void setup() {
  Serial.begin(9600);
  dht.begin();
  if (bmp180.begin())
          Serial.println("BMP180 iniciado correctamenten");
        else {
          Serial.println("Error al iniciar el BMP180");
        }
  pinMode(UVOUT, INPUT);
  pinMode(REF_3V3, INPUT);

tft.begin();
  tft.setRotation(0);
  tft.fillScreen(ILI9341_BLACK);
  tft.setTextColor(ILI9341_DARKGREEN);
  tft.setTextSize(2);
  tft.setCursor(70,20);
  tft.print("S.E.M.S.");
  tft.setTextSize(1);
  tft.setTextColor(ILI9341_WHITE);
  tft.setCursor(20,310);
  tft.print("Colegio Panamericana");
  tft.setTextSize(1.5);
}

void loop() {
  char a;
  double T,P,A;
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float rzero = mq135_sensor.getRZero();
  float correctedRZero = mq135_sensor.getCorrectedRZero(t, h);
  float resistance = mq135_sensor.getResistance();
  float correctedresistence = mq135_sensor.getCorrectedResistance(t, h);
  float ppm = mq135_sensor.getPPM();
  float correctedPPM = mq135_sensor.getCorrectedPPM(t, h);

Serial.println();
  Serial.print("Temperatura: ");
  Serial.print(t);
  Serial.print(" °C ");
  Serial.println();
  Serial.print("Humedad: ");
  Serial.print(h);
  Serial.print(" %RH");
  Serial.println();

a = bmp180.startTemperature();
  if (a != 0) {

    delay(a);
    a = bmp180.getTemperature(T);
     if (a != 0) {
         a = bmp180.startPressure(3);
        if (a != 0) {

                  delay(a);

                        a = bmp180.getPressure(P,T);
                 if (a != 0) {

                  A= bmp180.altitude(P,PresionNivelMar);
                 }

              }

           }

       }

Serial.print("Temperatura: ");
  Serial.print(T);
  Serial.print(" °C , ");
  Serial.println();
  Serial.print("Presion: ");
  Serial.print(P);
  Serial.print(" mb");
  Serial.println();
  Serial.print("Altitud: ");
  Serial.print(A);
  Serial.print(" m s.n.m.");

  Serial.println();

int uvLevel = averageAnalogRead(UVOUT);
  int refLevel = averageAnalogRead(REF_3V3);
  float outputVoltage = 3.3 / refLevel * uvLevel;
  float uvIntensity = mapfloat(outputVoltage, 0.99, 2.8, 0.0, 15.0);

Serial.print("Output: ");
  Serial.print(refLevel);
  Serial.print(" v");
  Serial.println();
  Serial.print("ML8511 output: ");
  Serial.print(uvLevel);
  Serial.print(" v");
  Serial.println();
  Serial.print("ML8511 voltage: ");
  Serial.print(outputVoltage);
  Serial.print(" v");
  Serial.println();
  Serial.print("UV Intensity (mW/cm^2): ");
  Serial.print(uvIntensity);
  Serial.println();
  Serial.print("MQ135 RZero: ");
  Serial.print(rzero);
  Serial.println();
  Serial.print("Corregido RZero: ");
  Serial.print(correctedRZero);
  Serial.println();
  Serial.print("Resistance: ");
  Serial.print(resistance);
  Serial.println();
  Serial.print("Corregido Resistencia: ");
  Serial.print(correctedresistence);
  Serial.println();
  Serial.print("PPM: ");
  Serial.print(ppm);
  Serial.println();
  Serial.print("Corregido PPM: ");
  Serial.print(correctedPPM);
  Serial.println("ppm");
  Serial.println();

escribir(14,40,1,"ILI9341_GREEN","Temperatura");
  escribir(14,60,0.6,"ILI9341_RED",String(t));
  escribir(14,60,0.6,"ILI9341_RED","°C");
  escribir(14,80,1,"ILI9341_GREEN","Humedad");
  escribir(14,100,0.6,"ILI9341_BLUE",String(h));
  escribir(14,100,0.6,"ILI9341_BLUE","%RH");
  escribir(14,120,1,"ILI9341_GREEN","Presión");
  escribir(14,140,0.6,"ILI9341_LIGHTGREY",String(P));
  escribir(14,140,0.6,"ILI9341_LIGHTGREY","psi");
  escribir(14,160,1,"ILI9341_GREEN","Calidad del Aire");
  escribir(14,180,0.6,"ILI9341_CYAN",String(correctedPPM));
  escribir(14,180,0.6,"ILI9341_CYAN","ppm");
  escribir(14,200,1,"ILI9341_GREEN","Radiación UV");
  escribir(14,220,0.6,"ILI9341_MAGENTA",String(uvIntensity));
  escribir(14,220,0.6,"ILI9341_MAGENTA","mW/cm^2");
}

int averageAnalogRead(int pinToRead) {
  byte numberOfReadings = 8;
  unsigned int runningValue = 0;
  for(int x = 0 ; x < numberOfReadings ; x++)
          runningValue += analogRead(pinToRead);
          runningValue /= numberOfReadings;
    return(runningValue);

}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

void escribir(int X,int Y, int tam, short color, String mensaje){
  tft.setCursor(X,Y);
  tft.setTextSize(tam);
  tft.setTextColor(color);
  tft.print(mensaje);
}

```

Also I adds a little screen.

I make this:

Sorry for the size, the original image was too heavy to upload, in addition to the disorder.

I bought on: naylampmechatronics.com . And I used his information. And I read a bit of adafruit.com

# Answer
The method for troubleshooting is:

1. Disconnect everything.
2. Add one sensor.
3. Verify if the sensor works.
4. If it works repeat step 2 for next sensor.
5. If it doesn't work, why? is it the connections correct?
> 2 votes

---
Tags: arduino-nano, adafruit
---


title: Running Atmega1284P at 3.3 and 8Mhz

text:
# Question
Title: Running Atmega1284P at 3.3 and 8Mhz
can i run Atmega1284P at 3.3V and 8Mhz speed.? can i burn Nick Gammon Arduino bootloaders into the chip.?

Thank You

# Answer
> 1 votes
Atmega1284P 8MHz @ 3.3V?

Yes, you can. Documentation states this is permitted voltage for that frequency: 0 - 10MHz @ 2.7V - 5.5V http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42719-ATmega1284P\_Datasheet.pdf

Nick Gammon Arduino bootloaders?

On this page http://www.gammon.com.au/bootloader it states Atmega1284. In code https://github.com/nickgammon/arduino\_sketches/blob/master/Atmega\_Self\_Read\_Signature/Atmega\_Self\_Read\_Signature.ino there is signature for Atmega1284P so it should work without issues.

---
Tags: arduino-uno, arduino-mega, bootloader
---


title: Incomplete serial string input

text:
# Question
Title: Incomplete serial string input
I am using an Arduino M0 Pro and have a device connected via Pin 0 and 1 of it. So I am using the predefined Serial5 interface to receive data from it. I have the following code snippet/method that tries to read an answer from Serial5 if it is available. Otherwise it returns an empty string.

```
String read_answer() {
  String str = "";
  // Check if bytes are available
  if (Serial5.available()) {
    char c;
    // Read an character unless the read() method returns -1
    // The -1 is identical to 255
    while ((c = Serial5.read()) != 255) {
      // Append the read character to the string array
      str.concat(c);
    }

    // Output the string on the serial debug interface
    Serial.print("Read: \"");
    Serial.print(str);
    Serial.print("\"\n");
  }
  // Return the read string
  return str;
}

```

If I send an the following string "ABCDEF HIJKL MNOPQR" via an FTDI towards it the first times it correctly printed :

```
Read: "ABCDEF HIJKL MNOPQR"

```

But suddenly it just stops reading the complete string. The output is something like that:

```
Read: "ABCDEF HIJKL MN

```

It is just cut off and everything stops working, over and over again. It might be a very stupid mistake but I don't know where to check next. If I missed something to explain or more context is needed pls tell me.

# Answer
Your code has no idea when the string is finished. At the moment it is just waiting until the receive buffer is empty (`Serial.read()` returns -1), but since serial is a *slow* protocol that could happen at any time, not just at the end of the string.

You need something to terminate your string so it knows when the end is. The most common way is to use a line feed character (`\n`, character 10) or a carriage return (`\r`, character 13) or a combination of the two.

```
char c;
while ((c = Serial5.read()) != '\n') {
    if (c != 255) {
        str.concat(c);
    }
}

// Output the string on the serial debug interface
Serial.print("Read: \"");
Serial.print(str);
Serial.print("\"\n");

```
> 1 votes

---
Tags: serial
---


title: LEDs not working with tone() function

text:
# Question
Title: LEDs not working with tone() function
I have a strange issue. I have 3 LEDs, each is supposed to beep with a correlated tone... Imagine the beginning of a racing game (beeping with traffic lights). Here's my code:

```
#include "pitches.h"

//Beginning Melody
int melody[] = {
  NOTE_C3, NOTE_C3, NOTE_C4
};

//Beginning Note Durations
int noteDurations[] = {
  2, 2, 1
};

int redLight = 3;
int yellowLight = 5;
int greenLight = 6;

void setup() {
  Serial.begin(9600); //initialize serial communication

  pinMode(redLight, OUTPUT);
  pinMode(yellowLight, OUTPUT);
  pinMode(greenLight, OUTPUT);
}

void loop() {
  playBegin();
  delay(5000);
}

void playBegin(){
  int lightColor = 1;

  for (int thisNote = 0; thisNote < 3; thisNote++) {

    if(lightColor == 1){
      analogWrite(redLight, HIGH);
    }else if (lightColor == 2){
      analogWrite(yellowLight, HIGH);
    }else{
      analogWrite(greenLight, HIGH);
    }
    lightColor++;

    int noteDuration = 1000 / noteDurations[thisNote];
    tone(11, melody[thisNote], noteDuration);
    delay(1000);
    noTone(11);

    analogWrite(redLight, LOW);
    analogWrite(yellowLight, LOW);
    analogWrite(greenLight, LOW);
  }
}

```

Originally, the 3 LEDs would light up correctly. The red light is plugged into Pin 3, the yellow light into Pin 5, and the green light into Pin 6. HOWEVER, when I added in the tones, the red light (in Pin 3) doesn't light up. The 3 tones still sound off correctly, and the yellow and green LEDs work perfectly fine. This is ONLY not working for the red LED, it just doesn't light up while the 1st tone happens.

When I take out the line of code where tone() is, it works fine and the red light will turn on at the correct time again. This is ONLY happening when the tone() function is included.

To be clear, this is the exact line of code that is affecting the red LED:

```
tone(11, melody[thisNote], noteDuration);

```

Furthermore, I swapped the pins of the yellow and red LEDs to see if it was an issue with the red LED, and it was not. It's whatever LED is plugged into Pin 3, and again, ONLY when the tone() function is in the code as well. I'm not sure how they're conflicting. This does not appear to be an issue with my hardware.

I'm working with Arduino Uno. If you need anymore info, let me know.

Thanks!

# Answer
You have a timer conflict.

`tone()` uses a timer, and `analogWrite()` on certain pins uses the same timer.

Quite why you're using `analogWrite()` though, with `HIGH` (which equates to `1`) as the duty cycle I don't quite understand. I would have though `digitalWrite()` would be a better choice. A duty cycle of 1 would be pretty much invisible anyway...
> 2 votes

# Answer
If you read the documentation for the tone function ( https://www.arduino.cc/en/Reference/Tone ), you might notice this line:

```
Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

```
> 0 votes

# Answer
Following on from the information provided by Majenko and Delta\_G and a minor modification/simplification, here is the resulting code:

```
#include "pitches.h"

//Beginning Melody
int melody[] = {
  NOTE_C3, NOTE_C3, NOTE_C4
};

//Beginning Note Durations
int noteDurations[] = {
  2, 2, 1
};

int redLight = 3;
int yellowLight = 5;
int greenLight = 6;

void setup() {
  Serial.begin(9600); //initialize serial communication

  pinMode(redLight, OUTPUT);
  pinMode(yellowLight, OUTPUT);
  pinMode(greenLight, OUTPUT);
}

void loop() {
  playBegin();
  delay(5000);
}

void playBegin(){
  for (int thisNote = 0; thisNote < 3; thisNote++) {

    if(thisNote == 0){
      digitalWrite(redLight, HIGH);
    }else if (thisNote == 1){
      digitalWrite(yellowLight, HIGH);
    }else{
      digitalWrite(greenLight, HIGH);
    }

    int noteDuration = 1000 / noteDurations[thisNote];
    tone(11, melody[thisNote], noteDuration);
    delay(1000);
    noTone(11);

    digitalWrite(redLight, LOW);
    digitalWrite(yellowLight, LOW);
    digitalWrite(greenLight, LOW);
    delay(200);
  }
}

```
> 0 votes

---
Tags: arduino-uno, led, sound, speaker
---