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 multiply strings?
I want to have a line like this
Serial.println(count*"B");

So if count=6, it would print BBBBBB, etc.
Is there anything like this for arduino?

Nothing that will be more effective than a loop.

A loop that prints char by char, or a loop that builds a string, and is printed at the end of the loop?

That would depend on whether or not count has a reasonable limit.

For(let str = ‘a’; str.length<6; str+=‘a’){ Console.log(str) }

A more simple "noob" way could also be:
int count = 6

for(int i=0; i<count; i++)
{
  Serial.print("b");
}

Serial.println();

This is what I ended up doing (although made the for loop one line). I wasn't really looking to make my own method like the others have done, I was just hoping there'd be some kind of string * int syntax

You can write a helper function to do it, like this:
void printRepeat (Stream & device, const char * str, unsigned int count)
  {
  while (count-- > 0)
    device.print (str);
  }   // end of printRepeat

void setup()
  {
  Serial.begin (115200);
  printRepeat (Serial, "-", 20);
  Serial.println ();
  } // end of setup

void loop()
{
  printRepeat (Serial, "Hello, World! ", 5);
  Serial.println ();
  delay (500);
} // end of loop

The function printRepeat is passed a Stream argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.

Just for fun, here is a version of Nick Gammon's answer reformulated
with some C++ magic:
// A "repeated string" that has no use except for being printable.
class RepeatedString : public Printable
{
public:
    RepeatedString(const char * str, unsigned int count)
    : _str(str), _count(count) {}
    size_t printTo(Print& p) const
    {
        size_t sz = 0;
        for (unsigned int i = 0; i < _count; i++)
            sz += p.print(_str);
        return sz;
    }
private:
    const char * _str;
    unsigned int _count;
};

void setup()
{
    Serial.begin(115200);
    Serial.println(RepeatedString("-", 20));
}

void loop()
{
    Serial.println(RepeatedString("Hello, World! ", 5));
    delay(500);
}

You can .print() and .println() the RepeatedStrings on anything
that can print.

Nice! You can also overload "*" so that OP's exact syntax would work!

source: Stack Exchange

license: 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/

sort: votes


text:
ESP8266 cannot read DHT22
I am trying to build a WiFi humidity and temperature sensor. My board is a nodeMCU using the ESP8266 connected via USB. The board is working fine with various WiFi examples and various serial examples. Hence I guest my environment is OK.
Now I am trying to connect a DHT22 to read temperature and humidity. To reduce the error sources I boiled down my code to the standard DHT example:
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");
  dht.begin();
}

void loop() {
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");
}

Nevertheless I always get the message "Failed to read from DHT sensor!".
Regarding the hardware I tried connecting the sensor with or without the 10k resistor, tried different DHTs and different pins. To rule out the DHTs I connected them with an Arduino Nano where these are working fine (both with and without resistor and using the same code). The only difference I see is that the Arduino is using 5V while the ESP8266 is using 3.3V - which is nonetheless inside the rating of the DHT.
Any ideas?

Have you got the right pin number?

Yes. Please check the link I posted in the answer below. I did not verify each pin but for example addressing pin 2 with the DHT library means you need to connect the DHT data to "D4" at your nodeMCU.

I found, that the pin mapping printed at the board of the nodeMCU does NOT match the pin mapping in the library/software.
Check out this issue/solution. It states the correct pin mapping (e.g. pin 2 is "D4" at the board) and provides also an according workaround. My DHT22s are working now... :-)

I had been racking my brain for over 16 hours trying to figure out why this library would not work. I tested the DHT on an Arduino and it worked fine but whenever I tried on the nodeMCU it failed to read or gave spurious data. That is untill I saw the above answer that is not mentioned anywhere. The pins for the nodeMCU are not the same as the Arduino. (I thought that by defining the pin it would be using the pin stated) This is false as the library is mapped the Arduino pins so this is something to look out for, for any nodeMCU/ESP8266 beginners.

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


text:
producing sine wave variable in amplitude and frequency
How to produce a sine wave with variable frequency and variable amplitude?
I found a library to produce variable frequency called sinwave but not produce variable amplitude (I want -2V to 2V amplitude)

How is -2V to 2V variable?

Here's one solution to do it using your own code implementing the following.The basic solution is as follows.
Start with the basic sine wave output (this has amplitude between -1 and 1, and repeats ever 360 degrees) implemented as a function in your Arduino sketch with a variable parameter for the frequency and amplitude.
Now input the frequency you want (which you don't specify) and the amplitude (that is multiply your sine function by 2). The frequency can be implemented by using the delay function to output a value corresponding to the y-axis of the sine wave  at the specified time on the x-axis. You would need the y output to depend on the delay and the frequency. This is all in code so far.
The next step is to output the corresponding voltages for each point on the sine wave. To make a varying voltage you can use a digital potentiometer with a voltage divider type circuit (it's not quite an voltage divider because it needs to produce negative voltages too). Thus you just need to make your code activate the digital potentiometer at the required resistance to create the required voltage that represents the y value of that sine value at that point in time (x axis has time). This voltage divider requires some more circuity to make the voltage between 0 and -2 volts (the negative voltage depends on the time the circuit has been on or the x-axis of the sine wave). There are lots of ways to make a corresponding negative voltage (the bottom half of the sine wave).  The triggering on or off of the potentiometer is done from the Arduino thus this also controls the frequency of the sine wave.
To sum up code the sine wave in a sketch with your desired frequency and amplitude use these values and implement the discrete point on the sine wave using a (digital) potentiometer which is part of a circuit which is a variation of  the simple voltage divider (the voltage divider type circuit will implement the amplitude of the sine wave which you want between 2v and -2v). The frequency is, basically, implemented with the delay function.

You can use a digital potentiometer as a programmable attenuator or as a feedback element in a programmable gain amplifier circuit.
See references  at arduino.cc regarding interfacing an AD5171 or AD5206 to Arduinos.


text:
Using a lot of interrupts on a single Arduino
I'm doing a little project that requires a lot of sensors. Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16 (for me that's a lot).
So, I have an Arduino MEGA 2560, and I'm new to Arduino (Had a little experience with PIC before).
I've started my project with buttons and leds to simulate the sensor, but my sensors work normally HIGH, and when something pass in front of it, it goes quickly to LOW and back. English is not my first language so I don't recall the name of this sensor, kind of like movement sensor(?).
A lot of stuff pass normally, up to 50/s, in front of it, so it should keep "bouncing" between HIGH and LOW. But when I changed the buttons for the sensors, sometimes my processor won't react, and I think it's because the signal goes back to HIGH before the code reads it. Maybe it's not a problem when it's sensing lot of things, but I can't test it right now with a lot of sensors, and it's not something that can keep getting errors.
So I got to interrupts, reading the awesome gammon review. I understood a lot of new things that i didn't know and I searched for a interrupt Library, but the one I found can't use too many sensors.
I forgot to tell, but I'm using a touch 2,4" shield too, so a lot of interrupts pins can't be used.
Will I be able to use all the sensors I want? If not, could I do it with 2 Arduinos and 1 screen? Am i missing something about the interrupts? Where can I find something to help me?
Edit 1: All the sensor are the same

What you want here are pin change interrupts

This actually would be a great candidate for implementing on a CPLD with lots of pins.

On a Uno, all of the digital and analog pins can trigger a pin-change interrupt. That gives you 20 inputs straight away. The Mega also has pin change interrupts but not on all its pins. The pins that the Mega supports for pin-change interrupts are documented on the Software Serial page.

Not all pins on the Arduino Mega and Arduino Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

(Note that the Atmega2560 chip itself supports more pin change interrupts, however those extra ones are not brought out to header pins on the Arduino board).
That's still quite a few (18 if I counted correctly). Plus the hardware interrupt pins: 2, 3, 18, 19, 20, 21.

Right now I'm using 4, but i want to reach up to 60 sensors, and a minimum of 16

To reach 60 you probably want an input shift register such as the 74HC165 - you can daisy-chain them together to get lots of inputs. However you would have to poll to see if pins changed.
Otherwise you could use something like the MCP23017 chip, which has 16 input/output pins, and supports interrupts. You can use 4 of them (interfacing with I2C) and thus get 64 inputs. There is a shield that has 4 of those chips on it:

With suitable software (see my page about I2C) you could configure for interrupts and read any of those 64 inputs when they change.

Do I have to keep checking all the time for every sensor one by one?

No, because you can configure the interrupts as open-drain, which means you can connect them all together (if you want to). Or, you could bring out the interrupts for the 4 x MCP23017 chips to four interrupt inputs on the Mega (that narrows down for you which chip caused the interrupt). Then you can read the chip's register(s) to find the state of the pins - either at the time of the interrupt, or right now.
However you might find that it is actually faster to just poll the chips (say) 100 times a second. There is some overhead to using I2C, you can also get SPI versions of that chip (MCP23S17) which would operate a bit faster.
Alternatively, the 74HC165, whilst simpler, could also turn out to be overall faster if you just poll rapidly.

And the sensor sense a lot of movement per second, won't that cause trouble for the Arduino?

You need to define "a lot" and "trouble". You won't do billions of read a second. You can probably do thousands. What would you do with thousands of readings anyway? The time taken to process them would probably be the limiting factor.

At the same time I'm using a GPS, no problem for the usage of Serial and I2C together right?

No problem, because serial input is interrupt-driven. Within reason, you can do both at once.

That quote, “Not all pins on the Mega and Mega 2560 support change interrupts”, is slightly misleading as an explanation of only 18 PCI pins on the Mega.   ATmega640-1280-1281-2560-2561 series chips support 24 PCI pins – #0-#7 on PB0-PB7; #8-#15 on PE0 & PJ0-PJ6; #16-#23 on PK0-PK7.  However, PE6 and PJ2-PJ6 aren't brought out to headers, leaving 18 available as you mention.

The OP said I have an Arduino MEGA 2560 so I was addressing the Arduino board, not the raw processor. I'll amend the post to make that clearer.

So, I read about the Centipede Shield and your page about I2C and now I'm pretty sure I need to use I2C one way or another. I'm thinking about the Centipede, but I'm not sure I understood how to implement it. Do I have to keep checking all the time for every sensor one by one? Or one time for each Chip? My master will only read, it's all sensors anyway. And the sensor sense a lot of movement per second, won't that cause trouble for the Arduino? At the same time I'm using a GPS, no problem for the usage of Serial and I2C together right (newbie question)?

For that many sensors (way more than the number of interrupts available on the chip), your interrupt service routine (ISR) will need to be able to poll the sensors to discover which one(s) caused the interrupt.
That might mean connecting each motion-sensor's output to both a latch and a many-input OR-gate to one of the interrupt pins. Your ISR would have to read the latches; set a flag for each LOW latch; clear the latches (to HIGH) and exit. The main routine would then take whatever action was needed for each sensor that had been LOW.

When you have implemented the solution given above, by Nick Gammon, it is recommendable that you try both of the solutions he provides, and use the timer circuit to time each version of the algorithm.
That is: You need to try out if the polled reading he mentions of lets say 100 times per second, or the interrupted method is the best, given your circumstances.
Reason being that if your system pulls the interrupts from time to time, lets say, each of the 64 inputs pulls its interrupt pin maybe once in 30 seconds, then you have just above 2 pulls per second to the board. That is not a lot, and checking the registers like 100 times per second (if you need time wise accuracy for instance), may prove very time consuming, as you would otherwise only run 2 interrupted algorithms per second.
Use the diode on the Arduino Mega circuit board if you have no display or output unit on the Arduino, to display the results. (If you need help communicating from the Arduino to yourself (human) via 1 diode, such that you can be told how much different a particular setup is, then let me know - that would be outside of the scope of this answer, I guess). I short, you can communicate to yourself by creating a little algorithm which starts with ie. 3 rapid blinks, then a pause, then it can create countable blinks for each figure, counting 0 with 10 blinks, and then you can count the blinks by putting breaks in between the figures. Thereby you can communicate the figure 1874 by 1 blink, pause, 8 blinks, pause, 7 blinks, pause, 4 blinks - then long pause, then 3 short blinks, pause, then it repeats.


text:
What are the logical errors in this piece of code?
The client always reply with "ThisCodeTurnsTheUnoOnn" or ThisCodeTurnsTheUnoOff" based on some conditions.
This piece of code is inside arduino uno's void loop().
Expected behavior:
The arduino read the reply and turn the digital pin 13 to HIGH if the onCount is 22 after matching every character one by one with the client's reply which was "ThisCodeTurnsTheUnoOnn" and the other way around:
The arduino read the reply and turn the digital pin 13 to LOW if the offCount is 22 after matching every character one by one with the client's reply which was "ThisCodeTurnsTheUnoOff".
and the digital pin 13 should always remain in the previous state if the new client's reply was the same as previous reply. (e.g. if
client's reply was "ThisCodeTurnsTheUnoOff" and the arduino turn the digital pin 13 to LOW, then in next loop the client's reply was same "ThisCodeTurnsTheUnoOff" and the arduino should keep the digital pin 13 in LOW state).
Actual behavior:
CASE :
client's reply was "ThisCodeTurnsTheUnoOff" and the arduino turn the digital pin 13 to LOW, then in next loop the client's reply was same "ThisCodeTurnsTheUnoOff" and the arduino should keep the digital pin 13 in LOW state but the arduino turns the digital pin 13 HIGH when entering the next loop(void loop()) then turns back to LOW after entered the loop(void loop()).
  // available() will return the number of characters
  // currently in the receive buffer.

  const int solenoidValve = 13;

  char onCode[23] = "ThisCodeTurnsTheUnoOnn";
  char offCode[23] = "ThisCodeTurnsTheUnoOff";

  int onCount = 0;
  int offCount = 0;

  while (client.available())
  {
    char c = client.read();

    if(c == onCode[onCount])
    {
      onCount++;

      if(onCount == 22)
      {
        digitalWrite(solenoidValve, HIGH);
        break;
      }
    }
    else
    {
      onCount = 0;
    }

    if(c == offCode[offCount])
    {
          offCount++;

          if(offCount == 22)
          {
            digitalWrite(solenoidValve, LOW);
            break;
          }
    }
    else
    {
      offCount = 0;
    }
    Serial.write(c);
  }

The complete code, in case the logical errors is not within the above piece of code:
#include <SoftwareSerial.h>
#include <SparkFunESP8266WiFi.h>

//////////////////////////////
// WiFi Network Definitions //
//////////////////////////////
// Replace these two character strings with the name and
// password of your WiFi network.
const char mySSID[] = "SSID";
const char myPSK[] = "PASSWORD";
const int solenoidValve = 13;
char onCode[23] = "ThisCodeTurnsTheUnoOnn";
char offCode[23] = "ThisCodeTurnsTheUnoOff";

//water flow calculation variables
volatile int flow_frequency; // Measures flow sensor pulses
unsigned int l_hour; // Calculated litres/hour
unsigned char flowsensor = 2; // Sensor Input
unsigned long currentTime;
unsigned long cloopTime;

//////////////////
// HTTP Strings //
//////////////////
const char destServer[] = "192.168.0.101"; //private ip //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132
const uint16_t port = 8080; // Code ID: 1126 [Kugan] added variable port
const String httpRequest = "GET /aquosdb/getStatus.php HTTP/1.1\n"
                           "Host: 192.168.0.101\n" //private ip [note for myself: dont forget to change IP]
                           "Connection: close\n\n"; //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132

// All functions called from setup() are defined below the
// loop() function. They modularized to make it easier to
// copy/paste into sketches of your own.
void setup()
{
   pinMode(flowsensor, INPUT);
   digitalWrite(flowsensor, HIGH); // Optional Internal Pull-Up
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
   sei(); // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;

  // Serial Monitor is used to control the demo and view
  // debug information.
  Serial.begin(9600);
  //serialTrigger(F("Press any key to begin.")); //[Kugan] 28/7/16 try3 : disabled serial trigger for self automation Code ID:1130

  // initializeESP8266() verifies communication with the WiFi
  // shield, and sets it up.
  initializeESP8266();

  // connectESP8266() connects to the defined WiFi network.
  connectESP8266();

  // displayConnectInfo prints the Shield's local IP
  // and the network it's connected to.
  displayConnectInfo();

  //serialTrigger(F("Press any key to connect client."));  //[Kugan] 28/7/16 try3 : disabled serial trigger for self automation Code ID:1130
  //valveControl();
}

void loop()
{
  setFlow();
  //delay(500); // [Kugan] 29/7/16 try3 : added delay to debug connection bug Code ID:1131
  valveControl();
}

void initializeESP8266()
{
  // esp8266.begin() verifies that the ESP8266 is operational
  // and sets it up for the rest of the sketch.
  // It returns either true or false -- indicating whether
  // communication was successul or not.
  // true
  int test = esp8266.begin();
  if (test != true)
  {
    Serial.println(F("Error talking to ESP8266."));
    errorLoop(test);
  }
  Serial.println(F("ESP8266 Shield Present"));
}

void connectESP8266()
{
  esp8266.disconnect(); // Code ID:1125 [Kugan] To disconnect from previously connected wifi AP
  delay(100);           // esp8266 has auto-reconnect function to connect previously connected AP

  // The ESP8266 can be set to one of three modes:
  //  1 - ESP8266_MODE_STA - Station only
  //  2 - ESP8266_MODE_AP - Access point only
  //  3 - ESP8266_MODE_STAAP - Station/AP combo
  // Use esp8266.getMode() to check which mode it's in:
  int retVal = esp8266.getMode();
  if (retVal != ESP8266_MODE_STA)
  { // If it's not in station mode.
    // Use esp8266.setMode([mode]) to set it to a specified
    // mode.
    retVal = esp8266.setMode(ESP8266_MODE_STA);
    if (retVal < 0)
    {
      Serial.println(F("Error setting mode."));
      errorLoop(retVal);
    }
  }
  Serial.println(F("Mode set to station"));

  // esp8266.status() indicates the ESP8266's WiFi connect
  // status.
  // A return value of 1 indicates the device is already
  // connected. 0 indicates disconnected. (Negative values
  // equate to communication errors.)
  retVal = esp8266.status();
  if (retVal <= 0)
  {
    Serial.print(F("Connecting to "));
    Serial.println(mySSID);
    // esp8266.connect([ssid], [psk]) connects the ESP8266
    // to a network.
    // On success the connect function returns a value >0
    // On fail, the function will either return:
    //  -1: TIMEOUT - The library has a set 30s timeout
    //  -3: FAIL - Couldn't connect to network.
    retVal = esp8266.connect(mySSID, myPSK);
    delay(60);
    if (retVal < 0)
    {
      Serial.println(F("Error connecting"));
      errorLoop(retVal);
    }
  }
}

void displayConnectInfo()
{
  char connectedSSID[20];
  memset(connectedSSID, 0, 20);
  // esp8266.getAP() can be used to check which AP the
  // ESP8266 is connected to. It returns an error code.
  // The connected AP is returned by reference as a parameter.
  int retVal = esp8266.getAP(connectedSSID);
  if (retVal > 0)
  {
    Serial.print(F("Connected to: "));
    Serial.println(connectedSSID);
  }

  // esp8266.localIP returns an IPAddress variable with the
  // ESP8266's current local IP address.
  IPAddress myIP = esp8266.localIP();
  Serial.print(F("My IP: ")); Serial.println(myIP);
}

void flow() // Interrupt function
{
   flow_frequency++;
}

void setFlow()
{
   // To use the ESP8266 as a TCP client, use the
  // ESP8266Client class. First, create an object:
  ESP8266Client client1;
  client1.stop(); //[Kugan] 28/7/16 try2 : added Code ID:1127

  // ESP8266Client connect([server], [port]) is used to
  // connect to a server (const char * or IPAddress) on
  // a specified port.
  // Returns: 1 on success, 2 on already connected,
  // negative on fail (-1=TIMEOUT, -3=FAIL).
  int retVal = client1.connect(destServer, port); //Code ID:1126 [Kugan] created variable port
  if (retVal <= 0)
  {
    Serial.println(retVal);  //[Kugan] 28/7/16 try2 : added Code ID:1130 for debugging
    Serial.println("flow");
    Serial.println(F("Failed to connect to server."));

    initializeESP8266(); // [Kugan] 28/7/16 try2 : added Code ID:1129 reinitialize, connect, and display connection info
    connectESP8266();
    displayConnectInfo();

    return;
  }

   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime; // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min.
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
      flow_frequency = 0; // Reset Counter
   }

  // print and write can be used to send data to a connected
  // client connection.
  String httpPostRequest = "GET /aquosdb/setFlow.php?data=" + String(l_hour) + " HTTP/1.1\n" //sets the water flow value
                           "Host: 192.168.0.101\n" //private ip
                           "Connection: close\n\n"; //[Kugan] 07/8/16 try4 : changed Global IP to Local IP for testing Code ID:1132
  client1.print(httpPostRequest);

  while (client1.available()) // [Kugan] 28/7/16 Code ID: 1128  to clear the buffer
    Serial.write(client1.read()); // read() gets the FIFO char

  if (client1.connected())
    client1.stop(); // stop() closes a TCP connection.
}

void valveControl()
{
  // To use the ESP8266 as a TCP client, use the
  // ESP8266Client class. First, create an object:
  ESP8266Client client;
  client.stop(); //[Kugan] 28/7/16 try2 : added Code ID:1127 stop any existing connections

  // ESP8266Client connect([server], [port]) is used to
  // connect to a server (const char * or IPAddress) on
  // a specified port.
  // Returns: 1 on success, 2 on already connected,
  // negative on fail (-1=TIMEOUT, -3=FAIL).
  int retVal = client.connect(destServer, port); // Code ID:1126 [Kugan] created variable port
  if (retVal <= 0)
  {
    Serial.println(retVal);  // [Kugan] 28/7/16 try2 : added Code ID:1130 for debugging
    Serial.println("valve");
    Serial.println(F("Failed to connect to server."));

    initializeESP8266(); // [Kugan] 28/7/16 try2 : added Code ID:1129 reinitialize, connect, and display connection info
    connectESP8266();
    displayConnectInfo();

    return;
  }

  // print and write can be used to send data to a connected
  // client connection.
  client.print(httpRequest);

  // available() will return the number of characters
  // currently in the receive buffer.
  int onCount = 0;
  int offCount = 0;

  while (client.available())
  {
    char c = client.read();

    if(c == onCode[onCount])
    {
      onCount++;

      if(onCount == 22)
      {
        digitalWrite(solenoidValve, HIGH);
        break;
      }
    }
    else
    {
      onCount = 0;
    }

    if(c == offCode[offCount])
    {
          offCount++;

          if(offCount == 22)
          {
            digitalWrite(solenoidValve, LOW);
            break;
          }
    }
    else
    {
      offCount = 0;
    }
    Serial.write(c);
  }

  // connected() is a boolean return value - 1 if the
  // connection is active, 0 if it's closed.
  if (client.connected())
    client.stop(); // stop() closes a TCP connection.
}

// errorLoop prints an error code, then loops forever.
void errorLoop(int error)
{
  Serial.print(F("Error: ")); Serial.println(error);
  Serial.println(F("Looping forever."));
  for (;;)
    ;
}

// serialTrigger prints a message, then waits for something
// to come in from the serial port.
void serialTrigger(String message)
{
  Serial.println();
  Serial.println(message);
  Serial.println();
  while (!Serial.available())
    ;
  while (Serial.available())
    Serial.read();
}

Thanks in advance for your efforts to answer my question.

The sample code looks fine, and shouldn't cause your problem. So my guess is that there is something wrong in the rest of the code. Either that or the board is somehow resetting.

The biggest obstacle to you getting this working is the somewhat bizarre way you are working out what has been sent to you, by counting characters that match and waiting until they reach 22.
Instead you should read the input character by character and place them into an array. Discard anything past the 22nd character so it doesn't overflow the array. Then you can compare what is in that array to strings stored in flash (using the F() macro) and the strcmp_P() function.


text:
NFC 'dynamic' UID database
Hi SE (and Majenko in particular, if I'm lucky) -
I have a setup with an SD module (on SPI) and an Elechouse PN532 NFC reader (on I2C). I would like to use a master tag to enter MASTER MODE [sic] to add tags if they are not present in a file on my SD card, or remove tags which are present in the same file. I am currently checking tag UID against a hardcoded master UID, and it works well enough for now. What trips me up is making the tag database in the most arduino-friendly way. How would you advise me to do this in the most spartan way? And when removing existing tags from the database, how would you suggest I update it, to remove unwanted UIDs? I am using a flat text database now, but it could be a binary file - I am just puzzled by what is the best method to remove an entry(line) from a file using SD library.

I an considering using EEPROM instead, if it can have a decent lifespan (I will only rarely add or remove tags), but it would be convenient to have the UIDs in a text file on microsd.

If the list isn't too large you could just read all the entries into memory, modify the list, and write back the modified list. Alternatively you could overwrite the entry with zeros instead of actually removing it.

You got me ;)
Since a UID is a fixed size you don't need to think in "lines", only in bytes.
The most efficient way of storing the UIDs is as pure bytes. I am not familiar with that specific card and reader combination, but I will assume as an example an 8 byte UID (though this all holds true for any other length you care to choose).
You treat your file on SD card like a kind of database with a number of records in it. Each record is the exact same size (8 bytes in this case) . To read or write a specific record you just "seek" to the record number multiplied by the record size - so multiples of 8 in this example.
myFile.seek(recordNumber * 8);

If .seek() returns false then you have reached the end of the file.
So to find a tag you can:
myFile.seek(0); // Start at the beginning of the file
int recno = 0;
char foundUID[8];
bool found = false;
while (myFile.read(foundUID, 8)) {
    if (strncmp(foundUID, myUID, 8) == 0) { // 8 bytes match
        found = true;
        break;
    }
    recno++;
}

At the end of that found will be true if there is a match, and recno will be set to the record number. Now the magic begins...
If it has been found and you want to delete it, think again. That's a very wasteful idea. Instead you just want to "invalidate" it - that is, replace the UID in the database with something the UID can never be - all 0xFF is a good choice. Simply:
myFile.seek(recno * 8);
for (int i = 0; i < 8; i++) {
    myFile.write(0xFF);
}

Now the tag has gone from the database. You may want to add a filter at the card reading phase to stop anyone using a card that has a UID of all 0xFF, of course.
Now for adding a new card...  This is where the fun starts.  You could just add 8 bytes to the end of the file, but then the file will grow and grow and grow. Instead, you can first search through the file for a tag entry that is all 0xFF and replace that data with your new UID. Just the same as when you deleted it - seek to 8x the record number and write 8 bytes.
It might help to write a function to wrap the tag seeking routine so you can easily call it multiple times from multiple places. Returning the record number would be most useful - and you could return -1 if it's not found.
If you really want it to be plain text you can do the exact same thing but work with the ASCII representation of the UID bytes instead of the raw values - maybe as HEX. So your 8 byte records would become 18 bytes (16 bytes for 2 ASCII characters per UID byte, plus two for the \r\n line ending). Doing the conversion between bytes and text and back to bytes again though is wasteful if you don't really need it.

In case you're wondering why I recommended 0xFF as the deleted tag fill value and not 0x00 or anything else, it is simply because when you erase flash memory it is set to 0xFF. When you change the contents of a block on an SD card the block is read, it is modified in memory, the block is then erased (the whole lot set to 0xFF), then the modified block re-written back to the card. The act of erasing the block slightly damages it as it forces electrons through bits they don't really want to go through to make it all 0xFF. By setting your empty records to 0xFF, when it comes time to filling them again, the flash doesn't have to work as hard to erase that block since those bits are already in the erased state. Therefore the lifetime of the flash card should be extended slightly.

Excellent. I won't have time to do it now, but I'll use a binary db. I will read this answer many times to fully appreciate it. Thanks!

You are a lesser deity - this is an excellent method!

Majenko is next to godliness.


text:
Bluetooth radio control of a motor
I need to purchase the correct bluetooth module for interfacing some simple functionality between an arduino and a motor. The tricky bit is getting the bluetooth radio to play nice with android and apple ios. There are things like MIT App Inventor, but I'd love to hear from someone with experience how to reliably control arduino from tablets/phones. Preferrably in a way that lets me define the control on the arduino. I can build android apps (slowly), not ios apps, but I would then have to either ask users to install untrusted apks or get it out through the google app store, which would take too long. Any help on this would be great.

This isn't an Arduino question, but an Android / iOS / Bluetooth one.  Putting something through the google store takes minutes, but many Anrdoid devices still have serious BTLE issues.  Meanwhile in the iOS world, last I heard app reviews take days, and you couldn't use classic bluetooth without jumping through MFI hoops.

You may want to have a look at the Adafruit BLE modules:
https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/bleuart?view=all
They have provided great examples of how to connect from Android and iOS devices, as well as providing apps or code to integrate into your own apps and you get to implement the motor controller code yourself on the Arduino so should have full control over that side.
They even have an example where they are controlling a motor using an Arduino and Bluetooth, it may not be exactly what you need but hopefully gets you closer to an answer:
https://learn.adafruit.com/bluetooth-motorized-camera-slider/overview?view=all

Happy to help :-)


text:
Control/switching of headphone audio
I need to do some simple line control of audio out from a phone, 3.5mm TRS. I would have preferred to use transistors, but the voltage drop on an already fairly weak signal makes it unusable. Also not sure about negative voltage from collector to emitter. Essentially I need to switch the line on/off. How can I do this while not introducing noise or signal loss (K.I.S.S.) - I haven't checked if optocouplers are without voltage drop, but in any case they're probably overkill.
Ask for clarification if needed.

This might be of interest to you: http://www.analog.com/media/en/training-seminars/tutorials/MT-088.pdf

Settled on a CMOS bilateral switch (4002). Thanks for the input.

My first thought was what about relays.  I've done a quick search and found this http://www.geofex.com/article_folders/relays/relays_for_switching_audio_signa.htm and this https://electronics.stackexchange.com/questions/110750/is-it-possible-to-turn-an-audio-signal-on-off-using-a-solid-state-relay so maybe it's not such a stupid idea, but like optocouplers it probably is a bit OTT.


text:
How to drive RGB LED fading alongside MAX7219s
Merry XMAS
I have a pro mini which drives 2 RGB LED strips on its 6 PWM pins, via 6 2N7000 N-channel MOSFETs. Alongside these, I have  4 x MAX7219 modules in series controlled via SPI. Both work perfectly, but not concurrently - yet. I need to do sleek PWM on the RGB strips whilst outputting scrolling text on the MAX7219s.
The functions for the MAX7219 display take some time to complete for each blob of text.
I added a udelay() function (works like delay(), but just uses delayMicroseconds instead) so I could use interrupts/timers.
I am now interested in the best practice for doing that - I have no experience with interrupts, and would rather not use something lile FreeRTOS for this.
Desired functionality:
1) Drive 2 RGB LED strips on 6 PWM pins, smoothly.
2) While at the same time outputting arbitrary text/foo on the MAX7219s on SPI.
I have this snippet for smoother RGB fading ( http://forum.arduino.cc/index.php?topic=12004.0 ) and would also like to know what variables periode, displace denote, and if this method has merit.

void loop()
{
 time = millis();
 value = 128+127*cos(2*PI/periode*time);
 value2 = 128+127*cos(2*PI/periode*(displace-time));
 analogWrite(ledpin, value);           // sets the value (range from 0 to 255)
 analogWrite(ledpin2, value2);           // sets the value (range from 0 to 255)
}

@Majenko et al?
Cluebats at the ready - any advice would be appreciated!

The functions for the MAX7219 display take some time to complete for each blob of text. - They shouldn't. How are you driving them? Have you thought about interleaving updating each row with updating your LED strips? What are you even considering any form of delay function?

@Majenko I am using the LedControl library - no I haven't thought about that, I don't know how to interleave updating each row, and even if I did, the text blobs have to be displayed for some time. I am interested in the equivalent of two threads (I'll use FreeRTOS if I must), can't that be done with interrupts? I'm sure there's plenty of delay()s in the printbuffer( textStr ) functions for the fading to take place. The udelay() function is explicitly for functions which run as interrupts - do forgive me my lack of insight here; if fork() was possible, this would be straightforward.

I see that library uses shiftOut(). First step will be to ditch that and use proper hardware SPI.

I'd probably go the other way than Majenko suggest, and leave the max7219 code as is, but use a timer interrupt to update the PWM values.

@Gerben Alright - You validate my own idea. I will proceed accordingly. Post as answer and I will close this question.


text:
Is my sketch 'thread safe'?
I come from a .Net background, typically I would 'lock' operations on an integer when I have thread-safe requirements. I'm not sure that applies to my sketch here? Could I potentially bypass an increment from one of my interrupt pins?
In summary, I have 2 interrupt pins - I want to increment a count which (every 5 seconds) writes via serial and resets.
I'm doing this to, kind of, avoid writing serial from within an interrupt - since I've read it's strongly discouraged.
#include <Controllino.h>

const byte interruptPin0 = CONTROLLINO_IN0;
const byte interruptPin1 = CONTROLLINO_IN1;
int counter1 = 0;
int counter2 = 0;
unsigned long previousMillis = 0;
unsigned long interval = 5000;
int a = 60;
char buffer[256];

void setup()
{
  pinMode(interruptPin0, INPUT_PULLUP);
  pinMode(interruptPin1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin0), pin1Fired, RISING);
  attachInterrupt(digitalPinToInterrupt(interruptPin1), pin2Fired, RISING);
  Serial.begin(9600);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    sprintf(buffer,"A%d",counter1);
    Serial.println(buffer);
    sprintf(buffer,"D%d",counter2);
    Serial.println(buffer);
    counter1 = counter2 = 0;
  }
}

void pin1Fired()
{
  counter1++;
}

void pin2Fired()
{
  counter2++;
}

There is indeed a race condition in your code: if an interrupt fires
while you are reading one of the counters, you might read garbage. If it
fires between reading and resetting the counter, you loose one count.
The way to prevent the race is to block interrupts while the main thread
(everything that does not run in interrupt context) accesses the
counters. BTW, do not forget to make the counters volatile.
The portions of the code that run with interrupts disabled are called
“critical sections”, and you should keep them as short as possible in
order to limit the interrupt latency they introduce. Typically, within
those critical sections you do nothing more than access the shared
variables. Example:
void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    noInterrupts();  // start of critical section
    int counter1Copy = counter1;
    counter1 = 0;
    interrupts();  // end of critical section
    Serial.print("A");
    Serial.println(counter1Copy);
    noInterrupts();  // start of critical section
    int counter2Copy = counter2;
    counter2 = 0;
    interrupts();  // end of critical section
    Serial.print("D");
    Serial.println(counter2Copy);
  }
}

Excellent! Thanks very much for this, probably saved me a lot of hassle when it came to missing counts! Just one question - during the time in which the interrupts are disabled(?) - are we not vulnerable to missing the interrupt handlers? i.e. still missing counts?

When an interrupt occurs in that time, it will be executed after you turned on the interrupts again.you only loose counts, when 2 or more interrupzs occur in that time. To prevent that you need to keep the disabled time lower than the time between 2 interrupts

@chrisl is right. To be more specific, you loose a count if 2 or more instances of the same interrupt fire during that window. If you get one INT0 and one INT1 you are fine.

Got you, brilliantly explained. Thanks Edgar.

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


text:
ATtiny serial.print() crash with INTs
I'm trying to print some data to and from an ATtiny85 via serial, using the SoftwareSerial library.  So far I've tried these setups with no results:

1/8MHz clock
baud rates from 9600 to 57600 (library doesn't seem to support higher rates)
printing to a newline or a single one
packing up a char array just as much as a String and then printing it
Txing/Rxing through an Arduino Nano/Uno/Mega or a cheap USB-Serial port

Reading up on the subject seemed to suggest that some values I was passing (such as '1000') might have been erroneously interpreted as EOL characters breaking the code, but attempts with different values (i.e. 845) returned the same failures.
As you might have guessed I'm writing code with the ArduinoIDE, and no errors are returned when compiling and uploading. Many other parts of the project involving serial work just fine, and I can communicate with the ATtiny on pretty much any of the above setups (actually packing up the String or char[] crash the whole thing).
The 'Ready' at the end of the setup is also printed fine, and the loop runs as long as it won't encounter any of the above issues.
Here's the code:
int VALUE = 1000;
int ANOTHER = 12;

#include <SoftwareSerial.h>
SoftwareSerial tSerial(3,4);

void _serialEvent() {
  if (tSerial.available()) {
    char mode = tSerial.read();
    if (mode == '?') {
      tSerial.println("someTextHere 1.23moreText");
      tSerial.print("value:");
      tSerial.print(VALUE);
      tSerial.print(";another:");
      tSerial.println(ANOTHER);
    }
    else if ...
  }
}

void setup() {
  tSerial.begin(57600);
  ...
  tSerial.println("Ready");
}

void loop() {
  ...
  _serialEvent();
}

Try to use F() macro to use string literals directly from flash. They must be copied into the RAM as they are now. Usage: tSerial.print(F("whatever you want")); and i saves lot of RAM.

ok that did it. can you please explain a bit more (a simple link to documentation will suffice) and set this as answer so I can accept it?

1/8 MHz is a little slow for using SoftwareSerial. I would rather clock it at 8 MHz.

Yes that's what I ended up doing, still that wasn't the cause.

It is much better to store string literals in the FLASH only. In Arduino there is __FlashStringHelper class and F() macro ensures that correct version of print method is used and that the string literal is not copied into the ram before it's printed.
Basically if you don't have enough memory, using lots of string literals results in stack overflows, coruption and/or returning to random adresses and it looks like crashes/resets.

Extremely helpful insight, thank you! This actually led to solve a couple other glitches I've been experiencing without understanding them. I was wondering if there is any tool available to debug this kind of situation?

You might want to read this article (https://learn.adafruit.com/memories-of-an-arduino/measuring-free-memory) reporting a quite clear explanation of typical micros memory usage, along with some advices to debug related problems


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:
433M modules w. soldered 34.6cm antenna, first test
I'm doing a first tx/rx on a pair of modules, and some hams have alluded that they 'autoadjust' - since I've soldered halfwave antennas onto the modules, what's the optimal range for first tests? And will I benefit from 1/2 or 1/4 wave radials? I was thinking about 4-6 spokes from a bicycle wheel. Also, what library would be best for RC control of a medium power pump - I'm pretty sure it's going to induce noise. How far away from the pump should I position the rx module? Thanks in advance.

I think the antenna should be slightly shorter as the module already has a very small antenna/coil on the  pcb. Just create a sketch that light an led if it successfully received data. Then keep moving further away till you can just barely receive data.  Then try clipping a (few) millimeters or the antenna and see if you can move further away. PS what specific model do you have?

Good idea, though I will start at ~25m and decrease distance. I trust the deep ham-fu. How much should I decrease it by? And what material would you use to make the antenna (solid core copper wire) completely straight? (and thanks )

@Gerben It's a noname module. They're all pretty similar, will use 5V for tx, and 3V3 for rx module. Tx works ok, will try it at 25m first.

Straight wire antennas are the easiest to make. Just power it by a battery, and start walking. They're all pretty similar, that's not really useful.

An english description here: https://arduinotech.dk/shop/rf-data-modul-433mhz/

I just read 3V3 is the optimal voltage for both tx and rx - bogus?

For the TX, the higher the voltage the greater the output power, and thus range (in most cases).


text:
PID tuning help
I'm currently working on a self-balancing robot with an Arduino Uno and a 10DOF ADXL345 sensor. Everything is going fine until I got to this PID tuning part. I've read about it several times but I'm unable to get the desired results. Can somebody give a detailed guide on PID tuning? Thank you.

How tall is it? How fast do the measurements and adjustments have to happen to keep things from falling down? How fast are they happening?  Where is the code?

Maybe you can help yourself with this tutorial for PID line follower robot. I successfully tuned my PID for line following and had some success with PID for wall following with sonar.

Thanks. Let me try it first. I'll tell you when it works :)

That tutorial looks pretty good.  One difference from most discussions and usages of the normal Arduino PID control is that it focuses on error by putting the setpoint outside the PID algorithm as "Tp", so you can use the arduino PID like this if you do those calcs outside. And "I just take the maximum value we want to send to the motor's power control (100) and divide by the maximum useable error value. For our line following robot we've assumed the maximum error is 5 so our guess at Kp is 100/5=20. When the error is +5 the motor's power will swing by 100 units." is the crux of PID tuning.

Thanks man. Didn't get the desired results yet but I'm a lot closer now. The robot is much more stable now. Thanks man

In real life there is no set equation to find the PID values. At best you'll get close with equations and then need to tune the parameters.
For anyone into PID loops have a read of this.
I've found it to be excellent.
My advice is to:

only use P
set I & D to 0
get it and good as you can by trial and error
add I and trial it too

D is for experts really and may cause weird/undesirable jitter.


text:
How can I set up a watchdog interrupt vector timer on the Arduino Redboard/Uno?
I'm trying to set up a watchdog timer interrupt to execute a routine in the WDT_vec ISR at some recurring interval. I don't want the processor to reset, just to execute the code in the interrupt and return to "normal" operation. I have the following test jig appropriated from the 'net that claims to set that up:
#include <avr/wdt.h>

 void setup_WDT() {
      noInterrupts();  // disable all the interrupts
      MCUSR = 0;       // ensure that the reset vectors are off

      /* Disable and clear all Watchdog settings. */

      _WD_CONTROL_REG = (1 << WDCE) | (1 << WDE);
      _WD_CONTROL_REG = 0;

      /* Setup Watchdog for interrupt and not reset, and a approximately 500ms timeout */
      _WD_CONTROL_REG = (1 << WDIE) | (1 << WDP2) | (1 << WDP0);

      interrupts();  // re-enable interrupts
    }

void setup() {
  setup_WDT();
  Serial.begin(9600);
  Serial.println("Startup");
}

void loop() {
}

ISR(WDT_vec) {
  Serial.println("Watchdog Interrupt");
}

The output indicates that the processor is just resetting repeatedly and never reaching the ISR. Also I get the following warning on compilation from the IDE (Arduino 1.8.2):

warning: 'WDT_vec' appears to be a misspelled signal handler, missing
  __vector prefix [-Wmisspelled-isr]  ISR(WDT_vec) {

Be careful using a serial.print line inside of your ISR. Serial communication requires interrupts to function.

@lemontwist Thanks, seems to work well enough just to test whether the ISR is firing, or not. I wouldn't do that in actual work...

Two errors:

The watchdog interrupt vector is named WDT_vect, not WDT_vec.
The statement _WD_CONTROL_REG = 0; serves no useful purpose, and
will likely mess up with the timed sequence for changing the watchdog
setting. Just remove it.

Those changes got it working!

_WD_CONTROL_REG = 0; serves an important purpose. If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of timeout resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialization
routine, even if the Watchdog is not in use.
if you are using it in developing a product whose programme should never freeze than this is important to remember.

this is not a good answer. in Arduino the bootloader controls the MCU some seconds after powerup or reset. correct AVR bootloaders turn off the watchdog. in setup() it is too late for most of the wdt intervals

thanks, @juraj for your kind comment.
The RESET what we percieve normally & reset occured after WDT reset are different. the hard reset runs the bootloader again but WDT reset does not even Reinitialize the RAM, running bootloader is a different issue.
Read article:
https://playground.arduino.cc/Main/ArduinoReset
& There it is written that:
Unfortunately, once the Arduino has started running a sketch, there is apparently no way to write a software function that has exactly the same effect as pushing the reset button.
I will appreciate & feel good if proved wrong & learn something new :).

the watchdog resets to bootloader

then, how can we prove that watchdog resets to the bootloader. please share the code or something authentic..!

there are projects of bootloaders for flashing over Ethernet. but to activate it, the board must be remote reset to bootloader. watchdog reset is used.https://github.com/per1234/Ariadne-Bootloader/tree/master/libraries/EthernetReset

on arduino.cc forum user flashed Atmega with esp8266 with AT firmware connected to RX/TX. From the sketch he initiated with AT commands the connection to the server and then he made a watchdog reset and the server executed the serial flashing over esp8266 in transparent mode.

the case from previous comment https://forum.arduino.cc/index.php?topic=519242.msg3545523#msg3545523

@juraj PFA the link of Atmega328pu datasheet on whose page no. 77, I found my answer as a note which you said is a bad answer..! I am little confused may be I am percieving the datasheet wrong please clarify this fact. Thanks in advance.
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf

in an Arduino the clearing of the watchdog flag is a responsibility of the Arduino bootloader. so your answer is out of scope here


text:
Using Air Quality Sensors like MQ135 to sense dust particles
Using MQ135 (or similar) to sense dust particles in PM
I was building a Air-purifier system. So, I need to monitor dust particles present in the air. Is it possible to use a gas sensor like the MQ135 to sense dust particles? Since, It can sense very small gas particles. Would it be possible to sense dust particles with it(MQ135 {Cheaper to buy}) or I need to buy a special optical dust sensor {Costly!}

You class this as costly?

@Majenko: i class that as very expensive; easily 4X the 2nd cheapest part in a build, when gas sensors are only a buck or two... it's hard to get a build out the door for $10-20 if a part cost $15...

The MQ sensors can not be used to sense dust particles. They are Electrochemical gas sensors which are sensitive for certain gasses. They are not sensitive for dust particles. Dust is not a gas, but tiny solid particles.


text:
I2C broadcast and reply on Arduino M0+
I am trying to set up several ATSAM-based AVR chips in a master/slave broadcasting arrangement. I want the master to be able to send a broadcast message to I2C address 0, and then for slaves to respond with different information. I have seen other implementations where this has been successful since I2C devices will typically self-arbitrate and if they are configured to back-off when arbitration is lost, the master can repeat its request and iterate over all addresses on the bus.
The challenge is that while I have Wire.beginTransmission(0) working to reach my slaves from the master, I cannot get Wire.requestFrom(0,6) to work. The slave acts as though no message had arrived in the reply case. This is in the reduced case of one master and one slave.
In the example below, changing RequestFrom to the slave address will work.
I am aware that on the SAMD architecture, ArduinoCore does not configure the SERCOM for I2C broadcasts so I made a one-line modification as follows to enable it:
sercom->I2CS.ADDR.reg = SERCOM_I2CS_ADDR_ADDR( ucAddress & 0x7Ful ) | // 0x7F, select only 7 bits
                      SERCOM_I2CS_ADDR_ADDRMASK( 0x00ul ) |
                      SERCOM_I2CS_ADDR_GENCEN // added by JAG

My master code:
#include <Wire.h>

void setup() {

  Serial.begin(9600);
  Serial.println("Sketch start" );

  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {

  Serial.print("-- Top of loop:" );
  Serial.println( millis() );

  Wire.beginTransmission(0); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission(true);    // stop transmitting

  // delay( 500 );

  uint8_t recvSize = Wire.requestFrom(0, 6);    // request 6 bytes from slave device #8

  Serial.print( "Got bytes: " );
  Serial.print( recvSize );
  Serial.print( "---> ");

  while (Wire.available()) { // slave may send less than requested
    char c = Wire.read(); // receive a byte as character
    Serial.print( "[") ;
    Serial.print(c);         // print the character
    Serial.print( "]" );
  }
  Serial.println();

  x++;
  delay(500);
}

My slave code:
#include <Wire.h>

void setup() {
  Wire.begin(9);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent); // register event
  Serial.begin(9600);           // start serial for output
  Serial.println( "Starting up" );
}

void loop() {
  delay(500);
    Serial.print( "In top of loop (slave): " );
    Serial.println(millis() );
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    SerialUSB.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  SerialUSB.println(x);         // print the integer
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Wire.write("hello"); // respond with message of 6 bytes
  // as expected by master
  Serial.println( "<<<< Writing a response." );
}

If you broadcast data using Wire.send(data), the slaves would receive this in there onReceive handler but as far as I can remember, the I2C slave will not respond on a Wire.requestFrom(...) broadcast from the master.
Imagine x slaves responding all at the same time to the request...

The I2C protocol supports bus arbitration only for masters sending (if more than one master in the bus starts sending at the same time). So, if any slave device would really respond to the General call address 0 with data, the data would geht corrupted if another slave would send data too. With this background it is reasonable, why an I2C slave device wouldn't respond to a request at the General call address.
If you have too many chips in the bus or don't want to address Thema directly due to another reason, you can send a trigger message to the General call address and let the other chips send their data as masters. Keep in mind, that in this case all involved chips must implement correct bus arbitration (and I'm not sure if the Wire library supports this).

authors: юрий смирнов


text:
Arduino Google speech api
I'm currently experimenting with my arduino Uno. I control it via an mobile (android) but wanted to just use a microphone on the board so I don't need to carry my mobile around. It is possible to record flac files from a mic and send it to Google speech api and get a return? And then maybe output it via the synthesis.
So it is possible to do this on an arduino uno and with C. If doesnt is there any other way I can go? I could buy a raspberry pi but I don't an whole operating system like linux installed. So any thoughts?

The Uno has only 2k of RAM so I doubt you will be able to record anything much.

You can use a special voice recognition shield (for example: EasyVR Shield 3.0 - Voice Recognition Shield) to integrate a simple and basic voice recognition. I think it's a very fast and easy prototyping way...
For the use of the more complex Google Speech Recognition I would use a more powerful microcontroller (such as Raspberry PI or something like that)...


text:
Store a variable?
I want to have a switch, that when on, will grab an analog number and essentially "freeze" it. Similarly to how STO> works on a TI83. What should I be using? Excuse my lack of technical terms, I'm not sure what to search and therefore do not know what to use. Thank you :)

Store/freeze it permanently, so it can be retrieved after power off, or just hold it in memory while power remains on?

@MarkSmith sorry, should have clarified. Just while power is on.

Then you don't need to do anything special - that's what variables do. Just read it: int value = analogRead(...);.  value now contains the value you read.

@MarkSmith but it will continuously read my analog input, which will be changing. I want it so when I press a button it'll grab that number and not keep reading from analog

Only if you tell it to. Can you think of a way to tell it only to read when the button is pressed? (Can you think of a way to tell it to do anything when a button is pressed?)

@MarkSmith I was planning on using a switch, not a button, so I will be using an if statement, but that will loop.

My recommendation:

Configure an external interrupt on the raising edges of the input where the button/switch is wired. Note that only pins 2 and 3 of Uno are capable of external interrupts.
Write a very simple ISR that just sets to True a global volatile variable (a flag to signal that the button/switch has been actuated) and does nothing else.
In the loop() check if the flag variable has been changed by the interrupt. If that's the case, then:

Debounce/deglitch the button/switch (optional, but highly recommended).
Read the analog input of your choice and store its value or do whatever you want to do with it.
Reset the flag variable to False so it can be changed the next time the interrupt is fired.

Only read the analogue pin if the button is pressed.
#define analogPin 0
#define buttPin 3

int analogVal = 0;

void setup() {
  pinMode(buttPin,INPUT);
}

void loop() {
    // You can do stuff here

    // If the button is pressed...
    if (digitalRead(buttPin)
    {
        // ..read the analogue pin
        analogVal = analogRead(analogPin) / 4;
    }

    // You can do stuff here
}

I'm not using a button, I'm using a switch. I just want when the switch is first turned on it will freeze a number, and when turned off it will unfreeze.

What do you mean "unfreeze"?  Throw the number away? Read continually?

You could use EEPROM on the Arduino. For example:
#include <EEPROM.h>

int valAddr = 0;

#define analogPin 0
#define buttPin 3
void setup() {
  pinMode(buttPin,INPUT);
}

void loop() {
  /***
    Need to divide by 4 because analog inputs range from
    0 to 1023 and each byte of the EEPROM can only hold a
    value from 0 to 255.
  ***/
  if(digitalRead(buttPin)){
     int val = analogRead(analogPin) / 4;
     EEPROM.write(valAddr, val);
     //access this value again by using int newvalue = EEPROM.read(valAddr)*4;

  }
}

By using EEPROM your value will be stored in non-volatile memory, meaning it will stay in memory even after a power cycle which is similar to how STO> works.

As noted in the EEPROMWrite page at arduino.cc,  “The EEPROM memory has a specified life of 100,000 write/erase cycles, so you may need to be careful about how often you write to it.”  The above program is not careful.   At 3.3 ms per EEPROM write, the above program will finish 100000 writes to valAddr in about 6 minutes if pin 3 is high.

Yes, definitely be careful of this. If your button is held down in your application you will have to write code to make sure it only writes once and only registers the button click once (debounce).

it will continuously read my analog input.

easy:

have the adc in free running mode and in the isr writes the adc value to a buffer.
watch the state of the button in an isr. if it changes, save the buffer value to something else.

there are simpler ways of doing it but less real time than that. need to watch out for atomicity if a multi-byte value is involved.

Read the analog input and store it, continuously. If the switch is off, also write the value to the "freeze" value:
void loop(){
   int value, freeze;

   value = analogRead(ANALOGPIN);
   if( !digitalRead(SWITCHPIN) ){
      freeze = value;   // sw is off, upd freeze value
   }
}

This doesn't take into account possible bouncing of the switch. That may or may not matter depending on the actual rate of sampling the analog input and what you intend to do with the frozen output, as the switch bouncing will be shorter than human perception but long enough (10s of msec, perhaps) for the MCU to notice and react to changes.

Here's a simple way of tracking the switch and managing the bit of state you need to manage:
int analogPin = 0;
int switchPin = 3;
int switched = 0; // the last-known state of the switch
int lastRead = 0; // the last-desired analog sample

void setup() {
  pinMode(switchPin, INPUT_PULLUP); // connect switch to switchPin+GND w/o resistors
}

void loop() {

  if(digitalRead(switchPin)){ // switch on:
    if(!switched){ // switch on, but was unknown
      lastRead = analogRead(analogPin); // the wanted leading-edge value
      switched = 1; // seen it on
    }//end if switch changed?
  }else{ // switch off:
    if(switched) switched = 0;      //  remember that switch is off
    lastRead = analogRead(analogPin); // the latest value
  }

  Serial.println("Value is " + String(lastRead));
  delay(500);
}

authors: Андрей Мастер

authors: Микола Зінченко


text:
Using an Arduino to drive a digital RGB LED strip
I recently purchased a 5M strip of digital RGB LEDs, that is compatible with the "Adafruit_NeoPixel.h" library.
Is maintaining the original order of the LEDs important?  Could I cut the strip in say four sections, and then reconnect those sections out of their original order?
Just to be clear these are digital 3-pin(+5V,DI,GRN) strips, not analog 4-pin(+12V, R, G, B) strips.
I'm just not finding good info regarding if the individual LEDs are pre-assigned an ID by the manufacturer, or if they somehow use a serial-timing way to assign IDs at startup.
Before digging through the Adafruit_NeoPixel.h, I wanted to see if I could get a quicker answer here.
THANKS!

I can not find detailed information regarding the 5M LED strips you bought.
I have used Adafruit addressable LED strips.  What Adafruit publishes on their web site helped a great deal when I cut my strips into smaller sizes.
Here is an Adafruit image which may help you:

I would think the order does not matter.  But you do need to connect the data such that "outs" go to "ins".  And you need to connect them in a row.  That is you need to connect them in one loop.
Added later...
Assuming we are using the WS2812:

We know from the specifications that the RGB data is encoded as 3 8 bit NZR (Non Zero Return) pulses.  8 bits for each color: red, green & blue.  That there is 1 such "word" of 24 bits for each pixel.  That the beginning of a set of "words" is marked by a 50us or grater interval where DI is zero.  And that each pixel strips off the first 24 bit "word" before passing the balance of the data on.
In other words, it doesn't matter what order WS2812 are assembled in.  Also that WS2812 have no idea where they are in the sequence.  All that matters is that each succeeding WS2812 gets its data from the previous WS2812.
One last note. The necessary timing is really fast and really tight. Can't be more than 150 billionths of a second off. No way can a multitasking platform like a PC, Mac or RaspberryPi pull this off.  When sending off a set of "words" to a string of pixels, the embedded processor will likely not be doing anything else!

I think "ins" and "outs" is confusing, as there really is only one data connector, it's just that when connecting one strip to another you must maintain the +5V and GND polarity, from one strip to the next.

I do not think, for example, connecting a DIN pin to a DIN pin will work.  Look at the picture.  Look at the silk-screen around the soldered strip connection.  Further, I think the data going into the DIN pin is altered by the NeoPixel's controller chip before coming out of the DOUT pin.  I believe this is the technique that the NeoPixels use to self address.  Hence why I believe you can connect them in any order.  But only in series.  Not in parallel.

I get what you're saying, but most of the strips I've seen are not labeled DIN and DOUT; just DI. So really the important part is as long as you keep the GRN connected to GRN and +5V connected to +5V, the digital connector will take care of itself. That is a fair point about connecting strips in parallel, that would not work because the addressing is done via serial bit-shifting.

I STAND CORRECTED! There is a DI and a DO, so the "DI" needs to be the "beginning" of the strand(s).  Could you incorporate the serial-shifting-register information from the duplicate post, and I'll then select your answer?

I can do that.  But after looking over the translated specification, I would have to disagree with the duplicate answer and say the first 24 bits is used by the first pixel.  Think about it, how could the 1st pixel use and strip off the last 24 bits as it has no idea how long to wait.  This is, it has no idea how many pixels are being addressed.  There is no address information in the data stream.  It is all brightness levels.


text:
Arduino controlling a heavy solenoid water valve
So after burning up a couple Arduinos, I'm running out of ideas...
I am trying to power both a Solenoid valve and the Arduino(nano) with the same 12V-2amp power supply. I've tried it with both a relay breakout board, and via transistor switching, and both are giving me sporadic behavior for the Solenoid.
Early failures came from realizing that the solenoid water value was actually a coil (duh), and thus needed some kind of diode placed over its connections, so I'm assuming the back voltage spike is what fried the first two boards.
At first I added a small diode that helped but wasn't enough, so I beefed it up to a 3 amp "rectifier diode" 200PIV, which stopped the board frying.
Here is a link to the solenoid water valve. Not much to go on I'm afraid. 12V 0.02-0.8Mpa.
The behavior that I'm seeing now, is that the solenoid will engage, but it won't disengage.
Do I need to add a Capacitor for the solenoid?  If so, any recommendations on sizing?

int relayPin = 2;

void setup()
{
  pinMode(relayPin, OUTPUT);
  Serial.begin(115200);
}

void loop()
{
  Serial.println("starting");
  digitalWrite(relayPin, HIGH);
  delay(2000);
  digitalWrite(relayPin, LOW);
  delay(2000);
}

The valve might require the water to be pressurized, to disengage properly. Using the water pressure instead of a sprint, like in regular solenoids.

Sorry, I did leave out that it's a "normally closed" solenoid.  I've tried direct powering with the 12v supply and it works fine that way.

Please double check your transistor pinout. The TIP3055 you name doesn't come in the TO-92 case you depict.

It's a prototyping board, so each vertical line (when laid horizontally) are all connected. So you'll see the the 12v power is provided to both the arduino and the solinoid

I have setup Arduino UNO and succeeded turning solenoid on when pot soil moisture dry, I was adding rain sensor when I mistakenly disvmcoonected the diode it fried my board, but atleast I had it working . I am using 24 volt normally closed solenoid , since I was monitoring over web I also had ethernet shield attached. And I was powering over ethernet using splitter and extracter.

The vin should only feed in 3.3 volt which you can get using stepdown buck converter , and use remains power to connect to solenoid. The transistor should be on the ground same as arduino nano the ground
The top became messy later

What I've discovered is that the step-down is the key. Because using the same 12v ground for both the arduino (directly) and the solenoid creates a feedback loop of some kind that keeps the transistor energized. The step-down buck your using to provide power to the arduino at 3.4V must include some kind of diode that is keeping the voltage from flowing backwards.

The fact that the solenoid turns on but not off makes me think the Arduino might just not switch off the GPIO. This could happen if the current drawn by the solenoid is so high that the power supply voltage drops below the threshold needed for the Arduino, resulting in a reset.
The result would be that the Arduino repeatedly switches on the solenoid but is reset before it can switch it off again.
Try to flash the built in LED in the same main loop to verify that the loop is still alive.

Try This Circuit...

I think you are overpowering Arduino Board.
Transistor Will not Carry heavy current for long duty period.
It easy to use Simple 5v relay board then you don't have to worry about Current limits and all...

If you review my diagram this is the exactly same setup I had already outlined, just using a different transistor. I'll try again with a TIP120.

authors: ธวัชชัย ชัยศลา


text:
Reverse the order of a hex string
I'm printing an "unsigned long" value to HEX via:
println(cardCode, HEX);

The value that I'm getting is: 69fb879d
I need it to be reversed as: 9d87fb69
I populate cardCode via the code:
for (i=1;i<bitCount;i++)
{
  cardCode <<=1;
  cardCode |= databits[i];
}

going into this my bitCount value is 32, so basically I'm populating cardCode based on 32 bits from the variable databits which is of type unsigned char.
I am absolutely crap at bitwise conversions (bit-shifting, etc.), is there a simple way to do this reversal?  Is this even enough information to go on?

What exactly is in databits?

Your issue seems to be byte order (big endian) and not bit order. The simplest solution to byte order swap is to use the builtin functions provided by the compiler (AVR GCC).
unsigned long cardCode;
...
Serial.print(__builtin_bswap32(cardCode), HEX);

There are two compiler builtin functions for byte order swap. One for 16-bit data and one for 32-bit data.
uint16_t __builtin_bswap16(uint16_t);
uint32_t __builtin_bswap32(uint32_t);

AVR MCUs are little endian (least significant byte first in memory). There are many devices that use big endian (most significant byte first). This is also known as network order. There are a set of functions/macros to help write portable code, especially device drivers.
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

These are used to map data from host to network byte order and reverse. They are defined as byte swap functions for hosts with little endian byte order. Unfortunately they are not available in the GCC AVR library but easy to define.
#define htonl(x) __builtin_bswap32((uint32_t) (x))
...

Cheers!

The title of this question is "Reverse the order of a hex string" but it was actually about reversing byte order in an unsigned long int.
Here is an answer for reverse the order of a string (null terminated vector of char).
There is a standard function for that in the C string function library.
char* strrev(char* s);

Cheers!

Sorry, misleading question title. It was about reversing the byte order of a value that became a hex string, and not reversing the string itself. Thanks

No problem! I just wanted to add this alternative answer for googlers. It also strengthens the original answer somewhat.


text:
Design Dilema -- What hardware?
I'm trying to build a smart thermostat for a particular application. I have the following design criteria and goals for the system:

Must be able to set up and monitor the device from either a mobile
phone or local network device.
No go on Ethernet or other hardwired connection, except for initial setup.  This must be a wireless solution. I'm presuming WiFi is best.
Needs a clock, an on time and an off time setting.
The system does a system time verification check once daily.
Needs a temperature input.
Needs to run an existing heater system (24v) thru a relay.
120v AC power (battery backup not required.)
Needs to be "hidden" in existing wall as much as possible.  (i.e. small & compact)  My intent is to hide the unit behind a double wide electrical duplex dead panel. (i.e. 4" x 4" nominal access thru drywall)

Here's a visual of my design intent package:
As I review a number of different hardware controller devices, I can see some issues.  I am very familiar with the Intel Edison, and I know exactly how to do this project there, including using the controller as a stand alone web host. (The Edison uses Yocto Linux to create a node.js server using http module.)  I was hoping to save a few $$ on hardware using an alternative controller but not sure that will work.  I've been wading thru the code for both the Photon and generic Arduino devices, and I'm getting the impression that I may need a custom server / api tool for a web page interface.  Its not clear that those hardware choices will support an interactive web page, particularly for easy user data update via browser Submit button.  That's not a big problem, I'm a freelance software developer, handy in C/C++/Java, PHP and JavaScript. And as for the Raspberry Pi, I have no experience but the pricing on some of their boards is below $15.
Here are my questions:

Has anybody used an Arduino board to host an interactive web page, including user input via Submit / Form ?  (Can I declare a local network static IP address for an Arduino?)
Has anybody used an Particle Photon board to host an interactive web page, including user input via Submit / Form? (It looks like declaring a local network static IP address on a Photon is anything but easy...)
Has anybody written an API Restful server for their Arduino, with both get and put functionality?  (I'm thinking PHP, or node.js makes the most sense for me.)  I know if I have to use Dynamic IP addressing to the controller, that I can always make an API system work for the system.
Other comments?

Why not ESP8266?

@ignaciovazquezabrams That board appears to be awesome as a WiFi interface, but doesn't appear to have the processing power to read analog input and function as a server and overall stand alone controller.  Its very well priced to provide WiFi service to another device.

Then you haven't really looked at it.

@IgnacioVazquez-Abrams  Very right you are.  I'm looking at the documentation at a number of places and its not at all clear this board will be fully functional for this application. 1- instructables 2 - nurdspace 3 - Sparkfun  Can you recommend better documentation that makes your suggestion and the device capabilities really clear.  I'm really liking the pricing of this thing!  Thx.

@IgnacioVazquez-Abrams   ha... here is a better reference at Makezine  In fact, make this recommendation an answer, will you?

What are your priorities when it comes to HW cost vs. ease of implementation? An Rpi is clearly over-dimensioned for the task, but will be up and running in an afternoon or so with HTTP, PHP, node.js & c. An Arduino-like board can be made for US$3-5, but significantly more development may be required; there's no PHP or other fancy stuff. HTTP server is available, NTP I'm not sure. WiFi via external component...

FYI; Using a relay isn't ideal if you have an modulating furnace.

Personally, since you want to build just one prototype and not many, I suggest you to use a raspberry PI. You can use it almost the same as the edison (you won't use yocto but just a debian derivative; the packages and applications, however, are almost the same). It costs about half the price of an edison (or even less if you get the cheapest one - you don't need the ethernet port, do you?) and you will have a lot of computing power. If you want to lose time, you can use an ESP in standalone version. And BTW, you can use a digital temp. sensor (it's easier to use and with less components).

Has anybody used an Arduino board to host an interactive web page, including user input via Submit / Form ?

I have a Tiny Web Server for the Arduino. It is designed to be light-weight on RAM. It supports GET/POST/Cookies for interacting with web forms.

Example code and more information on the linked page above.

(Can I declare a local network static IP address for an Arduino?)

Yes.

Other comments?

You could use NRF24L01 modules for short-range communication of wireless information. I have example code and schematics. My tests seemed to indicate 20m range was achievable.

Have you looked at the Adafruit Huzzah boards? It's small, inexpensive ($10), comes with wireless capability and a 10-bit ADC for a temperature sensor. If you'll have access to the Internet, then you could use NTP to get time.

I've been looking at it.  That is exactly the same suggestion as was made by @IgnacioVazquez-Abrams to look at the ESP8266.  In fact I've been studying up on those for the past two hours.  The Adafruit Huzzah and the NodeMCU are two implementations that have got my interest.  Both of those boards expand the pinouts, as well as add 5v -> 3.3v regulation.  I've been reading up the awesome E-book on the ESP8266 from Neil Kolban  Clearly this chip makes a lot of sense for me, if I can get the desired I/O to fit and function in existing memory.

From the looks of your specs for the project a '328 Arduino would have more than enough flash (32K) and RAM (2K) to run your application – based on having built similar projects using an Uno. You've got the ADC as well as several GPIO pins. What I can't tell from Adafruit's page and the data sheet is if you get any flash, but it is capable of addressing up to 16 MB and that's way more than you need.

Sounds great.  I just ordered a few boards and supporting supplies from Ebay.  I ordered a few xtra sets, thought this would make a good meetup project for the folks locally.  The board was $5.36 / ea, Wow.  Not sure what you mean about the 328 Arduino.  I'm hoping to use a virgin ESP8266 board.  From what I can see that board has 512KB flash memory.  I only need one analog input and one general I/O output.  Not sure about the web stuff yet.. For as little as this cost I'm going to try and see what happens.  I know I can always fall back and use the Intel Edison.


text:
How to configure 2nd Quadrature Decoder IO pins in Arduino IDE
I am working to read two quadrature encoders using a single Arduino DUE, as part of my summer vacations project. According to the following link
http://atmel.force.com/support/servlet/fileField?id=0BEG0000000HRvP, the SAM3X8E has 2 quadrature decoders in it. Now I am not being able to understand how can I initialize this second quadrature decoder. According to Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483 Pg16 we have to first configure the IOPINS for QDEC1. I have to do that same task in Arduino IDE instead of Atmel Studio.
This is the code that I have found and works well to read encoder using QDEC0. However, I now need to read the encoder using the second quadrature decoder, whose input pins are TIOA6 , TIOB6 which correspond to Pin 5 and 4 of Arduino DUE. After reading the Atmel SAM3X datasheet, I think I should change "TC0" with "TC2" to make the second decoder work. However, this doesn't work. I think it does not work because channel 2 is busy in time base calculations.
In Application Note 5.52 QDEC Speed Measurement Mode point 2 says to Initialize TC0, TC1, TC2. If I wanted to used other encoder which timer instance will be used.
/*
** Quadrature Encoder on Arduino Due in "Speed Mode"
** Will not work on other Arduino types because of a specific hardware requirement.
**
** @bungle99 / 2014-02-28
**
** Many thanks to @Designservicecorp (notably post #32 and post #42) that gave me the base to work from.
**
** Uses *hardware* to do the heavy lifting of interpreting the Encoder output, which gives it significant
** advantage over other Arduino's for this use case. Eg many people have reported their Unos maxing out
** or skipping counts when interpretting high RPMs, whereas people using the Due in hardware mode have
** reported better success with high RPMs.
**
** This particular example puts the hardware into "Speed" mode, whereas other examples in this thread use
** "Position" mode (see posts 32, 42). The one example in the thread that attempts Speed calcs uses Position
** Mode and uses an interrupt on the Z Index axis to manually apply a time period (needed to caculate speed)
** on each rotation.
**
** This code below has been used in tests (using Lego NXT and a gear train for driving / comparison) to
** ~3,500 RPM with a 1,024 PPR Encoder (4 x 1,024 Edges). The Arduino didn't seem to struggle and the
** numbers (eg RPM) matched fairly closely with the Lego (eg as a sanity check, the calcs in the code look
** correct).
**
** I bought one of these encoders, which seems ok;
**
**   * http://proto-pic.co.uk/rotary-encoder-1024-p-r-quadrature/
**
** Great service from proto-pic. The encoder specs are officially
**
**   * http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Robotics/E6B2Encoders.pdf
**
** But look an awful lot like this one too (which is easier to read)
**
**   * http://www.ia.omron.com/product/item/e6b27032r/index.html
**
** Note that this Encoder is rated at 5V min. I've successully powered it off the 5V Arduino pin header,
** and it doesn't work off the 3.3V one. At 5V, the outputs need to be run through some resistors to bring
** them into tolerance of the Arduino inputs.
**
** The inputs are 2 and 13 (and optionally A6 for the index).
**
** The test hardware (some Lego NXT servos and gear train) was unable to turn any faster (more gears
** stalled the servos) - eg the Arduino Due was not the limiting factor. At this speed, the Due Hardware
** is dealing with approx 238,000 edges per second.
**
** This example offloads the speed calculation onto the hardware, meaning no interrupt is required.
** In addition, the index is not required either, so it allows speeds to be seen even for rotations that
** don't pass the index marker (for example, slow rotations needing a speed before a complete rotation).
** That said, index is available if you want it and the docs suggest you can still use it (and others) as
** interrupt if you wish.
**
** NB There appears to be a myriad of features on the Chip that have not been touched. Eg you can still add
** interrupts to this code to do other things; eg passing the Z index, direction changes. There are also
** filters available if your encoder suffers from noise (eg vibrations). All this is available to play with
** another day :)
**
** Code appears to work, but no guarantees. Understand it. Test it. Feedback to the group. YMMV. Don't blame
** me if it doesn't work or expolodes!
*/

const int ENCODER_EDGES_PER_ROTATION = 3200;  // this depends on your encoder
const int ENCODER_SAMPLES_PER_SECOND = 10;        // this will need to be tuned depending on your use case...
const int LOOP_DELAY_MS = 1 * 1000;               // ... as will this (see comments in main code)

void setup() {

  Serial.begin(115200);
  delay(10);

  // Setup Quadrature Encoder
  // http://www.atmel.com/Images/doc11057.pdf
  // Section 37 p869
  // Section 37.6.14 p885
  // Section 37.6.14.2 p890 Position and Rotation Measurement
  // Section 37.6.14.5 p891 Speed Measurement (what this is about)

  REG_PMC_PCER0 = PMC_PCER0_PID27
                | PMC_PCER0_PID28
                | PMC_PCER0_PID29;

  // Setup a channel in waveform mode (eg an input into the encoder to trigger the time based sampling)
  // Note some of the choices here impact calculations below and if you change them, you need to change
  // the next section to suit.
  // Section 37.7.11 p906 (also refer to Section 37.6.14.5 p891 for detail of what to set)
  REG_TC0_CMR2 = TC_CMR_TCCLKS_TIMER_CLOCK4
               | TC_CMR_WAVE
               | TC_CMR_ACPC_TOGGLE
               | TC_CMR_WAVSEL_UP_RC;

  // Now define the sample period, using the clock chosen above as the basis
  // Note that REG_TC0_CMR2 above is using CLOCK4; this is an 128 divisor. You need to change the
  // divisor below if you change the clock above. You could change the input clock and the RC mode to
  // suit your app (eg how many pulses are you  expecting - depends on encoder type
  // and slowest/normal/fastest rotation speed and what you want to do with the result).
  // Section 37.6.14.5 p891 notes you need to set this up, otherwise 0 comes out all the time :-)
  REG_TC0_RC2 = F_CPU / 128 / ENCODER_SAMPLES_PER_SECOND;

  // Setup a channel in capture mode
  // Section 37.7.10 p904 (also refer to Section 37.6.14.5 p891 for detail of what to set)
  REG_TC0_CMR0 = TC_CMR_ABETRG
               | TC_CMR_LDRA_EDGE
               | TC_CMR_LDRB_EDGE
               | TC_CMR_ETRGEDG_EDGE
               | TC_CMR_CPCTRG;

  // Enable features, noting Speed not Position is chosen
  // Section 37.7.2 p895 (also refer to Section 37.6.14.5 p891 for detail of what to set)

// 37.7.2 TC Block Mode Register
  REG_TC0_BMR = TC_BMR_QDEN
              | TC_BMR_SPEEDEN
              | TC_BMR_EDGPHA; //Pg 896

/*EDGPHA: EDGe on PHA count mode
0: edges are detected on both PHA and PHB.
1: edges are detected on PHA only.*/

  // Set everything going
  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;
}

void loop() {

  int iIndexCount = REG_TC0_CV1;  // Don't need this, but manual notes its available
  int iSpeedPPP = REG_TC0_RA0;    // This is what we're really after (speed in Pulses Per sample Period)

  // which we can convert to rps or rpm easily
  double dSpeedRPS = ((iSpeedPPP / (ENCODER_EDGES_PER_ROTATION * 1.0)) * ENCODER_SAMPLES_PER_SECOND);
  double dSpeedRPM =  dSpeedRPS * 60;

  Serial.print("Speed ppp: ");
  Serial.print(iSpeedPPP);
  Serial.print(", ");
  Serial.print("Speed rps: ");
  Serial.print(dSpeedRPS);
  Serial.print(", ");
  Serial.print("Speed rpm: ");
  Serial.print(dSpeedRPM);
  Serial.print(", ");
  Serial.print("Indexes: ");
  Serial.print(iIndexCount);
  Serial.print(". ");
  Serial.println();

  // Slow down the main loop noting the Encoder can update independently in the background (we're
  // effectively polling it to find out the latest and greatest info on each loop around).
  delay(LOOP_DELAY_MS);
}

Additionally I wanted to ask what is the difference between REG_TC0_CMR2 REG_TC0_CMR0 and REG_TC0_CMR1 ? Two of them are used in the above code.
Motor with Encoder I am using is:

TC blocks are pretty much identical (except TC1 doesn't have wired some signals to pins)
So you have to copy registers containing *_TC0_* = and replace TC0 to TC2.
Plus PC25 and PC24 should be set to its alternate function PIO_PERIPH_B. 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);

Also TC6, TC7 and TC8 clocks must be enabled by:
REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

And TC_CMR0..2 are Channel Mode Registers for one of three timers/counters in one TC block. Again, these are the same, but WAVE mode dependent.

Full configuration:
  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 have tried this , but it doesn't work. We are not getting any measurement....

@MasoodSalik also clocks must be enabled for channels 6-8. I though it's enabled for whole block by REG_PMC_PCER0 = PMC_PCER_PID29 but it was just third counter in TC0.

I have enabled all the clocks using
{ REG_PMC_PCER0 = PMC_PCER0_PID27                     | PMC_PCER0_PID28                     | PMC_PCER0_PID29                      | PMC_PCER0_PID30                       | PMC_PCER0_PID31;  REG_PMC_PCER1 = PMC_PCER1_PID32                     | PMC_PCER1_PID33                     | PMC_PCER1_PID34                      | PMC_PCER1_PID35; }
Now I am able to read QDEN1 from pin 4 and 5 . QDEN0 from pin 2 and 13. I am now reading clicks_per_revoluion using REG_TC2_CV0 and  REG_TC0_CV0. Now i am trying to measure the speed