text:
Webserver on Arduino: Refresh issues
I am using W5100 Ethernet Shield Network Module with arduino Uno 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();
}

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).


text:
Webserver on Arduino: How to 307 temporary redirect
I originally asked this question. 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?

@Majenko I would like you to answer this please.

This might be of use to you: http://stackoverflow.com/help/merging-accounts

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();
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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.

Is it a genuine Arduino Nano or a cheap Chinese clone Nano?

@Majenko most probably a clone. I don't see anything written on the board. And the same coloured power and pin13 LED further confirm the fact. Have I done a mistake??

No, but it will need different drivers. CH340G

@Majenko I bought it online. The seller listed it a genuine one, but I just noticed that. BTW a google search for CH340G shows up differrent adapters. Do I need to buy an external adapted to program it??

Check the numbers on the chip on the underside first.

yes its CH340G...

So download and install those drivers then. Then Windows should identify it and give you a COM port to use.

@Majenko  did download them. Tried installing. Nothing happened...

I find it hard to believe that nothing happened. Did windows try and identify the hardware? Is there an unidentified or failed device in the device manager? Did windows make any sounds when you plugged the Nano in?

No sounds no devices in device manager. I installed the driver and it said pre-installed the drivers. Just nothing happened. is that bcz I'm on Win10.

Are you using a cable with no data wires in it?

@Majenko I don't know. Its a new cable I bought off at a local shop just half an hour ago. It powers up the Nano. But I'm not sure about how many wires are in it

Do you not have more than one cable? You should have a drawer full of USB cables. Everyone has a drawer full of USB cables.

@Majenko I had a drawer full of USB cables. In fact I kept a usb b type cable for charging my wireless headpiece but it went missing. BTW I tried connecting a phone using the same USB cable and guess what, nothing happened, the phone is just charging and my PC didn't detect a thing. So its a cable fault I assume

Certainly sounds like it. You can get cables without data wires that are purely for charging small devices (not phones and things which use the data wires to identify the charger and get more current).

@Majenko and yes the cable it was. Borrowed a cable from my neighbor and the Nano is working perfectly fine. Thanks. Please state that as an answer so I can mark it

I solved the problem, followed this: "http://www.instructables.com/id/How-To-Burn-a-Bootloader-to-Clone-Arduino-Nano-30/"

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.

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.

Phew. I never would have guessed this. Thanks!

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/

I don't really see a question in the OP, but here is the immediate answer:
Go into Control Panel..Device manager.  Open the Ports (COM & LPT) and see what you have.  It should be listed.
If it is a CH340 port it will just give a COMx number.
If you have the genuine article then it will actually say so and give you the COMx number to use.
If no COM ports show then try switching out the cable.  Power cycle the Arduino and try again.
There aren't that many moving parts in this, but sometimes, Windows gets confused and a Windows reboot might be necessary.  That usually only happens if you unplug and replug the Arduino too many times for Windows to keep track of.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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.

Are you actually using softwareserial?  On the leonardo you are probably using the hardware UART, so you should remove that tag.  In terms of your problem, have you received any data?  If it is failing in both directions you likely have not paired the devices, have the baud rate misconfigured or your Android app is broken.

As I wrote receiving data works fine. I cannot only send data from arduino. And I've deleted the tag. Thanks for noticing.

Do you have BT module with 5V to 3.3V level shifter? Does BT module works if you wire it as loopback (tx pin connected to rx pin without arduino)?

I've tried connecting it as loopback but it doesn't work either. My module is Sparkfun mate gold

I've found the problem
It should be:
Serial1.println("2");

instead of:
Serial1.write("2");


text:
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?

Please post a Minimal, Complete, and Verifiable example

Compiled OK for me, when I supplied (empty) setup() and loop() functions. There being fewer than 23 lines (the line # of the cited errors), I assume we're seeing an excerpt. Can you reduce your code to the minimum necessary to demonstrate the problem and show that, entirely?

@JRobert I also did just like you: I created a new sketch and copied the code from my post (I didn't put anything into setup() or loop()). I got the same errors. Why do i get them?

I second JRobert: compiled OK for me with void setup(){} void loop(){}, save for a couple of warnings about the function parameters not being used.

I'm using Arduino IDE 1.7.10. I'll check this code on my second PC

So I tried to compile the same code on my laptop (Arduino IDE 1.7.7) and the result is the same. I literally have: empty void setup(), empty void loop() and the code from my post above (which I put above setup() function). Actually I updated my post to show the whole thing I have in my .ino file.

You're suffering from the IDE's preprocessor being thick and doing things wrong.

So what can I do about it?

I am working on that... Just waiting for 1.7.10 to download.

Ok, thanks. Same thing happends on 1.7.7

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.

Thank you very much. What other IDE do you recommend? To be honest, I can't stand Arduino IDE, the code is really hard to read, personally I write programs in Visual Studio Code. I wish it was possible to upload to Arduino from there.

Well, I have to recommend UECIDE, but then I am biased since I wrote it ;)

I'll check it out

I wouldn't recommend Arduino at all, use C/C++ directly instead. There is a plethora of IDE for C/C++ out there. If you get a real programming pod you can even single step and inspect hardware registers.

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:
void Move(Dir direction, int distance);
void Move(Dir direction, int distance)
{
     direction = forward;
}

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() {}

Or just use a different IDE. Thanks for your input

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.

C++ creates typedefs of all enums and structs by default without you needing to do it manually.


text:
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 ?

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.

Thanks for the answer .. i updated my code. it kind of works but as i wrote.  i am getting different readings ... ONLY channel 0 is hooked !! .... it seems that it reads with different delays. changing the delay gives me different sequence. what is wrong

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.

Thanks .. i just updated my code. is that what you meant ?

That looks better, but you've also now removed the code you originally asked about. Try reverting to the previous version and then adding the loop() implementation as a new section? That structure indeed what I was thinking. If that implementation works for you, please mark this answer as 'accepted'. Also, if you are delay()ing for 100ms, that may be inconveniently long, but choosing the delay is application and system dependent.


text:
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.

Technically USB device can be composite device, say with 4 USB-CDC (or VCP - virtual comport) devices. Arduino Mega has no native USB, but it is possible to use V-USB library that emulates USB 1.1 device at physical layer using just 2 pins (hardware UART will not be used). But there are some issues: 1) it seems for 1 VCP device 3 endpoints are needed and V-USB can't provide that many, so likely library modification will be needed; 2) for Windows driver - not sure if it is possible to use standard VCP drivers for a such composite device

@Flanker Looks like it will be easier to use a USB to four channel RS232 module and connect Arduino to one of the four RS232 channels.

You might look at the FT4232H, though who knows what that will be like software wise.

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).

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.

Dang it, I need to remember to look at the dates of posts!


text:
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

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.


text:
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!

You need a regulator to decrease the pressie. A modern 2 stage scuba regulator's 1st stage can decrease 3000psi to 200psi. A power tool compressor can decrease 150psi down to about 45psi.

Per some google searching, CO2 is about 850psi.  I like the air-tool regulator idea (~18$ from Home Depot), since they are adjustable to the 0-200psi range on the low side, if they don't break on the high side.    How much volume are you talking about? 1 child's breath per actuation? 1/7000th of a 12g CO2 capsule?

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.

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?


text:
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?

I would suggest, instead of a valve, a 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.


text:
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!

How's about showing us what gets logged in /var/log/syslog when you plug in the arduino usb cable.

The magic word in your question is "clone". You're very much on your own unless you can identify just what components are in use on your board, especially the USB interface chip. The smart money is on it being a CH340 chip, and those are notoriously unstable and break very easily.

They break under Windows, not Linux. Is your user in the dialout group, Aaron? You must be to use serial ports.

@Avamander They break in two ways - one is shoddy drivers in windows, the other is a complete disregard for any form of ESD protection. They die horribly and never work again.

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.

Hi Ronaldo and welcome to SE Arduino. While your answer is good, and maybe correct, do you happen to have tried another version of the kernel (which is not 4.x) that works? I only ask, as it would help to back up your claim. Also, any links to documented evidence that also backs up your claim would be great. In addition, what is "kernel mermo"? I can find no reference to it on the web.


text:
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 component, which, according to the product specifications, 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)?

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.


text:
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

The code indentation looks odd, check if the curly braces are balanced the way you intend. especially line 6 opens a new block that is unconditional. The else in line 25 belongs to the if in line 19.

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

Comments are not for extended discussion; this conversation has been moved to chat.


text:
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 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

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

You are trying to use a URL in place of a hostname.
You are trying to connect to an HTTPS service which runs on port 443 not on port 80
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 to get the SIM900 to perform an HTTPS request on your behalf rather than opening a socket and sending / receiving data.

I have posted my previous version in an edit to the main question. I believe that version did what you are describing, but I also received errors on the result of this.

Not quite. Close, but not quite. In that version you're using HTTP commands to access an HTTPS site. You need to use HTTPS commands not HTTP commands.

Following the HTTPS commands I get very close, but with only errors occurring on the download. I have added "AT+HTTPSSL=1" to enable https. I have added another edit to reflect my new results.

Are you actually sending 1000 bytes of data to the server?

I am only sending Serial1.println("{\"device_info\":\"breadcrum-prototype-a\"}");.
But I believe the issue is being caused by the URL being chopped, there are logs which say 'not found /bre'. Why would the command:
Serial1.println("AT+HTTPPARA=\"URL\",\"https://rocky-garden-56471.herokuapp.com/breadcrum/lifecycle/register\""); be cut down?

That's 39 characters. Why tell it you're sending 1000 when you only want to send 39?

I have been testing varying values for that just to see if it affected anything. 1000 was simply what I had left in there when I pasted it through.

Setting the message size to the correct amount has worked. Thank you so much for your help Majenko!


text:
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?

Check the C++ syntax definition for static member data. They have to be defined; e.g. State Robot::state = initState;

"errors are gone" Because now the compiler isn't generating any code for anything, so there are no references to not find.

Just as a tip, when you see an error in a file ending in .o like this: ccU9OfJk.ltrans0.o - that is a linker error, not a compiler error. In other words, the syntax is OK, but you are missing something which the linker is trying to find.

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!  :) )

It's weird. In C# I wouldn't have to do it I guess.


text:
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.)

By using the transformer sold by the same people that sold you the wire.

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.

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.

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.


text:
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?

You understand that the ADC measures voltage, right?

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)


text:
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?

You will not get good result in an unshielded environment from a simple setup.  To do well, you need either an external lock-in amplified which does synchronous analog detection of a pulsed signal, or to take reading with the ADC and implement a lock-in in software.

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
You would have to change the buzzer in tutorial for an LED and resistor in series.


text:
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?

Is there any reason why V-USB isn't an option?

Haven't looked into V-USB yet. If it fits, I'm fine with that.

@IgnacioVazquez-Abrams So is this what we're talking about? http://codeandlife.com/2012/02/22/v-usb-with-attiny45-attiny85-without-a-crystal/

That article is badly out of date, but yes.

It might seem a little old fashioned, but a software implementation of an RS-232 type link could work for you. It might be easier than V-USB and require less resources on the AVR. I think that's the way I would go.  Regards,

The problem with using RS-232 with the ATtiny85 is that the '85 doesn't have a hardware UART. Its USI can be used to emulate one, but only in half duplex.

Sorry, I'm not up on my baud rates and hardware but what would that be equivalent of in units of bits per second? How fast could I shove 16 bytes to the ATTiny85 and back?

I think half duplex would work in this application.  A 16 char string comes in, gets processed, then a 16 byte string goes out.  Remember the V-USB has to send data, RS-232 can do it at the same rate, it seems to me.  Looking around the 'net it seems that LadyAda coded a interrupt driven software serial port which is now included in the base code for Arduino.  Here is a bit of a write-up:  http://arduiniana.org/libraries/newsoftserial/

Or you could use this.

So thanks to Ignacio Vazquez-Abrams' tip, it looks like I'll be able to accomplish this with V-USB:

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:

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 :)

Keep us updated on how it works out, please. Regards,

Haven't had a chance to implement this yet, but I might also look at your RS-232 recommendation. Ah, reminds me of my very first electronics project: the $4.00 serial link for my Ti-83+.

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 for further details.
I2C is supported on ATtiny by the USI module.
Cheers!

need to come up with a way to communicate with it from a PC

would be difficult to make an uart out of usi?


text:
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.

This error occurs due to a mismatch in Baud rates. So I suggest you try different baud rates, specifically 9600 and 115200 as these seem to be the most common....Gd Luck!!

I have copy-paste @Mero55's comment as an answer so OP can accept it and close the question.

Problem is......
In the ESP8266 Flash_Download_Tool_v3.6.1 The lowest setting available is 115200 baud

It's actually likely that the ESP isn't in flashing mode.- you did follow the points under Flash it! to the letter, right

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!

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


text:
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.

For AVR + SDCard you should check FatFs from Chang. It is widely used and proven C library. You can tweak the configuration file to get minimal size (8K shall be easy). Check wrapper library for Arduino here (6K with default options).
There is also even smaller version called Petit FAT (2-4K) but it doesn't support file delete feature.
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).


text:
FastLED int + float problem
I'm working on a code based on PaletteCrossfade.ino 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:

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.

Why don't you just use lower UPDATES_PER_SECOND?

I've tried, but even at 30 its faster than setting the index to 0.1, and also prevents faster animations.

"But i found the motion speed too fast. its stated in this:" "and also prevents faster animations. " I'm confused what do you want?

Change FastLED.delay(1000 / UPDATES_PER_SECOND); to FastLED.delay(1000); and tell me what happens or change #define UPDATES_PER_SECOND 100 to #define UPDATES_PER_SECOND 1

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.

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


text:
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...

What about using RC Oscillator and just measure the frequency?

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.


text:
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#?

Have you tried ls -l /dev/serial/by-id? On my Ubuntu, it shows aliases with rather indicative names (ProductID in particular) and the alias points to the right ttyACM#.

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.


text:
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?

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.

If you're going to use a transistor make sure you use it as a high side switch

@Hayman Could you please explain reasons for this? Now it's like "because someone said so"

In most cases you can just use it either side. However as it is a reasonably sized pump I'd probably remove the power from the device rather than the ground from the device (just personal preference/intuition). That's only because of this specific circumstance however. Also a couple of other things, you can get low Vce(sat) transistors even at higher currents. A Mosfet with a drain current of 5A is going to likely need more voltage on the gate than an arduino can supply. The best choice here is a relay used with a low side NPN transsistor

I know I'm being a bit wordy now, sorry about that. Here's a good article about possible issues with low side switching

I'm not 100% sure, but could a flyback diode help with the relay situation?

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
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.


text:
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).

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

According to Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483 and referenced excel sheet with Device to No of QDEC channels 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;

I am using Arduino IDE for programming. According to Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483 Pg 16 I have to first configure the IOpins. How can i configure TIOA6 and TIOB6 as QDEC input pins?

@KIVV Please see the above comment

@MasoodSalik How exactly it's done right now for TC0? Some library or directly in arduino? Do you have code for it? And also which Arduino IDE - there is arduino.cc and arduino.org

I have posted the code in another post   http://arduino.stackexchange.com/questions/28268/how-to-configure-2nd-quadrature-decoder-io-pins-in-arduino-ide

I am currently using Arduino IDE 1.6.10.(zip file download fromhttps://www.arduino.cc/en/Main/Software) After Installing the board "Arduino SAM board (32 bit ARM Cortex M3). All libraries of DUE are already added in it.


text:
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.

I finally found a documentation about RF X10 protocol:
X10 RF Receiver.pdf
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.

Just to say, since my previous answer, I concluded it was too much effort for each new sensor to find how to implement a new protocol. So I finally tried and adopted "MySensors", because I only need to feed it with payload.


text:
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?

Use a board with more memory. Both those operations use a lot of RAM for buffers.

Please suggest the board.

How do you copy the data? It's very unlikely that your UNO can copy all the data at once.

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

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.

Tried to put serial.println(F(" ")) but still same problem.

If it still gives the same problem, why is this answer accepted?


text:
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?

BTW, I switched over to [link]http://drazzy.com/package_drazzy.com_index.json[/link] Spence Konde core and fixed my compile problems.  Sometimes it's a real pain to figure out what is the latest/greatest most evolved / currently developed package to use.

Serial isn't the class name, its the instance name.

@Matt, while what you say is true, where is it misused in the question?  Understand that I can't fix the case in the title (StackExchange edit restriction), and that if(serial) is a quote from the Arduino people, who are trying to dumb things down.  I did say Serial is the instance of Serial_.  So, pray tell, what other words need correction?

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

Thanks @Majenjo.  C++ has been inactive quite a while for me, and now that you point it out, I'm doing "head slaps" over how obvious it is!