text:
How to load page from SD card and still show live data from sensors?
I am just wondering, how can we display page from SD card and still show live data from sensors?
I have web server running on Arduino mega using ethernet shield, in my sketch I am doing client.print to build content of a page being displayed, and refreshing it display live data.
But I can't think of a way how can I load page from SD card and display data from sensors.

Can you show your code please? It very much depends on how you're doing it.

@MarkSmith http://codereview.stackexchange.com/q/149563/22943

Is your problem really that you want your device to serve two different web pages?  Or are you trying to embed your live data into the middle of a pre-formed page? Or something else?

I want to embed live data onto a pre formed page.

I am sorry I didnt understand you, the above link I pasted is just how I am loading page from without sd card .

Sorry, I'm typing on a phone. Do you know how to load a file from the SD card into memory?

Use a character that you are not using (e.g. @) and place that where you want to put the live data. Then, when reading the file forward all characters other than '@' to client.print, but when you find a '@' print the live data. Very rudimentary templating.

Maybe combine JavaScript with Arduino-Websockets. But it would be more logical tot connecties your arduino to a more capable server.

Based upon this W3C example you can have w3-include-HTML.js file with the following contents:
function w3IncludeHTML() {
  var z, i, a, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    if (z[i].getAttribute("w3-include-html")) {
      a = z[i].cloneNode(false);
      file = z[i].getAttribute("w3-include-html");
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          a.removeAttribute("w3-include-html");
          a.innerHTML = this.responseText;
          z[i].parentNode.replaceChild(a, z[i]);
          w3IncludeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }

Now you can put this in your .html file:

and then you can use something as:
server.on("/generated_data.html", live_data);

If you want to be able to use server.on() you must include <ESP8266WebServer.h> but you can serve the content the way you like. You can examine the ESP8266WebServer::on() method source code and adapt it according to your needs or you can just use that method as is.
Everything until now will result with calling the live_data() function and inserting it's response into the div which has the attribute w3-include-html="generated_data.html".
Now you only need to generate the live data inside the live_data() and to send the response:
void live_data() {
  String data_from_sensor;

  // read here the data from some sensor and store it in data_from_sensor
  String response = "
Live data

The data is: " + data_from_sensor + "some unit
";
  server.send(200, "text/html", response);
}

And that's it. The live data generated inside live_data() will show where was the empty div with w3-include-html attribute.
Of course, you can have more divs with different w3-include-html attributes and belonging server.on() statements.
There are many ways, this is just an example so you can get an idea from where to start. This code will not update the live data on and on but now that you know the mechanism, you can modify the code to do whatever you like.

This is a variation on Chupo_cro’s answer... His suggestion to use
XMLHttpRequest() is definitely the way to go. But unlike his answer, I
suggest here to not send HTML-formatted data. Just send the raw data
as JSON, which is the simplest data format suitable
for this job. Since your client computer is likely to be orders of
magnitude more powerful than your server, you can offload all the job of
presenting the data to the client JavaScript code. Keep your Arduino
server minimalist and have it only serve:

static content (HTML, JavaScript and CSS) from the SD card
raw live data as JSON.

And then let the client handle the presentation of the data in whatever
form you like.
Your static Web page would then contain no data and have instead
placeholders of the form ---. For example:

Rain sensor reading: ---,
--- rain

Temperature: --- °C
/ --- °F

Humidity: ---%

Dew point: --- °C

Your client JavaScript code starts by collecting references to those
placeholders:
// HTML elements with replaceable content.
var elements = null;

window.onload = function() {
    var getElt = document.getElementById.bind(document);
    elements = {
        rainValue: getElt("rainValue"),
        rainQuality: getElt("rainQuality"),
        tempCelsius: getElt("tempCelsius"),
        tempFahrenheit: getElt("tempFahrenheit"),
        humidity: getElt("humidity"),
        dewPoint: getElt("dewPoint")
    };
    setInterval(requestLiveData, 5000);
};

Then the page can be updated from live data simply by filling the
innerHTML attributes of the elements:
function dewPoint(temperature, humidity) {
    return ...;
}

// Update page from live data.
function updatePage(data) {
    elements.rainValue.innerHTML = data.rain;
    elements.rainQuality.innerHTML =
        data.rain < 300 ? "heavy" :
        data.rain < 500 ? "moderate" : "no";
    elements.tempCelsius.innerHTML = data.temperature;
    elements.tempFahrenheit.innerHTML = data.temperature * 9 / 5 + 32;
    elements.humidity.innerHTML = data.humidity;
    elements.dewPoint.innerHTML = dewPoint(data.temperature, data.humidity);
}

Notice that the data processing (Celsius → Fahrenheit conversion, dew
point calculation, converting the rain reading to words) is now done by
the client. The live data is retrieved from the server using Ajax, aka
XMLHttpRequest():
function requestLiveData() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState != 4) return;
        if (request.status != 200) {
            alert("Ajax request failed: "
                + "status = " + request.status);
            return;
        }
        var data = JSON.parse(request.responseText);
        updatePage(data);
    };
    request.open("GET", "/live_data");
    request.send(null);
}

You may have noticed the last line of the window.onload function is
setInterval(requestLiveData, 5000);

which means the requestLiveData function above will be automatically
called every 5000 ms.
Now, the only thing your server has to do is answer a request for
GET /live_data by sending the raw data as "application/json". It
should look like this:
{"temperature":15,"humidity":48.3,"rain":500,"soilMoisture":22}


text:
Nothing received from function returning array of strings
My read function returns an array of strings. i.e ssid and password
String* configuration::read() {
    String rw_ssid = "";
    String rw_pswd = "";
    const int keys = 2;
    String read_ssid_pswd [keys];
    if (EEPROM.read(0) != 0) {

      for (int i = 0; i < 32; ++i) {
        rw_ssid += char(EEPROM.read(i));
      }
      for (int i = 32; i < 96; ++i) {
        rw_pswd += char(EEPROM.read(i));
      }
      Serial.print("rPASSWORD: ");
      Serial.println(rw_pswd);
      read_ssid_pswd[0] = rw_ssid;
      read_ssid_pswd[1] = rw_pswd;
      Serial.print("Sending ssid:");
      Serial.print(read_ssid_pswd[0]);
      Serial.print(" Pswd: ");
      Serial.println(read_ssid_pswd[1]);
      return read_ssid_pswd;
    } else {
      Serial.println("Data wifi not found!");
      return read_ssid_pswd;
    }
}

I can see the print in the serial monitor.
Sending ssid:SSID Pswd: password

but where this function is called from I have set it up like this:
void setup() {
  Serial.begin(115200);
  Eeprom::configuration::initialize();
  String* ssid_password = Eeprom::configuration::read();
  Serial.print(">SSID: ");
  Serial.println(ssid_password[0]);
  Serial.print(">Password: ");
  Serial.println(ssid_password[1]);
  Funcs::connection::connectWifi(ssid_password[0], ssid_password[1]);
}

and I get thing in the prints  I thought its not giving any error at compile time so it should be correct.

Majenko has it right, your String array should be allocated in Setup().  Notice that I passed back the success/failure of your initial EEPROM test as the return value.
void setup() {
  Serial.begin(115200);
  Eeprom::configuration::initialize();
  const int keys = 2;
  String ssid_password[keys];
  if (Eeprom::configuration::read(ssid_password)) {
    Serial.print(">SSID: ");
    Serial.println(ssid_password[0]);
    Serial.print(">Password: ");
    Serial.println(ssid_password[1]);
    Funcs::connection::connectWifi(ssid_password[0], ssid_password[1]);
  } else {
    Serial.println("Data wifi was not found!");
  }
}

The String array is the parameter, not the return value.  It is passed by reference.  The copying of EEPROM chars to String doesn't need to be into temporary variables, in fact it's inefficient and pointless; it can go straight into read_ssid_pswd[0] and [1], but I didn't want to change your code excessively, and delete the debugging serial writes.
bool configuration::read(String read_ssid_pswd[]) {
    String rw_ssid = "";
    String rw_pswd = "";
    if (EEPROM.read(0) != 0) {

      for (int i = 0; i < 32; ++i) {
        rw_ssid += char(EEPROM.read(i));
      }
      for (int i = 32; i < 96; ++i) {
        rw_pswd += char(EEPROM.read(i));
      }
      Serial.print("rSSID: ");
      Serial.println(rw_ssid);
      Serial.print("rPASSWORD: ");
      Serial.println(rw_pswd);

      read_ssid_pswd[0] = rw_ssid;
      read_ssid_pswd[1] = rw_pswd;
      Serial.print("Sending ssid:");
      Serial.print(read_ssid_pswd[0]);
      Serial.print(" Pswd: ");
      Serial.println(read_ssid_pswd[1]);
      return true;
    } else {
      Serial.println("Data wifi not found!");
      return false;
    }
}

I see so just because the array in initialised in the setup method I do not have to return the array . thanks for posting an example.

tried your suggestion , but I got this error: expected ',' or '...' before 'read_ssid_pswd' at boolean configuration::read(String[] read_ssid_pswd) {

My bad.  Try read(String read_ssid_pswd[]) {

Thanks for the edits in the if statement and the function definition, both were my mistakes.

You can't return locally defined arrays like that. The array only exists in the function, and all you do is return a pointer to where that array was. As the array has gone when you leave the function your pointer just points to garbage.
Instead you should pass an array to the function that the function then populates.

but the save is in a different cpp file and I am trying to access from setup function of the sketch.

So? How does that affect what you pass to the function?

you said function then populates !

ah  I see just declare the read_ssid_pswd outside teh function module level.

Define your array in setup() then pass that as a parameter to the read function. The read function then uses that passed array which means setup() sees the same data. You can then use the return value to indicate success or failure.

I did that sorry, I got the error sayng incompatible types in assignment of 'String*' to 'String [2]' the function that returns the array is  declared as String* configuration::read(String read_ssid_pswd[2]) {...}

You should have String * as your receiving type.

you mean String* configuration::read(String *read_ssid_pswd) {...} ?

Yep. Just that.

I see, so I got compile working but in serial monitor i am getting massive stacktrace, however earlier what I was trying to do to have an array with only 2 items reserved length.

source: Stack Exchange

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

sort: votes


text:
Cannot run arduino as web client
I have ethernet shield mounted on arduino mega, I am able to run it as server but when i try to run it as client it doesnt work , most of the time it assigns itself 255.255.255.255 ip address which i get to know as i am printing from my sketch using Ethernet.localIP()  it sometimes randomly works but then it does nt establish connection with server, I have double checked there is no firewall on my router that can block arduino ethernet web client.
#include "Ethernet.h"
#include <SPI.h>
#include<dht.h>
dht DHT;

#define DHT11_PIN 8

double tempInC;
int humidity;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
//IPAddress ip(192, 168, 1, 177);

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,1,177);

byte subnet[] = { 255, 255, 255, 0 }; //assigning subnet mask
byte gateway[] = { 192, 168, 1, 1 }; //assigning gateway

EthernetClient client;
char server[] = "192.168.1.3"; // IP Adres (or name) of server to dump data to

String data;

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

  while (!Serial) {
    ; //wait for serial port to connect. Needed for native USB port only
  }
  Ethernet.begin(mac, ip, gateway, subnet);

  Serial.print(F("connected. My IP is "));
  Serial.println(Ethernet.localIP());
  // give the Ethernet shield a second to initialize:
  delay(1000);
  data = "";
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  delay(200);
  tempInC = DHT.temperature;
  humidity = DHT.humidity;
  Serial.print("Temp: ");
  Serial.print(tempInC);
  Serial.print(" Humidity: ");
  Serial.println(humidity);
  if (client.connect(server, 80)) {

    // Make a HTTP request:
    client.print(F("GET /arduino/add.php?temp1="));
    client.print(tempInC);
    client.print(F("&hum1="));
    client.print(humidity);
    client.println(F(" HTTP/1.1"));
    client.print(F("Host: "));
    client.println(server);
    client.println(F("Connection: close"));
    client.println();

  }
  else {
    Serial.println(F("connection failed"));
  }

  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  else {
    Serial.println("Client not available");
  }
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
  //  delay(60000); // WAIT FOR A MINUTE BEFORE SENDING AGAIN
  delay(10000);
}

Here is the output of what I get from above sketch
connected. My IP is 255.255.255.255
Temp: 26.00 Humidity: 63
connection failed
Client not available

Even when it gets correct IP assigned which I am setting up in the sketch the connection to server fails.
I am very upset not being able to run client. Please help.

This could be an SD card SPI bus issue.
Note that because the W5100 and SD card share the SPI bus, only one can be active at a time. If you are
using both peripherals in your program, this should be taken care of by the corresponding libraries. If
you're not using one of the peripherals in your program, however, you'll need to explicitly deselect it. To do
this with the SD card, set pin 4 as an output and write a high to it. For the W5100, set digital pin 10 as a
high output.

Check the Arduino shield datasheet.

Changing pin mode:
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);

So that means to be able to use both I would have to flip flop between SD card and w5100 ?

Yes most probably you will make pin 4 OUT when you will not use then 4 IN when you will be using it. And i think it is preferable not to use pin 4 for any i/o data. Like don't put your DHT on pin 4. I can see from your code you are using pin 8 so its fine.

thanks that helps, however even after it is connected I see it is not pushing data based on the web client call to URL as shown in above post !

@Ciastopiekarz try changing the GET method to POST.

Done that already

I don't know what the problem is, but I can see some issues with your code.  Perhaps fixing them will make it work, or at least get you closer.
Reading between the lines in your code, it looks like you are expecting an IP address from DHCP.  You won't get that, according to the documentation because you are specifying one.  Just so that you know.
You're calling the four-parameter version of Ethernet.begin() but using an invalid set of parameters.  You're probably meaning to use one of these:
Ethernet.begin(mac, ip, dns, gateway);
Ethernet.begin(mac, ip, dns, gateway, subnet);

or if you want to use DHCP (which I'd recommend, if you can, because managing them yourself is a pain), just use
int success == Ethernet.begin(mac);
if (success) { /* it worked */ }

Lastly -- and this is a guess --  I wonder if adding a delay(1000) after Ethernet.begin() would change the behaviour.  It's not really a solution, but it might help you debug.

I removed SD card I inserted yesterday night, and then it seems to work but not able to insert into db also instead of using server port 80 I used port 443, since I have HTTP to HTTPS redirection on apache web server running at home.

I don't understand the significance of what you're saying. New problems for a new question perhaps?

however , atleast you can tell me why removing SD card make it works.

I can't, sorry.

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


text:
how to do Arduino to esp8266 communication
I am trying to do Arduino to ESP8266 communication, but I am not able to send data to esp8266. However I can receive data from esp8266.
Here if my Arduino code:

#include <SoftwareSerial.h>
SoftwareSerial ESPserial(0, 1); // RX | TX

void setup()
{
  Serial.begin(115200);     // communication with the host computer
  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Enter 1 to turn led high & 2 to turn led low.");
}
// the loop function runs over and over again forever
void loop() {
  // listen for communication from the ESP8266 and then write it to the serial monitor
  if ( ESPserial.available() )   {
    Serial.write( ESPserial.read() );
  }

  // listen for user input and send it to the ESP8266
  if ( Serial.available() )       {
    ESPserial.write( Serial.read() );
  }

}

Here is esp8266 code:
void setup()
{
  Serial.begin(9600);     // communication with the host computer
  // Start the software serial for communication with the ESP8266
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  Serial.println("ESP -- Hello");
  delay(1000);
  // listen for user input and send it to the ESP8266
  if ( Serial.available() )  {

    int ledState = Serial.parseInt();
    if (ledState == 1) {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      Serial.println("ESP Led On\n");
    }
    if (ledState == 2) {
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      Serial.println("ESP Led Off\n");
    }
  }
}

Once I upload both sketches, then I can see it terminal " ESP -- Hello " keep printing comming from esp8266 but when I enter 1 or 2, its not sent to esp8266 due to which I never see "ESP led on/off" messages , so correct me guys what mistake I am making.

Don't ever use SoftwareSerial in pins 0 and 1!  And never use pins 0 and 1 for anything if you are using Serial for Arduino to PC communication.

@Majenko ok thanks then how can i solve the issue of this communication on UNO i have just these one RX and TX pair it 0,1 pins so should i try the same code on mega2560

you can use SoftwareSerial on any pair of pins. that is why it is called 'software' Serial

using SoftSerial on the hardware serial isn't working on Arduino properly as sometime data receive and sometime not with garbage added so Using digital pins  other  2, & 3  other than hardware serial resolved the issue.

Perhaps you should clarify that using SoftSerial on the hardware serial isn't working, choose any other digital pins than the hardware serial pins.

@MatsK thanks i updated the answer

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


text:
How to wake up Arduino with an rtc?
I am doing a data logger with an Arduino Mega2560 and I want to use a code to make it sleep when no measure is needed and wake it up with an RTC when time comes. The reason I want this is because I intend to run the code on a Pro Mini later so I need to save as much energy as I can. I am able to put the arduino to sleep using the alarm interrupt when a minute is passed but it doesn't wake up from sleep afterwards.
Here is the code I am using:

#include <Wire.h>
#include <RtcDS3231.h>
#include <avr/sleep.h>

const byte interruptPin = 2;
volatile bool alarm = 0;
volatile byte counter = 0;

RtcDS3231<TwoWire> rtcObject(Wire);

void setup() {

  Serial.begin(9600);
  Serial.println("Initialisation");
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, FALLING);

  rtcObject.Begin();

  RtcDateTime timestamp = RtcDateTime(__DATE__, __TIME__);
  rtcObject.SetDateTime(timestamp);

  rtcObject.Enable32kHzPin(false);
  rtcObject.SetSquareWavePin(DS3231SquareWavePin_ModeAlarmOne);

  DS3231AlarmTwo alarm2(
    0,
    0,
    0,
    DS3231AlarmTwoControl_OncePerMinute);

  rtcObject.SetAlarmTwo(alarm2);
  rtcObject.LatchAlarmsTriggeredFlags();

}

void loop() {
  if (alarm == true){
    handleAlarm();
    if (counter == 1){
      mesure();
      counter = 0;
      delay(100);
      sleepNow();
    }
  }
}

void handleInterrupt() {
  alarm = true;
  counter ++;
  Serial.println(counter);
}

void handleAlarm() {
  alarm = false;
  rtcObject.LatchAlarmsTriggeredFlags();
}

void mesure(){
  RtcDateTime timestamp = rtcObject.GetDateTime();

  Serial.print("time interrupt at: ");
  char time[10];

  sprintf(time, "%d:%d:%d",
          timestamp.Hour(),
          timestamp.Minute(),
          timestamp.Second()
         );
Serial.println(time);
}

void sleepNow() {
  Serial.println("Entering sleeping");
  delay(100);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // sleep mode is set here
  sleep_enable();                         // enables the sleep bit in the mcucr register
  attachInterrupt(digitalPinToInterrupt(interruptPin),wakeUpNow, FALLING);  // use interrupt 0 (pin 2) and run function
  sleep_mode();                           // here the device is actually put to sleep!!
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

  sleep_disable();         // first thing after waking from sleep: disable sleep...
  detachInterrupt(digitalPinToInterrupt(interruptPin));      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
Serial.println("Woke up");
delay(100);
}

I want to understand how to wake it up properly so I can later make it sleep first in the loop and wake it up only if an interrupt is detected from the rtc.
Thank you for your help !

Try to sleep in IDLE mode, or to attach the interrupt in LOW mode.

I tried both of your advice but none of them worked for me...

You may not need to use an RTC to wake up. Jeelabs has done extensive work on low-power consumption maybe you just need to use the jeelib library from Github. They even sold (not anymore) ultra low power optimized UNO compatible devices (https://jeelabs.org/202x/jnc/). You find jeelib on github on the linked page.
Look at the Sleepy class. It does some low level power saving magic directly with the hardware. It would be interesting to extract that class from Ports.h and Ports.cpp and try if it works standalone.
You simply use it with: Sleepy::loseSomeTime(32); and it will power down the whole MCU for some time. https://github.com/jeelabs/jeelib/blob/635113edea74b1290713360649679c3a13016304/Ports.h#L346
It uses the watchdog timer of the MCUs:
ISR(WDT_vect) { Sleepy::watchdogEvent(); }

If you use the DS3232RTC library then you can setup an alarm which is like an alarm. I have put a good tutorial on how to do that below.
https://thekurks.net/blog/2018/2/5/wakeup-rtc-datalogger
There is also other threads on arduino.cc you should check out. They might have additional work-arounds.
https://forum.arduino.cc/index.php?topic=333654.0
https://forum.arduino.cc/index.php?topic=99588.0


text:
Hex String -> Byte Array -> Serial Write
I'm writing code that I discussed in a previous post. I now have a setup where I send my Arduino an ASCII-encoded Hex String that represents the bytes I want to write to my serial device. I think I've got most the code figured out other than the way to best convert the hex string for sending
This Code is working
void SendCTRL (String &input)
{
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
  RS485Serial.write(cmd[i]);   // Send string someplace
  }
  delay(clen/4);
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
  Serial.println();

}

byte dehex(char c)
{
  // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
}

From what I understand something along the lines of char ISS = SubS.GetBytes(), but guidance would be appreciated

What your code is aiming at isn't particularly clear to me, but I will assume that for some obscure reason you want to accept an input String containing a series of ASCII-encoded hex digits, and create an array of half that many bytes with reconstituted byte values.
First, here are several criticisms of the code shown.
It's likely length(input) won't compile but that input.length() will.
The expression input.substring((2*i),(2*i)+1)) is a String of one character.  If you want two characters, use input.substring((2*i),(2*i)+2)).  And use i += 2 instead of i++ in the for loop.
I don't understand String CMD = CMD+ISS.  I won't say it's invalid, as I don't know without more research.  But it looks like it's declaring variable CMD and using CMD in the initialization of CMD.  [In the example code I give below, I assume CMD should begin as an empty string and be filled up with reconstituted bytes.]
RS485Serial.write(input); // Send byte to Remote Arduino looks mis-commented; presumably it will write out all of the input, not just a byte.
Using a timed delay for holding RS485 Transmit open, as in
delay(10);
 digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
may cause problems.  On the one hand, it may usually waste five to ten milliseconds of time; on the other, it might occasionally disable RS485 transmit before transmission finishes.  Instead, look for a flag to test for transmission complete, or look for a buffer-fill count, or compute how long to wait, etc.
The next paragraph describes some reasons that Strings may perform badly in this sketch.  For additional discussion of Arduino String objects, see arduino.cc's String page, and see Majenko's The Evils of Arduino Strings page.
Each of the String-object operations in the code creates a new String.  New String objects SubS and CMD are created and destroyed in each pass of the for loop.  The object headers (with type data and member variables, such as a buffer pointer and buffer size) can be stack-allocated, which is harmless (does not leak or fragment memory) but takes some time.  Each String object's character-buffer is heap-allocated: see code in cores/arduino/ file WString.cpp.  Heap fragmentation can and will occur.  ... In brief:  In this application where using String objects is clunky and in the way, you might as well use ordinary C strings instead of String objects.

Ok, with criticisms out of the way, here's some example code that converts ASCII-encoded hex digits into a command string.  Note, as I don't know the specs for RS485Serial.write() or how it determines how much to send, for demonstration purposes I've supposed it can handle a C string.
// Function declaration for dehex()
byte dehex(char c); // Get nibble value 0...15 from character c

void SendCTRL (String input) {
  const char *hin = input.c_str();  // Get character array
  int clen = input.length/2;
  // Next line invalid in C++, ok in C99.  Probably need to
  // instead declare a fixed-length array, cmd[MAXCMDLEN], etc
  char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2) {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  RS485Serial.write(cmd);   // Send string someplace
  delay(clen/4);        // Wait for write to complete? What rate?
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

byte dehex(char c) { // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
  // Above assumes that c is a 'hex digit' in 0...9, A or a ... F or f.
  // It would make more sense to just use 16 consecutive characters,
  // like eg 0123456789:;<=>? or @ABCDEFGHIJKLMNO so the above
  // could just say `return c & 0xF;`
}

Edit 2:

The first statement, byte dehex(char c); is a function declaration for the dehex() function.  It tells the C/C++ compiler the datatypes that the function accepts and returns.  Note, instead of a function declaration at that point, one could instead put the function definition itself (which in the above follows SendCTRL(), a dehex() caller that needs to know dehex()'s datatypes).  Some versions of the Arduino IDE appear to work ok without function declarations ahead of use, but almost all other C/C++ environments will not.
In this edit I added const before char *hin = input.c_str(); because ATE-ENGE reports  “char *hin =input.c_str() is giving me an invalid conversion error from const char* to char*”.  That error indicates the left-hand-side variable has a datatype different from that of the right-hand-side expression and an automatic conversion isn't available.  Note, unfortunately the arduino.cc c_str() webpage doesn't specify the return type of c_str().

Edit 3:  Changed for (int i=0; i < clen; i+=2) to for (int i=0; i < 2*clen; i+=2) per notes in another question's answer.
Edit 4:  Changed cmd[i/2] = dehex(hin[i])<<4 + dehex(hin[i+1]) to  cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]) to avoid an operator precedence problem.  The precedence of +, addition, is higher than that of <<, bitwise shift, which in turn is higher than that of |, bitwise OR.  The unparenthesized expression with + adds 4 to dehex(hin[i+1]) and uses the total as a shift count; not at all as desired.  Note, one can of course use parentheses to control the problem, as in the expression (dehex(hin[i])<<4) + dehex(hin[i+1])

This looks like what I want, thanks a lot! I have two questions. One, What does calling byte dehex(char c); at the beginning do?  Two char *hin =input.c_str() is giving me an invalid conversion error from const char* to char* how should I fix that?

@ATE-ENGE, see edit 2

Ok! that all seems to be working now. I seem to not be getting the same input and output though. If you could give me your thoughts on what might be going wrong. As an Example, the input  010307E40001C549 should return me (as ASCII \code) \01\03\07\E4\00\01\C5I or (as U8) [1,3,7,228,0,1,197,73] Instead I'm getting (as ASCII) \100~@\EE or (as U8) [16,48,126,64,238] Updated code is posted above

How do you know the input the Arduino gets is 010307E40001C549, and the output the Arduino sends [1,3,7,228,0,1,197,73]? Or is that what you sent to the Arduino, and received from it somewhere?  Do you have a way for the Arduino to display debugging output?  (All of that is info I'd need as basis for what to do next)

Got it working, the counting was off in two different places. I have working code posted above now. If you see any improvements though, I'd like to know :D

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


text:
Programmatically Change Arduino Com Port Name
I have some devices that, when I plug in, will display a unique name, usually a serial number, as opposed to "COM #" is there any way I can have my Arduino Uno (or Mega) give itself a different name in my program's set up structure?
Edit: My purpose here is that I'm writing a program on the computer side that needs to find the Arduino among multiple possible COM ports. I'm deploying this program over multiple computers that I don't have admin access to so changing the registry is likely a non-starter.
Right now, I'm going through each port and sending a *idn?\n (which my program responds to with a specific string). For another device I have, I can search the possible connections for a port named [device serial number] and test that one first.

When I plug in my Arduino, I'd like it to identify to the computer as an arbitrary string specified in the setup phase of the code as opposed to "COM #" as it does by default

So you don't want the default name of that specific serial port that is COM# Am I correct ? Please correct me if I have mistaken.

What platform are you using to connect to your Arduino, Windows or Linux? (Suspect Windows)

"will display a unique name" .... where do they display this "unique name"?

I am using windows, That is a correct understanding. In terms of display location: when given the option on my computer to connect to various devices, I can select COM port 1 -> COM port N or a string that represents the serial number of a device like "Tektronix 25145134514"

If you read this So it says:
You'll have to change the software on the Arduino USB chip itself,
and you may need to modify the drivers for the Arduino USB interface
on the computer side. It's not trivial, and probably not worth it.

Then according to this you need to toggle and tinker with the Driver software

Wait that means it is not the correct answer. So according to your plan you need to maybe toggle with IDE that is instead of manually changing the ports you want the software to identify on its own. So for that purpose you have to tweak with Arduino board bootloader, and say it send a message to the Arduino IDE on startup . After that you have to tweak with Arduino ide source codes and then tweak it to Search for that message and then it reads down the address that is its COM

Thanks! That's too bad that there isn't an easier solution. (As a side note I think you mean to say "tinker with," in US English at least "tinkle," is slang for urinate XD )

tinkle and tinker are different things, just don't tinker with you winkle when tinkling :)

On Windows you can change the "Friendly names" assigned to devices and COM ports are devices.  The process is basically open the device manager, open the device properties, find the 'Device Key' and then locate that in the registry and change the 'Friendly Name' value.
See this page for more details:
https://www.eightforums.com/customization/15321-tutorial-how-change-device-names-device-manager.html

Ok, is there a way to do this on my Arduino so that it would be constant from computer to computer?

No.  The name is generated by the device driver on the PC.  The Arduino has nothing to do with it.

Often those names can be used to ensure that every time you plug into a specific USB port on the PC you get the same COM number.


text:
SdFat Library what is dir_t*?
I'm using the SDFat library and the FatFile type has the functions:

bool FatFile::dirEntry(dir_t* dir)
Return a file's directory entry.
Parameters

[out] dir    Location for return of the file's directory entry.

Returns

The value true is returned for success and the value false is returned
    for failure.

And

uint8_t FatFile::dirName(const dir_t *dir, char *name)
Format the name field of dir into the 13 byte array name in standard
  8.3 short name format.
Parameters

[in] dir The directory structure containing the name.
[out]    name    A 13 byte char array for the formatted name.

Returns

length of the name.

From what I understand, I should be able to pass something like this into the functions:
dir_t Bass;
char dName [13];
FatFile BrowseFile;
BrowseFile.open("/Folder1/File1.txt", O_RDONLY);
Serial.print(BrowseFile.dirEntry(&*Bass));
Serial.print(BrowseFile.dirName(Bass,*dName));
Serial.println(dName);

to which the program should output
1
[Folder1's 8.3 name length]
[Folder1's 8.3 name]

However, I'm getting an error and I can't find any included examples that use these two functions in a sketch. if someone could explain what I'm doing wrong, it would be greatly appreciated.

However, I'm getting an error Then post the full error.

dir_t * is a pointer to a variable of type dir_t.
I don't know the API to which you refer, but the format for passing it would be:
dir_t Bass;
char dName[13];
BrowseFile.dirEntry(&Bass);
BrowseFile.dirName(&Bass, dName);
Serial.println(dName);

Thank you, that seems to be the correct format. Unfortunately, it returns information on File1.txt and not Folder1 which makes it less useful. Also, a link to the API is now in the question

Well, .dirEntry() gets the entry in the directory for the file, not the directory the file is in. FAT has no way of going "up" from a file. In fact I am not aware of any filesystem that has the concept of "up" - even going up a directory in a tree is actually going down into the directory called ".."

Oh, then I have a misunderstanding in regards to how FAT files work. Is there a good resource I can use to learn more about FAT? How would I go up a directory in a tree? Would it be as easy as saying BrowseFile.open([&directory],"..",O_READ?

In most filesystems a directory contains two special files ".", which is the current directory, and ".." which is the parent directory. If you want to go up the tree you have to get the ".." directory entry and open that as a directory. There's nothing like that for a file though, only directories.  You can start here for FAT information: https://en.wikipedia.org/wiki/File_Allocation_Table

what is dir_t*?

a pointer to a data type called  dir_t -> it must have been defined somewhere in  your code/libraries used.


text:
Issue with IF statement
The program plays a random mp3 file from an Adafruit mp3 breakout board. The trigger to play the song is a sharp IR sensor. Basically to play a file you pass your hand over the sensor and it plays the full track. If you want to stop the file playing pass your hand over again and it switches it to an off mode.
I wrote a while statement using millis() to keep track of time. I would like for the songs to keep playing for a defined time or if you pass your hand over it, it stops playing the music.
Right now it's only playing a single file. It appears that the if statement I have in the while loop is being ignored. The program goes straight to break when the file is played.
//----------------------------------------------------------
// MUSIC PLAYER
// vonderasche
// 3/26/2017
//----------------------------------------------------------

// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
#include <SharpIR.h>

// constants
#define ir A4
#define model 1080
#define TRIGGER_PIN  5
#define ECHO_PIN     6
#define MAX_DISTANCE 200

// These are common pins between breakout and shield
#define DREQ 3
// VS1053 Data request, ideally an Interrupt pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define CARDCS 4 // Card chip select pin
// These are the pins used for the breakout example
#define BREAKOUT_DCS 8
// VS1053 Data/command select pin (output)
// used to be pin 8
#define BREAKOUT_RESET  9 // VS1053 reset pin (output)
#define BREAKOUT_CS     10 // VS1053 chip select pin (output)

Adafruit_VS1053_FilePlayer musicPlayer =
// create breakout-example object!
Adafruit_VS1053_FilePlayer(BREAKOUT_RESET, BREAKOUT_CS, BREAKOUT_DCS,     DREQ, CARDCS);

SharpIR SharpIR(ir, model);

int state = 1;
const unsigned long onTimer = 1200000;

/// File listing helper
void printDirectory(File dir, int numTabs) {
  while (true) {
    File entry = dir.openNextFile();
    if (!entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i<numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

// random seed function
int rNumbers(int rNum) {
  randomSeed(analogRead(3));
  rNum = random(1, 10);
  return rNum;
}

// play a certain file
void playFile(int rNum) {
  switch (rNum) {
    case 1:
      Serial.println(F("Playing track 001"));
      musicPlayer.startPlayingFile("track001.mp3");
      break;
    case 2:
      Serial.println(F("Playing track 002"));
      musicPlayer.startPlayingFile("track002.mp3");
      break;
    case 3:
      Serial.println(F("Playing track 003"));
      musicPlayer.startPlayingFile("track003.mp3");
      break;
    case 4:
      Serial.println(F("Playing track 004"));
      musicPlayer.startPlayingFile("track004.mp3");
      break;
    case 5:
      Serial.println(F("Playing track 005"));
      musicPlayer.startPlayingFile("track005.mp3");
      break;
    case 6:
      Serial.println(F("Playing track 006"));
      musicPlayer.startPlayingFile("track006.mp3");
      break;
    case 7:
      Serial.println(F("Playing track 007"));
      musicPlayer.startPlayingFile("track007.mp3");
      break;
    case 8:
      Serial.println(F("Playing track 008"));
      musicPlayer.startPlayingFile("track008.mp3");
      break;
    case 9:
      Serial.println(F("Playing track 009"));
      musicPlayer.startPlayingFile("track009.mp3");
      break;
    case 10:
      Serial.println(F("Playing track 010"));
      musicPlayer.startPlayingFile("track010.mp3");
      break;
    }
  }

void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit VS1053 Simple Test");
  if (!musicPlayer.begin()) {
    // initialise the music player
    Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
    while (1);
  }
  Serial.println(F("VS1053 found"));
  if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1); // don't do anything more
  }
  // list files
  printDirectory(SD.open("/"), 0);
  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(30, 30);
  // Timer interrupts are not suggested, better to use DREQ interrupt!
  //musicPlayer.useInterrupt(VS1053_FILEPLAYER_TIMER0_INT);
  // timer int
  // If DREQ is on an interrupt pin (on uno, #2 or #3) we can do background
  // audio playing
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT); // DREQ int
}

void loop() {
  // calls random number function
  int randomNumber;
  // takes distance measurment
  float distance = (SharpIR.distance() / (2.4));
  static enum { ON, OFF } state;
  // if distance range is between certain values switch the state
  if (distance > 1 && distance < 12) {
    switch (state) {
      case ON:
        {
        unsigned long previousMillis = millis();
        unsigned long currentMillis = millis();
        while ((currentMillis - previousMillis) < onTimer) {
          Serial.println("inside while loop");
          randomNumber = rNumbers(randomNumber);
          // calls random number function
          playFile(randomNumber); // plays music file
          float distance2 = (SharpIR.distance() / (2.4));
          delay(1000);
          //breaks timer if hand swipe
          if (distance2 > 2 && distance2 < 8) {
            Serial.println("Break");
            break;
          }
          currentMillis = millis();
        }
        state = OFF;
      }
      break;
    case OFF:
      {
      Serial.println("Triggered Off");
      musicPlayer.stopPlaying();
      state = ON;
      }
      break;
    }
  };
}

There's probably a good chance that when you trigger the ON state by placing your hand close to the sensor, the while loops runs and hits the if statement before you have moved your hand out of the trigger distance.
I see the delay of 1 second before the if, however, you take the reading of the IR sensor before the delay.
Try the delay before reading the sensor:
        ...
        playFile(randomNumber);  // plays music file

        delay(1000); // let the user move their hand
        float distance2 = (SharpIR.distance() / (2.4));

        //breaks timer if hand swipe
        if (distance2 > 2 && distance2 < 8)
        {
        ...

If you wanted to remove the delay function (highly recommended) after playing the file, set the state to something like PLAYING.
Then in the PLAYING state switch case you first wait for an IR reading that there is no hand present (allowing the user to finish moving their hand away), set a flag that you are ready to detect the hand. Then if that flag is true and the IR sensor reads a hand, then you can move to the OFF state.
You can add a second condition to the PLAYING state to test for elapsed time as well.

that seems to work. Ill look into trying to implement a flag setup later.

The intent of some of your code isn't clear, and the description “The program goes straight to break when the file is played” looks wrong – it appears that at least one delay(1000) will occur between start and break, so perhaps you mean that about a second after playing starts, it breaks.
If so, here is a possible explanation of that behavior:

At the beginning of loop(), you say distance = (SharpIR.distance() / (2.4));
Suppose that results in a value between 2 and 8.  Then the if condition (distance > 1 && distance < 12) will be true, so the body of the if will execute.
state initially is ON (state is static, and per §6.7.9.10 of the N1570 C++ spec, apparently gets initialized to 0, which corresponds to ON) and will be ON after each execution of the OFF case in loop().
When state is ON, we proceed into the ON case of the switch, set some variables to current time, then use a few microseconds to serial-print and call rNumbers() and playFile().  Then distance2 = (SharpIR.distance() / (2.4)); sets distance2 to about the same value read a few microseconds earlier into distance; as we supposed earlier, a number between 2 and 8.
With delay(1000), the program sits for a second doing nothing and paying attention to nothing.
The (distance2 > 2 && distance2 < 8) condition for the next if is  true, so program prints "Break", breaks out of the while, turns off state, breaks out of the switch, exits loop(), enters loop(), etc.

However, now that a second has gone by, the Sharp sensor shouldn't be reading a gesture.  If it is, that will allow the OFF case to execute and call musicPlayer.stopPlaying().

Note, issue the randomSeed(analogRead(3)) call only once, and do so within setup().  Calling it within each rNumbers() call is going to give you non-random numbers.


text:
How can I set 4 Arduino Leonardo PWM-ports between 200Hz and 1kHz?
I've noticed that I can set D9, D10, and D11 to around the timer 1 can be set to ~244Hz. However I need 4 ports that are between 200-1000Hz but I have been unable to figure out how to find the last one. I can't really touch timer 0 as they control millis etc.

Can't you use a software PWM? If your loop is long ok, you can't, but if it isn't maybe you can just implement it..

The ATmega32U4 on the Leonardo has 4 timers, named Timer0, Timer1, Timer3 and Timer4. Timer0 would be used for millis().
Timers 1 and 3 are 16-bit timers, and Timer4 is a 10 bit timer.
You can get a wide range of frequencies by changing the prescalers and other factors. A bit would depend on whether you want them to all have the same frequency (but maybe with different duty cycles) or different frequencies. Each timer has two "ports" associated with it, so you can have different outputs - up to a point - for each timer. A given timer can only be in one mode at a time, which limits a bit what its two output ports can be doing at one time.
I have a page about timers which is for the Atmega328P, but the Leonardo timers have a lot in common with that. For more details see the ATmega32U4 datasheet.
You could get a more detailed answer if you clarified what the exact frequency you want is, what mode (eg. PWM, fast PWM or something else) and whether each output should be the same or different frequencies.

According to the Leonardo product page:

PWM: 3, 5, 6, 9, 10, 11, and 13. Provide 8-bit PWM output with the analogWrite() function.

So even if you lose two to Timer 0, you should have 5 outputs left (it looks like the "B" side of Timer 1 and Timer 4 share the same pin).

According to Arduino Leonardo, you have available for PWM configuration ports numbered 3, 5, 6, 9, 10, 11 and 13. The specifications presented there do not provide the range of the frequency available, but I would expect that if you are able to use 9, 10 and 11, one of the others would fall into place.


text:
Is it possible to increase the Arduino's input and output pins?
I am undergoing a BSc (Hons) Degree in Computer Science and working on an Arduino project.
I am using the Arduino Mega and even though this microprocessor has plenty of input and output pins I am running out.
In the event that there are no more I/O pins available for me to make use of, and I am also referring to both analog and digital pins, is it possible to increase them?
I did some research, however the solutions are too vague... One of the suggestions was to use one or more of the following: 74HC595 8-Bit Shift Register DIP-16.

I am good at coding however when it comes to hardware sometimes I'll need some push.
Thanks a lot.

Could you give us some specific numbers? Like how many output-pins? How many input-pins? How many analog pins? Also what is connected to the different pins. E.g. leds can be placed in a matrix, and multiplexed to massively reduce the number of pins needed.

Posting an image of an IC package is not a meaningful way to propose an idea, use the part number and a functional description

There are lots of multiplexer ideas, the port expanders people have mentioned will help or you can do a search for "arduino multiplexer" or similar. (the 74HC595 you have linked is a very common device used for this sort of thing.)

Also do a search on this site, by doing something like: http://arduino.stackexchange.com/questions/tagged/multiplexer

Hi Chris Stratton the part number of the attached image is: 74HC595 8-Bit Shift Register DIP-16 IC CF.

IMHO if you don't tell us what you want the pins to do it'll be very difficult to give you more than basic ideas. Are you driving LEDs? if you need independent channels, use a matrix arrangement or charlieplexing. Are you using buttons? definitely matrix arrangement. Analog pins? maybe an analog multiplexer, or external serial ADCs. lots of parallel wires? maybe you can serialize them (for instance LCDs use 7-11 pins, but you can find easily serial LCDs which use only 2-3 pins, and are highly expandable). Different scenarios? use one, two, three port expanders. Just explain what you need

You could use an MCP23017 port expander to get 16 more pins. It communicates via I2C. The pins can be set as inputs, outputs, or inputs with pullups.
Adafruit has a library for the expander: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library
This is the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf
As an alternate solution, you could just add another Arduino Mega to your project, and have them both communicate via serial. You could set up state machines on each one (like in Mr. Gammon's tutorials: http://www.gammon.com.au/statemachine) for fast communication. That way you could easily add an extra 52 pins to your project.

Hi Jerry, thank you so much for the informative answer.
In addition what would you recommend as an effective programming language to interface with the arduino. At this moment in time I am considering to use ASP.NET and creating a web application.
The reasoning behind this is to create a website and display and store some of the data read from the arduino's sensors in a database.
Thanks again.

You might want to look into ready-made IoT services. Thingspeak.com is a popular free one. You could download the Thingspeak library for Arduino, attach an ethernet shield, and have the Arduino upload the data by itself. When I don't do it like that, I like to use a Python daemon that grabs the Arduino data via the serial port (pyserial module) and uploads it to the IoT site. Thingspeak has easy to use Python examples too.

You can either use external hardware or communicate to a 2nd Arduino and control the 2nd Arduino's digital and analog ports.  Being good at coding would suggest you would prefer communicating to a 2nd Arduino.  Also, most hardware solutions only add digital pins, not analog pins.

You can use a CD74HC4067 Mux multiplexer to increase the number of inputs/outputs. This IC will convert 4 analog or 4 digital pins to 16 inputs and outputs.


text:
Serial communication on Arduino Uno
I have a Raspberry Pi 3 connected to the serial of my Arduino Uno (pins 0 and 1), but I also have another device connected to two other serial pins on the Arduino (pins 10 and 11, using the SoftwareSerial library).
What I want to do is send a string from the RPI, then the Arduino gets it and resends that information through the other serial port to my device.
Until now the Arduino can receive the information from the RPI, but I'm not sure how to send that same string through the other serial port, the one going to the device.
Here is the code I'm using:
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }
  portOne.listen();
  while(portOne.available() > 0){
      Serial.println("Data from port one:");
      Serial.println(b);
    }
  }

I just get the data coming from the RPI, but nothing from portOne.
Any thoughts?

You might find this interesting about buffers on both sides of a Nano connected to a Raspian system running a Python data logger, using just a regular USB programming cable between the two:
https://arduino.stackexchange.com/questions/11710/does-data-came-on-serial-port-store-for-some-time

Instead of just using pins 1 and 0 I use the regular serial-to-USB programming cable.  Ont he Pi it comes in as /dev/ttyUSB0 or /dev/tty ACM0 depending on the board.  The main advantage of doing this is that you can WiFi int o your Pi with RDP and remotely reprogram the ASrduinos on the fly as necessary.  Your strange readings may well be because of the way you are cabling to the module.  Perhaps try software.serial and regular pins?

After reading more about the SoftwareSerial, I managed to get the communication I wanted in a simpler way. This is what I ended up using in my void loop:
void loop() { // run over and over

  if (Serial.available()>0) {
    HW = Serial.read();
    mySerial.write(HW);

  }

  if (mySerial.available()>0) {
    SW = mySerial.read();
    Serial.write(SW);
  }
}

Thank you all for your help, your answers gave me also a better understanding of what I was doing.

Your code is not reading the SoftwareSerial. b is only populated when the Pi sent data. The loop below sends what it reads from the SoftwareSerial, after that is prints a new line println() (only because that's what your code is doing)
The listen() method of SoftwareSerial is only required if you have more than one SoftwareSerial connection.
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }

 //not required with only one software serial connection
 //portOne.listen();

  if (portOne.available() > 0)
  {
   while(portOne.available() > 0){
      byte byteRead = portOne.read();
      Serial.write(byteRead);
    }
    Serial.println();
   }
  }

I tried something like this with no luck. I read that a limitation SoftwareSerial has, is that the ports can retrieve data one at a time. Could this be affecting me? should I interrupt the serial port between the RPI and the Arduino?

Try the softwareSerial on pins 2 and 3 otherwise post a code example. You haven't given much information such as baud rates so the issue could be anything. There isn't normally an issue using serial and soft serial together.

I added an Edit of the question where I added the code.

I have updated the answer, see if that makes sense to you.

If you goal is to relay a string from RPI through the Arduino to a device connected via SoftwareSerial then you should be doing something like this:
#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {

  if (Serial.available() > 0) { // data available on HW Serial
    b = Serial.readString();    // Read it
    portOne.print(b);           // and write it to SW Serial
  }

}

authors: Сергей Вуколов


text:
Problems running several Arduinos off of one HC-05 Tx pin
TL;DR: Multiple Arduinos listening to a single serial rail are burning out my HC-05's TX pin. Arduinos are leaking voltage onto the signal rail. How do I stop, or isolate that to keep from burning out Bluetooth TX pin?
I'm trying to build an LED-based track light that uses an HC-05 to communicate with up to 8 Arduinos to control up to 16 LEDs total. Each Arduino can only control 2 LEDs because of the shape and form factor of the project.
The track has 3 rails, 12V, Ground and Signal and all Arduinos share the same rails. Hopefully the schematic below does a good job explaining it.

On to my issue. Initially, I was getting almost 5V from my pin 7 (SoftwareSerial pin) on the Arduinos, which was quietly ruining the TX pin on my HC-05. I lowered that to about 1v after using pinMode(bluetoothTx, INPUT);, which is good but not good enough. That voltage starts to add up as I add more and more Arduinos to the overall setup.
My solution in theory is to add diodes to pin 7 on the Arduinos, so they can't put voltage on the signal rail. This drops the voltage by 0.7v from what I've read, which most likely is why the Arduinos aren't reading a signal now, because that drops it below the logic level required, since the HC-05 is only putting out 3v3. So I think to add a level shifter on the HC-05 to pump up the signal to 5v, then the diode's voltage drop shouldn't matter right? See schematic below.

My solution seems unnecessarily convoluted and I don't even know if it would work. The more I read without bouncing the information off of others, the more confused I am becoming. Now after reformatting this post for an hour, I am thinking about a decoupling capacitor between the pin and ground... Will that have the effect I am looking for?
I also looked into using a pulldown resistor, but from everything I've seen (and from the first electronics course I've taken), it seems like an inappropriate solution. The examples I've seen usually use a switch, which makes sense, but for my application I am protecting the TX pin on my HC-05, so I think it would not give the effect I am looking for (tapping the line in between resistor and pin would not isolate the voltage, tapping in after the resistor would short the signal to ground).
I'm including my code for completeness, but the schematic is where I think I need help. Could someone point me in the right direction, I don't mind working for my answers but I've been going solo at this for over a month now, and I'm not even at the point in my education where we've covered much logic yet. I'm reaching a little here.
#include <EEPROM.h>
#include <SoftwareSerial.h>

byte address = 1; //change this to change light address
byte lightno = (address + 1); // variable to print light number
int addressShifter= ((address)*500); //This number will be subtracted from input
int bluetoothTx = 7; //btTX to pin 7 //input from HC-05
int bluetoothRx = 8; //btRX to pin 8 //not used
int led1 = 3; // the PWM pin LED1 is attached to
int led2 = 5; // the PWM pin LED2 is attached to
int brightness1 = EEPROM.read(0); //Recalling previous setting
int brightness2 = EEPROM.read(1); //Recalling previous setting
int thismodMin = (0 + addressShifter); //min two-byte looked for
int thismodMax = (499 + addressShifter); //max two-byte looked for

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); //naming it bluetooth and assigning it to the variables shown

void setup() {
    pinMode(led1, OUTPUT); // sets the pin as output
    pinMode(led2, OUTPUT); // sets the pin as output
    pinMode(bluetoothTx, INPUT); // sets the pin as input
    //Setup usb serial connection to computer
    Serial.begin(9600);
    //Setup Bluetooth serial connection to android
    bluetooth.begin(9600);
    analogWrite(led1, brightness1); //Set Led brightness from stored values
    analogWrite(led2, brightness2); //Set Led brightness from stored values
    Serial.println("SETUP COMPLETE, I am Light #"); //Identify self
    Serial.println(lightno);
    Serial.println("expecting Min "); //Min value listened for
    Serial.println(thismodMin);
    Serial.println("expecting Max "); //Max value listened for
    Serial.println(thismodMax);
}

void loop() {
    //---------Serial Communication---------
    if(bluetooth.available()>= 2) {
        unsigned int blu1 = bluetooth.read();
        unsigned int blu2 = bluetooth.read();
        unsigned int blueinput = (blu2 *256) + blu1;
        //I don't know why any of the above is neccesary but it will not read correctly without this conversion
        //Serial.println("blueinput = "); Not used
        //Serial.println(blueinput);  Not used
        if (((blueinput) >= (thismodMin)) && ((blueinput) < (thismodMax))){
            //If this blueinput is within this modules adress range, convert signal to PWM
            int thisMod = ((blueinput) - (addressShifter));
            //Convert blueinput to a value this module will work with (0-500)
            //-----------Lights---------
            if (((thisMod) >= 0) && ((thisMod) < 100)){ //0=off 1-100=on-Bright
                brightness1 = ((thisMod)*2.55); //converts percentage brightness to PWM value
                analogWrite(led1, brightness1); //apply brightness
                //      Serial.println("brightness1: "); //diagnostics
                //      Serial.println(brightness1); //diagnostics
                delay(10);
            } else if (((thisMod) >= 101) && ((thisMod) < 201)){ //101=off 102-201=on-Bright
                brightness2 = (((thisMod)-101)*2.55); //subtract starting value and then convert percentage brightness to PWM value
                analogWrite(led2, brightness2); //apply brightness
                //      Serial.println("brightness2: "); //diagnostics
                //      Serial.println(brightness2); //diagnostics
                delay(10);
            } else if ((thisMod) == (399)){ //if specific code recieved
                EEPROM.write(0, brightness1); //store brightness setting for light 1
                Serial.println("Epprom1 written");
            } else if ((thisMod) == (424)){
                EEPROM.write(1, brightness2); //store brightness setting for light 2
                Serial.println("Epprom2 written");
            } else{}
        }
    }
}

Have you considered that it's not the voltage on the lines, but rather the current that the TX pin is sourcing when connected to multiple Arduinos in parallel that is burning out the pin?

first of all just to clarify some things.
softwareSerial library sets PinMode for rx,tx declared pins internally so it should not have any impact on voltages you measure if you include pinMode(bluetoothTx, INPUT); and if this happens, as you describe, it indicates a problem.
a pin declared as INPUT is on a high impedance state which means that it will not (in general) affect signals connected to it.
an RX pin, by default is pulled up which means that when you do not have anything connected to it, you should measure 5V and when you connect it to GND you should read 0V.

i tried to reproduce your problem by implementing your first schematic utilizing 3 arduinos as receivers with the difference of having another arduino as transmitter instead of HC-05 and using a simplified version of your program (see it below).
I could not reproduce it. Also, I suspect that parallel pull up resistors from ~8 arduinos may be the problem, so I would suggest:

make sure communication between HC-05 and only one arduino works.
try connecting HC-05 with two arduinos and see if both arduinos are able to read incoming data.
keep adding arduinos and checking if every arduino can read incoming data.

also try with another arduino as transmitter instead of HC-05 in case you still have a problem and post the results so we can further investigate .
#include <SoftwareSerial.h>

int bluetoothTx = 7;    //btTX to pin 7 //input from HC-05
int bluetoothRx = 8;    //btRX to pin 8 //not used

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);  //naming it bluetooth and assigning it to the variables shown

void setup()
{
        //Setup usb serial connection to computer
        Serial.begin(9600);

        //Setup Bluetooth serial connection to android
        bluetooth.begin(9600);

        Serial.println("SETUP COMPLETE, I am Light #");  //Identify self
}

void loop()
{
        //---------Serial Communication------
        if(bluetooth.available() )
        {
             Serial.print(bluetooth.read(),HEX );
        }

}

Thanks for such a thorough and fast reply, I tested both your code and my own on my uno, mega and nano and all seem to measure 4.5-5v with no load with multimeter (DMM)connected between pin 7 and ground. With a load (2.2k resistor to ground) voltage drops immensely (like a dead batter would with high impedance) so I see what you are saying. With High impedance, the voltage would show but not be there as soon as a load is applied? That said,

the voltage without load and with load both drop significantly when I specify pinmode input, can you verify that on your end? If my devices are normal, will this voltage without load hurt my TX pin or is that unrelated? When you say parrallell pull up resistors would that apply to the TX pin that is an input, I assume that the resistor that is giving it high impedance is that same that functions as a pullup, just connected differently? Lastly, if I'm connecting that 2.2k resistor for pin 7 to G, and the voltage drops a ton, I think that takes care of my problem right just using a pulldown?

ok, I found an HC-05 and have connected it's TxD pin to 2 uno's , one micro, one mega, all at the same time. Note that on arduino mega, pin 7 cannot operate as softwareSerial RxD pin, so I used it's pin 53 instead. The voltage on the line, when not transmitting any data, is stable to 3.3V as expected, regardless of whether or not pin 7 (or 53 for mega) is explicitly declared as INPUT (with pinMode function). I still suggest you follow the steps provided on this answer and report back on which step problems start appearing.

for the time being, do not concern yourself with pull up resistors think I described.It has a small probability of being the problem source and we must narrow down the problem first.


text:
Arduino Mega + SIM808 GSM + GPS Module + Program Switch ON without pressing Push Button?
I am new to IOT and tried out integration and a small test code with an Arduino Mega + SIM808 + GSM + GPS Module. It works fine with the SIM808 Library.
My requirement is to put it in an enclosure, but when the power restarts, for some reason we have to manually start the SIM 808 + GPS + GSM Module. Can we control it from code? Can we do a software trigger from Arduino code?
Maybe if we have some pins to connect and trigger the power on. Kindly provide inputs/suggestion for this module.
If you are aware of some module that can be started through code kindly suggest.
Here's one reference I found for a different module with Software Trigger.

I tried connecting D9 to 5 V and Damn it works !! ,, I don't know where didi you get that information from but it works giving 5V for D9 on sim808 evb 3.2 for 3 - 4 seconds will make it power on .

There is a simple way of power the module without pressing the button. There is pin call D9 at the bottom right corner of the module. Just power the pin by Arduino digital pin or 5v pin around 3, 4 seconds. Then it will power the whole module. No need to press the press switch. Make sure you connect power(9V-12V) to the board and provide 5V and GND to the sim808 module. below figure shows the pin D9

This is great solution, vote up! Anyway please how did you get to this information? As I bought this board on Aliexpress I have no datasheet.

About the 5V, if the board is powered by DC044 then V_IN is not needed. Note: blue arrow on the image is pointing to the VMCU which controls the high level of TTL UART.

Google probably answered my "D9" question: https://www.elecrow.com/wiki/index.php?title=SIM808_GPRS/GSM%2BGPS_Shield_v1.1

I can't get a great view of the board, but if you are pressing the button just below "GSM" and "Made" then I would suggest soldering some leads onto the button and connecting them to a digital output and Gnd on the Arduino.  (You might need resistors and stuff)  Then when you wanted to press the button you could pulse the line high.

Thanks ! will try the same and add relay ..and control using arduino !


text:
Wire.h not found!
Here's the code that's making this error:
#include "Wire.h"

Here's the error:
fatal error: Wire.h: No such file or directory
 #include "Wire.h"
                  ^
compilation terminated.
Error compiling.

I also can't include any file from my Arduino\libraries folder. I tried to reinstall the IDE several times in different places and nothing happened. Why is this happening?
EDIT: after some time I discovered that this error occurs in header files only, not in sketches!

Could you clarify a little more on your setup of the IDE and the full paths to those libraries and if you have any duplicates. Also what is the settings you chose in the Boards menu.

D:\Arduino\hardware\arduino\avr\libraries\Wire\Wire.h And I chose the Arduino Uno COM3

Is the library there header there(I know its an obvious ques). That is where the arduino system should be looking when UNO is chosen

yes it is there

try hard linking it to the exacr path in the #include macro. Also what version of the IDE are you using?

my version is 1.6.3

Change it from #include "Wire.h" to #include <Wire.h>

I still get the same error

Delete your IDE. Delete your preferences.txt file. Download and install 1.6.9

Use #include <Wire.h>
Including files in double quotes (") will point to headers in current working directory first.
Edit: ... and there is nothing wrong with copying headers to CWD if you are modifying them, but that's probably not what you want.

First go to your library folder and check whether u included that Wire.h header file or not.If not then first include that file then problem will get solved automatically.

The line that is causing the problem in the include statement, the one you think will fix it. If that's not what you mean please can you clarify your answer?

I copy here the answer from https://forum.arduino.cc/t/wire-h-no-such-file-or-directory-solved/297761, cause it worked for me:

It's not enough to put "#include <Wire.h>" in the source file you are using the library in. It seems you must also put "#include <Wire.h>" in the main *.ino file for the sketch as well, before it can be used in any other source code files.

I had a similar issue and found this question. However, the solution for me is different.
I already had #include <Wire.h>, nevertheless the compiler told me it's missing. It turned out, I had selected a wrong board from a previous project. Needed to change to "Arduino Uno".


text:
Arduino Serial data communication with NodeJS
I am using an Arduino Uno and a DTH11 temperature sensor to read temperature and then send that value to a computer via the serial port.
A NodeJS application is running on the computer and captures that value and writes to a log file.
When I try to get values from my NodeJS application, sometimes the value is broken into two values. Eg: 25 -> 2 and 5
This is my Arduino code:
dht DHT;

#define DHT11_PIN 7
float tem [4];

void setup() {
  Serial.begin(9600);
  pinMode(12, OUTPUT);
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  int val = (int)(DHT.temperature);
  Serial.println(val);
  delay(600000);
}

This is my NodeJS program.
var fs = require('fs')
var logger = fs.createWriteStream('/data/Temperature/temperature.csv', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

var SerialPort = require("serialport")
var serialPort = new SerialPort("/dev/ttyACM0", {
  baudRate: 9600,
});

serialPort.on("open", function () {
  serialPort.on('data', function(data) {
    var moment = require('moment');
    var dayTime = moment().format('YYYY-MM-DD,hh:mm');
    var val1 = data.toString();
    var val = val1.trim();
    if (val == '') {
      console.log('no data');
    else {
      console.log(val);
      logger.write(dayTime + ',' + val + '\n');
    }
  });
});

Is it a problem with my code?
Thanks in advance.

@LookAlterno yes, sometimes its getting data properly. So how I can get char by char?

As Look Alterno wrote in a comment, you need to parse the incoming data on the receiving side. In this instance, you have to look for the line terminators. The Node.js serialport module provides a parser for this called Readline. Read that doc and use it.


text:
My Arduino Ethernet shield is not working
Actually I'm using a W5100 Hanrun HR911105A 16/02 Ethernet shield with an Arduino Uno (original).
I tried this code from the examples:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};
IPAddress ip(192, 168, 1, 177);
IPAddress myDns(192,168,1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
// telnet defaults to port 23
EthernetServer server(23);
boolean gotAMessage = false;
// whether or not you got a message from the client yet

void setup() {
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // start the Ethernet connection:
  Serial.println("Trying to get an IP address using DHCP");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // initialize the Ethernet device not using DHCP:
    Ethernet.begin(mac, ip, myDns, gateway, subnet);
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  ip = Ethernet.localIP();
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(ip[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
  // start listening for clients
  server.begin();
}

void loop() {
  // wait for a new client:
  EthernetClient client = server.available();
  // when the client sends the first byte, say hello:
  if (client) {
    if (!gotAMessage) {
      Serial.println("We have a new client");
      client.println("Hello, client!");
      gotAMessage = true;
    }
    // read the bytes incoming from the client:
    char thisChar = client.read();
    // echo the bytes back to the client:
    server.write(thisChar);
    // echo the bytes to the server as well:
    Serial.print(thisChar);
    Ethernet.maintain();
  }
}

That code prints the following on the serial monitor:
Trying to get an IP address using DHCP
Failed to configure Ethernet using DHCP
My IP address: 192.168.1.177.

So what is the problem? Why it is not connecting? I tried all the ethernet examples, but not one works. I don't know, maybe the problem is that I don't have a sticker of MAC address on the shield and I'm using the MAC address of the examples. Or maybe I'm writing the IP address wrong? Here is the data from the network connection details.
Connection-specific DNS Suffix: zte.com.cn
Description: Intel(R) Dual Band Wireless-AC 3165
Physical Address: 72-57-C5-BC-66-07
DHCP Enabled: Yes
IPv4 Address: 192.168.1.2
IPv4 Subnet Mask: 255.255.255.0
IPv4 Default Gateway: 192.168.1.1
IPv4 DHCP Server: 192.168.1.1
IPv4 DNS Server: 192.168.1.1
IPv4 WINS Server:
NetBIOS over Tcpip Enabled: Yes
Link-local IPv6 Address: fe80::b523:b9f2:b43c:6a8a%14
IPv6 Default Gateway:
IPv6 DNS Server:

My router is a ZTE model ZXHNH108N.

Are you using the right sort of cable, Cat5e straight through, not crossed.  DHCP seems enabled of the router, so do you have any spare addresses in your pool?  Do you use mac address filtering?  It looks like your router can't/won't give the board an address rather than there being anything wrong with the shield.

No i don't make anything from that because I don't know what is that . May be if you discuss it to me we can solve it . Actually i don't know if there is any permission i should make from the router every thing here is on its difficult  . And i don't know what is the filtring of the mac address

Your doomed then! :)  Hopefully the answer clears things up for you.

If your Arduino can not get an IP address, it could be because there is a problem with your code, your shield or your network.
There doesn't seem to be a problem with your code from a quick glance, so let's look at the network.

The cable. Are you using the right sort of cable? You should be using a Cat5e straight through cable. Cat5e is the type of cable for Ethernet, if it is plugged into the router and you didn't make it yourself, it is probably either a CAT5e or CAT6 cable, so it will be OK. There are two types of cable and they are almost impossible to tell apart, the normal sort is a "straight through" cable, which means the Transmit and Receive pins at one end go to the Transmit and Receive pins at the other end. The other sort is a "crossed" cable where the Transmit goes to the Receive, this is for connecting a computer to a computer.  Since you are plugging to a router you should have a straight cable, if in doubt test it with a working device, ie plug it into your PC.
DHCP - I see from your PC output DHCP is enabled on 192.168.1.1 and I guess this is your router. A DHCP server needs to know what addresses it can give out to devices, these addresses are called "the DHCP pool". If you have no more free addresses in the pool then you can't connect anymore devices. It sounds like you haven't restricted your pool, but it might be worth logging onto your router and seeing if you can see what addresses are in the pool or range.
MAC Filtering - For security some routers only allow certain MAC addresses to connect to the router and request a DHCP address. If you have it turned on then add your MAC address to the white list. If you don't have it turned on, don't worry.
Speed - I suspect that your shield has a maximum speed of 10MBs. Most modern networking equipment only supports 100/1000MBs so the shield just won't work with your router. Your router should have the numbers near the wired sockets to confirm or deny this.

If none of that works the you are going to need to see if you can read the data from the shield and see if you can work out what is going wrong. You will need a network snooper like WireShark and a HUB. An Ethernet switch will not work, it must be an Ethernet Hub, because switches don't rebroadcast the data on all ports. If your PC has two network cards you could set it up as a 'bridge' and you can snoop on the data as it passes across the bridge.
Sorry if some of these terms are confusing, but you should be able to Google them and get a better explanation than I can give you in the space here.
One final thought: are you running the Arduino from a battery? If so it might be worth using a mains supply, because the battery might not be able to support the Ethernet transmissions.


text:
how to send argument to ESP8266WebServer objects on function
this probably simple thing to do however I can't think of a way to pass argument to function call
ESP8266WebServer server ( 80 );

void toggleRelayOne() {
  char temp[400];
  String msg = "";
  if (relay1 == 0) {
    relay1 = 1;
    msg = "Light is turned on";
  }
  else {
    relay1 = 0;
    msg = "Light is turned off";
  }

  digitalWrite (5, relay1); //GPIO 5 // Relay 1
  snprintf ( temp, 400,
             "<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU DHT11 Sensor and Relay Board</title>\
    <meta http-equiv='refresh' content='0; url=../'>\
    </head>\
  <body>\
  %d .</body>\
  </html>"
             , 1);
  server.send ( 200, "text/html", temp );
}

void setup ( void ) {

  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );
  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( host ) ) {
    Serial.println ( "MDNS responder started" );
  }
  MDNS.addService("http", "tcp", 80);
  server.on ( "/", handleRoot );
  server.on("/relay1", toggleRelayOne);
  server.begin();
  Serial.println ( "HTTP server started" );
}

in the above function where I am calling toggleRelayOne using server.on("/relay1", toggleRelayOne); I want to be able to pass relay id so I can use same function to toggle multiple relays.

server.on ( "/", handleRoot );
why it used??

When a user tries to navigate to "/" I call a function  handleRoot . This function reads the data from sensors connected to ESP826.

Use server.arg() to pass commands from the web as GET params:
digitalWrite (5, relay1);
becomes
digitalWrite (server.arg("pin").toInt(), relay1);
where the URL is something like http://192.168.1.5/relay1?pin=15
Of course, the rest of your code probably needs to be adapted to manage the extra states, read/write all in one http call, etc.


text:
How to insert into table in database after every 5 minutes using Real time clock module
I have RTC module attached to arduino mega,
to calculate time difference of minutes I am getting minute from the RTC module
and checking if passed time is greater than 5 minutes  then insert to MySQL table in database.
  int mint = util::getMinute();

  if (util::getMinute() - mint >= 5)

  {
    // inserting to sql database on mysql server
    INSERT_SQL = "";
    INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
    INSERT_SQL.concat(tempInC);
    INSERT_SQL.concat("');");

    const char *mycharp = INSERT_SQL.c_str();
    delay(1000);

    if (!connected) {
      my_conn.mysql_connect(server_addr, 3306, user, password);
      connected = true;
    }
    else if (connected == true)
    {
      delay(500);
      Serial.print("Inserting : ");
      Serial.println(INSERT_SQL);
      Serial.println("Connection Successfull,inserting to database.");
      my_conn.cmd_query(mycharp);

    }
    else {
      Serial.println("Connection failed.");
    }
    mint = util::getMinute();
  }

the full code is here

Move int mint = util::getMinute(); outside the loop function. Otherwise util::getMinute() - mint will always be 0.

Just a tip, you didn't specify what RTC you're using, but most RTCs have an internal alarm functionality that will trigger an alert when a specific time of day is reached. This allows you to eliminate the polling from your code, and even sleep in between the 5 mins, which can greatly improve your power consumption.

Oh sweet I didn't knew that it's DS3231

So I figured it out myself and used millis instead.
in global declaration I did:
unsigned long sqlInsertInterval = 300000; // the repeat interval after 5 minutes

then initiate timer in setup method
  timer = millis(); // start timer

followed by below changes in the loop method.
void loop() {
  // perform sql insert after 5 minutes
  if ((millis() - timer) > sqlInsertInterval) {
    // timed out
    timer += sqlInsertInterval;// reset timer by moving it along to the next interval

    // inserting to sql database on mysql server
    INSERT_SQL = "";
    INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
    INSERT_SQL.concat(tempInC);
    INSERT_SQL.concat("');");

    const char *mycharp = INSERT_SQL.c_str();
    if (!connected) {
      my_conn.mysql_connect(server_addr, 3306, user, password);
      connected = true;
    }
    else if (connected == true)
    {
      Serial.print("Inserting : ");
      Serial.println(INSERT_SQL);
      Serial.println("Connection Successfull,inserting to database.");
      my_conn.cmd_query(mycharp);

    }
    else {
      Serial.println("Connection failed.");
    }
  }
}

int mint = util::getMinute();

if (util::getMinute() - mint >= 5)

{

Well, if mint is util::getMinute() then surely util::getMinute() - mint will always be 0.
I think you meant mint to be static, or a variable in the global scope.

done that but I don't see database getting inserted even after making the change


text:
Sim800L HTTP post request stop working after a while
I am desperate to get my SIM800L module (http://www.ebay.co.uk/itm/SIM800L-GPRS-GSM-Module-Board-Quadband-QUAD-BAND-Antenna-for-MCU-Arduino-/321992759287) sending POST requests for a long period of time... Sometimes it stops after 100 requests in a row, sometimes 300 so it's really weird.
Everytime I run it, it sends the request for a while (between 1 and 3 hours) and suddenly stops on these AT commands:
---> AT+HTTPINIT
<---

OK

When it works the OK is on the same line and it goes on to the next AT command.
        ---> AT+HTTPTERM
    <--- ERROR
         ---> AT+HTTPINIT
    <--- OK
    ---> AT+HTTPPARA="CID"
    <--- OK
    ---> AT+HTTPPARA="UA"
    <--- OK
    ---> AT+HTTPPARA="URL"
    <--- OK
    ---> AT+HTTPPARA="CONTENT"
    <--- OK
    ---> AT+HTTPDATA=1221,10000
    <--- DOWNLOAD
    <--- OK
    ---> AT+HTTPACTION=1
    <--- OK
Status: 201
Len: 0
    ---> AT+HTTPREAD
    <--- OK
    ---> AT+HTTPTERM
    <--- OK

I thought it was a powering problem so I connected the module to the VIN pin of my arduino mega via a buck converter but the problem is still here!
Does anybody have any idea what could be wrong? I can send you the code if needed.
Many thanks in advance
Pauline

Cross-posting? At least include your code instead of this indecipherable nonsense.

Could you try enabling "verbose error codes" (or atleast numeric error codes) using AT+CMEE=2 or AT+CMEE=1 and then post the (error) response on AT+HTTPINIT. There are no errors in the log you have attached.

Maybe it just lost signal. You might want to make your code check for errors. And if it finds a response with: "Error" it will attempt to re-send. (Maybe add a timeout or re-try limit also).


text:
Simple Speed question - Mapping PWM values
I am working on an Arduino project for school to power a 12V DC cooling fan.
I want to adjust the speed of the fan. The instructions say to set the motor pin at an equation of (0 to 9) * 10 + 150 to get a range of 150 to 240.
I need to write a mathematical equation but can not figure out what 150 to 240 means.  Is this voltage, resistance...?  Thanks for the help.

The analogWrite() function takes a value that is between 0 (fully off) and 255 (fully on).
Your value of 150 to 240 is a value within that range of 0 to 255 and represents a percentage of the "on time" of the PWM signal.

(150 / 255) * 100 = 58.8% on time
(240 / 255) * 100 = 94.1% on time.

You seem to have an "input value" of between 0 and 9 inclusive.  Let's call this value "i".  You want an output value, let's call it "o".
The instructions say "0 to 9 times 10 plus 150 to get a range of 150 to 240". That is simple enough to convert to a formula.  0-9 is i, remember:

o = i × 10 + 150

If i is 0 then o = 0 × 10 + 150 = 0 + 150 = 150.
If i is 9 then o = 9 × 10 + 150 = 90 + 150 = 240.
As Ignacio mentions, the Arduino API has a map function which is meant to be used for this kind of thing;
o = map(i, 0, 9, 150, 240);

However: the map() function is quite heavyweight since it is designed to be a generic mapping function for scaling values. Doi g the calculation manually will always be far more efficient since map will use steps and calculations that are not really part of your needed result. It's a bit like the differende between 1 + 2 and 1+ 5 - 3 + 2 - 4 + 2. The result is the same, but one is far simpler to calculate than the other.

Doesn't map just approximate with integer division instead of using floating-point?

Actually it looks like the current version does use long not float. I am sure an older iteratipn was float based. They probably changed it because it was too heavyweight. So yes, you can use map if you like, but since it is a generic function it will be less efficient anyway than doing the correct specific simple calculation.

They're the value to pass to analogWrite() in order to generate a PWM waveform with an appropriate duty cycle.
But don't bother writing your own algorithm, just use map().

He said he needs to write the equation

The map() function is the answer. It "rescales" the range of the data, using this formula:
(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

You input these five values:
map(value, fromLow, fromHigh, toLow, toHigh)

value is the X value you want to resize
fromLow and fromHigh is the range that X is currently in
toLow and toHigh is the range that you want to scale X to

The question wanted to know what the "150 to 240" means so, no, this isn't the answer.


text:
Arduino Nano - Upload verification error
I'm new to Arduino; and I'm trying to upload a simple sketch to a new Arduino Nano
I tried a few sketches (blink / helloworld / empty one); and changing the USB PORT.
Windows find the correct serial port (but it's a CH340 USB-Serial; I think that's some Chinese clone).
I tried a few USB ports.
When I upload the sketch, it seems to upload. But a verification error appears:
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x00ea
         0x8c != 0x8d
avrdude: verification error; content mismatch

This is the command line
D:\Arduino\hardware\tools\avr/bin/avrdude -CD:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b57600 -D -Uflash:w:C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:i

This is the full verbose log of the flashing:
avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "D:\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 2
         Firmware Version: 1.16
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex"
avrdude: writing flash (1066 bytes):

Writing | ################################################## | 100% 0.32s

avrdude: 1066 bytes of flash written
avrdude: verifying flash memory against C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:
avrdude: load data flash data from input file C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex:
avrdude: input file C:\Users\corti\AppData\Local\Temp\build462236accad2415310c5b24cce7ccca0.tmp/Blink.ino.hex contains 1066 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.24s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x00ea
         0x8c != 0x8d
avrdude: verification error; content mismatch

Run through some of the suggestions here and see what happens.

(but it's a CH340 USB-Serial; I think that's some chinese clone) Good luck with that then. Those CH340s aren't the most reliable chips around.

Have you tried just uploading blink through the IDE?

Yes, I tried any kind of sketch. I also tried to reflash the bootloader (and went just fine).  When I write something with serial monitor, leds blinks /but no answer/

Have you installed drivers for CH340?

@Lipsyor with no drivers you can't even get to that point

I have seen this once before when one of my mates was having troubles programming a ATMega328P on a custom board. It turned out to be his physical serial port. We later confirmed it with a scope - indeed the first packet wasn't what it was meant to be sending. So we switched to a USB-to-Serial dongle that I had and the problem was resolved.
In your case, I highly suspect that it is the CH340 to blame here.
Try programming the Adruino with the AVRISPmkII or another USB-to-TTL converter.
Edit: Alternatively you could program your microcontroller using a genuine Arduino Uno board (such as a friends) and then place it back onto your board.