body:
This is probably a bit advanced but...

You could use a base class and pointers to the derived LED and Buzzer classes to reduce you loop function to a loop.  You won't gain much at this level, but as you add more objects, such as the flashing headlights and mirror lights, maybe even a rear facing message board you will make life easier for your self.

    /*
    Jacob & Dad’s Police Car light and sounds
    */

    class BaseOutputObject
    {
    protected:
     int Pin;
    public:
     BaseOutputObject(const int& pin)
      : Pin(pin)
     {
      pinMode(Pin, OUTPUT);
     }
     virtual void Update()
     {
     }
    };

    class FlashingLED : public BaseOutputObject
    {
     long OnTime;
     long OffTime;
     int ledState;
     unsigned long previousMillis;
    public:
     FlashingLED(const int& pin, const long& on, const long& off, const bool& startLow = true)
      : BaseOutputObject(pin)      // Call base class constructor
      , OnTime(on)       // Use initialisers rather than assignments
      , OffTime(off)
      , ledState(startLow ? LOW : HIGH)
      , previousMillis(0)
     {
     }

     void Update()
     {
      // check to see if it's time to change the state of the LED
      const unsigned long currentMillis = millis();   // Make it const because it won't change within this call of the function.

      if (currentMillis - previousMillis >= OnTime)
      {
       ledState = (ledState == LOW ? HIGH : LOW); // Toggle the state.
       previousMillis = currentMillis;  // Remember the time
       digitalWrite(Pin, ledState);  // Update the actual LED
      }
     }
    };

    class Buzzer : public BaseOutputObject
    {
     float SinValue;
     int ToneValue;
    public:
     Buzzer(const int& pin)
      : BaseOutputObject(pin)
      , SinValue(0.0f)  // Always initialise variables, in case you change the code later.
      , ToneValue(0)
     {
     }

     void Update()
     {
      for (int x = 0; x < 360; x++)
      {
       SinValue = sin(x * (PI / 180));
       ToneValue = 2000 + SinValue * 500;
       tone(Pin, ToneValue);
       delay(1);
      }
     }

    };

    // The objects could be declared dynamically, but thats not a great idea on embedded systems.
    FlashingLED ledOne(5, 100, 400);
    FlashingLED ledTwo(7, 100, 400);
    Buzzer buzzer(9);
    enum { LED_ONE, LED_TWO, BUZZER, MaxObjects };
    // Have to have pointers to the objects to allow you to cast them down to the base objects.
    BaseOutputObject* objects[MaxObjects] = {  &ledOne, &ledTwo, &buzzer};

    void setup()
    {
    }

    void loop()
    {
     for (int index = 0; index < MaxObjects; ++index)
     {
      objects[index]->Update();
     }
    }


sender: user

message:
Segmentation fault at Serial.begin()

I try to communicate with my Arduino clone (Elegoo Uno R3) from Arduino IDE (v1.8.4 installed by `dnf` from repos) at Fedora 27. Compiling and upload of normal example code works well. However, as I try to start any serial communication (e.g. for debug), the compiler fails returning following segfault:

    "/usr/bin/avr-gcc"  -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_407070/AnalogReadSerial.ino.elf" "/tmp/arduino_build_407070/sketch/AnalogReadSerial.ino.cpp.o" "/tmp/arduino_build_407070/../arduino_cache_983152/core/core_arduino_avr_uno_1621df717313d057c92202babd71649a.a" "-L/tmp/arduino_build_407070" -lm
    lto1: internal compiler error: Segmentation fault
    Please submit a full bug report,
    with preprocessed source if appropriate.
    See <https://bugzilla.redhat.com/> for instructions.
    lto-wrapper: fatal error: /usr/bin/avr-gcc returned 1 exit status
    compilation terminated.
    /usr/lib/gcc/avr/6.3.0/../../../../avr/bin/ld: error: lto-wrapper failed
    collect2: error: ld returned 1 exit status
    exit status 1
    Error compiling for board Arduino/Genuino Uno.

I found similar issue here https://github.com/sudar/Arduino-Makefile/issues/486 However, that solution deals with Arduino-Makefile software that is little bit complex for me.

I would appreciate any help either how to solve the segfault itself, or how to easily use Arduino-Makefile (I would like to compile from Arduino IDE or any user-friendly IDE).

sender: assistant

body: There's a new version of the avr-gcc package that's currently available in the updates-testing repo that should fix the problem. You can install/update it by enabling the updates-testing repo, or grabbing the rpm from koji (https://koji.fedoraproject.org/koji/buildinfo?buildID=1013122)


message:
How to add additional sensors [Arduino]

I am new to Arduino.
I have currently connected a FSR sensor to the TOUT pin of ESP WROOM-02.
How do I add additional FSR sensor to ESP WROOM-02?
[![enter image description here][1]][1]

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

body:
An [FSR][1] (Force Sensing Resistor) varies in resistance as force or pressure is applied.  Most often such devices are connected to the positive power rail and the ADC input of a embedded micro controller.  At the same time a second known fixed resistor is connected to the opposite power rail (ground) and the same ADC input.  This forms a resistor divider network where the ADC in the embedded micro controller can measure the force applied to the FSR by measuring the voltage of the resistor divider.

To measure 2 or more FSRs using the same ADC input, consider connecting one lead of each FSR to a digital input/output pin of the embedded micro controller. Then connecting the other lead of each FSR to the ADC input.  To measure the force on the 1st FSR, configure the connected digital pin as a high ouput using software.  So that all the other FSRs do not influence the measurement, configure all the other digital pins to have high impedance.  Often this can be done by programming these other digital pins as inputs.  Cycle through all FSRs in a similar fashion using software.

  [1]: https://en.wikipedia.org/wiki/Force-sensing_resistor


message:
Multiple LED on arduino

I am currently trying to control multiple LEDs with one Arduino Mega 2560 board. However, since each LED needs 3.6 volts and the board only supplies 5V I cannot make more than one light up.

Is there a way to increase to output voltage of the Arduino board ? Or perhaps of using arduino to turn on or off a battery that has a high enough voltage to power multiple LED ?

Thanks for your help

body: If you connect them in parallel instead of series you'll be able to turn them on and off with 3.6 volts (5 volts through an appropriate dropping resistor), assuming the Arduino can supply the current. [Here's](https://www.ledsupply.com/blog/wiring-leds-correctly-series-parallel-circuits-explained/) a general explanation of the difference.


body:
Each pin on any Arduino (with some exceptions) can only handle 40mA MAX. Even the 5V and similar output sources can't handle more than 600mA, So I suggest you use them to power a MOSFET or Darlington to connect them in appropriate series and parallel connection counts.

Both the above transistors can handle high voltage, but you need to choose ones that correspond to a voltage that an Arduino can provide.

This is the most robust method if you want all the LEDs to light up at the same time. However for array addressable LEDs you might need extra BJTs coupled with resistors for each led, maybe along with two decided that would be appropriate for your application.


message:
Combining codes for 3 sensors

I am trying to combine codes for my 3 sensors: GSR, Pulse sensor, and ECG but I keep getting errors. I have a poor background in coding. I have the 3 codes separately and I'm not the one who wrote them.
Here are the new Sketch after Combining the loops and the setups.I didn't get any error after uploading and verifying but I am not getting values in my Serial Monitor

Combined sketch:

    <!-- language-all: lang-cpp -->

    #include <Wire.h>
    #include "rgb_lcd.h"
    #define ANALOG_IN 2   // analog input pin to display
    #define OUTPUT_PIN 10 // test signal output pin
    #define PULSE_MS 250  // pulse width in ms

    int PulseSensorPurplePin = 1;        // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
    int LED13 = 13;   //  The on-board Arduion LED
    int Signal;                // holds the incoming raw data. Signal value can range from 0-1024
    int Threshold = 550;            // Determine which Signal to "count as a beat", and which to ingore.

    const int BUZZER=3;
        const int GSR=A0;
        int threshold=0;
        int sensorValue;
        rgb_lcd lcd;

    long ms;        // timer in ms
    int out = HIGH;     // output level

    void setup() {
       pinMode(LED13,OUTPUT);         // pin that will blink to your heartbeat!
       Serial.begin(9600);         // Set's up Serial Communication at certain speed.

       long sum=0;
          //VERIFY VALUE
          lcd.begin(16, 2);
          Serial.begin(9600);
          pinMode(BUZZER,OUTPUT);
          digitalWrite(BUZZER,LOW);
          delay(1000);
    //VERIFY VALUE
          for(int i=0;i<500;i++)
          {
          sensorValue=analogRead(GSR);
          sum += sensorValue;
          delay(5);
          }
          threshold = sum/500;
           Serial.print("threshold =");
           Serial.println(threshold);

           pinMode(OUTPUT_PIN, OUTPUT);    // set output pin mode
           Serial.begin(19200);        // initiate serial communication
           digitalWrite(OUTPUT_PIN, out);  // set initial digital output
           ms = millis();          // query current time (in ms)

    }

    void loop() {
      Signal = analogRead(PulseSensorPurplePin);  // Read the PulseSensor's value.
                                                  // Assign this value to the "Signal" variable.

       Serial.println(Signal);                    // Send the Signal value to Serial Plotter.

       if(Signal > Threshold){                          // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
         digitalWrite(LED13,HIGH);
       } else {
         digitalWrite(LED13,LOW);                //  Else, the sigal must be below "550", so "turn-off" this LED.
       }

    delay(100);

       int temp;
          sensorValue=analogRead(GSR);
          Serial.print("sensorValue=");
          Serial.println(sensorValue);
          lcd.setCursor(0, 0);
          lcd.print("GSR Value: ");
          lcd.print(sensorValue);
          temp = threshold - sensorValue;
          if(abs(temp)>50)
          {
            sensorValue=analogRead(GSR);
            temp = threshold - sensorValue;
            if(abs(temp)>50){
           digitalWrite(BUZZER,HIGH);
            Serial.println("YES!");
            delay(3000);
            digitalWrite(BUZZER,LOW);
            delay(1000);}
          }

          int val = analogRead(ANALOG_IN);    // read voltage at input pin
      Serial.write( 0xff );         // write value to serial port
      Serial.write( (val >> 8) & 0xff );
      Serial.write( val & 0xff );

      if (millis() >= ms+PULSE_MS) {    // check if pulse width has elapsed
        ms = millis();            // query current time (in ms)
        out = !out;             // invert output value
        digitalWrite(OUTPUT_PIN, out);    // update digital output
      }
    }

body:
In general:

- There can be only one setup, in most cases you can put the code from all three setup's together, but checkout the code does not interfere, i.e. does not use the same pins. In that case, change the pin numbers if possible (and change the circuit accordingly).

- For the loops it can be more tricky:
  - Check how often each loop should be called. If one loop costs e.g. 500 ms that means the other loops will be called less often, which can affect the precision or even good readout of the sensor.
  - If all loops are relatively small and the duration do not matter, you can just call them after each other (rename the loops and call them one by one).
  - If there is a time constraint, than split the lengthy loop in a small part, and call it whenever needed. There is no clear rule for this.

What you can try is:

- Check for reach loop how long it takes
- Than for each loop add a delay with same time as the other loops, thus:
  - Test the duration (average) of loop 1, than of loop 2, than of loop 3. Assume loop1 takes 100, loop2 200 and loop3 300 ms.
  - Test loop1 without calling loop2 and loop3, but just add the delay (200+300=500 ms).
  - Check if it works, if so, it means you can call the other loops without problems.
  - Do the same for loop2 (with 100+300ms delay) and loop3 (100+200ms).
  - If all loops work correctly, than you can call the loop1, loop2, loop3 in sequence.
  - If not, you have to call the loop(s) that do not work either more often or in a different way.


message:
ESP8266 disconnects after few hours

My system looks like this:

ESP8266 is connected to Arduino Uno (2, 3 pins) and a relay's data input to Arduino's pin 12 and power for relay is provided from another source.

Arduino gets data from server and switches on/off relay according to that signal. This system works perfectly for few hours and then suddenly crashes. In my WiFi console I have:

> wlan0: STA 2c:3a:e8:4e:bf:70 WPA: pairwise key handshake completed
> (RSN) wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0:
> AP-STA-DISCONNECTED 2c:3a:e8:4e:bf:70 wlan0: STA 2c:3a:e8:4e:bf:70
> IEEE 802.11: disassociated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11:
> associated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated
> wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0: STA
> 2c:3a:e8:4e:bf:70 IEEE 802.11: associated wlan0: AP-STA-CONNECTED
> 2c:3a:e8:4e:bf:70

I have read [this Arduino question][1], but circuit diagram similar to that one. I get power from my PC to run Arduino.

This is my Arduino code :

<!-- language: lang-cpp -->

    #include "WiFiEsp.h"

    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(2, 3); // RX, TX
    #endif

    char ssid[] = "RPi";            // your network SSID (name)
    char pass[] = "raspberry";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    char server[] = "192.168.50.1";

    unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds
    int testLED = 12;
    // Initialize the Ethernet client object
    WiFiEspClient client;

    void setup()
    {
      pinMode(testLED, OUTPUT);
      // initialize serial for debugging
      Serial.begin(9600);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);

      // check for the presence of the shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue
        while (true);
      }

      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }

      Serial.println("You're connected to the network");

      //printWifiStatus();
    }

    void loop()
    {
      // if there's incoming data from the net connection send it out the serial port
      // this is for debugging purposes only
      while (client.available()) {
        char c = client.read();
        //code to run relay
        if (c == '#')
        {
          while (client.available() == 0) { } // Do nothing while we wait for the next value

          // reading the second charactor
          c = client.read();
          if (c == '1') {
            Serial.println("On");
            digitalWrite(testLED, HIGH);
            delay(600000);
          }
          else if (c == '0') {
            Serial.println("Off");
            digitalWrite(testLED, LOW);
            delay(600000);
          } //end of C cheking if-else
        }  //end of first charactor # if
        //end of replay code
      }
      // if 10 seconds have passed since your last connection,
      // then connect again and send data
      if (millis() - lastConnectionTime > postingInterval) {
        httpRequest();
      }
    }

    // this method makes a HTTP connection to the server
    void httpRequest()
    {
      Serial.println();

      // close any connection before send a new request
      // this will free the socket on the WiFi shield
      client.stop();

      // if there's a successful connection
      if (client.connect(server, 80)) {
        Serial.println("Connecting...");

        // send the HTTP PUT request
        client.println(F("GET /simple.txt HTTP/1.1"));
        client.println(F("Host: localhost"));
        client.println("Connection: close");
        client.println();
        // note the time that the connection was made
        lastConnectionTime = millis();
      }
      else {
        WiFi.begin(ssid, pass);
        Serial.println("Reconnecting again");
      }
    }

  [1]: https://arduino.stackexchange.com/questions/43641/esp8266-disconnects-after-relay-switch

body: As long as I know you need at least 170mA to power the esp8266 also you need 100-200mA for the arduino and 100mA for the relay so I recommend to use a 1A power supply and solder some capacitors on the 5V and 3.3V rails. Also if your Wi-Fi is giving a ip address that is limited for certain time for example 1-2 hours you need to expand that time for your needs.If it disconnects the esp will lose its IP address and try to recover for example on my NODE MCU it works well for weeks. It also depends on your library (I am using ESP8266WiFi.h). Anyway I recommend to try the WebServer example for testing if the issue is in your code.


body:
After quite long research I found the solution for my problem.

I did some changed power connection to ESP-8266.

ESP 8266    ---------  Arduino Uno

`Vcc`       --------->  3.3v

`CH_PD`     --------->  5v divided into 3.3v using resistors

`RX`        --------->  PIN-2 via 3.3v regulator.

After this configuration, my system was working perfectly for days. Thanks for the all suggestions given.


body: After four months of searching - Just use 3.3 V with 1.5 or 2 A and everything will work correctly.


message:
Store values in array

I'm trying to implement the "BNO055 9 Axes Motion Shield".
There is an existing Arduino sketch [GitHub][1] that reads out the Euler data, I changed it a bit to print out quaternion data.

    #include "NAxisMotion.h"        //Contains the bridge code between the API and the Arduino Environment
    #include <Wire.h>

    NAxisMotion mySensor;         //Object that for the sensor
    unsigned long lastStreamTime = 0;     //To store the last streamed time stamp
    const int streamPeriod = 20;          //To stream at 50Hz without using additional timers (time period(ms) =1000/frequency(Hz))

    void setup() //This code is executed once
    {
      //Peripheral Initialization
      Serial.begin(115200);           //Initialize the Serial Port to view information on the Serial Monitor
      I2C.begin();                    //Initialize I2C communication to the let the library communicate with the sensor.
      //Sensor Initialization
      mySensor.initSensor();          //The I2C Address can be changed here inside this function in the library
      mySensor.setOperationMode(OPERATION_MODE_NDOF);   //Can be configured to other operation modes as desired
      mySensor.setUpdateMode(MANUAL); //The default is AUTO. Changing to MANUAL requires calling the relevant update functions prior to calling the read functions
      //Setting to MANUAL requires fewer reads to the sensor
    }

    void loop() //This code is looped forever
    {
      if ((millis() - lastStreamTime) >= streamPeriod)
      {
        lastStreamTime = millis();
        mySensor.updateQuat();        //Update the Quat data into the structure of the object
        mySensor.updateCalibStatus();  //Update the Calibration Status

        Serial.print("Time: ");
        Serial.print(lastStreamTime);
        Serial.print("ms ");

        Serial.print(" W: ");
        Serial.print(mySensor.readQuatW());

        Serial.print(" X: ");
        Serial.print(mySensor.readQuatX());

        Serial.print(" Y: ");
        Serial.print(mySensor.readQuatY());

        Serial.print(" Z: ");
        Serial.print(mySensor.readQuatZ());

        Serial.println();
      }
    }

Here is a snippet of the "NAxisMotion.h" header file:

        /*******************************************************************************************
     *Description: This function is used to return the w-axis of the quaternion data
     *Input Parameters: None
     *Return Parameter:
     * int16_t: W-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
     *******************************************************************************************/
     int16_t readQuatW(void);

     /*******************************************************************************************
     *Description: This function is used to return the x-axis of the quaternion data
     *Input Parameters: None
     *Return Parameter:
     * int16_t: X-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
     *******************************************************************************************/
     int16_t readQuatX(void);

     /*******************************************************************************************
     *Description: This function is used to return the y-axis of the quaternion data
     *Input Parameters: None
     *Return Parameter:
     * int16_t: Y-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
     *******************************************************************************************/
     int16_t readQuatY(void);

     /*******************************************************************************************
     *Description: This function is used to return the z-axis of the quaternion data
     *Input Parameters: None
     *Return Parameter:
     * int16_t: Z-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
     *******************************************************************************************/
        int16_t readQuatZ(void);

I understand that the output data type is signed integer, but what syntax do I need to use to store them in an array?
Because it seems the only way to access them is through "mySensor.readQuatX()"

  [1]: https://github.com/arduino-org/brackets-arduino/blob/master/libraries/NAxesMotion/Euler/Euler.ino

body:
If I understand correctly you want to store a number of signed integers in an array.  Arrays have fixed sizes so you need to know the number of values you want to store.

    // Global declarations
    enum QIndex {WAxis, XAxis, YAxi, ZAxis, MaxIndex};
    int16_t qData[MaxValues] = {0};

    // Code inside loop
    qData[WAxis] = readQuatW();
    qData[XAxis] = readQuatX();
    qData[YAxis] = readQuatY();
    qData[ZAxis] = readQuatZ();

    // Pass the array  of values to another function with the declaration
    // void SomeFunction (int *ar);
    // or
    // void SomeFunction (int ar[]);
    SomeFunction (qData);

Is that what you mean?


message:
How to find how much data in the transmit buffer?

How do you find how many bytes are currently waiting in the transmit buffer?

I'm trying to diagnose a weird serial disconnection problem with an Arduino Uno and a rosserial node. It works fine for 10-20 minutes, and then mysteriously losing connection. At first, I thought the Arduino was running out of memory, but I'm able to use the MemoryFree library to log available memory, and it never drops below 9051 bytes.

I now want to make sure the problem isn't because the serial buffer is overflowing, from the Arduino trying to send too much data.

body:
> I now want to make sure the problem isn't because the serial buffer is
> overflowing, from the Arduino trying to send too much data.

If you are using the software serial Arduino library there is a way to [check for overflow][1].

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerialOverflow


body:
If you really want to know (not that it would do you any good) you can use the `Serial.availableForWrite()` function (which returns how much space is left in the buffer) and subtract the returned value from the size of the buffer.

    int used = 64 - Serial.availableForWrite(); // Assuming a 64 byte buffer

I haven't tested it, but you may be able to use `SERIAL_TX_BUFFER_SIZE` instead of the `64` to make it properly portable.

    int used = SERIAL_TX_BUFFER_SIZE - Serial.availableForWrite(); // Possibly portable


message:
ESP8266 PHP Web Server

I need my ESP8266 web server to load my website files with `.php` extensions. So far I managed to load `.htm` `.css` and `.js` files from my SD card, but when I upload PHP files on my SD card, they won't run. How can I do that?

body:
It sounds like you are trying to put a PHP file on an SD card that the ESP8266 will serve itself.

This is not possible, as no one has, and probably never will, port PHP to the Espressif 8266 platform.

Your device can serve `.htm` `.css` and `.js` files because it's just a matter of streaming the file content to the client. But PHP requires that an application on the server run the PHP code, and then send the resulting output to the client.


message:
Why Ethernet webclient fails to initiate?

I use the Ethernet shield with an Uno and create a web client. If I put a delay like one second for initialization it works fine. However if I wait for it in a while loop (like waiting for the serial, and as mentioned in Arduino docs) it never gets out of the loop that means the client instance is null.

I found this method on Arduino website in an example code:

<!-- language-all: lang-js -->

    while(!client) { ; } // waiting to get ready
Here's the code; if I uncomment it will stay there. Also the same with providing the MAC argument only.

    #include <SPI.h>
    #include <Ethernet.h>

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
    char server[] = "www.google.com";    // name address for Google (using DNS)

    IPAddress ip(192, 168, 1, 213);

    EthernetClient client;

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

      Ethernet.begin(mac, ip);
      delay(1000);
      //while(!client){ ; }
      Serial.println(Ethernet.localIP());
    }

body:
What you write is not a function but a variable. And the variable will not change its value (unless you have some interrupt and it is a global variable).

so you need to change 'client' to some function you want to call, probably 'client.xxx()' where xxx is the name of the function you want to call (possibly with parameters).


body:
Your `while(!client){ ; }` line can never do anything useful.

It is used to wait for a client socket to connect to a remote port. You aren't connecting to a remote port (that `client` object is doing *nothing*), so how it can never succeed.

It's like saying "Do nothing, and tell me when you're done".

I don't know what you hope to achieve with that line of code...


message:
Arduino + SIM808 HTTP GET POST headers

I am trying to get working SIM808 with Arduino. Can GET and POST GPRS HTTP request but only what cames on it's just body from server side `{"error":true,"message":"Unauthorized"}`
but I need header as it brings cookie for session.

    +CREG: 0,1

    AT+SAPBR=3,1,"Contype","GPRS"

    OK

    AT+SAPBR=3,1,"APN","giffgaff.com"

    OK

    AT+SAPBR=3,1,"USER","giffgaff"

    OK

    AT+SAPBR=3,1,"PWD",""

    OK

    AT+SAPBR=1,1

    AT+SAPBR=2,1

    +SAPBR: 1,1,"xx.xxx.xxx.xxx"

    OK
    AT+HTTPINIT

    OK
    AT+HTTPPARA="CID",1

    OK
    AT+HTTPPARA="URL","http://www.xxx.co.uk/index.php"

    OK
    AT+HTTPPARA="UA","MH Tracker"

    OK
    AT+HTTPPARA="CONTENT","Content-Length: 42"

    OK
    AT+HTTPPARA="CONTENT","Content-Type: application/x-www-form-urlencoded"

    OK
    AT+HTTPSSL=0

    OK
    AT+HTTPDATA=41,30000

    pass=xxxx&user=xxxx&action=xxxx

    OK

    AT+HTTPACTION=1

    OK

    +HTTPACTION: 1,401,39

    AT+HTTPREAD

    +HTTPREAD: 39

    {"error":true,"message":"Unauthorized"}

    OK

    AT+HTTPTERM

I got some results, but with error, looks like my code have some junk characters

any advice

POST /client/index.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: www.mhprojects.co.uk
Content-Length: 41

pass=xxx6&user=xxx&action=xxx

SEND OK
HTTP/1.1 400 Bad Request
Date: Thu, 01 Feb 2018 00:38:56 GMT
Server: Apache
Content-Length: 357
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>400 Bad Request</title>

Bad Request

Your browser sent a request that this server could not understand.

Additionally, a 500 Internal Server Error
error was encountered while trying to use an ErrorDocument to handle the request.

Arduino code

    char data[350]="POST /client/index.php HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nHost: www.mhprojects.co.uk\r\nContent-Length: 41\r\n\r\npass=xxx&user=xxx&action=xxx";
int PowerOn = 12;//Power on pin
int Reset = 11;//Reset pin
char aux_str[50];
//////////////
void setup() {

  pinMode(PowerOn, OUTPUT);
  pinMode(Reset, OUTPUT);
  Serial.begin(9600);// UART baud rate

  power_on();

  Serial.println(F("Powering ON"));
  Serial.println();
  Serial.println(F("Connecting to the network..."));

  while( send_command("AT+CREG?", "+CREG: 0,1", 1000)== 0 );

}

/////////////
void loop() {

char buffer[200];

if (send_command("AT+CIPMUX=0", "OK", 2000) == 1)// Selects Single-connection mode
  {
  if (send_command("AT+CSTT=\"giffgaff.com\",\"giffgaff\",\"\"", "OK", 2000) == 1)// Sets the APN, user name and password
    {
      if (send_command("AT+CIICR", "OK", 10000) == 1)// Brings Up Wireless Connection
        {
          if (send_command("AT+CIFSR", ".", 3000) == 1)// Gets Local IP Address
            {
              if (send_command("AT+CIPSTART=\"TCP\",\"www.mhprojects.co.uk\",\"80\"","CONNECT OK", 10000) == 1)// Opens a TCP socket
                  {
                     sprintf(aux_str,"AT+CIPSEND=%d", strlen(data));
                     if (send_command(aux_str, ">", 1000) == 1) {

                     send_command(data, "SEND OK", 1000);

                     while (true)  {

                     read_UART_buffer(buffer,sizeof(buffer), 0);

                     }
                     Serial.println(buffer);
                     }
                                }
                                else
                               {
                             Serial.println(F("Error setup TCP connection\r\n\r\n"));
                           }
                        }
                      else
                    {
                  Serial.println(F("Error getting the IP address\r\n\r\n"));
                }
              }
             else
           {
         Serial.println(F("Error bring up wireless connection\r\n\r\n"));
        }
      }
    else
  {
Serial.print(F("Error setting the APN\r\n\r\n"));
    }
      }
        else
        {
          Serial.print(F("Error setting the single connection\r\n\r\n"));
         }

    send_command("AT+CIPCLOSE", "CLOSE OK", 1000);

    send_command("AT+CIPSHUT", "SHUT OK", 1000);

}

////////////////
void power_on() {

        // power on pulse
        digitalWrite(PowerOn,LOW);
        delay(500);
        digitalWrite(PowerOn,HIGH);
        delay(3000);
        digitalWrite(PowerOn,LOW);
        delay(3000);
}

///////////////
void reset()  {
  digitalWrite(Reset,LOW);
  delay(500);
  digitalWrite(Reset,HIGH);
  delay(3000);
  digitalWrite(PowerOn,LOW);
  delay(500);
}

///////////////////////////////////////////////////////////////////////////////////
int8_t send_command(char* ATcommand, char* expected_answer, unsigned int timeout) {

  uint8_t x = 0,  answer = 0;
  char response[50];
  unsigned long previous;

  memset(response, '\0', 50);    // Initialice the string

  delay(100);

  while ( Serial.available() > 0) Serial.read();   // Clean the input buffer

    Serial.println();
    Serial.println();
    Serial.println(ATcommand);    // Send the AT command

  x = 0;
  previous = millis();

  // this loop waits for the answer
  do {
    if (Serial.available() != 0) {  // if there are data in the UART input buffer, reads it and checks for the asnwer
      response[x] = Serial.read();
      Serial.print(response[x]);
      x++;
      if (strstr(response, expected_answer) != NULL)    // check if the desired answer (OK) is in the response of the module
      {
        answer = 1;
      }
    }
  }

  while ((answer == 0) && ((millis() - previous) < timeout));   // Waits for the asnwer with time out

  return answer;
  while ( Serial.available() > 0) Serial.read();   // Clean the input buffer
}

////////////////////////////////////////////////////////////
void read_UART_buffer(char *buffer,int count, unsigned int timeOut) {
  int i = 0;
  unsigned long timerStart;
  timerStart = millis();

 while(1) {
  while  (Serial.available()!=0){
    Serial.write(Serial.read());
    char c = Serial.read();
    buffer[i++] = c;

  }
  //buffer[i]='\0';
    if((unsigned long) (millis() - timerStart)  > timeOut * 1000UL) {
            break;
        }
 }
}

body:
Are you sure the Content length is 41? Doesn't seem like it, make sure it's the same length as your message body.

This depends from server to server, but I think you should also put a CRLF after your message body.


message:
(Neopixels) How to keep the pixels of the same colour despite increasing brightness?

I've been doing a fade function for the NeoPixels. However, the moment I have maximum brightness for the pixels, *I noticed there 2 colours even though in my function I have only specified one colour*.

Some strips are one colour and the others are another colour. I
specified the colour to be blue for the strips however many strips are blue and the strips nearer the end are green (but closer to a blue-green colour).

Is there any way to keep the colour even when the brightness changes? I've read somewhere online a different colour is seen with different brightness levels i.e. `setPixelColor(brightness, r,g,b)`.

I've also tried FastLED library and followed documentation. However, the lights are not doing what it has said in the codes, I've tried `leds[i].fadeLightBy(200)` and it has given me no result.

My code for the fade function (edited from http://moving-rainbow.readthedocs.io/en/latest/guide/fade-in-and-out/):

<!-- language-all: lang-cpp -->

    void fade(uint32_t color) {
      for (int i = 0; i < 255; i++) {
        for (int q = 0; q < strip.numPixels(); q++) {
          strip.setPixelColor(q, Wheel((color) & 255));
        }
        strip.setBrightness(i);
        strip.show();
      }

      //decreasing brightness
      for (int l = 255; l > 255; l--) {
        for (int p = 0; p < strip.numPixels(); p++) {
          strip.setPixelColor(p, Wheel((color) & 255));
        }
        strip.setBrightness(l);
        strip.show();
      }
    }

The method "Wheel" is from the Arduino Neopixel strandtest example.

    uint32_t Wheel(byte WheelPos) {
      WheelPos = 255 - WheelPos;
      if (WheelPos < 85) {
        return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
      }
      if (WheelPos < 170) {
        WheelPos -= 85;
        return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
      }
      WheelPos -= 170;
      return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
    }

Any advice on how I should go about doing it?

body:
I have some simple NeoPixel fading going on in this example sketch:

    /*
     *
     * NeoPixels demo - fades colours (in array) up and down
     *
     */

    #include <SPI.h>
    #include <NeoPixels_SPI.h>

    const unsigned int PIXELS = 8; // Number of pixels in the string

    void setup()
      {
      ledsetup();
      } // end of setup

    float patterns [] [3] = {
      { 1, 0, 0 },  // red
      { 0, 1, 0 },  // green
      { 0, 0, 1 },  // blue
      { 1, 1, 0 },  // yellow
      { 1, 0, 1 },  // magenta
      { 0, 1, 1 },  // cyan
      { 1, 1, 1 },  // white
      { 160.0 / 256, 82.0 / 256, 45.0 / 256 },  // sienna
      { 46.0 / 256, 139.0 / 256, 87.0 / 256 },  // sea green

    };

    // number of items in an array
    #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

    void loop()
      {

      for (byte i = 0; i < ARRAY_SIZE (patterns); i++)
        {
        // fade up
        for (byte m = 0; m < 100; m++)
          {
          showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
          delay (10);
          } // end of for

        // fade down
        for (byte m = 100; m > 0; m--)
          {
          showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
          delay (10);
          } // end of for
        } // end of for each array item

      } // end of loop

This is using the simple [NeoPixel library](http://www.gammon.com.au/forum/?id=13357) that I wrote using the SPI hardware. The library with the exact code above is [available here](https://github.com/nickgammon/NeoPixels_SPI).

Basically the fading is done by multiplying the floating-point values for the R/G/B values by a constant from 0 to 100 (you could make it 0 to 255).

Since the colours themselves are expressed in the range 0 .. 1 then the result of the multiplication would be 0 to 255. To my naked eye the colours seem true at all brightnesses.

To use the library on your Uno just connect +5V, Gnd, and the data pin is MOSI (D11 on the Uno).


message:
Log vs linear pots and the arduino

I have noticed that when I used a log pot from a guitar amp I found, it gives janky results when using it in a motor PWM sketch, but if I use it in a fade sketch, it works. why does log pots give sketchy results when using them in a PWM control sketch, like when using the `map()` function?

body:
There are two associated issues here that underly your problem.

Firstly, with a log pot, you get a period of very small changes in resistance followed by a period of massive changes:

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

(* a "commercial" log pot is how log pots are usually manufactured - two linear traces of different resistances back to back).

So when turning you get "not much ... not much ... not much ... lots ... even more ... full".

Now couple that with how a motor works. A motor has a "stall current", which is higher than the "run current" (especially the "unloaded" run current).  This is the minimum amount of current required to overcome the inertia of the motor and start it spinning. This is, in effect, a lower threshold on the PWM value that you need to exceed before the motor will begin moving (once it's started moving you can go a little below that threshold and it will still move).

With a linear pot it's easy to get to that threshold and stay around it, increasing slowly above it, etc.  However, as you can imagine looking at the curve of the log pot above, if the "flatter" area of the pot is below the stall current threshold of the motor, the motor will do nothing until you are well into the sharper up-turn of the curve.  The effect of this is you will go from "stopped" to "quite fast" in one jump. It's very very hard to get even close to the stall current threshold.

For instance, if your motor needs a minimum of 30% duty cycle to start it running, that's about a 160 degree turn on the log pot above, compared to just 70 degrees of a linear pot, and the rest of the log pot's PWM range is compressed into a tight space.

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


message:
Confusion with two Serial.begin() function calls

Why are there two Serial.begin() function calls? What does that signify?
   Here is the minimal code i am working on:

    void setup() {
          Serial.begin(115200);
          Serial.begin(9600);
          Serial.println("Pressure Sensor Test"); Serial.println("");
        }

Here is the full Code:

    #include <SimpleDHT.h>
    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BMP085_U.h>

    int pinDHT11 = 2;
    Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

    void displaySensorDetails(void)
    {
      sensor_t sensor;
      bmp.getSensor(&sensor);
      Serial.println("------------------------");
      Serial.print  ("Sensor:       "); Serial.println(sensor.name);
      Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
      Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
      Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" hPa");
      Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" hPa");
      Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" hPa");
      Serial.println("----------SDNx real time scientific data---------------");
      Serial.println("");
      delay(500);
    }

    void setup() {
      Serial.begin(115200);
      Serial.begin(9600);
      Serial.println("Pressure Sensor Test"); Serial.println("");
      if(!bmp.begin())
      {
        /* There was a problem detecting the BMP085 ... check your connections */
        Serial.print("  Ooops, no BMP085 detected ... Check your circuit some errors are there!");
        while(1);
      }

      /* Display some basic information on this sensor */
      displaySensorDetails();

    }

    void loop() {

      Serial.println("===========");
      Serial.println("Sample DHT11...");

      byte temperature = 0;
      byte humidity = 0;
      byte data[40] = {0};
      if (simple_dht11_read(pinDHT11, &temperature, &humidity, data)) {
        Serial.print("Read DHT11 failed");
        return;
      }

      Serial.print("Sample RAW Bits: ");
      simple_dht11_serial_print(data);

      Serial.print("SDNx says you are genius and every thing is OK: ");
      Serial.print((int)temperature); Serial.print(" *C, ");
      Serial.print((int)humidity); Serial.println(" %");

      // DHT11 sampling rate is 1HZ.
      delay(1000);

      sensors_event_t event;
      bmp.getEvent(&event);

      if (event.pressure)
      {

        Serial.print("Pressure:    ");
        Serial.print(event.pressure);
        Serial.println(" hPa");

        float temperature;
        bmp.getTemperature(&temperature);
        Serial.print("Temperature: ");
        Serial.print(temperature);
        Serial.println(" C");

        float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
        Serial.print("Altitude:    ");
        Serial.print(bmp.pressureToAltitude(seaLevelPressure,
                                            event.pressure));
        Serial.println(" m");
        Serial.println("");
      }
      else
      {
        Serial.println("Sensor error");
      }
      delay(1000);
    }

body:
It looks like a mistake, as Chris says.  I can't tell you what will happen but my **guess** is it will work at 9600.

I would recommend that you delete one of the lines to avoid further confusion.


message:
Submit data from HTML form to ESP8266

I need to submit HTML form from my remote website to my ESP8266 server using `POST` method. I'm looking for something like that :

        <form action="my esp8266 IP" method="POST">
            <input type="text" name="foo" value="go">
            <input type="submit">
        </form>

Can I use IP address in `action` attribute?
How can I detect and print received data on ESP8266 side?

body:
> Can I use IP address in action attribute?

Sure, if your ESP8266 is either on the same internal (behind a NAT router) subnet as your web server, or your ESP8266 has a public IP address.

> How can I detect and print received data on ESP8266 side?

By parsing the data as it comes in through the socket.

If your ESP8266 is on your home network and your website is out on the internet somewhere you will have to arrange some form of port forwarding through your router (outside the scope of this site) and have some way of your website tracking your (most likely dynamic) home IP address. Again, outside the scope of this site.

It is much more common to use protocols such as MQTT or another RESTful API to have your ESP8266 check in with a remote server to request updated data and instructions, rather than a web server blindly pushing the information directly to the ESP8266.  This is because:

* Putting your ESP8266 directly (or indirectly through port forwarding) on the internet is a security nightmare, and
* Putting all the pieces of the jigsaw together to make it work reliably is not trivial.


message:
Arduino doesn't boot unless I short USB pin 1-2 (VCC/Data -)

I've made my own AVR programmer with an Arduino Nano V3 clone. It has been working fine, but yesterday I was trying to program a faulty board that pulled too much current. Was powering via USB and my OSX laptop told me it had disabled it due to pulling too much power.

After that I couldn't power it anymore, not even from a simple phone charger. I thought I had burnt something, but when testing with a DVM I accidentally shorted pin 1 and 2 of the USB connection:

1 - (red) VDC / plus / +5V

2 - (white) Data -

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

Then it boots up and is powered as long as I have them connected. Without it wont start with any usb connection, laptop or phone charger. Just to show what I mean:

https://photos.app.goo.gl/rtFj6bp3j4SbuYKr1

Why is this and is there something I can do to save this Nano - it seems to be working fine when usb is shorted like this…

Would hate to have to build up another one while waiting for a new programmer from China :)

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

body:
When you plug the board in, the computer enumerates it. The normal device descriptor (IIRC) requests 50mA. If you are (as you most likely are) drawing more than that then the computer is quite within its rights to turn it off.

By shorting those pins you are preventing it from enumerating, so the computer doesn't know the requested amount, so it assumes (probably) 500mA.

You can achieve the same effect by using a cable with no data wires in it.


body:
It's possible you've blown the voltage regulator.  If you happen to have a source of those, like another dead Nano, you can try replacing it to see if that works.

Shorting the +5 to data is likely going to destroy your computers USB controller, so please quit.


message:
variable doesnt have a type name

Why can't i assign the value to a variable  outside the function?

    void setup(){}
    int a;
    a=12;   //  WHY IS THIS GIVING ME ERROR
    void loop(){
    }
Why the line `a=12` gives me an error?
Thanks!

body:
> a=12;   //  WHY IS THIS GIVING ME ERROR

Because you can't do assignments like that outside of a function.

You can, though, create *and* assign the variable at the same time:

    int a = 12;

That is a declaration of the variable, whereas

    a = 12;

is a procedural statement. Procedural statements cannot be executed in the global scope. They can only be executed inside a function during the execution of the program (the global scope never gets executed).


message:
Extending EEPROM life

I'm working on some software using an Uno (ATmega328P). I have a stage byte that can be 1 of 5 values (0-4) in my code and it will increase by 1 every 2.5 hours. If I lose power I need to ensure that on wake up the stage is the same as it was at the time of power loss, so each time the stage is updated I save it to EEPROM.

To ensure the EEPROM lasts as long as possible I want to write some code that uses more than a single byte which I continually erase and write to. I was wondering if there is any library to do this or if my idea below would work?

I currently don't need to use the EEPROM for anything else so to extend the EEPROM life I was going to section of 1 quarter of it (0-255 bytes) for saving this value. Each time I change the stage I will write 3 bytes to EEPROM which will be:

 - An index byte (used to shift addresses I write to).
 - A stage byte (the stage I need to store).
 - A count byte (the amount of times I have wrote the stage at the current index).

To begin with the index will be written to byte 0 in the EEPROM, the stage to byte 1 and the count to byte 2.

My plan is to allow the stage to be written to byte 1 250 times, then clear the count and shift the index to 3. This will in turn move the bytes that the stage and count are being written to to 4 and 5. I will do this until the index reaches the end of the 255 bytes and then return the index to 0. So in total I should be able to shift 85 times.

Each byte has 100,000 erase/write cycles so this means I can pass through bytes 0-255 400 times, writing the stage 250 times each pass. So instead of having 100K writes I would have about 8.5 million writes.

This is my first idea and I realize there is also some waste in the way I do it. I haven't worked with EEPROM much and I was just hoping for some advice as I'm sure I could be going at this completely wrong.

body:
You can load spread by saving the current value ORred 0x80 or 0x00.

When writing you write to the next memory location and when it wraps you take the other value to OR with.

The values in the eeprom will be

    [{0x00|value},{0x00|value},{0x00|value},...,{0x00|value},{0x00|value},{0x00|value},{0x80|value},{0x80|value},{0x80|value},...,{0x80|value},{0x80|value}]

or

    [{0x80|value},{0x80|value},{0x80|value},...,{0x80|value},{0x80|value},{0x80|value},{0x00|value},{0x00|value},{0x00|value},...,{0x00|value},{0x00|value}]

Then you read the first and last byte and if the upper bit is equal you take the last value.

If they are not equal you binary search until to the position changes, the most recent value will be the one right before the change.


body:
There are many ways of achieving what you want. The method I would use would be to use pairs of bytes, but split up differently.

For each 16 bits I would have 13 for a counter, and 3 for a value. The counter, being 13 bits, can count from 0 - 2^13-1, or 0 - 8191.  The 3 value bits can store 0 - 2^3-1, or 0 - 7, which is fine for your 0-4 value.

The size of the counter is important, since it is more than double the number of 16-bit pairs in the EEPROM.  Assuming a 1kB EEPROM that's 512 16-bit values, so you want more than 1024 values available in your counter (if you wanted to change the split to store a larger number...).

The algorithm is simple:

1. Read through the EEPROM looking at the next counter value. If the count increases by more than 1 the last value read is the current one.
2. If the count goes from 8191 to 0 then keep going, you have just looped is all.
3. Increase the counter by 1 and write to the EEPROM addresses where the count jumped by more than 1.

For example, if you have:

    78 1
    79 2
    80 3
    8191 7
    8191 7
    8191 7

you know that the space after 80 hasn't been used (0xFFFF is split as 0x1FFF and 0x7) so you write "81 4" to it.

Another:

    8190 2
    8191 3
    0 4
    1 0
    2 1
    7283 3
    7284 4
    7285 0

The jump from 8191 to 0 is just a wrap around and can be considered sequential. However the jump from 2 to 7283 isn't sequential, so you can overwrite entry 7283 with "3 2".

When you write, if you are going past the end of the EEPROM's memory space, you just loop back round to the start again.

This gives you 512 * 100,000 writes, or 51.2m writes.


body: Also, check that the values you want to write are actually changing. No point in erasing and writing a value that is already there. And you save 3.3 ms by not having to do the write.


message:
Sharing serial Rx to read a push button on ESP8266-01

I'd like to know if it's possible, and if so how to use the serial Rx pin in a shared way to read a push button?

I've seen people using it in sort of a dedicated way but my idea is to use it dynamically. Which means it would stay as a standard Rx pin, with a push button sharing it. So the question is, what would happen if the push button was pressed? Would it be possible to detect it from the Rx stream?

body:
I have experimented with my NodeMCU (ESP8266-12F, but the core chip is the same ESP8266EX).

First, the theory: UART is a asynchronous serial protocol. It has a configuration which consits of the baud rate (bits per second), parity bit (enabled or not) and number of stop bits (between 1-2). A common configuration is "9600N1", meaning 9600 bits per second, **n**o parity bit, 1 stop bit.

If you want to trasmit the bitstring `0101 0101` with no parity, 1 stop bit, the RX line voltage will be:

[![uart1][1]][1]

RX line idles in high state (for us: 3.3V). Transmission is started by the start bit, which means that the line is pulled LOW. Then, the bits are transmitted LSB to MSB, followed by parity (if enable) and the stop bits.

I wrote the sketch

    #include <Arduino.h>

    void setup() {
     //use 300 Baud, lol
     Serial.begin(300);
    }

    void loop() {
     if(Serial.available()) {
      char readChar = (char) Serial.read();
      Serial.println("Read char: " + String(readChar) + " hex " + String((int)readChar, HEX));
     }
    }

When transmitting a normal "A" (binary: `0100 0001`) over serial, it looks like this in a logic analyzer:

[![uart_1][2]][2]

When I connected a pulled-up button the RX line and press, the signal goes as

[![uart2][3]][3]

As one can see, the analyzer sees the pushing down of the button as a start bit, but the timing is way of. The line is pulled back to high much later. The time slot for the stop bit (which must be *1*) was missed, so the logic analyzer displays "FRAMING ERROR". But the UART circuit inside the ESP8266 doesn't seem to care. It reads this as the transmission of a byte of the value "0x00".

Serial output: `Read char:  hex 0`

So, in response to the question "what would happen the push button was pressed?" we can say: At this speed of 300 baud (lowest possible setting), the UART received a bogus transmission but still reads it as an incomming `0x00` byte. However, depending on the bouncing of the signal due to the button presses, other received byte values might well be possible. You could be able to de-bounce the button to make the signal more stable, timing wise.

Anyway, you should not make a push button act as a crude UART transmitter if it isn't the absolute last possible solution. Depending on your application, you might be able to use the solution from [this question][4] and switch the function of the TXD0 and RXD0 to GPIO ([more info][5]). If you know exactly when to expect a button push, switch the pins to GPIO mode before and poll the status of the button (or install an interrupt).

However, as a bottom line: If you have no idea when the button will be pushed, then you will be fundamentally unable to distinguish the cause of the RX line falling low at the time the transition happens. It could be the transmission of some actual data (maybe also the zero-byte), but it could have also been the button.

A I²C GPIO port expander like the MCP23017 ([link][6]) would make much more sense, especially if you already have an I2C bus. There are also SPI devices available for this.

  [1]: https://i.stack.imgur.com/0SFpa.png
  [2]: https://i.stack.imgur.com/6QiTC.png
  [3]: https://i.stack.imgur.com/TJwc2.png
  [4]: https://arduino.stackexchange.com/questions/29938/how-to-i-make-the-tx-and-rx-pins-on-an-esp-8266-01-into-gpio-pins
  [5]: http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations#uart_pins
  [6]: http://www.instructables.com/id/Adding-an-MCP23017-IO-Extender-to-Arduino-or-ESP82/


message:
Templated class: How to create instance and work with it?

I have created a class like this:

    #ifndef MyList_h
    #define MyList_h

    #include "Arduino.h"

    template <typename T>
    class MyList {
    public:
      MyList(void);
      ~MyList(void);

      void addItem(T* item);

      //more stuff

    };

    #endif

And implementation is like this:

    #include "Arduino.h"
    #include "MyList.h"

    template<typename T> MyList<T>::MyList(void) {
      // constructor implementation here
    }

    template<typename T> MyList<T>::~MyList(void) {
      // desctructor implementation here
    }

    template<typename T> void MyList<T>::addItem(T* item) {
      // function implementation here
    }

    // ...more stuff

In my .ino Sketch I'm doing this (found this solution in a C++ example):

    #include "MyList.h"
    MyList<word>* list = new MyList<word>(); // global scope
    //... more stuff

But when compiling, Arduino IDE complains:

> Test.ino:5: undefined reference to `MyList<unsigned
> int>::MyList()'

I googled a bit and found this alternative way for creating the instance:

    ArrayList<word>* list;

Then there's no error, just compiles file. BUT as soon as I want to use this instance (=adding code) like this:

    list->addItem(i);

compiler complains again:

> Test.ino:25: undefined reference to `MyList<unsigned
> int>::addItem(unsigned int*)'

What's wrong? Why is this reference undefined?

I tried another way:

    ArrayList<word> list; // again global scope

But then the compiler also tells me:

> Test.ino:5: undefined reference to `MyList<unsigned
> int>::MyList()' /tmp/ccp8qmCz.ltrans0.ltrans.o: In function
> `_GLOBAL__sub_D_list':
> /....../Test.ino:5:
> undefined reference to `MyList<unsigned int>::~MyList()'

So, how can I create an instance of my class that uses a template?

----
Environment: Arduino IDE 1.8.3 (I know, I could update...) + Arduino Nano Board.

body:
I think I found the solution:

According to: https://stackoverflow.com/questions/8752837/undefined-reference-to-template-class-constructor

--> Put all implementation in .h file. That's it. No more compler complains, code runs fine.

I think I have to dig deeper into c/c++ development ...


message:
Arduino Uno and Arduino Yun software. Which version of the IDE works with both best?

I have been working with Unos and just started working with Yun. I have 1.86 currently installed but the Yun starts up saying to use 1.5.6-r2 Beta IDE. Should I uninstall 1.8.6 and install 1.5.6-r2?

Thanks for your help.

Lisa

body:
The Yun startup was written when the normal IDE didn't support the yun, so you had to use a release candidate of a future version.

Those days are long gone.

Always use the latest version of the IDE.


message:
Bluesmirf Mate Silver (RN-42) enter command mode when in HID mode

I am having problems getting the Bluesmirf Mate Silver (RN-42) into command mode once I have switched to HID mode. I have bought a second new Bluesmirf Mate Silver to confirm my issue.

I soldered the Bluesmirf and connecting to Arduino Uno. I used the ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.

I then entered the following commands in command mode (leaving out the comments):

    SM,5   // Mode = 5, (any) Auto reconnect
    SA,2   // Authentication Mode 2 (SSP, "just works" mode)
    S-,myName  // // Set BT Name, This short name with no spaces is Picked up ok on windows
    S~,6   // Enable HID on reboot
    R,1    // Reboot to lock in perameters

Next I use a PC and pair with the bluetooth ‘keyboard’ I have created above. I am able to use the Bluetooth and Arduino sketches to write into notepad on the bluetooth connected PC.

However now I cannot get back into command mode to make changes to the Bluesmirf config. Trying to use the example code above I can see ‘`$$$U,9600,N`’ typed into notepad on the connected PC each time I load the sketch, rather than being used to enter command mode.

How do I get back into command mode after HID mode has been triggered.

body:
I believe that the problem is caused by the mode I entered. According to the [datasheet][1] on pg 10 Auto-Connect Master Mode (SM,3) enters high speed mode and this `connection cannot be broken via commands or software break characters`.
It goes on to explain that both Auto-Connect DTR Mode (SM,4) and Auto-Connect ANY Mode (SM,5) (which I used) function like Auto-Connect Master Mode (SM,3), so I guess that in these modes the `$$$` escape characters cannot be used to enter command mode either.

I was able to resolve this by performing a hard factory reset on the Bluesmirf Mate Silver (RN-42). I previously tried following a couple of you-tube tutorials that weren't very clear and didn't have any success. I looked at the [instructions in this thread][2] titled 'Factory Reset the RN-41 or RN-42' to get me on the right lines.

This worked for me:

 1. Connect the Bluesmirf Mate Silver GND pin to GND and disconnected all other pins
 2. Connect a wire to 3.3v on Ardunio
 3. Load the Ardunio with an empty sketch, and keep it powered on
 4. Touch the 3.3v wire repeatedly (3+ times) to the GPIO4/PIO4 connection hole on the Bluesmirf. This is a third of the way down one edge of the board.
 5. Factory reset should now be complete - note I didn't see any indication lights during this process.

Then I could wire up the Bluesmirf as normal and use ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.

  [1]: https://cdn.sparkfun.com/datasheets/Wireless/Bluetooth/bluetooth_cr_UG-v1.0r.pdf
  [2]: https://learn.sparkfun.com/tutorials/using-the-bluesmirf/discuss#comment-55a587adce395f07568b4567


message:
Output works on UNO Pin 13, but not on 2?

I am experimenting with IR receive and transmit (basically I want my IOT to be able to turn on the TV, satellite receiver, and set the channel - yes, I am really that lazy).

I can receive and record the remote codes, and I can transmit the codes to an IR LED.

Now for the puzzle. I originally had my IR LED on Pin 13, but to clean things up I moved the output to pin 2 and changed the pin assignment in the sketch. Now it doesn't work. My phone camera shows that the IR LED is pulsing as before, but the appliance code is not working. Moving back to pin 13 and it works again.

So, what could be different between pins 13 or 2? I know that Pin 13 has the built-in LED but since I am setting it to output that shouldn't make a difference.

I am bit-banging to create the 38kHz pulses to the IR LED, so I am wondering if there is a latency difference from pins 2 and 13?

The sketch, since I know someone will ask for it:

<!-- language: c++ -->

    int IRledPin =  13;
    int buttonPin = 4;

    void setup()   {
      pinMode(IRledPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      digitalWrite(buttonPin, HIGH); // pullup
      Serial.begin(115200);
    }

    void loop()
    {
      if (! digitalRead(buttonPin)) {
        // button down
        Serial.println("Sending IR signal");
        SendCode();
      }
    }

    // This procedure sends a 38KHz pulse to the IRledPin
    // for a # of microseconds.
    void pulseIR(long microsecs) {
      // we'll count down from the number of microseconds we are told to wait

      cli();  // this turns off any background interrupts
      while (microsecs > 0) {
        // 38 kHz is about 13 microseconds high and 13 microseconds low
        digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds
        delayMicroseconds(10);         // hang out for 10 microseconds
        digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
        delayMicroseconds(10);         // hang out for 10 microseconds
        // so 26 microseconds altogether

        microsecs -= 26;
      }
      sei();  // this turns interrupts back on
    }

    void SendCode() {
      // This is the code for my FIOS FF
    Serial.println("FIOS- FFwd");
      pulseIR(9220);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(22320);
      pulseIR(9200);
      delayMicroseconds(2240);
      pulseIR(540);
      delayMicroseconds(24664);
      pulseIR(9220);
      delayMicroseconds(2240);
      pulseIR(540);
      delayMicroseconds(24684);
      pulseIR(9200);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(24684);
      pulseIR(9200);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(24664);
      pulseIR(9220);
      delayMicroseconds(2260);
      pulseIR(520);

    }

body:
 <!-- language: lang-c++ -->

    void SendCode() {
      // This is the code for my FIOS FF
      Serial.println("FIOS- FFwd");
      pulseIR(9220);
      delayMicroseconds(4540);

Personally I would be putting the `cli()` around everything in `SendCode` (apart from the Serial.println) because the serial print will cause interrupts, and they could occur between successive function calls there.

I checked your code using IDE 1.6.9 and got this pulse width for pin 2:

[![Pulse width on pin 2][1]][1]

And this pulse width on pin 13:

[![Pulse width on pin 13][2]][2]

You'll notice they are virtually identical and that neither show a frequency of 38 kHz. The measured period of 30.71 µs gives a frequency of 32.563 kHz.

Unless your version of the compiler generates different code than mine, I suggest you need to tweak your timing loops.

> I am wondering if there is a latency difference from pins 2 and 13?

No, I think not. The problem may be elsewhere, such as electrical. I suggest you try to measure the frequency of your timing loops using whatever external equipment you have to hand. For example, just call your pulseIR function constantly and measure with a frequency meter. I measured 32.555 kHz on my meter, for example.

---

## Use a timer to generate 38 kHz

You will get a more accurate 38 kHz signal if you use the hardware timers, properly configured. For example:

<!-- language: lang-c++ -->

    const byte LED = 10;  // Timer 1 "B" output: OC1B
    const byte buttonPin = 4;

    // Clock frequency divided by 38 kHz frequency desired
    const long timer1_OCR1A_Setting = F_CPU / 38000L;

    void setup()   {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode (LED, OUTPUT);
      Serial.begin(115200);

      // set up Timer 1 - gives us 38.005 kHz
      // Fast PWM top at OCR1A
      TCCR1A = bit (WGM10) | bit (WGM11);                // fast PWM
      TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
      OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
      OCR1B =  timer1_OCR1A_Setting / 2 - 1;             // duty cycle
    }

    void loop()
    {
     if (! digitalRead(buttonPin)) {
        // button down
        Serial.println("Sending IR signal");
        SendCode();
        delay (200);
      }
    }

    // This procedure sends a 38KHz pulse to the IRledPin
    // for a # of microseconds.
    void pulseIR(const unsigned int microsecs) {
      TCCR1A |= bit (COM1B1); // clear OC1B on compare
      delayMicroseconds (microsecs);
      TCCR1A &= ~bit (COM1B1); // don't clear OC1B on compare
      digitalWrite (LED, LOW);
    }

    void SendCode() {
      // This is the code for my FIOS FF
      Serial.println("FIOS- FFwd");
      noInterrupts ();
      pulseIR(9220);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(22320);
      pulseIR(9200);
      delayMicroseconds(2240);
      pulseIR(540);
      delayMicroseconds(24664);
      pulseIR(9220);
      delayMicroseconds(2240);
      pulseIR(540);
      delayMicroseconds(24684);
      pulseIR(9200);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(24684);
      pulseIR(9200);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(24664);
      pulseIR(9220);
      delayMicroseconds(2260);
      pulseIR(520);
      interrupts ();
    }

This sets up Timer 1 to output 38 kHz, and then for the timing of the pulses you just turn its output on and off.

Note that you have to use D10 on your Uno because that is where Timer 1 outputs to.

---

For more information see [my page about timers](http://www.gammon.com.au/timers).

I have a graphic which shows a lot of the useful registers:

[![Timer 1 information][3]][3]

  [1]: https://i.stack.imgur.com/UtD6v.png
  [2]: https://i.stack.imgur.com/qunZi.png
  [3]: https://i.stack.imgur.com/xU8Nd.png


message:
Creating a simple menu for Arduino LCD button shield

I am trying to create a very simple menu to use with my lcd keypad shield, I have tried looking into how tutorials say to do this but I don’t really understand them.

Would it be possible to do it by doing something like creating an integer I.e menuTotal, that depending on the what the value of menuTotal is a menu item would display, then have the the up and down buttons add or subtract 1  of the menuTotal value.

Any help you can give would be greatly appreciated.

Liam

body:
Your approach of holding the "current" menu selection and incrementing or decrementing upon external input (button press) is a sound approach.

Consider writing a `drawMenu()` function that draws the screen, based on the current menu. In your program, keep a `bool updateScreen` variable. Then, any time you get an external input that would change the screen, set the `updateScreen` variable to `true`.  The actual `drawMenu()` function, after drawing the screen, should reset the `updateScreen` variable back to `false`.

In your `loop()` function, have a section like:

    loop() {
      // [... other code ...]

      if (updateScreen) {
        drawMenu();
      }

      // [... other code ...]
    }

In this way, the screen is updated when necessary, and your main loop can keep running, processing input, etc.


message:
Using millis() to time the start / stop of a DC motor

I'm trying to use a DC motor with pinion engaged to a rack gear, and have that motor move a distance, save the distance, delay, reverse, and travel back the same distance from where it started, delay, do it again. I want to start/stop the initial save with a button push, then from those saves, loop the motor movement.

I have considered using a Hall effect sensor or reed switch to count, but it seems a software interrupt or timing is easier using `millis()`. I researched and found that `millis()` cannot be reset, so I'm wondering if this is possible.

I haven't started a sketch, but I got this idea from the BlinkWithoutDelay example sketch included with the Arduino IDE. Like, have the motor positioned at "home" position, button push, start the timer, motor travels to end of work piece, stop the timer, save that forward distance traveled into a variable, reverse the motor, (at this point the timer would be at 0 again for the reverse travel) travel back to "home" save that reversed distance traveled into another variable with a button push, and then use these start/stop values in a loop. So I would save the values with a button pushes, then just loop that.

Or I'm thinking about putting an if or while button push outside the loop with a nested `counter++`, eyeballing the motor travel, once it gets to where I want it, save those counts in variables, then using them in the loop to `analogWrite()` to the motor.

body:
You can't reset the `millis()` function, but you can count the amount of milliseconds and stop when necessary: beware though, the positioning might not be as precise as you wish and you have to consider the error will accumulate on the long run.

Nonetheless here is the code:

    uint16_t duration;
    bool direction = true;
    void loop() {
      if (duration != 0 and !buttonPressed()) {
        // running back and forth if setup and no "finish" button detect
        uint16_t start = millis(); // reset the timer
        startMotor(direction);
        while (millis() - start < duration && !buttonPressed()) {
          ; // keep going
        }
        direction = !direction; // reverse direction
      } else if (duration == 0) {
        // your motor positioning setup
        while (!buttonPressed()) {
          ; // wait for button to start positioning
        }
        uint16_t start = millis(); // ask for time
        startMotor(true); // run the motor cw
        while (!buttonPressed()) {
          ; wait for button to end positioning
        }
        duration = millis() - start; // store duration
        direction = false; // reverse motor direction
        // next time loop() is executed the motor will go back to home
      }
    }
    bool buttonPressed() {} // define this to determine if the button has been pressed, safer if you use an interrupt
    void startMotor(bool cw) {} // define this to run your motor clockwise or counterclockwise


message:
Time remaining with os_timer_t

The [Ticker](https://github.com/esp8266/Arduino/tree/master/libraries/Ticker) library for the ESP chips is quite useful, which wraps a `os_timer_t` object. I'd like to be able to see the time remaining on the timer, is it possible to do that witha `os_timer_t` object?

body:
The library just calls `os_timer_setfn` and `os_timer_arm` which will call the callback function after some time. To add the feature to see how many remaining time there is, you would need to extend the library (the `Ticker` class, specifically) to save a timestamp when the timer was started. You can then write a function which returns for how much time is remaining or has passed by doing `uint32_t remaining = timestamp_now() - timestamp_started`.

A good function to hook would be the `_attach_ms` in Ticker.cpp. Add a `uint32_t timestamp_started` variable in the `Timer.h` header for the class. Then set `timestamp_started = system_get_time()` (from `user_interface.h`). Then write a function `uint32_t remainingUs() { return system_get_time() - timestamp_started; }`. Beware of integer overflows -- `system_get_time` returns passed microseconds since µC startup.


message:
How can I find the time taken while a function is being called?

I tried using millis, but I wanted to know if there is any better way to find out the exact time from when a function is called and finally when it terminates.

body:
There is `micros()` which returns the number of microseconds the board has been active. But it rolls over much more frequently (a bit over an hour vs the month and a half for `millis()`)

    unsigned long preFunction = micros();
    foo();
    unsigned long timeElapsed = micros() - preFunction;


body:
Beyond the answer of ratchet freak, I also suggest to (for test only), put it in a loop and divide it to get a better result, like:

    unsigned long preFunction = micros();
    for (int i = 0; i < 1000; i++)
    {
      foo();
    }
    unsigned long timeElapsed = (micros() - preFunction) / 1000;

The number of repeats depend on the length of foo(), make sure it will not have a value beyond an unsigned long.


message:
Detect current in car handbrake circuit

[![circuit][1]][1]

Using Arduino, how can I detect that the switch is on? I have access to the wire within the red rectangle only. That's because the switch is closely connected to the car body (ground). When the handbrake is up, the switch is pushed by a coil to touch car body and close the circuit. And when the handbrake is down, the switch go away from the car body and the circuit is open.
[![switch][2]][2]

  [1]: https://i.stack.imgur.com/zgn7r.png
  [2]: https://i.stack.imgur.com/xsQkE.jpg

body: If you truly only have access to the red rectangle content, and not the Ground or +12V supply, you could use an opto-isolator, assuming you can use enough of the wire in the red rectangle to be able to form a voltage divider to get at least 1-2 mA through the input side of the opto.


body: Wrap the wire around a ferrite or some iron core and detect magnetic field.


body:
If you can modify the cabling, you can add a shunt resistor in series and measure the voltage drop between the terminals. This way you can measure the current draw that would be 0 if the switch is open and something if the switch is closed.
Other way you can use an ACS712 Current Sensor.


body:
Based on your comments:

"It's the handbrake switch button..." and "..if the switch is closed, the voltage would be zero as the ground, and if the switch is open, it will read 12 V.",

you could splice into the wire and use it as an input for the Arduino. You can NOT connect it directly to an Arduino because 5V is the maximum voltage permitted on a digital input (assuming your Arduino is running at 5V).

There are several ways to connect it to the Arduino safely, such as an opto-isolator, a level-shifter or using passive components.

This circuit using 2 resistors and a zener diode may work for you:

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

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

Be sure to connect the vehicle ground to the Arduino GND.


body:
After examining the answers provided by "Jose can u c", "Alberto Perro" and "VE7JRO", and the comments by "Mark Smith", It was clear to me that there are a lot of methods to use, but I found out that the simplest way is to just measure the voltage at any point within the red rectangle. While the circuit is close, it will read 0V, and while the circuit is open, it will read about 12V.
And of course we will use voltage divider to reduce the voltage to  about 4V, and 4.7 zener diode to protect Arduino's pin.

[![open circuit][1]][1]

[![closed circuit][2]][2]

  [1]: https://i.stack.imgur.com/5x9R3.png
  [2]: https://i.stack.imgur.com/hGFf7.png


message:
What does drawmenu() mean

Can anybody tell me what drawmenu() means, I got an answer on here that has the term on and I don’t quite understand it, I’m very new to this.

Any help you can give will be greatly appreciated.

Liam

body:
I gave you [that particular answer][1]

The function `drawMenu()` has no meaning. I was suggesting that you **create** a function with that name, whose action is to write text to the LCD with your selected menu item. The name of the function is not relevant. It does not exist until you create it.

  [1]: https://arduino.stackexchange.com/questions/48904/creating-a-simple-menu-for-arduino-lcd-button-shield


message:
Put integer and double into char array

I want to print text and numbers mixed in a table with Serial.print(); from a char array. My problem is the conversion between the different data types. My idea is to print the data of the rows in a for loop with the variable i and the columns in a for loop with the variable j.

I have in the following example two variable, one is type integer and the second is a double. Now i want to add the values of the variables into the char-array, but I can't find a way to do this...

In my main program the variables need to have this data types and should be inserted later into the char array.

Does someone have a solution for this challenge?

Here is a small example code:

    int a = random(0, 100);
    double b = random(0, 100);

    char* myStrings[][6] = {"This is string 1", "This is string 2", "This is string 3",
                            "This is string 4", "This is string 5", "This is string 6"
                           };

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

    void loop() {

      //now put the integer and double variables into the char array in the second column

      //Print the values
      for (int i = 0; i < 2; i++)
      {

        for (int j = 0; j < 6; j++)
        {
          Serial.print(myStrings[i][j]);
          Serial.print("  ");
          delay(100);
        }
        Serial.println();
      }

    }

Many thanks in advance.

Guss

EDIT:
The output should look like this:
Headline (in this example it is the text "This is string 1", "This is string 2"...)
and then the values of the variables in the next row. It should be like this:

    This is String 1     This is String 2     This is String 3

    Variable a           Variable b           Variable int

    Variable double      Variable double      Variable int

body:
First of all, you should decide for a datastructure for you table. There are many options with various advantages and disadvantages. I am choosing a statically allocated table here, with a fixed width for each entry in the table and a fixed number of columns. One may also use pointers to strings which are allocated on the heap or elsewhere, but I find this to be the simplest.

Anyways, the basic problem doesn't change: We want to write a integer value in some string buffer. I am using the C library function `snprintf()` here. This function is like `printf()`, just that it writes its output to a given buffer of a maximum size. Thus, we can use simple format strings here and some workarounds for non-working format strings ([floating points..][1])

Here is the code.

<!-- language: lang-cpp -->

    #include <Arduino.h>

    /* A table is a 2 dimensional array of char buffers.
       The core element is a char buffer of fixed size.
       The number of columns must be fixed at compile time.
       Rows can by dynamically added in the structure without having to
       declare the number of elements.
       You can declare the number of rows at compile time, but do not need to fill them.
       Thus you can dynamically add rows to the table.
     */

    #define MAX_ENTRY_SIZE 20
    #define NUM_COLUMNS 3
    #define COLUMN_PRINT_WIDTH MAX_ENTRY_SIZE

    char myTable[][NUM_COLUMNS][MAX_ENTRY_SIZE] = {
      {"Column 1", "Column 2" ,"Column 3"}, //Row 1
      {"Variable a", "Variable b", "Variable int"}, //Row 2
      {"Variable double", "Variable double" ,"Variable double"}, //Row 1
    };

    char* get_table_entry(int row, int column) {
     char* entry = myTable[row][column];
     return entry;
    }

    void write_int_to_table(int value, int row, int column) {
     //Get a pointer to where the entry is
     char* entry = get_table_entry(row, column);
     //write a new string inside it
     snprintf(entry, MAX_ENTRY_SIZE, "%d", value);
    }

    void write_double_to_table(double value, int row, int column) {
     //Same as above, different format string..
     char* entry = get_table_entry(row, column);
     //Formatting floats on an Arduino Uno is tricky. %f formatters don't work (cut out due to size.)
     //use String API instead
     String stringFloat(value);
     const char* cString = stringFloat.c_str();
     strncpy(entry, cString, MAX_ENTRY_SIZE);
    }

    void print_table() {
     //Get number of Rows
     int numRows = sizeof(myTable) / (MAX_ENTRY_SIZE * NUM_COLUMNS);
     for(int row = 0; row < numRows; row++) {
      //Print all columns of this row
      for(int column = 0; column < NUM_COLUMNS; column++) {
       char* entry = get_table_entry(row, column);
       Serial.print(entry);
       //fill with spaces to the right
       for(unsigned int i=0; i< COLUMN_PRINT_WIDTH - strlen(entry); i++) Serial.print(" ");
      }
      Serial.println();

      //Table header seperator
      if(row == 0)
       Serial.println("============================================");
     }
    }

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

    void loop() {
     int a = random(0, 100);
     double b = random(0, 100);

     Serial.print("Will write new values for a = ");
     Serial.print(a);
     Serial.print(" and b = ");
     Serial.println(b);

     //write these in the second row (first row after header), first and second column.
     write_int_to_table(a, 1, 0);
     write_double_to_table(b, 1, 1);

     //Print table again
     print_table();
     Serial.println();
     Serial.println();

     delay(5000);
    }

Two rounds give the output:

    Column 1            Column 2            Column 3
    ============================================
    Variable a          Variable b          Variable int
    Variable double     Variable double     Variable double

    Will write new values for a = 7 and b = 49.00
    Column 1            Column 2            Column 3
    ============================================
    7                   49.00               Variable int
    Variable double     Variable double     Variable double

  [1]: https://stackoverflow.com/questions/27651012/arduino-sprintf-float-not-formatting


message:
How well will the Arduino Uno survive in a vacuum?

Im doing some experiments with Pocketlab and Arduino, Vacuum will get to around -30inHg. I tried with my raspberry pi and it just kept dying everytime a vacuum was pulled. The only problem I can image is the arduino heating up.

body:
Interesting question. You're right- heat is your enemy. Given the power dissipated by a Pi even when idle I'm not surprised it died. Most chips depend on convection to get rid of heat. A loaded Pi might require a (convective) heat sink and/or fan to keep it's core temperature down to an acceptable level, and that's at normal pressure and temperature. An Arduino -might- be able to work in a vacuum- it can lose some of it's heat through lead conduction- it'll only draw ~.25 watts normally vs 2.5 watts plus for a loaded Pi.

Ultimately it will depend on your application. If you have idle time when you can put the Arduino to sleep that will help keep it cool. If you have a conductive heat sink you can use then that would certainly help.


message:
Temperature control using a DHT11

I am trying to do a project on temperature control and found an example but cannot get the code to work. I have read forums and tried to fix the issue which is below the code.

Code:

<!-- language: lang-cpp -->

    #include<DHT.h>      // Including library for dht
    #include<LiquidCrystal.h>
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
    #define dht11dpin 12
    DHT11;
    #define pwm 9
    #byte degree[8] =
    {
      0b00011,
      0b00011,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000
    };

    #void setup()
    {
      lcd.begin(16, 2);
      lcd.createChar(1, degree);
      lcd.clear();
      lcd.print("   Fan Speed  ");
      lcd.setCursor(0, 1);
      lcd.print("  Controlling ");
      delay(2000);
      analogWrite(pwm, 255);
      lcd.clear();
      lcd.print("Circuit Digest ");
      delay(2000);
    }

    void loop()
      DHT11.read(DHT11pin);
      int temp = DHT11.temperature;
      lcd.setCursor(0, 0);
      lcd.print("Temperature:");
      lcd.print(temp);   // Printing temperature on LCD
      lcd.write(1);
      lcd.print("C");
      lcd.setCursor(0, 1);
      if (temp < 26 )
      {
        analogWrite(9, 0);
        lcd.print("Fan OFF            ");
        delay(100);
      }
      else if (temp == 26)
      {
        analogWrite(pwm, 51);
        lcd.print("Fan Speed: 20%   ");
        delay(100);
      }
      else if (temp == 27)
      {
        analogWrite(pwm, 102);
        lcd.print("Fan Speed: 40%   ");
        delay(100);
      }
      else if (temp == 28)
      {
        analogWrite(pwm, 153);
        lcd.print("Fan Speed: 60%   ");
        delay(100);
      }
      else if (temp == 29)
      {
        analogWrite(pwm, 204);
        lcd.print("Fan Speed: 80%    ");
        delay(100);
      }
      else if (temp > 29)
      {
        analogWrite(pwm, 255);
        lcd.print("Fan Speed: 100%   ");
        delay(100);
      }
      delay(3000);
    }

Error:

<!-- language: lang-none -->

    In file included from C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:2:0:
    C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected unqualified-id before numeric constant
     #define DHT11 11
                   ^
    C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:6:1: note: in expansion of macro 'DHT11'
     DHT11;
     ^
    C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected initializer before numeric constant
     #define DHT11 11
                   ^
    C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:35:1: note: in expansion of macro 'DHT11'
     DHT11.read(DHT11pin);
     ^
    sketch_jan20b:36: error: request for member 'temperature' in '11', which is of non-class type 'int'
     int temp=DHT11.temperature;
                    ^
    sketch_jan20b:37: error: 'lcd' does not name a type
       lcd.setCursor(0,0);
       ^
    sketch_jan20b:38: error: 'lcd' does not name a type
       lcd.print("Temperature:");
       ^
    sketch_jan20b:39: error: 'lcd' does not name a type
       lcd.print(temp);   // Printing temperature on LCD
       ^
    sketch_jan20b:40: error: 'lcd' does not name a type
       lcd.write(1);
       ^
    sketch_jan20b:41: error: 'lcd' does not name a type
       lcd.print("C");
       ^
    sketch_jan20b:42: error: 'lcd' does not name a type
       lcd.setCursor(0,1);
       ^
    sketch_jan20b:43: error: expected unqualified-id before 'if'
       if(temp <26 )
       ^
    sketch_jan20b:50: error: expected unqualified-id before 'else'
         else if(temp==26)
         ^
    sketch_jan20b:57: error: expected unqualified-id before 'else'
          else if(temp==27)
          ^
    sketch_jan20b:64: error: expected unqualified-id before 'else'
          else if(temp==28)
          ^
    sketch_jan20b:71: error: expected unqualified-id before 'else'
         else if(temp==29)
         ^
    sketch_jan20b:77: error: expected unqualified-id before 'else'
          else if(temp>29)
          ^
    sketch_jan20b:83: error: expected constructor, destructor, or type conversion before '(' token
       delay(3000);
            ^
    sketch_jan20b:84: error: expected declaration before '}' token
     }
     ^
    exit status 1
    request for member 'temperature' in '11', which is of non-class type

body:
It's a bit hard to see, but

    DHT11;

does not look like a correct statement, assuming DHT11 is a class (not a define like shown) it should be something like

    DHT11 dht;

where dht is an instance and you can use that.

Than in

    DHT11.read(DHT11pin);

you should replace it by

    dht.read(DHT11pin);


message:
Rfid reader and SD card shield won't work together

I recently encountered a problem that's been bugging me for days. I want to make a project using a RFID reader and log data on an SD card with an Arduino Nano, but apparently no matter what I do, I can't seem to make them work together on SPI. They both work individually, and the SD shield works in parallel with the RFID reader, but the RFID doesn't work in parallel with the SD shield.

I'm absolutely sure that the wiring is correct, slave select on both modules are wired to different digital pins, and both are connected through bidirectional level shifters.

I noticed that the RFID reader works fine when I disconnect the MISO pin from the SD shield. I tried putting a diode between SD MISO and digital pin 12, I tried adding pullup resistors on both SS pins, I tried adding resistors on MISO lines, I tried pulling HIGH the SS i don't use, and low the one I want active. Nothing seemes to work and I'm out of ideas. The last thing I will try is conencting the modules on separate VCC, but I don't have faith that it will make any difference.

I hope someone has some advice for my problem.

Thanks in advance

body:
SD cards (or really their breakout boards) don't tend to obey the rules with regards to SPI. In particular the MISO pin isn't set to high impedance when the slave select is not selected.

You can fix this with a tri-state buffer that you feed the SD card's miso line to and controlled by the slave select. The output from the buffer goes to the arduino's MISO.


body:
The only way I could get it to work was to buy a separate SD logger shield (which contains an SD card via SPI).

When I used the SRAM (SPI) together with the SD card (SPI) it never did work. At least not on an Arduino (Uno or Mega).