message:
Initialize a class (HX711) within a class with constructor and parameters

I am far from being an Arduino specialist, so please bear with me if some of my code below is far from correct.

I am writing a sketch in which I need to use 3 instances of the [HX711 library][1], as I am using 3 different weight sensors.

In order to try to clean up the code, I want to put basically all the code using HX711 in my own class.

Here is what my ScaleMeasure.h looks like:

    // ScaleMeasure.h
    #ifndef _SCALEMEASURE_h
    #define _SCALEMEASURE_h

    #if defined(ARDUINO) && ARDUINO >= 100
     #include "arduino.h"
    #else
     #include "WProgram.h"
    #endif

    #include <CmdMessenger.h>
    #include "HX711.h"

    class ScaleMeasure
    {
     public:
     ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
     void Setup();
     float Measure();

    private:
     int _dout_pin;
     int _clk_pin;
     float _calibration_factor;
     byte _scaleID;
     HX711 _scale = HX711(_dout_pin, _clk_pin);
    };

and .cpp

    #include "ScaleMeasure.h"

    ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
    {
     _clk_pin = Clk;
     _dout_pin = Dout;
     _calibration_factor = CalibF;
     _scaleID = ScaleID;
    }

    void ScaleMeasure::Setup()
    {
     _scale.power_up();
     _scale.set_scale();
     _scale.set_scale(_calibration_factor);
     _scale.tare();
     _scale.read();
    }

    float ScaleMeasure::Measure()
    {
     return _scale.get_units(5);
    }

but there is obviously something wrong, as a call to the constructor lock the rest of the program. I believe that my instantiation, of HX711 in ScaleMeasure.h  `HX711 _scale = HX711(_dout_pin, _clk_pin);` is not correct, or not in the right place. The code compile fine, though.

Thanks for your help.

  [1]: https://github.com/bogde/HX711

body:
The line

    HX711 _scale = HX711(_dout_pin, _clk_pin);

would be executed at construction time, which is the wrong time for it to run since `_dout_pin` and `_clk_pin` won't be set. Instead (much as it pains me to recommend it) you will have to use dynamic allocation:

    HX711 *_scale;

Then you can, in your constructor:

    _scale = new HX711(_dout_pin, _clk_pin);

Since you now have a pointer all your accesses to it need to change to `->` instead of `.`:

    _scale->power_up();
    ... etc ...

Also you should add a destructor to your class that deletes the object pointed to by `_scale` if it has been created.


sender: user

sender: assistant

body:
Unfortunatly HX711 has no default constructor. So the easiest way would be to add one in the header:

    HX711() {} // default constructor, empty

Add member function to do the init job (done by original constructor), also in the header file

        void Init(byte dout, byte pd_sck, byte gain = 128) {
     PD_SCK  = pd_sck;
     DOUT  = dout;

     pinMode(PD_SCK, OUTPUT);
     pinMode(DOUT, INPUT);

     set_gain(gain);
    }

Now your ScaleMeasure class will be like (header):

    class ScaleMeasure
    {
     public:
        ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
        void Setup();
        float Measure();

    private:
        int _dout_pin;
        int _clk_pin;
        float _calibration_factor;
        byte _scaleID;
        HX711 _scale;
    };

and cpp

    ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
    {
        _clk_pin = Clk;
        _dout_pin = Dout;

        _scale.Init(_dout_pin, _clk_pin);

        _calibration_factor = CalibF;
        _scaleID = ScaleID;
    }


body:
The right way, in C++, to properly construct a field member `b` (of type class `B`) inside a class `A` is to do it as follows in `A`'s constructor:

    A::A() : b(...) {
        // Other init code here
    }

In your situation that would mean:

    class ScaleMeasure
    {
     public:
        ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID);
        void Setup();
        float Measure();

    private:
        int _dout_pin;
        int _clk_pin;
        float _calibration_factor;
        byte _scaleID;
        HX711 _scale;
    };

Note that I have removed the init part for `_scale`.

    ScaleMeasure::ScaleMeasure(int Dout, int Clk, float CalibF, int ScaleID)
    : _scale(Dout, CLk)
    {
        _clk_pin = Clk;
        _dout_pin = Dout;
        _calibration_factor = CalibF;
        _scaleID = ScaleID;
    }


message:
Controlling an OSX app by Arduino

I am trying to control an app on OSX with an Arduino Uno.  Specifically, I would like to start and stop play of an MP3 on iTunes, or a track on Spotify, using an Arduino connected to the Apple computer with USB.

Any suggestions would be greatly appreciated.

body:
I am now having Screen output to log.txt, and the following applescript works just great!

set trigger to 1

set stopString to ""

repeat until (stopString = "stop")

set testTxt to paragraphs of (read POSIX file "/Users/fed/log.txt")
set countTxt to (count of testTxt) - 1
set lastLine to item countTxt of testTxt
if lastLine contains "Start MP3" and trigger is 1 then
    tell application "Spotify" to playpause
    set trigger to 0
end if

if lastLine does not contain "Start MP3" then
    set trigger to 1
end if

if lastLine contains "Stop Loop" then
    set stopString to "stop"
end if
end repeat


message:
Webserver on Arduino: Refresh issues

I am using [W5100 Ethernet Shield Network Module with arduino Uno ][1]as a webserver to trigger four relays connected to it.

The relays may be toggled through the four buttons attached to it physically, or through the four buttons on the hosted webpage. There is a counter how many times the relays are toggled which can be reset through a button on the webpage.

My issue is, whenever I toggle the relay through physical button, it does not update the counter on the webpage. And if I refresh the page, the last command from the page, such as togglerelay1 keeps echoing.

What solution do you propose to this problem:

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

    int Relay1 = 2;
    int Relay2 = 3;
    int Relay3 = 4;
    int Relay4 = 5;
    int Button1 = 8;
    int Button2 = 9;
    int Button3 = 10;
    int Button4 = 11;

    String on = "On";
    String off = "Off";

    String Relay1Status = on;
    String Relay2Status = on;
    String Relay3Status = on;
    String Relay4Status = on;

    int count1 = 0;
    int count2 = 0;
    int count3 = 0;
    int count4 = 0;

    byte toggle1 = LOW;
    byte toggle2 = LOW;
    byte toggle3 = LOW;
    byte toggle4 = LOW;

    void toggleRelay1();
    void toggleRelay2();
    void toggleRelay3();
    void toggleRelay4();

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };   //physical mac address
    byte ip[] = { 172, 168, 1, 178 };                      // ip in lan (that's what you need to use in your browser. ("192.168.1.178")
    byte gateway[] = { 172, 168, 1, 1 };                   // internet access via router
    byte subnet[] = { 255, 255, 255, 0 };                  //subnet mask
    EthernetServer server(80);                             //server port
    String readString;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
      pinMode(Relay1, OUTPUT);
      pinMode(Relay2, OUTPUT);
      pinMode(Relay3, OUTPUT);
      pinMode(Relay4, OUTPUT);
      pinMode(Button1, INPUT_PULLUP);
      pinMode(Button2, INPUT_PULLUP);
      pinMode(Button3, INPUT_PULLUP);
      pinMode(Button4, INPUT_PULLUP);
      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip, gateway, subnet);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {

      if (digitalRead(Button1) == LOW) {
        toggleRelay1();
        while (digitalRead(Button1) == LOW);
      }
      if (digitalRead(Button2) == LOW) {
        toggleRelay2();
        while (digitalRead(Button2) == LOW);
      }
      if (digitalRead(Button3) == LOW) {
        toggleRelay3();
        while (digitalRead(Button3) == LOW);
      }
      if (digitalRead(Button4) == LOW) {
        toggleRelay4();
        while (digitalRead(Button4) == LOW);
      }

      // Create a client connection
      EthernetClient client = server.available();
      if (client) {
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();

            //read char by char HTTP request
            if (readString.length() < 100) {
              //store characters to string
              readString += c;
              //Serial.print(c);
            }

            //if HTTP request has ended
            if (c == '\n') {
              Serial.println(readString); //print to serial monitor for debuging
              homepage();
              //controls the Arduino if you press the buttons
              if (readString.indexOf("?resetcount1") > 0) {
                count1 = 0;
              }
              if (readString.indexOf("?resetcount2") > 0) {
                count2 = 0;
              }
              if (readString.indexOf("?resetcount3") > 0) {
                count3 = 0;
              }
              if (readString.indexOf("?resetcount4") > 0) {
                count4 = 0;
              }
              if (readString.indexOf("?togglerelay1") > 0) {
                toggleRelay1();
              }
              if (readString.indexOf("?togglerelay2") > 0) {
                toggleRelay2();
              }
              if (readString.indexOf("?togglerelay3") > 0) {
                toggleRelay3();
              }
              if (readString.indexOf("?togglerelay4") > 0) {
                toggleRelay4();
              }
            }
          }
        }
      }
      //clearing string for next read
      readString = "";

    }

    void toggleRelay1() {
      toggle1 = !toggle1;
      digitalWrite(Relay1, toggle1);
      if (toggle1 == HIGH) {
        count1++;
        Relay1Status = on;
      }
      else
        Relay1Status = off;
    }

    void toggleRelay2() {
      toggle2 = !toggle2;
      digitalWrite(Relay2, toggle2);
      if (toggle2 == HIGH) {
        count2++;
        Relay2Status = on;
      }
      else
        Relay2Status = off;
    }

    void toggleRelay3() {
      toggle3 = !toggle3;
      digitalWrite(Relay3, toggle3);
      if (toggle3 == HIGH) {
        count3++;
        Relay3Status = on;
      }
      else
        Relay3Status = off;
    }

    void toggleRelay4() {
      toggle4 = !toggle4;
      digitalWrite(Relay4, toggle4);
      if (toggle4 == HIGH) {
        count4++;
        Relay4Status = on;
      }
      else
        Relay4Status = off;
    }

    void homepage() {
      client.println("HTTP/1.1 200 OK"); //send new page
      client.println("Content-Type: text/html");
      client.println("Connection: Close");
      client.println();
      client.println("");
      client.println("");
      client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
      client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
      client.println("<link rel='stylesheet' type='text/css' href='http://randomnerdtutorials.com/ethernetcss.css' />");
      client.println("<TITLE>Relay Control System</TITLE>");

      client.println("");
      client.println("");
      client.println("
Relay Control System
");
      client.println("
");
      client.println("
");

      client.println("
Relays Status
");
      client.println("
");

      client.println("Relay 1 Status: ");
      client.println(Relay1Status);
      client.println("
");

      client.println("Relay 2 Status: ");
      client.println(Relay2Status);
      client.println("
");

      client.println("Relay 3 Status: ");
      client.println(Relay3Status);
      client.println("

");

      client.println("Relay 4 Status: ");
      client.println(Relay4Status);
      client.println("

");

      client.println("Number of times Relay1 has been activated: ");
      client.println(count1);
      client.println("Reset Counter");
      client.println("

");

      client.println("Number of times Relay2 has been activated: ");
      client.println(count2);
      client.println("Reset Counter");
      client.println("

");

      client.println("Number of times Relay3 has been activated: ");
      client.println(count3);
      client.println("Reset Counter");
      client.println("

");

      client.println("Number of times Relay4 has been activated: ");
      client.println(count4);
      client.println("Reset Counter");
      client.println("

");

      client.println("Toggle Relay1");

      client.println("Toggle Relay2");

      client.println("Toggle Relay3");

      client.println("Toggle Relay4");

      client.println("");
      client.println("");

      delay(1);
      //stopping client
      client.stop();
    }

  [1]: https://www.amazon.com/Qunqi-Ethernet-Network-Starter-Arduino/dp/B015SCPCIE/ref=sr_1_3?ie=UTF8&qid=1469977802&sr=8-3&keywords=qunqi uno r3 board kit

body:
Instead of always responding with the `homepage()` for every request you should respond specially to the command requests with a `307` temporary redirect code to make the browser request the index page afresh

    client.println("HTTP/1.1 307 Temporary Redirect");
    client.println("Location: /");
    client.println("Connection: Close");
    client.println();
    client.stop();

So the client gets `/?togglerelay3`, which happens, and then gets sent a reply telling it to `make a new request to get /` which it then does to get the new status. The URL in the browser will not have the `?togglerelay3` in it, so refreshing won't cause the command to be run again.

If you want live updating of the page with new count values as they happen you will have to be more cunning. Either use AJAX and JavaScript in the page to fetch new values to display, or periodically refresh the page (with a [META Refresh](https://en.wikipedia.org/wiki/Meta_refresh)).


message:
Webserver on Arduino: How to 307 temporary redirect

I originally asked this [question.][1] Regarding a webserver Refresh issue on arduino.

I am totally new to web development and ethernet. The answer from @Majenko is correct, but I do not understand how to implement it. Should I change the `homepage()` function's first line to `HTTP/1.1 307 temporary redirect` and use `META REFRESH`?

Or do the `homepage()` first using `HTTP/1.1 200 OK` and then for all the following requests, use `HTTP/1.1 307 temporary redirect`?

  [1]: https://arduino.stackexchange.com/questions/28124/webserver-on-arduino-refresh-issues?newreg=fec67955f67e4baea0fc7402e8cb57da

body:
You need to make a decision on what to respond with depending on what the request is you have received.

If you receive a "command" URL (which you already check for by looking for certain sub-strings) then you need to respond with the `307` response. If you don't receive a "command" URL (so anything *except* the things you are specifically looking for) then you respond with the homepage.

A slight re-formatting of your decision code to use `else if` instead of just `if` would make it easier:

    if (c == '\n') {
      Serial.println(readString); //print to serial monitor for debuging
      // homepage(); << This is now moved elsewhere.
      //controls the Arduino if you press the buttons
      if (readString.indexOf("?resetcount1") > 0) {
        count1 = 0;
        redirect();
      } else if (readString.indexOf("?resetcount2") > 0) {
        count2 = 0;
        redirect();
      } else if (readString.indexOf("?resetcount3") > 0) {
        count3 = 0;
        redirect();
      } else if (readString.indexOf("?resetcount4") > 0) {
        count4 = 0;
        redirect();
      } else if (readString.indexOf("?togglerelay1") > 0) {
        toggleRelay1();
        redirect();
      } else if (readString.indexOf("?togglerelay2") > 0) {
        toggleRelay2();
        redirect();
      } else if (readString.indexOf("?togglerelay3") > 0) {
        toggleRelay3();
        redirect();
      } else if (readString.indexOf("?togglerelay4") > 0) {
        toggleRelay4();
        redirect();
      } else { // If none of them match then send the homepage.
        homepage();
      }
    }

`redirect()` is as simple as:

    void redirect() {
      client.println("HTTP/1.1 307 Temporary Redirect");
      client.println("Location: /");
      client.println("Connection: Close");
      client.println();
      client.stop();
    }


message:
Cannot upload sketch to Arduino Nano

I've been using Arduino UNO for quite sometime and brought a new Arduino Nano. When I connected it to my computer, the power usb lit up and the blink sketch started running ( as expected of course).

Now I opened up the IDE and switched boards. But when I try to upload code to my Nano I get an error-

>avrdude: ser_open(): can't open device "\\.\COM3": The system cannot find the file specified.

Clearly the IDE can't see my board. Uploading to my UNO goes fine. The serial port option is greyed out so I can't change it.

I have searched extensively online for a solution and have found none. This must be either a very unique issue or a very simple one.

body:
Firstly, you have a clone not a genuine Arduino Nano. They use a different USB chip and require different drivers. Install the CH340 drivers.

Secondly your cable is bad. It sounds like one with no data wires in it used for powering or charging small low-powered devices like bluetooth headsets etc. Replace the cable with a proper one.


body: When using a cheap knockoff Nano, it seems that in the newer versions of the Arduino IDE (at least in 1.8.8), you may need to select "ATmega328P (Old bootloader)" from the Processor options under the Tools menu in order to upload sketches.


body: I've seen this error a few times and renaming the serial port fixed the problem in my case. I documented the steps in detail in Tip #4 of this blog post: https://gyorgybalassy.wordpress.com/2020/10/16/cant-open-device-com-access-is-denied-arduino-upload/


message:
Sending data via bluetooth

I am trying to both send and receive data using bluetooth module.

Receiving data works fine with this code:

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

    void loop() {
        if (Serial1.available()) {
            Serial.println(Serial1.read());
        }

        delay(20);
    }

But I cannot send any data. This is what I am doing:

    void loop() {
        if (Serial1.available()) {
           Serial.println(Serial1.read());
        }

        delay(20);

        if (digitalRead(bluetoothInput) == HIGH) {
            Serial1.write("2");
            // only "send" prints. Nothing in android terminal
            Serial.println("send!");
            delay(1000);
        }

        delay(20);
    }

What am I doing wrong?

I am using Arduino Leonardo and Bluetooth terminal app on Android device.

body:
I've found the problem

It should be:

    Serial1.println("2");

instead of:

    Serial1.write("2");


message:
Can't use enum as function argument

I declared my enum and called it Dir. I wanted to use value of that type in my function Move(). Here's the code:

    enum Dir
    {
      forward = 1,
      backward = 2,
      left = 3,
      right = 4
    };

    void Move ( Dir direction , int distance )
    {
         direction = forward;
    }

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

    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

Unfortunately i get the following errors:

    V2.ino:23:13: error: variable or field 'Move' declared void
    V2.ino:23:13: error: 'Dir' was not declared in this scope
    V2.ino:23:29: error: expected primary-expression before 'int'

What's wrong?

body:
I did not experience the problem because I usually use a Makefile instead of
the Arduino IDE. I now tried with the IDE version 1.0.5 and I had the same
problem as you. The fix is to explicitly declare the function before
defining it:

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

    void Move(Dir direction, int distance);
    void Move(Dir direction, int distance)
    {
         direction = forward;
    }


body:
The Arduino 1.7.x series from Arduino.org uses the old build system that is severely broken when you try and do anything more complex than simple types.

It adds prototypes to your functions to the top of the program so you don't have to get the order right, but it puts them in completely the wrong place.  The result is a C++ file that looks like this:

    #include <Arduino.h>
    void Move ( Dir direction , int distance );
    void setup();
    void loop();

    enum Dir
    {
      forward = 1,
      backward = 2,
      left = 3,
      right = 4
    };

    void Move ( Dir direction , int distance )
    {
         direction = forward;
    }

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

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

As you can see the prototype involving `Dir` has been placed before the definition of `Dir`, and so it fails miserably.

There are some hacks you can do to force it to place the prototypes after your definition, but I can't recall what they are off hand.

The simple answer is to ditch Arduino 1.7.10 and switch to Arduino 1.6.10 from Arduino.cc instead. This uses the Arduino Builder system which does things much better, including placing the prototypes in the right place.

Despite the numbering 1.7.10 is not a newer version than 1.6.10 - it is an older version renumbered. It's all part of the schism between the two halves of Arduino.

Even better is to ditch the awful Arduino IDE entirely and use one of the many far better IDEs that exist.


body:
You have to define a new enum type:

    typedef enum
    {
      forward = 1,
      backward = 2,
      left = 3,
      right = 4
    } Dir;

    void Move ( Dir direction , int distance )
    {
         direction = forward;
    }

without `typedef` your Dir is just static enum variable, it can't be used to define other vars.


body:
As Majenko points out, this seems to be a problem with the parsing of the preprocessor.

You have two options:

Use Edgar Bonets solution and declare the function before defining it

Create a separate header file for your enum in a new tab and import it with #include "[myEnumsHeaderFilename].h"

    #include "myEnums.h"

    void Move(Dir direction, int distance)
    {
       direction = forward;
    }

    void setup() {}

    void loop() {}


message:
How to code for cascading multiplexers?

I hope I can get some help on how to get this to work.

I have multiple Sensors (32 of these) which values I want to read. I am using a master multiplexer **HC4051** connected to 4 slave multiplexers, this is my wiring:
[here][1]

I tested it using one single multiplexer and it works as intended, but when adding the slave I cannot getting it to work, I am not sure how to code for it.

When using this code:

    // 74XX4051 ADDRESS PINS :
    #define  M_S0 2
    #define  M_S1 3
    #define  M_S2 4

    #define  S_S0 7
    #define  S_S1 6
    #define  S_S2 5

    // 74XX4051 ANALOG PIN :
    #define  Z 0

    void setup() {
        // CONFIGURE ADDRESS PINS
        pinMode(M_S0, OUTPUT);
        pinMode(M_S1, OUTPUT);
        pinMode(M_S2, OUTPUT);

        pinMode(S_S0, OUTPUT);
        pinMode(S_S1, OUTPUT);
        pinMode(S_S2, OUTPUT);

        // CONFIGURE SERIAL
        Serial.begin(57600);
    }

    void loop() {
        int value;

        // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
        for ( byte count = 0; count < 4 ; count++ ) {
             // SET THE ADDRESS
             digitalWrite(M_S0, bitRead(count, 0) );
             digitalWrite(M_S1, bitRead(count, 1) );
             digitalWrite(M_S2, bitRead(count, 2) );

             // LOOP THROUGH ALL THE ADDRESSES OF THE SLAVES
             for ( byte count_1 = 0; count_1 < 32 ; count_1++ ) {
                 digitalWrite(S_S0, bitRead(count_1, 0) );
                 digitalWrite(S_S1, bitRead(count_1, 1) );
                 digitalWrite(S_S2, bitRead(count_1, 2) );

                 // READ THE ANALOG VALUE
                 value = (bitRead(count_1, 2), bitRead(count_1, 1), bitRead(count_1, 0));
             }

             // READ THE ANALOG FOR THE MASTER ADRESSE
             value = analogRead(Z);

             // SERIAL OUTPUT
             // print : ### value
             Serial.print(bitRead(count, 2));
             Serial.print(bitRead(count, 1));
             Serial.print(bitRead(count, 0));
             Serial.print(' ');
             Serial.println(value);

             delay(100);
         }
    }

I am only getting random readings really (the reading LED for the moisture sensor does not switch on when the reading is done).

What I am doing wrong? Any help is appreciated.

**UPDATE:**

i updated my code as follows :

    // Master moisture sensor pins
    #define  M_S0 7
    #define  M_S1 8
    #define  M_S2 9
    // Slave moisture sensor pins
    #define  S_S0 4
    #define  S_S1 5
    #define  S_S2 6

    // PIN from the transistor to power the sensors only when doing a reading
    int sensorVCC = 13;

    //  ANALOG PIN :
    #define  Z 0

    void setup() {
        Serial.begin(9600);
        // CONFIGURE ADDRESS PINS
        pinMode(M_S0, OUTPUT);
        pinMode(M_S1, OUTPUT);
        pinMode(M_S2, OUTPUT);

        pinMode(S_S0, OUTPUT);
        pinMode(S_S1, OUTPUT);
        pinMode(S_S2, OUTPUT);
        pinMode(sensorVCC, OUTPUT);

        digitalWrite(sensorVCC, LOW);
    }

    void loop() {

        // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
        for (int i = 0; i < 32; i++) {
        digitalWrite(sensorVCC, HIGH);
        delay(100); //make sure the sensor is powere

        digitalWrite(M_S2, i & 0b100000);
        digitalWrite(M_S1, i & 0b010000);
        digitalWrite(M_S0, i & 0b001000);
        digitalWrite(S_S2, i & 0b000100);
        digitalWrite(S_S1, i & 0b000010);
        digitalWrite(S_S0, i & 0b000001);

        delay(1);

        int humidityRaw = analogRead(Z); // 1023 to 0 ===> 0 to 100%
        int humidityReal = map(humidityRaw, 975, 523, 0, 100);
        digitalWrite(sensorVCC, LOW);

        Serial.print("Input ");
        Serial.print(i);
        Serial.print(": ");
        Serial.print(humidityReal);
        Serial.println(" % ");
        delay(1000);
    }
    }

and this is my output :

        Input 0: 100 %
        Input 1: 0 %
        Input 2: 100 %
        Input 3: 0 %
        .
        .
        .
        Input 0: 0 %
        Input 1: 100 %
        Input 2: 0 %
        Input 3: 0 %
        .
        .
        .
        Input 0: 100 %
        Input 1: 0 %
        Input 2: 0 %
        Input 3: 0 %
        .
        .
        .

ONLY channel 0 is hooked !! .... it seems that it reads with different delays. changing the delay gives me different sequence. what is wrong ?

body:
It becomes much easier if you start thinking in binary.

If you have an 8 bit multiplexer connected to four 8 bit multiplexers that gives you 32 inputs. Four of the inputs on the "master" multiplexer are unused and can be ignored.

You have 32 inputs. That's inputs numbered 0 to 31. In binary that equates to, in full,

    0 = 000000   8 = 001000  16 = 010000  24 = 011000
    1 = 000001   9 = 001001  17 = 010001  25 = 011001
    2 = 000010  10 = 001010  18 = 010010  26 = 011010
    3 = 000011  11 = 001011  19 = 010011  27 = 011011
    4 = 000100  12 = 001100  20 = 010100  28 = 011100
    5 = 000101  13 = 001101  21 = 010101  29 = 011101
    6 = 000110  14 = 001110  22 = 010110  30 = 011110
    7 = 000111  15 = 001111  23 = 010111  31 = 011111

I have laid it out like that especially so that you see a pattern occurring. Four columns with 8 rows. Four slave multiplexers with 8 inputs. A perfect match. Each column has bits that are distinct to that column. Each row has bits that are unique to that row.  So you could split those bits up and know that the left-hand three bits indicate the column, and the right-hand three bits indicate the row. Between the two it's a unique location in the table.

The same applies to the multiplexers.  The left-hand three bits indicate which slave multiplexer to use, the right-hand three bits which input to use on the selected multiplexer.

So you can loop through each of the 32 inputs with a single loop and examine the individual bits of the input number and apply those bits directly to the select outputs to control the multiplexers - the left-hand bits to the master to select which slave to use, and the right-hand bits to the slaves to select which input to use.

So you have:

    for (int i = 0; i < 32; i++) {
        digitalWrite(M_S2, i & 0b100000);
        digitalWrite(M_S1, i & 0b010000);
        digitalWrite(M_S0, i & 0b001000);
        digitalWrite(S_S2, i & 0b000100);
        digitalWrite(S_S1, i & 0b000010);
        digitalWrite(S_S0, i & 0b000001);

        delay(1);

        int reading = analogRead(Z);
        Serial.print("Input ");
        Serial.print(i);
        Serial.print(": ");
        Serial.println(reading);
    }

The `i & 0b000001` etc performs the same function as `bitRead()` but is more explicit using a mask that is far more visual as to what it achieves.

I also include a tiny delay after setting the multiplexers up so as to ensure they have settled into their new settings properly before reading. It shouldn't be needed, but it doesn't hurt.


body:
I think that you have confused your address *encoding* in your code. Your complete address space is only a total of 5 bits, decimal 0 to 31. Your two loops (`for ( byte count = 0; count < 4 ; count++ )` and `for ( byte count_1 = 0; count_1 < 32 ; count_1++ )`) are actually counting through a 7 bit address space, just with the 3 MSBs of the inner loop being ignored.

For your 32-input example, I'm going to assume that the master 4051 only has inputs A-D (`y0` to `y3`) connected to downstream muxes and that the analog mux decodes based on the binary value of the input select. Then your digital outputs should correspond to, for `byte address` as your counter:

- `S_S0` -> `bitRead(address, 0)` (LSB)
- `S_S1` -> `bitRead(address, 1)`
- `S_S2` -> `bitRead(address, 2)`
- `M_S0` -> `bitRead(address, 3)`
- `M_S1` -> `bitRead(address, 4)`
- `M_S2` -> constant `0` (MSB)

Thus, your test should only use a `for ( byte address = 0; address < 32 ; address++ )` to acquire data from all 32 possible inputs. Remember to have a long enough delay from selecting a different multiplexer input to starting your ADC conversion to avoid errors due to signal settling.

Additionally, you should be calling only one analog read location corresponding to the pin connected to the `AnalogInPin` in the schematic. You will have to record what the current multiplexer selection to determine which of the 32 inputs is actually being recorded by that conversion. Basically, there's only one 'master" analog input.

Your use of `value = (bitRead(count_1, 2),bitRead(count_1, 1),bitRead(count_1, 0));` is confusing and seems incorrect. After you `digitalWrite()` the new address for your multiplexers, you shouldn't need to read-back the digital pins to know what address you have selected.


message:
Arduino 2560 as an Interface to 4 Serial Hardwares

I am writing a software that runs on the PC that has a Arduino 2560 connected to it via USB. This PC needs to communicate with multiple devices through RS232.

Is it possible to use the Arduino's 4 UARTs to communicate with 4 different hardware that uses RS232 serial communication, using just 1 USB connection between the PC and the Arduino 2560?

The Arduino 2560 will basically act as an interface for 1 USB to talk to 4 RS232 devices.

body:
No, but it is possible to use 3 of them. The reason being that one of them is the connection to the computer.

The hard part is in the programming. You will need not only a suitable sketch on the Arduino (the easy part), but also some software on your computer that presents three COM ports to the operating system and forwards the data through to the Arduino in a suitably packeted format, and receive data back and sent it on to the right COM port.  Depending on your operating system that may be a very easy task (on Linux and OS X) or a complete and utter nightmare (Windows).


body:
In Arduino terms:

Serial will be committed to receiving data from the PC.

Connecting Serial1, Serial2, and Serial3 via RS232 will be easy.

Adding a 4th Software Serial (or NewSoft Serial or AltSoft Serial) via RS232 will also be straightforward. If you need high speeds for the 4th port, than a UART with SPI (or I2C) interface to the Mega might be a better idea.

The only tricky part is putting in some info in the data from the PC so the Mega can re-send it to the correct port.


message:
Connect to Arduino 2560 using a RS232 Connection

Is it possible to connect to an Arduino 2560 using a RS232 (DB9) connection rather than the regular connection using USB cable?

I am thinking of this connection scheme:

    PC -> USB cable -> USB to RS232 Multiplexer -> DB9 Cable -> Adapter board -> Arduino 2560

body:
Yes, perfectly possible.  You need an RS-232 interface chip - the most common and well-known of these is the MAX232. You can get them as breakouts on eBay.

That interfaces between the DB9 and pins 0/1 (or other UART comms pins) on the Arduino.

If you are wanting to program the board through it you will also need to connect (after converting the voltage through the MAX232) the DTR line to RESET through a 100nF capacitor.

... Exactly like you would with a breadboard Arduino.


message:
Releasing gas from a bottle via Arduino - opening a valve?

I'm looking for a mechanical component that enables me to do two things:

 - contain a gas in a bottle and if opened, the gas should smoothly flow out (with the same pressure as a child blowing out candles on his birthday cake)
 - a valve for the bottle that can be opened by an Arduino when powered via USB

I already figured out that there are outlets for CO2 capsules. This could work, but then I'd need to figure out a way to decrease the pressure in order to receive a gentle gas flow.

Do you know any better approaches? Thanks in advance!

body: If you can tolerate a decreasing flow as the pressure in the bottle drops, a simple restrictor (fluidic equivalent of a resistor) will limit the flow but of course, I = E/R; the flow will be proportional to the bottle pressure. If that is acceptable, it is probably the cheapest, simplest, and most reliable way.


body:
You can use the product "electronic expansion valve" to control gas, also you can control valve openness degree this is optional, then put in CO2 capsules closed box also add air pressure sensor in the box, air pressure sensor controls valve to set up gas pressure, make one hole to box the gas out from here thereafter measure the pressure what you want.
Also do you need a mechanic component to control CO2 capsule?


message:
Water valve for food

I am working on a project, where i need to control the flow of a liquid made from food.

For example: making chicken curry, I will separate all the liquid from the meat, and run that tough a pipe, where this control pipe is on.

But I have been unable to find a subtle valve for this, as the liquid on all of them will flow tough the mechanics of the valve, and this would not be optimal as it would make it impossible to clean, and it would diffidently get stuck.

Can one of you suggest a valve that would work for this case?

body:
I would suggest, instead of a valve, a [Peristaltic Pump](https://en.wikipedia.org/wiki/Peristaltic_pump).

In short, it comprises a set of rollers that squeeze a flexible tube and push the fluid along. It has good advantages for food use:

* Very easy to clean - only the inside of the tube needs cleaning
* Pumped fluid is not in physical contact with the pump mechanism so can't be contaminated.

They are used in many sterile environments - medical, industrial, etc., because they are so easy to keep clean and have no way of contaminating the pumped fluid. They are also good with viscous (sticky, gloopy) fluids like soups and sauces.

They can also deliver precisely measured amounts very easily.


message:
Serial Port greyed out Ubuntu 16.04

I am running Ubuntu Mate 16.04 LTS, with an Arduino Uno R3 clone. I am having the dreaded serial port graying out problem, and have not found a solution for fixing it. Currently, The serial port will grey out sometimes, and sometimes it will be not grayed out, and I can see that I have selected ttyUSB0. Usually when it is not grayed out, uploading a sketch will not work, and I get the error like it is grayed out:

> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
An error occurred while uploading the sketch

    chmod a+rw /dev/ttyUSB0
doesn't solve the issue, with log out included

    gpasswd -a aaron dialout
doesn't solve the issue, with log out included

I searched preferences.txt and serial.debug rate is set to 9600

I have tried entering preferences.txt and deleting all of the serial entries. They are recreated the same after deletion, and this doesn't solve anything.

I tried running as sudo, doesn't work.

I tried solving this originally on Arduino IDE 1.0, didn't work.

I have upgraded to Arduino IDE 1.6.10, still not working.

running lsusb in terminal yields this while Arduino is plugged in:

    Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
    Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 001 Device 003: ID 0a5c:21e6 Broadcom Corp. BCM20702 Bluetooth 4.0 [ThinkPad]
    Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Checking var/log/syslog after plugging in Arduino:

>kernel: [42043.787178] usb 3-2: new full-speed USB device number 109 using xhci_hcd

>kernel: [42043.916241] usb 3-2: New USB device found, idVendor=1a86, idProduct=7523

>kernel: [42043.916249] usb 3-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0

>kernel: [42043.916253] usb 3-2: Product: USB2.0-Serial

>kernel: [42043.916964] ch341 3-2:1.0: ch341-uart converter detected

>kernel: [42043.918199] usb 3-2: ch341-uart converter now attached to ttyUSB0

>mtp-probe: checking bus 3, device 109: "/sys/devices/pci0000:00/0000:00:14.0
/usb3/3-2"

>mtp-probe: bus: 3, device: 109 was not an MTP device

Ran to add to dialout group, then logged out

    sudo usermod -a -G dialout aaron

No solution.
So it looks like Arduino board is not being recognized. Not sure what to try next. It is important that I have uploaded sketches before, but am not sure if there is a pattern to when it does not work. It does not work 95% of the time.

Thanks for the help!

body:
I have the same problem,
I believe that the problem is related to the 4.x kernel, since I have already tried another distribution with the kernel mermo and the problem persists. Using a windows virtual machine as guest works, which excludes communications and hardware issues.


message:
UVB sensing with Arduino

As part of the research I am involved with, the detection (not imaging) of UV (ultraviolet) sources, either emitters or reflectors is an important factor.

I am aware of the [SparkFun UV Sensor Breakout - ML8511][1] component, which, according to the [product specifications][2], has a decent broadband response across the UVA and UVB, with little amount of visible light.

Is there an Arduino component that only detects the UVB waveband (280nm to 320nm)?

  [1]: https://www.sparkfun.com/products/12705
  [2]: https://cdn.sparkfun.com/datasheets/Sensors/LightImaging/ML8511_3-8-13.pdf

body:
The SparkFun board you mentioned should detect UVB and UVA, but I guess, from your question, that you want one that cannot detect UVA.

Basically any device that has an I2C interface *should* work with an Arduino as long as you know how to interface with the device in the code.

If your intention is professional research, than a demo device such as the SparkFun may not fit your needs anyway as it will not be particularly accurate and is mainly intended as a little board to play about with on your Arduino and say "Hey, look, there's UV light there!"

The answer to your question is that the best place to look is above the consumer range, at some higher-end UV sensors that are not generally suitable for the little Arduino demos due to price, but may give you much more accurate readings and only sense the UVB waveband.


message:
help with arduino programming

my project involves:
1 ultrasonic sensor.
1 servo motor.
3 leds.
when a person comes in range of ultrasonic sensor (7 to 20),servo turns by 150 degree.
then ultrasonic sensor check again if the person is in range, if yes then led1 turns on for 10sec n turns off, still if the person in in range then led2 turns on for 10sec and turns off, still if the person is in range then led3 turns on for 10sec and this keep on repeating for the leds(led1, led2, led3 but servo is still in 150)
once detected and the person is not detected the leds should not glow and servo should return to 0

code:

    if ((distance1>7)&&(distance1 <= 20))
     {
      myservo1.write(150);
      delay(1000);
     }
     {
      if ((distance2>7)&&(distance2 <= 20))
       {
       digitalWrite(led1,HIGH);
       delay(1000);
       digitalWrite(led1,LOW);
       }
      if ((distance1>7)&&(distance1 <= 20))
       {
       digitalWrite(led2,HIGH);
       delay(1000);
       digitalWrite(led2,LOW);
       }
       if ((distance1>7)&&(distance1 <= 20))
       {
       digitalWrite(led3,HIGH);
       delay(1000);
       digitalWrite(led3,LOW);
       }
    else
    {
     myservo1.write(0);
      }

but this code does not work the way i want.
it blink the leds even when there is no person in range.
need help in programing so that the leds blink only when ultrasonic detects the person in range and stops when person is not detected.
thank u in advance

body:
Your indenting doesn't match your code.

Right after the very first `if` (without an `else`), you have a new open brace (`{`). This looks wrong:

    if ((distance1>7)&&(distance1 <= 20))
     {
      myservo1.write(150);
      delay(1000);
     }
     { // <<<< What is this?

The very very final `else` matches the very very final `if` - certainly not the first `if`!

Also, what is the difference between `distance1` and `distance2`? You only have one ultrasonic sensor - there is only one `distance`!

### EDIT:

I think what you need to do is use `loop()` more effectively. At the moment, you're pausing in the middle of your code, rather than letting the rest of the code work and using `millis()`. That function returns the number of milliseconds since the program started - which you can use for your problem (with a little mathematics):

### EDIT 2:
I've added a little extra code to play different tunes depending on the current state. It uses the library at http://www.rhydolabz.com/other-widgets-c-205_124/mini-mp3-player-module-p-2159.html

    static unsigned lastMilli = 0;
    static byte lastLED = 0;
    static const byte LEDs[] = { led1, led2, led3 };

    distance1 = // Whatever you call to get the distance...
    if (distance1>7) && (distance1<=20)) { // Too close?
       if (lastMilli==0) {       // Is this new???
           lastMilli = millis(); // Yes! Record that...
           mysero.write(150);    // ...and set servo.
       } // if
       unsigned delay = millis() - lastMilli; // Get how long it's been
       byte which = delay / 10000 % 3;        // Which LED / tune?
       byte LED = LEDs[which];                // Which LED?
       if (LED != lastLED) {                  // Has LED changed?
           if (lastLED!=0) {
               digitalWrite(lastLED, LOW);    // Yes! Stop that one
           } // if
           mp3_single_loop(true);             // Play forever!
           mp3_single_play(which+1);          // Play "mp3/000#.mp3"
           lastLED = LED;
           digitalWrite(LED, HIGH);           // And start the new one
       } // if
    } // if
    else if (lastMillis!=0) { // They're gone!
        digitalWrite(lastLED, LOW); // No LED
        myservo.write(0);           // No servo
        lastMilli = 0;              // So start again
        lastLED = 0;
        mp3_stop();
    } // else


message:
SIM900 TCP Connection issue

I am having a strange issue where if I try and create a TCP connection to my service, it doesn't work. But any other website, such as google, works fine. The serial monitor output is also slightly different, but I cannot see any difference in the code. I am using [this][1] module for communications.

This is the method that I am using:

    void SendPost()
    {
      Serial1.println("AT+CGATT?");
      delay(1000);
      ShowSerialData();

      Serial1.println("AT+CSTT=\"everywhere\"");//start task and setting the APN,
      delay(1000);
      ShowSerialData();

      Serial1.println("AT+CIICR");//bring up wireless connection
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+CIFSR");//get local IP adress
      delay(2000);
      ShowSerialData();

      Serial1.println("AT+CIPSPRT=0");
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+CIPSTART=\"tcp\",\"www.google.com/\",\"80\"");//start up the connection //https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register
      delay(5000);
      ShowSerialData();

      Serial1.println("AT+CIPSEND");//begin send data to remote server
      delay(4000);
      ShowSerialData();

      Serial1.println("{\"device_info\":\"breadcrum-prototype-a\"}");
      delay(500);
      ShowSerialData();

      Serial1.println((char)26);//sending
      delay(5000);//waitting for reply, important! the time is base on the condition of internet

      Serial1.println();
      ShowSerialData();

      Serial1.println("AT+CIPCLOSE");//close the connection
      delay(100);
      ShowSerialData();
    }

Using 'www.google.com' I get an OK upon tcp connection (with an expected error on the data as I try to POST):

    Setup CompleteAT+CGATT?

    +CGATT: 1

    OK
    AT+CSTT="everywhere"

    OK
    AT+CIICR

    OK
    AT+CIFSR

    100.66.4.95
    AT+CIPSPRT=0

    OK
    AT+CIPSTART="tcp","www.google.com/","80"

    OK

    STATE: IP STAAT+CIPSEND

    ERROR
    {"device_info":"breadcrum-prototype-a"}

    AT+CIPCLOSE

    ERROR

But using the address I actually want to post data to (https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register), it cannot connect and I get this:

    Setup CompleteAT+CGATT?

    +CGATT: 1

    OK
    AT+CSTT="everywhere"

    OK
    AT+CIICR

    OK
    AT+CIFSR

    100.66.4.95
    AT+CIPSPRT=0

    OK
    AT+CIPSTART="tcp","https://rocky-garden-56471.herokuapp.com/breAT+CIPSEND

    ERROR
    {"device_info":"breadcrum-prototype-a"}

    AT+CIPCLOSE

    ERROR

This errors on connection, and you can also see that the full address isn't printed out for some reason. Does anyone have any idea what could be causing this issue?

Thanks :)

EDIT:
@Majenko, my previous version did what I believe you are describing. The issue being I got an error that I struggled to resolve so attempted this version. The previous version is:

    void SubmitHttpRequest()
    {
      Serial1.println("AT+CSQ");
      delay(100);
      ShowSerialData();

      Serial1.println("AT+CGATT?");
      delay(100);
      ShowSerialData();

      Serial1.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR, the connection type is using gprs
      delay(1000);
      ShowSerialData();

      Serial1.println("AT+SAPBR=3,1,\"APN\",\"everywhere\"");//setting the APN, the second need you fill in your local apn server
      delay(4000);
      ShowSerialData();

     //Enable GPRS
      Serial1.println("AT+SAPBR=1,1");
      delay(2000);
      ShowSerialData();

      //Query if connection is setup correctly, return IP address if it is
      Serial1.println("AT+SAPBR=2,1");
      delay(2000);
      ShowSerialData();

      Serial1.println("AT+HTTPINIT"); //init the HTTP request
      delay(2000);
      ShowSerialData();

    //Set up bearer profile identifier (NEW PART)
      Serial1.println("AT+HTTPPARA=\"CID\",1");
      delay(2000);
      ShowSerialData();

      Serial1.println("AT+HTTPPARA=\"URL\",\"https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register\"");// setting the httppara, the second parameter is the website you want to access
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+HTTPDATA=1000,10000");
      delay(3000);
      ShowSerialData();

      Serial1.println("{\"device_info\":\"breadcrum-prototype-a\"}");
      delay(3000);
      ShowSerialData();

      Serial1.println("AT+HTTPACTION=1");//submit the request //0:READ 1:POST 2:HEAD
      delay(10000);//the delay is very important, the delay time is base on the return from the website, if the return datas are very large, the time required longer.
      ShowSerialData();

      Serial1.println("AT+HTTPREAD");// read the data from the website you access
      delay(1000);
      ShowSerialData();

      Serial1.println("");
      delay(100);
    }

But the results I got from this was another error when attempting to post:

    Setup CompleteAT+CSQ

    +CSQ: 18,0

    OK
    AT+CGATT?

    +CGATT: 1

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

    OK
    AT+SAPBR=3,1,"APN","everywhere"

    OK
    AT+SAPBR=1,1

    OK
    AT+SAPBR=2,1

    +SAPBR: 1,1,"19.177.18.205"

    OK
    AT+HTTPINIT

    OK
    AT+HTTPPARA="CID",1

    OK
    AT+HTTPPARA="URL","https://rocky-garden-56471.herokuapp.com/breAT+HTTPPARA="CONTENT","application/json"

    OK
    AT+HTTPDATA=1000,10000

    DOWNLOAD

    ERROR
    AT+HTTPREAD

    OK

EDIT 2:
Following HTTPS commands:

     AT+CSQ

    +CSQ: 18,0

    OK
    AT+CGATT?

    +CGATT: 1

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

    OK
    AT+SAPBR=3,1,"APN","everywhere"

    OK
    AT+SAPBR=1,1

    ERROR
    AT+SAPBR=2,1

    +SAPBR: 1,1,"31.94.203.234"

    OK
    AT+HTTPSSL=1

    OK
    AT+HTTPINIT

    OK
    AT+HTTPPARA="CID",1

    OK
    AT+HTTPPARA="URL","https://rocky-garden-56471.herokuapp.com/breAT+HTTPPARA="CONTENT","application/json"

    OK
    AT+HTTPDATA=100,10000

    DOWNLOAD

    ERROR
    AT+HTTPREAD

    OK
    AT+HTTPTERM

    OK

  [1]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield

body:
There is so many things wrong that I don't know where to start.

1. You are trying to use a URL in place of a hostname.
2. You are trying to connect to an HTTPS service which runs on port 443 not on port 80
3. HTTPS is encrypted. You are opening a plain TCP socket to an encrypted service.

Your whole methodology is wrong. You need to use the [SIM900 HTTPS AT Command Set](http://simcom.ee/documents/SIM900/SIM900_HTTPS AT Command Set_V1 00.pdf) to get the SIM900 to perform an HTTPS request on your behalf rather than opening a socket and sending / receiving data.


message:
A lot of "undefined reference" errors

I'm trying to create a program for my robot, but something is not right.
Here's the code:

    #include <SPI.h>
    #include <Tone.h>
    #include <Wire.h>   // standardowa biblioteka Arduino
    #include <LiquidCrystal_I2C.h> // dolaczenie pobranej biblioteki I2C dla LCD

    //Enums:
    enum Dir
    {
      forward = 1,
      backward = 2,
      left = 3,
      right = 4
    };

    enum State
    {
        movingForward = 1,
        movingBack = 2,
        turningLeft = 3,
        turningRight = 4,
        doingNothing = 5,
        readyToMove = 6 //Potrzebne?
    };

    enum SpeedState
    {
      slowingDown = 1,
      maxSpeed = 2,
      accelerating = 3,
      notMoving = 4
    };

    //Classes:
    LiquidCrystal_I2C lcd1(0x27, 20, 4);

    //Base class for devices
    class Device
    {
        public:
            virtual void Init() = 0;
    };

    //STEPPER::
    class StepMotor: public Device
    {
        public:
            int motorPin;
            int dirPin;
            int sleepPin;

            void Init ( void )
            {
                pinMode(motorPin, OUTPUT);
                pinMode(dirPin, OUTPUT);
                pinMode(sleepPin, OUTPUT);

                toneObject.begin(motorPin);
            }

            void SetSpeed ( int speed )
            {
              toneObject.play(speed);
            }

        private:
          Tone toneObject;
    };

    //VARIABLES:
    int a = 1; //przyspieszenie (przyrost prędkości i jej ubytek przy hamowaniu
    int s_accelerating = 1; //droga przyspieszania [mm]
    int s_braking = 1;  //droga hamowania [mm]

    class Robot
    {
        public:
            static float x;
            static float y;
            static float t;
            static State state;
            static SpeedState speedState;
            static int currentSpeed;
    };

    class MoveOrder
    {
      public:
        static Dir direction;
        static int distance;
        static int speed;
        static int distanceRemaining;
        static int distanceMade;
    };

    //FUNCTIONS:
    void SetInterrupt ( void )
    {
        noInterrupts();           // disable all interrupts
        TCCR5A = 0;
        TCCR5B = 0;
        TCNT5  = 0;
        OCR5A = 310;            // compare match register 16MHz/256/2Hz   400 okolo 6.4ms  380-6.1ms 300-4.9ms
        TCCR5B |= (1 << WGM12);   // CTC mode
        TCCR5B |= (1 << CS12);    // 256 prescaler
        TIMSK5 |= (1 << OCIE1A);  // enable timer compare interrupt
        interrupts();             // enable all interrupts
    }

    void SetSpeed ( int speedValue )
    {
       //currently empty
    }

    void setup()
    {
        SetInterrupt();
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

    ISR(TIMER5_COMPA_vect)
    {
        if (Robot::state != doingNothing)
        {
            if (Robot::state == movingForward || Robot::state == movingBack )
            {
              if (MoveOrder::distanceMade < s_accelerating)
                {

                    Robot::currentSpeed += a;

                    SetSpeed(4);

                }
            }
        }
    }

Compilation returns this:

    Arduino:1.6.10 (Windows 10), Płytka:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

    C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_21':

    ccU9OfJk.ltrans0.o:(.text+0x812): undefined reference to `Robot::state'

    ccU9OfJk.ltrans0.o:(.text+0x816): undefined reference to `Robot::state'

    C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_47':

    ccU9OfJk.ltrans0.o:(.text+0x820): undefined reference to `MoveOrder::distanceMade'

    ccU9OfJk.ltrans0.o:(.text+0x824): undefined reference to `MoveOrder::distanceMade'

    ccU9OfJk.ltrans0.o:(.text+0x82e): undefined reference to `Robot::currentSpeed'

    ccU9OfJk.ltrans0.o:(.text+0x832): undefined reference to `Robot::currentSpeed'

    ccU9OfJk.ltrans0.o:(.text+0x838): undefined reference to `Robot::currentSpeed'

    ccU9OfJk.ltrans0.o:(.text+0x83c): undefined reference to `Robot::currentSpeed'

    collect2.exe: error: ld returned 1 exit status

    exit status 1

I noticed that when I comment these lines:

            Robot::currentSpeed += a;

            SetSpeed(4);

errors are gone. Why?

body:
Because you have only *declared* the class static variables; you never *defined* them.  For the `Robot` class, you must have:

    class Robot
    {
        public:
             ...
    };

    float      Robot::x;
    float      Robot::y;
    float      Robot::t;
    State      Robot::state = doingNothing;
    SpeedState Robot::speedState = notMoving;
    int        Robot::currentSpeed;

    void setup()
    {

Ditto for other classes.  (Dangit, Mikael!  :) )


message:
How to increase voltage of Arduino?

Hey I'm very new to Arduino. I don't have very much knowledge in electrical engineering either.

My project: an EL wire working on Arduino. Since the Arduino can only support 5V and the wire needs 120V, how can I make sure that it works? (I assume the voltage provided by the Arduino is not high enough for the EL wire to operate.)

body: In this case, you can use relays. You can give your supply voltage (120v as you said) to EL via relays. And you can switch ON and switch OFF your EL by controlling relays with Arduino.


body:
There are two ways of tackling this.  You can either switch the low-voltage DC power to the EL wire inverter (which is safe and easy) or you can switch the high voltage AC power out of the inverter (which is harder, more dangerous, but does allow you to route the power to different EL wires for animation).

The former can be arranged in just the same way as switching any heavy load from an Arduino - with an N-channel MOSFET as a low-sided switch, or a combination of N- and P-channel MOSFETs as a high-side switch. You could add further isolation with a relay should you wish. BJTs could be used instead of MOSFETs but MOSFETs are better at switching higher currents from low current sources.

For switching the high-voltage side you will need a TRIAC circuit. While it is possible to switch a TRIAC direct from the Arduino it is preferred to opt-isolate the system from the Arduino both for safety and ease of switching at higher voltages.

The most common opto-isolator to use is the MOC3041 Opto-Isolated Triac. This is used to switch the gate of a higher voltage / power TRIAC to switch the load.

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

In that circuit the "220V" comes from the EL inverter, and the LOAD is the EL wire itself. Each EL wire you want to switch would use a copy of that circuit, but can (power permitting) use the same inverter as the source.

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


message:
How to convert Arduino GSR values to microsiemens?

In my project Arduino provides value range between 0-1024. I need to convert this serial value to a standard µSiemens value to measure emotional stress.

Can anybody point me to an answer that would give an appropriate equation for the conversion?

body:
A Siemens (aka a Mho) is a unit of conductance, the inverse of resistance.

You have a measure of the voltage (A/D value) between the pads so you can find voltage. You'll also need to know the current between the pads.
Convert your A/D reading into voltage and use that and the current to find resistance (using Ohm's law), and the reciprocal of the resistance is in Siemens. 1 Siemens == 1,000,000 uSiemens.

[https://en.wikipedia.org/wiki/Siemens_(unit)][1]

  [1]: https://en.wikipedia.org/wiki/Siemens_(unit)


message:
build simple IR sensor with 220 ohm and 1000 ohm resistors

I am brand new to the arduino board and I am trying to build a simple IR proximity sensor. I bought a handful of emitters and detectors from amazon here:

https://www.amazon.com/gp/product/B01HGIQ8NG/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1

I am about to pull my hair out and shoot my board with a 12 gauge shot gun if I don't figure this out soon. Can someone point me to a good SIMPLE tutorial that uses ONE emitter and ONE detector and ONE LED. All i can find are a bunch of complex circuits with multiple sets of sensors or a buzzer or whatever else and anything that is as simple as that has no information on schematic or code. Can someone please post a tutorial link?

body:
You could always start out attempting a simple IR detector circuit.

Google Arduino IR detector brings up several tutorials, such as [this one from the Instructables website][1]

You would have to change the buzzer in tutorial for an LED and resistor in series.

  [1]: http://www.instructables.com/id/ARDUINO-Burglar-Alarm-Using-Infrared-Emitter-Detec/?ALLSTEPS


message:
Serializing data created by ATTiny85 for use on PC

Have an AES-128 implementation I'd like to install on an ATTiny85 for embedded use but need to come up with a way to **communicate with it from a PC** as you would do via Serial on Arduino Uno. For example, I'd like to stream 16 bytes of plaintext and get back 16 bytes of ciphertext (or signature hash, etc.).

The faster the transfer rate, the better obviously, but it would of course need to fit on the remaining space on an ATTiny85.

Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

body:
So thanks to Ignacio Vazquez-Abrams' tip, it looks like I'll be able to accomplish this with [V-USB](https://www.obdev.at/products/vusb/index.html):

> V-USB is a software-only implementation of a low-speed USB device for
> Atmel’s AVR® microcontrollers, making it possible to build USB
> hardware with almost any AVR® microcontroller, not requiring any
> additional chip.

**Requirements:** AVR microcontroller with at least 2 kB of Flash memory, 128 bytes RAM and a clock rate of at least 12 MHz.

Taken from [ATTiny85's Datasheet](http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf):

> - 8K Bytes of In-System Programmable Program Memory Flash
> - 512 Bytes In-System Programmable EEPROM (enough for third-two 16-byte keys)
> - 512 Bytes Internal SRAM

Looking forward to trying it out :)


body:
> Any thoughts or working examples out there (i.e. I2C for PC, etc.) without incurring a lot of extra hardware cost?

Yet another alternative is to use the Display Data Channel (DDC) on the PC. This is 5V and I2C. Unfortunately not all PC video boards support I2C. Please see the [reference][1] for further details.

I2C is supported on ATtiny by the USI module.

Cheers!

  [1]: http://www.instructables.com/id/Worlds-Cheapest-I2C-I-Squared-C-Adapter/?ALLSTEPS


body:
> need to come up with a way to communicate with it from a PC

would be difficult to make an uart out of usi?


message:
Esp8266 firmware update with uno "chip sync error"

I have an ESP8266-01. I followed the instructions on this

http://yaab-arduino.blogspot.com/2015/12/flashing-esp8266-firmware-arduino.html?m=1

 exactly. When I start the firmware update the TX and RX pins blink rapidly along with the blue light on the ESP.

Then the terminal spits out "chip sync error" and disconnects.

I would like this to work because buying a ftdi cable isn't an option right now.

body: I run the same problem too and took me countless hours to figure this error out. The problem seems the Baud rate starts at 115200 while the COM port is set to 9600. What I did is I checked the Device Manager and find the COM port, right clicked to properties and to the Port Settings Tab, I changed the Baud Rate to 115200 and flash the firmware again. And it works!


body: just after compilaion starts in the arduino ide , press and hold the flash button and then press the reset button , now release the reset button and finally release the flash button, this is how the esp goes into flash mode.this will work


message:
most effective ( progsize/speed ) SD card usage

I am making a project with several modules and libraries involved. I just tested the SD lib example, and got a binary at ~14KB  - way too much. I'd like the SD bits to go below 8KB, since it's just for logging from an NFC and RTC module. I notice some 'stabs' debug bits in my Makefile, and wonder if I could do something with that. Besides that, perhaps the experts here can recommend a smaller library for my SD bits, so I won't exceed my ~27KB flash capacity. I am using the SD example for creating/deleting files. Ask me to clarify if needed.

body:
For AVR + SDCard you should check [FatFs][1] from Chang. It is widely used and proven C library. You can [tweak the configuration][2] file to get minimal size (8K shall be easy). Check wrapper library for Arduino [here][3] (6K with default options).

There is also even smaller version called [Petit FAT][4] (2-4K) but it doesn't support file delete feature.

  [1]: http://elm-chan.org/fsw/ff/00index_e.html
  [2]: http://elm-chan.org/fsw/ff/en/config.html
  [3]: https://github.com/greiman/PetitFS
  [4]: http://elm-chan.org/fsw/ff/00index_p.html

If you would like to get smallest possible code, there is option to use Atmel Studio for programming Arduino boards, but you will loose the convenience of Arduino libraries (re-implement the libraries or find AVR versions of them, work with registers directly etc).


message:
FastLED int + float problem

I'm working on a code based on [PaletteCrossfade.ino][1] example. But I found the motion speed too fast. It's stated in this:

      static uint8_t startIndex = 0;
      startIndex = startIndex + 1; /* motion speed */
      FillLEDsFromPaletteColors(startIndex);
      FastLED.show();
      FastLED.delay(1000 / UPDATES_PER_SECOND);
    }

    void FillLEDsFromPaletteColors( uint8_t colorIndex) {
      uint8_t brightness = 255;
      for( int i = 0; i < NUM_LEDS; i++) {
        leds[i] = ColorFromPalette( currentPalette, colorIndex + sin8(i*16), brightness);
    colorIndex += 3;

Since the startIndex defined in `uint8_t`, it cant be lower than 1. So I used float and set it to 0.2 in my code. Which seems to work, and animation slowed down. However I'm not sure how is that float value added into the `ColorFromPalette` function.

[Its documentations states][2]:
> CRGB  ColorFromPalette (const CRGBPalette16 &pal, uint8_t index,
> uint8_t brightness=255, TBlendType blendType=LINEARBLEND)

To my understanding it accepts only integer, and also int based sin8 being added to float value. So, what exactly happens there? Is this method viable, or is there any better way to slow down the animation?

I'm thinking about adding a millis() based delay and only increasing the colorindex every 2-3 seconds or so.

  [1]: https://gist.github.com/kriegsman/1f7ccbbfa492a73c015e
  [2]: http://fastled.io/docs/3.1/group___colorutils.html

body:
The code you have seems to fill the lights with a colour and change every nth of a second.  You could control that to change every 1ms to 2^16ms (which is 65 seconds) just by changing the FastLED.delay() value.

sin8() might return a float or I suspect an int, but colourIndex is an uint8_t so that is a whole number.  All it is doing is picking a colour, based on some scheme.  If the value passed to the function is a float i.e. 1.611 then it will be converted to an int by taking just the whole number part, in this case 1.  It does not round up.

Its not clear what you are trying to do.

If you are trying to slow the rate that the LEDs change colour, you need to change the delay statement.

If you want to smooth the transition between colours you need to change in the area of the sin8 statement, but what you change it to will depend on what your palette is loaded with.

Hope that helps, if not please can you try and describe what it is you are tying to achieve.


body:
In order to change the update rate you have to change it.

You have two choices in ColourPalette example:

1st:
# LINE 10

    #define UPDATES_PER_SECOND 100 // higher number means more frames a second
2nd:

# LINE 58

    FastLED.delay(1000 / UPDATES_PER_SECOND); // change it to:
    FastLED.delay(2000); //2000ms means 0.5 frame per second or 1 frame every two seconds


message:
how to find find out capacitance using time constant?

i'm trying to find out the capacitance value using the time constant of the RC ciruit. so i followed the technique on the below link.

http://www.gammon.com.au/forum/?id=12075

Now, it's working fine.. but still i need wider range so i want to know the full core logic of that program like how the capacitance formula has been derived out in those program?

thanks in advance...

body:
The key concept is this line:

> ... we find the point where the voltage reaches 63.2% ...

The time constant τ is how long it takes for a capacitor to charge up to 63.2% of the supply voltage. That is governed by both the capacitance (C) and the resistance (R). τ=RC. That is one of the basic formulae you should know as an Electronic Engineer.

If you know R (which you do because you chose it at 10KΩ) and you know τ (which you do because you measured it) then you can calculate C (τ/R).

Since τ, C and R are tied together like that it is possible to change the balance of C and R and keep τ the same. For instance, a 10KΩ resistor and a 47nF capacitor would give the same τ as a 1KΩ resistor and a 470nF capacitor. Also the same τ as a 100kΩ resistor and a 4.7nF capacitor.

You can easily change the range without having to change your time measurement system by changing the resistor to give a different scale.


message:
Identifying Bootloader ttyACM# device

I'm using a modified version of Arduino Zero Bootloader. I am trying to write software to automatically detect which USB device the bootloader is currently running on in order to execute bossac.

I have noticed a few unique characteristics when using "lsusb -v". Things like "bDeviceClass" is always 2. and "bDeviceSubClass" is always 0; However, I do not feel confident in using these traits to identify the bootloader. Is there any clear indication of bootloader so I can find the correct ttyACM#?

body:
The only things you have at your disposal are what is in `lsusb -v`. Using those you can craft a `udev` rule to create a symlink to a unique device name. I do that with all my boards so that they all get a unique name.

Here is one of my rules:

    ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0042",
      ATTRS{serial}=="95336333635351F091B1", KERNEL=="ttyACM*",
      MODE="0660", GROUP="plugdev", SYMLINK+="board/arduino/mega2560"

That links `/dev/board/arduino/mega2560` to whatever `/dev/ttyACM*` node got created when it was plugged in.  That is in `/etc/udev/rules.d/50-boards.rules`

More on udev here: http://playground.arduino.cc/Linux/Udev

A useful command is `udevadm info -a -n /dev/ttyACM0` which lists all the attributes for that device which you can then use in the `udev` rule.


message:
switch pump on with transistor, mosfet, or relay

I would like to control a pump.
The pump rating is 12 volt 60watts.
The pump mfg says to use a 12 volt power supply of 5 - 12 amps but AT LEAST 5 amps. This pump has a pressure turn off at 116 psi and the mfg states that the pump will not make maximum pressure with less than 5 amps.

So the question becomes, to be able to switch this pump on and off based on some sensor reading what would be considered best practice:
transistor, MOSFET, or relay?

body:
* Transistor - Big voltage drop between C-E @ 5A (depends on type but it will be about 2V). Power dissipitation is voltage drop times current so about 24Watts. You must be careful with inductive load - induced high voltage must be supressed. Usual way is using anti-parallel fast diode over load.

* Mosfet - Voltage drop can be really small, so it might be possible to use it without heatsink. Big Gate capacity needs strong driver to charge and discharge. If not, slow switching causes huge losses (again voltage drop times current). For inductive load it's same as for transistor.

* Relay - It must be selected carefully as switch-off causes electric arc (= burning contacts) and because of DC current it's burning for much longer time than AC.


body:
The problem with a MOSFET is that at 5A you might find that the arduino output pin can't deliver enough voltage to the gate of the MOSFET to get it to fully turn on.

For the transistor, it is possible to use a transistor however it is probably best to construct it as a high side switch as opposed to a low side switch. This is to deal with potential problems that may arise with disconnecting the ground from the pump whilst running.
[This is a good article which explains why low side switching can be bad][1]

The best possible solution in this circumstance would be to use a relay connected to a NPN transistor which switches the low side of the relay. This isolates the delicate arduino electronics from the pump.

[![enter image description here][2]][2]

  [1]: http://jeelabs.org/2012/11/11/low-side-switching/
  [2]: https://i.stack.imgur.com/xMxjg.png


message:
Reading Two Quadrature Encoder using a single Arduino Due

I am working on an autonomous robot in my summer vacations. I am currently working on running the motors of my robot in a closed loop. In order to do so, I have to interface **two Quadrature encoders** of the motors with the Arduino Due that I have. My motor encoder have **3200 Edges per Revolution**. I have read the Atmel SAM3x8E datasheet and have successfully tested one encoder in Arduino IDE. It appears that TIOA0 and TIOBO are used to read PHA and PHB of of one Encoder which correspond to Pin 2 and 13 of Arduino Due. I am not using Index pin (TIOB1).

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

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

It seems that I can only interface 1 quadrature .Is their any way I can use Quadrature decoder to read 2 encoders instead of one. As I have stated earlier I am not using the index pin. So, maybe there might be a way to decode to encoders using the three available pins as shown in the above diagram. I don't want to use Interrupts to do this job.

Here's is the link of SAM3x Manual:
http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf

Link of Motor that i am using:
www.pololu.com/product/2824

body:
According to [Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483][1] and referenced excel sheet with [Device to No of QDEC channels][2] it seems to have two of them. However in DUE almost none of interesting devices are wired to headers completely (Extmem, SD interface,...)

However TIOA6 and TIOB6 should be on pins 5 and 4

Pin configuration should be something like this:

      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

And TC0 is pretty much same as TC2, so just copy&paste and change TC0 to TC2

Full config:

      REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
      REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

      PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
      PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

      REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
      REG_TC0_RC2   = F_CPU / 128 / 1;
      REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
      REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
      REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
      PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

      REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
      REG_TC2_RC2   = F_CPU / 128 / 10;
      REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
      REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
      REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
      REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  [1]: http://www.atmel.com/Images/Atmel-42706-Quadrature-Decoder-QDEC-for-SAM3-4-Devices_ApplicationNote_AT11483.pdf
  [2]: http://atmel.force.com/support/servlet/fileField?id=0BEG0000000HRvP


message:
Send RF 433MHz data to Domoticz RfxCom with protocol X10 from Arduino Nano

I have installed Domoticz on Raspberry Pi and bought an RfxCom 433MHz emitter/receiver.
It works well for example with Chacon DiO 54781 door sensor.
I want to create my own sensor with Arduino that would be recognized by Domoticz as a native RF 433MHz device.
In first place, I want to make a flooding sensor, I also need an On/Off information.
I would like to implement X10 protocol because it seems to be the simplest one.

body:
I finally found a documentation about RF X10 protocol:
[X10 RF Receiver.pdf][1]

With following Hardware :

 - Arduino Pro Mini 5V         (4€)        https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
 -   RF 433MHz emitter/receiver  (3€) (Note: only the emitter is used)       https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
 -   3 wires : VCC, GND, Signal (on Arduino pin 2)

I've created the following working code for Arduino Nano :

    /*
    * Custom sensor (base code)
    *
    * Emission in RF 433MHz with the X10 protocol for Domoticz
    *
    * Hardware :
    * Arduino Pro Mini 5V   (4€)  https://www.amazon.fr/gp/product/B00QPUEFNW/ref=oh_aui_search_detailpage?ie=UTF8&psc=1
    * RF 433MHz emitter/receiver  (3€)  https://www.amazon.fr/HDigiWorld-metteur-cepteur-commande-Arduino/dp/B00JTQI39G/ref=sr_1_3?s=computers&ie=UTF8&qid=1470813610&sr=1-3&keywords=433
    *  Note: only the emitter is used
    * 3 wires : VCC, GND, Signal (on Arduino pin 2)
    *
    * Documentation found for RF X10: http://www.printcapture.com/files/X10_RF_Receiver.pdf
    *
    * Example of malformed data received in RfxMngr in mode "nodec" (before this code was correctly debugged) :
    *
    *  Packettype        = UNDECODED RF Message
    *  UNDECODED NEC:1C515C86F0
    *
    *
    * Correct data that is now receveived by RfxMngr with this program :
    *
    *------------------------------------------------
    *  Packettype    = Lighting1
    *  subtype       = X10
    *  Sequence nbr  = 13
    *  housecode     = D
    *  unitcode      = 1
    *  Command       = On
    *  Signal level  = 7  -64dBm
    *------------------------------------------------
    *  Packettype    = Lighting1
    *  subtype       = X10
    *  Sequence nbr  = 14
    *  housecode     = D
    *  unitcode      = 1
    *  Command       = Off
    *  Signal level  = 7  -64dBm
    *------------------------------------------------
    */

    const int pin_emit = 2;   // Signal pin for RF433 emitter
    const int pin_led = 13;   // Internal LED : it will be ON when the "On" command is sent in RF, and OFF the the "Off" command is sent (changed each 60s)

    const unsigned int X10_A1_ON = 0x00;
    const unsigned int X10_A1_OFF = 0x20;

    const unsigned int X10_address = 5;  // this is Housecode. In my case 5 results in "D" house code
    unsigned int X10_data = X10_A1_ON;  // command. I have implemented only On/Off for unit code 1

    void setup() {
      pinMode(pin_led, OUTPUT);
      pinMode(pin_emit, OUTPUT);
      digitalWrite(pin_emit, LOW);
    }

    /**
    * Bit to 0 : 1.125ms between rising edges, so before next bit
    */
    void X10_sendBit_zero()
    {
      digitalWrite(pin_emit, HIGH);
      delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
      digitalWrite(pin_emit, LOW);
      delayMicroseconds(570);       // Total 555+570 : 1125µs = 1.125ms
    }

    /**
    * Bit à 1 : 2.25ms entre les "rising edges"
    */
    void X10_sendBit_one()
    {
      digitalWrite(pin_emit, HIGH);
      delayMicroseconds(555);       // Arbitrary value: I took around 1.125ms divided by two for the "VCC" state.
      digitalWrite(pin_emit, LOW);
      delayMicroseconds(1695);      // Total 555+1695 : 2250µs = 2.250ms
    }

    void X10_send8bits(unsigned int data)
    {
      // - Send the 8 bits, and then the complementary of the 8 bits.
      // from documentation: "Within each byte, bit7 is received first and bit0 last"
      int mask = 0x80;
      for(int i = 0; i < 8; i++)
      {
        int bit = mask & data;
        if (bit == 0)
          X10_sendBit_zero();
        else
          X10_sendBit_one();

        mask = mask >> 1;
      }
    }

    /**
    * Sending a byte consists of sending this byte, and then sending the opposite of the same byte.
    * As we send the opposite as well as the data, the total duration is always the same : 8 * (1.125ms+2.250ms) = 8 * 3.375 = total of 27ms
    */
    void X10_sendByte(unsigned int data)
    {
      X10_send8bits(data);
      X10_send8bits(~data);
    }

    /**
    * Send a complete X10 packet
    *
    * Total duration :
    * (9ms + 4.5ms) + (27ms + 27ms) + 0.555ms + 40ms = 108.055 ms
    *  from doc: "It appears, from articles on the 'net, that other people have seen a range from 95 msec to 116 msec for various transmitters and that standard X-10 transceivers can tolerate timing variations of 30-35% from nominal."
    */
    void X10_sendState_once(unsigned int data)
    {

      // - Header
      digitalWrite(pin_emit, HIGH); // "Burst" de 9ms
      delayMicroseconds(9000);
      digitalWrite(pin_emit, LOW); // Silence de 4.5ms
      delayMicroseconds(4500);

      // - Data
      X10_sendByte(0x50); // - Address
      X10_sendByte(data); // - Data

      // - Send a last rising edge to validate last bit
      digitalWrite(pin_emit, HIGH);
      delayMicroseconds(555);       // Arbitraty value (but always the same), for "VCC" state.

      // - Footer
      digitalWrite(pin_emit, LOW); // Silence de 40ms pour signifier la fin de l'émission
      delayMicroseconds(40000);

    }

    /**
    * Send a complete packet multiple times (this X10 protocol has not ACK))
    * From doc: "Most X-10 RF transmitters send a minimum of five copies of the code separated by 40 msec silences although some can send single bursts."
    *
    *  5 times 108.055ms = 540.275 ms, half a second
    */
    void X10_sendState(unsigned int data)
    {
      // - "clean" to be sure to have a zero for the first rising edge on init
      digitalWrite(pin_emit, LOW);
      delay(1);

      // - Send 5 time complete packet
      for(int repeat=0 ; repeat<5 ; repeat++)
        X10_sendState_once(data);

    }

    void loop() {

      if(X10_data == X10_A1_ON)
        digitalWrite(pin_led, HIGH);
      else
        digitalWrite(pin_led, LOW);
      X10_sendState(X10_data);
      delay(60000);              // 1 minute

      // - I change state each 60 seconds to see changes in Domoticz
      if(X10_data == X10_A1_ON)
        X10_data = X10_A1_OFF;
      else
        X10_data = X10_A1_ON;
    }

By changing House code and data, it is now possible to create our own RF sensors.

  [1]: http://www.printcapture.com/files/X10_RF_Receiver.pdf


message:
Low memory error using SD card

I called HTTP web service on Arduino Uno, now i am trying to store the data in SD card. But as soon as i compile the program, it shows LOW MEMORY error and no data stored in SD card.
Any one can help?

body: Try Arduino mega. It has more memory 8 KB RAM, 256 KB flash memory.


body: Try to use properly  kind of variables for example if u r using Int in a value can would  use byte of try to put some serial.println(F("wherever  you can print "))  for running  on sram instead of  stack memory.


message:
How does if(serial) work, a c++ question

The Arduino documentation says **if(Serial)** always returns 1, except for the case where Leonardo USB serial connection delays becoming ready.

(Leonardo has two USB IDs, and switches between them for boot loader and Serial USB.  After boot loader finishes and kicks off the program, it takes a while for the USB master (e.g. your PC) to process the disconnect of the boot loader USB device and the connection of the Serial USB device.  Thus the need for a wait.)

Now "*Serial*" is a static external instantiation of the *Serial_* class (defined as ***extern Serial_ Serial;***).

The c++ rules, as I understand them, do not allow a constructor to return a value, nor may the class name (which is also the constructor name) be used as a member (function) name in the class.

"*Serial*" cannot be defined in class *Serial_*, or the **if(Serial)** syntax would have to be **if(Serial.Serial)**.

"*Serial*" cannot be defined outside the **class Serial_,** or it will conflict with (i.e. hide) the definition of *Serial* as an instantiation of *Serial_*.

___So how does the Arduino IDE do it?___

All I can think of is that the magic pre-scanner does something...  But what exactly, pray tell?

body:
It's not the constructor that's returning the value, it's the `bool` operator:

Uno:

    HardwareSerial::operator bool() {
        return true;
    }

Leonardo:

    Serial_::operator bool() {
        bool result = false;
        if (_usbLineInfo.lineState > 0)
            result = true;
        delay(10);
        return result;
    }

When you use the object in a setting where a boolean value is expected of it (e.g., `if`, `while` etc.) the `bool()` operator is called (if it exists) and that value is used.

More specifically, the `bool()` operator is called when the object is being *cast* to a `bool` type, either implicitly (as in `if...`) or explicitly (as in `... = (bool)Serial;`).

More on C++ class operators here: http://en.cppreference.com/w/cpp/language/operators


message:
A question about resistance measurement with arduino

Lately I was asking myself about the possibility of measuring a potentiometer resistance with Arduino.

My questions are:

1. Is it possible?
2. If it's possible, what kind of restriction does the Arduino have with the resistance value measured?

body:
_The question isn't explicitly clear, this answer is based on having a single known value pot and wishing to know its resistance at any one point rather than trying to find an unknown resistance entirely_

You can't measure resistance directly. What you can do however is measure the voltage across a potentiometer.
There is a really good example provided by arduino [which can be found here][1].

Now, it is possible to turn this into a resistance value with a little bit of editing to the code

    int potPin = A0;    // Select the input pin for the potentiometer
    int potR = 1000;    // This is your max potentiometer resistance in Ohms
    int val = 0;        // Variable to store the value coming from the sensor
    float voltage;      // This is the voltage from the wiper of the pot
    float resistance;   // This is the resistance of the pot at the wiper

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

    void loop() {
      val = analogRead(potPin);                      // Read the value from the pot wiper
      voltage = val * (5.0 / 1023.0);                // Convert the value into a voltage
      resistance = (voltage / 5.0) * potR;           // Convert the voltage into a resistance
      Serial.print("Voltage = ");
      Serial.print(voltage);                         // Print the voltage
      Serial.println("V");
      Serial.print("Resistance = ");
      Serial.print(resistance);                      // Print the resistance
      Serial.println("R");
      delay(1000);                                   // Add a little delay
    }

As for your second question, it can do as high a resistance as you want. As long as you update the potR value in the code with the resistance of your pot (e.g. 1000000 for a 1MOhm pot)

_I'm an electronics engineer by trade so my code could probably be cleaned up and made more efficient, this is just a starting point_

  [1]: https://www.arduino.cc/en/Tutorial/ReadAnalogVoltage


body:
If you know Ohm's Law (which you should) and you realise that the ADC measures voltage, you should be able to work it out from there. But I will go into minute detail for you to ensure you understand.

Ohm's Law defines the relationship between Voltage (V), Current (I) and Resistance (R).

    R = V/I

To find one unknown value (in your case R) you need to know the other two values.  That is, the current flowing through the resistor, and the voltage dropped across the resistor.

We have no way of directly measuring current, but we can measure voltage using the ADC. So if we can somehow measure a voltage and use that to calculate the current then we have two of the three values and we can calculate the third. However, calculating the current requires that we know the resistance - and that is what we are wanting to find out.

So we need to then provide a *known* resistance that we can measure the voltage across, and thus find the current flowing through it. First a couple of reminders of basics:

* Current flows the same through all resistances connected in series
* The sum of all voltages dropped across resistors in series equals the total voltage across all the resistors.

So if we put two resistors in series and apply an fixed voltage across it (5V in our case) a single current will flow through them both. With that two voltages will be dropped across the resistors - and those two voltages will add up to 5V.

If we have one known resistor and one unknown resistor and we know the voltage dropped across both resistors then we can calculate the current that is flowing through the known resistor. And that current is the same current that is flowing through the unknown resistor. And since we know the voltage drop across that resistor we can then calculate its resistance using that voltage and the current we have just calculated.

Here's the circuit I just described:

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

Vin us 5V. Let's have R1 as, say, 10KΩ (a common enough value). R2 we don't know.

Using the ADC of the Arduino we measure a value of 681. First we convert that into a voltage:

    Vout = 681 / 1024.0 * 5.0
         = 3.325V

So we know that R2 has 3.325V dropped across it, and since all the voltages must add up to 5V we know that R1 has (5 - 3.325) 1.675V dropped across it.

So the current (I=V/R) through R1 must be (1.675 / 10,000) 167.5µA (0.0001675A).

Now we can calculate the resistance of R2 since R=V/I and V is 3.325 and I is 0.0001675, so R must be 19850Ω - or pretty much 20KΩ.

That's the long-hand version from a current-based perspective. However there is a short-cut.

Since the output voltage is a simple ratio of the input voltage defined by the ratio between the resistors we can use that to create a much simpler formula.

From the example above the output voltage is two thirds the input voltage - and R2 is two thirds the total resistance (R1+R2). The two match perfectly.  So we can use a simple ratio calculation to give us the resistor.

For instance, the ratio formula:

    Vout = R2 / (R1 + R2) * Vin

(that's R2 as a proportion of the total resistance multiplied by the input voltage)

When rearranged to get R2 gives us:

    R2 = R1 * (1 / ((Vin / Vout) - 1))

So taking the voltage we measured above (3.325) and the known resistor (10,000Ω) and the input voltage (5V) and substituting those values into the formula, we get:

    R2 = 10,000 * (1 / ((5 / 3.325) - 1))
       = 10,000 * (1 / (1.504) - 1)
       = 10,000 * (1 / 0.504)
       = 10,000 * 1.984
       = 19840

Or pretty much 20KΩ. (Note: the discrepancy in the results is purely due to rounding errors. Use higher precision values and you get better results).

You have to have a rough idea of the kind of order of magnitude of resistor you are trying to find, though, in order to select an R1 of a comparable value so that the voltage Vout is large enough to measure accurately.

Also you need to be aware that the input to the ADC has quite a (relatively) low impedance (can be very crudely thought of as a resistor between the input and ground) which is measured in the low mega-ohm range. This can have an impact on the values you read with the ADC if your resistors are too high, since this impedance will be in parallel to the resistor R2, so you'd actually be measuring the resistance of both R2 and the ADC's input in parallel. To measure very high resistances you should first buffer the ADC through a *voltage follower* with a very high (tens or hundreds of tera-ohms) impedance input.

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


message:
Powering multiple Arduino shields

To start, I am a software guy, so I am not too clued up on the electronics side of things. My question is: I have a number of Arduino shields and would like to power them with a portable power source, and therefore would like some advice on what to use without frying any electronics.

This is a list of the current equipment that will require power:

 - [Arduino Mega 2560][1]
 - [SIM900 GPRS/GSM Shield][2]
 - [Sparkfun GPS Logger Shield][3]
 - [Sparkfun Wifi Shield - ESP8266][4]

The shields will be stacked on top of each other.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield
  [3]: https://www.sparkfun.com/products/13750
  [4]: https://www.sparkfun.com/products/13287

body:
All the shields are 5v compatible. So no need to worry about 3.3v.

But there may be a chance of insufficient current if you use a battery to the power-jack of arduino mega (due to the internal voltage regulator). I'd suggest you cut a USB cable and solder the +5(red color) wire to VIN on the mega and ground(black wire) to GND pin. And use a 'power bank', which is used for mobile phones.


body:
Your stack will need quite a lot of current - most probably more than the Arduino can supply itself.

You will need to provide your own regulated 5V supply - either from a USB port (convenient if you are by a computer) - as long as it can supply more than 500mA of current (you need a Charging Downstream Port *CDP* for that) or from some external regulated 5V power supply, such as a mobile phone charger.

That 5V supply should be connected direct to the 5V pin of the Arduino's power header.

One thing to note: the headers themselves are only rated for up to 1A. If you need more than 1A throughout the entire stack it could be worth connecting the 5V power supply direct to the 5V pins of ALL the shields in the stack. Also do the same with the GND pins to the negative of the power supply. That way the high current doesn't need to flow through the pins themselves.


message:
Arduino-Pyserial communication on Python 3, Windows machine: Pyserial.write() doesn't seem to do anything

I've recently gotten my hands on an Arduino (or rather a Genuino, but the overall architecture should be the same) UNO. I'm now using that Arduino to test how data is transmitted from a USB to Serial Connector to the Arduino.

I've already verified that data transmission from Arduino to the PC is possible, by using hTerm and PySerial. However, whenever I send data from Pyserial or hTerm, it doesn't show up in the Arduino serial terminal. Also, I'm using SoftwareSerial to set up a secondary serial terminal to see what the Arduino receives. (I'm using the standard serial port to send data to the terminal, and the SoftwareSerial Port to connect to the USB to Serial Connector.)

Here's my code so far:

Python side:

<!-- language: lang-python -->

    import serial
    import time
    import sys
    import struct
    ser = serial.Serial('COM3', 9600, timeout=0)
    time.sleep(10)
    while 1:
        print(ser.write(struct.pack('>B', 0)))
        time.sleep(2)
        print(1)
        sys.stdout.flush()

The Arduino side looks like this, and is essentially the default example:
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

<!-- language: lang-cpp -->

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11); // RX, TX
    void setup() {
      // put your setup code here, to run once:
      if (Serial) {
        Serial.end();
      }
      Serial.begin(9600);
      while (!Serial) {
        ;
      }

      Serial.println("Godnight moon!");

      mySerial.begin(9600);
      mySerial.println("Hello, world?");
    }

    void loop() {
      // put your main code here, to run repeatedly:
      mySerial.listen();
      if (mySerial.available() > 0) {
        Serial.println("Hello User");
        Serial.println(mySerial.read());
      }
    }

The Terminal never prints "Hello User". Also, no other signals are being printed. By removing the if-condition, I get a whole lot of "Hello User" and "-1" in the Arduino IDE serial monitor.

Concerning my setup:

I've got an USB to Serial converter, which is connected as "COM3". On the other side, I have an Arduino UNO which is connected via USB to the same computer. The TX pin of the converter is connected to the RX pin of the Arduino and vice versa. Also, Ground is connected to Ground. Furthermore, I use Jupyter/IPython notebook to run my Python script, and the default Arduino IDE to compile programs for my Arduino. In the case there I received data from the Arduino, I used the script specified in the URL provided, which is very similar to the one I'm already showing here. Also, `ser.write()` is replaced by `ser.read(1)`, so that it reads one byte at a time. My system is Windows 7 (64 Bit).

Edit: Here is an established connection between hTerm (a serial terminal) and the Python script while using com0com as a port emulator.
[![A successful communication between the Python script and hTerm][1]][1]

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

body:
What do you think should come out?

I'm no expert with Python but you seem to be using struct pack, which I think prepends a number of bytes to the data to generate a 4 byte word.  You are using NULL, 0 to pack the structure.  When Serial.println() encounter a NULL it will assume that is the end of the string.  So you seem to be printing a zero byte string.

Oh and Serial.read() only reads one byte of data, so there is an issue with that too. I suspect that the write call has a similar issue, you normally need to supply a size parameter because its binary data.

Does that make sense?


body:
When you run your python code, do you see the things you are sending on the screen there?

I think you need to be calling  ser.open().


message:
IDE 1.6.10 on LinuxMint 17.3 Cinnamon

When compiling I get the error
'as: unknown option »-mmcu=avr5« exit status 1'

I succeeded now using your piece of advise. Thank you so much.

body: Delete or rename the old "Arduino15" directory located at /home/(username)/.arduino15    (a.k.a. ~/.arduino15) and re-install 1.6.10.