text:
Multiple MPU9250 using Multiplexer
Anybody here have tried connecting multiple MPU9250 into multiplexer. Anyway, I've used the HD74LS151 as the substitute for the 74HC4051 multiplexer. I already tried running the program and just followed how it is connected as it is connected like in the picture. Please see the attached image in here.
Right after running the code I just only got zeros on the output. I hope someone could help me figure out what's going on with my program or  the connections of my pins.
And here is the code I used:
    #include <I2Cdev.h>
    #include <MPU6050.h>

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE    implementation
    // is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for InvenSense evaluation board)
    // AD0 high = 0x69
    MPU6050 mpu_0(0x68);
    MPU6050 mpu_1(0x68);
    MPU6050 mpu_2(0x68);
    MPU6050 mpu_3(0x68);
    //MPU6050 accelgyro(0x69); // <-- use for AD0 high

    int16_t ax_0, ay_0, az_0, ax_1, ay_1, az_1, ax_2, ay_2, az_2, ax_3, ay_3, az_3;
    int16_t gx_0, gy_0, gz_0, gx_1, gy_1, gz_1, gx_2, gy_2, gz_2, gx_3, gy_3, gz_3;

   // uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
  // list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
 // not so easy to parse, and slow(er) over UART.
 #define OUTPUT_READABLE_ACCELGYRO

 // uncomment "OUTPUT_BINARY_ACCELGYRO" to send all 6 axes of data as 16-bit
 // binary, one right after the other. This is very fast (as fast as possible
// without compression or data loss), and easy to parse, but impossible to read
// for a human.
//#define OUTPUT_BINARY_ACCELGYRO

 #define LED_PIN 13
 bool blinkState = false;

 //Mux control pins
 int s0 = 5;
 int s1 = 6;
 int s2 = 7;

 //Mux in "SIG" pin
 int SIG_pin = 0;

 const int MPU=0x68;

 void setup() {

  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);

  //    delay(5);
  //    Wire.begin();
  //    Wire.beginTransmission(MPU);
  //    Wire.write(0x6B);  // PWR_MGMT_1 register
  //    Wire.write(0);     // set to zero (wakes up the MPU-6050)
  //    Wire.endTransmission(true);
  //    delay(15);
 //
 //    digitalWrite(s0, HIGH);
 //    digitalWrite(s1, LOW);
 //    digitalWrite(s2, LOW);
//    delay(5);
//
//    Wire.begin();
//    Wire.beginTransmission(MPU);
//    Wire.write(0x6B);  // PWR_MGMT_1 register
//    Wire.write(0);     // set to zero (wakes up the MPU-6050)
//    Wire.endTransmission(true);
//    delay(15);

// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    Wire.begin();
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif

// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(38400);

// ================= MPU: 0 =================
digitalWrite(s0, LOW);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
delay(5);
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(15);
mpu_0.initialize();
Serial.println("Testing device connections #0 ...");
Serial.println(mpu_0.testConnection() ? "MPU6050 connection #0 successful" :      "MPU6050 connection #0 failed");
delay(5);

// ================= MPU: 1 =================
digitalWrite(s0, HIGH);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
delay(5);
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(15);
mpu_1.initialize();
Serial.println("Testing device connections #1 ...");
Serial.println(mpu_1.testConnection() ? "MPU6050 connection #1 successful" :  "MPU6050 connection #1 failed");
delay(5);

// ================= MPU: 2 =================
digitalWrite(s0, LOW);
digitalWrite(s1, HIGH);
digitalWrite(s2, LOW);
delay(5);
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(15);
mpu_2.initialize();
Serial.println("Testing device connections #2 ...");
Serial.println(mpu_2.testConnection() ? "MPU6050 connection #2 successful" : "MPU6050 connection #2 failed");
delay(5);

// ================= MPU: 3 =================
digitalWrite(s0, HIGH);
digitalWrite(s1, HIGH);
digitalWrite(s2, LOW);
delay(5);
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
delay(15);
mpu_3.initialize();
Serial.println("Testing device connections #3 ...");
Serial.println(mpu_3.testConnection() ? "MPU6050 connection #3 successful" : "MPU6050 connection #3 failed");
delay(5);

// use the code below to change accel/gyro offset values
/*
Serial.println("Updating internal sensor offsets...");
// -76  -2359   1688    0   0   0
Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
Serial.print("\n");
accelgyro.setXGyroOffset(220);
accelgyro.setYGyroOffset(76);
accelgyro.setZGyroOffset(-85);
Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
Serial.print("\n");
*/

// configure Arduino LED for
pinMode(LED_PIN, OUTPUT);
}

void loop() {
// read raw accel/gyro measurements from device
//    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// these methods (and a few others) are also available
//accelgyro.getAcceleration(&ax, &ay, &az);
//accelgyro.getRotation(&gx, &gy, &gz);

// ================= MPU: 0 =================
digitalWrite(s0, LOW);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
delay(5);
mpu_0.getMotion6(&ax_0, &ay_0, &az_0, &gx_0, &gy_0, &gz_0);
#ifdef OUTPUT_READABLE_ACCELGYRO
    Serial.print("#0\ta/g:\t");
    Serial.print(ax_0); Serial.print("\t");
    Serial.print(ay_0); Serial.print("\t");
    Serial.print(az_0); Serial.print("\t");
    Serial.print(gx_0); Serial.print("\t");
    Serial.print(gy_0); Serial.print("\t");
    Serial.println(gz_0);
  #endif
  delay(5);

// ================= MPU: 1 =================
digitalWrite(s0, HIGH);
digitalWrite(s1, LOW);
digitalWrite(s2, LOW);
delay(5);
mpu_1.getMotion6(&ax_1, &ay_1, &az_1, &gx_1, &gy_1, &gz_1);
#ifdef OUTPUT_READABLE_ACCELGYRO
    Serial.print("#1\ta/g:\t");
    Serial.print(ax_1); Serial.print("\t");
    Serial.print(ay_1); Serial.print("\t");
    Serial.print(az_1); Serial.print("\t");
    Serial.print(gx_1); Serial.print("\t");
    Serial.print(gy_1); Serial.print("\t");
    Serial.println(gz_1);
#endif
delay(5);

// ================= MPU: 2 =================
digitalWrite(s0, LOW);
digitalWrite(s1, HIGH);
digitalWrite(s2, LOW);
delay(5);
mpu_2.getMotion6(&ax_2, &ay_2, &az_2, &gx_2, &gy_2, &gz_2);
#ifdef OUTPUT_READABLE_ACCELGYRO
    Serial.print("#2\ta/g:\t");
    Serial.print(ax_2); Serial.print("\t");
    Serial.print(ay_2); Serial.print("\t");
    Serial.print(az_2); Serial.print("\t");
    Serial.print(gx_2); Serial.print("\t");
    Serial.print(gy_2); Serial.print("\t");
    Serial.println(gz_2);
   #endif
   delay(5);

   // ================= MPU: 3 =================
   digitalWrite(s0, HIGH);
   digitalWrite(s1, HIGH);
   digitalWrite(s2, LOW);
   delay(5);
   mpu_3.getMotion6(&ax_3, &ay_3, &az_3, &gx_3, &gy_3, &gz_3);
   #ifdef OUTPUT_READABLE_ACCELGYRO
    Serial.print("#3\ta/g:\t");
    Serial.print(ax_3); Serial.print("\t");
    Serial.print(ay_3); Serial.print("\t");
    Serial.print(az_3); Serial.print("\t");
    Serial.print(gx_3); Serial.print("\t");
    Serial.print(gy_3); Serial.print("\t");
    Serial.println(gz_3);
    #endif
    delay(5);

   //    #ifdef OUTPUT_BINARY_ACCELGYRO
     //        Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax &    0xFF));
     //        Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
     //        Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
      //        Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
      //        Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
     //        Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
     //    #endif

    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
   }

Cheers!

What attached image? What code?

What sort of Arduino is it?

@NickGammon I posted the codes and the photo above. Thanks :)   It's arduino mega..

This seems remarkably similar to your other question

Yes, @NickGammon but this time I tried connecting it to a multiplexer.

Try grounding INH (pin 6) and VEE (pin 7). Also try running an I2C scanner before doing something more elaborate like this. Make sure it detects all four chips. You probably need to plug one in at a time, since they all have the same address.

Btw, the image I posted above is not exactly what I used. Instead of using the 74HC4051, I used HD74LS151 where pin6=output    pin7=strobe

I2C SDA is both in- and output, bi-directional. Does that really work with an 74LS151?

74HC4051 has just the same pins to 74LS151 except the strobe, and 74HC4051 has one output while the 74LS151 has two outputs. @MikaelPatel

They are not replaceable when the multiplexed signal is bi-directional. Does your MPU9250 module have an AD0 pin?

@MikaelPatel Yes, it is bi-directional but the VEE has no supply. My MPU9250 has AD0 pin.

Please add a link to the data sheet for HD74LS151. There is another solution to this problem. Connect the AD0 to digital pins and use I2C addressing. See http://arduino.stackexchange.com/questions/19935/how-to-use-multiple-mpu9250-to-arduino-lilypad

This is the link for the HD74LS151 http://www.techmake.com/media/datasheets/HD74LS151.pdf .

@MikaelPatel and here is for the other one http://www.nxp.com/documents/data_sheet/74HC_HCT4051.pdf

Btw, the image I posted above is not exactly what I used. - I'm not too good at debugging issues of code or schematics that are different to what is posted. Perhaps if you post exactly what you are doing?

@Thomas Thanks for the links. Now it is easier to say - they are not the same! I guess it would be possible to only multiplex the clock signal with 74LSL151 and have a common data signal.

Your concept sounded sensible enough so I gave it a try-out.

First point is: The master always generates the clock so we don't need to multiplex that. We only need to multiplex the data (SDA).
Code snippet:
// the multiplexer address select lines (A/B/C)
const byte addressA = 6; // low-order bit
const byte addressB = 5;
const byte addressC = 4; // high-order bit

int selectTarget (const byte which)
  {
  // select correct MUX channel
  digitalWrite (addressA, (which & 1) ? HIGH : LOW);  // low-order bit
  digitalWrite (addressB, (which & 2) ? HIGH : LOW);
  digitalWrite (addressC, (which & 4) ? HIGH : LOW);  // high-order bit
  }  // end of readSensor

All you have to do is call selectTarget(n) where n is 0 to 7, and you redirect SDA to the desired chip. I suggest a 4.7k pull-up on the target side so that the line is pulled high when not selected.
I tested it out and it seems to work OK.

The beauty of this setup is that you can multiplex 8 devices (eg. sensors) which happen to have the same I2C address, with only one additional chip. And, you can get 16-channel multiplexers if you want to take this further. Of course, in the code you still have to select the correct I2C address for the chip.

Oh great, @NickGammon ! :D You've given me hope to continue this project. But, can I ask you the whole code you used? I tried reediting the code I used with the one you added, and I'm still confused on where should I put the selectTarget you are telling me to do. Thanks.

I think it is important to emphasize that 74LS151 cannot replace the HC4051 in the circuit above. The HC4051 is acting as a switch and the I2C slave device can drive the signal. If using a 74LS151 the clock signal can be multiplexed instead. The data signal is then common. The third alternative is to use a digital pin to control the MPU9X50 AD0 pin.

My code was just testing talking to a couple of other Arduinos using the code on my I2C page - with modifications. I don't know about the 74LS151. Your original schematic in the question has 74HCT4051 on it.


text:
How to use Multiple MPU9250 to Arduino Lilypad
Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad? How will I set the addresses, and where should I put the pins for SDA and SCL? I hope someone out there could help me on this project.
Cheers!
What if I have this working codes, how will I edit this to connect more than two MPU9250? Please guide me. Thanks.
 #include <Wire.h>
 #include <TimerOne.h>

 #define    MPU9250_ADDRESS            0x68

 #define    MAG_ADDRESS                0x0C

 #define    GYRO_FULL_SCALE_250_DPS    0x00
 #define    GYRO_FULL_SCALE_500_DPS    0x08
 #define    GYRO_FULL_SCALE_1000_DPS   0x10
 #define    GYRO_FULL_SCALE_2000_DPS   0x18

 #define    ACC_FULL_SCALE_2_G        0x00
 #define    ACC_FULL_SCALE_4_G        0x08
 #define    ACC_FULL_SCALE_8_G        0x10
 #define    ACC_FULL_SCALE_16_G       0x18

 // This function read Nbytes bytes from I2C device at address Address.
// Put read bytes starting at register Register in the Data array.
void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t*      Data)
{
// Set register address
Wire.beginTransmission(Address);
Wire.write(Register);
Wire.endTransmission();

// Read Nbytes
Wire.requestFrom(Address, Nbytes);
uint8_t index=0;
while (Wire.available())
Data[index++]=Wire.read();
}

// Write a byte (Data) in device (Address) at register (Register)
void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)
{
// Set register address
Wire.beginTransmission(Address);
Wire.write(Register);
Wire.write(Data);
Wire.endTransmission();
}

// Initial time
long int ti;
volatile bool intFlag=false;

// Initializations
void setup()
{
// Arduino initializations
Wire.begin();
Serial.begin(115200);

// Set accelerometers low pass filter at 5Hz
I2CwriteByte(MPU9250_ADDRESS,29,0x06);
// Set gyroscope low pass filter at 5Hz
I2CwriteByte(MPU9250_ADDRESS,26,0x06);

// Configure gyroscope range
I2CwriteByte(MPU9250_ADDRESS,27,GYRO_FULL_SCALE_1000_DPS);
// Configure accelerometers range
 I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_4_G);
 // Set by pass mode for the magnetometers
 I2CwriteByte(MPU9250_ADDRESS,0x37,0x02);

 // Request continuous magnetometer measurements in 16 bits
 I2CwriteByte(MAG_ADDRESS,0x0A,0x16);

 pinMode(13, OUTPUT);
 Timer1.initialize(10000);         // initialize timer1, and set a 1/2   second period
 Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt

 // Store initial time
 ti=millis();
 }

 // Counter
 long int cpt=0;

 void callback()
  {
  intFlag=true;
  digitalWrite(13, digitalRead(13) ^ 1);
  }

  // Main loop, read and display data
  void loop()
  {
  while (!intFlag);
  intFlag=false;

  // Display time
  Serial.print (millis()-ti,DEC);
  Serial.print ("\t");

   // _______________
  // ::: Counter :::

   // Display data counter
  //  Serial.print (cpt++,DEC);
 //  Serial.print ("\t");

  // ____________________________________
  // :::  accelerometer and gyroscope :::

 // Read accelerometer and gyroscope
 uint8_t Buf[14];
 I2Cread(MPU9250_ADDRESS,0x3B,14,Buf);

 // Create 16 bits values from 8 bits data

// Accelerometer
int16_t ax=-(Buf[0]<<8 | Buf[1]);
int16_t ay=-(Buf[2]<<8 | Buf[3]);
int16_t az=Buf[4]<<8 | Buf[5];

// Gyroscope
int16_t gx=-(Buf[8]<<8 | Buf[9]);
int16_t gy=-(Buf[10]<<8 | Buf[11]);
int16_t gz=Buf[12]<<8 | Buf[13];

 // Display values

// Accelerometer
Serial.print (ax,DEC);
Serial.print ("\t");
Serial.print (ay,DEC);
Serial.print ("\t");
Serial.print (az,DEC);
Serial.print ("\t");

// Gyroscope
Serial.print (gx,DEC);
Serial.print ("\t");
Serial.print (gy,DEC);
Serial.print ("\t");
Serial.print (gz,DEC);
Serial.print ("\t");

// _____________________
// :::  Magnetometer :::

// Read register Status 1 and wait for the DRDY: Data Ready

uint8_t ST1;
do
{
 I2Cread(MAG_ADDRESS,0x02,1,&ST1);
}
while (!(ST1&0x01));

// Read magnetometer data
uint8_t Mag[7];
I2Cread(MAG_ADDRESS,0x03,7,Mag);

// Create 16 bits values from 8 bits data

// Magnetometer
int16_t mx=-(Mag[3]<<8 | Mag[2]);
int16_t my=-(Mag[1]<<8 | Mag[0]);
int16_t mz=-(Mag[5]<<8 | Mag[4]);

// Magnetometer
Serial.print (mx+200,DEC);
Serial.print ("\t");
Serial.print (my-70,DEC);
Serial.print ("\t");
Serial.print (mz-700,DEC);
Serial.print ("\t");

// End of line
Serial.println("");
//  delay(100);
 }

Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad?

Yes, that is possible with both SPI and I2C. With SPI you will need MOSI(11), MISO(12), SCK(13), and CSn where CSn is CS0..CS4 are digital pins in output mode for chip select.
With I2C the following pins are needed SDA(A4), SCL(A5), and CSn. The chip select pin is connected to AD0 on the device. AD0 is used for the lowest bit in the I2C address. Addressing is achieved by connecting AD0 to CSn and keeping all high except the one that is addressed. The I2C address is the same for all access. The CSn pin defines which device will response.
The example code below uses the lower address and chip select is put low for the selected device.
// Chip select pin device#0
const int CS0 = 4;
...
void setup()
{
  ...
  // Initiate chip select pin for device#0
  pinMode(CS0, OUTPUT);
  digitalWrite(CS0, HIGH);
  ...
}
...
void loop()
{
   ...
   // Select device#0
   digitalWrite(CS0, LOW);
   MPU9250_someFunction();
   digitalWrite(CS0, HIGH);
   ...
}

How will I set the addresses, and where should I put the pins for SDA and SCL?

SDA is connected to A4 and SCL to A5.
Using the above given example code (from the question) a rewrite of the I2Cread function could be:
// This function read Nbytes bytes from MPU9250 device with chip select pin.
// Put read bytes starting at register Register in the Data array.

void MPU9250_read(uint8_t CS, uint8_t Register, uint8_t Nbytes, uint8_t* Data)
{
  digitalWrite(CS, LOW);

  // Set register address
  Wire.beginTransmission(MPU9250_ADDRESS);
  Wire.write(Register);
  Wire.endTransmission();

  // Read Nbytes
  Wire.requestFrom(Address, Nbytes);
  uint8_t index = 0;
  while (Wire.available()) Data[index++] = Wire.read();

  digitalWrite(CS, HIGH);
}
...
// Read magnetometer data from device#3
uint8_t Mag[7];
MPU9250_read(CS3, 0x03, 7, Mag);

Cheers!

Please see above @MikaelPatel I posted the code that I am using from the internet.

What was the question? Do you want to know how to change that? It is really bad. There must be better drivers to change. And if we do that we should make that shared. A possible fork on github on a good driver?

I have added a rewrite of I2Cread to give you a hint how to do this.

where should I put the pins for SDA and SCL?

Same as on a Uno:

SDA is on pin A4
SCL is on pin A5

Can you suggest me some links that can help me learn more about SPI?

I have an SPI page and also one about I2C.
There is also a page about SPI on this site: How do you use SPI on an Arduino?
If you want to use 5 devices, it sounds like Majenko's recommendation is good: Use SPI. You would share MOSI/MISO/SCK between all devices (D11/D12/D13), and give each one a separate SS (slave select) line.

Thank you for responding to my concern. Can I ask you if you have the existing codes already on it? @NickGammon

No I don't, sorry. There are dozens of Arduino models these days, and hundreds, if not thousands, of things you can connect to them. I don't happen to have a Lilypad and 5 x MPU9250 devices. However the links I provided should help you to get started in writing your own.

Please see above @NickGammon I posted the code that I am using from the internet.

According to the datasheet the MPU-9250 can work in either I2C or SPI mode.
When it is in SPI mode you can connect up as many MPU-9250s as you have spare IO pins.  With SPI the clock and data lines are all shared, and each slave device has its own Slave Select line.
In I2C mode it is possible to only use 2 devices at once - the AD0 pin configures which is which device (connect it to GND or VCC to identify the two devices).
Interestingly the MPU-9250 does include an I2C master module for connecting other sensors to it. Theoretically it should be possible to connect the master port of an MPU-9250 to two other MPU-9250s, and each of those could connect to a further two MPU-9250s each, and so on and so forth in a huge tree.  However the programming of such an environment would be an absolute nightmare and not something I would like to undertake.
So in summary: use SPI mode, it's simpler.

Thank you for giving me that idea. It helped me enlighten my mind about this project. @Majenko Can you suggest me some links that can help me learn more about SPI, or some working codes which can be a stepping stone to start making the said project work? Cheers!

https://www.arduino.cc/en/Reference/SPI http://playground.arduino.cc/Code/Spi

Please see above @Majenko posted the code that I am using from the internet.

If you use I2C, you can use an I2C multiplex chip to handle the arbitration to handle lots of MPU-9250s.  I had a setup with 6x of them going.  I did find however, that the amount of CPU time that it takes for I2C communication is high, so once you get in to that many 9250s, you don't have much CPU time left over for other things.  Using SPI is a bit trickier to get going, but it is wicked fast and also lets you take advantage of the FIFO buffer on the 9250s.
Majenko mentioned using the I2C master functionality on the 9250 to daisy chain - I had also tried that approach before I tried the I2C multiplexer.  I have to say it was a horrible experience.  When you use that I2C master function, you are actually programming the advanced functionality of the 9250 instead of using the Arduino coding in C.  Once it all starts working (if it does), it acts quite flaky.  That functionality on the chip was really designed to enable using an external magnetometer on the 6250 to get 9dof.  Any more complex use than that gets hairy with the interchip timing, and initializing on startup is also rough.
Final answer - put in the time to learn how to use the SPI bus as mentioned in some of the other answers.  Once you get through the learning curve, it can run at up to 20khz communication speed.  SPI is designed for high speed communication.  I2C is designed to be easier to use but for things with lower update rates.

source: Stack Exchange

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

sort: votes


text:
Consequences of messing with Timer 0
I'm following this tutorial to generate square waves using the timers of the attiny85, but I'm afraid this could mess with something else in the chip.
This is the relevant snippet:
// Set up Timer/Counter0 for 20kHz interrupt to output samples.
TCCR0A = 3<<WGM00;             // Fast PWM
TCCR0B = 1<<WGM02 | 2<<CS00;   // 1/8 prescale
TIMSK = 1<<OCIE0A;             // Enable compare match, disable overflow
OCR0A = 49;                    // Divide by 400

I understand that this might affect delay(), but as I'm using watchdog timer to send the attiny to sleep, I think this in this case it should not affect this specific function.
Are there another negative consequences of modifying this timer?

so, what is your question? ... the easiest thing would be to write a program that tests timer0 affect on sleep()

Timer 0 is usually used for millis() and delay().

I don't see how this could affect sleep. It does affect millis and delay, if you are using a "core" that implement that for the ATTiny85. I think most of them use the overflow interrupt (e.g ATTinyCore does). Your code disables that, so as long as you never call delay() or millis() there shouldn't be a problem.

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


text:
Find remote ip address TCP
Found this "Remote IP of TCP Socket" at:
https://e2e.ti.com/support/wireless_connectivity/simplelink_wifi_cc3000/f/851/t/380635
I am trying to log the remote ip address of a client.  Using Ethernet, I have accomplished remote ip address logging.  Trying to do the same with the Adafruit CC3000 library.
Answer provided; does not respond every time with the correct "client.IP". When it is wrong; client.IP is always "client.IP: 0.0.0.0.0" which occurs more frequently than the correct "client.IP" of my computer.  Why is does this happen?  Is there a solution?   Answer is on the right track; need additional help, so client.IP is correct every time.
Edit:  File modified is Adafruit_CC3000_Server.cpp  Only change was to the clientIndex value.  Will this cause an impact on client connecting?  File is contained in "Arduino Stack Exchange.zip" linked in this post and is located in the Adafruit_CC3000 folder of the zip.  Changes are commented.
Modified files with client ip  returned.  https://drive.google.com/open?id=0Byo8QWKyqAT9TUt4d0FteENQS2s CC3000.zip
William

As a guess one of three things may be happening: you are trying to get an address without a valid connection, the address was never saved, or it was saved but overwritten before you try to obtain it.  You may need to figure out how to instrument or debug the code to determine which.

I found that if I set clientIndex = 2; every time I get correct client ip address.  Are there any adverse effects to setting clientIndex  equal to 2?  What happens to other clientIndex values?

Where exactly did you make this change?

This function is not built-in so you'll have to modify the library slightly. This is one way to do it, I think:

Navigate to the class Adafruit_CC3000_ClientRef in the file Adafruit_CC3000_Server.h. In the class definition, just before the private methods and attributes are defined, you will add a new public attribute as follows:
uint8_t ip_addr[4];  // assuming a typical IPv4 address

It will hold the IP address of each ClientRef instance as the connection is accepted.
Go to Adafruit_CC3000_Server::acceptNewConnections() near the end of Adafruit_CC3000_Server.cpp. A few lines will be added to get the IP address from the CC3000 and store it temporarily in the appropriate struct:
static sockaddr tSocketClientAddr;  // file scope
static socklen_t addr_len;

// Accept new connections and update the connected clients.
bool Adafruit_CC3000_Server::acceptNewConnections() {
  bool newClientCreated = false;
  // For any unconnected client, see if new connections are pending and accept
  // them as a new client.
  for (int i = 0; i < MAX_SERVER_CLIENTS; ++i) {
    if (!_clients[i].connected()) {
      // Note: Because the non-blocking option was set for the listening
      // socket this call will not block and instead return SOC_IN_PROGRESS (-2)
      // if there are no pending client connections. Also, the address of the
      // connected client is not needed, so those parameters are set to NULL.
      cc3k_int_poll();
      addr_len = sizeof(tSocketClientAddr);
      int soc = accept(_listenSocket, &tSocketClientAddr, &addr_len);
      if (soc > -1) {
        _clients[i] = Adafruit_CC3000_Client(soc);
        newClientCreated = true;
      }
      // else either there were no sockets to accept or an error occured.
    }
  }
  return newClientCreated;
}

You'll also edit the getClientRef() method in Adafruit_CC3000_Server.cpp:
Adafruit_CC3000_ClientRef Adafruit_CC3000_Server::getClientRef(int8_t clientIndex) {
  if (clientIndex != -1) {
    Adafruit_CC3000_ClientRef newClient =  Adafruit_CC3000_ClientRef(&_clients[clientIndex]);
    // at least 2 (family) + 2 (port) + 4 (ip_addr) bytes expected
    // also check if address is standard ipv4
    if ((addr_len >= 8) && (tSocketClientAddr.sa_family == AF_INET)){
       // copy address into array; in network byte order
       memcpy(newClient.ip_addr, &(tSocketClientAddr.sa_data[2]), 4);
    }
    return newClient;
  }

  // Couldn't find a client ready to read, so return a client that is not
  // connected to signal no clients are available for reading (convention
  // used by the Ethernet library).
  return Adafruit_CC3000_ClientRef(NULL);
}

Save all the files.
Now the address is stored in an array for each client and can be accessed from your sketch. For example, you can access the address in your sketch like this:
In the loop() of the the HttpServer example:
 Adafruit_CC3000_ClientRef client = httpServer.available();
 if (client) {
   Serial.println(F("Client connected."));
   for (int i = 0; i < 3; i++){
     Serial.print(client.ip_addr[i]);
     Serial.print('.');
   }
   Serial.println(client.ip_addr[3]);
   // other code
 }

Completely untested. Good luck.

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

@NickGammon by moving the followup you have basically broken this question and answer - it doesn't work, but the history to understand it isn't here either, which breaks the whole everything should be right here, not in external references spirit of stack exchange.

@ChrisStratton - what are you talking about? What followup? You mean the comments?

Yes the comments, which are the way people are supposed to respond to answers that almost but not completely work.  How else would this question be resolved - start over from scratch with no benefit from the effort already expended?  Just give up and close it?

The "effort already expended" is safely archived in chat, @ChrisStratton. See the link Nick posted above. If you care to refer to it when editing this answer or posting your own, you'll find it readily accessible.

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


text:
Setting a pointer to NULL in Arduino library - error: ‘NULL’ was not declared in this scope
I am writing my own library for using with my Arduino. In my code, if I set a pointer I have declared to NULL, such as
int *ptr=NULL;

I get the error
error: ‘NULL’ was not declared in this scope

I need to initialize it to NULL as I am using pointers to implement a list.
If I use NULL directly in the program in the IDE, I do not get this error. This seems to be happening only when it is a part of the library code.
How do I correct this? Is there any alternative keyword to use? Or do I have to include some library?
Thank you.

Works fine for me. No need to include anything. It is, actually, part of stddef.h, but that gets included by default anyway, and is used by many other headers, like stdio.h.

@Majenko Thank you. I checked, it works when I use directly. I forgot to mention that this error appears when I use NULL in a definition of a header file which I have written. I hadn't realized that it works otherwise. Edited by question.

I am writing my own library for using with my Arduino.

You should really include Arduino.h, i.e.
#include <Arduino.h>

Not only will that define NULL for you, but you also get the other standard Arduino functions like digitalRead, pin number declarations, and various useful macros.

Thank you. Is there any reason to prefer it over including individual libraries?

Including Arduino.h gives you all the stuff you should need (including the standard libraries). If you ever need something like a port or pin address, or any of the Arduino functions (like analogRead) you are going to have to include Arduino.h anyway.

You should make sure your header includes the stddef.h header, which holds all these standard definitions (hence its name):
#include <stddef.h>


text:
Dereferencing char into a struct
I am sending some data over an NRF24 link, using the RF24Network  library. So far I have only sent numbers, now I also want to send a string, so I have set up my payload struct as
struct payload_t {                  // Structure of our payload
   unsigned long data;
   unsigned long datatype;
   char sensorid[20];
   unsigned long counter;
};

As far as I do understand, I can not use string here, since I need to know the length of the data I am sending.
At the moment I am using sensors without an internal ID, so in loop(), I am calling:
 writeToNetwork(voltage,'v',"nosid",packets_sent++);

My writeToNetwork function is defined as
 bool writeToNetwork(unsigned long data,unsigned long type,char sid[20],unsigned long package){

and within that, I am setting up the payload with
 payload_t payload = { data,type,sid, package };

Which gives me an
 error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]

Clearly, I have no interest of the address the pointer is referencing, so I need to somehow dereference the sid - pointer to get my array into the struct. How can I do that?
Or am I barking up the wrong tree? I tried to transfer the id as a string:
#include <string.h>
bool writeToNetwork(unsigned long data,unsigned long type,String sid,unsigned long package){
char sidchar[20];
sid.toCharArray(sidchar,20);
payload_t payload = { data,type,sidchar, package };

Which gives me the error
array must be initialized with a brace-enclosed initializer

Which I do not understand. Doing
char sidchar[20]={0};

gives me the same error.

Just to clarify - I can not use string here - do you mean a "string" or a "String" object? I only ask, because you are using a "string" with char sensorid[20];... Also, have I linked to the correct RF24Network library?

Thanks, wrong library, but I've corrected it. Where you quoted, I did mean "string".

Best check the payload size. That is 32-bytes which is max for NRF24L01 but the libraries you want to use will needs some of the payload for addressing etc.

In your situation, your best bet is probably to use the standard C function strcpy:
payload_t payload;
char* source = "abcdef";
strcpy(payload.sensorid, source);

Note that source string does not have to be declared as char source[20] and can be declared as the rather standard C string char*.
Also, since you are limiting the size of the string to be passed in payload, you may prefer to use strncpy which will ensure no more than 20 characters get copied:
payload_t payload;
char* source = "abcdef";
strncpy(payload.sensorid, source, 20);
// Explicitly add a string termination to the end of string
payload.sensorid[19] = 0;

In the snippet above, please notice the last line, it is necessary in the situation where source string length is 20 or more non-null characters, as in this case, strncpy will copy all 20 characters but will not add the terminating 0 at the end of the string.

I deleted my comment as I was wrong with the missing \0.


text:
Send multiple sensor values over serial
I want to send a JSON string over serial from arduiono device to my computer. The JSON string contains a sensor value array. To fill this array I use String.concat("value") function. But If I have more than 100 values I get the JSON string with an empty array and an error message:
{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[],"landscape": PUF}
VMDPE_1|3147_VMDPE

Is there any other way to send more than 100 values in one message? The arduino device is running with a battery and the communication is wireless. So I want to save energy and reduce the send interval.
EDIT:
After reading the answers I updated my sketch:
Serial.print("{\"deviceID\":\"ZB_ROUTER_1\",");
    Serial.print("\"sensorID\":\"MMA8451\",");
    Serial.print("\"sensorType\":\"accelerator\",");

    Serial.print("\"aX\":[");
    for (int i = 0; i < samples; i++)
    {
        if(i != 0)
        {
            Serial.print(",");
        }

        Serial.print(xArray[i]);
    }
    Serial.print("],");

    Serial.print("\"aY\":[");
    for (int i = 0; i < samples; i++)
    {
        if(i != 0)
        {
            Serial.print(",");
        }

        Serial.print(yArray[i]);
    }
    Serial.print("],");

    Serial.print("\"aZ\":[");
    for (int i = 0; i < samples; i++)
    {
        if(i != 0)
        {
            Serial.print(",");
        }

        Serial.print(zArray[i]);
    }
    Serial.print("],");

    Serial.print("\"landscape\":\"");
    Serial.print(orientation);
    Serial.println("\"}");

In the xArray, yArray and zArray, there are 50 double values stored. One double value needs 4B. So that shouldn't be too much. But there are problems when I receive the JSON string on my computer:
{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-1.17,-1.31,-1.26,-1.25,-1.16,-1.09,-1.40,-0.91,-0.94,-0.97,-1.39,-1.06,-0.91,-0.75,-0.78,-0.83,-0.72,-0.62,-0.74,-0.53,-0.82,-0.86,-0.84,-0.79,-0.79,-0.76,-0.83,-0.82,-0.97,-1.07,-0.92,-0.87,-0.97,-1.20,-1.51,-1.53,-1.82,-0.99,-1.04,-0.41,-0.54,-0.27,-0.24,-0.08,-0.02,-0.63,-0.{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[0.16,-0.04,-0.18,-0.03,0.01,-0.17,-0.10,-0.30,-0.31,-0.21,-0.16,-0.16,-0.15,-0.19,-0.17,-0.17,-0.17,-0.18,-0.16,-0.17,-0.17,-0.20,-0.18,-0.16,-0.17,-0.16,-0.15,-0.13,-0.20,-0.19,0.37,-0.88,-0.20,-0.05,-0.12,-0.21,-0.20,-0.17,-0.17,-0.17,-0.17,-0.17,-0.19,-0.17,-0.19,-0.16,-0.18,-0.17,-0.18,-0.17],"aY":[9.80,8.63,8.37,9.05,9.19,8.83,9.01,9.69,8.42,7.94,7.72,7.83,8.43,8.82,9.24,9.21,8.79,8.60,8.39,8.44,8.61,8.77,8.87,8.76,8.66,8.59,8.54,8.73,8.879,8.73,8.66,8.60,8.61,8.68,8.71,8.76,8.71,8.66,8.60,8.63,8.69,8.71],"aZ":[-4.81,-4..28,-4.02,-4.02,-4.29,-4.49,-4.67,-4.63,-4.46,-4.32,-4.28,-4.38,-4.42,-4.52,-4.58,-4-4.52,-4.52,-4.42,-4.39,-4.34,-4.40,-4.47,-4.51,-4.47,-4.44,-4.38],"landscape":" PDB{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.18,-0.17,-0.19,-0.20,-0.18,-0.17,-0.18,-0.19,-0.19,-0.20,-0.17,-0.18,-0.17,-0.18,-0.16,-0.18,-0.18,-0.18,-0.17,-0.16,-0.19,-0.18,-0.17,-0.17,-0.16,-0.18,-0.17,-0.18,-0.18,-0.18,-0.16,-0.19,-0.17,-0.16,-0.17,-0.18,-0.17,-0.17,-0.17,-0.16,-0.17,-0.19,-0.18,-0.18,-0.17,-0.18,-0.17,-0.18,-0.17,-0.18],"aY":[8.67,8.68,8.69,8.68,8.68,8.68,8.66,8.68,8.69,8.69,8.69,8.67,8.69,8.70,8.68,8.67,8.68,8.69,8.69,8.68,8.67,8.69,8.69,8.70,8.68,8.66,8.67,8.67,66,8.76,8.80,8.98,8.99,8.76,8.46,8.37,8.55,8.71,8.80,8.85,8.74,8.59,8.58,8.64,8.70,8.44,-4.43,-4.43,-4.44,-4.42,-4.43,-4.43,-4.43,-4.42,-4.44,-4.43,-4.44,-4.43,-4.41,-44.13,-4.20,-4.44,-4.58,-4.68,-4.60,-4.41,-4.31,-4.29,-4.40,-4.50,-4.52,-4.48,-4.41,-{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.18,-0.19,-0.22,-0.15,-0.15,-0.19,-0.23,-0.13,-0.16,-0.21,-0.20,-0.17,-0.15,-0.10,-0.16,-0.18,-0.24,-0.17,-0.12,-0.20,-0.28,-0.20,-0.13,-0.19,-0.21,-0.17,-0.18,-0.20,-0.19,-0.17,-0.17,-0.17,-0.17,-0.15,-0.18,-0.16,-0.18,-0.19,-0.18,-0.16,-0.17,-0.18,-0.19,-0.17,-0.19,-0.18,-0.17,-0.16,-0.17,-0.17],"aY":[8.67,8.55,8.61,8.73,8.82,8.73,8.66,8.54,8.54,8.60,8.67,8.60,8.77,8.88,8.79,8.57,8.60,8.51,8.79,8.72,8.83,8.72,8.66,8.68,8.79,8.76,8.67,8.58,75,8.78,8.63,8.63,8.70,8.79,8.77,8.72,8.71,8.67,8.67,8.66,8.70,8.70,8.70,8.69,8.66,87,-4.47,-4.45,-4.32,-4.36,-4.31,-4.41,-4.30,-4.37,-4.46,-4.42,-4.20,-4.39,-4.49,-4.4.40,-4.35,-4.36,-4.39,-4.41,-4.43,-4.40,-4.41,-4.39,-4.40,-4.40,-4.41,-4.42,-4.44,-4{"deviceID":"ZB_ROUTER_1","sensorID":"MMA8451","sensorType":"accelerator","aX":[-0.19,-0.18,-0.18,-0.17,-0.17,-0.18,-0.18,-0.17,-0.19,-0.18,-0.18,-0.17,-0.17,-0.17,-0.18,-0.18,-0.18,-0.18,-0.20,-0.18,-0.16,-0.17,-0.17,-0.18,-0.18,-0.17,-0.18,-0.19,-0.17,-0.19,-0.19,-0.19,-0.17,-0.18,-0.16,-0.18,-0.18,-0.18,-0.19,-0.20,-0.18,-0.17,-0.17,-0.17,-0.18,-0.22,-0.18,-0.17,-0.17,-0.17],"aY":[8.69,8.68,8.69,8.68,8.69,8.68,8.69,8.70,8.69,8.69,8.70,8.68,8.69,8.69,8.70,8.70,8.69,8.67,8.66,8.62,8.73,8.80,8.79,8.75,8.68,8.57,8.60,8.66,8,8.67,8.66,8.69,8.62,8.67,8.76,8.75,8.71,8.71,8.70,8.66,8.67,8.66],"aZ":[-4.43,-4.4-4.41,-4.40,-4.41,-4.42,-4.43,-4.44,-4.47,-4.36,-4.30,-4.30,-4.39,-4.45,-4.51,-4.52,,-4.49,-4.42,-4.35,-4.32,-4.37,-4.38,-4.41,-4.42,-4.46,-4.43],"landscape":" PDB"}

Sometimes there is "aZ" missing, sometimes I get wired array values like 8.83.2 (values with two "."). Do I have to many Serial.print operations? The sending interval is 500ms.

How long is the String you intend to send, and how does it compare to the RAM size of the arduino device?

@DaveX I don't know the exact length. The string looks like the posted one. But I want to fill as many sensor values as possible in the "aX" "array". What is the common way to transmit such values?

I have had a very similar problem and the Arduino core team has accepted a change from me to facilitate this functionality.
It is a complex story so you may have to reread a couple of times.
1) Serial.print returns before the data is send over serial.
The first thing to realize is that when you do serial.print() the data is not actually send over serial.
When your code looks like
serial.print("I'm dead");
resetArduino(); //This method does not exists in the arduino core

The message "I'm dead" will not be send over serial. That is because Serial print does not wait until the data has been delivered.
2) There is a software buffer used for serial.
The second thing to realize is that when you do serial.print() the data is not actually send but is put into a software buffer. A interrupted routine sends the data from the buffer over the "transport layer" (like in the osi model) here the serial connection.
This buffer uses the same memory that your string is using. In other words you are storing the string 2 times. This is why I agree with majenko when he states

Don't use String. Don't use concat(). Just print each bit as a separate Serial.print() function call.

3) If the software buffer is full serial.print will wait
If you do serial.print and the software buffer is full the function will not return until all data is in the buffer.
In other words: If a sketch tries to send more data than is transmittable over the serial connection the behaviour of the sketch will change over time.
4) Serial is slow
115200 baut may seem lightning fast but it is slow compared to what your arduino can do.
In other words: if you send lots of data you will need to calculate wether the serial connection can handle that amount of data.
So how can you improve on the situation.

As majenko implied: Only use the buffer of serial.
Reduce the amount of data you send. Jason is not a good way to send lots of similar data over a serial line because you have to add the variable name each time. I have split my variable names from the data to do reduce the amount of data to send.
If you send bursts of data bigger than the software buffer; increase the buffer. This is the change Arduino core team accepted from me.you can set the define SERIAL_TX_BUFFER_SIZE for changing the send buffer size and SERIAL_RX_BUFFER_SIZE for changing the receive buffer size. The default is 64 which means 64 characters.
Only send changed data.
Preprocess your data so you can send less data

Thanks for sharing improvement suggestions. My target is to analyze the frequencies of the signals (FFT). I wanted to do that on my computer. I choose the JSON format, because I have a wireless sensor network (WSN). So I get sensor values from more than one sensor device. Thats why I need at least one sensor ID. The software buffer uses the RAM right?

Yes the sensor buffer uses RAM. just like String and char[].

Is there any other way to send more than 100 values in one message?

Yes. Don't use String. Don't use concat(). Just print each bit as a separate Serial.print() function call.

Maybe avoid doing the dynamic string manipulations?
Serial.print("{\"deviceID\":\"ZB_ROUTER_1\",\"sensorID\":\"MMA8451\",\"sensorType\":\"accelerator\",\"aX\":[");
for(i=0; i <10000; i++){
   if (! i==0) Serial.print(',');
   Serial.print(i);
}
Serial.print("],\"landscape\": PUF} VMDPE_1|3147_VMDPE");


text:
How can I read delay of a note that I am playing
I am playing note tone with CapacitiveSensor and an output of tone
like this
void loop() {
    time_before = millis();

    long total1 =  cs_2_3.capacitiveSensor(30);
    long total2 =  cs_2_4.capacitiveSensor(30);

    if((total1>200)||(total2>200)) {

        if(total1>200) {

            tone(12,261);
            time_after = millis();
            Serial.print("Time: ");
            Serial.println(time_after-time_before);
        }
        if(total2>200) {
             tone(12,294);
             time_after = millis();
             Serial.print("Time: ");
             Serial.println(time_after-time_before);
        }
    }
}

How can I read how many seconds I play this note par example

You are not calling noTone() anywhere, and you are calling tone() with two args, so the duration is indefinite. Perhaps you should add more conditional statements to detect when the "press" is released, and stop the tone there, as well as calculate the note length.

@uint128_t - Your comment is the correct answer to this OP's question. You should post it as an answer. As it stands only the code execution time is measured, and not the tone duration, and it is the latter which is the OP's real goal.

@Greenonline Your answer looks pretty good, so I will upvote that :)

Your code currently will only measure the code execution time and not the duration of the note(s) being played.
You need to follow uint128_t's suggestion and rewrite the code to detect the "button release", at which point you measure the time with millis(), and call noTone(). Only then will you be able to measure the note's duration.
I believe that the source of confusion is that you seem to think that tone() acts like delay() and waits for the note to finish - it does not. tone() merely starts the note and then the next instruction is executed, without waiting for the note to end.
So, using millis() straight after calling tone() will actually only measure the time it takes to execute the tone() statement (and a few if statements - depending on whether you use your original code, or Maximus's code).


text:
How to upload one program into several Arduinos at once?
I am trying to upload a single program to a number of Arduinos one by one. But it is time consuming. So I would like to know if there is any way to upload the code at once to multiple Arduinos.
I have tried as follows:
3 Arduino with all the Rx, Reset, Vcc, Gnd line connected to each other. Only pin left is Tx line. So I just connect the Tx line of one arduino and program it and so on.
Is there any other way?

Are you programming them for the first time or doing a update?
If is the first programming, I cant see another way.
Otherwise, If is a update and your Arduino have a Wifi module you could try something like an update on the air, where you put your new firmware in a server for example and all devices updates yourself automatically or by a command.
Google for Arduino OTA (on the air) you will get a lot of source code and examples of doing that.

Thank You for valuable time.
This is not about OTA.Its for first-time code uploading.

Arduino uses a microcontroller from Atmel and uses a programming tool that is designed for development use and not for production programming.
What you are looking for are tools that are called "production programming tools". Atmel has a nice documentation which describes their different programming solutions: link.


text:
"'Serial' does not name a type" error
I'm getting a "'Serial' does not name a type" error when this program is compiled. I need for the 8 channels of voltage to be displayed. I'm sure it's a simple fix, however I'm still learning Arduino programming. I thank you for your help.
int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};
//float Mux1_State[i] =0;
int RawValue=0;
float Voltage = 0;
void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  //Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
}

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}
Serial.print("Raw  Value = " );
Serial.print(RawValue);

Things like pin_Out_S0 need to be declared, otherwise they will generate error messages.

Your last two lines are not in any function. This confuses the compiler. You need to move those two statements inside a function.
Because those statements refer to RawValue, I'm guessing you want to put them in loop(), where RawValue is being updated.
Also, remember that the IDE will tell you on which line the error is, which is helpful when debugging compilation errors.

In addition to the good answers by Mikael and Uint, everything needs to be inside {curly braces} otherwise the IDE does not know where it belongs. If you didn't want the last 2 lines in your loop segment you could put them in a separate void xxxx () section to be called when the time is right (by using an ISR with an enableinterrupt function for example).

Please put these lines inside the loop() function block:
Serial.print("Raw  Value = " );
Serial.print(RawValue);

Should look something like:
void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  //Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
  Serial.print("Raw  Value = " );
  Serial.print(RawValue);
}

That should at least remove the first issue with your code.
Cheers!

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


text:
If - else statement in Arduino
I'm starting to learn how to use Arduino and I tried to make this code, which is just a simple if else statement; what I want to make is when the input is LOW, LED 1 is HIGH and LEDs 2,3 are LOW, and when the input is HIGH, the LEDs 2,3 are HIGH and LED 1 is LOW. I wrote this code but when I put the switch in LOW, instead having just like what I intended, all the outputs are HIGH.
I try changing the output and I checked all the wiring to the LEDs so my mistake is in the code.
Could you guys tell me what's wrong with the code?
int switchstate = 0;
void setup() {
  pinMode (13,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(3,INPUT);
}

void loop() {
  switchstate = digitalRead(3);
  if (switchstate == LOW) {
    digitalWrite(11,HIGH);
    digitalWrite(12,LOW);
    digitalWrite(13,LOW);
  } else {
    digitalWrite(11,LOW);
    digitalWrite(12,HIGH);
    digitalWrite(13,HIGH);
  }
}

Can you post a schematic of your circuit.

do you check voltages ?
When input is HIGH, does it give right answer ?

What type of switch, a push button or a slide switch?

You say your circuit is correct, yet by looking at your code,  the leds should never be lit at the same time.. You do not debounce the input in software, but it should not matter as if the input flickered, it should change the state of all the leds. Review the circuit again.

Pull-up/-down in place?

Your problem is definitely not in the code.

First of all, whoever change this to this forum is amazing. Thanks. I will upload the schematic as soon as I got home.

Your code doesn't seem to be the problem. Contrary to what you are saying I think your problem is most definitely in your hardware setup.
Most likely, your digitalRead doesn't register a HIGH input, so it doesn't get 5V. Instead of digitalRead, go for analogRead(A0). So change your circuit and attach it to pin A0.
Use serial.println(switchstate) to print the results to the serial monitor and then decide what your top value (HIGH) and bottom value (LOW) for detection will be. Perhaps include a pull down resistor as well on the A0 pin.

Thanks, I will try that as soon as I got home. One more thing thou, how the output generate all high even I put the wrong wiring. is the arduino have NC thing when there is no logic in it will just outputing high ?

I don't know what you are using to create this HIGH input. Switchstate also is an integer so it could be possible your thing that is supposed to create a HIGH output, isn't creating a HIGH output and as such Switchstate is filled as an integer, not a boolean (booleans have two states: true or false, or HIGH or LOW). Experiment.

To debug this, as Len has suggested I would recommend putting in some Serial.println("Debug info") commands into your code. This will confirm that you are programming the Arduino as you expect, and that the Arduino is running.
To do this simply include a Serial.begin(9600) command in your setup block, and then a Serial.println("Some text") wherever you want to check if you are reaching a certain part of the code. You can then read these messages via the serial monitor (which you can get to from Tools->Serial Monitor in the Arduino IDE).
For hardware debugging if you have a multi-meter available I would check that you are getting 0V/5V on digital pin 3 when you expect (i.e. when you are / are not pressing the button). Also, to check your LEDs are working, and connected to the output pins you think they are, write a script which just scrolls through them with a short delay (See the Blink example under File->Examples->01.Basics->Blink for an example of how to do that).


text:
Need some explain before desigin my own custom Arduino Due board
I'd like to ask you some questions about ARM processor from Atmel like the SAM3X8E, the one used in the Arduino Due. I have found this [AVR programming guide] from abcminiuser on avrfreaks very helpful.
Q1. Why are there no ICSP pins in Arduino Due to use it to program the SAM3X8E from an external programmer instead of the USB port in the Due board?
Q2. If I want to program an Arduino Due from an external programmer which of the programmers in abcminiuser guide will do the job and give me the ability to program 8/16/32bit AVR and ARM chips from Atmel at the same time?
Q3. On the Arduino Due website I read this:

"Uploading sketches to the SAM3X is different than the AVR Microcontrollers found in other Arduino boards because the flash memory needs to be erased before being re-programmed. Upload to the chip is managed by ROM on the SAM3X, which is run only when the chip's flash memory is empty. "

What is that mean?

What is an Arduino Duo? I believe you mean "Arduino Due"

Did you look at Chap. 18. Enhanced Embedded Flash Controller (EEFC) in the datasheet. http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf. If you are constructing a board I would recommend starting there.

Because it is not needed. The chip comes with the bootloader pre programmed in  ROM, not in Flash. It cannot be replaced, upgraded, removed, etc like other more sensible chips. So there is no real need for ICSP since the main use for that is putting the bootloader on.
Unknown.
Unlike the AVR chips, whose bootloader always runs first for about 2 seconds, the SAM3X's boot loader only runs if the flash is empty. As a result there is a way to empty the flash built in to the Arduino code, so that it can be erased by software. That means that the software has to be working right though, which isn't always the case, since people write bad code which crashes the chip. As a result they added a erase button to the board so you can manually erase the chip and get the bootloader to run.

I have always maintained that the SAM3X is a really idiotically designed chip and I wouldn't ever use it in a design of my own.

Thank for this info, but any other alternative chip to SAM3X8E, It 3.3v and 512K.B of RAM , and have many IO pins , There is no 3.3v with 512K.B RAM chip in AVR family, by the way I make some search and find that Atmel have two programmer Atmel-ICE and JTAGICE3 the last is less expensive and about half price the one and support AVR like Atmega2560 and ARM like SAM3X8E, So can I use it to programming SAM3X8E if I design custom SAM3X8E board and remove both USB port from Arduino Due design, Also what pins should I connect this programmer to the chip to programming It?

Maybe you should look furthrt afield? Btw, it has 512k flash, not ram. It only has 96k ram. I use PIC32 chips mostly.

There are many makes of microcontroller that are better than the sam chips. Many manufacturers make them, so shop around. Define your requirements then fit the chip to those requirements, don't fit your requirements to the chip just because some toon at Arduino is a fan of it.

Maybe you should look Dear Majenko thank for your advise, the reason that make me choice AVR because it's very simple and can be programmed by C,also if there is library for and sensor work with Arduino I could make this library work with AVR with little change in it's code that's why i decide to upgrade from AVR to ARM from Atmel.

All microcontrollers of this ilk can be programmed in C or C++. Many have an Arduino compatible API as well, such as Teensy, chipKIT, Energia, etc. so programming is almost identical.


text:
Low power wifi temperature sensor
I want to make a wifi-enabled temperature sensor and place it inside my HVAC system to measure and push the temperature to a central server, every minute or so.
I have a LoLin NodeMcu v3 unit laying around, and I am wondering if it is possible to use this one - and have it last for many years inside the HVAC system?
I realize the LoLin unit has a onboard wifi chip, I also realize LoLin takes 3v input. Aside from that, I am pretty blank.
Yesterday I tested the LoLin board by programming it with the following code, which lists networks in the vicinity. It worked great:
#include "ESP8266WiFi.h"

void setup() {
  Serial.begin(9600);
  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(2000);
  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  int n = WiFi.scanNetworks();// WiFi.scanNetworks will return the number of networks found
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

The actual question
Is the LoLin board a feasible board for making a low power wifi enabled temperature sensor? Or should I rather make board that communicates with a wall-connected parent unit via radio?

What part of that is your actual question?

Execllent question @majenko. Thanks for pointing that out ;-)

How are you thinking of powering it?

I was thinking a battery. Any battery.

Yes, the NodeMCU can connect to a temperature sensor and forward that on to your WiFi access point to send to the internet.
Yes, the NideMCU can run from batteries.
Can it do it off one battery for many years? Only if that battery contains a small nuclear reactor.
Running something from battery for many years requires incredibly close attention to detail and incredibly tight component specifications, even down to the precise battery chemistry used. It's a very very difficult task for which people are very highly paid.
When you start looking at periods like that you begin to run up against the problem of battery self-discharge. Getting your power consumption down to an absolute minimum is a must, but even then if you have near zero power consumption the battery is still going to go flat by itself. So you have to invest time and effort into selecting a battery technology with a very low self-discharge.
All that is pretty moot though with the NodeMCU since:

WiFi is a power hungry technology. You can expect hundreds of mA while transmitting, and doing that once a minute for, say, 10 seconds (reconnecting to the WiFi takes time) will give you quite a high average power consumption just from the WiFi
The NodeMCU is far from optimised WRT power consumption. Linear voltage regulators, poor choice of components for low power consumption, etc, abound.

So yes you can run it from batteries, but be prepared to replace the batteries very often. By "very often" I mean every couple of days.
That means you basically have two options:

Don't use the NodeMCU but instead use something designed to be incredibly low power and run for long periods on battery (typically it won't use WiFi but something more efficient like nRF24L01+)
Don't use batteries. Hard-wire your NodeMCU into a mains-connected power supply.

Great answer @majenko. Thanks for taking the time to educate newbies like me :-)

You're welcome. Incidentally, my current wireless keyboard uses the nRF24L01+ (actually a Nordic MCU with built-in nRF24L01+) and runs from two AAA batteries. I have had it a number of years now, and it is still on the same batteries it came with. So it is possible if done the right way, but it takes expertise to do it.

Interesting. I had a chat with representatives from Nordic Semiconductors at NDC Oslo a few years ago, and I had the impression they could sell me IoT-devices with years of battery capacity (off a coin battery). They were probably Bluetooth 4 (?) devices.

Most likely nRF24L01+ based devices using a gateway to the internet. There's a new technology these days specially for IoT - LoRa - which is low power and long range designed to work with municipal-grade carrier gateways. There's a big one in Munich.


text:
LiPo batteries with L298N controller
I built an avoidance detector robot from this kit.
When I drove the robot, the two motors performed unequally, so I tested replacing the four x 1.5 AA battery pack with a 9 volts battery. It did the trick. I realized, after having read around Stackexchange a bit, that the L298N controller steals a 1.5 V cell just for "heating up".
So... my question is: Can I run the controller off a LiPo battery? If so, which voltage should I choose, when I want to power my Arduino Uno (copy) and the two motors off it?
I don't really understand what voltage the motors can take.

Lipro? Do you mean LiPo?

I think so? :P Let me google. Yap. LiPo. Just uncovered my knowledge level. Thanks :-)

Cause Lipro are some diet pills. I see you want to make your Arduino diet a bit on the power but not sure that Lipros will work!!

Haha. They're even from Norway, where I live ;-)

Personally I would ditch the L298N and use a modern MOSFET based motor driver.

Good question by Nitech and great answer, mwwalk! (A little low on reputition so I cannot comment directly below you, so I'm posting this here) I'm also new to using batteries and powering electronics. I'm going with the exact description you gave, with an Arduino Uno and L298n motor controller, however with 4 yellow motors. Would a 7.2 V Li-Po (Li-Ion) still be the way to go? I'm also wondering, if I were to connect the arduino Uno to a RPi, e.g. a RPi model 3b, will the problem then be reduced to power the RPi, so that the arduino will draw power from the battery through the RPi? And is ther

First off, congratulations on entering the world of robotics.  I hope you enjoy it as much as I have.  You are correct that the L298N has a voltage drop that is between 1.8V and 3.2V (at 1 Amp) or 4.9V (at 2A).  This is a problem I sometimes see in older generations of H-bridge designs.  After you figure this problem out and move on, I'd recommend switching to something a little newer like the TB6612FNG or maybe the DRV8871, both of which are pretty common, smaller, and more efficient.  But that's a future step.  First lets get this current project powered.
I'm having to make some assumptions based on the images that you linked to but I'm going to assume that the motor board can take up to 12V and that it ouputs 5V that you are using to power the arduino.  I'm also going to assume that those yellow motors are the familiar cheap hobby motors that run at 3-6V.  If any of those are not true, please comment and we can see how things change.
Now as to what kind of batteries to use; there are literally thosands of ways to power this.  One option is AA batteries as you are doing now.  I would use maybe 6-7 AA batteries to account for the voltage drop of the hbridge but remember that they start at 1.5 but can quickly drop voltage.  And the more current you pull from them, the faster they will drop.  This will be cheaper if you only want to run it a few times since AA batteries are like $0.50 a piece in bulk.  But if you want to run it a lot to experiment, it's going to get expensive (and annoying) fast.  Another option is to use NiCad or NiMH batteries that are rechargable.  The batteries will be a little more expensive initially and you'll have to buy a seperate charger but this will save money in the long run and be able to supply more current to your motors.  NiCad and NiMH batteries are 1.2V (nominal) but come packaged in battery packs so I'd recommend probably an 8.4V pack.  Finally there is the Lipo battery packs, also called Li-Ion (which is a much better and more accurate name but I won't get started on that).  Li-Ion are rechargable like NiCad and NiMH but are much smaller and lighter for the same energy capacity (mAh).  Because of this they have become very popular and have become pretty economical.  For instance you can get a decent li-ion for under $20 on hobbyking and be very happy for several years.  Li-ion do have an inherant risk but as long as you don't do anything stupid, you'll be fine.  They also require a special charger but as long as you aren't worried about super fast charging this isn't too expensive.  Li-ion come in individual cells of 3.6V nominal (sometimes advertised as 3.7V) but also come in packs of 7.2V, 11.1V, or 14.4V.  Remember that these are the nominal values.  A 7.2V pack will start at 8.4V and drain to 6V before it is "dead"  If you go this route, I'd go with the 7.2V pack.
I would highly recommend you go with one of the three rechargable options since that will be more economical in the long term and will also allow for longer run times and will supply more current to the motors.  Hobbyking.com is a great resource for cheap rechargable batteries as is amazon.
I can't explain everything but here are some further quesitons you should google to get started:
-LiPo safety
-Lipo C rating
-Lipo voltage range
-Lipo mAh rating
I just want to fix a couple misconceptions from other answers:
1) Lipos are not expensive as hell if you take into acount how long they last and their other benefits such as size, weight, and ability to supply current.
2) For a given battery capacity, a LiPo will be smaller and ligher than AA batteries and will provide more current and longer battery life than AA batteries.  The ammount of current the Arduino draws will be tiny compared to the current of the motors so don't worry much about it.
3) Not only are Lipos recommended by many people for ground (and air and water) robots, they are becoming the standard for RC cars of almost every size.  The motors you are using here are 6V max so 7.2V lipo is a good way to go.  Later you might use motors that are 12V and will move up to a 11.1V or 14.4V lipo.  Some of the nicer lipos can deliver hundreds of amps to motors and are commonly use in battlebots and similar competions.  But you aren't there yet so you're going to use smaller lipos with these smaller motors and maybe someday you'll use big lipos with big motors.  Every project has different needs.
4) Sometimes a rechargable battery back will get hot if you are pulling a lot of curernt from it.  But as long as you respect the "C" rating (google it) you will be absolutely fine.

Thank you for your gentle approach to my lack of knowledge, @mwwalk. I believe you are correct regarding the motors. I tried running the motor controller off a 9V battery- which worked fine, and then the motors ran equally. I am also moving into RC planes and quads, and therefore I can benefit from using Li-ion batteries, since I can probably use the same charger.

I've started reading this guide to LiPo batteries: http://rogershobbycenter.com/lipoguide/


text:
DHT11 sensor works on Arduino Uno, not on LoLin NodeMcu
When run this code on an Arduino Uno (clone), everything works.
When I run it on my LoLin NodeMcu, I get the following verbose upload output:
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM4
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

The only difference I really see is that on the Arduino Uno, the voltage pin is connected to 5V, while on the LoLin, it's connected to one of the 3V pins. Does the DHT11 require 5V?
Edit
So I stumbled upon this list of port mappings. When I change my pin number to 5 (meaning D1), it actually works. Kinda. The numbers outputted are strange. Even when I put the board outside, in about -6 Celcius, it still displays
Temp 247.208 °C
RH 216.208 %

Well, I guess this oddity should be posted as another question. I'll answer my own question here with reference to the weird pin-to-number mapping on the LoLin board.

The problem is that the code doesn't upload? Try removing all peripherals and uploading a basic, verified to be working sketch

The problem was that the port mappings on the LoLin board didn't make much sense.
Port D0 is for instance mapped to number 16, not 0.
Go to this Github comment to get a complete list:
/*
 * Weird pin mappings on LoLin:
 *
 * static const uint8_t D0   = 16;
 * static const uint8_t D1   = 5;
 * static const uint8_t D2   = 4;
 * static const uint8_t D3   = 0;
 * static const uint8_t D4   = 2;
 * static const uint8_t D5   = 14;
 * static const uint8_t D6   = 12;
 * static const uint8_t D7   = 13;
 * static const uint8_t D8   = 15;
 * static const uint8_t D9   = 3;
 * static const uint8_t D10  = 1;
*/

Missing decimal digits and not able to measure sub zero values
If this comment on github is correct, the DHT11 sensor does not offer decimals and does not measure values below zero.

I was scratching my head since last two days over similar issue. I am using ESP8266 NodeMCU which is V2 of LoLin NodeMCU and wanted to read DHT11 sensor data over WiFi into blynk app. However my serial output was 'Failed to read from DHT sensor!'. The program and interfacing was working perfectly with Arduin Uno and Raspberry Pi but not with NodeMCU.
Being a hardware guy, I tried all sorts of hardware modification possible. I had DHT11 sensor module which is already having 5k pull up resistors on board. Since NodeMCU board doesn't have 5V supply, I desoldered the sensor and did direct interfacing with 10k resistor as recommended by adafruit DHTxx guide. Doing internet search , someone recommended IDE version issue, tried that too. Nothing worked.
Finally referring per @nitech answer, I checked the pin details of NodeMCU board and got the idea of D2 pin actual mapped on GPIO4. Just changed the pin 2 with 4 in example code and it worked. Voila! I think recent race in achieving most of the boards as Arduino shield and IDE standard compatible, we need to be used for such issues for any deviation.

Glad my experience could help you.

The datasheet says 3V-5V. 3V is the minimum so I DOUBT that isn't the problem, BUT try to pump more juice into it to see what happens. Never believe the datasheet if these cheap components at 100%.
It does say this though:

VDD=5V, T = 25℃ (unless otherwise stated)

So maybe....
Link to datasheet.

Check out my edit - does it shed light?

Well check the pin out of your circuit a second time.... I dont know...

Sorry, didn't quite understand what you meant there. The signal pin of the sensor is connected to D1 on the LoLin board, and in the code, I write int DHpin = 5;

Please post a circuit schematic

Btw: More juice into it? I don't understand. I'm quite newbie in electronics. Are you talking about the sensor or the board? the board gets power from the USB-connection and as far as I can see, the board doesn't have any other than 3V outputs.

Hm, okay. It seems that the VU pin might output 5V.


text:
My Arduino freezes if power removed from the HMI
I have an Arduino (Pro Mini) connected to an HMI display over serial. When the user pushes a button on the HMI screen, it activates a relay attached to one of the digital pins on the Arduino.
For safety reasons, if the Arduino loses communications with the HMI, I want it to turn off the relay. So, when the button has been pushed, it triggers a polling sequence to verify that the button is still being pushed (I'm not relying on the button release event, again for safety).
The following code works perfectly if I disconnect either of the signal lines (tx or rx) or ground from the HMI. If I disconnect the +5 volts, however, the Arduino freezes completely, and therefore never shuts down the relay.
What could be causing this, and what can I do to overcome the problem?
The code is as follows, however, it works as expected if the data lines or ground are severed.
int getNumber(const char *reqString)
{
  sendString(reqString);

  long startTime = currentMillis;
  long waitTimer = currentMillis - startTime;

  bool responded = false;
  int endcount = 0;
  byte inbyte;
  byte bytebuffer[80];
  int bytecount = 0;

  while (waitTimer < 100 && !responded)
  {

      if (HMI.available())
      {
        inbyte = HMI.read();

        if (inbyte == 0xFF)
        {
          endcount++;
          if (endcount == 3)
          {
            responded = true;
            endcount = 0;
          }
        }
        else
        {
          endcount = 0;
        }

        bytebuffer[bytecount] = inbyte;
        bytecount++;
      }

      // Update the wait Timer.
      waitTimer = millis() - startTime;
  }

  // If we received a response, return the first data byte. If not, return 0
  if (responded)
   {
     Serial.println("Received response");
     return bytebuffer[1];
   }
   else
   {
 Serial.println("No response");
     return 0;
   }
}

The more time I spend troubleshooting this, the more I think it's an electrical issue. When I disconnect the power from the display, either' s attempting to draw power or discharge a load through the data lines.
As I said in the post, the code works when I disconnect either data line or the ground.

Can you post also the schematic?

I will have the generate a schematic first. Simply, though, the Arduino and the HIM are both connected to a common 5VDC bench supply. The HMI TX line is connected to pin 2 and the HMI RX line to pin 3.

I did some probing. It appears that the software serial enables the internal pullup resistor, because I always read 5V when nothing is connected to the pin. The HMI, on the other hand, appears to clamp the TX line to ground when it has no power. Armed with this, I shorted the RX pin (pin 2) on the Arduino to ground and got the same result. The unit freezes.

Yes, I thought it could be this, but there isn't any place in the code which actually blocks this, unless a lot of pin changes happen. The problem is that the "idle" state of the serial wire is +5V (that's why the TX wire goes to +5V). You will have to double check first of all what happens when you apply 5V on a pin of the unpowered HMI (if it is not protected you can also break it). Then you will need a way to cope with the fact that you receive an invalid idle state. The solutions I can see are 1) don't use SoftwareSerial 2) pull a wire with the HMI 5V to the arduino, and use it to [...]

[...] ignore the enter condition of the SoftwareSerial ISR function (here is the source code of the library, and the point I'm mentioning is line 146 - avoid the block if there is no power). 3) use something (e.g. logic ports or a PMOS) to pull the RX wire to +5V in the case of a loss of power on the HMI.

It seems that Software Serial is waiting for "high" on RX
Only a hardware solution comes to my mind

simulate this circuit – Schematic created using CircuitLab
This way Arduino RX will be released on HMI power loss
Later edit
You can also use the watchdog timer to unfreeze your code when unresponsive. It will reset the Arduino if wdt_reset() is not called in a given amount of time and you can make the cleaning you need before using Software Serial again. Here is a useful tutorial.


text:
ATmega32U4 (Leonardo/Pro Micro) bootloader, 8K rather than 4K?
Recently hit the dreaded 0x7000 / 28k~ AVRDUDE+LUFA limit.  It states everywhere this is because the bootloader uses 4KB, thus reducing the 32KB to 28KB.  Makes sense, except...
Blank sketches on the 32U4 take nearly 4KB from the get go, which I thought was attributed to the bootloader?  So now I'm confused.  If I'm losing 4KB off the top, and 4KB off the bottom - is the bootloader 8KB?
EDIT:  In case the above is unclear, it appears my sketches only have ~24k of the 32k available to them.  Is this expected behavior?

32u4 sketches include the USB stack that 328p sketches don't. That consequently uses more space.

I read the USB stack lives in the bootloader; are there two USB stacks?

The bootloader needs a USB stack to work. It is possible to run the main sketch without a bootloader. So yes, I suppose you must have two of them. Looking at the assembler output for a blank sketch, it appears that you get the USB code in it by default. As I said, they have to assume you may not have the bootloader around, so they can't just execute the stack from the bootloader.

Not the answer I was hoping for, but an accurate and informative answer nonetheless.  Thank you!


text:
Significant drop in speed between Arduino IDE and Visual Studio?
So, I'm not sure what is causing this, but maybe I'm overlooking something simple. I have a simple program designed to read the analog input at 640 Hz, it looks like this:
int Ch0 = 0;
int count = 0;
unsigned long startTime;
unsigned long currentTime;
bool startedReading = false;

void setup() {
  //set up pin(s)
   pinMode(Ch0, INPUT);

  //begin serial at 115200bps
  Serial.begin(115200);
}

...

//if the current time exceeds the start time by one second, set the start time equal to current time, print the count, set count equal to zero
if (currentTime - startTime >= 1000) {
  startTime = currentTime;
  Serial.println("time");
  count = 0;
}

//read input, delay some microseconds as a means of controlling sampling rate, bring count up by one
//should read somewhere along the lines of 640-ish Hz
analogRead(Ch0);
delayMicroseconds(1230);
Serial.println(count);
count++;

And this all works fine and dandy in the Arduino IDE, I pull up the Serial Monitor, and it prints every number 1-640 and then says time, with good consistency. Yet, when I open up a Visual Studio program and call the command:
EDIT: Added entire data received event method
private: System::Void serialPort1_DataReceived(System::Object^  sender, System::IO::Ports::SerialDataReceivedEventArgs^  e) {
    if (!this->reading) return;
    else
    {
         try
         {
            //get incoming port and read
            SerialPort^ sp = (SerialPort^)sender;
            String^ sInData = sp->ReadLine();
            //parse read data
            double inData = double::Parse(sInData);

            //write data to debugger for testing
            Debug::WriteLine(inData);

            //start populating the "in" array
            AppendIn(inData);
          }
          catch (Exception^ e)
          {
            Debug::WriteLine(e->Message);
          }
    }
}

Aside from the obvious error that occurs when I try to parse the string "time" to indicate when 1 second has elapsed, everything works fine. Except for the fact that the numbers feed into the debugger very slowly. As in, it'll take roughly 4-5 seconds to read through all 640 reads of the count integer and then it throws the time at me. Thus, this leads me to conclude that Arduino is indeed calculating that 1 second has elapsed and then sending that over, but the output is essentially the same, the only difference being that the message takes exactly 1 second to read on the Arduino IDE and over 4 seconds to read in real time in Visual Studio.
Maybe it has something to do with the way I'm reading the data in VS? I have it set up to constantly monitor the stream by calling that read method every as an event when data is received over the serial. No data at all is being lost, it's just very slow...and only in VS. Thanks in advance for any help you can give, but I'm at a bit of a loss.

I have it set up to constantly monitor the stream by calling that read method every as an event when data is received over the serial.

I suspect that is the issue. Waiting for an incoming "serial data available" event and then processing it, is likely to be slow. I would rework how you get serial data. You haven't shown that bit but maybe you can use a larger buffer.

Hmmm, I'm not entirely sure what you mean by "how I get serial data," but I did include the rest of the event if that's what you mean. The method is attached to the OnDataReceived event of a serial port control in a c++ Windows form if that sheds any more light on it also. That said, I took your suggestion and cranked the read buffer size to16384 (4x what it was before), but there weren't any noticeable speed improvements. So it might have something having to do with firing an event 640 times a second. Though, I'll have to see what other way I could read continuously then.

I don't know exactly how the Windows functions work in this case. Can you provide a reference? (link). What I suspect is happening is that the event is called on the first incoming byte, and ReadLine is waiting for an entire line (and timing out after a couple of seconds).

I think you might be right, according to this page, it does read up until the new line character. In the mean time, I'll try messing around with some of the properties referenced on this page.
https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readline(v=vs.110).aspx

Ok, looks like I'll have to double comment because I can only edit comments for 5 minutes, but I went through and disabled the timeout, then tried changing the ReadLine() command to each of the other alternative reads (there were only about 5 or so, so it wasn't too difficult to test them all) and it seems like it's working perfectly now. I seem to be getting the best speed out of ReadExisting(), granted with marginally less accuracy.  It's a little difficult to tell if it's still reading at exactly 640 Hz, but it's very close if it's not. Thanks a ton for the help!


text:
Need help debugging my Binary Clock
I have tried everything but I can't get my binary clock to display correctly. The diagram and code are here: Binary Clock | Electronics Lab.
The hardware is based off this (it also explains the process that my program is trying to do): DIY: Binary Clock with Arduino. The problems lie in a, probably, simple error as my variable tempTime, which is used to convert the individual digits to their binary equivalent, does not change when I tell it to. All this occurs in the display function. (Sorry, I'm new Here and only a high school student)
While debugging it I realized that the only problem is the variable tempTime - the hardware and other functions work as they were intended.
Can anyone help? (Sorry if this is not very well documented).
    int digitPins[4][4] = {{13,6,-1,-1},{12,7,3,1},{11,8,4,-1},{10,9,5,2}};
int time[4] = {0,0,0,0};
int steps[4]={1,2,4,8};
int tempTime = 0;
void setup(){
  for(int x = 0; x < 4; x++){
    for(int y =0; y<4; y++){
    pinMode(digitPins[x][y],OUTPUT);
    }
  }
    Serial.begin(9600);
    convertHour(12);
    convertMinute(57);
    Serial.println("The time is:");

  for(int z = 0; z < 4; z++){
    if(z == 2){
    Serial.print(":");
    }
  Serial.print(time[z]);
  }
  display();
}
void loop(){

}
void display(){
  int displayer[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
/*
0 - Hour
1 - Hour
2 - Minute
3 - Minute
4 - Hour(Total)
5 - Minute(Total)
*/

  int counter1 = 0;
  for(int i = 0; i < 4; i++){ //Loop for the individual digits
    tempTime = time[i];
    if(tempTime >= 10){
    tempTime = tempTime % 10;
    }
    Serial.print("\nBegining new iteration i = ");
    Serial.print("\nStarting with digit: ");
    Serial.print(tempTime);
    Serial.print(i);
    Serial.println("");
    for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
      if(time[i]/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
        Serial.print("\n");
        Serial.print(time[i]);
        Serial.print("/");
        Serial.print(steps[j]);
        Serial.print(" = ");
        Serial.print(time[i]/steps[j]);
        tempTime =tempTime - (time[i]*steps[j]);
        displayer[counter1] = digitPins[i][j];
        Serial.print("\nAdded: ");
        Serial.print(digitPins[i][j]);
        counter1++;
      }
    }

  }
  clear();
  for(int a = 0; a < 13; a++){
  digitalWrite(displayer[a],HIGH);
  }
}
void clear(){
  for(int x = 0; x < 4; x++){
    for(int y =0; y<4; y++){
    digitalWrite(digitPins[x][y],LOW);
    }
  }
}
  void convertHour(int value){
    int digits[] = {0,0};
    if(value >= 10){
        debug("Bigger than 10");
        if(value >= 20){
            digits[0] = 2;
        }else{
            digits[0] = 1;
        }
    }
    digits[1] = value - (digits[0] * 10);
    //String hour = digits[0]+""+digits[1];
    //Serial.print(digits[0]);
    //Serial.print(digits[1]);
    time[0] = digits[0];
    time[1] = digits[1];
  }
void convertMinute(int value){
  int digits[2] = {0,0};
  int val = value;
  if(value >= 10){
    digits[0] = val/10;
  }
  digits[1] = value - (digits[0] * 10);
  Serial.print("\n");
  Serial.print(digits[0]);
  Serial.print(digits[1]);
  time[2] = digits[0];
  time[3] = digits[1];
}
  void debug(String value){
    boolean de = true;
    if(de){
    Serial.println(value);
    }
  }

Serial and LED on the same pin?

Calculate the power requirements for all these LEDs (and 120 ohm). Will the Uno be able to deliver that?

We need more information.  What should it do? What does it do? What have you tried?

Very Sorry wrote that post in a hurry. The hardware is based off this (it also explains the proccess that my program is trying to do): http://www.danielandrade.net/2008/07/15/binary-clock-with-arduino/ The problems lie in  a probably simple error as my variable tempTime which is used to convert the individual digits to their binary equivalent does not change when I tell it to. All this occurs in the display function. (Sorry New Here and only a highschool student)

Can you edit your question and paste the code into it please? This is looking like a link-only question. Format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. If that link goes down the question, and any following answer, will be meaningless.

In your “Loop to determin the arrangement”, you are erroneously using
time[i] in several places where you mean tempTime. Also, to update
tempTime you only have to subtract steps[j]. With these fixes, your
loop becomes:
for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
  if(tempTime/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
    Serial.print("\n");
    Serial.print(tempTime);
    Serial.print("/");
    Serial.print(steps[j]);
    Serial.print(" = ");
    Serial.print(tempTime/steps[j]);
    tempTime = tempTime - steps[j];
    displayer[counter1] = digitPins[i][j];
    Serial.print("\r\nAdded: ");
    Serial.print(digitPins[i][j]);
    counter1++;
  }
}

Now, if you learn a little bit about how binary numbers work, and about
the binary operators in C and C++, you can rewrite your loop in a
simpler form:
for (int j = 3; j >= 0; j--) {
  int weight = 1 << j;      // 2 raised to the power j
  if (tempTime & weight) {  // if bit j of tempTime is set
    displayer[counter1++] = digitPins[i][j];
    Serial.print("Added bit ");
    Serial.print(j);
    Serial.print(", weight ");
    Serial.print(weight);
    Serial.print(", output ");
    Serial.println(digitPins[i][j]);
  }
}

As a side note, it is considered good practice to print a new line at
the end of each string you print (using println()), rather than at
the beginning.
Edit: As your display() function is way too complex for what it
does, I did not resist the temptation to simplify it:
void display() {
  for (int i = 0; i < 4; i++)
    for (int j = 0; j < 4 && digitPins[i][j] >= 0; j++)
      digitalWrite(digitPins[i][j], time[i] & (1<<j));
}

Thank you so much, I'm relatively new to c++ with a background in js and php, still trying to get the hang of it.

Well, the bitwise operators of C and C++ are the same you already know from JavaScript and PHP.


text:
Connecting Winbond W49F002U-12B to Arduino Mega
I am trying to connect a CMOS flash memory Winbond W49F002U-12B to an Arduino Mega, but failing.

What I did:

Read the Winbond W49F002U-12B datasheet. The key points are: CE - chip enabled; OE - output enabled; WE - write enabled and this table:

Wrote this code and uploaded to Mega2560:
int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
int CE = 50;
int OE = 49;
int WE = 48;

char ch;
char addrs[5];
unsigned long address;
unsigned int result;
void setup() {
  Serial.begin(9600);
  for(int i=0; i<18; ++i)
      pinMode(A_pins[i], INPUT);
  for(int i=0; i<8; ++i)
      pinMode(DQ_pins[i], OUTPUT);
  pinMode(CE, OUTPUT);
  pinMode(OE, OUTPUT);
  pinMode(WE, OUTPUT);
  digitalWrite(WE, HIGH);
  digitalWrite(OE, HIGH);
  digitalWrite(CE, LOW);

}

void func(unsigned long adr)
{
  for(int i=0; i<18; ++i){
    if(adr & (1ul << i)){
      digitalWrite(A_pins[i], HIGH);
      Serial.print("A_pins[");
      Serial.print(i);
      Serial.println("] = HIGH");}
    else{
      digitalWrite(A_pins[i], LOW);}}
  digitalWrite(OE, LOW);
  delay(100);
  for(int i=0; i<8; ++i){
    if(digitalRead(DQ_pins[i]) == HIGH){
      result|=1<<i;
      Serial.print("DQ_pins[");
      Serial.print(i);
      Serial.println("] = HIGH");}
  }
  Serial.println(result);
  digitalWrite(OE, HIGH);
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print("address = ");
   Serial.println(address);
   func(address);
   }
}

What this code is doing is basically after reading serial:
-> takes the value as address
-> changes pins A0-A17 to select particular address cell
-> changes OE to LOW
-> reads DQ0-DQ7
-> coverts those readings into int
-> prints result out.
Example of Arduino IDE Serial Monitor inputs/ouputs stuff:
address = 0
0
address = 1232
A_pins[4] = HIGH
A_pins[6] = HIGH
A_pins[7] = HIGH
A_pins[10] = HIGH
0
address = 131072
A_pins[17] = HIGH
0
address = 245760
A_pins[14] = HIGH
A_pins[15] = HIGH
A_pins[16] = HIGH
A_pins[17] = HIGH
0

Arduino Mega board is 100% functioning. I don't think Winbond w49f002u-12b is not working. Where am I wrong?

UPDATE: Here is fixed code:
int A_pins[18] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39};
int DQ_pins[8] = {40, 41, 42, 43, 44, 45, 46, 47};
int CE = 50;
int OE = 49;
int WE = 48;

unsigned long address;
unsigned int result;
void setup() {
  Serial.begin(9600);
  for(int i=0; i<18; ++i)
      pinMode(A_pins[i], OUTPUT);
  for(int i=0; i<8; ++i)
      pinMode(DQ_pins[i], INPUT);
  pinMode(CE, OUTPUT);
  pinMode(OE, OUTPUT);
  pinMode(WE, OUTPUT);
  digitalWrite(WE, HIGH);
  digitalWrite(OE, HIGH);
  digitalWrite(CE, LOW);

}

void func(unsigned long adr)
{
  result = 0;
  for(int i=0; i<18; ++i){
    if(adr & (1ul << i)){
      digitalWrite(A_pins[i], HIGH);
    }
    else{
      digitalWrite(A_pins[i], LOW);}}
  digitalWrite(OE, LOW);
  //delay(100);
  for(int i=0; i<8; ++i){
    if(digitalRead(DQ_pins[i]) == HIGH){
      result|=1<<i;
    }}
  Serial.println(result);
  digitalWrite(OE, HIGH);
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print(address);
   Serial.print(": ");
   func(address);
   }
}

UPDATE: Changed code using PORTs, Thanks to @MikaelPatel for reminding about PORTs:
unsigned long address;

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

  DDRL = B00000000; //  DQ7-DQ0 42-49
  DDRA = B11111111; //  A7-A0   29-22
  DDRC = B11111111; //  A15-A8  30-37
  DDRG |= B00000011; // A17-A16 40-41
  DDRB |= B00000111; // WE, OE, CE

  PORTB = B00000110; // WE - HIGH, OE - HIGH, CE - LOW
}

void func(unsigned long adr)
{
  PORTA = adr;
  PORTC = (adr>>8L);
  PORTG = (adr>>16L);
  PORTB = B00000100; //OE - LOW
  Serial.println(PINL);
  PORTB = B00000110; //OE - HIGH
}

void loop() {
  if (Serial.available() > 0)
  {
   address = (unsigned long)Serial.parseInt();
   Serial.print(address);
   Serial.print(": ");
   func(address);
   }
}

RESET is connected to 5 VCC. Windbond chip's pins are not shorted (checked). Breadboard is good, everything is connected.

That was a great update and it looks like you did the optimization. There are some small details if you intend to move towards a general device driver library but this is a good starting point! Nice work!

What this code is doing is basically after reading serial: ... -> reads DQ0-DQ7

But all the DQn pins are in OUTPUT mode and the A pins in INPUT mode. Seems to be a mix up. BW: it is the same with all of the pins. The pin mode is from the Arduinos point of view and not the memory chip.
Cheers!

Hi. Maybe I'm understanding you incorrectly, but from Arduino board point of view, atmega2560 controls/sets address A, and then reads DQ, therefore A - output, DQ - input

Your code says the opposite. Check the setup().

omg, what a dumb. I am ashamed. Such stupid mistake. Thank you for pointing this out. Now it works :D

You might want to consider using the port directly and assigning the address and read/write data in a single operation. With all the digitalWrite() and digitalRead() this will more less be the same performance as a serial EEPROM on I2C. An SPI EEPROM/Flash would be faster.

I just have this chip. Just wanted to read data, to use it in some way. Don't want to throw it out. But what do you mean saying "using the port directly"?

You can get 100X performance by using the port directly. http://tronixstuff.com/2011/10/22/tutorial-arduino-port-manipulation/. For instance, connect A0-A15 to D22-D37 allows setting all 16-bits in two write operations (PORTA and PORTB). A16-A17 to D40-41 requires a two bit update (PORTG). And last DQ0-DQ7 to D42-D49 and port access (PORTB) in single operation. You are doing 100X more operation than needed to access the memory.

Thanks, I will try it. Now I'm trying to write some data. Could you please help me? The "Byte Program" operation requires 4 cycles: 5555:AA, 2AAA:55, 5555:A0, Ain:DQin. Did I understand correctly that cycles are ruled by WE signal?

And yes, I have to erase chip's memory before writing anything