text:
Arduino Mega not flashable with XBee PRO S2B
I have an Arduino Mega 2560 with a libelium XBee Shield. If I have an XBee S2 mounted on it and set the two jumpers to the USB setting or remove them, I am able to flash a program onto my Arduino.
However, when I'm mounting one of my XBee PRO S2B (I have three of them available and all behave the same) on the Arduino, no matter how I set the jumpers, it is not possible to flash anything on it. I always see avrdude: stk500v2_getsync(): timeout communicating with programmer in the Arduino IDE.
Is the XBee PRO S2B incompatible with the Arduino or what might be the issue? I also tried to add an external power source additionally to the USB, but it didn't help either.
Update
After some more experimenting, I found out new details. I tried to disconnect each pin of the shield individually. While doing it, I discovered that disconnecting the reset pin from the arduino makes it possible to flash it - take a look at the XBee shield schematic, it's pin 5 from the ICSP connector; Photo:
I used a multimeter and discovered that the XBee PRO S2B CTS / DIO7 port is high, while the one from the XBee S2 is low, and so constantly resetting the arduino. I mounted the XBee PRO S2B onto the Sparkfun XBee Explorer USB and opened a serial port with PuTTY.
In contrast to the S2, the PRO S2B provides a menu with several options:
B-Bypass Mode
F-Update App
T-Timeout
V-BL Version
A-App Version
R-Reset
>

As soon as I type B, the CTS port goes low, and would prevent the arduino from resetting. Also this mode is needed to detect the module via XCTU. However, with an unmodified arduino, I wouldn't have a chance to send this letter, since the XBee is constantly resetting it. What is this menu, can it be disabled somehow?

May seem obvious, but did you compare the register settings of the XBee S2 and S2B? Such as through X-CTU. Speed, parity, etc.

See the update; since this DIO7 port seems to be an issue, I took a look at the configuration especially on this setting; on both, the S2 and the PRO S2B it says DIO7 Configuration: CTS flow control [1]. I suspect that all of these settings are irrelevant while it waits in this "bootloader thing"?

Not a full answer - but IO/7 appears to be CTS flow control. I strongly urge you to download and use the X-CTU software (by Digi Intl.) to program them. Command line ATD7 will show current setting, ATD7=0 will disable (but use X-CTU). Why is this important? The XBee shields use CTS/RTS to signal a reboot to the Arduino (shield) - and then the bootloader will kick in and accept the data stream for flashing.

I used X-CTU to change this setting. If I disable DIO7 [0], it shows the same behaviour - as long as it is in this bootmenu, it is high. When I enter bypass mode, it goes low. If I set DIO7 to 5 (Digital Out, High), it keeps beeing high even after choosing bypass mode. So it seems like all the settings take only effect after entering bypass mode :/

Compare every setting on the working S2 with the non-working S2B thru X-CTU.

I don't have a PRO to play with, but I just looked at the datasheet and it appears that it SHOULD timeout after 60 seconds

If no serial transaction is initiated within a 60 second timeout period, the bootloader times out and returns to
  the menu. If the upload is interrupted with a power cycle or reset event, the EM250 will detect an invalid
  application image and enter bootloader mode.  (page 139)

Also, it seems that it takes a particular set of conditions to get to the bootloader, obviously these conditions are being met:

XBee modules use a modified version of Ember’s bootloader. This bootloader version supports a custom entry
  mechanism that uses module pins DIN (pin 3), DTR / SLEEP_RQ (pin 9), and RTS (pin 16). To invoke the bootloader,
  do the following:

Set DTR / SLEEP_RQ low (TTL 0V) and RTS high.
Send a serial break to the DIN pin and power cycle or reset the module.
When the module powers up, DTR / SLEEP_RQ and DIN should be low (TTL 0V) and RTS should be high.
Terminate the serial break and send a carriage return at 115200bps to the module.
If successful, the module will send the Ember bootloader menu out the DOUT pin at 115200bps.
Commands can be sent to the bootloader at 115200bps.

Note: Hardware flow control should be disabled when entering and communicating with the EM250 bootloader.

Perhaps check pins 3, 9 and 16 on boot and see if you can modify their behaviour.

I've long since closed the document, but I believe the second block quote there came from page 138


text:
Serial.write displaying repeating output from Xbee communication
I want to use xbee's to communicate between two different arduinos.  I'm using this tutorial as a guide to setup my xbee's. I've already used XCTU to setup one xbee as a router and another as a coordinator (both in ZIGBEE AT mode).  I used XCTU's terminal feature to verify that info was being sent and received properly.
Basically, I have both arduinos connected to the same PC via USB cables, but the communication is taking place through the Xbee's.  I also made sure to disconnect the TX & RX wires when uploading the sketches to avoid an AVRDUDE error.
I wanted to test the communication by sending a "hello world" message once every five seconds, from the router to the coordinator.  To do this, I wrote the following code:
//Code for Arduino attached to Xbee in Router AT mode
void setup(){
 Serial.begin(9600);
}

void loop(){
  Serial.println("Hello World!");
  delay(5000);
}

and
//Code for Arduino attached to Xbee in Coordinator AT mode
void setup(){
  Serial.begin(9600);
}

void loop(){
  if (Serial.available()>0){
    Serial.write(Serial.read());
  }
}

I checked the serial monitor for the arduino connected to the router, and it does exactly what I expected to see:  a new Hello World message once every 5 seconds.  However, the serial monitor on the arduino connected to the coordinator does not produce the desired effect:  the "hello world" message instantly displays the message over a hundred times per second and repeats without end, each time on a separate, new line.  Sometimes, when I turn the serial monitor on, the message instantly appears with a few repetitions before displaying some strange characters and stopping altogether.
I'm not sure if the problem is with the serial monitor or with the xbee.  Any help with this problem would be greatly appreciated.

The same issue was reported on the Arduino forum and the user was able to solve it by setting the DL parameter to be 1 on the coordinator Xbee and 0 on the router Xbee.

Code is correct and it does what it is asked to. The receiver code reads the RX pin of arduino which is connected to the Xbee. The same pin is used by the FT232 interface IC to send data to your computer through USB.
The "hello world" you send is received by the Xbee and is send to microcontroller and FT232 at same time as that pin is shared between them. Thus the "hello world" will be seen in serial monitor, first time from Xbee and second time, from Serial.write(Serial.read()) of the program.
Also check whether the settings are correct from this tutorial, as Xbee will not be configured as P2P.

But why would the message repeat infinitely and fill up the serial monitor at a rate faster than one message every 5 seconds?

The problem is that the message repeats over a hundred times a second, much faster than the "once per 5 seconds" that the message is being sent from the other xbee.  Why would this happen?

Did you check the baud rate configured for xbee and serial monitor is same as in the code (9600)?

I checked, and it was, in fact, set to 9600 baud rate.

Is there any way to work around this problem?  I just want to be sure that the data that was sent is received and displayed at the proper speed in which it was sent.

source: Stack Exchange

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

sort: votes


text:
How can I use an MPU6050 with Arduino to measure linear speed?
I need to measure linear speed of a body which travels 1000 m forward and backward recursively. How can I use an MPU6050 with Arduino Nano to measure the linear speed of a moving object? (the object does not have any rotation). I tried my best, but I was not able to measure linear speed, can I get sample source code?

You can't. Integration of horizontal accelerations will give you a considerable error.

Exactly. Error will add up making your measurement completely useless. On the other hand, I assume 1000m is somewhere in the open. So adding GPS to the accelerometer, and using Kálmán filter to use both sensors will give you acceptable results. Or if your movement is on rails or wheels, using an encoder will be even better.

The problem is small errors and drift. If your acceleration reading is off by 5% for each reading, that error compounds and after just a few readings the error completely swamps the calculated velocity and position readings. You can't sense velocity using an accelerometer, so you have no way to tell if you are moving at 0 kpm or 1000 kpm.

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


text:
Need help combining two sketches (HC05 and temperature)
I have a project where I have to combine 4 sensors and get data wireless via Bluetooth (HC05). I just want help with combining just 1 sensor sketch and the Bluetooth sketch. I want the data from the temperature sensor to be displayed on my phone.
Temperature sensor code:
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2

OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup(void)
{
  // start serial port
  Serial.begin(9600);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
}

void loop(void)
{
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures();
  Serial.println("DONE");

  Serial.print("Temperature is: ");
  Serial.print(sensors.getTempCByIndex(0));
  delay(1000);
}

Bluetooth code:

#include <SoftwareSerial.h>
SoftwareSerial BT(11, 10);
int ledPin = 8;
int state = 0;

void setup()

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

void loop() {
  if(BT.available() > 0){
  state = BT.read();

  }
    if (state == '0'){
      digitalWrite(ledPin, LOW);
      BT.println("LED: OFF");
      state = 0;
    }
    else if (state == '1'){
      digitalWrite(ledPin, HIGH);
      BT.println("LED: ON");;
      state = 0;

    }
}

Instead of writing it all out, I give some tips:

First combine the content of both setup functions. You can remove duplicate lines (e.g. Serial.begin(9600); is needed only once. Keep the order in a logical way.
Than combine the content of both loop functions. However, the delay could cause a problem. Replace this by keeping a variable with the current time, and check when it's at least a second ago you checked the temperature sensor, if so, measure the sensor (and update the variable to the current time).

So you get something like:
unsigned long lastSensorMeasurement;

void setup()
{
   // Combination of both setup functions

   lastSensorMeasurement = millis();
}

void loop()
{
   // Process sensor
   if (lastSensorMeasurement + 1000 >= millis())
   {
      // Code for sensor as in loop
   }

   // Process Bluetooth
   // Code for bluetooth as in loop
}

now() only has a resolution of 1 second. Usually you use millis() for timing, which gives 1/1000 of a second resolution.

@DuncanC Thanks ... of course I meant that; I updated my answer, thanks for the notification.

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


text:
Hold button / press button/ push button
I want to control a servo motor in a way that

if you push the button, you can control it by potentiometer a
if you push double time, you can control servo with infrared
if you hold button step motor start to to rotate from one position to another

I have a problem that when I press button it goes to an infinite loop and I can not stop it .
I try different button library but I still have a same problem.
Here is my code :
// includes the Servo library
#include <Servo.h>
#include <IRremote.h>
#include <OneButton.h>

int state = 0;
int RECV_PIN = 12;
const char type ='W';// W for white, B for black. Must keep single quotes like 'B' or 'W'
const boolean PCB = 0;// if receiver is PCB set to 1, if not set to 0. See video for details
boolean displayCode = true;// to display remote code. if not, set to false

const int SERVO_PIN = 8;  // analog pin used to connect the potentiometer
int angle =90;    // initial angle  for servo
int angleStep =10;
const int ANGLE_CENTRE =90;// the centre/reset angle of your servo
//**** Servo settings settings ends

// remote settings
const String RIGHT="CH+";// move servo to the right with this key on remote
const String LEFT ="CH-";// move servo to the left with this key on remote
const String CENTRE ="CH";// move servo to centre with this key on remote
// remote settings end

IRrecv irrecv(RECV_PIN);
// Defines Tirg and Echo pins of the Ultrasonic Sensor
const int trigPin = 10;
const int echoPin = 11;
const int potPin = 0;
const int pushButton = 8;
OneButton button(A1, true);
int value;

// Variables for the duration and the distance
long duration;
int distance_cm;
Servo myServo; // Creates a servo object for controlling the servo motor

// this is array holding codes for White Remote when used with non-PCB version of receiver
unsigned int whiteRemote[] ={
            0xFFA25D, // CH-
            0xFF629D,   // CH
            0xFFE21D,  // CH+

            0xFF22DD, // |<<
            0xFF02FD, // >>|
            0xFFC23D, // >||

            0xFFE01F, // -
            0xFFA857, // +
            0xFF906F, // EQ

            0xFF6897, // 0
            0xFF9867, // 100+
            0xFFB04F, // 200+

            0xFF30CF, // 1
            0xFF18E7, // 2
            0xFF7A85, // 3

            0xFF10EF, // 4
            0xFF38C7, // 5
            0xFF5AA5,  // 6

            0xFF42BD, // 7
            0xFF4AB5, // 8
            0xFF52AD  // 9
            };
// key lables of white remote
 String whiteRemoteKey[] ={
            "CH-",
            "CH",
            "CH+",

            "|<<",
            ">>|",
            ">||",

            "-",
            "+",
            "EQ",

            "0",
            "100+",
            "200+",

            "1",
            "2",
            "3",

            "4",
            "5",
            "6",

            "7",
            "8",
            "9"
            };

// this is array holding codes for Black Remote when used with non-PCB version of receiver
 unsigned int blackRemote[] ={
            0xFF629D, // ^
            0x38D3975C,   // <
            0x9334F738,  // OK
            0x320412D8, // >
            0xFFA857, // v

            0xFF6897, // 1
            0xFF9867, // 2
            0xF0C41643, // 3

            0xFF30CF, // 4
            0xFF18E7, // 5
            0xFF7A85,  // 6

            0xFF10EF, // 7
            0xFF38C7, // 8
            0xFF5AA5,  // 9

            0xFF42BD, // *
            0xFF4AB5, // 0
            0xFF52AD  // #
            };
// Black remote key names
 String blackRemoteKey[] ={
            "^",
            "<",
            "OK",
            ">",
            "v",

            "1",
            "2",
            "3",

            "4",
            "5",
            "6",

            "7",
            "8",
            "9",

            "*",
            "0",
            "#"
            };

decode_results results;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an input
  Serial. begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  myServo.attach(SERVO_PIN); // Defines on which pin is the servo motor attached

  button.attachDoubleClick(doubleClick);            // link the function to be called on a doubleClick event.
  button.attachClick(singleClick);                  // link the function to be called on a singleClick event.
  button.attachLongPressStop(longClick);            // link the function to be called on a longpress event.

}
void loop() {
  button.tick();                                    // check the status of the button
  delay(10);                                        // a short wait between checking the button
}

// Function for calculating the distance measured by the Ultrasonic sensor
int calculateDistance(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HiGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
  //Comment by me!
  //distance= duration*0.034/2;
  //
  distance_cm = (duration/2) / 29.1;
  return distance_cm;
}
void doubleClick() {                                // what happens when button is double-clicked
  while(1) {
    if (irrecv.decode(&results)) {
      if(displayCode)Serial.println(results.value, HEX);
      validateCode(results.value);// used the "robojaxValidateCode" bellow
      irrecv.resume(); // Receive the next value
    }
    delay(50);// 50 melisecond delay
    break;
  }
}

void singleClick(){                                 // what happens when the button is clicked
  while(1) {
    value = analogRead(potPin);
    value = map(value, 0, 1023, 15, 165);
    myServo.write(value);
    delay(30);
    distance_cm = calculateDistance();

    Serial.print(value); // Sends the current degree into the Serial Port
    Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing iDE for indexing
    Serial.print(distance_cm); // Sends the distance value into the Serial Port
    Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing iDE for indexin
  }
}

void longClick(){                                   // what happens when buton is long-pressed
  for(int i=15;i<=165;i++){
    myServo.write(i);
    delay(30);
    distance_cm = calculateDistance();// Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree

    Serial.print(i); // Sends the current degree into the Serial Port
    Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing iDE for indexing
    Serial.print(distance_cm); // Sends the distance value into the Serial Port
    Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing iDE for indexin
  }
  // Repeats the previous lines from 165 to 15 degrees
  for(int i=165;i>15;i--){
    myServo.write(i);
    delay(30);
    distance_cm = calculateDistance();

    Serial.print(i);
    Serial.print(",");
    Serial.print(distance_cm);
    Serial.print(".");
  }
}
/*
 * function: validateCode
 * validates the remote code and prints correct key name
 * cd is code poassed from the loop
 * Written by A. S. for Robojax
 */
void validateCode(int cd)
{

  // Robojax IR Remote decoder
  int found=0;

 if(type =='W' && !PCB)
 {
    // Robojax IR White Remote decoder
    // if tyepe is set to 'W' (white remote) and PCB=0 then check Black remote code
      for(int i=0; i< sizeof(whiteRemote)/sizeof(int); i++)
      {
        if(whiteRemote[i] ==cd)
        {

          Serial.print("Key pressed:");
          Serial.println(whiteRemoteKey[i]);
          servoAction(whiteRemoteKey[i]);// take action
          found=1;
        }// if matched
      }// for
 }else{

      // if tyepe is set to 'B' (black remote) and PCB =0 then check Black remote code
       for(int i=0; i< sizeof(blackRemote)/sizeof(int); i++)
      {
        // Robojax IR black Remote decoder
        if(blackRemote[i] ==cd)
        {

          Serial.print("Key pressed:");
          Serial.println(blackRemoteKey[i]);
          servoAction(blackRemoteKey[i]);// take action

          found=1;
        }// if matched
      }// for
 }// else
  if(!found){
    if(cd !=0xFFFFFFFF)
      {
    Serial.println("Key unkown");
      }
  }// found
}// validateCode end

/*
 *
 * servoAction()
 * receives string "value" as input and based on the settings,
 * sends translates it to servo value and controls servo
 * either
 * rotates servo to right
 * rotates servo to left
 * moves the servo to middle
 *
 */
void servoAction(String value){
  // Servo button demo with IR remote by Robojax.com
  while(value == RIGHT){

    if (angle > 0 && angle <= 180) {
      angle = angle - angleStep;
       if(angle < 0){
        angle = 0;
       }else{
      myServo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
       }
    }// if
    value =".";
    delay(100);
  }// while for RIGHT
  while(value == LEFT){

    // Servo button demo with IR remote by Robojax.com
    if (angle >= 0 && angle <= 180) {
      angle = angle + angleStep;
      if(angle >180){
        angle =180;
       }else{
      myServo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
       }
    }
    value =".";
    delay(100);
  }// while for LEFT

  if(value == CENTRE)
  {
    angle = ANGLE_CENTRE;
    myServo.write(angle); // move the servo to centre at 90 degree angle
  }
    // Robojax IR Servo control
}//relayAction end

sorry about my English.
I hope someone help me.

You have infinite loops in the click event call functions, after a button event you never return to the main loop.
Use the event functions just to set a status variable then, in the main loop use switch case case to select the code used by the servo control like this:
 ....
 unsigned int status = 0;
 ....
 void doubleClick(){
    status = 0;
 }
 void singleClick(){
    status = 1;
 }
 void longClick(){
    status = 2;
 }
 void setup() {
 ....
 }
 void loop {
   button.tick();                                    // check the status of the button
   //delay(10); // this is not needed.
   switch (status){
     case 0:{
       //action for double click
     }
     case 1:{
       //action for single click
     }
     case 2:{
       //action for long click
     }
 }

Inside each case insert the corresponding code code you have in the while(1) loops of the button event functions.
Another option is to insert inside the forever loops a return when the button is pressed like this:
if (button pressed)  return;

Please use Enum instead of "magic number"

Thanks for your answer.But I need that action happen infinitely until the status of the button change from for example single push to double push .when I use if statement It does not work properly.

@AmirHosseinJobeiri The while(1) loop is replaced by the main loop so it is happening forever until you press the button and change the status variable. Or just use return on button pressed inside while(1) loop but it is quite difficult to extend your code further.


text:
Arduino + USB Host Shield + ESP8266
I am using an Arduino Uno and a USB Host shield for Barcode Scanner. The whole scenario is that when I scan the barcode through USB Barcode Scanner, it scans and gives a code. Now the question is how to connect the ESP8266 with the USB Host Shield to transfer data to the web server. I have set the pins to 2, 3 for receiving data from server. Send Data and Receive data with ESP8266.
The Arduino Code:
#include <SoftwareSerial.h>
#include <hid.h>
#include <hiduniversal.h>
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
String result = "";
#define DISPLAY_WIDTH 16

// initialize the LCD library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
SoftwareSerial esp(3, 2);

USB     Usb;
USBHub     Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

class KbdRptParser : public KeyboardReportParser
{
 void PrintKey(uint8_t mod, uint8_t key);
protected:
  virtual void OnKeyDown  (uint8_t mod, uint8_t key);
  virtual void OnKeyPressed(uint8_t key);
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{

    uint8_t c = OemToAscii(mod, key);

    if (c)
        delay(100);
       OnKeyPressed(c);

}

/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key)
{
static uint32_t next_time = 0;      //watchdog
static uint8_t current_cursor = 0;  //tracks current cursor position

    if( millis() > next_time ) {
      lcd.clear();
      result = "";
      current_cursor = 0;
      delay( 5 );  //LCD-specific
      lcd.setCursor( 0,0 );
    }//if( millis() > next_time ...

    next_time = millis() + 200;  //reset watchdog

    if( current_cursor++ == ( DISPLAY_WIDTH + 1 )) {  //switch to second line if cursor outside the screen
      lcd.setCursor( 0,1 );
    }

 result += (char)key;//Serial.print("Result "+result+"\n");
 delay( 50 );
    //Serial.print((char)key );
    //lcd.print((char)key );
};

KbdRptParser Prs;

void setup()
{
    Serial.begin(9600);
    Serial.println("Start");
    esp.begin(115200);
    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay( 200 );

    Hid.SetReportParser(0, (HIDReportParser*)&Prs);
    // set up the LCD's number of columns and rows:
    lcd.begin(DISPLAY_WIDTH, 2);
    lcd.clear();
    lcd.noAutoscroll();
    lcd.print("Ready");
    delay( 200 );

}

void loop()
{
  String content = "";
  char character;
  Usb.Task();
  if(result != ""){
    delay(10);
    Serial.println(result);
    }
   /*while(Serial.available()){
    character = Serial.read();
    content.concat(character);
    Serial.print("Serial Result : "+content);

    }*/
    if (esp.available())
   {

    char c = esp.read();
    if(isDigit(c)){
      lcd.clear();
      lcd.print(c);
        Serial.print(c);

       }
    }

}

The ESP8266 Code is:
#include <ESP8266WiFi.h>

const char* ssid     = "stormfiber"; //Wi-Fi SSID
const char* password = "11223344"; //Wi-Fi Password

//Server IP or domain name
const char* host = "192.168.100.228";
void setup()
{
  Serial.begin(115200);
  Serial1.begin(9600);
  WiFi.begin(ssid, password);
  Serial.println(ssid);
  while (WiFi.status() != WL_CONNECTED) { //Wait till connects
    delay(500);
    Serial.print(".");
  }

}

void loop()
{
  char character;
  String content = "";
  delay(5000);

  //Serial.print("connecting to ");
  //Serial.println(host);
  while(Serial1.available()){
    character = Serial1.read();
    content.concat(character);
    }
    if(content == ""){
      content = "123";
     }
  WiFiClient client; //Client to handle TCP Connection
  const int httpPort = 2124;
  if (!client.connect(host, httpPort)) { //Connect to server using port httpPort
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "/test/index.php?code="+content; //File or Server page you want to communicate with. along with data

  // This will send the request to the server
  client.print(String("GET ") + url + "\r\n");

  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 25000) { //Try to fetch response for 25 seconds
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }
  Serial.println();
  //Serial.println("closing connection");
  client.stop(); //Close Connection
  /*static unsigned long timer = 0;
  unsigned long interval = 5000;
  static unsigned int index = 0;
  if (millis() - timer >= interval)
  {
    timer = millis();
    Serial.print("The index ");
    Serial.println(index);
    index++;
  }*/
}

Please help how to connect the ESP8266 with the host shield. Although it works fine with Arduino only.
Any help regarding this will be appreciated.
Thanks

the USB host shield doesn't use pins 2 and 3 but your LCD setup does

Thanks for the answer but how we can connect esp8266 communicating with USB Host Shield. Is there any possibility?

Can we read data from 2,3 pin by esp8266?

what problem do you have with the USB shield? it changes nothing for the SoftwareSerial on pins 2 an 3

yes it shows nothing

you write that it works without the shield. so what are you asking? it should work the same way with the shield. but you use pins 2 and 3 for LCD too. how?

The USB shield has no relevance to anything here. It is "the other sided" of the Arduino. USB <=> Arduino <=> ESP8266. Ignore the USB shield. Remove it from your perception completely.

Bro I have just removed the USB Host shield over Arduino and place ESP8266 directly to arduino. Now it shows the data that comes from ESP8266 , When i place again USB Host shield and ESP over Host shield it again shows nothing on 2,3.

Does disconnecting the USB host shield also disconnect the LCD that is conflicting with the serial connection?

i did not connect LCD yet. just writing a code for that. Sorry for the inconvenience

please ignore the LCD here just i am focusing on ESP8266

Remove all the code for the LCD then. It's confusing matters.


text:
HC-05 with ELM327 mini OBD2 Bluetooth adapter connection problem
I am using Arduino Uno and HC05 Zs-040 Bluetooth module to establish a connection with ELM327 mini OBDII Bluetooth adaptor.
I have tried more than 15 different sequences of AT commands and most of them works successfully and HC05 reply with "ok" with no errors.
When I switch off the power from the HC05 and reconnect it again to connect automatically to the MAC address stored in it during configuration, the HC05 connects to the ELM327 OBDII adaptor for a time interval ranges from 2 to 5 seconds then the connection is lost.
I was able to notice that from the LED blinking on the HC05. This process of connection and disconnection is repeated automatically and the LED on the HC05 blinks in different patterns.
Also, I was able to connect to the ELM327 OBDII adaptor using a python script and it connects to it (I did that at the same time when the HC05 was trying to connect to OBDII adaptor which confirms that the connection between HC05 and the adaptor was not established).
In addition, I was able to connect to ELM 327 adaptor using Torque application and Bluetooth terminal application and both work fine.
Can anyone help me figuring out why does the connection is lost as soon as it is established?

I faced a similar problem when working with HC-05 module with an Android terminal application and connection was lost after some time and many it was just not able to connect.
Upon some hit and trials I found that it was just an power issue with HC-05 and as soon as I tried it out by reducing load on HC-05 by connecting it alone on 5V supply from Arduino and switching others to a 3V supply it worked like butter and I didn't faced any problem till now.
This worked for me try this out.


text:
How to upload .hex file to Atmega8 Using Arduino IDE and Uno as an Isp?
I want to upload an .hex file to an Atmega8 chip (SMD). I want to use the Arduino IDE and an Uno as the ISP program. But I'm unable to find any details on how to load a sketch which is in .hex format.
Following is the batch file I created to use with avrdude. I would like to know if the Command is correct?
C:\Users\Pranay\Desktop\DIY\arduino-1.0.1!\hardware\tools\avr\bin/avrdude -CC:\Users\Pranay\Desktop\DIY\arduino-1.0.1!\hardware\tools\avr\etc/avrdude.conf -v -v -v -v -patmega8 -cstk500
 -P\\.\COM4 -b19200 -Uflash:w:C:\Users\Pranay\Desktop\DIY\arduino-1.0.1!\hexFiles\Heart.hex:i

pause

It looks okay. Have you tried running it? It can't do any harm if it's wrong; you just get an error message.

When i run the batch file it says "C:\Users\Pranay " is not recognised as internal or external command, operable program or Batch file.
In the next line it says the system cannot find the path specified.

I think that means you got the file-path wrong.

Thanks for your help @Gerben. figured out the mistake and finally sucedded in uploading sketch.

That good to hear. Could you share your solutions, so others might learn from it?

@Pranay Could you please post the solution as an answer to this post. https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/

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


text:
How to connect two IMU in one arduino board?
The code below works fine when  one IMU (MPU9250). What I want to know is how can I edit this code to work perfectly with two IMU (MPU9250) in one arduino board ?
Hope someone can help me. THANKS :)
////////////////////////////////////////////////////////////////////////////
      //
      //  This file is part of RTIMULib-Arduino
      //
      //  Copyright (c) 2014-2015, richards-tech
     //
     //  Permission is hereby granted, free of charge, to any person           obtaining a copy of
    //  this software and associated documentation files (the "Software"), to deal in
    //  the Software without restriction, including without limitation the rights to use,
   //  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
   //  Software, and to permit persons to whom the Software is furnished to do so,
   //  subject to the following conditions:
   //
   //  The above copyright notice and this permission notice shall be included in all
  //  copies or substantial portions of the Software.
  //
  //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  //  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  //  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  //  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  //  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  //  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

  #include <Wire.h>
  #include "I2Cdev.h"
  #include "RTIMUSettings.h"
  #include "RTIMU.h"
  #include "RTFusionRTQF.h"
  #include "RTPressure.h"
  #include "CalLib.h"
  #include <EEPROM.h>

  RTIMU *imu;                                           // the IMU object
  RTPressure *pressure;                                 // the pressure object
  RTFusionRTQF fusion;                                  // the fusion object
  RTIMUSettings settings;                               // the settings object

  //  DISPLAY_INTERVAL sets the rate at which results are displayed

  #define DISPLAY_INTERVAL  300                         // interval between   pose displays

 //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

 #define  SERIAL_PORT_SPEED  115200

  unsigned long lastDisplay;
  unsigned long lastRate;
  int sampleCount;

  void setup()
  {
  int errcode;

  Serial.begin(SERIAL_PORT_SPEED);
  Wire.begin();
  imu = RTIMU::createIMU(&settings);                        // create the    imu object
  pressure = RTPressure::createPressure(&settings);         // create the  pressure sensor

  if (pressure == 0) {
  Serial.println("No pressure sensor has been configured - terminating");
    while (1) ;
   }

   Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu-   >IMUName());
   Serial.print(", pressure sensor "); Serial.println(pressure->pressureName());
   if ((errcode = imu->IMUInit()) < 0) {
   Serial.print("Failed to init IMU: "); Serial.println(errcode);
   }

   if ((errcode = pressure->pressureInit()) < 0) {
   Serial.print("Failed to init pressure sensor: ");
   Serial.println(errcode);
   }

   if (imu->getCalibrationValid())
   Serial.println("Using compass calibration");
   else
   Serial.println("No valid compass calibration data");

    lastDisplay = lastRate = millis();
    sampleCount = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
   // In-between gives the fusion mix.

   fusion.setSlerpPower(0.02);

   // use of sensors in the fusion algorithm can be controlled here
   // change any of these to false to disable that sensor

    fusion.setGyroEnable(true);
    fusion.setAccelEnable(true);
    fusion.setCompassEnable(true);
    }

     void loop()
     {
     unsigned long now = millis();
     unsigned long delta;
     float latestPressure;
     float latestTemperature;
     int loopCount = 1;

      while (imu->IMURead()) {                                // get the latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount >= 10)
         continue;

      fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
      sampleCount++;
      if ((delta = now - lastRate) >= 1000) {
      Serial.print("Sample rate: "); Serial.print(sampleCount);
      if (imu->IMUGyroBiasValid())
      Serial.println(", gyro bias valid");
      else
      Serial.println(", calculating gyro bias");

        sampleCount = 0;
        lastRate = now;
       }
       if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
        lastDisplay = now;
       //          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());
                  // gyro data
        //          RTMath::display("Accel:", (RTVector3&)imu->getAccel());
                     // accel data
       //          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
          // compass data
        RTMath::displayRollPitchYaw("Pose:",   (RTVector3&)fusion.getFusionPose()); // fused output

        if (pressure->pressureRead(latestPressure, latestTemperature)) {
            Serial.print(", pressure: "); Serial.print(latestPressure);
            Serial.print(", temperature: ");
        Serial.print(latestTemperature);
        }
        Serial.println();
        }
        }
        }

EDITED CODE:
       #include <Wire.h>
       #include "I2Cdev.h"
       #include "RTIMUSettings.h"
       #include "RTIMU.h"
       #include "RTFusionRTQF.h"
       #include "RTPressure.h"
       #include "CalLib.h"
       #include <EEPROM.h>

       RTIMU *imu;                                           // the IMU object
      RTPressure *pressure;                                 // the pressure object
      RTFusionRTQF fusion;                                  // the fusion object
      RTIMUSettings settings;                               // the settings object

      //  DISPLAY_INTERVAL sets the rate at which results are displayed

      #define DISPLAY_INTERVAL  300                         // interval between   pose displays

     //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

     #define  SERIAL_PORT_SPEED  115200

    unsigned long lastDisplay;
    unsigned long lastRate;
    int sampleCount;

    // ================= MPU: 1 =================

   RTIMU *imu1;                                           // the IMU object
   RTPressure *pressure1;                                 // the pressure object
   RTFusionRTQF fusion1;                                  // the fusion object
   RTIMUSettings settings1;                               // the settings object

   unsigned long lastDisplay1;
   unsigned long lastRate1;
   int sampleCount1;

   const int CS_MAX = 2;
   const int CS[CS_MAX] = { 7, 8 };

   void setup()
   {
  for (int i = 0; i < CS_MAX; i++) {
  pinMode(CS[i], OUTPUT);
  digitalWrite(CS[i], HIGH);
  }

  int errcode;

  Serial.begin(SERIAL_PORT_SPEED);
  Wire.begin();
   imu = RTIMU::createIMU(&settings);                        // create the imu object
  pressure = RTPressure::createPressure(&settings);         // create the pressure sensor

  if (pressure == 0) {
  Serial.println("No pressure sensor has been configured - terminating");
  while (1) ;
   }

   Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu->IMUName());
   Serial.print(", pressure sensor "); Serial.println(pressure->pressureName());

  for (int i = 0; i < CS_MAX; i++) {
  digitalWrite(CS[i], LOW);
  if ((errcode = imu->IMUInit()) < 0) {
  Serial.print("Failed to init IMU: "); Serial.println(errcode);
  }

  if ((errcode = pressure->pressureInit()) < 0) {
  Serial.print("Failed to init pressure sensor: "); Serial.println(errcode);
  }

  if (imu->getCalibrationValid())
    Serial.println("Using compass calibration");
  else
    Serial.println("No valid compass calibration data");

  lastDisplay = lastRate = millis();
  sampleCount = 0;

   // Slerp power controls the fusion and can be between 0 and 1
   // 0 means that only gyros are used, 1 means that only accels/compass are   used
  // In-between gives the fusion mix.

  fusion.setSlerpPower(0.02);

  // use of sensors in the fusion algorithm can be controlled here
  // change any of these to false to disable that sensor

   fusion.setGyroEnable(true);
   fusion.setAccelEnable(true);
   fusion.setCompassEnable(true);
   digitalWrite(CS[i], HIGH);
   }

   int errcode1;
   Serial.begin(SERIAL_PORT_SPEED);
   Wire.begin();
   imu1= RTIMU::createIMU(&settings1);                        // create the imu object
   pressure1 = RTPressure::createPressure(&settings1);         // create the pressure sensor

    if (pressure1 == 0) {
    Serial.println("No pressure sensor has been configured - terminating");
    while (1) ;
    }

    Serial.print("ArduinoIMU10 starting using IMU "); Serial.print(imu1->IMUName());
    Serial.print(", pressure sensor "); Serial.println(pressure1->pressureName());

    for (int i = 0; i < CS_MAX; i++) {
    digitalWrite(CS[i], LOW);

    if ((errcode1 = imu1->IMUInit()) < 0) {
    Serial.print("Failed to init IMU1: "); Serial.println(errcode1);
    }

    if ((errcode1 = pressure1->pressureInit()) < 0) {
     Serial.print("Failed to init pressure sensor1: ");
     Serial.println(errcode1);
     }

     if (imu1->getCalibrationValid())
    Serial.println("Using compass calibration");
    else
    Serial.println("No valid compass calibration data1");

    lastDisplay1 = lastRate1 = millis();
    sampleCount1 = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
    // In-between gives the fusion mix.

    fusion1.setSlerpPower(0.02);

   // use of sensors in the fusion algorithm can be controlled here
   // change any of these to false to disable that sensor

     fusion1.setGyroEnable(true);
     fusion1.setAccelEnable(true);
     fusion1.setCompassEnable(true);

     digitalWrite(CS[i], HIGH);
     }
     }

     void loop()
     {
     unsigned long now = millis();
     unsigned long delta;
     float latestPressure;
     float latestTemperature;
     int loopCount = 1;

      while (imu->IMURead()) {                                // get the   latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount >= 10)
        continue;

       fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
        sampleCount++;
        if ((delta = now - lastRate) >= 1000) {
        Serial.print("Sample rate: "); Serial.print(sampleCount);
        if (imu->IMUGyroBiasValid())
            Serial.println(", gyro bias valid");
        else
            Serial.println(", calculating gyro bias");

        sampleCount = 0;
        lastRate = now;
        }
        if ((now - lastDisplay) >= DISPLAY_INTERVAL) {
        lastDisplay = now;
        //          RTMath::display("Gyro:", (RTVector3&)imu->getGyro());

         // gyro data
         //          RTMath::display("Accel:", (RTVector3&)imu->getAccel());

         // accel data
        //          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
        // compass data
          RTMath::displayRollPitchYaw("Pose:",
          (RTVector3&)fusion.getFusionPose()); // fused output

         if (pressure->pressureRead(latestPressure, latestTemperature)) {
            Serial.print(", pressure: "); Serial.print(latestPressure);
            Serial.print(", temperature: ");
            Serial.print(latestTemperature);
        }
        Serial.println();
        }
        }

       unsigned long now1 = millis();
      unsigned long delta1;
      float latestPressure1;
      float latestTemperature1;
      int loopCount1 = 1;

      while (imu1->IMURead()) {                                // get the latest data if ready yet
      // this flushes remaining data in case we are falling behind
      if (++loopCount1 >= 10)
        continue;

      fusion1.newIMUData(imu1->getGyro(), imu1->getAccel(), imu1-  >getCompass(), imu1->getTimestamp());
      sampleCount1++;
      if ((delta1 = now1 - lastRate1) >= 1000) {
        Serial.print("Sample rate: "); Serial.print(sampleCount1);
        if (imu1->IMUGyroBiasValid())
            Serial.println(", gyro bias valid");
        else
            Serial.println(", calculating gyro bias");

        sampleCount1 = 0;
        lastRate1 = now1;
    }
    if ((now1 - lastDisplay1) >= DISPLAY_INTERVAL) {
        lastDisplay1 = now1;
      //          RTMath::display("Gyro1:", (RTVector3&)imu1->getGyro());
      // gyro data
      //          RTMath::display("Accel1:", (RTVector3&)imu1->getAccel());
      // accel data
      //          RTMath::display("Mag1:", (RTVector3&)imu1->getCompass());
        // compass data
        RTMath::displayRollPitchYaw("Pose1:", (RTVector3&)fusion1.getFusionPose()); // fused output

        if (pressure1->pressureRead(latestPressure1, latestTemperature1)) {
            Serial.print(", pressure: "); Serial.print(latestPressure1);
            Serial.print(", temperature: "); Serial.print(latestTemperature1);
        }
        Serial.println();
    }
}

}

Before editing the code to support an additional MPU9X50 you will need to figure out a way to address them on the I2C bus. Hopefully the MPU9X50 module you are using has a pin named AD0.
There are two basic solutions to multiple MPU9X50.
The first solution is to use the two different addresses. AD0 pin LOW on one and AD0 pin HIGH on the other. The sketch above would require two instances (imu), one for each module/address.
The second solution, which works for several modules, is to hold the AD0 pin LOW for the module that is addresses and all other HIGH. The setting must be handled by a digital pin. One for each module. They will be used as chip/module select. Below the example code assumes that the MPU I2C address is with the lowest bit LOW.
In the setup() initiate these pins to output mode and high. The example code uses pin 7 and 8.
const int CS_MAX = 2;
const int CS[CS_MAX] = { 7, 8 };

void setup()
{
   ...
   for (int i = 0; i < CS_MAX; i++) {
     pinMode(CS[i], OUTPUT);
     digitalWrite(CS[i], HIGH);
   }
   ...
}

Set the digital pin LOW for the module you want to address before calling an MPU library function and back to HIGH afterwards.
digitalWrite(CS[0], LOW);
imu->someMemberFunction();
digitalWrite(CS[0], HIGH);

If several functions are called in a block it can be convenient to run all of them per module. An example section from the setup:
for (int i = 0; i < CS_MAX; i++) {
  digitalWrite(CS[i], LOW);

  if ((errcode = imu->IMUInit()) < 0) {
    Serial.print("Failed to init IMU: ");
    Serial.println(errcode);
  }

  if (imu->getCalibrationValid())
    Serial.println("Using compass calibration");
  else
    Serial.println("No valid compass calibration data");

  digitalWrite(CS[i], HIGH);
}

Cheers!

Thank you so much ! :) I really appreciate you . Yes , my MPU has ADO. Please see the above edited code if that is what you mean . When I upload the code the value of MPU1 n MPU2 are almost same even if I just move one of the MPU . Please guide me . Thanks :)  By the way where should I place this code   "    digitalWrite(CS[0], LOW); imu->someMemberFunction(); digitalWrite(CS[0], HIGH);             "

How can I declare tha address in the exmaple code above? thank you

Check RTIMUSettings. It contains the I2C address.

I already edit that but still no luck . :( i put MPU9250 0x69  but still the same result , is that what you mean ?

It should be 0x68 if you are going to do chip select with a LOW assert. Also the AD0 pin should be tied low. The alternative solution is to tie AD0 low on one and high on the other. They are then addressed 0x68 and 0x69 and will need two instances of the settings (imu).

I know it's too much for you to do this can you please show me how to do it ? If it's okay to you . Because i don't really get your point, THANKS :))

I got what you mean , It's now working ! Thank you so much! :)


text:
What is the Proper Voltage to supply an enough Current to the Arduino
I'm just confused about the supply that I should use in driving my arduino. Is it okay to use a 3.7V with a 1000mAh to supply it?
I will be using a Lilypad Arduino.
Your replies would be a big help to me.
Cheers!

The Technical Specs say that 2.7-5.5V DC is ok so you should be good at 3.7V DC.
Remember though:  Power consumption = Current  x  Voltage
So check that your power supply has enough current available. The current amount used will depend on how many pins you are using. The maximum each digital pin may use is 40mA. 1A (1000mA) will be plenty but mAh (milliampere hours) sounds like a battery specification.
Also, a word from the wise is that some cheap power supplies can be bad (little spikes and dips). If you are having trouble with strange issues it can be a good idea to check the power is ok.

I/O pins do not consume 40mA. They have an absolute maximum limit on what they are able to supply of 40mA and a recommended sustained maximum of 25mA. The actual current drawn through the I/O pin is dependent on what is connected to that pin.

Majenko raises a good point about the max rating (40ma).


text:
DigitalWrite Cannot Power HC-06 Bluetooth
To save power consumption, I tried to connect the HC-06 bluetooth module to a digital pin of my Arduino Nano. (HC-06 +5V <=> pin 11, HC-06 gnd <=> gnd) In that way, I can toggle the bluetooth when I am not using it. However, when I tried to pinMode(11, OUTPUT) and digitalWrite(11, HIGH), the led on HC-06 does not turn on which means it is not powered. I have tried to connect the HC-06 +5V to the 5V output of arduino and the HC-06 can turn on sucessfully. I have also tried to use a multimeter and the digital pin outputs a voltage of 5V. As the digital pins of Arduino can give 40mA while the HC-06 draws 30mA - 40mA, it should have enough power. I have also tried to use other digital pins as well but still the HC-06 cannot be powered.
What have I done wrong?

Is it average or maximum current consumption? And also 40mA for output pin is listed in section "Absolute Maximum Ratings" and there is also mentioned: "Exposure to absolute maximum rating conditions for extended periods may affect device reliability."

A digital IO pin is only capable of powering an LED or an incredibly low powered device. It is not suitable for powering meaty RF modules.
Instead you need to control the power to your module using a P-channel MOSFET as a High-Side switch.
For instance, assuming a 5V module with built in 3.3V LDO:

simulate this circuit – Schematic created using CircuitLab
Note that /RFEN is active low - set the pin OUTPUT and LOW to turn the module on. M1 should have a threshold of no lower than -4V, better -2V or higher.
Also be sure to set RX and TX to be INPUT when you power down the module or back-powering through the TX/RX pins may occur.
R2/R3 is a simple logic level shifter for the 3.3V logic signal the RX pin expects.

The RX line at least often has a pullup, which should probably be disabled.  And the TX to the module is better driven low than left high.

it should have enough power.

Probably not. Debugging is about challenging all assumptions, especially implicit ones.
Put a high side switch there and it should be ok.


text:
How to emulate an RFID tag with the RC522
Is it possible to emulate an RFID tag with the RC522? (Spec sheet: nxp MFRC522.pdf)
I want the RC522 to act like a NTAG213 nxp.com/documents/data_sheet/NTAG213_215_216.pdf and to be read/write by other readers/writers.
Are there libraries for that purpose?

Hi and welcome to the Arduino.SE site. To better help people answer your query you need to enhance your question with more information. At present it is not clear what you wish to achieve. Can you provide a usage example and more detail about what exactly you want to do?

No. Looking at the datasheet, card emulation is not a feature provided by the RC522.
Another popular chip, the PN532, does seem to indicate support for that feature, however, looking at the most popular library for this chip from Adafruit, it does not implement this feature. Another library from Seeed, does seem to implement it, but it looks rather limited as to which cards can be emulated, and the library itself hasn't been updated in a while.


text:
Can an a Arduino make music or speech without a speaker?
I have an Arduino Leonardo that can turn a relay off and on and the click is audible on the relay -this is simply done by making one of the control wires HIGH in the program code to turn the relay on and make the same control wire LOW to turn the relay off. In this way it can turn a set of relays on and off. By varying the patterns of on and off timings to the relay it make distinct sounds-it reminded me of a piezoelectric speaker for some of the programmed values. At fast on or off puling this 6V relay makes a buzzing noise. I was wondering if the sound emitted from the relay could be used as a crude speaker- I'm not talking about a quality speaker- just good enough to recognise a melody or speech. So my question
I was thinking the problem maybe be simplified if a set of relays is used buzzing at a certain frequency-corresponding to tones heard in the human voice to make it sound like speech. Im no expert in acoustics.
My questions are
1) is  it theoretically possible to use the clicking noise from a set of relays only to act as a a crude speaker (so hear a crude known melody or a crude speech)?
2) Is there such a circuit (if so what is it exactly and the theory of how it works) that can be built with an arduino?-so it only used the noise from a relay to act as a crude speaker.
I personally think it possible it would be an interesting circuit to build as I have not seen a relay used like this before. I just think it sounds interesting that music or speech can possible be made by a circuit without using a speaker type component. Maybe there's another non-speaker component (i.e. a component that was not originally designed to make a sound) that can be used instead of a relay.
I'd love to know the answers.
Update
I started on this. And the relays do make different tones-thats as far as I got.
So music seems to be possible; something like a famous melody of a song. I havent got any ideas yet for a another component instead of a relay.

It sounds like you have a good idea of the basic circuit and theory of how it would work. If you have the components you should try it out!

You will break the relay, simple as that. They are not designed to be switched on and off rapidly.

I dont care if I break the relay I have lots of them-too many. Actually they can relaibly buzz to the same tone.  Im happy to break few realy too keep myself entertained and learn something new ttrying out my idea. I just want to know if I can use them to create an organised sound-even if it for a few seconds. Your answer to my question seems to be no as you seem to be saying -without proof - that the rapid switching will break them. I'd like to see a mathematical based proof of that.

The operate/release time for a typical relay is 10ms/4ms - that means it takes 14ms for the contacts to close and open again. 14ms equates to a maximum 'click' frequency of 71Hz. You will not achieve anything worthwhile with that.

Why the down vote? This is a good, well-written question

Sound happens because of a disturbance in the air (or other conducting medium). So the short answer is an unqualified "yes." To start making a recognizable "tune" or "voice" you would need to vary the frequency at which you create the disturbance. In the case of a relay, you'd be varying the rate at which you activate it. This would be very possible on the Arduino.
To get recognizable sounds out of a relay you'd need one that can respond in the range of a few hundred Hz (which would give notes around middle C (roughly 260 Hz) up to a few KHz. From what is posted in @CharlieHanson's comments and answers, it doesn't seem like common relays can do that.
A function that takes agreements of pitch and duration, something like:
 note(hz, ms)

would give you a fairly easy way to describe the music you wanted to play.
Just for fun, here are a few examples of "speakerless devices" making music:

Floppy disc drive music
Lotus F1 car plays Happy Birthday

The operate/release time for a typical relay is 10ms/4ms - that means it takes 14ms for the contacts to close and open again. 14ms equates to a maximum 'click' frequency of 71Hz.
Typical rates of cycles-before-failure are in the region of 100,000  minimum - but at a rate of 5 cycles per second. This will rapidly decrease as you increase the switching rate.
Furthermore, as alluded to in the above datasheet, must-operate and must-release voltages increase as the number of completed cycles moves into the tens-of-thousands. Thus, if you were to find a relay that switched fast enough you will eventually (and maybe only after a 100 seconds of non-continuous operation) run its operating voltage above a level that can be achieved.

Due to the maximum switching frequency of a relay you cannot use one, or many, to synthesise speech. Speech is an incredibly complex mixture of frequencies, the majority of which are well above those that can be produced by switching a relay on and off.

Music is a loose term. Simply switching the relay on and off once per second is technically a rythym, and therefore music. Different relay models will have different 'clicks' - the smaller the contacts the higher the click will be in pitch (logically speaking, that is). A collection of different relays could definitely create music, akin to percussion, but by their individual clicks and not by the rapid switching thereof.

Music: no, not with any meaning. Speech: absolutely no.

For sure the realy emits some organised sound that is why I asked the question if (yes  or no) music or speech was possible. I have not concluded anything definite yet.

How do you plan on synthesising speech if you can only operate the relay at around 70Hz? "Telephone quality speech" consists of frequencies between 34Hz and 3.4kHz.

I dont know how to synthesize speech or music obviously which is why I asked it in the question to ask if the reader knew how to do it (thus answering that it is possible). I was going to copy it from the ideas in the other answer (the floppy disk drive or Lotus car) if I can get further information on how they did it.

Even if it was possile it woudnlt be good as  telephone quality speech.

I  believe everthing I hgave written is logical and makes sense and written with good reason. If it turns out to be possiblre I'll post the answer here and a link to a video of it working.

The numbers in a datasheet are always conservative because they are intended to guarantee reliable operation. But the OP is not interested in reliable operation of the relay, only in hacking some notes out of it. From this perspective, it is definitely worth trying frequencies beyond the specifications. She can also transpose the tunes a couple of octaves down, they should still be recognizable.


text:
Multiple RGB LEDs
I'm quite new to these things and I need some help. I'm building a computer shelf with plexiglass and RGB LEDs (one per length) and I need some help to sketch up a data sheet of some sort for this.
I'm thinking of using an Arduino Uno, but will it be able to run 12+ LEDs?

A key piece of information is how many is "12+ leds"? Is it 13, 14, 100? Without that it is quite hard to give advice? What do you want to do that a cheap, off-the-shelf, RGB LED controller can't do?

Well basicly what I'm hoping for is to control two shelves with led which then means 12x2. As mentioned I'm very inexperienced with this so I though it would be the better solution to use a arduino. Do you have any other recommendations instead?

Just get some rgb-led-strips. Connect them to and Arduino using some mosfets.

If all you want is some lighting effects, then I'd suggest some LED strips with controller and remote control from one of the well-known e-stores. You can get a power-supply, remote control and RGB LEDs at a reasonable cost. For 24 LEDs, you'll need a separate power supply anyway; the Arduino isn't enough. If what you want to do is learn about Arduino, I'd recommend jwpat7's advice. Try to get some Ws2812b RGB LEDs on a strip, and a power supply, and experiment with Adafruit's NeoPixel library

@Green, imho, there are millions of projects/tutorials on this, which are often much more detailed.

If your RGB LEDs are WS2812-style, 5050-size units, it is no problem to control dozens of them using an Arduino Uno or several other models of Arduinos.  [For ATtiny systems, other libraries than Adafruit's NeoPixel may be needed; the NeoPixel library keeps several bytes of state data per pixel, which some other libs don't.]
WS2812-style LEDs typically are arranged in serial strings, driven by a single IO pin from an Arduino.
If you have more than half a dozen WS2812s in the string, power for them should come from an external power supply, rather than via an Arduino's built-in 5V regulator.
For more information, see related questions like Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns, and Arduino and WS2812 RGB LED Strip "freezing", and  fading colors on a ws2812 strip; also see Google search Arduino Stackexchange for WS2812.


text:
How to control 6 stepper motors with Arduino?
I would like to control 6 stepper motors (0.225A, 2 V) with Arduino. I was thinking to use motor drivers from Pololu website, for example DRV8834.
Is it possible?
Any suggestion for another type of motor driver?
We need to limit the current, but I also got the advice to use the PWM signal to control the stepper motor. Any advice for this?

Two questions: 1) Are you wanting unipolar or bipolar steppers? 2) What is the end result you actually want to achieve?

You can set the current using the potentiometer on the DRV8834 board. PWM doesn't make sense for stepper-motors. PWM only makes sense for regular DC motors. It seems more like you need to look into what motor you need for your application before deciding on the motor driver.

We already decided to use stepper motors. I have 6 bipolar steppers. I need just to move forward and backward 6 wires that are connected with the stepper motors by means of a simple mechanism. Do I have enough pin in Arduino for 6 motor drivers?

Your requirements are so close to typical 3d printer electronics that you could learn a lot from those designs, even if you end up having to create something of your own.

We can also be use easy driver for 6 stepper motor ... or if we want to many stepper motor control we can use there bit shift Resister 74HC595. for driver ULN20003 IC driver or l293d IC.

Yes it is possible, of course everything is possible!
These drivers need two IO lines at very minimum: DIR and STEP. Pulsing STEP makes one step movement forward or backwards (depending on DIR).
For 6 steppers you need therefore 12 outputs from Arduino. (Which Arduino please? pick one which has enough IO, or otherwise use an I2C output extender).
M0 and M1 controls microstepping mode - configure at your wish. CFG is high on this Pololu board, allowing the board to use as a stepper driver out of the box.
Steppers (if you want to get them working at full torque) require a constant-current drive. (Inexpensive solutions use a constant voltage drive, such as using an ULN2803 - however those can not get too much torque). Happily this driver can do this well, the potentiometer sets the maximum current.
Steppers need considerable current when starting movement to a next step. However, unlike DC motors, even a still position will consume current, which eventually makes the motor hot. Therefore you are supposed to limit the current when the motor is not moving. This is usually done from software (the driver does not known when it is time for a long period at stop).
The way for limiting motor current at stop can be either an analog limiter, or a PWM. This driver has no dedicated input for this purpose. You can do two things:

use smaller drive current (use the potentiometer) - this can work well if you're satisfied with the torque
use the sleep mode of the driver with a PWM from the Arduino side.

This latter solution needs you to:

connect all EN pins of all 6 drivers, and connect it to one Arduino pin which has PWM (i.e. analogWrite())
drive this to 0, then start movements
once movements are finished, use analogWrite() and set to say, 128 (usually half of the move current is a good guess for holding current)

This way when the motors are stopped, the holding current will be less, hence the motors don't get hot.

You could create your own custom shield with an Arduino mega and 6 Stepper sticks
http://www.amazon.com/Hobbypower-StepStick-4-layer-DRV8825-Stepper/dp/B00NCSK6T2/ref=sr_1_1?ie=UTF8&qid=1455740571&sr=8-1&keywords=DRV8825
Here is a link to the stepper sticks I was talking about. To make this work you would need to be able to solder the breadboard together and set up the arduino to accept pins from the breadboard. You would also need a 12v power supply to give the motors power

Why the DRV8825 over the DRV8834?


text:
How to do run time calibration for MPU9250?
Does anyone know how to do the run time calibration for MPU9250 ?

By that you mean finding the calibration matrix for each sensor? Like offsets, gains, hard iron corrections?

I used this script to calibrate the MPU6050, which is the same as the MPU9250 minus the digital compass. This guide explains how to calibrate the MPU9250's magnetometer.


text:
Use large variables without using much memory
I've wired up a dot matrix, and I display characters on the screen by using something like the example code below.
The Char_B variable is a global variable in a library used by the Arduino, and displayPixels() is called from inside the library.
bool Char_B[8][8] = {
{0,1,1,1,1,0,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,0,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,0,0,0}
};

displayPixels(1000, Char_B);

However, each time I declare a new character like the array above, I use a relatively massive amount of memory. Is there any way to reduce memory usage? Keep in mind I am willing to change the structure of the array if necessary, since I'll need well over 100 characters loaded onto the Arduino to write text.

As a first step, pack your bits.

I use a relatively massive amount of memory. - 64 bytes, perhaps? You don't need 64 bytes to store 8 lots of 8 bits. You would need 8 bytes.

The data structure will take 64 bytes as sizeof bool is 1 byte not a bit. The first option is to pack each line (or column) in a byte (or bytes). The prefix 0b is for binary constant value (in gcc).
uint8_t Char_B[8] = {
0b01111000,
...
0b01111000
};

The second option is to move the data structure to program memory.
const uint8_t Char_B[8] PROGMEM = { ... };

This will require reading each line with a special function.
for (int line = 0; line < sizeof(Char_B); line++) {
  uint8_t pixels = (uint8_t) pgm_read_byte(Char_B + line);
  ...
}

Use a single byte to store a row of data. As a bool still takes a single byte.
Optionally you could flip the axis, and store column data, instead of row data in the array. Since letters like i use fewer columns that letters like B. Even in your example you can see you have 3 columns with only 0s.
A final suggestion would be to use PROGMEM and use the pgm_read_byte_near function. That way the data will remain in the flash memory, and will not take any space in the program-memory.

PROGMEM is an excellent idea. That saves storing anything in RAM.


text:
Switching LED on and off using microcontroller
I am new to microcontrollers and just become confused trying to solve the following problem:
An ATmega32 chip is connected to four on/off switches (SW0-SW3) and 4 LEDs (LED0-LED3). SWi is connected to PAi.  LEDi is connected to PA(4+i).
How will I code in such a way that turning a switch on, turns the corresponding LED on? For example, turning SW1 on will turn LED1 on. I am confused in the part that after taking input what will I send to port A? Multiple switches can be switched on at the same time.
For clarification:
switch0 is connected to PA0
switch1 is connected to PA1
switch2 is connected to PA2
switch3 is connected to PA3

LED0 is connected to PA4
LED1 is connected to PA5
LED2 is connected to PA6
LED3 is connected to PA7

Do you know that the ATMega328 doesn't have a port A?

A common approach is, to read the input pin, check the read value and then write to the output pin.
As the events on the input pin are generally asynchronous to your code, you have to check it more than once, which means in fact you have to check it regularily.
So in your arduino sketch you could write:
loop()
{
  uint8_t pin1=digitalRead(PA0);
  if (pin1==HIGH)
  {
     digitalWrite(PA4, HIGH);
  }
  uint8_t pin2=digitalRead(PA1);
  if (pin2==HIGH)
  {
     digitalWrite(PA5, HIGH);
  }
  // and so on
}

I assume you have already done the prerequisites in your setup() routine.

digitalWrite(PA5, ...);?

What about and PA4? q-:

Only one thing at a time ...


text:
Upload Code on Arduino Mega using FTDI Cable
I would like to upload my code to the Arduino Mega 2560.

The USB is fried hence I have to use the FTDI
I've a FTDI cable, but it has only 4 wires, Vcc,GND,TX,RX

How do you upload, as the ATmega is not responding to anything?

FTDI cables usually have RTS which is used to bring Reset low. If you only have four pins, press the Reset button on the board the moment you start the upload.

Thanks, But this need a bit of luck

*shrug* - well get an FTDI cable with the extra wire then.

Such a simple answer Nick, but works like a charm. I was on the verge of chucking the damn thing out the window, thank you.


text:
Does Atmega-2560 support image processing capability?
As the title says can I perform image processing on Atmega-2560?
Basically I have to capture real time images and detect green or red color.
I have not thought of the frame rate but it is not that fast or slow.

How large images? What type of image processing operations? How fast; frame rate etc. In general - no.

@MikaelPatel I have updated the question.Thank you

Please give numbers. You may as well ask if a bus with an unspecified number of seats can carry an unspecified number of passengers an unspecified distance in an unspecified time. For example: 1024 x 768 pixels, in 24-bit RGB, at 30 FPS. Do you need to detect exact green? A range? What if green and red are mixed? Do you want to detect if there is a single pixel of red, or more than one?

No. Your question really is: Can an 8-bit processor, running at 16 MHz, with 8 KB of RAM, do image processing at an acceptable rate? Unless you are talking about 10 pixels by 10 pixels, at a frame rate of 1 frame per second, then I doubt it.
You may want to ask the "real" question. See The X-Y Problem. There are sensors around that detect colours. If you are making a maze-following robot that needs to stop if it gets near to a red wall, that is a much more achievable objective.


text:
How to select arduino 101 in ubuntu?
How to I select arduino 101? I  have ubuntu.

In that ancient version of the IDE? You don't.
You download and install the latest version of the IDE from the Arduino website, then use the Boards Manager to install the packages that include the Ardiuno 101.

This is ubuntu, most of the software is older... I don't know!

There hasn't been a new package submitted to the repos for decades. You download it manually from Arduino.cc

I had the same problem in Gentoo - also had to instal Arduino manually, but it is easy, so do not worry about it and just do it :)

The default serial port it shows up in for me is ttyACM0
You can set this as your default port, so when you open the IDE with sudo arduino
~ $ vim ~/.arduino/preferences.txt

change the value for serial.port
serial.port=ttyACM0


text:
Life span of arduino
We are students of Pragati Engineering College -AP. We are currently working on Automatic Street Light  project selected in Smart India Hackathon 2017 under ministry of steel. For this project  We are using Arduino nano to control street lights in industries. Now we are requiring some general following  information about arduino nano.
What is the life span of Arduino nano?
We need a micro-controller with on analog input pin to read analog voltage and four digital pins for output. The program that we are dumping include  serial communication with Java UI in PC. The program occupies 6750 bytes, 318 bytes for global variables and 1730 bytes for local variables. We would like to know which arduino board is best suitable for our project?

A few important  questions: will it be a genuine Arduino nano or a chinese clone? Do you write to EEPROM or not?

It might be better to design your own board with a bare "Arduino" chip on it. An ATMega328 or just a basic ATTiny85.

What is the life span of Arduino nano ?

Many years.
Flash memory can degrade with time and the program can become corrupted or lost - however:

Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

Wet electrolytic capacitors dry out over time. When resurrecting old hardware the first thing you do is replace all the electrolytic capacitors. Depending on how much you de-rate them they could last a few years, or tens of years, before they need replacing. If possible avoid them and use MLCC and tantalum instead since they never dry out.
The biggest problem of any kind of industrial installation is that of the environment. Corrosion from airborne contaminates (water, etc) will destroy the PCB (oxidise the copper of the tracks, etc) long before the components have worn out. Proper sealing, and even "potting" in extreme environments, is essential for longevity.
Another important thing to remember is to factor in a certain number of failures over the intended lifetime of the product. If you find you will be needing to replace portions of a unit on a semi-regular basis then make those portions easy to replace. For instance, it may be more cost effective to routinely replace a board after 5 years rather than have to replace the entire unit every 8 years because the board that has failed is impossible to replace (e.g., it's potted).
As others have mentioned you shouldn't be using an Arduino of any form in a product. Instead you will be designing (or paying someone to design) a dedicated PCB. During that design phase extra steps can be taken to make the board more rugged - such as wider tracks and thicker copper that will take longer to corrode; increased clearances that will take longer for corroded copper to bridge; components chosen to have a suitable MTBF, etc.
Many components have a "service life" or "lifetime" quoted. This is especially important for components such as electrolytic capacitors. For instance, the EEUFR1C471 from Panasonic (to pick one at random) is quoted as 6000 hours at 105°C. 105°C is the maximum temperature you can run it at, so the quoted service life is a minimum at worst case parameters. 6000 hours is, of course, just 250 days (about 8 months or so) - but of course that is worst case, and the minimum guaranteed time (they guarantee that it will run for at least 6000 hours at 105°C). Run it at a lower temperature and you get longer life out of it.

Atmel chips (the ones used in the Arduino) have been used in all sorts of industrial appilications way before Arduino came along. Same for other micro controllers like the still popular 8051.
What you want to focus on might be the enclosure, seal it against the outside.
Rather than using a (chunky) pre-manufactured Arduino board, you'll have to pick the right chip for your application and design a board around it. http://www.atmel.com/products/microcontrollers/avr/

What is the life span of Arduino nano ?

the answer is use dependent. Just like you don't know for sure what's the life span of a particular individual, it is hard to know the life span of a product in a particular application, as it depends on the environment, design, and operations of that application.

We would like to know which arduino board is best suitable for our project ?

hard to tell, and likely none. street lighting is exposed all sorts of elements, from high / low temperatures to moistures and lightening for example, and demands high reliability in all conditions, particularly in failure. Arduino wouldn't be great in that environment.
if you have to go down that path, develop the code in arduino and burn the hex into bare chips so you have the choice of the chip and other components going into your application.

What is the life span of Arduino nano ?

Electronics doesn't really "die". Treated well, it should last for years. I have a RFID security system that I made in 2011 (six years ago, as I write this) and it is still working perfectly.

We would like to know which arduino board is best suitable for our project ?

These sorts of questions are hard to answer. What is "best"? Price? Size? Weight? Ease of use?

Best is tot use high-grade components though and check if the environment is fit. Voltage spikes can kill electronics instantly. Moist or corrosion are also worth taking into account Things as a too high/low temperature can also affect the lifetime. Also microcontrollers don't really have a "fail safe" you may want to put the lights in a warming/error state (flashing orange) if odd behaviour is detected.


text:
Share I2C pins with other device when lacking GPIOs
We're Using ESP12E as our MCU and we have three functionality :

SIM800 connected to TX(GPIO1), RX(GPIO3)
Matrix Keypad connected to GPIOs: 14,13,2,10,0,4,5,16
GLCD connected to GPIOs: 15,12

And we also need to communicate with an RTC(DS3231) module via I2C bus!
So i'm wonder how we could do this?
Is it possible to share I2C pins with any other pins ?
And BTW for some reason we can't use IO expander such as PCF8574

Why can't you use a IO expander? It'll save you those 8 pins needed for the matrix keypad. Can you use any other external IC?

Yeah i know, that's a great IC but for now we've some restriction on PCB and some other issue on supply

GLCD (graphical LCD) connected via two wires? How is that possible, it usually requires far more wires? If this is already an I2C bus device, just put the RTC module on the exact same lines? I2C is a bus after all..

@MaximilianGerhardt  It's a ST7920 GLCD with 3 Wire software SPI using this nice lib:https://github.com/olikraus/u8g2 , also we're in serial mode so cs is chip enable and is connected to logic 1

Then if you used another display with same characteriscs (columns, lines, ..) but with a I2C interface, wouldn't your problems be solved? Then you have still 2 wires but with 2 devices on the I2C bus. Or throw in an I2C to SPI converter chip like NXP SC18IS602B.

We found 74C922 at long last! without any other choices.
A cheap, available, reliable and easy setup IC.
The simple schematic we use:

here is a good topic to start with

Since you already want to use I2C it makes sense to move other things onto that same I2C bus to save IO pins.  And even off-load processing.
For instance, you could move your keypad to a dedicated matrix keypad interface chip, such as the MAX7365 (probably overkill for a small keypad), or a general I2C GPIO IO expander, such as the MCP23017.


text:
Serialize JSON as response to HTTP request
I'd like my ESP8266 to provide some JSON endpoints. I want to use ArduinoJson for serialisation. While this works in general if I serialize into a String and return this String afterwards, I was wondering if there is really no way to do this without wasting so much memory. Shouldn't it be possible to do something like this? Any hints?
ESP8266WebServer server;
StaticJsonDocument<768> response;
response["night"] = _playback.isNight();
response["shuffle"] = _playback.isShuffle();
server.send_P(200, "application/json", NULL);
serializeJson(response, server.client());

(this gives the following error:)
no instance of overloaded function "serializeJson" matches the argument list -- argument types are: (ArduinoJson6141_0000010::StaticJsonDocument<768U>, WiFiServer::ClientType)

Did you look at the documentation of ArduinoJson? Did you try? Did it work? If not, what errors did you get?

Yes I did. Yes I tried. No it did not. I added the error message.

you can just build it as a string. imho, the big advantage of the json lib is parsing, not serializing.

Weird. WiFiServer::ClientType is defined as WiFiClient, which inherits from Client, which inherits from Stream, which inherits from Print, which you should be able to serialize to. Could you try to serialize to Serial, just to see if it works?

That’s what I thought! I serialized into a char[] and it works fine

serializeJson() accepts a Print&, i.e, a reference to a class that implements the Print interface.
WiFiClient does implement the Print interface, but serializeJson() cannot make a reference to it because ESP8266WebServer::client() returns a temporary. Indeed, C++ forbids references to temporary variables, only const reference to temporaries are allowed.
To fix this compilation error, you must extract a variable:
WiFiClient client = server.client();
serializeJson(doc, client);

The way I see it, ESP8266WebServer::client() should return a WiFiClient& instead of a WiFiClient, just as HTTPClient::getStream() does. I opened issue #7075 about that.
Anyway, even it this fixes the compilation, I'm not sure it will work as you intend because ESP8266WebServer may not allow writing directly to the WiFiClient.


text:
Issue with HC-SR505 sensor
I have been using a HC-SR501 PIR module with my Arduino Mega and it was tracking presence pretty well.
Because of cost constraints, I decided to go with HC-SR505 sensor - bought a bunch of them. The performance is very bad. It almost seems like it is giving random HIGH and LOW values. Out of the 20 odd sensors I bought, may be one or two are fairly ok - others are all behaving weird. Have someone experienced this kind of behavior with HC-SR505?
Are they highly sensitive to noise in the power supply - is there any workaround to mitigate the effect? Help?
Code:
const int buttonPin = 4;

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

   pinMode(buttonPin, INPUT);
 }
 void loop()
 {
    if (digitalRead(buttonPin) == HIGH)
    {

      Serial.println("Presence Detected");
    }
    else {

      Serial.println("No Presence Detected");
    }

 delay(2000);

 }

I had the same problem of the sensor giving random 1/0 values. I then looked at the circuit closer.
The PINs are badly marked which doesn't tell great detail, PIN-1 is marked with "+", however the word "OUT" is sitting between PINs 2 and 3.
If you connect + to the +5V, and then the middle PIN into the GND and then OUT into your Arduino (say PIN-10 of your Arduino), then you will notice ups and downs that does not correspond to any movements, (i.e. telling you "Bad Sensor")... however:

Part-1 of the solution:

Swapping PINs 2 and 3 of the sensor (i.e. + goes into +5V of Arduino, Ground is PIN-3 of the sensor, and Middle is what you should be reading (i.e. PIN-10 of Arduino)) then this should start to work, but we're not finished yet, you would still get bad results...

Part-2 of the solution:

If you are reading from PIN-10 of Arduino, then on your setup() function would usually be like this:
setup()
{
 pinMode(10, INPUT);
}

This is NOT enough for that sensor!... I know,... should be right?!...
Anyway, you MUST tell that PIN to be ZERO at the start, otherwise, it's hell brake loose... Therefore, please write the PIN with 0 and then it should all work fine after that:
setup()
{
    pinMode(10, INPUT);
    digitalWrite (10, LOW);
}

Following the above does resolve the issue, the sensor worked absolutely fine.
One annoying issue however which I am currently trying to work on is to reduce the sensor delay timer from 8 seconds into just 1-2 seconds, i.e. once someone is in-front of the sensor I don't want it to tell me that the person was there still when he left the area almost 7 seconds ago... I might post another article on how to do this later.
In the mean time, I hope this helps to resolve this problem
Regards
Heider

You asked if anyone else has experienced this behavior, and from the documentation I can find the answer must be yes.
The 505 holds the HIGH output for a certain amount of time.  None of the documentation I can find on it specifies the amount of time.  So it is very possible that you are operating right near that limit.  If their quality control is not perfect, some might work correctly and some might not.
In other words, I believe the problem is that you are not allowing for the built-in time delay in the SR505.
That is the main difference between the 501 and the 505.  On the 501 it is adjustable in both sensitivity and time delay.  With the 505 those values are preset.
As a workaround, you can try increasing your delay upwards from 2000ms until you find the right value that will work consistently with your batch of them.
The sensitivity cannot be adjusted, either, but this can be an advantage if you are trying to cover a smaller area than you would try with the 501.  They both have the same 90-100 degree width of view, but the 505 is made for shorter range like a doorway, as opposed to the 501 which can cover an entire room.

By shining with a bright light through the PCB, I came up with this reverse-engineered circuit diagram. From my understanding, the IC is some sort of special OP amp. I suppose one can change the timing by adjusting the 154 (150k) resistor and the sensitivity by adjusting the 335 (3.3Meg) and/or the 103 (10k) resistor.

According to this wiki: https://www.elecrow.com/wiki/index.php?title=HC-SR505_Mini_PIR_Motion_Sensor, there is an 8 second +/-30% delay.
The sensor is very sensitive to motion. Waving your hand in front of it "as fast as you can" (at close range) will trigger the sensor. While testing the two I had purchased, they had to be pointed away from me or there were "false alarms".


text:
How do I install a library in Arduino Yun cross compile environment?
A few days ago, I've asked this question.
Thanks to the replies I've received, I've set up a cross compile environment for Yun by following this guide.
I've created a virtual machine with virtualbox and installed Debian 8.0 on it. I installed all the software required to download and compile the OpenWRT-Attitude Adjustment version (which, I think, is the version used by Arduino Yun) on Debian.
So, I've downloaded the OpenWRT source code, downloaded its packages feed (with "git clone git://git.openwrt.org/12.09/packages.git"), downloaded and installed all available "feeds" (with: "./scripts/feeds update -a" "./scripts/feeds install -a") and then compiled it with: "make defconfig" "make prereq"
and "make menuconfig".
When I typed in "make menuconfig", a graphical interface prompted. In that interface I selected:
Target System: (Atheros AR7xx/AR9xx);
Base System: I selected libc, libcc and marked as package libpthread and librt.
I left any other option as default. Then I compiled all with "time make V=99" command.
After about 2 hours, the compiling finished and I set the environment variables as the above mentioned guide described.
Looks like now I can compile any C code with this cross-compiler. Anyway, my application includes the png.h header in order to use the libpng library, and every time I try to cross-compile it, a "png.h not found" error pops up during the process.
So I tried to cross-compile the libpng library but when I ran "./configure" with the options for cross-compiling, it failed saying that zlib wasn't installed. So I downloaded the zlib library source code but looks like I can't cross-compile it.
Eventually I compiled zlib and libpng normally on Debian and now, when I try to cross-compile my application, it still says that it can't find png.h...
So, how can I "integrate" the libpng library to the cross-compiling environment?
Sorry for this long question, but it is all I've done today.
As always, I thank you for any help you can give me.


text:
Problems with Ultrasonic Sensor
I want to check my understanding on how to use digitalWrite for 5V and Grd and why this code isn't working.
This is for the Makeblock sensor
Consider the image here which says to plugin a wire to 5V, Grd and a signal pin.
My code does the following
#define h  22
#define l  24
#define sig 26

void setup() {
   Serial.begin(9600);
   pinModde(h, OUTPUT);
   pindMode(l, OUPUT);
   pinMode(sig, OUPUT);

   digitalWrite(h, HIGH);
   digitalWrite(l, LOW);
}

void loop() {
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

When I run this code duration is always 0.  If I unplug 22 and 24 and use the board's 5V and Grd I get duration is 30001 no matter how far away an object is from the sensor.  Meaning it's not sensing anything, just returning this number.
Full disclosure that I'm using solder-less wires but I don't that would make this much of a difference?
So to summarize: why are 22 and 24 resulting in a 0 readout and not acting as 5V and Grd?  My only thought is maybe too much voltage and a resister is needed?
Secondly: why is the sensor not working even when using 5V and Grd pins?

You've set pinMode(sig,INPUT); and never changed this back to OUTPUT before triggering next measure:
void loop() {
   pinMode(sig, OUTPUT);    // ensure sig is configured as an output
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

And for example PING))) (which is basically the same module) has power consumption about 30mA-35mA in datasheet. Output pin might be strong enough to power it, but I'd recommend at least GND connect directly to arduino GND. And using transistor for powering it up would be even better


text:
Use PWm and zero_cross_detect interrupt
I use an Arduino Uno for controlling one DC motor speed with PWM and one dimmer for control heater.
The dimmer and PWM control worked standalone, but when I want them to work together, the dimmer doesn't work.
#include  <TimerOne.h>          /
#include <Wire.h>

 //////////////                    //pin 2 zero kesmesi icin
int isiticiPWM = 9;                //  Opto Triac isitici PWM icin
int fanPWM=11;                     //motor pwm pini

int hiz=0;

volatile int i=0;               // Variable to use as a counter volatile as it is in an interrupt
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero

char   data ;
int dim = 255;                    // Dimming level (0-128)  0 = on, 128 = 0ff
int inc=5;    // counting up or down, 1=up, -1=down
int freqStep = 75;    // This is the delay-per-brightness step in microseconds.

void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(isiticiPWM, LOW);       // turn off TRIAC (and AC)
}

// Turn on the TRIAC at the appropriate time
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(isiticiPWM, HIGH); // turn on light
      i=0;  // reset time step counter
      zero_cross = false; //reset zero cross detection
    }
    else {
      i++; // increment time step counter
    }
  }
}
///////////////
void setup() {

  pinMode(fanPWM,OUTPUT);
  pinMode(isiticiPWM, OUTPUT);

    attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to----------------------------------->  Pin 2 (interupt 0) for Zero Cross Detection <<------------------------------------------------
    Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
    Timer1.attachInterrupt(dim_check, freqStep);

}

void loop()
{
hiz=450;analogWrite(fanPWM,hiz);

for(int k=0;k<=255;k++)
{dim=k;
}

  }

hiz=450;analogWrite(fanPWM,hiz); -- PWM goes from 0 to 255. 450 is too high.

Your loop function doesn't make sense to me. You are ramping dim from 0 to 255 in full speed. I guess you want dim to be the currently set time to turn on the triac. Most likely dim will change so fast, that the Timer interrupt does not have time to actually apply the value. Somewhat a racing condition.

Zero crossing is used for AC to detect when the alternating current is as close to zero as possible so when a TRIAC/MOSFET doesn't generate a lot of transients!    https://en.wikipedia.org/wiki/Zero_cross_circuit


text:
Is if statement correct?
if(temperature < baselineTemp)else{
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
}else if(temperature >= baselineTemp+2 && temperature < baselineTemp+4){
  digitalWrite(2, HIGH)
  digitalWrite(3, LOW)
  digitalWrite(4, LOW)
}else if(temperature >= baselineTemp+4 && temperature < baselineTemp+6){
  digitalWrite(2, HIGH)
  digitalWrite(3, HIGH)
  digitalWrite(4, LOW)
}else if(temperature >= baselineTemp+6){
  digitalWrite(2, HIGH)
  digitalWrite(3, HIGH)
  digitalWrite(4, HIGH)

No, the first lines should be:
if(temperature < baselineTemp) {
  digitalWrite(2, LOW);

Thus the else should be removed; after the first if and later else or else if conditions, statements can be placed.
Next time align your code by selecting it and select ctrl-K.
Also, your code can be much more simplified.
Hence the following (reverse engineered) requirements:

pin 2 is HIGH when temperature >= baselineTemp + 2, else LOW
pin 3 is HIGH when temperature >= baselineTemp + 4, else LOW
pin 4 is HIGH when temperature >= baselineTemp + 4, else LOW

So your entire code can be written as:
digitalWrite(2, temperature >= baselineTemp + 2 ? HIGH : LOW);
digitalWrite(3, temperature >= baselineTemp + 4 ? HIGH : LOW);
digitalWrite(4, temperature >= baselineTemp + 6 ? HIGH : LOW);