body:
I've got this project that that is using the LiquidCrystal.h library. My import looks like this...

    #import <LiquidCrystal.h>

I've tried making a 'libraries' folder in my repo, and copying the LiquidCrystal directory from arduino's global libraries folder to my_project/libraries and changing my import to...

    #import "libraries/LiquidCrystal/LiquidCrystal.h"

and it explodes on me. I know the path is right, because it gives me a different error if I change the import path to be wrong... but even when it's right, I get this traceback...

    Arduino: 1.8.1 (Mac OS X), TD: 1.36, Board: "Arduino/Genuino Uno"

    /var/folders/sz/cdsmvqws6rq9839mhd802prm0000gp/T//cc4gIISN.ltrans0.ltrans.o: In function `__static_initialization_and_destruction_0':
    /Users/chris/art/greenhouse/greenhouse/greenhouse.ino:36: undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
    etc....

What's the deal? Aren't I supposed to be able to import libraries with an absolute path to the library? This is literally the same file.

What is the difference between `#import <foo.h>` and `#import "my_libraries/myfoo.h"` ?

title: How can I move an arduino library into my project repo and use it from there?

Answers: 2

body:
> What's the deal? Aren't I supposed to be able to import libraries with
> an absolute path to the library? This is literally the same file.

Yes you can use both absolute and relative paths, but "libraries/LiquidCrystal/LiquidCrystal.h" is a relative path because it doesn't start from `C:\\` or `/` basically. Also make sure you get the `LiquidCrystal.cpp` file which actually contains all the functions `LiquidCrystal.h` specifies.

> What is the difference between #import <foo.h> and #import
> "my_libraries/myfoo.h" ?

`#include "my_libraries/myfoo.h"` specifies that `myfoo.h` is in a folder `my_libraries` first searched for in `current_folder/my_libraries/myfoo.h` then quote directories and rest of the search paths later, `#include <foo.h>` specifies that `foo.h` is a system header, it's only searched for in search paths.

Solution here would be saying inside your sketch that it is in a subfolder, that the folder is one folder below and then two folders deeper for ex. `#include "../libraries/LiquidCrystal/LiquidCrystal.h"` this here assumes your sketch is in `root_folder/Sketch/Sketch.ino` and library in `root_folder/libraries/LiquidCrystal/LiquidCrystal.h`.

body:
Try it with this folder structure:

    my_project
    |_src
      |_LiquidCrystal

and change the import to:

    #import "src/LiquidCrystal/LiquidCrystal.h"

Since Arduino IDE 1.6.10, recursive compilation of the sketch folder has been limited to the `src` subfolder (see [Arduino/arduino-builder#148](https://github.com/arduino/arduino-builder/pull/148)).

By the way, it's much more common to use `#include` instead of `#import`, which is deprecated and will cause a compiler warning. Any properly written library will not require the use of `#import`.


body:
        //set initial values
    int x = 0; // set initail zero value for the counter
    int preE = 512; // set initial value for light intensity in east direction
    int preW = 512; // set initial value for light intensity in west direction
    int predtime = 512; // set initial value for delay time
    int pretol= 512; // set initial value for tolerance value
    void setup() {
      Serial.begin(9600); // set the baud rate for the serial monitor

      // first set the relays off
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      digitalWrite(7,HIGH);
      digitalWrite(8,HIGH); // began the loop
    }

      void loop()
      {
        // Read the first reading

        //read the east LDR
        int E1 = analogRead(5); //read the west LDR
        int W1 = analogRead(4); // read the delay time potentiometer
        int dtime1 = analogRead(1);
        //read the tolerance potentiometer
         int tol1 = analogRead(0); // Check if the readings reasonable, otherwise set them to previous ones.

    if (E1 < 10 || E1 > 1000 )
    {
      E1 = preE ;
      }
      if (W1 < 10 || W1 > 1000 )
      {
        W1 = preW ;
        }
        if (dtime1 < 10 || dtime1 > 1000 )
        {
          dtime1 = predtime ;
          }
          if (tol1 < 10 || tol1 > 1000)
          {
            tol1 = pretol ;
            }
            delay(100); // delay for one 0.1 second and take the next reading

            int E2= analogRead(5);
            int W2= analogRead(4);
            int dtime2= analogRead(1);
            int tol2= analogRead(0);
            if (E2 < 10 || E2 > 1000 )
            {
              E2= preE ;
            }

    if (W2 < 10 || W2 > 1000 )
    {
      W2= preW ;
      }
      if (dtime2 < 10 || dtime2 > 1000 )
      {
        dtime2= predtime ;
        }
        if (tol2 < 10 || tol2 > 1000 )
        {
          tol2= pretol ;
          }
          delay(100); // delay for one 0.1 second and take the third reading

          int E3= analogRead(5);
          int W3= analogRead(4);
          int dtime3= analogRead(1);
          int tol3= analogRead(0);
          if (E3 < 10 || E3 > 1000 )
          {
            E3= preE ;
            }
            if (W3 < 10 || W3 > 1000 )
            {
              W3= preW ;
              }
              if (dtime3 < 10 || dtime3 > 1000 )

    {
      dtime3= predtime ;
      }
      if (tol3 < 10 || tol3 > 1000 )
      {
        tol3= pretol ;
        }
        int E4 = analogRead(5);
        int W4 = analogRead(4);
        int dtime4= analogRead(1);
        int tol4= analogRead(0);
        if (E4 < 10 || E4 > 1000 )
        {
          E4= preE ;
          }
          if (W4 < 10 || W4 > 1000 )
          {
            W4= preW ;
            }
            if (dtime4 < 10 || dtime4 > 1000 )
            {
              dtime4= predtime ;
              }
              if (tol4 < 10 || tol4 > 1000 )
              {
                tol4= pretol ;
                }

    delay(100);
    int E5 = analogRead(5);
    int W5 = analogRead(4);
    int dtime5= analogRead(1);
    int tol5= analogRead(0);
    if (E5 < 10 || E5 > 1000 )
    {
      E5= preE ;
      }
      if (W5 < 10 || W5 > 1000 )
      {
        W5= preW ;
        }
        if (dtime5 < 10 || dtime5 > 1000 )
        {
          dtime5= predtime ;
          }
          if (tol5 < 10 || tol5 > 1000 )
          {
            tol5= pretol ;
          }
          delay(100);
          int E6 = analogRead(5);
          int W6 = analogRead(4);
          int dtime6= analogRead(1);
          int tol6= analogRead(0); if (E6 < 10 || E6 > 1000 )
          {
    E6= preE ;
    }
    if (W6 < 10 || W6 > 1000 )
    {
      W6= preW ;
      }
      if (dtime6 < 10 || dtime6 > 1000 )
      {
        dtime6= predtime ;
        }
        if (tol6 < 10 || tol6 > 1000 )
        {
          tol6= pretol ;
          }
          delay(100);
          int E7 = analogRead(5);
          int W7 = analogRead(4);
          int dtime7= analogRead(1);
          int tol7= analogRead(0);
          if (E7 < 10 || E7 > 1000 )
          {
            E7= preE ;
            }
            if (W7 < 10 || W7 > 1000 )
            {
              W7= preW ;
              }
              if (dtime7 < 10 || dtime7 > 1000 )

    {
      dtime7= predtime ;
      }
      if (tol7 < 10 || tol7 > 1000 )
      {
        tol7= pretol ;
        }
        delay(100);
        int E8 = analogRead(5);
        int W8 = analogRead(4);
        int dtime8= analogRead(1);
        int tol8= analogRead(0);
        if (E8 < 10 || E8 > 1000 )
        {
          E8= preE ;
          }
          if (W8 < 10 || W8 > 1000 )
          {
            W8= preW ;
            }
            if (dtime8 < 10 || dtime8 > 1000 )
            {
              dtime8= predtime ;
              }
              if (tol8 < 10 || tol8 > 1000 )
              {
                tol8= pretol ;
                }

    delay(100);
    int E9 = analogRead(5);
    int W9 = analogRead(4);
    int dtime9= analogRead(1);
    int tol9= analogRead(0);

    {
    if (E9 < 10 || E9 > 1000 )
    {
      E9= preE ;
      }
    {
      if (W9 < 10 || W9 > 1000 )
      {
        W9= preW ;
        }
    {
        if (dtime9 < 10 || dtime9 > 1000 )
        {
          dtime9= predtime ;
          }
    {
          if (tol9 < 10 || tol9 > 1000 )
          {
            tol9= pretol ;
            }
            delay(100);
            int E10 = analogRead(5);
            int W10 = analogRead(4);
            int dtime10= analogRead(1);
            int tol10= analogRead(0);

              if (E10 < 10 || E10 > 1000 )

            {
    E10= preE ;
    }
    {
    if (W10 < 10 || W10 > 1000 )
    {
      W10= preW ;
      }
      {
      if (dtime10 < 10 || dtime10 > 1000 )
      {
        dtime10= predtime ;
        }
        {
        if (tol10 < 10 || tol10 > 1000 )
        {
          tol10= pretol ;
          }

          //Average the ten readings

       int E=(E1+E2+E3+E4+E5+E6+E7+E8+E9+E10)/10;

       //light intensityin east
       int W =(W1+W2+W3+W4+W5+W6+W7+W8+W9+W10)/10;

       // light intensity in west
       int dtime=(dtime1+dtime2+dtime3+dtime4+dtime5+dtime6+dtime7+dtime8+dtime9+dtime10)/10;

       int tol = (tol1+tol2+tol3+tol4+tol5+tol6+tol7+tol8+tol9+tol10)/10;// tolerance value
       int delaytime = (dtime *10);// increase the delay by magnitude of 10
       int tolerance = tol / 40;

       // display the readings through serial monitor
       Serial.println("Light intesity in the East");
       Serial.println(E);
       Serial.println(" ");
       Serial.println("Light intesity in the west");
       Serial.println(W);
       Serial.println(" ");
       Serial.println("delay time");
       Serial.println(delaytime);
       Serial.println(" ");
       Serial.println("tolerance");
       Serial.println(tolerance);

       //check the differenc and open the coresponding relays

       // check the diffirence of light intensity in east and west
       int diff = E - W;

       // check if the diffirence is in the tolerance else rotates the motor
       {
       if (-1*tolerance > diff || diff > tolerance)

       {
        if (E > W)// check if light intensity in east is greater than in west

        {
          if ( x <30)// check counter to ensure the motor does not run infinitely

        {
          Serial.println("Turn motors towards east");

       digitalWrite(7, LOW);// Turn ON Relay 1

       delay(2000);

       digitalWrite(7,HIGH); //Turn OFF Relay 1
       ++x;
       }
       }
       //check if light intensity in west is greater than in east
       else if (W > E) { if (x > -30)

       {
        }
        }
       }

    Serial.println("Turn motor toward west");
    digitalWrite(8, LOW);// Turn ON Relay 4
    digitalWrite(9, LOW);
    delay(2000);
    digitalWrite(8, HIGH);//Turn OFF Relay 4
    digitalWrite(9, HIGH);
    --x;
    // decrease counter
    }
    }
    }
    //store the values for the next loop

    preE = 512;
    preW = 512;
    pretol= 512;
    predtime = 512;
    Serial.println(" ");
    Serial.println("--------------------------------------------------------------------- ");
    // delay the next loop
    delay(1000);
    }

title: someone can help please? am getting an error saying expected } at the end of input

Answers: 3

body:
You are missing five `}` at the end of your sketch.

As @Chris said, proper indentation will make your problem obvious. Use the menu Tools-AutoFormat (Ctrl-T) to format your sketch.

That's is looks like with the missing `}` added:

    //store the values for the next loop

          preE = 512;
          preW = 512;
          pretol= 512;
          predtime = 512;
          Serial.println(" ");
          Serial.println("--------------------------------------------------------------------- ");
    // delay the next loop
          delay(1000);
         }
    //--- This } are missing in your sketch
        }
       }
      }
     }
    }

body:
I mean no offence by this but you have got in such a mess because you have written monolithic code.  As a new developer you aren't expected to know this, I sure as hell didn't know it 30+ years ago.  The fact that you have posted you code on here, shows that it is too big for a normal brain to manage.  You loop function is over 300 lines long!  A screen full is about all a normal person can manage.

What I think you should do is refactor your code, look at it and pick out common blocks and turn them into functions, this will reduce the number of lines, making in it easier to read and reduce the possibility of bugs.  So firstly I notice you have this block repeated:

 if (E1 < 10 || E1 > 1000)
 {
  E1 = preE;
 }

If you wrote that as a function:

    int CheckLimits (const int& value, const int& lowerBound, const int& upperBound, const int& default)
    {
      if (value < lowerBound || value > upperBound)
        return default;
      return value;
    }
    // This means those 4 lines collapse to this one line.
    E1 = CheckLimits (E1, 10, 1000, preE);

Those 4 lines of code appear at least 39 times in loop, that's 120 lines that have just bee removed!

The `preE` value (and its pre friends) is never changed, so make it a constant and that will remove another 4 lines at the end.

Using literal numbers for your pins makes it harder to change them if you ever need to rewire.  More importantly it makes the code harder to understand, so always `#define` them at the top of you code.

If you create two variables to hold the same sort of number you should be thinking about using an array instead.  When you create E1 to E10  to hold ten readings, you should have done it in an array.  The array size should be a constant, defined in a single place, so you can change it if necessary.  And guess what, the averaging code should have been a function.

**ANYWAY**
I rewrote you code and hopefully it will explain what I mean.  Loop is down to about 90 lines now and it would be easy to make it smaller.  Yes, get a decent editor, Notepad++ or Visual Studio or Visual Code are all free, but you have to learn to think in smaller blocks, if you ever copy and paste more than one line, it probably should be a function :)

I haven't compiled it, but it should work - Please don't copy it just look at it and make your code better than this.

    //set initial values
    int x = 0; // set initial zero value for the counter
    static const int preE = 512; // set initial value for light intensity in east direction
    static const int preW = 512; // set initial value for light intensity in west direction
    static const int predtime = 512; // set initial value for delay time
    static const int pretol = 512; // set initial value for tolerance value
    // Define the PINS
    #define APIN_E (5)
    #define APIN_W (4)
    #define APIN_DTIME (1)
    #define APIN_TOL (0)
    static const int MaxReadings(10);  // The number of readings used to form the average
    int E_Reading[MaxReadings];    // Holds all the readings, not sure it is required any more, replaced by average variable.
    int W_Reading[MaxReadings];
    int dtime_Reading[MaxReadings];
    int tol_Reading[MaxReadings];

    void setup()
    {
     Serial.begin(9600); // set the baud rate for the serial monitor

          // first set the relays off
     pinMode(7, OUTPUT);
     pinMode(8, OUTPUT);
     digitalWrite(7, HIGH);
     digitalWrite(8, HIGH); // began the loop
    }

    /// Check that the given value is within the limits
    /// value: The reading to check
    /// lowerBound : The lowest acceptable value
    /// upperBound : The highest acceptable value
    /// defValue : The value to use if outside the range.
    int CheckLimits(const int& value, const int& lowerBound, const int& upperBound, const int& defValue)
    {
     if (value < lowerBound || value > upperBound)
      return defValue;
     return value;
    }

    /// Take a reading from the specified pi and check it is within the acceptable bounds.
    /// pinNumber : The Analog pin number
    /// lowerBound : The lowest acceptable value
    /// upperBound : The highest acceptable value
    /// defValue : The value to use if outside the range.
    int TakeReading(const int& pinNumber, const int& lowerBound, const int& upperBound, const int& defValue)
    {
     return CheckLimits(analogRead(pinNumber), lowerBound, upperBound, defValue);
    }

    void loop()
    {
     int Eaverage = 0;
     int Waverage = 0;
     int dtimeaverage = 0;
     int tolaverage = 0;

     // Read the first reading
     for (int index = 0; index < MaxReadings; ++index)
     { // You don't actually need the values unless you want them, TakeReading could be assigned to the average variables.
      E_Reading[index] = TakeReading(APIN_E, 10, 1000, preE);   // read the east LDR
      W_Reading[index] = TakeReading(APIN_W, 10, 1000, preW);   // read the west LDR
      dtime_Reading[index] = TakeReading(APIN_DTIME, 10, 1000, predtme); // read the delay time potentiometer
      tol_Reading[index] = TakeReading(APIN_TOL, 10, 1000, prepretol); // read the tolerance potentiometer

      Eaverage += E_Reading[index];
      Waverage += W_Reading[index];
      dtimeaverage += dtime_Reading[index];
      tolaverage += tol_Reading[index];
      delay(100);
     }

     //Average the ten readings
     Eaverage /= MaxReadings;
     Waverage /= MaxReadings;
     dtimeaverage /= MaxReadings;
     tolaverage /= MaxReadings;

     const int delaytime = (dtime * 10);// increase the delay by magnitude of 10
     const int tolerance = tol / 40;

     // display the readings through serial monitor
     Serial.println("Light intensity in the East");
     Serial.println(E);
     Serial.println(" ");
     Serial.println("Light intensity in the west");
     Serial.println(W);
     Serial.println(" ");
     Serial.println("delay time");
     Serial.println(delaytime);
     Serial.println(" ");
     Serial.println("tolerance");
     Serial.println(tolerance);

     //check the difference and open the corresponding relays

     // check the difference of light intensity in east and west
     const int diff = E - W;

     // check if the difference is in the tolerance else rotates the motor
     if (-1 * tolerance > diff || diff > tolerance)
     {
      if (E > W)// check if light intensity in east is greater than in west
      {
       if (x < 30)// check counter to ensure the motor does not run infinitely

       {
        Serial.println("Turn motors towards east");
        digitalWrite(7, LOW);// Turn ON Relay 1
        delay(2000);
        digitalWrite(7, HIGH); //Turn OFF Relay 1
        ++x;
       }
      }
      //check if light intensity in west is greater than in east
      else if (W > E)
      {
       if (x > -30)
       {
        // MISSING CODE??
       }
      }
     }
     Serial.println("Turn motor toward west");
     digitalWrite(8, LOW);// Turn ON Relay 4
     digitalWrite(9, LOW);
     delay(2000);
     digitalWrite(8, HIGH);//Turn OFF Relay 4
     digitalWrite(9, HIGH);
     --x;
     // decrease counter

     //store the values for the next loop
     Serial.println(" ");
     Serial.println("--------------------------------------------------------------------- ");
     // delay the next loop
     delay(1000);
    }

body:
usually unmatched brackets.

run your code through astyle and it will be more clear to you.


body:
I'm new to this kind of thing. My code works on my Uno without problem with two separate servos. I've ensured that it's not any faulty leads, having tried a few other circuits with LEDs, buttons and potentiometers as well, simply switching between my Uno (which works fine) and the Nano.

I've chosen the correct port, chipset and board each time and the code uploads fine to the Nano. The Nano simply refuses to do anything I tell it.

- Digital PIN of servo goes to designated D5 pin.

- Ground goes to the GND near the Analog pins (shouldn't matter which I imagine).

- Power goes to 5V.

The code above simply tells the servo to go to a certain degree when uploaded. Could anybody tell me why the servo will not move at all with the Nano? I just bought it and I haven't hooked up any power to it other than the USB, surely it isn't fried. It lights up and flashes as well.

    #include <Servo.h>
    Servo my_servo;

    void setup() {
      my_servo.attach(5);
      // Pin definition
    }

    void loop() {
      my_servo.write(60);
      // No. of degrees
    }

title: Can't move servo with my Nano

Answers: 2

body:
Connect a multi meter in series with the servo connection from the uno to the servo and see how much current it draws when working (probably less than 20ma, definitely less than 40ma). Then connect it in series with the nano and see what happens. If you get no current then you're activating the wrong pin.

If you see a current draw but the servo doesn't move then you need to use some sort of switch (transistor, FET, relay) to switch the servo. You could also compare the voltage and current read off the nano to the requirement in the datasheet for the servo. Again, this may lead you to needing a switch.

Edit based on comments above... Also try your 5v directly to the servo, then add a forward biased diode in series which should simulate the voltage drop to the level of your nano (0.4-0.6v). If the servo doesn't work with the diode and does without then you can be pretty sure the issue is insufficient volts (which is likely given the rating of 4.8v you mentioned in comments).

body: I has the same problem. Example: With Arduino Uno only conected to 5V from PC, the servos run perfectly, but with Nano no, maybe the servos try to move, but not. I charged the skecth on the arduino Nano and deesconect form pc, and then i supply Arduino Nano with baterry Li-ion 2s. In another words, for servos you must to supply over 6 volts. Be careful because the max voltage of servos,can be 6 volts, you can use the regulator of Arduino, severals servos produce overheating in this regulator. Yes my english is noob.


body:
My question is about hardware that i'll control with my arduino... Not Arduino itself (So I don't know if I'm in the right section ... :s)

My project is to create a cocktail machine at the cheapest price.

I was wondering if [this kind of solenoid piston][1] would be strong enough to seals a plastic pipe like [this one][2] ?

My idea from now is to use only 1 water pump ([as this one][3]) and connect all the pipes from the bottles with some Y and control which one is giving the liquid by controling pistons that are going to compress the tube.

I'm open to all advices you could give me and new ideas ... I saw that there's also [solenoid valves][4] ... But I only find it in 12V ... Does it exist in 5V ?

  [1]: https://www.sparkfun.com/products/11015
  [2]: https://www.gearbest.com/robot-vacuum/pp_47721.html
  [3]: https://www.banggood.com/12V-Mini-DC-Brushless-Garden-Fountain-Pump-Hydrological-Cycle-Submersible-Water-Pump-p-1009353.html?rmmds=buy
  [4]: https://www.banggood.com/12V-Electric-Solenoid-Valve-Magnetic-DC-NC-Water-Air-Inlet-Flow-Switch-12-p-1023361.html?rmmds=buy

title: Is a solenoid piston strong enough to lock a water tubling?

Answers: 1

body:
The pump you are looking at is to powerful for you application: 350 liters/hour, or little less than 5 ltr/min. It will fill a 250 ml glass in about 3 seconds!

The solenoid cost you $5 a piece, but you still need a valve and a way to attach solenoid, valve and tubing.

Also, your idea means liquids will get mixed inside the tubes. And nobody wants a trace of whiskey in his Vodka Screwdriver.

You must visit [The Inebriator][1], a cocktail mixing machine. His design have one tube for every bottle pouring liquid into the glass.

[![Cocktail Mixing Machine][2]][2]

As they note, they have in version 2.0

> Switching mixers from a pressurised system with valves to using pumps
> – This slows the pouring, but vastly simplifies the machine as a
> whole. We have a capacity for 16 pumps

They don't use valves, but pumps. I recomend a peristaltic pump ($7 on Aliexpress), like this:

[![Peristaltic pump][3]][3]

They don't touch the fluid, easy to mount, and are a very precise delivery mechanism, like in this video https://youtu.be/GdTUIwj5ros, showing an Arduino controlling a pump to 1ml precision:

[![Arduino controlled pump][4]][4]

  [1]: https://www.theinebriator.com/
  [2]: https://i.stack.imgur.com/OR8FD.jpg
  [3]: https://i.stack.imgur.com/F0bTH.jpg
  [4]: https://i.stack.imgur.com/EWYcM.jpg


body:
I'm not from electronics background so I don't know what should be the connections. My Hall sensor has 4 pins(AO, GND, +, DO)

So, I have connected hall sensor pins to Arduino nano pins in this order(connection)

    AO(Sensor) <-> A4(Arduino)   [Changed from A0 to A4]
    DO(Sensor) <-> D4(Arduino)   [Changed from D0 to D4]
    +(Sensor) <-> 5V(Arduino)
    GND(Sensor) <-> GND (Arduino)

What should be pseudo code? So that if the magnet passes close to the sensor. Arduino should get the output & I'll blink the led on Arduino

This below is my code that I have written so far

    int sensorPin = 4; // this is for sensor in analog pin 4
    int buttonPin = 4; // we are looking for digital 4
    int val;

    bool flag = false;

    void setup() {
      // put your setup code here, to run once:
      pinMode(buttonPin, INPUT); // defines digital pin 4 as input for LED
      Serial.begin(9600);
    }

    void loop() {
       int reading = analogRead(sensorPin);

       float voltage = reading * 5.0;
       voltage /= 1024.0;

      if(voltage > 3.0) {
       Serial.print(voltage); Serial.println("volts");
      }
       val = digitalRead(buttonPin);  // read data from digital Pin

       if(val == HIGH) // when the sensor detects a magnetic field
       {
          flag = !flag;
          if(flag){
             digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
          } else {                 // wait for a second
              digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
          }
          //delay(1000);                       // wait for a second
       }
       delay(100);
    }

**Expected output:** It should turn On/Off the LED when voltage goes `HIGH`

**Known issues:** It works sometime. It doesn't work sometime. Also it works only when magnet is kept clone. Doesn't detect when I'm waving magnet close to the sensor

title: connection for hall sensor 4 pin and arduino nano

Answers: 2

body:
Someone will probably post a comment saying this is not a code writing service, but I get the impression that you just need pointers, so here they are.

In the IDE you have an example on how to blink the LED, called **blink**, if you haven't already make yourself familiar with that.

I think there is an example on how to read from the analog pin, if not its **`int value = analogRead(A0);`**

Now **print** that value to the **Serial** monitor and see what happens when you start waving the magnet around.  The value will change say for 400 odd to 800 odd.

Now write an **if** statement that turns on the LED when the value you read is greater than (**>**) a certain value.

If you need any help on the code you need to write look in the Help->Reference section of the IDE, you might find the **Bold** words especially relevant :)

If you get stuck, post the code of how far you have got and people will help.

body:
The board you have has two outputs - AO and DO (note, those are the letter O not the number zero - for output).

You can connect AO to any of the analog inputs on your board if you want to read a discrete analog value from the sensor.

You can connect DO to any of the digital inputs (or analog ones since they are also digital inputs) if you just want a simple "Something is there" signal.

The sensitivity of the "something is there" is controlled by the trimmer on the board.

The simplest way of doing what you want is to use DO and adjust the trimmer to suit. Then the sensor looks, to all intents and purposes, like a switch or a button (but you don't need the pull up / pull down resistor).  So you can leave AO disconnected.

Note that using D0 (zero) and D1 (one) on the Arduino is discouraged since they are connected to the USB interface and using them can affect your ability to upload sketches. It also means you cannot use any serial communication in your program.


body:
I have the following code for a [TTL to RS-485 Adapter Module ](https://www.newegg.com/Product/Product.aspx?Item=9SIA4SR1T56020&ignorebbr=1&nm_mc=KNC-GoogleMKP-PC&cm_mmc=KNC-GoogleMKP-PC-_-pla-_-AT+-+Electronics-_-9SIA4SR1T56020&gclid=Cj0KCQjwierMBRCHARIsAHl9i4FHSB6Xl5JEhlYYHC-P1SXYl0Tb-_HCnV8KZf9hBH_MuPIc__QB3kEaAsEZEALw_wcB&gclsrc=aw.ds)

    [...code]
    digitalWrite(DE_PIN, HIGH); //directional control for adapter
    Serial2.write(Message, Size);
    Serial2.flush();
    digitalWrite(DE_PIN, LOW);  // Set To Recieve
    Serial2_reading_foo();
    [code...]

I've noticed that `DE_PIN` does not seem to go `High` fast enough before `Serial2.write()` executes I confirmed this by adding a small `delay(ms)` which made the code function perfectly.

    digitalWrite(DE_PIN, HIGH);
    delay(100);
    Serial2.write(Message, Size);
    Serial2.flush();
    digitalWrite(DE_PIN, LOW);  // Set To Recieve
    delay(100);
    Serial2_reading_foo();

Unfortunately, there's pretty much [universal agreement](http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/) that you shouldn't ever use `delay()` in programming. Plus doing any kind of wait function here seems to be insensitive to the real problem. Is there a better way to make sure that `DE_PIN==HIGH` before the Serial2.write() Function begins?

title: Make Sure Digital pin is high before Serial.write()

Answers: 1

body:
The MAX485 requires 2V on the DE pin to register a HIGH. It takes no more than an absolute maximum of 50ns for the DE pin to switch the buffers. The Arduino takes 10.4ns for an IO pin to rise to 2V.

That's an absolute maximum of 60.4ns.

One clock cycle of a 16MHz Arduino is 63ns.

That is longer than it takes for the IO pin to tell the MAX485 to switch the buffers.

You can increase that rise time by taking in to account the input capacitance of the MAX485 and the resistance of the connection between the Arduino and the DE pin, but it will still be microscopically small compared to the time between the pin going HIGH and the serial transmission starting.

So there must be something fundamentally wrong with your setup.  Two possibilities spring to mind:

1. You aren't controlling RE, only DE, so RE is floating and is being capacitively linked to DE through the parasitic capacitances of the board and circuitry, making it rise and fall very slowly.
2. You haven't set the IO pin on the Arduino to OUTPUT, so it switches between floating and HIGH through a very high resistance, causing slow rise to HIGH and maybe never getting to LOW at all.

Or a combination of the two.


body:
I am new to Arduino an working with the Uno.  My dream is to activate servos in a perticular order once some type of sensor recognizes a live person near it.  Is their a perticular easy to understand book out there I can read?  There are lots and lots of books but they all get very complex rather quickly.  I'd be curious as to fellow inventors in here telling me how they mastered the Arduino?  Maybe it was not a book but rather a complete course.  Will others please respond to help me.  ps... I do have an electronics degree so I don't need soldering or component understanding.  I know what Vcc is.  I need please some type of course book which will take me now beyond the self blinking light into robotic control if that easy to understand book or course is out there.
Thank you.  Michael in Palm Beach, FL

title: New to Arduino building

Answers: 1

body:
There are lots of examples on the official Arduino website.

My advice is you follow them, not only by reading, but buy the components you need (they are cheap) and practice and see how to handle them within the Arduino environment.

Do one component at a time (led, switch, Servo, Sensor), and focus on the servo/sensors you want to use.

Than try to combine multiple components, step by step until you have your dream project ready.

Also, try not to just copy sketches (programs), but understand them. And than adapt them a bit, make variations on the component 'tests'.

I have a whole folder where I test each component with Arduino (and for some complicated components multiple sketches). Save them, and add links etc, so you can easily reference back to it.

You can use books, but there is so much information for the Arduino that this forum, the official web site and google should be enough to get you going.

(note: for the Arduino I did not use books, since as above said, there is so much information. I'm now diving in to STM32 which is more complex and a book/PDF is more convenient).


body:
I want to detect when an LED is powered on using an Arduino NANO. The LED is part of an external circuit. The LED uses about 1.8V. Would the circuit below allow me to detect when the LED is switched on? Is this the correct method of doing it? (The LED in the diagram represents the external circuit).

[![Circuit][1]][1]

  [1]: https://i.stack.imgur.com/wyece.png

title: How to detect if LED is switched on in external circuit using Arduino NANO?

Answers: 3

body:
The answer depends on your definition of "on".

An led is on if

1. There is voltage across I th or

2. There insufficient voltage across it, or

3. There is current through it, or

4. It generates light output, or

5. It generates sufficient light output.

...

Based on each of the above, there is an answer to your question.

body:
No, you will not detect the LED state at all, as your transistor base is connected to the target circuit's supply rail, not a switched node.

Additionally, your circuit risks burning out the LED as it lacks a current limiting resistor.

Speaking more generally, the only *safe* way to do this with a fully unknown circuit is to have an optical sensor looking at the LED.

If you can determine that it is safe to make an electrical connection to the circuit (ie, that the internal ground is not riding on mains voltage) and that the point of the circuit you want to measure is within an allowed voltage above that, then you can connect the grounds and measure the switched side of the LED / resistor.  **But until you have far more electrical engineering experience, you are probably not in a position to make this safety determination.**  Even battery powered devices can generate dangerous voltages internally.

It's important that you not connect *between* the LED and resistor, but rather to whichever side of that series unit is not connected to a supply rail, as the voltage drop on the LED itself may not be sufficient to register.

Certain fancier LED drivers may give you problems, for example if they regulator current internally.  Also, LEDs with PWM brightness control may require filtered polling, or even interrupts / hardware pulse-in.

body:
I'm afraid your circuit does not work.
In fact, the base of the transistor is always connected to the power, regardless the LED being ON or OFF. Therefore the BJT would be always in the ON-state. Also a current limiting resistor in series to the LED is missing (but I think that it was just for sake of simplicity).

Assuming that:

- you can mount in series something to the LED

- an additional 1.3-1.5V voltage drop will not cause too much issues (to be short: if the external circuit power supply is "large enough", and if you will not be too much upset if the LED luminosity will be smaller).

- You want to sense a signal LED, i.e. let's say with a current smaller than 20 mA.

Then, the safest way would be to use an optocoupler, such as 4N25-4N35. Put the LED of the optocoupler (transmitter side) in series to the LED you want to "sense", and use the phototransistor side to sense the LED status: it's emitter goes to the GND to your Arduino Nano, the collector to any input, with pull-up (The pull-up is mandatory!).

In this way, when current flows across the LED, it will also flow in the optocoupler LED, therefore the optocoupler phototransistor will be ON.

Also, using the optocoupler the two systems are electrically insulated each other (and you won't need to share the grounds).

Below you can find an example.

[![enter image description here][1]][1]

EDIT:
If you cannot wire the optocoupler LED in series (e.g. not enough voltage headroom because the power supply is too close to the LED Vf, or your LED is already on a PCB), you can connect the optocoupler in parallel.
Assuming the LED current is much larger than 1mA, you can use the following circuit. Choose RO so that the current flowing on the optocoupler will be 1mA (390-470 Ohm in your case). Usage of high current-transfer-ratio (CTR) optocoupler is suggested, but this might work also with a 4N25 or 4N35 (you'll be pretty close to the limit...)
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/cgGyH.png
  [2]: https://i.stack.imgur.com/8EuZ8.png


body:
i'm working on project where i'm trying to achieve that arduino parse caller ID so i can use it later to send SMS with sensor reading data.

Somehow i made that code (with much googling) and it works great... But when i include arduino sleep part, it does work at beginning, but after i call SIM800 4-5 times with distinct of 30 seconds, i get unusable data on Serial, so i can't no longer parse correct number.

I tried many things, dropping baud rate to 1200, changing delay, but still i get strange characters after few calls.

Can anyone help me?

P.S. ATMEGA328P ic MCU

Thank you,
Matija

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

    SoftwareSerial SIM800(8, 7);

    String buffer1;
    unsigned int current_millis = 0;
    String phone;

    void setup() {
         buffer1.reserve(200);
         phone.reserve(20);

         Serial.begin(19200); //
         SIM800.begin(9600);
         delay(1000);
         SIM800.write("AT\r");  // because of SIM800L autobounding mode
         delay(1000);
         SIM800.write("AT+IPR=9600\r");  // set baud at 9600, i tried with 1200
         and  other, and with autobauding but still got same problem
         delay(1000);
         SIM800.write("AT+CMGF=1\r");  // set SMS mode to text
         delay(1000);
         SIM800.write("AT+CNMI=2,2,0,0,0\r");
         delay(1000);
         Serial.print(SIM800.readString());
         SIM800.write("AT+CLIP=1\r\n");
         delay(1000);
         SIM800.write("AT+SGPIO=0,7,1,0\r");
         delay(1000);
         SIM800.write("AT+CSCLK=2\r"); //power saving mode of SIM800L
         delay(1000);
         current_millis = millis();
    }

    void loop() {
       // put your main code here, to run repeatedly:
       if (SIM800.available() > 0) {
          buffer1 = SIM800.readStringUntil('\n'); //Saving string then parsing
               caller number from it
          Serial.println(buffer1);
          parse();
          current_millis = millis();
          }

        if ((millis() - current_millis) > 10000) { //Putting atmega tu sleep
           sleepNow();
           delay(1000);// tried many delays
           current_millis = millis();
         }

     }

    void parse() {
        if (buffer1.indexOf("CLIP:") > 0) {
            phone = buffer1.substring(buffer1.indexOf("+CLIP: ") + 8,
            buffer1.indexOf("+CLIP: ") + 21); //parsing caller number
            Serial.println(phone);
            SIM800.write("ATH\r"); //hang out phone call
            delay(500);
            SIM800.write("ATH\r");
            delay(500);
      }

    }

    void sleepNow() { //PIN CHANGE INTERRUPT ON PIN 7,8 BECAUSE SOFTWARE SERIAL
                       LIBRARY USE IT AND IT WILL WAKE UP ATMEGA
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set herethe
                                              sleep bit in the mcucr register
        sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
        sleep_disable();         // first thing after waking from sleep: disable
                                    sleep...
        }

[![Serial OUTPUT][1]][1]

  [1]: https://i.stack.imgur.com/xT0Mv.png

title: SIM800L and Arduino Sleep - getting whimsy Serial output after 5 calls

Answers: 2

body:
Give [AltSoftSerial][1] a try, it's hands down superior.

Reset might work but it does not actually solve your problem, it just swipes it under the mattress. Also, have you considered ditching that String? It is the source of many problems regarding memory. You could relatively easily substitute it for an array of chars instead. Something like this, taken from [example#2][2]:

    void recvWithEndMarker() {
        static byte ndx = 0;
        char endMarker = '\n';
        char rc;

        while (Serial.available() > 0 && newData == false) {
            rc = Serial.read();

            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                ndx = 0;
                newData = true;
            }
        }
    }

  [1]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
  [2]: http://forum.arduino.cc/index.php?topic=396450

body:
When you use sleep mode SLEEP_MODE_PWR_DOWN you're turning off all of the microcontroller's timers, Including the timer SoftSerial is using.  I expect that turning off and then when wake from sleep turning back on the timers is affecting the timing of your serial communications.

Try using SLEEP_MODE_IDLE instead of SLEEP_MODE_PWR_DOWN and see if it corrects the problem.


body:
I have a NodeMcu Lua ESP8266 ESP-12E which i want to use to control to a relais via Wifi network.

The first step was to write an Arduino Sketch which scans networks and connects to the network. However, even the standard example from the examples menu didn't work (c.f.,https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino) .

To rule out hardware problems I tried the LUA version from the list API doc (see below), which worked.

     -- print ap list
    function listap(t)
          for k,v in pairs(t) do
            print(k.." : "..v)
          end
    end

    wifi.sta.getap(listap)

Using a firmware build from http://nodemcu.com/index_en.html

I gave the INO version another try and it seemed to work as well. However, it turned out it only works if the previous firmware has been the firmware from http://nodemcu.com/index_en.html

To I need to include a library or something ?

Thanks in advance,
Cafebabe

title: Wifi with ESP8266 and Arduino sketches

Answers: 1

body:
(By googling) I figured out the problem and a work-around. **But not an executable solution.** The problem seems to be that the RF module is not properly initialised when the device is powered on or awakes from reset.

Sadly there seems to be no manual mode to switch on the RF module.

However, I found a workaround. First I made the connection to enable deep sleep, for that, we need to tie the `RST` pin to `D0`/`GPIO 16` on the ESP8266.

Then I added the following code to setup

    extern "C" {
      #include "user_interface.h"
    }

    void setup(){
      if (resetInfo->reason != REASON_DEEP_SLEEP_AWAKE) {

          ESP.deepSleep(10, WAKE_RF_DEFAULT)
      }

Basically whenever the system comes into setup from something else than deep sleep, the system goes to deep sleep and when powering back on the RF module is enabled.


body:
I am facing issues while uploading sketch to **Adafruit Feature 32u4 Bluefruit LE** devices. When i try to upload **Blink** demo it was working fine and my device also blinking, But bellow error i am getting every time when i upload sketch.

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

I am using **Adafruit Feature 32u4 Bluefruit Le device,Arduion 1.8.3 version, MacMini with macOs Sierra(10.12.3).**

Answers: 1

body:
Finally i found answer for my question, It happen because of uploading sketch in selected pin.

    // Neopixel
    //#define PIN            6   /* Pin used to drive the NeoPixels */
    #define PIN            13   /* Pin used to drive the NeoPixels */

I Changed Pin 6 to 13 , it's worked for me.


body:
I'm working on a project in which an ESP8266 is the brain of the device. I want to add new features to the device controller later but this requires that the user open the controller and reprogram the ESP8266.

I want the user to be able to update the firmware with his smartphone (maybe through an application). How can I do that? Is this possible with this chip?

title: Flashing ESP8266 over WiFi whith samrtphone?

Answers: 1

body:
ESP8266 OTA can be performed through a web browser as detailed [in the ESP8266 OTA information page](http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html).

Since a smartphone has a web browser I can see no reason why you can't use that.


body:
I'm looking for a complete list of the arithmetic types in the Arduino framework.
On the Internet I found various incomplete lists: sometimes there is `short`, sometimes `word`, but other types are missing.

Could someone please provide an exhaustive list of the arithmetic data types in Arduino, including the C/C++ types and the Arduino-defined types (or aliases, e.g. the one created among others in Arduino.h with `typedef uint8_t byte;`) with a short description? If two types are identical please include both names in the list but making clear that they are the same.

title: Arithmetic types in Arduino

Answers: 2

body:
The Arduino "language" is actually C/C++. GNU GCC and tool chain are used. The Arduino IDE uses a preprocessor to make it easier for beginners by removing some of the C/C++ requirements such as forward declaration of functions.

The GNU AVR GCC data types and representation, and the answer to your question can be found on the project Wiki page; https://gcc.gnu.org/wiki/avr-gcc

For C/C++ there are build-in data types but also a set of standards. One of the standard header files with data types is `stdint.h`. http://www.nongnu.org/avr-libc/user-manual/group__avr__stdint.html

`Arduino.h` and additional header files within the Arduino core libary contains the extensions or redefinitions made. The complete reference list; https://www.arduino.cc/en/Reference/HomePage

Cheers!

body:
You have integers in 8, 16, 32 and 64 bits, both signed and unsigned. You have float and double, which can be the same thing on some systems.

There are many names given to those variable types, some standard or ubiquitous, some vague or unique, or change depending on which type of CPU you are working with.

The names aren't important, since they only exist in the source code. All that matters is the underlying size. Names of the same underlying size and signedness are interchangeable at will.

For example:

* uint8_t = unsigned char
* int32_t = long = int on 32 but systems
* uint16_t = unsigned short = int on 8 bit systems

As you can see `int` changes depending on the system you are on. So it is best to stick to specifically named types. I always use the `[u]int[N]_t` types.

So you have:

* uint8_t
* int8_t
* uint16_t
* int16_t
* uint32_t
* int32_t
* uint64_t
* int64_t

And:

* float
* double (if the compiler supports double on the platform you are compiling for, otherwise it is just float).

Arduino itself provides some more unique variable names that are completely nonstandard, such as `byte` for `unsigned char`.

In `short` (pun intended), stick to variables that specifically define their type if you are worried about how big they all are, and avoid all the rest.

For overloading the compiler will automatically "upscale" the variables to the best fitting available function (known as *type promotion*) unless functions are flagged as `explicit`, so you can have a function with a `long` parameter and pass any integer variable up to and including a `long` in size. The same with `float` / `double` types - if your function takes a `double` you can pass it a `float`. Useful when you don't know if the target provides a real `double` or not - just use `double` and it will work regardless with either `double` or `float`.


body:
I have wired my Arduino as seen in the picture, with the RX of the cable plugged into the TX (D1) of the Leonardo and the TX of the cable plugged into the RX(D0) of the Leonardo. I then have the ground plugged into GND and the power into 5V. The driver is installed correctly and the IDE recognizes the port, however, whenever I try and upload any sketch, I get the error:

Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

I can upload sketches fine via usb, is it just unable to do so via a USB to TTL cable?

[![enter image description here][1]][1]

Thanks in advance

  [1]: https://i.stack.imgur.com/OYJD7.jpg

title: Programming Leonardo with TTL to USB cable

Answers: 1

body:
The bootloader on the Leonardo operates through the native USB port of the ATMega32U2 chip, not the UART.

You cannot treat it like an Uno because it isn't an Uno.

You can only program it through the USB port or through the ICSP connector.

If you want to use UART to upload you will need to replace the bootloader with a suitable UART based alternative. (Before you ask, no I don't know if one even exists or where to get it if it does).


body:
Good day. I've been learning on how to transfer data from Arduino to Raspberry Pi wirelessly using NRF24L01 based on the following reference:
[Raspberry Pi 3 Tutorial 14 – Wireless Pi to Arduino Communication with NRF24L01+][1].

The reason why I want to do this is to log temperature and humidity data wirelessly using DHT22 sensors.

The Arduino code is shown below:

    //SendReceive.ino

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

    // CE, CSN pins
    RF24 radio(9, 10);

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

     radio.begin();
     radio.setPALevel(RF24_PA_MAX);
     radio.setChannel(0x76);
     radio.openWritingPipe(0xF0F0F0F0E1LL);
     const uint64_t pipe = (0xE8E8F0F0E1LL);
     radio.openReadingPipe(1, pipe);

     radio.enableDynamicPayloads();
     radio.powerUp();

    }

    void loop(void){
     radio.startListening();
     Serial.println("Starting loop. Radio on.");
     char receivedMessage[32] = {0};
     if(radio.available()){
      radio.read(receivedMessage, sizeof(receivedMessage));
      Serial.println(receivedMessage);
      Serial.println("Turning off the radio.");
      radio.stopListening();

      String stringMessage(receivedMessage);

      if(stringMessage == "GETSTRING"){
       Serial.println("Looks like they want a string!");
       const char text[] = "Yo wassup, haha";
       radio.write(text, sizeof(text));
       Serial.println("We sent our message.");
      }
     }
     delay(100);

    }

Meanwhile, the Raspberry Pi code is shown below:

    import RPi.GPIO as GPIO
    from lib_nrf24 import NRF24
    import time
    import spidev

    GPIO.setmode(GPIO.BCM)

    pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

    radio = NRF24(GPIO, spidev.SpiDev())
    radio.begin(0, 17)

    radio.setPayloadSize(32)
    radio.setChannel(0x76)
    radio.setDataRate(NRF24.BR_1MBPS)
    radio.setPALevel(NRF24.PA_MIN)

    radio.setAutoAck(True)
    radio.enableDynamicPayloads()
    radio.enableAckPayload()

    radio.openWritingPipe(pipes[0])
    radio.openReadingPipe(1, pipes[1])
    radio.printDetails()
    # radio.startListening()

    message = list("GETSTRING")
    while len(message) < 32:
        message.append(0)

    while(1):
        start = time.time()
        radio.write(message)
        print("Sent the message: {}".format(message))
        radio.startListening()

        while not radio.available(0):
            time.sleep(1 / 100)
            if time.time() - start > 2:
                print("Timed out.")
                break

        receivedMessage = []
        radio.read(receivedMessage, radio.getDynamicPayloadSize())
        print("Received: {}".format(receivedMessage))

        print("Translating the receivedMessage into unicode characters")
        string = ""
        for n in receivedMessage:
            # Decode into standard unicode set
            if (n >= 32 and n <= 126):
                string += chr(n)
        print("Out received message decodes to: {}".format(string))

        radio.stopListening()
        time.sleep(1)

Based on the Arduino code above, the code that shows the data that is transmitted is shown below:

    const char text[] = "Yo wassup, haha";

Based on the Raspberry code above, the codes that decode the received data from Arduino are shown below:

    for n in receivedMessage:
        # Decode into standard unicode set
        if (n >= 32 and n <= 126):
            string += chr(n)

However, these decoding code only works if I transmit string or integer from Arduino to Raspberry Pi. It doesn't work if I transmit float. Since DHT22 records temperature and humidity up until 1 decimal point, it is required for me to transmit float. Can anyone here please teach me how to decode the float values?

Thank you very much.

  [1]: http://invent.module143.com/daskal_tutorial/raspberry-pi-3-wireless-pi-to-arduino-communication-with-nrf24l01/

title: Using Raspberry Pi to Receive Float from Arduino using NRF24L01

Answers: 1

body:
If you say you only need one digit, why not multiplying your value with 10 (with rounding), transmit it as a 4 byte (unsigned?) integer, and divide by 10 after receiving.

You only need to check if you have little or big endian conversion needed (swapping MSB/LSB 2 byte or single byte). But you see this very fast if you print the values in hex format.


body:
I have found code that can blink an LED on Arduino according to Heart Beat. I am using AD8232 as a sensor for Heart Rate.

Code for it is:

    //  Variables
    int PulseSensorPurplePin = 0; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
    int LED13 = 13; // The on-board Arduino LED
    int Signal; // holds the incoming raw data. Signal value can range from 0-1024
    int Threshold = 550; // Determine which Signal to "count as a beat", and which to ingore.

    void setup() {
      pinMode(LED13, OUTPUT); // pin that will blink to your heartbeat
      Serial.begin(9600); // Sets up Serial Communication at certain speed.
    }

    void loop() {
      Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor's value.
      // Assign this value to the "Signal" variable.
      Serial.println(Signal); // Send the Signal value to Serial Plotter.
      if(Signal > Threshold) {
        // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
        digitalWrite(LED13, HIGH);
      } else {
        digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
      }
      delay(10);
    }

My question is: How can I get BPM?

Edited below:

Is this code for BPM correct?

    int x = 0;
    int LastTime = 0;
    bool BPMTiming = false;
    bool BeatComplete = false;
    int BPM = 0;
    #define UpperThreshold 518
    #define LowerThreshold 490
    int LED13 = 44; // The on-board Arduino LED
    int Signal; // holds the incoming raw data. Signal value can range from 0-1024

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

    void loop() {
      int value = analogRead(0);
      if (value > UpperThreshold) {
        if (BeatComplete) {
          BPM = millis() - LastTime;
          BPM = int(60 / (float(BPM) / 1000));
          BPMTiming = false;
          BeatComplete = false;
        }
        if (BPMTiming == false) {
          LastTime = millis();
          BPMTiming = true;
        }
      }
      if ((value < LowerThreshold) & (BPMTiming))
        BeatComplete = true;
        // display bpm
      Serial.print(BPM);
      Serial.println(" BPM");
      x++;
      Signal = analogRead(0); // Read the PulseSensor's value.
      // Assign this value to the "Signal" variable.
      if (Signal > UpperThreshold) {
        // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
        digitalWrite(LED13, HIGH);
      } else {
        digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
      }
    }

title: Getting BPM from the given code

Answers: 1

body:
If you know the interval between heart beats, you can calculate the frequency using the formula: frequency = 1 / time. Now if you take the frequency and multiply it by 60, you should get BPM.

I don't have one of the sensors you are using so I connected a potentiometer to pin A0 to test this code.

        int UpperThreshold = 518;
        int LowerThreshold = 490;
        int reading = 0;
        float BPM = 0.0;
        bool IgnoreReading = false;
        bool FirstPulseDetected = false;
        unsigned long FirstPulseTime = 0;
        unsigned long SecondPulseTime = 0;
        unsigned long PulseInterval = 0;

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

        void loop(){

          reading = analogRead(0);

          // Heart beat leading edge detected.
          if(reading > UpperThreshold && IgnoreReading == false){
            if(FirstPulseDetected == false){
              FirstPulseTime = millis();
              FirstPulseDetected = true;
            }
            else{
              SecondPulseTime = millis();
              PulseInterval = SecondPulseTime - FirstPulseTime;
              FirstPulseTime = SecondPulseTime;
            }
            IgnoreReading = true;
          }

          // Heart beat trailing edge detected.
          if(reading < LowerThreshold){
            IgnoreReading = false;
          }

          BPM = (1.0/PulseInterval) * 60.0 * 1000;

          Serial.print(reading);
          Serial.print("\t");
          Serial.print(PulseInterval);
          Serial.print("\t");
          Serial.print(BPM);
          Serial.println(" BPM");
          Serial.flush();

          // Please don't use delay() - this is just for testing purposes.
          delay(50);
        }

Updated answer in response to your comments below:

The sketch is reading the data and sending the data to the serial monitor every 50ms because of the delay(50). What if we changed that to 1000 ms? The serial monitor would update once per second which would be more "human readable". The problem with that idea is for heart rates faster than 60 BPM, the reading would be inaccurate. I don't have a sensor to test with but I'm guessing a 1 second delay would make the code inoperable.

Before we add more complexity to this sketch we really should get rid of that delay. It would be nice to have one "timer" that we could use to update the BPM calculation and a second "timer" to update the serial monitor every second, or half second, or what ever you want it to be.

We can do that without any libraries using millis(). Here is an updated sketch using millis() for timers. This sketch has the blinking of the on board LED added to it. I'm using an Uno so you'll have to change LED_BUILTIN to what ever pin number you are using.

    int UpperThreshold = 518;
    int LowerThreshold = 490;
    int reading = 0;
    float BPM = 0.0;
    bool IgnoreReading = false;
    bool FirstPulseDetected = false;
    unsigned long FirstPulseTime = 0;
    unsigned long SecondPulseTime = 0;
    unsigned long PulseInterval = 0;
    const unsigned long delayTime = 10;
    const unsigned long delayTime2 = 1000;
    const unsigned long baudRate = 9600;
    unsigned long previousMillis = 0;
    unsigned long previousMillis2 = 0;

    void setup(){
      Serial.begin(baudRate);
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, LOW);
    }

    void loop(){

      // Get current time
      unsigned long currentMillis = millis();

      // First event
      if(myTimer1(delayTime, currentMillis) == 1){

        reading = analogRead(0);

        // Heart beat leading edge detected.
        if(reading > UpperThreshold && IgnoreReading == false){
          if(FirstPulseDetected == false){
            FirstPulseTime = millis();
            FirstPulseDetected = true;
          }
          else{
            SecondPulseTime = millis();
            PulseInterval = SecondPulseTime - FirstPulseTime;
            FirstPulseTime = SecondPulseTime;
          }
          IgnoreReading = true;
          digitalWrite(LED_BUILTIN, HIGH);
        }

        // Heart beat trailing edge detected.
        if(reading < LowerThreshold && IgnoreReading == true){
          IgnoreReading = false;
          digitalWrite(LED_BUILTIN, LOW);
        }

        // Calculate Beats Per Minute.
        BPM = (1.0/PulseInterval) * 60.0 * 1000;
      }

      // Second event
      if(myTimer2(delayTime2, currentMillis) == 1){
        Serial.print(reading);
        Serial.print("\t");
        Serial.print(PulseInterval);
        Serial.print("\t");
        Serial.print(BPM);
        Serial.println(" BPM");
        Serial.flush();
      }
    }

    // First event timer
    int myTimer1(long delayTime, long currentMillis){
      if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
      else{return 0;}
    }

    // Second event timer
    int myTimer2(long delayTime2, long currentMillis){
      if(currentMillis - previousMillis2 >= delayTime2){previousMillis2 = currentMillis;return 1;}
      else{return 0;}
    }

The code compile size with delay is 4,732 vs the millis timers at 4,682 (with the LED code removed). Two timers for less than the price of one delay :)

The LED will remain on for the duration of the heart beat reading above the LowerThreshold. If you want to have it on longer or decide how long it should be on for, I won't write the code for you but I will give you a hint. You can copy myTimer1() again and make a third timer.


body:
So I'm building a MIDI controller. It has a 16-positions selector that lets the user select a "program": a playlist of commands to send to a MIDI instrument.

A push-switch allows the user to scroll through that playlist, running each command in sequence, one at a time.

The way I'm trying to implement this is as follows:
Playlist is a pure abstract class and each Program is derived from it. Each Program would have their own methods for each step, an array of pointers to these functions and a public playNext() method that loop() could call whenever the push-button is pressed with program.playNext()

I'm stuck at the selection of a program stage. I guess I could have an array of pointers to each program and call *arrayOfPrograms[currentProgram]->playNext()
but that would mean I would have to instantiate all the programs in setup() and keep them alive at all times...

Is there a way I could only instantiate the selected program and still call its playNext() method easily?

Sorry for the noob question. I'm fairly new to this and it gets confusing very quickly ;-) Thanks for your help.

Max

title: How can I have the user instantiate an object?

Answers: 2

body:
I'm not fully understanding the way your sketch should work.

However, I think what you need is some kind of Controller object.
The controller object instantiates one program. The controller also keeps a Boolean to play the next one (playNext). Once the program finishes, the controller can delete the just played program, checks if the Boolean is set to play the next, instantiate the next program to play and play it.

This results that programs are not depending on each other.

body:
You seem like you are almost there. Allocate the objects using `new` and free with `delete`.

    // Abstract parent
    class Playlist {
        public:
        virtual void playNext() = 0;
        // etc.
    };
    // Derived classes
    class Something : public Playlist
        public:
        void playNext() {
            // your code here
        }
    };
    class SomethingElse : public Playlist
        public:
        void playNext() {
            // your code here
        }
    };
    // More derived classes......

    // A pointer of the current program
    Playlist *play_list = nullptr;

    // A factory function to create a Playlist while also freeing previous
    Playlist * create_playlist(int which_program) {
        // Important - delete old
        delete play_list;
        play_list = nullptr;
        // There are only 16 types, use a switch or if
        switch (which_program) {
            case 1:
                // Create a new one and save in global ptr
                play_list = new Something;
                break;
            case 2:
                play_list = new SomethingElse;
                break;
            // More cases here.....
        }
        return play_list;
    }

[edit]--------------------------

Ok. The issue is that C++ does not have a lot of reflection options. So you can't create a class only by its name (as a string). Here's another solution I came up with. It's not completely automatic as it involves registering each class in `setup`. But I think it's close to what you want:

    class Playlist;  //Forward declaration

    // Each class will have a function to create itself
    typedef Playlist * (*CreateFunc)();

    // The parent class. It also holds a list of all child classes
    // Could probably refactor into 2 separate classes
    class Playlist{
      public:
      // Need virtual dtor
      virtual ~Playlist() {
        delete last_created;
      }

      // Put all the overridable function declarations here
      virtual void playNext() = 0;

      // This has to be called for each child. (See macro below)
      static void register_class(int id, CreateFunc f) {
        all_maps[num_maps].id = id;
        all_maps[num_maps++].f = f;
      }

      // Factory method to instantiate an object
      static Playlist * create_playlist(int id) {
          // Delete old pointer
          if (nullptr != last_created) {
              delete last_created;
              last_created = nullptr;
          }
          for (int i = 0; i < num_maps; i++) {
              // Search the list for name match
              if (id == all_maps[i].id) {
                  // Call the creation func
                  return all_maps[i].f();
              }
          }
          return nullptr;
      }
      protected:
      // A struct to hold the class name and a pointer to the creation function
      struct Map {
        int id;
        CreateFunc f;
      };
      static Map all_maps[32];
      static int num_maps;
      static Playlist* last_created;
    };
    // Static declarations
    Playlist::Map Playlist::all_maps[32] = {{0, nullptr}};
    int Playlist::num_maps = 0;
    Playlist* Playlist::last_created = nullptr;

    // Example child class
    class Child1 : public Playlist{
      public:
      void playNext() {Serial.println("Child1");}

      // Must have this function and it must be static
      static Playlist * create() {return new Child1;}
    };
    // Another example
    class Child2 : public Playlist{
      public:
      void playNext() {Serial.println("Child2");}
      static Playlist * create() {return new Child2;}
    };

    // Helper macro to simplify registering
    #define REGISTER_PLAYLIST(id, name) Playlist::register_class(id, &name::create)

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

      // This must be done for all classes
      REGISTER_PLAYLIST(0, Child1);
      REGISTER_PLAYLIST(1, Child2);

      // Example usage
      Playlist*p = Playlist::create_playlist(0);
      p->playNext();
      p = Playlist::create_playlist(1);
      p->playNext();
    }

    void loop() {

    }

I just whipped this up. Probably room for improvement....


body:
I own a couple of digital in-ear headphones that connect to my phone using USB (some micro, some type C), i.e. they have a built-in DAC and amp. Now instead of having to carry my phone along to listen to music, I'd like to build a portable music player - think of it as an iPod Shuffle minus the DAC+AMP - and I think the Arduino platform should be well-suited for a first prototype(?).

So if I understand correctly, then all I need is the following:

- an Arduino board
- some storage (i.e. a micro-SD card module)
- a serial to USB-C module
- some code that streams the files to serial

then "optionally":

- a battery
- some controls

Am I on the right track?
The headphones connect as USB OTG slave devices, so the Arduino will need to be the master - is that an issue? Also, is it possible to output serial data through the Arduino's own USB port? I've looked around, but my findings are somewhat inconclusive. On the other hand, this might not matter since I will need to power it somehow anyway...

As you may have guessed, this is my first Arduino project, so please be kind ^.^

Thanks!

title: Digital Music Player (SD to USB)

Answers: 0


body:
I am using ADXL345 accelerometer with Adafruit_ADXL345 library for vibration measurement.

I am reading acceleration at X, Y, Z-axis of a sensor placed on a vibrating platform.And serially sending it to PC at a baud rate of 115200.

When vibration is low sensor shows vibrations but as i increase the vibrations serial transmission seems to be halted. As shown in figure:(x-axis=Samples y-axis=Samples )[![Serial Plot Data][1]][1]

 I thought it may be due to loose connections so I soldered its terminals but it behaved the same way at higher vibrations.
 Here is the code that I’m using.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_ADXL345_U.h>
    /* Assign a unique ID to this sensor at the same time */

    Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12);
    int i=0;
    struct measure
    {
        int timestamp;
        float x;  // ACC in x direction
        float y;  //ACC in y direction
        float z;  //ACC in z direction
    };
    sensors_event_t event;
    struct measure measurements;

    int timestamp = 0;

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

      Serial.println("Accelerometer Test"); Serial.println("");

      /* Initialise the sensor */
      if(!accel.begin())
      {
        /* There was a problem detecting the ADXL345 ... check your connections */
        Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
        while(1);
      }
      accel.setDataRate(ADXL345_DATARATE_3200_HZ);
      accel.setRange(ADXL345_RANGE_16_G);
         pinMode(LED_BUILTIN, OUTPUT);
      delay(2000);
    }

    void loop(){

     accel.getEvent(&event);
       measurements.timestamp = timestamp++;
       measurements.x  = event.acceleration.x;
       measurements.y  = event.acceleration.y;
       measurements.z  = event.acceleration.z;

    if(measurements.timestamp%2==0)
      digitalWrite(LED_BUILTIN, HIGH);
      else
        digitalWrite(LED_BUILTIN, LOW);

      /* Sending the array with data through serial*/

      Serial.print(measurements.timestamp);
     Serial.print(",");
     Serial.print(measurements.x+0.06);
     Serial.print(",");
     Serial.print(measurements.y+0.7);
     Serial.print(",");
     Serial.println(measurements.z-10.10);
    }

Where does problem lie? How to resolve this issue?

Circuit Connections:
[![Circuit][2]][2]

  [1]: https://i.stack.imgur.com/pDamO.png
  [2]: https://i.stack.imgur.com/85KIS.jpg

title: ADXL345 hangs the microcontroller as vibrations increase

Answers: 0


body:
The strcat function is working fine when called for the first time but when the broker goes down and it's attempting to reconnect it is appending the value twice. I am not able to figure out the problem as i am writing C code for the first time.

    void reconnect() {

      while (!client.connected()) {
        const char* cid = clientID.c_str();
        if (client.connect(cid)) {
           const char* sTopic = strcat("clm/",cid);
           client.publish(outTopic, sTopic);
           client.subscribe(sTopic);
        } else {
        // Wait 5 seconds before retrying
        for(int i = 0; i<5000; i++){
          delay(1);
        }
      }
    }
  }

It is called in the loop method

    void loop() {
      if (!client.connected()) {
        reconnect();
      }
    }

The value of sTopic for the first time is `clm/5C:CF:7F:3D:5B:F6` but when the broker restarts and the client connects again it is `clm/5C:CF:7F:3D:5B:F65C:CF:7F:3D:5B:F6`

What could be the reason for the same ?

title: strcat appending multiple times when called in loop

Answers: 3

body:
You have to cat only one string per time. Your assumption is that it performs

    dest = strcat(string_1, string_2)

However, it is:

    dest = strcat(dest, string_1)

So you should use

    char sTopic[256]; // Max possible length

    ...

    strcpy(dest, "clm/");
    strcat(dest, cid);

This will first copy "clm/" to dest, than cid will be concatenated.

(code not tested)

See reference: [reference][1]

  [1]: http://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm

body:
> Appends a copy of the *source* string to the *destination* string.

source

Congratulations, you've broken your string literal. Either stick to using `String` or make sure you allocate a string properly and then concatenate into that.

body:
strcat won't allocate any memory for the new string. So what really happens is that the location where the string constant `"clm/"` is stored gets the id appended.

In other words the second time around it's as if you passed `"clm/5C:CF:7F:3D:5B:F6"` as first parameter.

To fix that you need to supply a proper buffer for strcat to do its work:

    if (client.connect(cid)) {
       char[64] sTopic ={0};
       strcat(sTopic , "clm/");
       strcat(sTopic , cid);


body:
My system requires that I read two independent PWM signals (60hz) and output two corresponding square waves. These output square waves vary in frequency according to their corresponding input duty cycle. The output frequencies will vary between 1-60Hz. (outside of tone() range)

I'm planning out the best way to approach this project.
My initial thought is to use the two available external interrupts set to CHANGE to measure the inputs. I believe I'll also need to reference a timer in this routine, to determine the time since the last change.

Unless I'm mistaken, it looks like I will also need a timer interrupt for each output, to control the frequency properly.

The Arduino UNO has 3 timers. timer0: 8bit (used internally), timer1: 16bit, and timer2: 8bit. In short, can I run all of these interrupts in the same code? Will I run out of timers, or can I multitask the timers between my requirements?

Thanks!

title: Can I read two PWM signals and output two square waves on an UNO?

Answers: 2

body:
Your signals are slow enough that you may not need any timer. You can
just use the Arduino `micros()` function to handle all your timings. Of
course, `micros()` itself relies on Timer 0, but you don't need to
access any timer directly.

I would use the external interrupts in `CHANGE` mode to measure the duty
cycle. For example:

<!-- language-all: lang-c++ -->

    const uint8_t INPUT_0_PIN  = 2;  // digital 2 is also INT0
    const uint8_t OUTPUT_0_PIN = 4;

    // Measured duration of the HIGH level of input 0.
    static volatile uint32_t input_0_high_time;

    // Interrupt handler invoked when input 0 toggles.
    static void on_input_0_change()
    {
        static uint32_t time_rise;             // last time the signal rose
        uint32_t now = micros();
        if (digitalRead(INPUT_0_PIN) == HIGH)  // detected rising edge
            time_rise = now;
        else                                   // detected falling edge
            input_0_high_time = now - time_rise;
    }

    void setup()
    {
        pinMode(INPUT_0_PIN, INPUT);
        pinMode(OUTPUT_0_PIN, OUTPUT);
        attachInterrupt(0, on_input_0_change, CHANGE);
    }

For handling two inputs, you can duplicate everything that has a `0` in
its name and name it with a `1`. If your signal is no slower than
60 Hz, you can also replace all `uint32_t` by `uint16_t` to make
the code slightly faster.

For generating the outputs, do something similar to the Blink Without
Delay example:

    void loop()
    {
        uint32_t now = micros();

        // Determine suitable period for output 0.
        uint32_t input_0_high_time_copy;
        noInterrupts();  // avoid race condition while reading
        input_0_high_time_copy = input_0_high_time;
        interrupts();
        uint32_t output_0_half_period =
                map(input_0_high_time_copy, 0, 16666, 8333, 500e3);

        // Toggle output 0 when needed.
        static uint32_t time_output_0_toggle;
        static uint8_t output_0_state;
        if (now - time_output_0_toggle >= output_0_half_period) {
            time_output_0_toggle += output_0_half_period;
            output_0_state = !output_0_state;  // toggle state
            digitalWrite(OUTPUT_0_PIN, output_0_state);
        }
    }

Again, you can handle two outputs by duplicating the code and replacing
`0` with `1`. Note that you _cannot_ replace `uint32_t` by `uint16_t`,
as it would not work for the slowest frequencies.

**Edit**: Now we may ask the question whether it is possible to use some
timers to make all this more accurate. The answer is yes, you could
achieve maximum accuracy by using four 16-bit timers:

* You could use the input capture function of a 16-bit timer, with the
  prescaler set to 8, to measure the transitions of one of your
  inputs with a resolution of 0.5 µs.
* You could use a 16-bit timer in CTC mode, with the prescaler set
  to 256, to toggle one of your outputs at the desired frequency, with a
  16 µs resolution.

For reference, `micros()` has a resolution of 4 µs. The 16 µs
resolution of the timer-generated output seems poor in comparison, but
the timer has the advantage of having zero jitter.

Now, for doing that that, you would need an Arduino Mega 2560. The Uno
has only one 16-bit timer, so it could help with only one of your two
channels.

There is still something you can do with a single 16-bit timer. Set it
to normal counting mode, with the prescaler at 8, and use it
instead of `micros()` for timing your inputs: in `setup()`

    // Configure Timer 1.
    TCCR1A = 0;          // normal counting mode
    TCCR1B = _BV(CS11);  // clock at F_CPU/8

and in the interrupt handler, you replace `uint32_t now = micros();` by

    uint16_t now = TCNT1;

And now you have `input_0_high_time` (which should also be `uint16_t`)
in units of 0.5 µs.

body:
Your approach is generally sound.

Depending on the square waves you are generating, one timer can generate two pulse train with independent duty cycles but dependent phases.

That leaves two times for measuring the duty cycles of the input pulse train.

But replicating the input pulse trains makes zero practical sense.


body:
I guess that my problems are because I'm new to C, but after spending three evenings without success I thought I'd give it a try to ask here!

I receive a JSON-formatted string in a UDP message. It contains several values that I would like to catch and convert to variables. The string format is like this:

    {
      "U1": 224,
      "U2": 227,
      "U3": 224,
      "I1": 0,
      "I2": 0,
      "I3": 0,
      "P": 0,
      "PF": 0,
      "E pres": 639,
      "E total": 69901578,
      "Serial": "16889379",
      "Sec": 393833
    }

Actually I really only need to get values U1, U2, U3 and I1, I2, I3. I'm grateful for all the help I can get solving this!

Best regards
Per

title: Urgent need of help splitting a JSON formatted string received by UDP

Answers: 1

body:
Two possible approaches:

 1. Tokenize the string using [`strtok()`][1], probably a few levels deep.
This may require you learning quite a bit more about C++, pointers, and character arrays as strings.
 2. An excellent opportunity to use an existing library, such as [ArduinoJSON][2], which abstracts out the difficulties you may encounter if the fields in your JSON string arrive in a different order, etc.

An example of using ArduinoJSON for your case is shown in the documentation (excerpted/adapted from [Decoding JSON][3])

    #include <ArduinoJson.h>

    // [...] other code

    char json[] = "{ \"U1\": 224, \"U2\": 227, \"U3\": 224, \"I1\": 0, \"I2\": 0, \"I3\": 0, \"P\": 0, \"PF\": 0, \"E pres\": 639, \"E total\": 69901578, \"Serial\": "16889379", \"Sec\": 393833 }";

    //
    // Step 1: Reserve memory space
    //
    StaticJsonBuffer<200> jsonBuffer;

    //
    // Step 2: Deserialize the JSON string
    //
    JsonObject& root = jsonBuffer.parseObject(json);

    if (!root.success())
    {
      Serial.println("parseObject() failed");
      return;
    }

    //
    // Step 3: Retrieve the values
    //
    uint16_t    u1 = root["U1"];
    uint16_t    u2 = root["U2"];
    uint16_t    u3 = root["U3"];
    uint16_t    i1 = root["I1"];
    uint16_t    i2 = root["I2"];
    uint16_t    i3 = root["I3"];

  [1]: http://www.cplusplus.com/reference/cstring/strtok/
  [2]: https://bblanchon.github.io/ArduinoJson/
  [3]: https://bblanchon.github.io/ArduinoJson/doc/decoding/


body:
The following program compiles in the Arduino IDE.

    void doSomething(bool) {}

    void setup() {
      doSomething(Serial);
    }

    void loop() {}

But, as expected, this one doesn't:

    class MyClass {};

    void doSomething(bool) {}

    void setup() {
      MyClass myClass;
      doSomething(myClass);
    }

    void loop() {}
The compiler returns the error `cannot convert 'MyClass' to 'bool' for argument '1' to 'void doSomething(bool)'`

---

Why is it possible to compile the former? Isn't Serial a normal class instance (of `HardwareSerial`)? Does it makes any sense to interpret `Serial` as a bool?

title: Using Serial as boolean function argument

Answers: 1

body: `HardwareSerial` defines `operator bool()`, which allows it to be used in a boolean context.


body:
I am trying to send Get request from my GSM Module but after connecting to server it is not responding any thing

    #include <SoftwareSerial.h>
    SoftwareSerial myGsm(2,3);
    void setup()
    {
    myGsm.begin(9600);
    Serial.begin(9600);
    delay(500);
    myGsm.println("AT+CGATT=1");
    delay(200);
    printSerialData();
    myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR,connection type is GPRS
    delay(1000);
    printSerialData();
    myGsm.println("AT+SAPBR=3,1,\"APN\",\"wap.mobilinkworld.com\"");//setting the APN,2nd parameter empty works for all networks
    delay(5000);
    printSerialData();
    myGsm.println();
    myGsm.println("AT+SAPBR=1,1");
    delay(10000);
    printSerialData();
    myGsm.println();
    myGsm.println("AT+SAPBR=2,1");
    delay(10000);
    printSerialData();
    myGsm.println("AT+HTTPINIT");
    delay(2000);
    printSerialData();
    myGsm.println("AT+HTTPPARA=\"URL\",\"http://sensor.somee.com/api/Data/GetData?SensorID=1\"");// setting the httppara,
    delay(1000);
    printSerialData();
    myGsm.println();
    delay(10000);//the delay is important if the return datas are very large, the time required longer.
    printSerialData();
    delay(9000);
    printSerialData();
    delay(1000);
    Serial.println("done ");
    printSerialData();
    }
    void loop()
    {
    }
    void printSerialData()
    {
    while(myGsm.available()!=0)
    Serial.write(myGsm.read());
    }

and the Out put is

    AT+CGATT=1

    OK
    AT+SAPBR=3,1,"CONTYPE","GPRS"

    OK
    AT+SAPBR=3,1,"APN","wap.mobilinkworld.com"

    OK

    AT+SAPBR=1,1

    OK

    AT+SAPBR=2,1

    +SAPBR: 1,1,"10.209.122.68"

    OK
    AT+HTTPINIT

    OK
    AT+HTTPPARA="URL","http://sensor.somee.com/api/Data/GetData?Sen
    done

title: Send HTTP get request from GSM SIM800c and Arduino

Answers: 2

body:
You should place the code to communicate (which is a recurring task) into the loop (and do this without blocking delay()s. Using delay stops the CPU so whatever comes to the buffer is probably not processed.

Read about the difference of placing code in the setup and the loop in the Arduino basic documentation.
Never use delay in communiction scenarios (except for intializing hardware in setup) see example blinkwithoutdelay in ArduinoIDE

body:
You haven't instructed the module to make a request yet.
With the AT+HTTPPARA command, you are just configuring the request you want to make. In your case, you just specified the URL you want to call.
Next, you have to send

    AT+HTTPACTION=1

to make the actual request using the HTTP GET method, and then you can read the HTTP response using

    AT+HTTPREAD

Keep in mind that after AT+HTTPACTION you will receive an unsolicited result code in the format

    +HTTPACTION: <Method>,<StatusCode>,<DataLen>

 this will happen after the module will actually do the request and will have the response.


body:
I've written some Arduino Code which kept crashing and i couldn't find out why. Then i reduced the code as much as i could in order to see the problem.
The reduced code currently doesn't do anything extraordinary except printing some strings over the serial line.

**This is the reduced code:**

    void setup()
    {
      Serial.begin(9600);
      Serial.print("Begin\r\n");
      send_wifi_beacon();
    }
    void loop()
    {
      delay(1000);
    }
    void send_wifi_beacon()
    {
      send_wlan_chip_command("AT+CIFSR");
      Serial.print("notreached"); // this part is never reached
      send_data_over_network(); // can't remove this line otherwise the crash won't happen which is weird since this is never called
    }
    void read_response_from_serial()
    {
      delay(2000);
      Serial.print("==-1\r\n"); // crashes here
    }
    void send_wlan_chip_command(char* command)
    {
      Serial.print("Sending command to wifi module: ");
      Serial.print(command);
      read_response_from_serial();
      Serial.print("Command response: ");
    }
    // this function is never called, since the crash happens before the call, but it can't be removed otherwise the crash won't happen
    // also it can't  be altered then, the crash also will not happen.
    void send_data_over_network()
    {
      char number[3] = "12";
      //char number[3] = "";
      char length_of_payload[20] = "0123456789012345678"; // 20 digits if assuming 64 bit integer is the maximum this code will ever run on
    //  char length_of_payload[20] = "";
      char *command;

      command = malloc(26);
      command = "AT+CIPSSEND";
      strcat(command, number);
      strcat(command, ",");
      strcat(command, length_of_payload);
      send_wlan_chip_command(command);
      free(command);
    }

**This is the according output:**

> Begin Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin

Which means that the arduino keeps crashing and resetting. This goes on forever.

The weird thing is, if I change the following two lines to: (in the"send_data_over_network" function as in example above)

    char number[3] = "1"; // changed from => char number[3] = "";
    char length_of_payload[20] = "123"; // changed from => char length_of_payload[20] = "0123456789012345678";

**The output now changes to :**

[![exact output][1]][1]

I call this behaviour weird since it shouldn't have any influence on the result because this function(send_data_over_network) is never called in the crash example from before.

**Troubleshooting options i already tried:**

 - Reinstalling Arduino IDE , i tried with mutliple versions 1.8 , 1.6, 1.4. 1.0
 - Different Arduino Boards (Arduino Uno and Arduino Mega)
 - Different Laptops (since i thought maybe it's related to power issues of my laptop)

Maybe it's something obvious and i just can't see it, but i already spent +16h debugging, so help would be really appreciated.

  [1]: https://i.stack.imgur.com/ktptw.png

title: Arduino crashing during serial print for no obvious reason

Answers: 2

body:
This code looks wrong:

      command = malloc(26);
      command = "AT+CIPSSEND";
      strcat(command, number);
      strcat(command, ",");
      strcat(command, length_of_payload);
      send_wlan_chip_command(command);

First you allocate 26 bytes, then a new string is created, which you strcat to it. This happens in memory that is not allocated (or overwrites other data).

Instead of

      command = "AT+CIPSSEND";

use

      strcpy(command, "AT+CIPSSEND");

Also check that 26 bytes is enough, change it to 128 bytes to be sure (check the correct amount you need later).

body:
You are almost certainly running out of memory and have a stack collision with the heap. Dynamic memory allocation and de-allocation is not a good idea when you have less than 2K RAM to work with. If you use malloc() use it only to allocate buffer space and then reuse the buffers. Put your test code entirely in setup and see what happens. Also check the amount of RAM allocated at compile time it may be more than you think.

    char *buf1;
    char *buf2;

    void setup() {
       buf1 = (char *) malloc(10);
       buf2 = (char *) malloc(10);
       .
       .
       // test code here
    }


body:
I am trying to set up a custom board under the Arduino IDE, but I can not figure out why I am getting the warning...

    Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt

My "vendor/maintainer" is `move38` and my platform is `avr`, so the path to the `boards.txt` is...

    Arduino\hardware\Move38\avr\boards.txt

Here is my `boards.txt` that defines the `blink` board...

    blink.name=Blinks Tile
    blink.upload.tool=avrdude
    blink.upload.protocol=avrisp
    blink.upload.maximum_size=15872
    blink.upload.maximum_data_size=1024

    blink.build.core=blinks
    blink.build.board=AVR_Blink

    blink.build.mcu=atmega168pb

    blink.c.extra_flags=-Wextra -flto
    blink.c.elf.extra_flags=-w -flto
    blink.cpp.extra_flags=-Wextra -flto
    blink.ltoarcmd=avr-gcc-ar

    # set F_CPU to 1Mhz for all boards on this platform
    build.f_cpu=1000000L

...which would seem to define `build.board` as `AVR_BLINKS`.

I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt

...but nonetheless the warning persists.

I am using Arduino IDE version 1.8.3 on Windows.

What am I missing here? Is there something special about the value, format, or position of the `build.board` key that I am missing here?

Thanks!

## More notes

Adding the following lines to a working `boards.txt` file...

    build.name=testname
    build.f_cpu=4000000L
    build.core=blinks
    build.board=AVR_BOARD

Will create a menu entry for a new phantom board called `testname`, but this is not a real board with usable keys. If you compile while that board is selected, you get the warning...

    Using board 'build' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
    Using core 'arduino' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
    Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

...despite the fact that the key `build.board` is explicitly defined.

title: Reason for warning "avr:build doesn't define a 'build.board' preference" when build.board is explicitly set in boards.txt?

Answers: 3

body:
It appears that you can no longer set a global property in the `boards.txt` file. You must set every property individually inside each board ID, even if they are the same for every board in the file. This seems to contradict the documentation that states that...

> The other properties will override the corresponding global properties
> of the IDE when the user selects the board.

Further, if any global key is set directly, then *both* the board specific keys  *and* the global keys are ignored.

So in my above `boards.txt`, setting the the global key `build.f_cpu` at the end of the file seems to cover the `blink.build.board` key and prevent it from being copied to `build.board` when the board is selected. Even if you set the global key `build.board` directly, this setting is ignored.

body:
The line in your boards.txt:

    build.f_cpu=1000000L

created a separate board entry with the board ID `build`, thus the error message:

    Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

From your comment:

    # set F_CPU to 1Mhz for all boards on this platform

and your answer I see that you expected that line to define a global value for the `build.f_cpu` property but the Arduino IDE has no mechanism for doing this in boards.txt and I don't believe it ever has. You need to define the properties for each board individually in boards.txt, where they will override previously defined properties of the same name. However, you can define default property values for the hardware package in your platform.txt just as you attempted to do in boards.txt.

body:
In my case: I erase the board configurations that was with problem in the file boards.txt.
These configurations appears between #### ... board configurations... #####.


body:
As far as I know, Ciao uses port 80 as the default and I haven't found a way of changing the port it attempts to connect to.

I tried using `"192.168.0.23:8080"` but the `Ciao.write()` seems to timeout after a while. Is there a way to specify the port to use?

P.S I'm using an Arduino Uno WiFi DevEd

title: Specifying port in Ciao.write

Answers: 1

body:
You can't. The factory firmware of Uno Wifi is discontinued.

[Uno WiFi and WiFi Link doc][1]

  [1]: https://github.com/jandrassy/arduino-firmware-wifilink/blob/ota/UNOWIFI_DEV_ED.md


body:
I've connected the circuit as shown in
https://www.arduino.cc/en/Tutorial/HelloWorld?from=Tutorial.LiquidCrystal
and I ran the program, but I can't fix this problem:

the LCD seems not to respond correctly: the first row is black and for what concerns the elements of the second, they all have three top lines of pixel high and the others low..

I checked over and over if I made some mistake connecting wires but I haven't found any error..

Is the LCD broken according to you? How can I fix?

Here the photos of the circuit:
https://drive.google.com/open?id=0B2h2zzEgtaqydElrRDVUNGVuWDA

title: Problem with 16x2 LCD using Arduino

Answers: 2

body:
I looked the images you have on Google Drive. On the image called IMG_20170822_233722.jpg, I see you are using a 50k ohm potentiometer to control the display contrast. Normally you would use a 10k ohm potentiometer. Using the 50k will make the adjustment very sensitive and hard to adjust. If you are careful and adjust it slowly, it might work for you.

The other image, IMG_20170822_234242.jpg, clearly shows "poor solder joint" connections on the display. D4 - D6 (especially D5 to D6) look like they could be "shorted" together. I think you could fix them by using Desoldering braid or if you don't have any, you could heat up each connection with your soldering iron then quickly "flick" the display to remove the solder. After you have removed the excess solder from each connection, I strongly recommend applying soldering paste to the connections next. The soldering paste really helps the solder to flow into the connection. Now try re-soldering each connection. I'm not sure what kind of solder or iron you are using but I can tell you what works for me. 25 watt pencil tip soldering iron with 22 gauge / 0.71mm rosin core solder.

I can't tell for sure from the pictures if any of the display pins are shorted together and I don't know if shorting them together will damage the display, Arduino or both.

body: Black first row suggests that the LCD is incorrectly initiated. That's often caused by wrong code or wrong hardware / connection.


body:
I am looking to work with deep sleeping, particularly with the ESP8266 but this question applies to most all micros. I am interested in running the device off of battery power for as long as possible. My solution would be something like a weather station where you know you only want to take a measurement every x minutes. So, I would like to sleep as much as possible in between measurements to extend battery life as much as possible. However, sleeping the microcontroller is one thing. How about when you have some sensors that piggyback off of the battery too. No need for those to be powered while the micro is sleeping and not taking a measurement.

Similar to this, I was thinking about reading the battery level. There are plenty of examples on how to do this online using a voltage divider (if necessary) and running the battery into analog input. This also draws from the battery while sleeping.

So, is there a way I can run all of these external sensors/devices through a transistor or something with low power draw when off and turn it all one when the device wakes up from sleep?

Thanks!

title: Is there a way to power off external devices during deep sleep

Answers: 1

body:
I made a [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) which runs off 3 x AA batteries. It lasts a couple of years without changing the batteries, and writes to an SD card.

The power-control part of the circuit is here:

[![Power management][1]][1]

The general idea is that Q1 is used to turn on/off a "switched 5V" rail (5V_SW) to which are attached most of the peripherals. This is done in conjunction with power-down sleep mode on the processor. A watchdog timer wakes the processor every 8 seconds to check to see if it is time to take another reading.

---

The full schematic is:

[![Full schematic][2]][2]

---

I think I've changed the batteries once since making it in 2013.

  [1]: https://i.stack.imgur.com/IkEbk.png
  [2]: https://i.stack.imgur.com/v8SCY.png