message:
Performing multiple Wire.writes() - does endtransmission slow things down?

Here's a question for anyone knowledgeable of the ways of I2C.

I'm curious about sending multiple writes to a device and was looking at the code for a [MPU9250 module](https://www.sparkfun.com/products/13762).

There is a nice library that compiled straight off the shelf by Kris Winer [here](https://raw.githubusercontent.com/kriswiner/MPU-9250/master/MPU9250BasicAHRS.ino).

In one of his code examples he makes multiple calls to a function called writeByte():

    // Wire.h read and write protocols
    void writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
    {
     Wire.beginTransmission(address);  // Initialize the Tx buffer
     Wire.write(subAddress);           // Put slave register address in Tx buffer
     Wire.write(data);                 // Put data in Tx buffer
     Wire.endTransmission();           // Send the Tx buffer
    }

here is a (truncated) example of the code calling writeByte():

    void initMPU9250()
    {
      writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x00);
      delay(100);

      writeByte(MPU9250_ADDRESS, PWR_MGMT_1, 0x01);
      delay(200);
      writeByte(MPU9250_ADDRESS, CONFIG, 0x03);
      writeByte(MPU9250_ADDRESS, SMPLRT_DIV, 0x04);
      .
      .
      .
      etc
    }

My question is why call Wire.endtransmission() each time your sending I2C to the same device? I can see one reason straight off the bat which is you may need to call delay after your write() - but in cases where you do not need to call delay, wouldnt it be faster to do something like:

    Wire.beginTransmission(address);
    Wire.write(data1);
    Wire.write(data2);
    Wire.write(data3);
    Wire.write(data4);
    Wire.endTransmission();

at least when it's possible?

body:
No, `Wire.endTransmission()` doesn't "slow things down". It is, however, critical to the operation of the Wire library.

When you do a Wire transaction all the data you send is first buffered in an internal array. Only when you call `Wire.endTransmission()` does that data actually get sent out. The actual `Wire.endTransmission()` doesn't add anything extra to the transmission though.

In your example you are sending a total of 5 bytes (address + 4 data bytes) plus start/ACK/stop bits. In general most devices require you to send specific numbers of bytes in a specific order - the most common being a register address followed by the content of that register. That means 3 bytes. Any more bytes after that in the same transaction will either be ignored or would overwrite the first bytes.

Some devices though would allow `<address><value><address><value>` to be sent, thus removing the need for the repeated I2C address byte for the device each time. Many won't though.

Other devices (most notably flash memory or SRAM chips) would allow you to do *page mode* accesses, which would be `<address><data1><data2>...<dataN>` where the `address` would automatically increment for each data byte. Again, some may, some won't.

It is entirely down to the device you are sending data to as to whether you are able to batch together multiple blocks of data, and the form that batching has to be in if it is supported at all. So you should look in the datasheet for the device to see just what it can support.


sender: user

message:
Using an Arduino on a motorcycle

I want to use the Arduino to control various electronics on my motorcycle. I would need to power the Arduino with the motorcycle battery. So the question is, when the motorcycle is running the alternator will be putting out something like 13v to the battery. So can I still just connect the battery directly to the vIn and ground to power it?

sender: assistant

body:
Accordly to Arduino Technical Specs:

-Input Voltage (recommended) 7-12V

-Input Voltage (limit) 6-20V

https://www.arduino.cc/en/main/arduinoBoardUno

Another Arduino thread:
https://forum.arduino.cc/index.php?topic=22676.0

I would say a better choice is to use another battery power supply just for Arduino. Is is easy to install, easier to handle and more verstile unless you really needs to use your motorcycle battery. And if you want or need to read your motorcycle battery just use a portable voltage meter plugged onto Arduino with no need to use your vehicle battery to power it.


body: Just add a rectifier diode or two before the vin input. This gives you a 0.7V drop per diode for large currents, for small currents the LDO won't overheat anyway...


message:
HC-06 Bluethoot communication

During this week i purchased two hc-06 bluethoot module for arduino with the purpose of maintain a stable bluethoot connection between two arduino devices. Most people use hc-05 and hc-06 togheter so my question is if i can make a connection without hc-05 module.

body:
No.

What you have is two slave devices and you need a master in order to initiate the Bluetooth communication with the slave. So, either you need two HC-05 Or 1* HC-05 and 1* HC-06.


body:
You have purchased two slave modules (HC-06). Actually, you have to use a master module (HC-05) in order to initiate the Bluetooth communication.

Therefore, the answer to your question is NO ,  can not make a connection without HC-05 module, unless you provide any other master module.


message:
Use registers as parameter?

I'm writing a helper class to manage timers, and I'm writing a lot of code like

    if (timer == 1)
   ICR1 = icr;
  else if (timer == 3)
   ICR3 = icr;
  else if (timer == 4)
   ICR4 = icr;
  else if (timer == 5)
   ICR5 = icr;

Is there a better way to store these registers?
e.g. an array

    timers {
    { ICR1, TCCR1A, OCR1A, OCR1B },
    { ICR2, TCCR2A, OCR2A, OCR2B }
etc.

to be accessed like

    timers[1][0]

for ICR1.

And ultimately, how would I assign a value? e.g.

    *timers[1][0] = 100;

**UPDATE:**

I solved the problem with

 volatile uint16_t* ICRs[5];
 ICRs[1] = &ICR1;
 ICRs[3] = &ICR3;
 ICRs[4] = &ICR4;
 ICRs[5] = &ICR5;

    *ICRs[1] = x;

body:
You can better use a switch statement:

    switch (timer)
    {
    case 1:
        ICR1 = icr;
        break;

    case 3:
        ICR3 = icr;
        break;

    case 4:
        ICR4 = icr;
        break;

    case 5:
        ICR5 = icr;
        break;

    default:
        // Handle other cases
        break;
    }

About the variables:

You can make a 2 dimensional array:

    typedef enum
    {
       TYPE_ICR,   // Value 0
       TYPE_TCCRA, // Value 1
       TYPE_OCRA,  // Value 2
       TYPE_OCRB,  // Value 3
       TYPE_LAST,  // Value 4
    } EType;

    EType timers[TYPE_LAST][2];

You can access it by

    timers[(int) TYPE_OCRB][0] = 3;
    timers[(int) TYPE_OCRA][1] = 0;

Maybe the (int) cast is not needed.

You also can just iterate over the type:

    for (int type = 0; type < (int) TYPE_LAST; type++)
    {
        timers[type][0] = -1;
        timers[type][1] = -1;
    }

Note 1: if a cast is needed probably static_cast(...) is better to use.
Note 2: I haven't tested the code above


body:
registers are nothing but pointers to memory addresses. so the best way to "parameterize" them is to do so via pointers.

*assuming* that ICRi is of 8-bit types - they are NOT to be sure:

    uint8_t *ICRs[4];  //isr pointers

    //initialize the icrs
    ICRs[0]=(uint8_t *)&ICR0;
    ICRs[1]=(uint8_t *)&ICR1;
    ...

    *ICRs[i]=icr; //assign value to ICRi

*note:* that piece of code isn't operable in reality. The way to go is to use a pointer to void. But I'm sure you can figure that out.


body:
i would suggest creating macro definitions for the timers you want

Something along the lines of:

    #define OCR_BY_INDEX(i) OCR##i
    //...other code...
    OCR_BY_INDEX(1) = value;

and then have the indices in an array


message:
if condition does not work

I'm trying to connect two Arduinos according to the example in [Example][1]

I added a bit of debug prints so the code looks like:

    #include <Wire.h>

    // Include the required Wire library for I2C<br>#include <Wire.h>
    int LED = 13;
    int x = 0;
    void setup() {
      // Define the LED pin as Output
      pinMode (LED, OUTPUT);
      // Start the I2C Bus as Slave on address 9
      Wire.begin(9);
      // Attach a function to trigger when something is received.
      Wire.onReceive(receiveEvent);
      Serial.begin(9600);
    }
    void receiveEvent(int bytes) {
      x = Wire.read();    // read one character from the I2C
      Serial.println(x);
    }

    void loop() {
      //If value received is 0 blink LED for 200 ms
      Serial.print("x = '");
      Serial.print(x);
      Serial.println("'");
      if (x == '0') {
        Serial.println("Do 0");
        digitalWrite(LED, HIGH);
        delay(200);
        digitalWrite(LED, LOW);
        delay(200);
      }
      //If value received is 3 blink LED for 400 ms
      if (x == '3') {
        Serial.println("Do 3");
        digitalWrite(LED, HIGH);
        delay(400);
        digitalWrite(LED, LOW);
        delay(400);
      }
    }

The strange thing is, the terminal gives the following information:

    ...
    x = '2'
    x = '2'
    x = '2'
    x = '2'
    x = '2'
    x3= '3'
    x = '3'
    x = '3'
    x = '3'
    x = '3'
    ...

However, I never see the expected "Do 3" lines. Why is that? I assume if (x == '3) would return true when x = '3'?

Also I see the x3 = '3'instead of x = '3'... now I print x also while an event is received, but are those in two different threads since the expected text would be "3x = '3'")  or "x = '3'3"

  [1]: https://www.instructables.com/id/I2C-between-Arduinos/step1

body:
Following code is printing value of integer as string.

    int x = 0;
    ...
    Serial.print("x = '");
    Serial.print(x);
    Serial.println("'");

It prints `x = '3'` for numeric value 3. But ASCII value for character '3' is actually 51.

And about the second issue - `reveiveEvent` is called from receive ISR asynchronously, so it's completely random when the main code gets interrupted. Btw printing anything inside of ISR is quite tricky. If the output buffer is full or will be filled up inside of ISR, everything gets deadlocked as it needs ISRs enabled.


message:
Differences between a real and clone Arduino uno?

Today I got my clone Arduino and connected it to my real Arduino and they both work. (UPDATE: The Arduino noted as real Arduino probably also is not a real Arduino; however both work fine).

However, I see some differences and wonder if these are good or bad:

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

My questions

1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.

2) At number 2 are 4 holes without any explanation. What is the function?

3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.

4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

  [1]: https://i.stack.imgur.com/Z9edm.jpg

body:
The best help is the [schematics][1] for the clone.

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

> 1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.

Lower left on the schematics is the 12 MHz crystal. It is for the CH340G (USB-UART chip).

> 2) At number 2 are 4 holes without any explanation. What is the function?

Lower middle is the pins X1. They are extra signals from the USB-UART chip (CTS, DSR, R and DCD).

> 3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.

Upper right on the schematics are the extra pins. This might be handy.

> 4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

The original has an extra ISP pins (ICSP1) for the ATmega16U2. See the [schematics][3]. The clone has the new layout I2C signals extending beyond pin 13.

  [1]: http://jarick.com.ua/все-остальное/25-схема-клона-arduino-uno-r3-на-atmega328-и-ch340g.html
  [2]: https://i.stack.imgur.com/pZnla.jpg
  [3]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf


message:
Why does this sketch give MPU FIFO overflows?

I'm transmitting this program over an NRF24l01, data from mpu, and I'm getting a FIFO overflow. Im not sure what the problem is but it gives me a lag when I put it on processing so I know the problem is in the code. I posted the code the below. Pleas help find the issue.

    // Include libraries necessary for the radios
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8);

    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"

        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            #include "Wire.h"
        #endif

        MPU6050 mpu;

        #define OUTPUT_TEAPOT

        #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
        bool blinkState = false;
        // MPU control/status vars
        bool dmpReady = false;  // set true if DMP init was successful
        uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
        uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
        uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
        uint16_t fifoCount;     // count of all bytes currently in FIFO
        uint8_t fifoBuffer[64]; // FIFO storage buffer
        // orientation/motion vars
        Quaternion q;           // [w, x, y, z]         quaternion container
        VectorFloat gravity;    // [x, y, z]            gravity vector
        float euler[3];         // [psi, theta, phi]    Euler angle container
        float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
        // packet structure for InvenSense teapot demo
        uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

        // ================================================================
        // ===               INTERRUPT DETECTION ROUTINE                ===
        // ================================================================
        volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
        void dmpDataReady() {
            mpuInterrupt = true;
        }
        // ================================================================
        // ===                      INITIAL SETUP                       ===
        // ================================================================
        void setup() {
            // join I2C bus (I2Cdev library doesn't do this automatically)
            #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
                Wire.begin();
              //TWBR = 8; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.

            #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
                Fastwire::setup(400, true);
            #endif

            radio.begin();

            radio.setRetries(15, 15);
            radio.openWritingPipe(0xF0F0F0F0A1LL);

            radio.stopListening();
            Serial.begin(115200);

            // load and configure the DMP
            Serial.println(F("Initializing DMP..."));
            devStatus = mpu.dmpInitialize();

            mpu.setXGyroOffset(54);
            mpu.setYGyroOffset(15);
            mpu.setZGyroOffset(33);
            mpu.setZAccelOffset(1613); // 1688 factory default for my test chip
            mpu.setXAccelOffset(-4009);
            mpu.setYAccelOffset(332);

            // make sure it worked (returns 0 if so)
            if (devStatus == 0) {
                // turn on the DMP, now that it's ready
                Serial.println(F("Enabling DMP..."));
                mpu.setDMPEnabled(true);

                Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
                attachInterrupt(0, dmpDataReady, RISING);
                mpuIntStatus = mpu.getIntStatus();

                Serial.println(F("DMP ready! Waiting for first interrupt..."));
                dmpReady = true;
                // get expected DMP packet size for later comparison
                packetSize = mpu.dmpGetFIFOPacketSize();
            } else {

                Serial.print(F("DMP Initialization failed (code "));
                Serial.print(devStatus);
                Serial.println(F(")"));
            }
            // configure LED for output
            pinMode(LED_PIN, OUTPUT);
        }
        // ================================================================
        // ===                    MAIN PROGRAM LOOP                     ===
        // ================================================================
        void loop() {
            // if programming failed, don't try to do anything
            if (!dmpReady) return;
            // wait for MPU interrupt or extra packet(s) available
            while (!mpuInterrupt && fifoCount < packetSize) {

              /*Do some computational stuff here*/

            }

            // reset interrupt flag and get INT_STATUS byte
            mpuInterrupt = false;
            mpuIntStatus = mpu.getIntStatus();
            // get current FIFO count
            fifoCount = mpu.getFIFOCount();
            // check for overflow (this should never happen unless our code is too inefficient)
            if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
                // reset so we can continue cleanly
                mpu.resetFIFO();

                Serial.println(F("FIFO overflow!"));
            // otherwise, check for DMP data ready interrupt (this should happen frequently)
            } else if (mpuIntStatus & 0x02) {

                // wait for correct available data length, should be a VERY short wait
                while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
                // read a packet from FIFO
                mpu.getFIFOBytes(fifoBuffer, packetSize);

                fifoCount -= packetSize;

                    /*Object to Transmit Yaw, Pitch, and Roll*/
                    typedef struct YPR_TX {
                      int y;
                      int p;
                      int r;

                    } YPR_TX;

                    YPR_TX ypr_tx;

                 //   ypr_tx = calcYPR(ypr_tx.y, ypr_tx.p, ypr_tx.r);

                    ypr_tx.y = ypr[0] * 180/M_PI;
                    ypr_tx.p = ypr[1] * 180/M_PI;
                    ypr_tx.r = ypr[2] * 180/M_PI;

                #ifdef OUTPUT_TEAPOT
                    // display quaternion values in InvenSense Teapot demo format:
                    teapotPacket[2] = fifoBuffer[0];
                    teapotPacket[3] = fifoBuffer[1];
                    teapotPacket[4] = fifoBuffer[4];
                    teapotPacket[5] = fifoBuffer[5];
                    teapotPacket[6] = fifoBuffer[8];
                    teapotPacket[7] = fifoBuffer[9];
                    teapotPacket[8] = fifoBuffer[12];
                    teapotPacket[9] = fifoBuffer[13];

                    Serial.print("teapotPacket/t");
                    Serial.print("\t");
                    Serial.print(teapotPacket[2]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[3]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[4]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[5]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[6]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[7]);
                    Serial.print("\t");
                    Serial.print(teapotPacket[8]);
                    Serial.print("\t");
                    Serial.println(teapotPacket[9]);
                   // radio.getDataRate();

                    radio.write(&teapotPacket, sizeof(teapotPacket));

                #endif

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

        }

body:
You are declaring a FIFO overflow every time the mpu sends interrupt 0x10.  Is that correct?

You are using the value in fifoCount before you have set it to a value.  Now with the Arduino IDE you are OK doing that, but its not a good practice.

You are checking that the fifoCount is exactly 1024. It might be better to check if it is >1023 because that will handle the case when it is 1025.

Is there a reason why you have chosen 1024?  Since the packet size defaults to 42 that's 24.3 packets.

Around

    while (!mpuInterrupt && fifoCount < packetSize) {
You never get the fifoCount again, so `fifoCount < packetSize` is always true, therefore you wait until there is an interrupt.  If there first time there is an interrupt is to tell you 0x10 (which I guess is) fifo full from the MPU's perspective) then that will be the reason it is always full.

       // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {

          /*Do some computational stuff here*/
          fifoCount = mpu.getFIFOCount(); // Don't forget to get the latest fifo size.
        }


body:
I have been playing around with the MPU6050 with DMP library too. I see you have used Jeff's example code (as have I). I was getting a lot of FIFO overflows too, but that was because my "do computational stuff here" was taking too long (code with delay()) and the FIFO on the DMP was filling up. Perhaps your radio.write() is taking too long?

The code as written by Jeff is really quite robust, but perhaps not what is necessary in all cases. I have put an extra mpu.resetFIFO() below the Serial.println's. Kind of a hack, but it works. I found the suggestion here:

https://arduino.stackexchange.com/questions/10308/how-to-clear-fifo-buffer-on-mpu6050

Also check on Jeff's own suggestion of lowering the data rate on the DMP by altering the header file:

https://www.i2cdevlib.com/forums/topic/27-fifo-overflow/#comment-99

Hope this helps.


message:
Directly read analog voltage using PWM duty cycle timer registers

I'm outputting an analog voltage by setting an 8-bit duty cycle using `analogWrite`. Once set, I'd like a way to read back this duty cycle. I've managed to read the duty cycle back from the `OCR4D` register, which matches the value set, e.g.:

    pinMode(6, OUTPUT);
    analogWrite(6, 123);
    Serial.print(OCR4D);   // 123

However, when setting the duty cycle to `0` or `255`, `OCR4D` is not actually set at all; instead `analogWrite` calls `digitalWrite` behind the scenes and the pin is digitally set to `LOW` or `HIGH`. This is seen in the source for `analogWrite`:

    if (val == 0)
 {
  digitalWrite(pin, LOW);
 }
 else if (val == 255)
 {
  digitalWrite(pin, HIGH);
 }
 else
 {
    // set PWM duty cycle as normal...

The problem with this is that `OCR4D` is simply left at its previous value, so it's not always possible to tell the actual output by reading `OCR4D` alone. In other words there is no way to tell the difference between:
- PWM is active and `OCR4D` reflects the duty cycle
- PWM is disabled and `OCR4D` reflects a previous duty cycle (which is not useful)

Which register(s) can I read to crosscheck the PWM is active?

I'm also aware of the `pulseIn` function, but would rather read the PWM register directly.

body:
In the end I managed to do this by reading the timer/counter control register relevant to pin 6:

    // read the voltage on an analog output pin
    int analogReadOutput(int pin) {
        switch(digitalPinToTimer(pin)) {
            case TIMER4D:
                if (TCCR4C & (1 << COM4D1)) {   // PWM active
                    return OCR4D;
                } else {                        // PWM not active
                    return 255 * digitalRead(pin);
                }
            case TIMER4A:
                if (TCCR4A & (1 << COM4A1)) {   // PWM active
                    return OCR4A;
                } else {                        // PWM not active
                    return 255 * digitalRead(pin);
                }
            default:
                return -1;
        }
    }

Note that this assumes two things that possibly aren't always true (outside of my simple program):

- `COM4D1` bit is a reliable way of telling if PWM is enabled,
- duty cycle value is 8 bit with a max of 255.


message:
When writing to SD card the file has all gibberish how do I fix it?

I am working on a class project where I am using a Teensy 3.5 with a Prop Shield with sensor attached that will be loaded into a rocket that I will launch and gather data from the altitude, pressure and temperature sensors and then read into an array and then dump at the peak of the height and when it hits the ground. I believe I have everything working when I test the code but when I open up the txt file I get what looks to be ASCII code but I don't know how to fix it.

Below is the code:

    //import statements
    #include <SD.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_MPL3115A2.h>

    // global variable declarations
    Adafruit_MPL3115A2 baro = Adafruit_MPL3115A2();

    int seconds = 0;
    int secondsPerTick = 0;
    int counter = 0;
    double pressure[15];
    double heightA[15];
    double temperature[15];
    File myFile;
    int tempNum;
    const int chipSelect = BUILTIN_SDCARD;

    //test to make sure program uploaded
    void setup() {
      Serial.begin(9600);
      Serial.println("Adafruit_MPL3115A2 test!");
      while (!Serial){
    }

      if (! baro.begin()) {
        Serial.println("Couldnt find sensor");
       return;
      }

    if (!SD.begin(chipSelect)) {
        Serial.println("initialization failed!");
        return;
      }

    while ( seconds < 5 ){

                  double pascals = baro.getPressure();
                  pressure[counter] = pascals;
                  Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

                 double altm = baro.getAltitude();
                  heightA[counter] = altm;
                  Serial.print(altm); Serial.println(" meters");

                 double tempC = baro.getTemperature();
                  temperature[counter] = tempC;
                  Serial.print(tempC); Serial.println(" *C");
                  tempNum ++;

                  secondsPerTick++; //increments seconds per tick
                  if(secondsPerTick == 3){  //if its 3 reset "secondspertick" and increments "seconds"
                    secondsPerTick = 0;
                    seconds++;
                  }
                  counter++;

     }

    myFile = SD.open("Sensor4.txt", FILE_WRITE);

       if(myFile) {
        Serial.print("Writing to file...");

        //cycle through the array and store it in the SD card
        myFile.write("Pressure Recordings(going up): ");
        for(int i=0; i< 15; i++){
          myFile.write(pressure[i]);
          }
        Serial.println('\n');

           //header for the height sensor recordings
       myFile.write("Height Recordings(going up): ");
        //cycle through the array and store it in the SD card
        for (int j = 0; j <15; j ++){
         myFile.write(heightA[j]);
        }
        Serial.println('\n');

        //header for the temperature sensor recordings
        myFile.write("Temperature Recordings(going up): ");
        Serial.println('\n');
        //cycle through the array and store it in the SD card
        for (int k = 0; k <15; k++){
         myFile.write(temperature[k]);
        Serial.println('\n');
       }

        // close the file:
        myFile.close();
        Serial.println("done.");
        }
       else {
        // if the file didn't open, print an error:
        Serial.println("error opening sensor_recordings.txt");
      }

         //as the rocket descends
    while ( seconds > 5 ){

                  double pascals = baro.getPressure();
                  pressure[counter] = pascals;
                  Serial.print(pascals/3377); Serial.println(" Inches (Hg)");

                  myFile.write(pressure[counter]);

                 double altm = baro.getAltitude();
                  heightA[counter] = altm;
                  Serial.print(altm); Serial.println(" meters");

                 double tempC = baro.getTemperature();
                  temperature[counter] = tempC;
                  Serial.print(tempC); Serial.println(" *C");
                  tempNum ++;

                  secondsPerTick++; //increments seconds per tick
                  if(secondsPerTick == 3){  //if its 3 reset "secondspertick" and increments "seconds"
                    secondsPerTick = 0;
                    seconds++;
                  }
                  counter++;

     }

    myFile = SD.open("Sensor4.txt", FILE_WRITE);

       if(myFile) {
        Serial.print("Writing to file...");

        //cycle through the array and store it in the SD card
        myFile.write("Pressure Recordings(going down): ");
        for(int i=0; i< 15; i++){
          myFile.write(pressure[i]);
          }
        Serial.println('\n');

           //header for the height sensor recordings
       myFile.write("Height Recordings(going down): ");
        //cycle through the array and store it in the SD card
        for (int j = 0; j <15; j ++){
         myFile.write(heightA[j]);
        }
        Serial.println('\n');

        //header for the temperature sensor recordings
        myFile.write("Temperature Recordings(going down): ");
        Serial.println('\n');

        //cycle through the array and store it in the SD card
        for (int k = 0; k <15; k++){
         myFile.write(temperature[k]);
        Serial.println('\n');
       }

        // close the file:
        myFile.close();
        Serial.println("done.");
        }
       else {
        // if the file didn't open, print an error:
        Serial.println("error opening sensor_recordings.txt");
      }
     }

    void loop() {

Here is what gets printed to the txt file:

>
 €€€ƒ€ƒ‚ƒ€€„~ƒ‚€€€€ƒ€ƒ‚ƒ€€„~ƒ‚€ƒ‚‚‚„‡€„ƒ„……ƒ‚ƒ„Pressure Recordings: ƒ‚‚‚„‡€„ƒ„……ƒ‚ƒ„
Height Recordings: 10010110010101111000Temperature
Recordings: Å……ƒƒ…€€ƒ‡‚w
Pressure Recordings: Å……ƒƒ…€€ƒ‡‚w
Height Recordings: 000010100010111     Temperature Recordings:      Pressure Recordings: Å……ƒƒ…€€ƒ‡‚w     Height Recordings: 000010100010111     Temperature Recordings:      Pressure Recordings: Ã‡…„†…„…„ˆ†„„€†     Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Ã‡…„†…„…„ˆ†„„€†     Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Â†‰†‡…††‰…‰ˆˆ…ˆ Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings: Â†‰†‡…††‰…‰ˆˆ…ˆ Height Recordings: 000000000000000     Temperature Recordings:      Pressure Recordings(going up): ÀŽ‘ŽŒŽŽHeight Recordings(going up): ///000/0/0/0///Temperature Recordings(going up): Pressure Recordings(going down): ÀŽ‘ŽŒŽŽHeight Recordings(going down): ///000/0/0/0///Temperature Recordings(going down): Pressure Recordings(going up): ½–™––•˜–••š™š—™Height Recordings(going up): ///////////////Temperature Recordings(going up): Pressure Recordings(going down): ½–™––•˜–••š™š—™Height Recordings(going down): ///////////////Temperature Recordings(going down):

I also don't know how I can get the data to be formatted to where it reads like:

Pressure(going up):----

Altitude(going up):---

Temperature(going up):---

Pressure(going down):----

Altitude(going down):---

Temperature(going down):---

body:
You should convert double to String with this kind of code:

    char[9] stringval;
    dtostrf(doubleval, 8, 4, stringval);

where 8 is presicion and 4 is number of digits after point.

More info: http://forum.arduino.cc/index.php?topic=282250.0


message:
How to code water flow sensor and solenoid valve?

I want to know if it is possible to put a boundary or limit to the volume that passes through a water flow sensor, and close the pipe using a solenoid valve.

Example: I only want 400 ml of water to pass, so when the water flow sensor reads how much water has passed in the pipe, if 400 is reached, the solenoid will close the pipe.

Sorry for my bad English, it is not my first language. I'm hopping that someone can help me out.

body:
Using a YF201 you cannot measure less than 1 litre / minute or more than 30 l/m.
(ref http://www.bc-robotics.com/tutorials/using-a-flow-sensor-with-arduino/)

The device sends a pulse for every 2.25ml that flows through it.  All you needs to do is take the amount you want to let through (400ml) and divide that by 2.25ml and you get 177.8 pulses.  So once your Arduino counts 178 pulses then you trigger the valve to close.

Its not going to be very accurate, because unless the valve closes instantly there will be a bit of an overshoot.  and you have to measure in units of 2.25ml.


body:
hello @kaisar Great you have not mentioned which flow sensor are you using. I am assuming that you are using flow sensor YF-S201 or YF-S401(Hall Effect).You have to do Little calculation for measuring water flow.
In order to measure the quantity of water being passed in particular time through the water flow sensor it was first passed through the water flow sensor which was taken as input interface in the flow. Formulas are applied in order to measure the number of rotations/pulses in a minute of rotation.

Here I have determined flow rate by change in velocity of water. Velocity depends on the pressure that forces the through pipelines. As the pipe’s cross-sectional area is known and remains constant, the average velocity is an indication of the flow rate. The basis relationship for determining the liquid’s flow rate in such cases is

**Q=VxA**, where **Q** is flow rate/total flow of water through the pipe, **V** is average velocity of the flow and A is the cross-sectional area of the pipe

**Calibration Factor** = *The hall-effect flow sensor outputs pulses per second per litre/minute of flow.(check your datasheet) here I have taken 4.5.*

**Flow Rate(litres/minute)** = *((1000.0 / Total time) x Pulse Count) / calibration Factor*

**Flow Rate(MilliLitres/Second)** = *(Flow Rate / 60) x 1000*

There you have to calculate the total water flow in a given time by adding flow rate for each second.
There after you have check your set point value(400ml)..if condition satisfied you you can turn off your Solenoid valve.

and the code is

    int sensorInterrupt = 0;  // interrupt 0
    int sensorPin       = 2; //Digital Pin 2
    int solenoidValve = 5; // Digital pin 5
    unsigned int SetPoint = 400; //400 milileter

    /*The hall-effect flow sensor outputs pulses per second per litre/minute of flow.*/
    float calibrationFactor = 4.5; //You can change according to your datasheet

    volatile byte pulseCount =0;

    float flowRate = 0.0;
    unsigned int flowMilliLitres =0;
    unsigned long totalMilliLitres = 0;

    unsigned long oldTime = 0;

    void setup()
    {

      // Initialize a serial connection for reporting values to the host
      Serial.begin(9600);
      pinMode(solenoidValve , OUTPUT);
      pinMode(sensorPin, INPUT);
      digitalWrite(sensorPin, HIGH);

      /*The Hall-effect sensor is connected to pin 2 which uses interrupt 0. Configured to trigger on a FALLING state change (transition from HIGH
      (state to LOW state)*/
      attachInterrupt(sensorInterrupt, pulseCounter, FALLING); //you can use Rising or Falling
    }

    void loop()
    {

       if((millis() - oldTime) > 1000)    // Only process counters once per second
      {
        // Disable the interrupt while calculating flow rate and sending the value to the host
        detachInterrupt(sensorInterrupt);

        // Because this loop may not complete in exactly 1 second intervals we calculate the number of milliseconds that have passed since the last execution and use that to scale the output. We also apply the calibrationFactor to scale the output based on the number of pulses per second per units of measure (litres/minute in this case) coming from the sensor.
        flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor;

        // Note the time this processing pass was executed. Note that because we've
        // disabled interrupts the millis() function won't actually be incrementing right
        // at this point, but it will still return the value it was set to just before
        // interrupts went away.
        oldTime = millis();

        // Divide the flow rate in litres/minute by 60 to determine how many litres have
        // passed through the sensor in this 1 second interval, then multiply by 1000 to
        // convert to millilitres.
        flowMilliLitres = (flowRate / 60) * 1000;

        // Add the millilitres passed in this second to the cumulative total
        totalMilliLitres += flowMilliLitres;

        unsigned int frac;

        // Print the flow rate for this second in litres / minute
        Serial.print("Flow rate: ");
        Serial.print(flowMilliLitres, DEC);  // Print the integer part of the variable
        Serial.print("mL/Second");
        Serial.print("\t");

        // Print the cumulative total of litres flowed since starting
        Serial.print("Output Liquid Quantity: ");
        Serial.print(totalMilliLitres,DEC);
        Serial.println("mL");
        Serial.print("\t");
        If (totalMilliLitres =< 400)
        {
          SetSolinoidValveON();
        }
        else{
          SetSolinoidValveOFF();
            }

    // Reset the pulse counter so we can start incrementing again
        pulseCount = 0;

        // Enable the interrupt again now that we've finished sending output
        attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
      }
    }

    //Insterrupt Service Routine

    void pulseCounter()
    {
      // Increment the pulse counter
      pulseCount++;
    }

    void SetSolinoidValveON()
    {
      digitalWrite(solenoidValve, HIGH);
    }
    void SetSolinoidValveOFF()
    {
      digitalWrite(solenoidValve, LOW);
    }


message:
How Arduino IDE works?

You know , a simple arduino sketch has no main function , no include preprocess cmds,so I just want to know how arduino IDE convert a sketch to normal C/C++ source code,and what is the source code looks like.

If possible,I also want to use cmd like  *g++ -E*   to see the .i file genetated after preprocess.How to do it?

ps: my English is poor.

body:
I'm not entirely sure what the `arduino-builder` does, but it should be similar to the traditional method.

Given the "bare minimum" sketch of:

    void setup() {
    }

    void loop() {
    }

First the IDE combines all `.ino` and `.pde` files together into one large one. I believe the order of concatenation is:

1. Start with the "main" INO file (the one named the same as the folder it's in).
2. Append to that each other `.ino` or `.pde` file in alphabetical order.

Then the IDE will add the required `#include <Arduino.h>` and function prototypes for any functions found - so it would end up as:

    #include <Arduino.h>

    void setup();
    void loop();

    void setup() {
    }

    void loop() {
    }

Finally it runs normal `gcc` and `g++` commands on the generated file(s).  You can find the generated file(s) in the *build* folder. Where that is depends on the operating system you are using.  Turn on *verbose compilation* in the preferences and you can see the `gcc` and `g++` commands that are being executed, and as well the paths for the files involved, which lets you then see where the preprocessed files are stored.

Another important step the IDE performs, which doesn't modify the files themselves, is to look for any `#include` entries that match libraries and add `-I <path>` to the compilation commands for those libraries. It also then finds any source files associated with those libraries and compiles them. It also compiles all the *core* source files, which is where the `main()` functions is (see [@jantje's answer](https://arduino.stackexchange.com/a/36485/4143) for details on how the `main()` function is formed).

Once the IDE has finished with its parsing and processing it's all standard `gcc` and `g++`.


body:
You can turn on verbose compiling.
This will show all the compiler commands used by Arduino IDE.

The ino file is converted to a .cpp file (which you can see in the verbose output). Basically the conversion is as follows:

 1. merge all .ino files into one big .ino file with the [project].ino
    file first
 2. Add arduino.h
 3. Add all function declarations of methods defined in the .ino files
 4. Save as .cpp file

As to the lack of main method.
The core contains a main.cpp file which defines main in avr world this looks like

    int main(void)
    {
     init();

     initVariant();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }


message:
Arduino nano select port option is blurred | Driver issue

I have just bought arduino nano board. when i connect the board via usb, system detects the new device but i am not able to select port in arduino ide for writing any code on board. I checked my device manager it says

> The drivers for this device are not installed. (Code 28)
>
> There are no compatible drivers for this device.

I have also updated my board and library list in arduino ide.

please help me out?

body:
on my nano board CH340G USB<-->uart chip was present, so i installed driver for that chip and everything works fine now. :P

link for the driver (windows 8,10): http://www.arduined.eu/ch340-windows-8-driver-download/


message:
"No Socket available" for WiFiClient

I have an LDR/Photocell which sends a value 1 or 0 (depending on the value) to a text file on my web address. The code works for a few seconds then prints out `No Socket available`.

Any help will be appreciated; code below.

 #include <SPI.h>
 #include <WiFi.h>

 int LDR = A0;
 int LED = 11;
 char ssid[] = "SSID";
 char password[] = "password";
 int status = WL_IDLE_STATUS;

 char server[] = "www.example.com";
 int value;

 void setup() {
   Serial.begin(9600);
   pinMode(LDR, INPUT);
   pinMode(LED, OUTPUT);
   connectWifi();
   printWifiStatus();
   // postData();
 }

 void loop() {
   value = analogRead(LDR);
   postData();

   delay(10000);
 }

 void connectWifi() {
   while (status != WL_CONNECTED) {
     Serial.print("Attempting to connect to ");
     Serial.println(ssid);
     status = WiFi.begin(ssid, password);
     delay(500);
   }
 }

 void printWifiStatus() {
   // Print the SSID of the network you're attached to
   Serial.print("SSID: ");
   Serial.println(WiFi.SSID());

   // Print your WiFi shield's IP address
   IPAddress ip = WiFi.localIP();
   Serial.print("IP Address: ");
   Serial.println(ip);

   // Print the received signal strength
   long rssi = WiFi.RSSI();
   Serial.print("signal strength (RSSI):");
   Serial.print(rssi);
   Serial.println(" dBm");
 }

 void postData() {
   WiFiClient client;
   if (client.connect(server, 80)) {
     Serial.println("Connecting...");
     if (value > 350) {
       Serial.println("0");
       digitalWrite(LED, LOW);
       String data = "value=0";
       client.print("GET /example/client.php?");
       client.print(data);
       client.println(" HTTP/1.1");
       client.println("Host: www.example.com");
       client.println("Connection: close");
       client.println(); client.println();
       //client.stop();
     } else {
       Serial.println("1");
       digitalWrite(LED, HIGH);
       String data = "value=1";
       client.print("GET /example/client.php?");
       client.print(data);
       client.println(" HTTP/1.1");
       client.println("Host: www.example.com");
       client.println("Connection: close");
       client.println(); client.println();
       //client.stop();
     }
   } else {
     Serial.println("Connection failed");
     client.stop();
   }

 }

Output:

 Attempting to connect to SSID
 SSID: SSID
 IP Address: 255.255.255.255
 signal strength (RSSI):-47 dBm
 Connecting...
 1
 Connecting...
 0
 Connecting...
 0
 Connecting...
 0
 No Socket available
 Connection failed
 No Socket available
 Connection failed
 No Socket available
 Connection failed
 No Socket available

Actual web address omitted.

body:
I guess you have commented the command:
 //client.stop();

If you allow it, I guess you will have your code running


message:
How to generate two pulses one with 60 and other 66 duty cycle at same instant in 2 pins?

I have to drive two switches one at a duty cycle of 60% and the other at a duty cycle of 66% simultaneously at 50khz frequency. I am using an Arduino Uno ATmega 328.

body:
I proposed a few approaches in generating 100kha pwm pulse trains here in response to someone's ask a couple of days ago. The identical code would work for your purpose as well.

It should come up quickly if you do a scan of topics here.

edit: to make it a little bit easier, here is the code I used to generate 50Khz pulse train with 60% and 66% duty cycles.

    void setup() {
      // put your setup code here, to run once:
      //pinMode(led1, OUTPUT);      //led1 as output
      //pinMode(led2, OUTPUT);      //led2 as output
      pwm1topr(F_CPU / F_PWM);      //set tmr1/pwm frequency to F_PWM
      analogWrite(led1, F_CPU / F_PWM * 60 / 100); //led1 @ 60% duty cycle
      analogWrite(led2, F_CPU / F_PWM * 66 / 100); //led2 @ 66% duty cycle
    }

    void loop() {
      // put your main code here, to run repeatedly:
        //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
        //delay(100);               // wait for a second
        //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
        //delay(100);               // wait for a second
    }

and a quick sim confirms its functionality.

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

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

enjoy.


message:
Fastest way to send serial commands and do something

I am trying to send a lot of serial commands really fast. I basically need to change color of my LED strip many times per second (10 times per second should really be enough). If I do this over WiFi, it will eventually clutter up and make the ESP8266 unresponsive. I need to send the colors as hex, then convert them into usable values (HEX to RGB). Something tells me that's going to cost a lot of resources and the MCU is therefore spending a lot of time just converting the colors into RGB values. Here's a pseudo code example of what I am trying to achieve:

    void loop() {
        if(Serial.available()) {
            if(Serial.read().first(8) == "0xABCDEF") {
                //0xABCDEF is basically my indicator saying "this is for individual LEDs"
                //Serial.read() can now be something like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000
                char* colors[] = Serial.read().split(" ");
                colorLED(colors);

            }
        }
    }

    void colorLED(colors) {
        for(i = 1; i < colors.length; i++) {
            strip.SetPixelColor(i, color[i]);
        }
    }

I hope this example makes sense. I can send a serial command like `0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000`. 5 colors in HEX.

My real question is: How do I take a lot of inputs like above (or another way) and turn them into strings, so I can convert them to RGB? Is there a better way to send commands (like pure RGB values? but remember I need to send many)?. Here is how I convert my colors into RGB:

    //hexColor can be "FF0000"
    int number = (int)strtol(&hexColor[0], NULL, 16);

    int r = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;

body:
Simple answer: don't.

Don't even consider strings in any form. Instead you want a state machine.

In pseudocode:

1. Start with an invalid count number (-1)
2. Read a character.
3. If that character is `x` then set your counter to 0.
4. Otherwise, if counter is 0 or more, convert the character to a number and place it into the right byte depending on the value of your counter
5. Increment counter
6. If counter is 6 then set your LED colours and set the counter to "invalid".
7. Return to start.

Or, in untested C:

    static int8_t counter = -1;
    static uint8_t r = 0;
    static uint8_t g = 0;
    static uint8_t b = 0;

    if (Serial.available()) {
        char c = Serial.read();
        if (c == 'x') {
            counter = 0;
        } else {
            if (c > 0x39) c -= 7;
            uint8_t v = c & 0x0f;
            switch (counter) {
                case 0: r = v << 4; break;
                case 1: r |= v;
                case 2: g = v << 4; break;
                case 3: g |= v;
                case 4: b = v << 4; break;
                case 5: b |= v;
            }
            counter++;
            if (counter == 6) {
                counter = -1;
                analogWrite(3, r);
                analogWrite(5, g);
                analogWrite(6, b);
            }
        }
    }

The "clever" bit that may confuse you is:

    if (c > 0x39) c -= 7;
    uint8_t v = c & 0x0f;

That is, if the character is greater than a "9" (character 0x39) then it *should* be a-f. Subtracting 7 from it converts ASCII HEX from `0123456789ABCDEF` to `0123456789:;<=>?`.  If you then mask it with 0x0F you end up with a number between 0 and 15, or 0-F in hex.

The rest just takes each nibble and places it into the right half of the right colour variable.


body:
Since Majenko is convinced that using binary is far too complicated here's how to do it in binary sending 32 bits per color.

The start of strip marker is any 4 non-zero bytes in a row e.g 0x01010101

Each LED is then sent as four binary bytes: 0x00, 0xRR, 0xGG, 0xBB

In the unlikely event that a byte is lost in transmission then it will re-sync at the start of the next update, depending upon the pattern there is a fair chance that lost data will be noticed and the incorrect colors not get displayed on the strip.

    loop() {
      static color_t color;
      static int8_t counter = -1;
      static int ledIndex = 0;
      static bool aligned= false;

      if (Serial.available()) {
        if (aligned) {
        switch (counter) {
          case 0: color.r=Serial.read(); break;
          case 1: color.g=Serial.read(); break;
          case 2: color.b=Serial.read();
                  strip.SetPixelColor(ledIndex, color);
                  ledIndex++;
                  break;
          case 3: // first byte of next data, should always be 0
                  // only not 0 if we've lost a byte or want to restart the strip
                  if (Serial.read() != 0) {
                    aligned=false;
                    counter = 0;
                  } else
                    counter = -1;
                  break;
          default: break;
        }
        counter++;
      } else { // not aligned
        ledIndex = 0;
        if (Serial.read() != 0) // count non-zeros
          counter++;
        else {
          if (counter >= 4)     // had a start marker, next byte is r
            aligned = true;
          counter = 0;
        }
      }
    }

Is it worth doing it in binary? It gives a 50% decrease in RS232 data which if serial data rate is an issue will be a big help. It also gives a decrease in required calculations, if you look at the code there are virtually no mathematical operations beyond increasing counters.

Personally I prefer this method because it just seems more efficient and cleaner to transfer numbers as numbers rather than converting them to text and back but ultimately if you don't need every last bit of performance then it comes down to what you feel most comfortable with.


message:
How to send data in response to HTTP get request from ESP8266?

I'm trying to control some RGB LEDs with ESP8266. I have built an HTML page to set the color and send the RGB color code to the ESP using HTTP get request. Everything works as expected. I just want to send an HTTP get request to the ESP and ask what the current color is. But after a couple of hours of searching and trying I don't know how to send data in response to get request, I just can send HTTP ok code. I'm using jquery to send get command as below

    $.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
        //I don't know how to send data fram ESP get it here.
    });

this is the corresponding ESP response code written in Arduini IDE

    WiFiClient client = server.available();
       if (client) {
      String req = client.readStringUntil('\r');
      client.print("HTTP/1.1 200 OK\r\n");
      client.print("Access-Control-Allow-Origin: *");
    .
    .
    .

This is the HTTP header, How do I send some data(text)?

body:
@Gerben answered my question in a comment all credit goes to him. I retype it here maybe it helps someone in the future.

I had to send two new line after setting up the header

    //header
    client.print("\r\n\r\n");
    clinet.print("Hello, I'm comming from ESP!!");

And in jQuery I get it like this:

    $.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
        var receivedData=data;  //=Hello, I'm comming from ESP!!
    });

It is simple but it may help some newbie like me.


message:
How to display extended ASCII characters, e.g., the standard degree symbol, DEC 167, on the Serial Monitor [not LCD]?

I spent an afternoon researching this, and read a lot of material, but with no successful results.  [I really thought this would be a trivial task.]

Is this problem Windows, or WIN10, specific, as the extended characters all seem non-displayable? Regardless, is there a solution?

body:
The Arduino serial monitor uses UTF-8, per the discussion at http://forum.arduino.cc/index.php?topic=172814.0 --

For the U+00B0 degree symbol, you'd send the bytes UTF8 `0xC2 0xB0` like this:

    Serial.print("°");


message:
Help using thermistor with esp8266

So I am trying to use [this](http://www.mouser.com/Search/m_ProductDetail.aspx?TE-Connectivity-Holsworthy/LT300014T2610KJ/&qs=HLeXuo0aL2oWuH78WH79GQ==) thermistor to measure temperature and with this code below it always puts the same value (2147483647).  I used [this](https://learn.adafruit.com/thermistor/using-a-thermistor) tutorial to do the wiring and coding.  I don't think the wiring is the problem but think the problem is somewhere in my code or perhaps I am using a wrong type of thermistor?  Am I missing something?  Any help is greatly appreciated.

I am only using a 1k resistor in series with the thermistor but don't think that would be a problem, right?

Edit: I should have mentioned I'm using the adafruit huzzah esp8266 so there are a few pins.

    #include <DHT.h>
    #include <ESP8266WiFi.h>
    #include <Phant.h>
    #include <ESP.h>

    #define DHTPIN 2
    #define DHTTYPE DHT22
    #define THERMISTORPIN 4

    DHT dht(DHTPIN, DHTTYPE);

    const char* ssid = "xxxx";
    const char* password = "yyyyyy";
    const char* host = "data.sparkfun.com";
    const String publickey = "uuuuuu";
    const String privatekey = "ttttttt";
    const byte NUM_FIELDS = 5;
    const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
    String fieldData[NUM_FIELDS];

    //thermistor variables
    const int thermresistor = 987; //value of resistor in series with thermistor
    int thermtemp = 0;
    uint8_t i;
    uint8_t numsamples = 5;
    uint8_t To = 25;
    const int B = 3950;

    void setup(){
        Serial.begin(115200);
        delay(10);
        WiFi.begin(ssid, password);

        while (WiFi.status() != WL_CONNECTED) {
      delay(500);
    }

        fieldData[0] = 1; //humidity
        fieldData[1] = 2; //garden temp
        fieldData[2] = 3; //light
        fieldData[3] = 4; //outside temp
        fieldData[4] = 8; //water temp

    //turnpumpon();
    posttophant();
    //turnpumpoff();
    ESP.deepSleep(1200000000, WAKE_RF_DEFAULT);

    }

    void posttophant()
    {
        fieldData[0] = dht.readHumidity();
        fieldData[1] = dht.readTemperature(true);

        //read outside temp (otemp) data and convert to a temp
        for (i=0; i<numsamples; i++){
          thermtemp = analogRead(THERMISTORPIN);
          thermtemp += thermtemp;
          delay(10);
        }

        //take the sum of all the readings and divide by # of samples to get avg.
        thermtemp = thermtemp / numsamples;

        #voltage divider equation
        thermtemp = thermresistor / (1023 / thermtemp - 1);

        //Steinhart eqn.
        thermtemp = 1 / (log(thermtemp / thermresistor) / B + (1 / (To + 273))) - 273;
        fieldData[3] = String(thermtemp);

        WiFiClient client;

        const int httpPort = 80;
    if (!client.connect (host, httpPort)){
      return;
    }

        client.print("POST /input/");
        client.print(publickey);
        client.print("?private_key=");
        client.print(privatekey);
        for (int i=0; i<NUM_FIELDS; i++)
        {
          client.print("&");
          client.print(fieldNames[i]);
          client.print("=");
          client.print(fieldData[i]);
        }
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println(host);
        client.println("Connection: close");
        client.println();
    }

body:
**Considerations about the ESP8266 analog pin**

The ESP8266 has only one pin that allows analog read. This pin is call A0 on the NodeMCU module or A on the ESP8266 Huzzah (some other ESP module don't expose that pad - for example ESP8266-01) or might label it differently - check the documentation of your ESP module.
Following your edit: make sure that you connect your thermistor to the A pin of the Huzzah ESP8266 module.

You should keep in mind that this analog pin is a 10bit ADC with in principle limited input voltage range.

To read an external voltage applied to the ADC pin, use `analogRead(A0)`. Unless you are using a board specially design to increase its range, the input voltage range is 0 — 1.0V. As @dandavis pointed out some boards (Node MCU e.g.) include a voltage divider on board to give you a full 0 - 3.3V input range.

**Thermistor equations**

The datasheet of your thermistor states that the TCR coefficient is 3000ppm/%C and has a 10K value [note that the manufacturer doesn't provide you with the temperature at which R = 10K]. The equation of the resistance variation ∆R with temperature variation ∆T is given by:

`∆R = ∆T*10k*3000ppm = 30*∆T`

So if T_0 is the temperature where R = 10k, the equation of the resistance value is given by:

`R = 10k + (T-T_0)*30`

I am assuming that you are using the 3.3V supply of your ESP and creating a voltage divider using the 1K resistor and the thermistor.
There are two ways to do this divider:

*1. Voltage divider option 1*

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/svVYG.png)

<!-- End schematic -->

[Note that the thermistor needs to be connected to the A pin of your ESP8266.]

 *2. Voltage divider option 2*

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/a9gbQ.png)

<!-- End schematic -->

**Equation of voltage at node A**

For both case here is the voltage V_A seen at node A:

 *1. Voltage divider option 1*

`V_A = R_series *3.3 / (R_th + R_series)`

 *2. Voltage divider option 2*

`V_A = R_th *3.3 / (R_th + R_series)`

**Analysis of the variations of V_A with temperature**

Lets look at the difference between the 2 formulas above:

 *1. Voltage divider option 1*

The numerator is a constant with temperature while the denominator changes with T. You will get a strong variation.

 *2. Voltage divider option 2*

Both the numerator and denominator increase with temperature. You won't get a lot of variation on V_A with temperature. *You should avoid this configuration.*

**Analysis of the maximum allowed value of R_series**

The important consideration is that for your ESP module V_A cannot be higher than 1V.

 *1. Voltage divider option 1*

Increasing R_series will increase V_A so we compute a **maximum** value:
`1V = 3.3V*R_series_max/(R_series_max+10K)`

That gives you: `R_series_max = 4300Ohms`

 *2. Voltage divider option 2*

Increasing R_series will decrease V_A so we compute a **minimum** value:
`1V = 3.3V*10k/(R_series_min+10K)`

That gives you: `R_series_min = 23kOhms`

This is the reason why it was suggested to you using a 30k resistor in that case.

**Considerations about temperature measurement precision**

The voltage variation `∆V` on the node `A` of the ESP between temperature T1 and T2 can be computed as follow:
`∆V = 3.3 *1K/(1k + 10k + 30*T1) - 3.3 *1K/(1k +10k+ 30*T2)`

If we assume that the thermistor is 10K for ambient temperatures the baseline voltage measured on the `A` pin is:
`3.3V*1K/11k = 0.3V`

For a 0 to 1V 10bit DAC of the ESP8266 that is around: 2^10*0.3 = 307

A change of 10C would lead to a variation of voltage of:
`∆V = 0.3 - 3.3 *1K/(11k + 300) = 8mV ~8ADC code`

The equation of ∆T vs ∆V is not linear but for small variation of temperature with your current setup you get ~1ADC code per degree.

Depending of your application this might not be enough for you. As suggested in several comment you could:

 - Add more thermistors in parallel
 - Increase the 1K series resistor (but not too much or you will saturate the ADC).
 - Change the architecture of the measuring circuit (RC oscillator using the thermistor and interrupt counter in the ESP, 555 timer circuit loaded with the thermistor and interrupt counter, ...)
 - Or since you want to do humidity and temperature measurement why don't you get the BME280 module. It can be read over I2C and libraries are readily available to read it with the ESP8266.


body:
Re “the problem is somewhere in my code”, lots of places in the code have problems.

• The following loop does not add up readings; it takes a bunch of readings and throws them away, then doubles the last one.  For example, if the five readings in a row are 300, 400, 500, 600, and 100, `thermtemp` is 200 after the loop.  To see this, try it out – mentally simulate what the code does, writing down the value of `thermtemp` after each step.

    for (i=0; i<numsamples; i++) {
       thermtemp = analogRead(THERMISTORPIN);
       thermtemp += thermtemp;
       delay(10);
    }

• Your “voltage divider equation” (below) has a form like that shown in [the Adafruit tutorial](https://learn.adafruit.com/thermistor/using-a-thermistor), but because *your* `thermtemp` is declared as an `int` (vs Adafruit's `float`), integer division with truncation will be used, producing inaccuracy.

    thermtemp = thermresistor / (1023 / thermtemp - 1);

• Your Steinhart-Hart equation is miscoded.  At that step, the fixed resistor's value, `thermresistor`, is no longer relevant.  The relevant value is the ADC reading as converted to thermistor resistance.

• In your Steinhart-Hart misimplementation, `log(thermtemp / thermresistor)` takes log of zero because in integer arithmetic, `thermtemp / thermresistor` is zero.

• The expression `1 / (To + 273)` is zero in integer arithmetic.


body:
There are a few possible issues you're having:

First off, from what I understand, the ESP8266 ADC only reads up to 1V. If wired per the Arduino example you cited, and using 1K, you'll have VCC->1K->THERMISTOR->GND. At room temp the thermistor is 10K, so the voltage at the ADC will be 3.3*(10K/(1K+10K)), so pretty close to 3.3V. I don't know the behavior of the ADC when overrange, but I'd assume you'd just get 0xFFFF. You'll probably want >30K in series with the thermistor to get it into a usable range.

I also see a subtle error(I think) in your code:

    //read outside temp (otemp) data and convert to a temp
    for (i=0; i<numsamples; i++){
      thermtemp = analogRead(THERMISTORPIN);
      thermtemp += thermtemp;
      delay(10);
    }

Should be:

    //read outside temp (otemp) data and convert to a temp
    thermtemp = 0
    for (i=0; i<numsamples; i++){
      thermtemp += analogRead(THERMISTORPIN);
      delay(10);
    }

Otherwise thermtemp is just the last reading added to itself.

Lastly, I would probably make the part of the code that posts the result to a function and call it throughout your calculations of the temp, to see if anything weird happening.

Hope this helps.


message:
Arduino board is turning off when I connect to +5V

I am trying to set up an LCD screen without using a resistor or a potentiometer for an Arduino project. This is the LCD I am using: [Basic 20x4 Character LCD][1].

But when I connect to +5V on the Arduino board, my Arduino board turns off. This is how I have the LCD connected to the Arduino on a breadboard.

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

Connections:

LCD RS pin to digital pin 12

LCD Enable pin to digital pin 11

Data:

• LCD D4 pin to digital pin 5

• LCD D5 pin to digital pin 4

• LCD D6 pin to digital pin 3

• LCD D7 pin to digital pin 2

LCD R/W pin to ground

LCD VSS pin to ground

LCD Cathode pin to ground

LCD Anode pin to digital pin 9

LCD VCC pin to 5V

Code:

    // include the library code:
    include <LiquidCrystal.h>
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    void setup() {
      analogWrite(6,20);
      // set up the LCD's number of columns and rows:
      lcd.begin(20, 4);
      // Print a message to the LCD.
      lcd.print("hello, world!");
    }

    void loop() {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }

  [1]: https://www.sparkfun.com/products/256
  [2]: https://i.stack.imgur.com/vtHxq.jpg

body:
Try out this connection. It will helpful.

[![LCD Connection][1]][1]

  [1]: https://i.stack.imgur.com/H6MNR.jpg


body:
Looking at your picture, it seems that you're powering everything through a USB cable. USB 1.x and 2.0 can supply up to to 500 mA **AFTER** the port is enumerated, otherwise the current is limited to 100 mA.

A quick current consumption budget:

 - LED backlight of your LCD module: typ **240 mA**
 - Arduino Mega2560: min **70 mA**
 - MIDI shield: some **15-35 mA**

That's just 325-350 mA to begin with, and probably higher than that. It's still safely within the 500 mA limit, but as I said some computers will provide 500 mA only after successful enumeration of the device connected to the USB port.

My recommendation for you would be to power your Arduino + MIDI shield + LCD through a wall adapter > 7V. If it works, then the problem is your USB port being unable to supply the required current right from the start.


message:
Programming Micro controllers using Arduino ISP

Can I burn my Arduino Code into this:

http://www.microchip.com/wwwproducts/en/ATSAM3A4C

or something similar by just using just the Arduino ISP?

body:
Page does nog exist (404).

Also, to run actual Arduino code on it, you'll most likely have to port the Arduino library, if this hasn't been done before.

You may opt for something as easy as a teensy 3.2, they probably meet your requirements and work well in combination with Arduino.
Or fetch one of the newer Arduino models that have comparable microcontrollers

If you still want an M3 (without development board?) you'll be entering a somewhat advanced usecase, in which you probably don't even want to rely on or use Arduino. There are far better IDE's.


body: I don't know about that chip I think this one also can be done as some of the other chips can be programmed using the Arduino ISP  I think it can be even done for this one. This [one](http://www.ladyada.net/learn/avr/programming.html) uses an AVR ISP Programmer while we are using the Arduino one but as they have similar working It is maybe possible. For example this [one](http://www.ladyada.net/learn/avr/programming.html)


message:
Modbus RTU slave library

I want to use an Arduino Genuino Zero as a Modbus slave. I tried to search on google, and found [a library][1]. When I try using the library, I get a timeout error.

Can anyone tell me how to solve that error? Did anyone manage to get the Arduino Modbus RTU slave library working?

  [1]: https://www.dropbox.com/s/a277isxsxqurnpk/MODBUS.rar?dl=0

body:
I am unable to simulate and see the result right now; I hope if the library functions properly this might be a communication issue. I can add a one step debug for you to check and see what is happening.

Your device is acting as a Modbus RTU slave, So take another Arduino, make it act it like a master device, and see what response is coming from the slave device.
Here is a glimpse of code I used to make arduino as a master and see the response coming in Serial terminal.

        #include <SoftwareSerial.h>
        #define rxPin 2
        #define txPin 3

        #define RS485_pin 10
        //SoftwareSerial mySerial(rxPin, txPin);
        #define mySerial Serial1

        byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

        int data_count = 5;
        byte rcvdata[15];
        int param_value_int[7];

        void setup() {
          // put your setup code here, to run once:
        //mySerial.begin(19200,SERIAL_8E1);
        mySerial.begin(9600);
        Serial.begin(9600);
        delay(1000);
        pinMode(RS485_pin, OUTPUT);
        digitalWrite(RS485_pin,LOW);
        delay(100);
        }
        int count = 0;
        void loop() {

          if(count == 0) {
            Serial.println();
            send_data();
          }

          count++;

          while(mySerial.available()>0)
          {
            byte b=mySerial.read();
            delay(1);
            Serial.print(b,HEX);
            Serial.print(" ");
          }
          //Serial.println(count);
          while(Serial.available())
          {
            digitalWrite(RS485_pin,HIGH);
            byte a=Serial.read();
            delay(1);
            mySerial.print(a);
            digitalWrite(RS485_pin,LOW);
           // Serial.print(a);
          }

          delay(1000);
          //while(1);
        }

        void send_data() {
          Serial.println("send data");

          digitalWrite(RS485_pin,HIGH);
          delay(1);
          for(char i=0;i<8;i++){
            mySerial.write(test_data[i]);
            delay(1);
            Serial.print(test_data[i],HEX);
            Serial.print(" ");
          }

          Serial.println();
          digitalWrite(RS485_pin,LOW);
          delay(1);
        }

Here you can use Software Serial or normal Serial1 or Serial2 on devices like Mega. Make sure if it is RS485 based you have to toggle the RS485 read-write pin each time to enable and disable one feature at a time as RS 485 uses half-duplex communication.

In this case test_data[] uses Function code FC03 Read holding register. You can make your custom data. I am assuming you are familiar with all the types available.Still there is a great site [  [ link](http://www.simplymodbus.ca/FC03.htm) ] to look up to if you don't know the basics. The last two bytes are checksum. And there is an online checksum calculator available if you need also
 <https://www.lammertbies.nl/comm/info/crc-calculation.html>

In this way you can at least debug and share the result, so that we can help more.


body:
so i edited code your as below
    #define mySerial Serial1

    byte test_data[8] = {0x01,0x03,0x00,0x64,0x00,0x02,0x85,0xD4};

    int data_count = 5;

    void setup() {

    mySerial.begin(9600);
    Serial.begin(9600);
    delay(1000);

    }
    int count = 0;
    void loop() {

      if(count == 0) {
        Serial.println();
        send_data();
      }

      count++;

      while(mySerial.available()>0)
      {
        byte b=mySerial.read();
        delay(1);
        Serial.print(b,HEX);
        Serial.print(" ");
      }
      //Serial.println(count);
      while(Serial.available())
      {

        byte a=Serial.read();
        delay(1);
        mySerial.print(a);

      }

      delay(1000);

    }

    void send_data() {
      Serial.println("send data");

      delay(1);
      for(char i=0;i<8;i++){
        mySerial.write(test_data[i]);
        delay(1);
        Serial.print(test_data[i],HEX);
        Serial.print(" ");
      }

      Serial.println();

      delay(1);


message:
Sketch Memory and EEPROM

Since I'm running out of sketch memory, I've decided to use the 512 bytes of EEPROM memory by using `EEPROM.put(addr,variable)`. But every time I use this my sketch memory use in gradually increasing. What am I missing in writing data to EEPROM? Why is the sketch memory use increasing? I'm using Arduino Pro Mini.

body:
> What am i Missing in writing data to EEPROM ? Why is the Sketch memory getting increased ?

Reading and writing to EEPROM will increase program memory size. They are function calls. One way to reduce code is to read/write blocks instead of single bytes. Post some code and we can help you rewrite to something smaller. There are plenty of tricks.


message:
How to find if AC Appliance is on or off using ACS712 current Sensor

I am trying to get the status of appliance using current sensor. My Circuit looks like below image. I don't want to measure current. I just want to know whether appliance is on or off.

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

I am getting following readings when power turned on and off, I don't see any difference, I am not able to figure out whether the bulb is on or off.

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

  [1]: https://i.stack.imgur.com/XBPkh.png
  [2]: https://i.stack.imgur.com/pPZTL.png

Please help me to know the status of appliance/bulb.

PS. Please find my code below:

    /*
    Measuring AC Current Using ACS712
    www.circuits4you.com
    */
    const int sensorIn = A0;
    int mVperAmp = 185; // Use 100 for 20A Module and 66 for 30A Module

    double Voltage = 0;
    double VRMS = 0;
    double AmpsRMS = 0;

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

    void loop(){

     Voltage = getVPP();
     VRMS = (Voltage/2.0) *0.707;  //root 2 is 0.707
     AmpsRMS = (VRMS * 1000)/mVperAmp;
     Serial.print(AmpsRMS);
     Serial.println(" Amps RMS");
    }

    float getVPP()
    {
      float result;
      int readValue;             // value read from the sensor
      int maxValue = 0;          // store max value here
      int minValue = 1024;       // store min value here

       uint32_t start_time = millis();
       while((millis()-start_time) < 1000)  // sample for 1 Sec
       {
           readValue = analogRead(sensorIn);
           // see if you have a new maxValue
           if (readValue > maxValue)
           {
                /*record the maximum sensor value*/
               maxValue = readValue;
           }
           if (readValue < minValue)
           {
               /*record the minimum sensor value*/
               minValue = readValue;
           }
       }

       // Subtract min from max
       result = ((maxValue - minValue) * 5.0)/1024.0;

       return result;
     }

body:
The code looks like it would produce rather larger values than you are seeing, if it gets correct inputs from the sensor.  For that reason, you probably should carefully check your wiring.  Also, with a DVM, measure the sensor output voltage with the light on and with it off, to verify sensor operation.  If you measure ok sensor voltages but don't get good readings, your analog input pin may have a problem; you could try other analog input pins.

Note, when debugging an issue like this, it does not make sense to run a few numbers through five levels of processing before printing anything out.  You should at least add serial prints in `getVPP()`, and just before returning the result, print out `result`, `maxValue`, and `minValue`.

Note, fix the erroneous comment “//root 2 is 0.707”; the square root of 2 is about 1.414213562, while 1/√2 = (√2)/2 is about 0.707106781.


message:
Using N mosfet to switch ESC to BLDC phases

I have an ESC that powers 36v 3 phase BLDC motor. The ESC has limited functionality and can power motor only in one direction. If I switch manually two of the ESC to Motor phase connections, than the motor direction will change. Now, I want to do the same i.e. switching phase to phase connections with 4 power mosfets.

As in scheme, the blue ESC phase will be connected to Mosfet source and the drain will be connected to Motors yellow phase. The next mosfet will connect to ESC yellow at source and motor blue at drain.  Two other mosfets will connect blue to blue and yellow to yellow.

I won't  do the switching while motor is on so I assume it should be safe.

How can I connect MOSFET's gate to Arduino ?
I need no pwm just ON/OFF.

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

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

body:
This is covered fairly well in an [EDN.com “MOSFET pair makes simple SPDT switch”](http://www.edn.com/design/analog/4360638/MOSFET-pair-makes-simple-SPDT-switch) article.  You would use two of the SPDT circuits to make a DPDT.  Attach switch commons to yellow and blue, and attach the “switch points” of one circuit to motor yellow and blue, and those of the other vice versa.  Attach both control pins to one Arduino IO pin.  The picture below comes from the referenced article, which shows the circuit in use for a primary-power vs secondary-power application.   See the article for details.

[![details and overview of circuit][1]][1]

  [1]: https://i.stack.imgur.com/YSaGC.gif


message:
Trying to make arduino heart beat counter but couldn't understand code

I am trying to make an Arduino heart beat counter . I looked for some code online and found this code on arduino.cc forum but I couldn't understand working of the given code .. specifically these few lines of code:
The full code is given below:

    int sensorValue = 0;
    int sensorValue = 0;  // variable to store the value coming from the sensor
    int count = 0;
    unsigned long time1 = 0;  // store the initial time
    unsigned long time2;    // store the current time
    void setup() {
     // declare the ledPin as an OUTPUT:
     pinMode(sensorPin, INPUT);
     Serial.begin(9600);
    }

    void loop() {
     // read the value from the sensor:
     if (count == 0)
     {
      time1 = millis();
     }
     time2 = millis();
     sensorValue = analogRead(sensorPin);
     if (sensorValue > 156)
     {
      increment();
     }
     if (time2 >= time1 + 10000)
     {
      counter();
     }

    }

    void increment()
    {
     count++;
     while (sensorValue > 156)
     {
      Serial.print("Sensor value is greater than .75V\n");
     }
    }
    void counter()
    {
     count = count * 6;
     Serial.print("Heart beat is ");
     Serial.print(count);
     Serial.print(" per min\n");
     time1 = 0;
     time2 = 0;
     count = 0;
    }

Lines of code I'm not able to understand :

    if (count == 0)
    {
     time1 = millis();
    }
    time2 = millis();
    sensorValue = analogRead(sensorPin);
    if (sensorValue > 156)
    {
     increment();
    }
    if (time2 >= time1 + 10000)
    {
     counter();
    }

PS: the given code is in void loop(). in the beginning of the loop.

if u are not able to understand the code i'm leaving a link to the page:[this is the link][1]

i would be highly obliged if anyone could really help me soon. Thank u in advance :-)

  [1]: http://forum.arduino.cc/index.php?topic=155997.0

body:
I've reformatted you code to make it easier to read.

Looking just at the lines you don't understand.

  Line 1 stores the start time of this loop in the variable `time1` and stores the current time in the variable `time2`  these are going to be almost identical until the first heart beat is seen (which will increment count).

  Line 6 `sensorValue = analogRead(sensorPin);` reads the value from the sensor, it the reading is greater than some predetermined threshold (156) then it `increment()` the counter and waits until the value goes below 156.

  Line 11 checks to see if 10 seconds (10,000 mS) have elapsed since the loop started.  If they have then you get your reading via the function `counter()`

Does that make sense?

It would be a lot easier to understand if the original author had put comments in, but most people writing examples assume there code is so easy to understand they don't need to, don't fall into that trap when you become a great programmer! :)


message:
Power suply for MicroSD card breakout board

I'm developing a project and I need to connect to my Arduino Mini with a SD card breakout board. The problem is that I can't plug it directly to the Arduino since it is already powering some sensors and a BITalino, and I was told that it would, for some reason, be better to connect an external battery to the SD board.

My question is if i can supply this  [MICROSD CARD BREAKOUT BOARD+](https://www.adafruit.com/product/254) with a 3.7V battery, instead of a 5V.

Thank you!

Description:

* Onboard 5V->3V regulator provides 150mA for power-hungry cards
* 3V level shifting means you can use this with ease on either 3V or 5V systems

body:
Yes you can give power supply to MICROSD CARD BREAKOUT BOARD from a 3.7V battery It has Onboard LP98x Voltage regulator winch provide 3.3V regulated power supply.

Take reference from here [Schematic of MICROSD CARD BREAKOUT BOARD][1]

  [1]: https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/download


body:
> My question is if i can suply this MICROSD CARD BREAKOUT BOARD+ with a
> 3.7V battery, instead of a 5V.

Yes you can supply MICRO SD Card Breakout with 3.7 volt battery as it has onboard voltage regulator which will provide required voltage to the board.

> I was told that it would, for some reason, be better to connect an
> external battery to the SD board.

Because every sensor will take 3V - 5V as per its requirement. So some time Arduino can not be able to provide 3.3 - 3.5 volt to SD Card board and there could be no data logging or some wrong data logging to SD card. Thus it is advised to do such.


body:
You just need to bypass the Pro Mini regulator in order to avoid loading it too much, because the uSD Card board already has one.

Instead of connecting the uSD Card breakout board to the VCC pin, connect it to the RAW pin. Provided that your power source (3.7V battery? wall adapter?) can source enough current for the Pro Mini plus the uSD card board (something that's very likely), everything will be fine. No need to add any extra power source.

The regulators in those boards have very similar dropout characteristics (300-400mV).


body:
The "some reason [it would] be better to connect an external battery to the SD board" is that you need to make sure that the controller chip and SD card are getting enough power that it can write reliably.

To figure out whether and what kind of external power you need you start with the specifications. The first clue is in the [general product description](https://www.adafruit.com/product/254) to which you linked; it says that it has an "Onboard 5v->3v regulator" that "provides 150mA for power-hungry cards." This is a good start, but you'll see below that we'll need further information from a link on the [tutorial page](https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/download).

Linear power regulators give a fixed voltage output (in this case, 3 V) from a higher voltage input. To work properly they need an input voltage a bit higher than their output voltage; the minimum difference between the two is called the dropout voltage. From the [schematic](https://learn.adafruit.com/assets/35635) we can see that the board is using an LP298x regulator. A [datasheet](https://www.ti.com/lit/ds/symlink/lp2985-n.pdf) for a (hopefully typical) part from that series indicates that dropout voltage is 300 mV or 0.3 V. 3.7 V is considerably higher than 3 V + 0.3 V, so you're very likely to be ok in that respect with your external battery. (We also note here that the input voltage can range up to 16 V; we'll use this information later.)

The other thing you need to look at is whether you can supply enough current to the board and card that, under all reasonable circumstances, they can function properly. From the original description you know the board uses a 150 mA regulator which means that the designers expect that you'd never need more than that. (And if you do, the card isn't going to get it anyway.)

For simplicity it's easiest just go go with being able to provide 150 mA or more on the regulator's input, regardless of voltage. (In theory you can supply less power on input if you're giving it a higher voltage, because P = EI, but it's not generally worth the time and effort to go there for a hobbyist project.)

Batteries have a discharge rates known as [C rates](https://en.wikipedia.org/wiki/Battery_(electricity)#C_rate), and unless you know what you're doing (I don't :-)) your best bet is to stay well within the standard discharge rate as specified by the manufacturer. Adafruit sells a typical [3.7v 1200mAh Lithium Ion Polymer Battery](https://www.adafruit.com/products/258); looking at its [datasheet](https://cdn-shop.adafruit.com/datasheets/503562+1200mah.pdf) we see that the standard discharge current is 0.5 C5 A, which is 0.5 * 1200 mAh / 1 h = 600 mA, plenty more than you need. So if you're using that battery you'd be safe. (I started out by looking at the [500 mAh battery](https://www.adafruit.com/products/1578) which has a  0.2 C5 A = 100 mA standard discharge rate; my guess is that that's fine because the maximum discharge rate is 1 C5 A, but this has implications on battery capacity and the like so I'd ask someone first.)

But it would be nice to use your existing power supply for the card rather than use a separate battery, I'm sure. Your best bet for that is the [suggestion from  Enric Blanco](https://arduino.stackexchange.com/a/36581/31794): use an external power supply that can deliver enough current to both the Arduino Pro regulator and the SD Card breakout board regulator that they'll both be happy.

Sadly, Adafruit's [Ardiuno Mini product page](https://www.arduino.cc/en/Main/ArduinoBoardMini) gives no indication of current requirements. However, a quick look at the [v5 schematic](https://www.arduino.cc/en/Main/ArduinoBoardMini) we can see that it's using an LP2985AIM5-5.0 regulator and a web search turns up a [product page](https://www.digikey.com/product-detail/en/texas-instruments/LP2985AIM5-5.0/LP2985AIM5-5.0CT-ND/3701530) for this that says it's rated at 150 mA.

Add the 150 mA for the Arduino Mini to the 150 mA for the SD card board and you can figure that any external power supply that is giving more than 300 mA at the minimum 7 V input voltage specified for the Arduino Mini should be just fine. The 7 V should also be ok for the SD card board regulator since, even if it's a slightly different model from our spec. sheet, it's unlikely to have a maximum voltage hugely below the 16 V for that part. But you could check the exact part your board is using if you're worried.


message:
Will an ATmega2560 board be faster than a Uno for hard real-time data logging?

I am designing a hard real-time data logger. The Uno is a bit marginal in processing speed.

a) Would it be **faster** if I changed to an ATmega2560?

b) On the datasheet, ATMEGA2560 has 135 instructions; it is **4 instructions more** than the ATmega328p.

What are the extra 4 instructions for?

Are they involved in floating point maths?

c) How to select compiler option for **fastest code** at the expense of bigger code size, longer compilation time, etc.?

The system is:

1. Receive data from wireless transceiver chip via hardware SPI port.

2. A good portion of the time is spent on data calculation using floating point maths.

3. Output processed data on serial port (then to PC via the Arduino board USB to Serial chip).

4. Code and RAM size is not an issue, Uno has plenty space left.

body:
No, it will not be any faster. The extra instructions are to access the extra flash memory of the 2560. Instructions like `EIJMP` - *Extended* indirect jump, `EICALL` - *Extended* indirect call, etc.

The compiler option `-O3` optimises the most, but there are other options you can enable, such as `-funroll-loops` which will cause major code bloat but speed things up.  Read the GCC manual pages to boggle at all the millions of optimisation options.

Or... use a faster chip, like an ARM or PIC32.


body:
Use the newest Arduino IDE, because some time ago the 'lto' option was added which is a major optimization for both speed and size.
It is possible to test a few compiler options with the #pragma. Try for example these at the top of the sketch:

    #pragma GCC optimize("-O3")
    #pragma GCC optimize("-ffast-math")

The 'fast-math' is dangerous, be careful with it.

The Arduino Zero and Arduino Due are faster but not a lot faster, because they are not fast with analogRead() and with floating point calculations.

A common mistake is that someone asks for a faster Arduino board, but uses a sketch and libraries with a lot of delay() in it. That won't be any faster with an other Arduino board. Have a good look at your code and at the source code of the used libraries.

Have you tried increasing the baudrate for outgoing data ? If that baudrate is slow, the whole sketch is slowed down because the Serial functions will wait until they can write the data into the Serial buffer. The fastest "baudrate" can be achieved with the Leonardo, Micro and Pro Micro boards. They transmit the data directly onto the USB bus without using the baudrate.


body: In the `platform.txt` file found in `~/Arduino15/packages/arduino/hardware/avr/1.6.17` or similar, you can change the three instances of `-Os` with `-Ofast`. The size of the code can increase dramatically though.


body:
They have very nearly the same instruction set and the same execution speed, so there will be no increase there. If your project spends a significant amount of time in floating-point arithmetic, replacing it with fixed point arithmetic will give you a noticeable speed up. If a few calculations are executed repeatedly (which is typical), you can get most of the advantage by rewriting only that part.

In a nutshell, fixed point arithmetic is what the computer does already, but with an assumed binary point (just like a decimal point) always to the right of the least significant bit. Fixed point arithmetic uses the built-in arithmetic, but you assume the binary point to be wherever you need it, keep track of it during multiplies and divides, and make sure you keep the intermediate results from overflowing.

Search for Fixed Point Arithmetic and you'll find out a whole lot more.


message:
Getting Bluetooth addresses of connected devices via Arduino Uno?

I want to find all the Bluetooth addresses of connected devices using  an HC-05/HC-06 Bluetooth module and an Arduino. I can't find any code related to this. Basically I need the addresses to put in an array. Is it possible to do this with an HC-05 or 06?

body:
The HC-05 has an AT command, `AT+BIND?`, that will tell you which slave device it is connected with currently. Since you can connect to one device only at the same time, your array is going to be a very short one.

`AT+INQ` will provide you with a list of nearby devices, to which it ***can*** connect.


body:
You just have to send the above Bluetooth command via serial port to your Bluetooth module using print command.

For example `yourserial.print("AT+BIND?");` OR `yourserial.print("AT+INQ");` if you are using SoftwareSerial. Otherwise just use `Serial.print("AT+BIND?");` OR `Serial.print("AT+INQ");` when using Rx/Tx pins. That will do the job.


message:
Error trying to compile an example from newly added Arduino menu library

I added the ArduinoMenu library https://github.com/neu-rah/ArduinoMenu and when I try to compile one of the examples, I get following error.

> Using library LiquidCrystal at version 1.0.5 in folder: C:\Program Files (x86)\Arduino\libraries\LiquidCrystal exit status 1 Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this?

body:
I think you have to add your library in the library folder. Below is the path of that folder. It will help you.

`C:\Program Files (x86)\Arduino\libraries`


body:
Can you compile the LCD example for that board?
just to make sure you have LiquidCrystal library ok.

Then tell us what was the example? There are hardware specific examples.

Also try to compile the serial menu example, just to make sure that ArduinoMenu library is ok for your board.


message:
How to restart a counter in a program using a push button in a LDR Tripwire setup

So, trying to configure this code so that when I push the button, the person counter will go to zero and just as it goes, the counter will increase when the LDR will get tripped and again when the button is pressed, the counter will go to 0.

    #include <LiquidCrystal.h>

    int laser=8;
    int pushbutton=12;
    int flag=0;
    int myCounter = 0;
    LiquidCrystal lcd(7,6,5,4,3);

    void setup()
    {
        pinMode(laser,OUTPUT); pinMode(pushbutton,INPUT);
        lcd.begin(16, 2);
        lcd.print("Person Counter:"); lcd.setCursor(0,1);
        lcd.print(0);
    }

    void loop()
    {
        lcd.setCursor(0, 1);
        digitalWrite(laser,HIGH);

        if(analogRead(A0) < 600) //A0= LDR
        {
            flag = 1;
        }

        if(analogRead(A0) > 600 && flag == 1)
        {
            myCounter++;
            delay(200);
            lcd.print(myCounter);
            delay(20);
            flag=0;
        }
    }

body:
Try out this code. I made some modification and also comment out that things.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(7, 6, 5, 4, 3);

    int laser = 8;
    int pushbutton = 12;
    int flag = 0;
    int myCounter = 0;

    void setup()
    {
      pinMode(laser,OUTPUT);
      pinMode(pushbutton,INPUT_PULLUP); // Provide pull-up

      lcd.begin(16, 2);
      lcd.print("Person Counter:");
      lcd.setCursor(0,1);
      lcd.print(0);
    }

    void loop()
    {
      lcd.setCursor(0, 1);
      digitalWrite(laser,HIGH);

      if(analogRead(A0) < 600) //A0= LDR
      {
        flag = 1;
      }

      if(analogRead(A0) > 600 && flag == 1)
      {
        myCounter++;
        delay(200);
        lcd.print(myCounter);
        delay(20);
        flag = 0;
      }

      if(digitalRead(pushbutton) == LOW) // When button pressed
      {
        myCounter = 0; // Set counter to 0
      }
    }


message:
Can I share the VCC (5V) on my Arduino Pro mini with multiple modules?

Right now I am onto a new project where I am building an obstacle avoiding landrobot.

I use an arduino pro mini as my board and I have a few hc-sr04 sensors here at home. The problem I have right now is that many pins is occupied with other modules, motors and bluetooth.

So right now on my Pro Mini the VCC is occupied by my BLE device and I was wondering if there is a possibility to solder a few wires together so that my BLE device share the same VCC with 4 other hc-sr04 modules? I do this regularly with the GND where I solder multiple wires together and share the GND across different modules which works fine.

I have soldered a wire looking like this:
[![enter image description here][1]][1]

The idea is to power the arduino itself through the "RAW" pin. I have a power distribution board that connects to my battery/motor and the VIN pin of the PDB goes to the "RAW".

I try to avoid a breadboard to decrease the size as much as possible so if it were to be possible then that would be the optimal solution for this project.

Something I am also wondering is if it is possible to use these hc-sr04 on both the analog pins and also the digital pins. I do not have enough space to fit all the sensor cables on the digital pins but if I use the analog pins also then they all would fit. Is this possible? Each HC-sr04 has two cables that needs to be inserted (Trig and echo) and right now I have 3, 4 free and all the analog pins 0, 1, 2, 3, 4, 5 which is enough to fit them all.

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

  [1]: https://i.stack.imgur.com/8fDtH.jpg
  [2]: https://i.stack.imgur.com/QgCHn.jpg

body:
To be frank you can use even your analog pins as digital pins as the analog pins are also digital pins but they are more enhanced

If you use a common Vcc you may not have enough power left for your board and when you share your ground it doesn't matter a lot as it is the -ve lead of your power  source and you may use an external power source


body:
Yes, you can do that as long as the total current draw of the modules you attach to VCC doesn't exceed the on-board regulator maximum current output.

The Arduino Pro Mini has a MIC5205 regulator capable of [delivering up to 150 mA][1], which is quite low if you plan to attach many modules to its output. So you should look through your modules datasheets and find out the total current draw, including the Pro Mini board itself, and check that against the 150 mA limit.

According to the [HC-SR04 datasheet][2], each module draws 15 mA. The Arduino Pro Mini itself draws about [about 20 mA][3]. The [BLE module peak current consumption][4] is 12.5 mA at active RX and 11 mA at active TX, so lets say 25 mA peak current draw for the BLE module.

Everything adds up to a worst case 105 mA peak current draw, within the maximum 150 mA limit. So **it should be fine**, but I would avoid connecting much more modules to that VCC rail.

[![MIC5205 on board the Arduino Pro Mini][5]][5]

**ADDED according to your additional question:**

If you run out of digital I/O pins, you can use the analog pins as digital pins if needed.

Additional note (thanks go to @jwpat7 for pointing this out in the comments):

However, this is true only of A0–A5 on most Uno and Nano Micro Arduinos, and not true of A6, A7 (except on -PB MCU models like ATmega168PB and ATmega328PB, where A6, A7 can be used as digital pins).

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
  [2]: https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf
  [3]: http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/
  [4]: http://www.nordicsemi.com/eng/Products/Bluetooth-low-energy/nRF8001
  [5]: https://i.stack.imgur.com/y6dK9.jpg