text:
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
  }
}

you can have only one setup() and one loop() subroutine ... you will have to merge the three subroutines into one for each of those .... first, you need to figure out what the code does

-1 for messing up code formatting after it was corrected. i will remove the downvote if you correct the formatting

@jsotola - isn't that blackmail :)

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.

Yep all that and use functions to break down you code into manageable chunks.  If its longer than 10 lines, or you do it more than once maybe it ought to be a separate function

@CodeGorilla good addition ... it also will make readability, efficiency, maintainability and testing easier to have small functions.


text:
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, but circuit diagram similar to that one. I get power from my PC to run Arduino.
This is my Arduino code :
#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");
  }
}

this does not describe how you are powering the arduino ... I get power from my PC to run Arduino.

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.

powering CH_PD from 5V did the trick. I suspect it powers the WiFi part

@Juraj sorry, what do you mean? directly connect 5v to ESP's CH_PD port?

no no, the regulator is ok. 3.3 V pin on Uno can provide only 50mA. normal is connecting Vcc and CH_PD together but the 3.3 V is not strong enough to power esp8266. I wonder that powering only CH_PD from stronger source helped.

@Juraj I tried to connect external voltage to Vcc, but it didn't work.

I looked up the docs. Your esp8266 is now stable because the CH_PD (chip enable) pin has stable power not affected by power drops caused by WiFi. a stronger power supply would by a better solution

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.

solder capacitors to Arduino board? can you explain it ?

@Sachith http://www.instructables.com/id/NRF24L01-Fixing-Connection-Issues/

you need 100-200mah for the arduino - 100 milliamp-hours? You mean 100-200mA don't you?

OP uses WiFiEsp library in Uno with AT firmware in esp8266

@Coder_fox An Ampere is a unit of measurement on its own. That's like saying kilograms are measured in kilogram-hours.

Amp-hours are for things like batteries. A 40Ah battery might produce one amp for 40 hours, or 2 amps for 20 hours, and so on.

@Sachith, are you here? You offered a bounty. It will go to Coder_fox. Did this answer help? If yes accept it, if not, give feedback

@Juraj No, that didn't slove my problem. I posted my answer below.

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

can you suggest full answer?

source: Stack Exchange

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

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

sort: votes


text:
Store values in array
I'm trying to implement the "BNO055 9 Axes Motion Shield".
There is an existing Arduino sketch GitHub 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()"

It would be better if you adopted the habit of including system libs first.  The reason behind this is it is theoretically possible (very unlikely) that a header file will include a the system lib header and then redefine a pre-processor variable that the system library uses and so you might get different/conflicting header files for the library.  Very very unlikely, unless you work with true coding cowboys.

Do you mean in this case Wire.h should come before NAxisMotion.h?

Yes  #include <xxx> before #include "xxx".
This also means if you get a duplicate definition int foo = 7 the error will be reported against the code you are more likely to have written rather than suggesting some system library is wrong.
Others will argue I'm wrong, but it would be boring if we all thought the same.

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?

So basically I tried it out and your code worked, thanks a lot. But now I my problem is, I can't convert the unsigned int sensor data to floats (which would also have to be unsigned) for further proccesing in the program "Processing" for visualization. Is there any way?

Yes, but it will only give you a whole number, because that's all you have.  float fValue = (float)iValue;

I want to divide each element of the int16_t data-type array by 1000 and then convert them to float. It works but only gives me whole numbers like you said. What am I doing wrong? I need at least 2 decimal places.

You are doing integer division, you want float division.  float result = ((float)input) / 1000.0f;  You have to make both number floats and then divide.

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


text:
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.

tx buffer doesn't overflow. the write function of HardwareSerial waits for space in the tx buffer

You mean the: https://www.arduino.cc/reference/en/language/functions/communication/serial/availableforwrite/ As @Juraj wrote, the tx buffer does not overflow, if you send too much data the Arduino is slowed down a lot (100 times or more) because it is waiting for space in the tx buffer.

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

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.

that is for rx buffer


text:
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?

What web server are you using? Does is it capable of running PHP? Did you check the docs?

I am using Wemos D1 mini, documentation doesn't say anything about PHP

golly, that would be really really handy. too bad it's not possible.

You can still achieve that by getting a Raspberry PI and running Linux server on it. Then you will be able to install:
PHP + MySQL + phpMyAdmin and many other features

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.

Thank you for that information! Looks like I need to buy a Raspberry PI and install Linux server on it


text:
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:
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());
}

Show the rest of your particular code.

@josecanuc #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());
}

Code in comments is unreadable. Edit it into the post.

What is the commented line supposed to achieve...?

@majenko I want to check that if the hardware is functional and ready and my client object has created successfully so I can start communication. Instead of putting a blind delay(n) and hope for the best.

Then you want to do such things as check that you have a valid IP address from your DHCP server. Your "client" object will only be in any way valid once you have tried making a connection to a remote server.

@majenko then I think the only way left to let a client or server knowing it's possible for them to start is polling the Ethernet.begin() for some time / tries . Then rising an error and halt. Or is there a better way?  A server.begin() is a null type and server.available() is a client object type. None of them return an error.

You try opening a connection. If it works you can open a connection. If it doesn't then you can't.

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...

So what does it serve here

is the linked example wrong?

Most likely. I can't see what they think they are doing there. That test can never pass unless a connection has been attempted, and no connection has been attempted.

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).

Actually it's an instance of an object with an int operator. It returns whether the socket is connected or not. That may be interrupt driven, or it may be done through yield(), which may explain it working with delay(), since delay() calls yeild().

I guess you're right but the code is available at link


text:
ESP8266WiFi client.print() strange response
I am using a NodeMCU, so ESP8266. I installed the core via the Boards Manager at the last version.
My goal is to control a GoPro camera through WiFi.
I am getting mad with these few lines of code:
uint8_t GoProControl::sendRequest(String request) {
    client.stop();
    if (!client.connect(_host.c_str(), _port)) {
        if (debugStatus){
            Serial.println("Connection lost");
            GoProConnected = false;
        }
    return false;
    }

    client.print(request);
    client.print("Connection: close\r\n\r\n");

    if (debugStatus){
        Serial.println("my request is:");
        Serial.println("-------------");
        Serial.print(request);
        Serial.print("Connection: close\r\n\r\n");
        Serial.println("-------------\n");
    }
    if (listen() == "HTTP/1.1 200 OK\r") {
        return true;
    }
    else {
        return false;
    }

}

the client is connected without problem (it never gives me error) and so i send the request:
GET http://10.5.5.9/camera/SH?t=password&p=%00 HTTP/1.1
Connection: close

the listen function mainly does:
char c = client.read();
response += c;

and then print the response, this is what i get from it:
HTTP/1.1 404 Not Found
Connection: close
Date: Sat, 13 Jan 2018 16:26:27 GMT
Server: Cherokee/1.2.101b150604_3b16072 (UNIX)
Content-Length: 355
Content-Type: text/html
Cache-Control: no-cache
Pragma: no-cache

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

<title>404 Not Found</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

404 Not Found

The requested URL /camera/SH was not found on this server.

Cherokee web server 1.2.101b150604_3b16072 (UNIX), Port 80

It looks like I am connected to the wrong host.
Since I am sure that this is the correct request, where is possible that I am doing any error?

can you connect to it with your computer?


text:
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

400 Bad Request

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)  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;
        }
 }
}

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.

The problem was in delays, seems its very important, got working code

can you give us your sketch source code


text:
Adafruit ESP32 device working on OSX 10.13 but not on OSX 10.11 on older machine
I'm new to Arduino - just got an ESP32-based Adafruit Feather HUZZAH32. I got it up and running on my Macbook Air (High Sierra) with no problem, following the instructions at this page linked from the Adafruit page on the HUZZAH32:
https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/mac.md (dead link)
Basically, install the Arduino IDE, install the Espressif stuff using a big shell command, and install the driver for the CP2104 USB->UART bridge.
It worked like a charm on the Macbook Air, no problem. But it was a different story when I went to install it on my 2009 vintage Mac Pro running El Capitan. Everything seemed to install ok, and the Arduino IDE runs and shows "Adafruit ESP32 Feather" (under Tools->Board).
However, when I try to upload a sketch (the "Blink" built-in example), it compiles ok but seems to hang while uploading, eventually finishing after about 5 minutes.  But the sketch isn't there, the one I previously uploaded from the HighSierra machine still executing.
Furthermore, it does weird things to the Mac: the System Profiler (About This Mac) no longer runs (shown as "Not Responding" in Activity Monitor), even after I've quit the IDE; occasionally I can't even seem to quit the IDE; and next time my computer sleeps, it can't be woken up (I have to restart with the power button).   Another thing: when I start the upload, the kernel-task (PID 0) starts using over 100% of the CPU (from Activity Monitor).
Maybe it's a version compatability issue with the Espressif uploader?   Or maybe I screwed up with the CP2104 driver, first installing the one here, CP210x USB to UART Bridge VCP Drivers, as pointed to by the How-To at Adafruit, and when things did not work, and the uninstall shell script for the driver failed too, I just deleted what seemed to be the relevant files before then installing the "legacy" driver, which also did not work.
Looked at some of the debugging stuff here ... The CP2104 driver shows up under USB in System Profiler, and both cu.SLAB_USBtoUART and tty.SLAB_USBtoUART show up under /dev (in Terminal).   So nothing seems wrong there.
Here is a screen grab (with verbose output for upload selected):
Archiving built core (caching) in:
 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_cache_759917/core/core_espressif_esp32_featheresp32_FlashFreq_80,UploadSpeed_921600,DebugLevel_none_4423141e818963094868f9e8ffa4e8ec.a

Sketch uses 136741 bytes (10%) of program storage space. Maximum is 1310720 bytes.

Global variables use 10908 bytes (3%) of dynamic memory, leaving 284004 bytes for local variables. Maximum is 294912 bytes.

/Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/esptool --chip esp32 --port /dev/cu.SLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 /Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/partitions/boot_app0.bin 0x1000 /Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/sdk/bin/bootloader_dio_80m.bin 0x10000 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_build_212318/Blink.ino.bin 0x8000 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_build_212318/Blink.ino.partitions.bin

It just seems to be a very long command line to run esptool, and then... nothing.
I'm at a loss - I've asked at Adafruit forums: trouble getting HUZZAH32 working on Mac
... and filed an "issue" at the Github page too: upload hangs on older Mac configuration (Mac Pro 4,1 w/ El Capitan) #983
In short, this Github issue says that the thing works fine on the USB ports on the rear of my Apple monitor, but hangs (as described in OP) on the ones on the front of the Mac Pro tower as well as the ones on the rear of the tower (including the one into which the monitor was plugged).

Is the difference USB 3.0 vs USB 2.0?

Yes, I think it may have to do with power, because I've run into some weird behavior, that seems power related, when I try to turn on wifi. And it's not the CP210X drivers, because it works on some ports and not others.  My machine only has USB 2.0 ports, and of course USB 3.0 can provide more power.   I'm going to buy an AC-powered USB hub and see if that works better.

The first link appears to have died, unfortunately. The guide appears to have been moved - could you please verify that this is now the link to the same guide that you followed: https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html#macos. In addition, I have found that older versions of OS X do not work well with CH34x or CP210x USB interfaces (when they are used on an Arduino clone), the drivers just aren't there (not built-in to the OS).

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


text:
(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/):
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?

Please edit your question to clarify what you mean by "2 colours". Do you mean that some of the LEDs on the strip are one color and other LEDs are a different color? If so, is there a particular pattern to which LEDs are which color? How different are the colors?

@per1234  I've edited the question to make it easier to understand. Sorry about that. Yes, the strips nearer the end are a different colour to the one I specified i.e. at the end it's more green than blue.

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 that I wrote using the SPI hardware. The library with the exact code above is available here.
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).


text:
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?

what does janky mean? .... please define sketchy results  .... what is the difference between linear taper and log taper pots?

not quite for sure, except that I suspect the log outputs in log increments and the linear is more direct

janky is slang for like twist the pot, then the motor goes from 0 to 255 with no increments, non linear

http://www.resistorguide.com/potentiometer-taper/

Are you asking why it seems to work better when controlling an LED rather than a motor?

well no actually in my motor pwm sketch, I have a fade like function with step and speed and there is not jumpy action with this function but with a map() pwm only, the log pot is real messy, linear no issue

linear pot no issue

thanks for the link, that might explain why with a small turn, the log pot is non linear and jumps to the high end

@Jim Print out the values ranging from 0 to 255 coming from your pot and copy it into the question so that we can see better what you mean...

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:

(* 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.

"Firstly, with a log pot, you get a period of very small changes in resistance followed by a period of massive changes:" yeah, that exactly what was happening, problem solved with a linear pot. forgot about the log study from my electronics

with the linear, even with the stall current, seems responsive throughout the range

There's a chance you may have an "antilog" pot (the pink line in the graph), which compresses most of the big changes to the left, then gives you not much after that. So you get a big jump at the beginning of the turn, then you see nothing else much for the rest of the turn.

the motor is very responive with a linear pot, and the serial monitor shows a clean transistion 0 - 255 using the analogWrite and map()

That is what I would expect.  Do a little experiment. See how far you have to turn the linear pot before the motor starts spinning, and look to see what the PWM value would be at that point. Try and do the same with the log pot.

the log sucks and I have ditched it. small turn gets a response with the linear, so changed the map() to compensate

Log pots are great for controlling things with a logarithmic response, such as audio volume, or LED brightness. And yes, they suck for anything (like a motor) that is more linear.


text:
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);
}

It signifies that the author of this code has made a mistake of either implementation or understanding.

The first begin() is probably being ignored by the Arduino.

I thought it would be enacted upon and then overwritten by the second.  I know that's the same result, but there might be some subtle difference.

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.

when i asked the author of this code he said that they were for maximum and minimum value of baud rate. Is there anything like that? PS. Also the arduino was connected to BMP085, DHT11 and a HC06

I think he misunderstands the calls he has made, they aren't.  Serial only refers to the serial communications over pin 0 and 1 on an Arduino.  You can have other objects that refer to other serial ports, but in this case its the serial monitor.

Also the output was taken from a Bluetooth terminal in an Android app

What do you mean by "You can have other objects that refer to other serial ports, but in this case its the serial monitor"

On a Mega you have Serial1 and 2(?). You can create SoftwareSerial objects which create a serial connection out of any pins.  You could even define you own and bitbang a serial port.  Heck you could even have an object that create a virtual serial port over Ethernet, Wifi, Bluetooth, etc, which is what I think you are using.


text:
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?

Did you google it? https://techtutorialsx.com/2017/03/26/esp8266-webserver-accessing-the-body-of-a-http-request/

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.


text:
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 -

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 :)

Try measuring some voltages. Maybe the solder joint on the USB mini-B connector is broken.

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.

But it's the same with a phone charger thats rated for 1A and worked before. Something has happened with the Arduino.

Then maybe it's broken. It looks like a cheap chinese clone, so throw it away and get a new one.

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.


text:
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!

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).

But why cannt we do that ?

Because that is the syntax of C. "Ye canne change the laws of physics, cap'n"

Actually, the global scope is used for declaration and initialization. Execution is not needed. In C it is a rule that the first function that is executed is main. And the function main should call all other functions that will be called. Note that this function is 'hidden' (auto generated) by the toolchain. Other languages (like Python) can execute code within the global scope, but for C this has not been designed.

Is it just the syntax? or is there anything else behind that?

It's just the syntax. It's done that way so that the compiler can easily tell the difference between a piece of code that should be executed (a = 12) and a variable initialization (int a = 12). In the latter the "12" is stored elsewhere (in flash), and during the startup of your code that value (and other global variables) are copied into memory in the right places.


text:
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.

I don't have much experience with EEPROMS, but maybe even a single byte is written per 'page' (which can be e.g. 256 bytes), so you might have to take this into account when you write your data.

Another tip (if applicable): only write bytes (or a page) when a value is really changed (e.g. check the current value of a byte and only write it when it is unequal to the new value).

That method sound good to me. What I did in the past was to write my single byte (non-zero) value to the first location that was zero/empty. So every write, I moved one over. When I reached the end of the EEPROM I would zero-out the whole EEPROM and start back at index zero. To read the last value on power-up, just keep reading values from EEPROM till you read a zero (/or are at the last location).

Why not use an RTC instead?  If the stage increases every 2.5h you could calculate the stage by `((hours since 1970) \2.5 ) % 5

There are algorithms for extending the life of EEPROM, but is it going to be worth it in terms of processing power expended when the cost of replacing the EEPROM every year or so is only a few quid?

@MichelKeijzers Page Size for the ATMega328Ps EEPROM is 4 bytes. So it would be better to not use byte 1, 2 and 3. So the first page is only uses for the index byte.

@CodeGorilla some RTCs also have some free, battery backed, RAM available that you can write to. This works the same as EEPROM, but doesn't deteriorate, and keeps it's value, as long as the backup battery has enough voltage.

@Gerben thanks for this info ... I only played with SRAM which had a page of 32 bytes if I remember correctly. Guess it depends per storage type/brand/model.

The RTC is the best solution. Avoiding that the Arduino has a power down is the second best. For an algoritme, I would not count up to 250, but use the EEPROM as a ring buffer and continuously write to the next location. The Arduino could be turned off while writing to EEPROM, perhaps the variable has to writting twice and maybe with a checksum. Only two bits needs to be remembered... someone who is more creative than me can do something with that (a protocol to store it, or remember it in a different way).

Also asked at: http://forum.arduino.cc/index.php?topic=523223 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

Hi All, thank you very much for your comments. @Gerben If I go with my Idea I  will ensure I zero out my EEPROM once I reach the last byte I am using, hadn't even thought of that.

@CodeGorilla I do use the RTC technique elsewhere in my code but using the RTC in this case would not be suitable as I need the process to pick up exactly where it left off regardless of how long it is powered off for.

@Jot the ring buffer is a great idea and will further extend the EEPROM life. I was really over complicating it with a count, thank you.

@per1234, apologies for not mentioning the cross post, project is time sensitive and I honestly didn't think I would get such great advice so quickly. I will link in future if I ever cross post

@user1649972 - wouldn't zeroing the EEPROM be wasting a write cycle?  I don't know how you would follow gerban's suggestion without doing that though.  (understand what you mean about the RTC idea not being suitable in this case)

@CodeGorilla it kind of wastes once cycle, but in doing so make the code a bit simpler. Using the full 1k of memory, but writing it twice, will still give you 500 times the number of write cycles (ignoring page size). If that’s enough for the lifecycle of the product...

@CodeGorilla Been trying to think of a way around this as it will mean I write twice for every 1 write each loop around. Unfortunately I have to remove the old data before returning to my start point. My plan is when I reach the end of the EEPROM I will scan through all elements and return them to 0xFF (default value). I need to do this so I can find my last index on wakeup after a power loss. On wakeup I will scan all indexes until I reach one that has the value 0xFF, then step back to the previous index, which will be the last index I have saved. I cant think of a way around this just yet

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.

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:

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.
If the count goes from 8191 to 0 then keep going, you have just looped is all.
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.

This is excellent and I will 100% use this idea on another project I am working on that uses a larger EEPROM. I will only use 2 bytes as suggested, drop my count sticking with just the stage and index and move the index after every EEPROM write. As I am only planning to use 256 bytes I would not need such a large index to cover them all as 1 byte will do. Again thank you for this it is appreciated and will be used. Using my basic idea I had 28 years, the idea I posted on here would have given me 2425 years and now with using the byte pairs I will get up to 3652 years so I'm well covered.

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.

Hi Edgar, thank you for the reply. The value will 100% change each time I try to write, the change in value is what prompts the write to EEPROM. Great advice tho, thanks again


text:
Wake up ESP8266 with multiple GPIOs
I am building a ESP-07 based IOT device, that detects the status of 4 doors. The device must connect to WiFi and send an http request, when 1 of 4 doors is opened. I want to place a reed switch, for example on each door. The battery consumption should be minimal, so I thought of using deepsleep () or something similar to keep the device asleep most of the time, or keep it completely off (like most Dash buttons does).
I have studied several options, but almost all use a single GPIO to wake up the device. For example, this option wakes the device up if D3 goes high, and sleep if D3 is low.

    #include
    #include
    #define WAKE_PIN D3
const char* ssid = "SSID";
const char* pass = "PASSWORD";

extern "C" {
    #include "gpio.h"
}

extern "C" {
    #include "user_interface.h"
}

void setup(){
    WiFi.begin(ssid, pass);
    uint8_t i = 0;
    while (WiFi.status() != WL_CONNECTED && i++ < 10) delay(250);
    Serial.begin(115200);
    Serial.println("Setup");
    pinMode(WAKE_PIN, INPUT_PULLUP);
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, LOW);
    gpio_init(); // Initilise GPIO pins
}

void loop(){
    Serial.println("Do something...");
    if(!digitalRead(WAKE_PIN)){
        sleep();
    }
    delay(1000);
}

void sleep(){
    Serial.println("Going to sleep...");
    delay(10);
    wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); // set sleep type
    gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_PIN), GPIO_PIN_INTR_HILEVEL);
    wifi_fpm_open(); // Enables force sleep
    wifi_fpm_do_sleep(0xFFFFFFF); // Sleep for longest possible time
    delay(100);
    Serial.println("Woke up!");
}

Here, GPIO_ID_PIN(2) corresponds to GPIO2 on ESP8266-01 , GPIO_PIN_INTR_LOLEVEL for a logic low, can also do other interrupts.
My question is:
Can I use more than one GPIO, that is, one of 4 GPIOs to wake up the device?
I have the problem of knowing which of the four doors has been opened!
The other option I have thought is to use a latch circuit that turns on the (previously turned off) device using a single GPIO. Something like this:

What I meant is that ESP-07 can latch its own power on (and off) using an MOSFET pair connected in parallel with the physical (momentary contact) power switch. When the power switch is pressed (or a door is opened), one of the  first things the ESP8266 needs to do is latch the power on. When the current iteration of this programm is done, it simply turns it's own power off again.
#define POWER_SW   2   // GPIO connected to POWER_LATCH

void LatchOn() {
    pinMode(POWER_SW, OUTPUT);
    digitalWrite(POWER_SW, HIGH);
}

void LatchOff() {
    digitalWrite(POWER_SW, LOW);
}

What I want to know is how I can use more than one signal from each of the 4 doors, or, use 4 GPIOs to activate the latch circuit. I tried with one single door connected to the GPIO that wakes the chip up. I want to extend the functionality of my program so that any of the 4 doors turns the chip on.
Thanks in advance!
P.S.
I have opened a thread about this topic in Arduino Forum as well.

do you have the option of using a logic IC?

Sounds good! Any ideas?

Idea: Wire the  four door-GPIOs together with an OR gate, connect that to your wakeup pin, but still connect all door-GPIOs to 4 different GPIO pins on your ESP8266. When a wakeup is triggered (because ANY of the door GPIOs were triggered), read the state of the 4 door-GPIOs, act on it, then go back to sleep. You can use simple diode-ORs or CMOS (N)OR logic gates for this.

Also asked at https://stackoverflow.com/q/48279829

A friend from Arduino Forum told me that I can use a bunch of diodes to have all door switches trigger two pins: the shared wake-up pin, and a unique one for each switch. I have no idea how I could do that.
Any idea of what a circuit with these characteristics would look like?
Thanks in advance.

I don't know if an TTL-CMOS OR gate like CD4072 works with 3V3 logic. A simple circuit with diodes or resistor looks better. Any ideas?

http://www.ti.com/product/cd74ac32 . PDIP package, four 2-input OR gates, voltage working for 3.3V and 5V as well.

I think Diodes would use less power that an IC, but...

Great! I will try with CD74AC32 as well. Thanks!

How to make a circuit like that with diodes? It seems better to me, but I have no idea

And what if I use the ADC or analog input of the ESP-07? I think that with an array of resistors I can determine which of the 4 doors has been opened. Something like that --> link

Hello!
I have an idea. What if I connect each door using a DPST (double pole single throw) switch?
This would be the scheme using two single switches.
link
My idea is to use the same switch to connect at the same time the RESET PIN and the corresponding pin to each door (for example, GPIO12).
Would there be problems if two doors open at the same time? Would not the RESET pin be overloaded when two switches are connected to VCC?

Hi!
I have made a small card to connect my ESP8266. It is supposed to connect the GPIOs corresponding to the 4 doors I mentioned. My idea is to use, as I said before, a simple switch on each door, to connect each one to GND and the corresponding pin. I have connected each pin (GPIO12, ..., GPIO15) to the inputs of the 74HC32 and the output to the RESET (so that any of the doors can wake up to the ESP8266 of deep sleep.)
74HC32 is already connected to GND and VCC.
Click to see the schematics  --> link  My question is: Ok what I have done?

@JoseAlfredoSanchezDiaz - any chance you can draw a schematic for wiring of your example above - the code was really helpful to me in trying to set up sleep mode in my own project, but I can only make the esp go to sleep with a button, not wake up.


text:
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?

Just to make sure: Are you have a X-Y problem maybe? (https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). If your basic problem is "I don't have enough I/O pins on my ESP8266 to add a push-button", then the actual answer would be "add more I/O pins by adding a GPIO port expander over I2C or SPI", not "whack it onto the UART RX line and see if I can detect it"

Just get a WeMos D1 mini or similar. You get access to all 11 GPIO pins (except the SDIO pins of course, those are reserved for the flash memory) and a USB interface for easy programming. They're like $3.50 from China, so there's really no reason to use the ESP-01 in the first place.

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, no 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:

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:

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

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 and switch the function of the TXD0 and RXD0 to GPIO (more info). 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) would make much more sense, especially if you already have an I2C bus. There are also SPI devices available for this.


text:
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::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::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::~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.

You need to combine the header and source into a single header file.

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 ...


text:
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

Get rid of the Yún. Buy a WeMos or NodeMcu or a Raspberry Pi. Every minute you put into the Yún will turn out to be wasted time.

I'm also learning RaspberryPi and Galileo, along with some tiny ones.

The Galileo had a lot of problems and has been "retired". The Arduino boards with ethernet or wifi chips are okay. Stay away from the boards that have a simple microcontroller and a advanced wifi module. The WeMos can do everything those can do and more. The Raspberry Pi is reliable and fun, it will never disappoint you.

thanks for the advice.  What do you think of WickedNode kits?  and 8266?  useful?  I'm mostly wanting to "SMART"-up my home and security.  I have a ton of sensors.  Today I'm playing with an RF send/receive modules.  This probably isn't good conversation on this thread.  Do you mind if I occasionally ask advice through PM?

StackExchange has no PM. The WeMos is EPS8266. The WickedNode seems too specific, I like more freedom. The RFM96 is a good transceiver, it is used by Adafruit. The RadioHead is a good library, but uses a lot of memory. RadioHead is fine for ARM processors (Arduino Zero, Arduino M0, Arduino Due). If you make something that should last at least 10 years, buy from good companies (they use higher quality components) and try to use the most common and most often used standard modules/boards. Wifi at 2.4GHz is common, therefor the WeMos or NodeMcu is a good choice. The Raspberry Pi is always good.

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.


text:
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.

I believe that the problem is caused by the mode I entered. According to the datasheet 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 titled 'Factory Reset the RN-41 or RN-42' to get me on the right lines.
This worked for me:

Connect the Bluesmirf Mate Silver GND pin to GND and disconnected all other pins
Connect a wire to 3.3v on Ardunio
Load the Ardunio with an empty sketch, and keep it powered on
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.
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.


text:
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:
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);

}

Maybe a trivial remark, but did you change the first line: int IRledPin =  13;  to value 2?

For equivalence checking, you would need to get a logic analyzer and measure the pin signals for your D13 and D2 version. If those are exactly equivalent (and the current leaving that pin, too), I wouldn't know what else makes a difference. You could check what signal it decodes to using a standard IR decoder (http://www.instructables.com/id/Arduino-Infrared-Remote-tutorial/) just to make sure, too.

 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:

And this pulse width on pin 13:

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:
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.
I have a graphic which shows a lot of the useful registers:

I know I am not supposed to say thanks here, but you have gotten me back into the books for the past two days to learn something about the Atmel chip timers.  (I hate to blindly copy code without knowing how it works).  So, if I understand correctly, Timer1 is in a free-run at 38 kHz.  The output pin is enabled with TCCR1A |= bit (COM1B1) and disabled with TCCR1A &= ~bit (COM1B1).  Do I have this right?

That's right, I've amended the answer to have a link to my page about timers, and a graphic showing various registers. With appropriate values in OCR1A and OCR1B you can set a frequency and duty cycle. In my case I made the duty cycle 50%.


text:
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

Rather than using a LCD which has commonly 2 lines, I suggest to use a small Oled display. After that, your problem is pure code. Take a sheet of paper, simulate what you want to display and you'll find variable you need, when to inc, when to dec and so on.

I don’t really understand them ... you need to learn the basics first

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.


text:
espcomm_sync failed when connecting ESP8266 (ESP-01)
I'm new to the Arduino (I'm a developer but didn't have a chance to work with this kind of device before) and wanted to connect my ESP8266 to the Arduino Uno. I followed this tutorial but I got errors:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_memfailed
error: espcomm_upload_mem_failed

I tried running WiFiScan from the examples. I've installed SiLabsUSB Driver (I'm on macOS) and tried different solutions across the internet and I couldn't make it work.
There are screenshots of the settings.

that error usually means the ESP isn't in programming mode when you try to upload a compiled sketch to it

@JaromandaX so how to put in the programming mode?

Of course, I'm assuming you're trying to flash new firmware onto the ESP-01, if so, read the tutorial again - see step 19 in the tutorial you "followed"

@JaromandaX actually I didn't get to the 19th step as I couldn't get past step 2 but this flasher contains only .exe file and I'm on mac

That instructable is rubbish then. To flash the firmware, you need to ground GPIO 0, then power up (or reset) the ESP01 - then it's in flashing mode

you do something else like the instructable. you installed the esp8266 core into Arduino IDE and you try to upload a sketch. but you did not put the module into flashing mode.

the wire connections in the instructable will damage your esp. esp rx pin is not 5 V tolerant. you need a level shifter. the 3.3 V pin on Uno can supply only 50 mA. the esp8266 needs 170 mA for WiFi transmition

@Juraj - According to the data sheet the pins of most ESP are 5V tolerant, I think I remember they support 6.7v but please check, before you trust me.  (There is a post on here about it somewhere)

I checked http://espressif.com/sites/default/files/documentation/0a-esp8266ex_datasheet_en.pdf

I used different scheme to connect and when I connect the Arduino to the MacBook then it flashes blue LED but I still cannot select COM port and get espcomm errors

I connected GPIO 0 to GND and clicked Upload it started blinking blue light but still got espcomm warnings.

i see that when some settings are off, or if i have a module wired to GPIO1/3

@Juraj The CEO of Espressif confirmed that the IO is 5V tolerant. And an older datasheet (bottom of p17) mentions over-voltage protection.

ok, so why doesn't it work for me?

I connected GPIO 0 to GND and clicked Upload ... no, connect GPIO0 to GND, then reset or power cycle the ESP01, only now is it in flash mode

@JaromandaX noob question but how can I reset it?

you could add a momentary switch between the reset pin and ground

@JaromandaX any other solution? I don't have a switch

as I said, power cycle (turn power off then on) while GPIO0 is held to ground


text:
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.

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

Comments under a question are for clarifying the question, and for the OP to respond to such requests for clarification. For example "what type of Arduino do you have?". They are not for extended debugging of the issue. This is not a forum. If you (Jim) want to clarify your question please edit the question to do so.

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

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

This is a great answer; I don't see the fault and it should be accepted. The first thing the answer does is point out the misunderstanding about millis() not being reset-able, and the second benefit is an example of using millis() properly.