text:
Sensirion library for SHT7x humidity sensor
I have following code (and it works great!) for SHT75 Sensirion sensor.

/*
 * Example code for SHT1x or SHT7x sensors demonstrating blocking calls
 * for temperature and humidity measurement in the setup routine and
 * non-blocking calls in the main loop.  The pin 13 LED is flashed as a
 * background task while temperature and humidity measurements are made.
 * In addition, the sensor may be placed in low resolution mode by
 * uncommenting the status register write call in setup().
 */

#include <Sensirion.h>

const uint8_t dataPin =  2;            // SHT serial data
const uint8_t sclkPin =  3;            // SHT serial clock
const uint8_t ledPin  = 13;            // Arduino built-in LED
const uint32_t TRHSTEP   = 3000UL;     // Sensor query period
const uint32_t BLINKSTEP =  250UL;     // LED blink period

Sensirion sht = Sensirion(dataPin, sclkPin);

uint16_t rawData;
float temperature;
float humidity;
float dewpoint;

byte shtState = 0;
byte ledState = 0;

unsigned long curMillis;               // Time interval tracking
unsigned long trhMillis = 0;
unsigned long blinkMillis = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  delay(15);                           // Wait at least 11 ms before first cmd
//  sht.writeSR(LOW_RES);                // Set sensor to low resolution
  sht.measTemp(&rawData);              // Maps to: sht.meas(TEMP, &rawData, BLOCK)
  temperature = sht.calcTemp(rawData);
  sht.measHumi(&rawData);              // Maps to: sht.meas(HUMI, &rawData, BLOCK)
  humidity = sht.calcHumi(rawData, temperature);
  dewpoint = sht.calcDewpoint(humidity, temperature);
  logData();
}

void loop()
{
  curMillis = millis();

  if (curMillis - blinkMillis >= BLINKSTEP) {    // Time to toggle the LED state?
    ledState ^= 1;
    digitalWrite(ledPin, ledState);
    blinkMillis = curMillis;
  }

  switch (shtState) {
  case 0:
    if (curMillis - trhMillis >= TRHSTEP) {      // Start new temp/humi measurement?
      sht.meas(TEMP, &rawData, NONBLOCK);
      shtState++;
      trhMillis = curMillis;
    }
    break;
  case 1:
    if (sht.measRdy()) {                         // Process temperature measurement?
      temperature = sht.calcTemp(rawData);
      sht.meas(HUMI, &rawData, NONBLOCK);
      shtState++;
    }
    break;
  case 2:
    if (sht.measRdy()) {                         // Process humidity measurement?
      humidity = sht.calcHumi(rawData, temperature);
      dewpoint = sht.calcDewpoint(humidity, temperature);
      shtState = 0;
      logData();
    }
    break;
  default:
    Serial.println("How did I get here?");
    break;
  }
}

void logData() {
  Serial.print("Temperature = ");   Serial.print(temperature);
  Serial.print(" C, Humidity = ");  Serial.print(humidity);
  Serial.print(" %, Dewpoint = ");  Serial.print(dewpoint);
  Serial.println(" C");
}

How can I extend it for two sensors (by using of another pins, of course)?

You simply create a second instance of the object with different pins and store the result in a different set of variables. Any extra logic of when to do what is purely down to you.

i.e. Sensirion sht2 = Sensirion(dataPin2, sclkPin2);

@Majenko Thank You! Your recommendation works very well! Many thanks to Gerben to.


text:
Arduino Ethernet shield server and client at the same time
Hardware:

Arduino Mega 2560 Rev3
Ethernet Shield Rev3
A sensor

Goal:

Take value from sensor, upload it to ThingSpeak.
Host a web page on the Arduino.

Question:
I've done both things in the past. But now I want to upload the data to ThingSpeak and host a page on the board at the same time , and it doesn't seem to work. Should I try to make two clients? I'm really new two the whole networking stuff.
I'm basically trying to stitch up ThingSpeak's example code with Zoomkat's client/server code. Here is what I'm trying. The webpage does work, but it doesn't upload to ThingSpeak for some reason.

//zoomkat 12-08-11, combined client and server
//simple button GET with iframe code
//for use with IDE 1.0
//open serial monitor and send an g to test client and
//see what the arduino client/server receives
//web page buttons make pin 4 high/low
//use the \ slash to escape the " in the html
//address will look like http://192.168.1.102:84 when submited
//for use with W5100 based ethernet shields

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
IPAddress ip(192, 168, 0, 197); // ip in lan
IPAddress gateway(192, 168, 0, 1); // internet access via router
IPAddress subnet(255, 255, 255, 0); //subnet mask

// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "2M6SFMKICXR7MU1A";
const int updateThingSpeakInterval = 4 * 1000;

// Variable Setup
long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;

EthernetServer server(84); //server port
EthernetClient client;
String readString;

void setup() {
  pinMode(4, OUTPUT); //pin selected to control
  Ethernet.begin(mac, ip, subnet, gateway);
  server.begin();
  Serial.begin(9600);
  Serial.println("server/client 1.0 test 12/08/11");
  // keep track of what is loaded
  Serial.println("Send an g in serial monitor to test client");
  // what to do to test client
}

void loop() {
  // Print Update Response to Serial Monitor
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  // Disconnect from ThingSpeak
  if (!client.connected() && lastConnected) {
    Serial.println("...disconnected");
    Serial.println();
    client.stop();
  }

  if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {
    Serial.println("sendPost function started");
    sendPost();
  }
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }
        //if HTTP request has ended
        if (c == '\n') {
          Serial.println(readString);
          //print to serial monitor for debuging
          //now output HTML data header
          if (readString.indexOf('?') >= 0) { //don't send new page
            client.println("HTTP/1.1 204 ");
            client.println();
            client.println();
          } else {
            client.println("HTTP/1.1 200 OK"); //send new page
            client.println("Content-Type: text/html");
            client.println();
            client.println("");
            client.println("");
            client.println("<TITLE>Arduino test page</TITLE>");
            client.println("");
            client.println("");
            client.println("
THIS IS A TEST
");
            client.println("");
            client.println("");
          }
          delay(1);
          //stopping client
          client.stop();
          readString = "";
        }
      }
    }
  }
}

void sendPost() {
  Serial.println("function initiated");
  client.stop();
  String tsData = String(analogRead(A0), DEC);
  if (client.connect(thingSpeakAddress, 80)) {
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + writeAPIKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(tsData.length());
    client.print("\n\n");
    client.print("field1=");
    //// is this the prob?
    client.print(tsData);
    lastConnectionTime = millis();
    if (client.connected()) {
      Serial.println("Connecting to ThingSpeak...");
      Serial.println();
      failedCounter = 0;
    } else {
      failedCounter++;
      Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");
      Serial.println();
    }
  } else {
    failedCounter++;
    Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");
    Serial.println();
    lastConnectionTime = millis();
  }
}

What's the issue you're facing with this? What do you expect to happen? Please edit your question to include exactly what you need. Thanks!

I don't know how to make a single program that does both server and post requests to ThingSpeak.

I edited the question with the code I'm trying.

I think you want to look at timeouts and then in loop poll to see if there is any data to send to the socket.  What you want to do is achievable normally, but I don't know if you can do it with this library.  An alternative is to use two Arduinos and get them to talk via serial.

source: Stack Exchange

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

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

sort: votes


text:
Receiving multiple bytes from an RPi using the i2c protocol
Trying to send bytes from an RPi as a master to an Arduino as a slave.
The send uses the write_byte(addr, value) function and seems to be working perfectly.
The Arduino however has issues with separating the received bytes into individual values.
I want to use the RPi to dictate when data is sent so I just need the Arduino to listen on wire.available.
Using the wire.onreceive event function I can have a separate function which has:

int var = wire.read()
Serial.print(var)   //for monitoring read byte

This code shows that the bytes being received are the right ones however, when I try something like
ledData[0] = wire.read();
ledData[1] = wire.read();
ledData[1] = wire.read();
etc
etc
...

This returns wildly different values as if the bytes are getting mixed up. Can anyone help me to specifically intake 16 bytes into array indexes for use in the main loop function.

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


text:
Arduino code won't upload with Ethernet Shield attached
I've been playing with my Arduino Boards for a while. I have an Arduino Nano and a Duemilanove 328.
I've been able to program both of them without problems for weeks. Any example project I try will compile and upload with no issue.
I recently got an Ethernet shield... I'm trying some test sketches and no matter which board I try, with the shield attached I get:
avrdude: stk500_getsync(): not in sync: resp=0x00

As I said, without the Ethernet shield attached all is bliss....
Do I have a bad shield or am I just doing something stupid?

I don't know how it works but Go to the Device manager and Assign a different COM port to your Arduino over there! It worked for me :D

The Ethernet Shield uses the pins  D10, D11, D12 and D13 on the Arduino UNO. I presume there is a conflict and you use one or more of these digital pins in your setup already.
A nice overview of possible conflicts between shields and arduino boards can be found at:
http://playground.arduino.cc/Main/ShieldPinUsage

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


text:
Program nodeMCU Over the Air (OTA)
I have a Lolin NodeMCU V3 with a broken USB port: no power, no data.
It does show up on WIFI as AI-thinker_xxx, I can connect, but what can I do next?
Is there a way to program the NodeMCU Over the Air (OTA), or through some pins?
Description found here under V3

To clarify, if it shows up with that WiFi Access Point name, it is getting power. So the USB cable is working that much at least?

Also, if you can include a link to the exact hardware you have or a photo that would assist with figuring out what other pins would be helpful.

Nope, powered over shield.

If powering over Vin pin is working, you can use the board without USB.
ESP8266 is bootloaded over UART pins. These are pins marked RX or D9 and TX or D10 on the NodeMcu board. You can use USB to TTL serial adapter to bootload (flash) the esp8266. To put the esp in flashing mode hold the FLASH button and click the RST button and then release the FLASH button.
You can then upload a sketch with ArduinoOTA library and do following uploads over OTA. After USB upload of a sketch, reset the board with RST button before doing the first OTA upload.


text:
Integer goes garbage after iteration. struct pointer manipulation messed up other variables in memory
I'm writing a library for Charlieplexed LED display (trying to write a common one actually). The library is working quite fine. In my arduino sketch, I'm using an integer to keep track of the LED, currently on. The integer value increases with time and the LED(s) glow one by one. The problem is, after couple of iterations, this integer value just goes out of chart (in Serial monitor, it has garbage values).
MatrixCharlieplex mch(Pins, 5, MXCHARLIE_CA); // instance of Class
int i = 0, j = 0;
boolean busy = false;
unsigned long time;
void setup() {
  //Serial.begin(9600);
  time=millis();
}
void loop() {
  if(millis() - time > 100){ // runs every 100 ms interval // corrected from (millis() > (time + 100))
    time=millis();
    blink();
  }
}
void blink(){
  if(!busy){
    busy = true;
    //Serial.print("i:\t");
    //Serial.println(i);
    //Serial.print("Node:\t");
    //Serial.println(i+1);
    mch.TurnOn(i+1);
    increase();
    busy = false;
  }
}
void increase(){
  i = (++i % 20); // resets after every 20 intervals
}

Output:
i:  16
Node:   17
i:  17
Node:   18
i:  18
Node:   19
i:  19
Node:   20
i:16 <-- Stopped working here. it should be "i:    0" & "Node:    1"
    16
Node:   17
    17
Node:   18
    18
Node:   19
    19
Node:   20
16
    16
Node:   17
    17
Node:   18
    18
Node:   19
    19
Node:   20

The sketch can also be found here
Update:
There were no hardware-fault. The problem lies in the struct variable declaration as pointers.updated the question & posted answer. The files in the github links have also been updated.

I tried running your code, but I couldn't reproduce your problem.

Unrelated to the question... but: you should not test for millis() > time + 100, you should test for millis() - time > 100 instead. Otherwise your code will fail when millis rolls over. Simple rule: do not compare timestamps, compare duration instead.

@Gerben: Without changing any part of the code? WOW... but mine still freezes. :(

Thanks @Edgar for the millis rollover correction. Corrected in question & github also.

How is the RAM usage?

I commented out the multiplex library. Try changing the name on the variable i to e.g. 'index'.

Does this behaviour happen with no LEDs connected? I presume Gerben didn't attach the hardware. If not, then it is hardware-related, like I said. BTW, inside a class you don't normally put this-> in front of every class variable. That's just clutter. You are already using underscores in the name to show that they are class variables.

@Paul: What's the way to check the RAM usage on runtime?

@NickGammon: Sorry, year old habits of Oops practices. Removed "this" from sources. I'll check the code with no LED matrix attached now.

After much trial and error effort, I've found the solution.
There was no problem in the hardware side (I ran the sketch with serial monitor after detaching the LED-matrix and all non-crutial hardwares. Thanks @jantje and @NickGammon fot the tips).
Apparently Arduino is not capable of handling pointers in advanced Oops fashion. The library itself used it heavily, specially "struct pointers" as function parameters and as return types (Arduino messed up these pointer values with other variable declarations in memory). After removing those pointers from the code and replace them with normal variables, the code runs well.
// correct definition
typedef struct {
    uint8_t vcc;
    uint8_t gnd;
} DiodeNode;

// wrong implementation
DiodeNode* node = new DiodeNode();
node->vcc = x;
node->gnd = y;

// correct implementation
DiodeNode node = (DiodeNode){x, y};
// or
DiodeNode node;
node.vcc = x;
node.gnd = y;
return node; // from functions etc.

If you have a Charliplexing board like mine (or even if you made your own) the problem could be electrical. If you turn on a lot of LEDs you may exceed the current consumption allowed and then the processor hangs or resets.
I suggest current-limiting resistors like this:

Thanks @Nick for replying. Yes, I've made one myself and there are resistors for all pins. The library itself doesn't allow turning on more than one LED at a time. i.e. it keep tracks of which one is currently on and a new request will turn the current one off & then turn the new LED on. Hence, there is no chance of over-current consumption. :(

First thing to do is find out whether your problem is electrical or not.
This can be done by removing the electrical parts not crucial to run the code.
If the problem is code related try using another board to eliminate some hardware malfunction on your board.
Doing these steps will give you some insight on the root cause of the problem.


text:
Why is the result shorter than expected when I do longString.toCharArray(bigCharArr, longLength)?
I'm running this on a Particle Photon, but I think the issue is just me failing at C++. I'm trying to retrieve some JSON data from a HTTP API, convert it to JSON, and then extract a few values for display on the screen. I convert the String to a char array for the JSON parser, but it seems to only grab the first 10 characters of the String (unless I manually set length to a number shorter than 10), and then of course, the JSON parser fails.
Here's the relevant bit of code:
int str_len = response.body.length() + 1;
tft.print("Length: "); tft.println(str_len);
char char_array[str_len];
response.body.toCharArray(char_array, str_len);

response.body is a big JSON string, but char_array is always just the first 10 characters of it: {"metadata
Another thing I noticed just now that might be related, str_len is usually reported to be ~500 characters, but when I hit the same URL in a browser it ends up more like ~1500 characters. Neither are pretty-printed, so I'm not sure what the discrepancy is.
Here's my complete code, except I removed the base64'd username and password from the Authorization header:
#include "HttpClient/HttpClient.h"
#include "SparkJson/SparkJson.h"
#include "Adafruit_mfGFX/Adafruit_mfGFX.h"
#include "Adafruit_SSD1351_Photon/Adafruit_SSD1351_Photon.h"

// OLED - You can use any (4 or) 5 pins
#define sclk A3
#define mosi A5
#define dc   D7
#define cs   A2
#define rst  D5

// Color definitions
#define BLACK           0x0000
#define BLUE            0x001F
#define RED             0xF800
#define GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0
#define WHITE           0xFFFF

// Option 1: Hardware SPI - uses some analog pins, but much faster
Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, rst);

// Option 2: Software SPI - use any pins but a little slower
//Adafruit_SSD1351 tft = Adafruit_SSD1351(cs, dc, mosi, sclk, rst);

HttpClient http;

// Headers currently need to be set at init, useful for API keys etc.
http_header_t headers[] = {
    //  { "Content-Type", "application/json" },
    { "Authorization", "Basic <snip>" }, // base64encode(username:password)
    { "Accept" , "application/json" },
    { NULL, NULL } // NOTE: Always terminate headers will NULL
};

http_request_t request;
http_response_t response;

void setup(void) {

    tft.begin();

    tft.fillScreen(BLACK);
    tft.setCursor(0,0);
    tft.setTextSize(0);
    tft.setTextColor(WHITE);

    // http://twcservice.mybluemix.net/api/weather/v2/observations/current?units=e&geocode=40.0388067%2C-84.3428471&language=en-US
    request.hostname = "twcservice.mybluemix.net";
    request.port = 80;
    request.path = "/api/weather/v2/observations/current?units=e&geocode=40.0388067%2C-84.3428471&language=en-US";
    //request.body = "{\"key\":\"value\"}";
    http.get(request, response, headers);

    tft.print("Status: ");
    tft.println(response.status);

    //tft.println("Response Body: ");
    //tft.println(response.body);

    int str_len = response.body.length() + 1;
    tft.print("Length: "); tft.println(str_len);
    char char_array[str_len];
    response.body.toCharArray(char_array, str_len);

    DynamicJsonBuffer jsonBuffer;
    JsonObject& root = jsonBuffer.parseObject(char_array);

    if (root.success()) {
        tft.print("Current Temperature: ");
        const char* temp = root["observation"]["imperial"]["temp"];
        tft.println(temp);
    } else {
        tft.setTextColor(RED);
        tft.println("parseObject() failed");

        tft.setTextColor(GREEN);
        uint32_t freemem = System.freeMemory();
        tft.print("Free memory: ");
        tft.print(freemem/1024);
        tft.println("k");

        tft.setTextColor(WHITE);
        tft.println(char_array);

        tft.setTextColor(CYAN);
        tft.println(response.body);
    }
}

void loop() {

}

The actual printout on the screen is smething like
Status: 200
Length: 501
parseObject() failed
Free memory: 59k
{"metadata
{"metadata":{"language":"en-US","transaction_id":"1460309558940:-660053703","version":"1","latitude":40.04,"longitude":-84.34,"units":"e","expire_time_gmt":1460310025,"status_code":200},"observation":{"class":"observation","expire_

Finally, here's an example of the JSON response I'm trying to parse:
{"metadata":{"language":"en-US","transaction_id":"1460309558940:-660053703","version":"1","latitude":40.04,"longitude":-84.34,"units":"e","expire_time_gmt":1460310025,"status_code":200},"observation":{"class":"observation","expire_time_gmt":1460310025,"obs_time":1460307900,"obs_time_local":"2016-04-10T13:05:00-0400","wdir":160,"icon_code":26,"icon_extd":2690,"sunrise":"2016-04-10T07:06:23-0400","sunset":"2016-04-10T20:11:13-0400","day_ind":"D","uv_index":3,"uv_warning":0,"wxman":"wx4400","obs_qualifier_code":null,"ptend_code":2,"dow":"Sunday","wdir_cardinal":"SSE","uv_desc":"Moderate","phrase_12char":"Cloudy/Wind","phrase_22char":"Cloudy/Wind","phrase_32char":"Cloudy/Wind","ptend_desc":"Falling","sky_cover":"Cloudy","clds":"OVC","obs_qualifier_severity":null,"vocal_key":"OT48:OX2690","imperial":{"wspd":20,"gust":24,"vis":10.000,"mslp":1018.7,"altimeter":30.09,"temp":48,"dewpt":27,"rh":43,"wc":41,"hi":48,"temp_change_24hour":11,"temp_max_24hour":44,"temp_min_24hour":27,"pchange":-0.10,"feels_like":41,"snow_1hour":0.0,"snow_6hour":0.0,"snow_24hour":0.0,"snow_mtd":1.2,"snow_season":21.3,"snow_ytd":21.3,"snow_2day":0.7,"snow_3day":0.8,"snow_7day":0.9,"ceiling":7400,"precip_1hour":0.00,"precip_6hour":0.00,"precip_24hour":0.00,"precip_mtd":1.10,"precip_ytd":11.76,"precip_2day":0.29,"precip_3day":0.30,"precip_7day":0.96,"obs_qualifier_100char":null,"obs_qualifier_50char":null,"obs_qualifier_32char":null}}}

Any idea what's going on?

Probably something specific to the Particle Photon. I can convert that string to and from String/char array quite happily on a Mega2560.

I tried it with the string hard-coded just now and that worked as expected. So maybe there's something funky with the HttpClient?

It turns out that the HttpClient library has a fixed response length limit of 1024 bytes and whatever it was doing after it hit that limit is what caused all of the trouble.
Forking the library and increasing the limit as recommended at https://community.particle.io/t/issues-with-string-char-array-length-json-parsing/21980 solved the issue.


text:
Number of elements in an array char
What kind of function can I use to know how many elements are in an array char?
sizeof() gives the number of 'spaces' available so it doesn't work for me.

Can you give an example please? eg. char foo [100] = "bar"; - is that what you mean? You want the answer: 3?

yes that's right

You want strlen.
char foo [100] = "bar";
Serial.println (strlen (foo));   // --> prints 3

If the answer worked for you please click the "accept" button (it looks like a tick). That way other people will know that the solution worked.

I had to wait a couple of minutes to do that

Note that this will only work if the data in your char[] contains an ascii string, and is properly null-terminated. Furthermore, if you have a long string in the char[], and you overwrite it with a shorter string without adding the null-termination, you will get the size of the older string.

Quite right. My answer was for the question as presented. The things you mention should be taken into account for null-terminated C strings.

I know you have your answer from @NickGammon, but I'd just like to add a bit more in-depth information about how all this works.
sizeof() is not a function in the normal sense of the word.  It is an operator which gives you the number of bytes of memory allocated to whatever you pass to it.  If you pass it an array then it returns the number of bytes that array has available to it.  If you pass it a pointer to an array then it returns the size of that pointer, not the size of the array.  If you pass it an integer variable it returns the number of bytes used by that integer variable (2 on an 8-bit system like AVR, 4 on a 32-bit system like the Due).
So some examples:
char array[50] = "hello";
// sizeof(array) = 50.
char *array_p = array;
// sizeof(array_p) = 2 or 4 depending on architecture.
char single = 'a';
// sizeof(single) = 1.
char string[] = "hello";
// sizeof(string) = 6 (5 letters plus \0) - it allocates the memory at compile time to fit the string

Now strlen().  How exactly does that differ from sizeof()?  Simply put, strlen() counts the number of characters in a character array up until it reaches the character \0 which is the "NULL" terminating character of a C string.  Let's take the examples before but use strlen instead:
char array[50] = "hello";
// strlen(array) = 5.
char *array_p = array;
// strlen(array_p) = 5.
char single = 'a';
// strlen(single) = ERROR!  strlen() doesn't operate on single characters.
char string[] = "hello";
// strlen(string) = 5.

You notice it always returns the number of characters in the string up to, but not including, the trailing \0 character.
In its simplest form the strlen() function might look like this:
int strlen(const char *data) {
    int c = 0;
    const char *p = data;
    while (*p) {
        c++;
        p++;
    }
    return c;
}

Basically it starts at the first character in the string (*p = data), examines if it's a \0 or not (while (*p)), increments the count of characters (c++) and moves on to the next character in the string (p++).
If you want to iterate through your string in your program you could call strlen() first to get the number of characters in the string then use that value in a loop.  That is a bit wasteful, since strlen() first iterates through the string, so you end up iterating through it twice.  It is far more efficient to learn how best to step through each character in the string until you find the terminating character, such as how the strlen() function uses the pointer to move through memory.  You can also see just how vital it is that you ensure the \0 character exists at the end of the string, otherwise how will functions like strlen() know when to stop?  They can't know how long the string is (sizeof() will return the size of the pointer it is passed, not the size of the array), so they have to have some kind of manual marker, and the convention in C is to use \0.
Note that Arduino's print() functions actually do it very inefficiently.  If you do something like:
char message[] = "Hello";
Serial.println(message);

It will actually do quite a lot of work it doesn't really need to.  Taken step by step it:

calls println(message)
which calls write(message)
which gets the string length with strlen(message)
and calls write(message, length)
which then loops from 0 to length-1 sending each character of message to write() in turn.
finally prints the \r\n for the new-line.

So it actually ends nested around 4 functions deep, and iterates the entire string twice. A classic example of how to waste processing time.  By iterating through the string once looking for the \0 character in the write(message) function (step 2) it would operate at least twice as fast.  Good old Arduino...

Re “In its simplest form the strlen() function might look like this”, in a shorter (perhaps simpler?) form it  could look like:  int strlen(const char *data) {     const char *p = data;     while (*p++);     return p-data-1; }

@jwpat7 I said "simplest", not "shortest and most compact".  That form, while smaller and more efficient, is much much harder for the OP (who is obviously not a programmer) to understand.

Agreed :)  Also easier to make mistakes in.  And if the \0 is the last accessible byte in a segment, the *p++ will fault. But int strlen(const char *data) { const char *p = data; while (*p) ++p; return p-data; } avoids that problem.

Actually, *p++ won't fault even if the \0 is the last accessible byte in a segment; the *p part will access the last byte; the ++ part will set p to an invalid address; but as that  invalid address doesn't get referenced, on a typical machine no fault occurs.

It is a compile-time macro ... It's not a macro, it's an operator (like "+" and "-" are operators). They are lower-level than macros which are things done at pre-processor time. See sizeof operator. Also Operators in C++

Indeed it is. Three years ago I thought differently.


text:
Interfacing Logitech Joystick to Arduino and interrupt a while loop
I am working on a project of a robot arm. The joints are made of servo motor. The basic function can be describe as:

The robot arm (the servos) were moved manually by the Logitech joystick.
The user could press a certain button to remember a position. I made 6 buttons for 6 positions, in detail.
After the remembering, if an activating button was pressed, the robot arm would move repeatedly around those 6 positions until a stopping button was pressed.

The problem was the bold words.
In order to make the robot arm could move repeatedly with one pressing, I used a while loop.
However, when the program was in while loop, the joystick events stopped updating no matter how I pressed or pulled the joystick. Therefore, I couldn't program a stopping button.
I guessed that was because the joystick events were called outside the loop, but I don't know how to get it inside. My code was based on the example of the USB Host Shield library.
Here is the code. It contained 3 files. My robot also has some more function so I only quote the part that I had problem here.
.ino file:

#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include "le3dp_rptparser.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

//int waist_back, shoulder_back, wrist_back, gripper_back;

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial);
#endif
  Serial.println("Start");

   if (Usb.Init() == -1)
       Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );

}

void loop()
{
    Usb.Task();
}

.cpp file: This was where I worked. Please look at the JoystickEvents::OnGamePadChanged
#include "le3dp_rptparser.h"

//Many parameters for robot here

JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
    joyEvents(evt)
{}

void JoystickReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
    bool match = true;

    // Checking if there are changes in report since the method was last called
    for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
        if( buf[i] != oldPad[i] ) {
            match = false;
            break;
        }
  }
    // Calling Game Pad event handler
    if (!match && joyEvents) {
        joyEvents->OnGamePadChanged((const GamePadEventData*)buf);

        for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
    }
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
  Serial.print("X: ");
  Serial.print(evt->x);
  Serial.print(" Y: ");
  Serial.print(evt->y);
  Serial.print(" Hat Switch: ");
  Serial.print(evt->hat);
  Serial.print(" Twist: ");
  Serial.print(evt->twist);
  Serial.print(" Slider: ");
  Serial.print(evt->slider);
  Serial.print(" Buttons A: ");
  Serial.print(evt->buttons_a);
  Serial.print(" Buttons B: ");
  Serial.print(evt->buttons_b);
  Serial.println("");

  // Manual control program here. I didn't post because it was so long.

  //Activation

  if (evt->buttons_a == 32){
    while (evt->slider == 0){

    //Robot working here, also a long code that was out of limit for a block here.

    Serial.print(evt->slider);
    }
  }
}

.h file:
#if !defined(__HIDJOYSTICKRPTPARSER_H__)
#define __HIDJOYSTICKRPTPARSER_H__

#include <usbhid.h>

struct GamePadEventData
{
  union { //axes and hut switch
    uint32_t axes;
    struct {
      uint32_t x : 10;
      uint32_t y : 10;
      uint32_t hat : 4;
      uint32_t twist : 8;
    };
  };
  uint8_t buttons_a;
  uint8_t slider;
  uint8_t buttons_b;
};

class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
  static GamePadEventData mostRecentEvent;
};

#define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)

class JoystickReportParser : public HIDReportParser
{
    JoystickEvents      *joyEvents;

  uint8_t oldPad[RPT_GAMEPAD_LEN];

public:
    JoystickReportParser(JoystickEvents *evt);

    virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

#endif // __HIDJOYSTICKRPTPARSER_H__

After the //Activation under JoystickEvents::OnGamePadChanged, no matter how I pulled the slider of the joystick, the event was not updated, the evt->slider always returned zero and the robot arm couldn't be stopped.
Is there any method to update the joystick event inside the while loop?
Or another method other than while loop to make something move repeatedly after pressing one button, and can be stopped with another button?
Thank you so much for reading, and please help me!

As full code is not posted I cant suggest you correctly but you should add the two buttons, START & STOP.
When STOP button is pressed all events (your code is performing on) should stop working.
Just make sure when you program for a joystick control, the code for START & STOP buttons  should fall under the joystick control loop.
if (STOP PRESSED){

}else if(START PRESSED){

    //INVOKE THE FUNCTIONS FOR ACTIONS TO BE PERFORMED
}

Thank you. I planed to post the full code at the beginning, but the site told me that I was out of limit so I had no choice but to post the part I needed.

The trick is to never use a while loop to wait for something physical to happen.  Instead write code that doesn't block execution of the rest of the code.  Write your code so that instead of sitting in a while loop, the function relies on being called over and over from the loop function.  Let the loop function do the looping.


text:
Sending data from Arduino w/HM10 to relay board with hm12
It all started when I tried connecting an hm10-nano to a relay board which is Bluetooth enabled.  Here is my nano with the hm10 module:

And here is the relay board's BT module, which looks like an hm12:

I started by connecting the nano-hm10 to my mac and using the Arduino IDE to send the module commands.  The hm12 has a mac for ble and another for edr:
ble:00-0e-0b-00-75-12
edr:00-0e-0e-00-75-12
The hm10 does connect because:

I get a steady blue led on the hm10 after AT+COmacble
I get the macble from the hm10 module after AT+RADD?
I hear the relay (channel1) open on the relay board after AT+COmacble

When I try the following steps -> I get these results
1. Unplug relay board -> hm10 blue blinking
2. Plug relay board -> hm10 blue steady, relay BT module blue led steady
3. AT commands to hm10 thru serial monitor stop working (expected)
4. AT+CO000e0e007512 to hm10 -> turns on relay 1 for some reason
5. Unplug relay -> RADD on hm10 = 00-0e-0b-00-75-12 instead of 00-0e-0e-00-75-12
My questions are:
A. Is it possible to send data from an hm10 to hm12?
B. Why does the relay get activated when I connect to the hm12-relay board?
C. I just realized my sketch's bluetooth.print() sends a command from the nano to the hm10, not to from the hm10 to the hm12.  How can I send the data from the nano to the hm12?
Sketch:

#include <SoftwareSerial.h>
int bluetoothTx = 10;  // TX-O pin of bluetooth
int bluetoothRx = 11;  // RX-I pin of bluetooth
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup(){
  Serial.begin(9600);  // Begin the serial monitor at 9600bps
  delay(200);
  bluetooth.begin(9600);  // Start bluetooth serial at 9600
  Serial.print("send...");
  bluetooth.print("AT");
    bluetooth.print("110"); //open relay 1
    delay(2000);
  bluetooth.print("100"); //close relay 1
}
void loop(){
  if(bluetooth.available()){
    Serial.print((char)bluetooth.read());
  }
  if(Serial.available()){
    bluetooth.print((char)Serial.read());
  }
}

Try switching the rx and tx pins


text:
WiFiClient::connected() not working
I use an ESP32 to open an access point and listen for TCP connections over a WiFiServer object.
When I get a client on the server I want to know when it has disconnected.
Currently I have a simple piece of code on both the client and the server side. I connect using a TcpClient in C#.
When I call client.close() on the client side, the client.connected() loop on the server just continues forever.
Here is the ESP code:

void setup()
{
   WiFi.mode(WIFI_AP);

   WiFi.softAP("test");

   WiFi.softAPConfig(IPAddress(192, 168, 4, 1), IPAddress(192, 168, 4, 1), IPAddress(255, 255, 255, 0));

   Serial.println(WiFi.localIP());

   server.begin();
}

void loop()
{
    while (!client)
    {
        client = server.available();

        delay(10);
    }

    while (client.connected())
    {
        Serial.println("ok");

        delay(1000);

        client.read();
    }
}

C# code:
static void Main(string[] args)
{
     TcpClient client = new TcpClient("192.168.4.1", 222);

     client.Close();
}

Welcome to Arduino SE.  I don't really see a question here.  I see a statement of the problem but no attempts at resolution nor a question about why such an attempted fix didn't work.    I recommend you take the tour at https://arduino.stackexchange.com/Tour to get the most out of this site.  Perhaps you can flesh it out enough to prevent closure of this one.  Or, if it does get closed, perhaps you can repost it with the elements necessary to present a question that can attract useful answers.

@SDsolar I'm absolutely aware on how to write on this site, because I'm on stackoverflow as well. Furthermore my question is clear when you read the title and the second line. I'm explaining my intention there and with a little bit of think you can guess that I need help with this function. Instead of writng pointless comments spend the time writing some answers.

I just don't see a question here, that's all.  This is a Q&A site.  Without one you can't have the other.   I voted to leave this one open when it came up in review, thinking a little nudge was all you needed.

This is a bug in a previous version of the library as mentioned on
https://github.com/bportaluri/WiFiEsp/issues/14
You can alternatively use WiFi.softAPgetStationNum() to get the count of stations connected to the AP interface.

WiFiEsp isn't the library I'm using, is it? Unfortunately WiFi.softAPgetStationNum() does't help me, because I need to know when the socket has disconnected and not a Station.

Whether you're using the WiFiEsp library is not a question I know the answer to.

I've seen the client.connected() function in WiFiEsp only

This one's WiFiEspClient::connected() and not WiFiClient::connected()

My actual answer
You can try to inquire client.status() as a workaround. When no one is connected it should return 0.
Context
What are you building on? I tried to reproduce your problem but everything works as expected, the serial stops printing "ok" when I disconnect.
Also, what libraries are you using exactly? I included ESP8266WiFi.h and WiFiClient.h.
I used platformio v3.4 on an ESP8266-01 module and a simple Android netcat app as client.

ESP8266WiFi.h is for an ESP8266 which is the wrong plattform, I have an ESP32 Development Board. I included #include <WiFi.h>.


text:
Node mcu does not connect
im trying to connect to my wifi with mit Nodemcu, i recently got a new router and since then i can't connect anymore. I use simple example sketches from esp library but it will not connect. Instead i get a lot of dots in the console. I disabled firewalls of my router, mac filter is disabled(as i tried to manually add the nodemcus mac to mac filter it said "invalid macadress" ) if intry to connect to my phones hotspot, everything is fine.but i can't connect to my home wifi, ssid and Passwort are 100% correct. My hardware is fine, i ordered a second nodemcu and it has the same problems as the old one.
Can someone help me please, i've set my entire rooms ligthing on the node mcu and now im living in the dark ...

is the new AP 5 GHz WiFi?

No i have 2.4 ghz and 5 ghz but i disabled 5ghz :/

This goes to show that one shouldn't ever rely on a single point of failure to make a home 'smart'.

You'll need to review the logs of your access point device to see why it is failing your requests. If it's a low-end residential device, it probably doesn't have any logs for you to review. What have you tried on the MCU side code-wise, to observe what may be happening on its side of things?

Turn on all the debugging you can in the IDE to see what your code is doing over the serial port


text:
Creating WebServer with 5000 port with AT command(ESP-01f)
I'm setting webserver with toggle led. I want to create global webserver. I`m mean hat use server with global ip. For it I must use port too. global ip/local ip:port.
I want to create on 5000 port. I'm used for ESP-01f and connect it arduino. Communicating by SoftwareSerial. I used AT+CIPSTA for static ip. When I used AT+CIPSERVER=1,5000 it worked. But when I connect to it, it works, but in second connection it doesn't want to connect itor when I use digitalWrite it doesn't connect to this server. How can I solute this problem?
code:

#include <SoftwareSerial.h>

SoftwareSerial softSerial(10, 11);
String ssid = "ssid";
String ip = "staticip";
String gateway="gateway";
String sub="submask;
String password = "password";
String _response = "";
#define DEBUG true
void setup()
{

  Serial.begin(115200);

pinMode(2,OUTPUT);

  softSerial.begin(115200);
  connectWifi();
}

void connectWifi() {

  do {

    sendData("AT+RESTORE\r\n", 5000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT\r\n", 2000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CWMODE=1\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"\r\n", 5000, DEBUG);
  } while (softSerial.find("OK"));
   do {

    sendData("AT+CIPSTA=\"" + ip + "\",\"" + gateway +"\",\"" + sub + "\"\r\n", 2000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CIFSR\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CIPMUX=1\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));
  do {

    sendData("AT+CIPSERVER=1,5000\r\n", 1000, DEBUG);
  } while (softSerial.find("OK"));

}

String sendData(String command, const int timeout, boolean debug)
{

  String response = "";

  softSerial.print(command);        long int time = millis();
  while ((time + timeout) > millis())
  {
    while (softSerial.available())
    {

      char c = softSerial.read();
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response);
  }

  return response;
}

void loop()
{

if(softSerial.available()){
  if(softSerial.find("+IPD,"){
   int connectionId = softSerial.read()-48;
softSerial.find("pin/");
int pin = softSerial.read()-48;

String htmlCode = "<label>"+String(pin)+"</label>";
digitalWrite(pin,HIGH);
sendData("AT+CIPSEND="+String(connectionId)+","+htmlCode.length()+"\r\n",1000,DEBUG);
sendData(htmlCode+"\r\n",1000,DEBUG);

sendData("AT+CIPCLOSE="+String(connectionId),3000,DEBUG);

  }
}
}

don't use restore. it clears the settings part of the flash. you wear out the flash. use AT+RST. set AT+CWAUTOCONN=0 if you don't want the esp8266 to start the connection on startup or use _CUR commands to not save the connection to flash

you should read all the request bytes. what is on pin 2?

On pin 2 led...

How can I read all request bytes

And sometimes it write -49. WHY.

use the WiFiEsp library

read() returns -1 if no data are available. you subtract -48

Juraj WIFIEsp Library. How can I use it?

Let us continue this discussion in chat.


text:
Creating global webserver without port forwarding
I'm setting up a "Smart House" project with Arduino+Esp01F(Serial Communication).
But I want to make it global server. For it I use WiFiEsp library. But for it I must Get any port (neither 80 nor 443), then make port forwarding on router. But there are no port forwarding in my router. I think how can I do it?
Code:
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif
 String response = "";
char ssid[] = "Nazim";            // your network SSID (name)
char pass[] = "eminmamedov1";         // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
int reqCount = 0;                // number of requests received

WiFiEspServer server(5000);

 WiFiEspClient client;

void setup() {
Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

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

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

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

WiFi.config(IPAddress(192,168,0,165));
  // start the web server on port 80
  server.begin();

}

void loop() {
   WiFiEspClient client = server.available();
   if(client){
    String res = "";
     Serial.println("New client");
      while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        res+=c;

        if (c == '\n') {
          Serial.println("Sending response");
           client.print(
            "HTTP/1.1 200 OK\r\n"
            "Content-Type: text/html\r\n"
            "Connection: close\r\n"  // the connection will be closed after completion of the response
               "\r\n");
               if(res.indexOf("on?") >=0){
               int s = res.indexOf("on?")+7;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  pinMode(i,OUTPUT);
                  digitalWrite(i,HIGH);
                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
                 }else{
                  client.println("ERROR\r\n");
                 }
               }else if(res.indexOf("off?") >=0){
                 int s = res.indexOf("off?")+8;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  pinMode(i,OUTPUT);
                  digitalWrite(i,LOW);
                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
                 }else{
                  client.println("ERROR\r\n");
                 }
               }else if(res.indexOf("state?") >=0){
                 int s = res.indexOf("state?")+9;
               int f = s+2;
               String ss = res.substring(s,f);
                  int i = ss.toInt();
                 if(i != 6 && i != 7&& (i>=2)&&(i<=13)){

                  bool s = digitalRead(i);
                  String state = s ? "OFF\r\n" : "ON\r\n";
                  client.println(state);
               }
               }

                   client.stop();

      }
      }

   }

}

You can't. Get a better router.

The ESP does only provide the server. The traffic from and to that server has to be routed between your local network and the internet. That is, what a router is for. You need a better one

I heard there is the IP Cameras without port forwarding(it works without por). I thought that was p2p but No. How can I realize it in my ketch

use the DMZ setting in the router to expose your server to the internet

@TheGamerCoder You may be talking about UPnP which can configure port forwarding for you. Or there are cameras that communicate with a service on the internet so need no port forwarding (they connect outwards).  If your router supports UPnP (why it would support that and not port forwarding would be a mystery) then maybe you could do it with that.  See this question

Incidentally, to do that you will have to give up the idea of using the AT command set and trying to get it working with an Arduino, and program the ESP8266 directly.

Can I use for it Esp01f adapter?

Only if you program it directly instead of using an Arduino as I said above.

Can I use UPnP Tiny library with WiFiEsp?

use web sockets and an always-on cloud server for 2-way non-ported real time communication.

What? How to use it? And Can I use it with WiFiEsp + TinyUPnP

What part of "Only if you program it directly instead of using an Arduino" don't you understand?

STOP. I understand. But how to use WEBSOCKETS and ALWAYS-ON CLOUD SERVER I didn't understand

@TheGamerCoder Use @ followed by a username to direct your comments at a particular user.

I mean how to realize @dandavis said

typically, you need a VPS to run a websocker server on. there's some free VPS options, and a few hosted websocket server options, like pubnub and pusher.

@dandavis Thanks  for information, but how can  I add VPS to wifi sketch


text:
How to use ESPAsyncWebServer with SoftwareSerial communicating ESP01f
I'm creating a web server with using host.com/?ll="some". But I read that I can use for it ESPAsyncWebServer for this things. And how can I use it without flashing esp? If possible give me link to the libraries.

You read wrong. That library is only for running on the ESP8266. You can only use it by directly writing software for, and flashing, the ESP8266. You can't use it by communicating over SoftwareSerial.

OK. Thanks...........


text:
Conversion between boolean and int went wrong
I have a small problem with conversion from bool array to int. It is working fine until it comes to the 12th cycle of while. I don't know why but this is really weird.
I try to paste here a code where I am doing this conversion.
int* BoolToInt(bool* set) {
  int* ret = (int*)malloc(3*sizeof(int));
  int sum0 = 0;
  int sum1 = 0;
  int sum2 = 0;
  //bool test[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1};
  for(int m=0; m<24; m++) {
    if(m<8) {
      sum0 += (int)set[m] * (pow(2,m));
    }
    if(m>7 && m<16) {
      sum1 += (int)set[m] * (pow(2,(m-8)));
    }
    if(m>15 && m<24) {
      sum2 += (int)set[m] * (pow(2,(m-16)));
    }
  }
  ret[0] = sum0;
  ret[1] = sum1;
  ret[2] = sum2;
  Serial.print("\n ret[0] = ");
  Serial.print(ret[0]);
  Serial.print("\n ret[1] = ");
  Serial.print(ret[1]);
  Serial.print("\n ret[2] = ");
  Serial.print(ret[2]);
  return ret;
}

And this is where I am using this function:
void Fitness(bool** set) {
  int maX = 0;
  int index = 0;
  int* temp;
    for(int i=0; i<10; i++) {
    int* phenotype = BoolToInt(set[i]);
    _fitness[i] = 1000/((phenotype[0] - _colours[0])*(phenotype[0] - _colours[0]) + (phenotype[1] - _colours[1])*(phenotype[1] - _colours[1]) + (phenotype[2] - _colours[2])*(phenotype[2] - _colours[2]) + 1);
    Serial.print("\n phenotype[0] = ");
    Serial.print(phenotype[0]);
    Serial.print("\n phenotype[1] = ");
    Serial.print(phenotype[1]);
    Serial.print("\n phenotype[2] = ");
    Serial.print(phenotype[2]);
    free(phenotype);
  }
  for(int i=0;i<10;i++) {
    temp = BoolToInt(set[i]);
    if(_fitness[i]>maX) {
      maX = _fitness[i];
      index = i;
    }
  }
  setColorOnSecond(temp[index]);
  free(temp);
}

As seen in the Fitness function, I have some debugging prints to see if everything is fine. My main is in the while cycle. Everything is fine and "ret" from BoolToInt function is the same as "phenotype" in Fitness, which is a good thing and this is what I want. But then the 12th cycle comes and phenotype[1] gives me 1200 as int. And of course everything in ret[] is fine(0-255). Am I doing something wrong?
NOTE: bool* set in BoolToInt is 24 bool array (yes 3 numbers as you can see).
NOTE 2: every previous cycle before 12th cycle is good and the result are equal.

yes of course it won't compile.. this is only a part of evolutionary algoritm.

while is used in main....imagine it as a while and inside of that is this Fitness function

Your problem is using pow.  It works in floats.  It may come as some surprise, but pow(2,3) gives 7 when you put it into an int.
Don't waste time on pow for powers of 2.  Just use a bitshift.   It's way smaller and faster.

Where did you see that pow(2, 3) gives 7? My Arduino tells me (int) pow(2, 3) == 8.

Oh, wait, you're right. It gives 8 if 3 is a constant, but 7 if it's a variable.

I've seen enough threads on Arduino.cc where someone is shocked that Arduino gets powers of 2 wrong to know that one pretty well.  I'm guessing that when it is done with constants the calculation is being optimized away and the compiler is smart enough to put 8 in there.

this helped me :)... now it gives me good answers :).. thanks

Let me the first one to say that 1. Boolean to int conversion shouldn't be this complicated and 2. Much simpler ways to do what you are trying to do.
Like this.
If (bool) boolint |= mask;
  Mask = mask << 1;
  ...
You get the idea.

yes I saw this already. But this doesn't solve my problem


text:
Arduino Yun not showing anything on the serial monitor
I am having issues with the ArduinoYun. It's not showing any data in the serial monitor. The sensor lights up when I plug it in but that's about it and the code seems to compile but nothing is coming through. I am using the Adafruit color sensor. I have SDA/SCL connected to pins 4 and 5. The servo is connected to pin 3. The rest is just on Vin and GND.
#include "Servo.h"
#include "Wire.h"
#include "Adafruit_TCS34725.h"

const int redPos = 160;
const int orangePos = 130;
const int yellowPos = 100;
const int greenPos = 70;
const int bluePos = 30;
const int nonePos = 0; // Kein Objekt erkannt

Servo myservo;

Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_1X);

void setup() {
  Serial.begin(9600);
  Serial.println("Makerblog.at - MuMs Color Sensor");
  if (tcs.begin()) {
    Serial.println("Sensor gefunden");
  } else {
    Serial.println("TCS34725 nicht gefunden ... Ablauf gestoppt!");
  while (1);
  }
  // Der Servo hängt am PWM-Pin 3
  myservo.attach(3);
  // Servo in Grundstellung fahren
  myservo.write(0);
  delay(1000);
}

void loop() {
  uint16_t clearcol, red, green, blue;
  float average, r, g, b;
  delay(100); // Farbmessung dauert c. 50ms
  tcs.getRawData(&red, &green, &blue, &clearcol);
  average = (red+green+blue)/3;
  r = red/average;
  g = green/average;
  b = blue/average;

  // Clear-Wert und r,g,b seriell ausgeben zur Kontrolle
  // r,g und b sollten sich ca. zwischen 0,5 und 1,5
  // bewegen. Sieht der Sensor rot, dann sollte r deutlich über 1.0
  // liegen, g und b zwischen 0.5 und 1.0 usw.
  Serial.print("\tClear:"); Serial.print(clearcol);
  Serial.print("\tRed:"); Serial.print(r);
  Serial.print("\tGreen:"); Serial.print(g);
  Serial.print("\tBlue:"); Serial.print(b);

  if ((r > 1.4) && (g < 0.9) && (b < 0.9)) {
    Serial.print("\tROT");
    myservo.write(redPos);
  } else if ((r < 0.95) && (g > 1.4) && (b < 0.9)) {
    Serial.print("\tGRUEN");
    myservo.write(greenPos);
  } else if ((r < 0.8) && (g < 1.2) && (b > 1.2)) {
    Serial.print("\tBLAU");
    myservo.write(bluePos);
  } else if ((r > 1.15) && (g > 1.15) && (b < 0.7)) {
    Serial.print("\tGELB");
    myservo.write(yellowPos);
  } else if ((r > 1.4) && (g < 1.0) && (b < 0.7)) {
    Serial.print("\tORANGE");
    myservo.write(orangePos);
  } else {
    Serial.print("\tNICHT ERKANNT");
    myservo.write(nonePos);
  }
  Serial.println("");
  delay(100);

Assuming the code works, you should be able to change the position of the servo by altering the initialized color values.  Currently they are:
 const int redPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int greenPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

If, for example, the positions of Red and green are to be swapped all that is needed is to alter the code like this:
 const int greenPos = 160;
 const int orangePos = 130;
 const int yellowPos = 100;
 const int redPos = 70;
 const int bluePos = 30;
 const int nonePos = 0;

The numbers, according to the Arduino's servo driver web page, are the angle in degrees the servo will be moved to after executing the call to the Arduino servo driver.
Given the above, if a new color violet were to be added to the original set of colors the first change would be to move the servo positions slightly higher to make room for the new color.
 const int redPos = 160;
 const int orangePos = 135;
 const int yellowPos = 110;
 const int greenPos = 85;
 const int bluePos = 60;
 const int violetPos = 35;
 const int nonePos = 0;

The next change would be to alter the ranges of the color test code.  As you did not specify what hardware you are using to detect colors, you will have to experiment to find the combination of red, green & blue which matches the new color violet.  The code used for detecting blue is:
 else if ((r < 0.8) && (g < 1.2) && (b > 1.2))

Likely violet contains more red and may be detectable with a line of code like this:
 else if ((r > 1.0) && (g < 1.2) && (b > 1.2))

The position of this test may be important depending on how the detector works.  It may be best to place it after testing for orange.  Remember to use the new initialized variable such that you code may look like this:
else if ((r > 1.0) && (g < 1.2) && (b > 1.2)){
  Serial.print("\tVIOLET");
  myservo.write(violetPos);
}

you are the best, thank you so much for breaking down the code for me.

Well, i am having issues with the arduino yun, showing any data in the serial monitor. The sensor lights up when i plug it in but that is about it and the code seems to compile but nothing is coming through.

Wow, I've never seen anyone edit a question like that.  My recommendation is to change back your question to its original wording.  Then post a new question about not getting the expected results.  Add a comment here if you can not figure out how to change your question back to its original form & I will try to do it.  By the way, you should try the original Adafruit example code and verify your hardware is connected properly and is working before trying unknown code.

I tried using the example codes in the arduino ide but i was still having the same issue. i read other post and they said that it had to do with using serial.begin instead of consol.begin.I found that suggestion impractical to my situation since i was not using wifi for the yun, i attempted using console.begin anyways just to see whether that would help but it did not. so, i am still having the same issue.

We can't have a discussion in the comments.  The "stackexchange bots" will start suggesting we move.  But I would test the code w/o the servo in an ordinary situation where the example code works.  Then dropping printing out the color and just use the detector and servo and finishing off your testing.


text:
How to detect water presence with only 2 wires
I don't know if this question belong here or on electronics SE.
A manufacturer just sent me a personalize device which include an ESP-32 and a Water Sensor.
My problem is that I don't know how to retrieve the water sensor data (if there is water or not).
When I used my Arduino Nano and a Funduino Water Sensor, it was easy to retrieve the value because this sensor got 3 connectors (VCC, GND, Data), I just had to do a basic analogRead(DATA_PIN).
But now, as you can see on the diagram bellow, the water sensor is just composed of 2 wires. I presume that it will detect water when these two wires are going to be connected by water.
So, How to detect the presence of water in Arduino using only these 2 wires ?
What I tried :

Analog Read on the pin GPIO33
Digital Read on the pin GPIO33
Try to use TOUCH_PAD with this pin using touchAttachInterrupt(T8, callback, Threshold); but callback was never called
Contact the manufacturer (He said that it works perfectly, he used touch_pad for testing but never used Arduino IDE, only ESP-IDF that I really don't know)

simulate this circuit – Schematic created using CircuitLab
EDIT:
This image represent the back of the device with the sensor, inner wire is directly connected to GND and outer wire is connected to GPIO_33. This is all, there is not hidden connectors or something else.

You'll have to show us what this mystery sensor is.

@Majenko I edited the question with a photo of the device

So it is just literally 2 bare wires then? Nothing else?

Yep that's it, one connected to GPIO_33 and the other connected to GROUND

Since all you have is 2 bare wires, the water simply forms a resistor between them.
You can use it as part of a resistive divider, with a fixed resistor between your analog input and +3.3V.  The resistance between the wires will change from infinite (dry) to something much lower (wet) and the reading you get from the ADC will depict that.
You will need to experiment with different resistances in order to get reasonable values, but start with 10kΩ, or 100kΩ.  If you use a very high resistance (in the order of 1MΩ or more) you may even be able to use it like a simple switch and connect it to a digital input.
Be warned, though, that this method will cause a small amount of electrolysis, causing one electrode to be eroded away and the other to gain extra material.  For this reason it can be good to connect the resistor to a GPIO pin instead of directly to +3.3V and switch the GPIO pin HIGH when you want to do a reading (to provide power) and LOW (or INPUT) when at other times (to remove power).  This will greatly increase the lifetime of your water sensor.

Hum, the device is already functional, and I don't have to add electronic parts
(according to the manufacturer). I just need a way to obtain the value I guess

I am not familiar with the ESP32, but you may be able to do it by turning on an internal pullup resistor on the GPIO pin.


text:
I am trying to combine an automatic door lock with an RFID MFRC522 with a IR REMOTE program
I am getting this error.
Arduino: 1.8.2 Hourly Build 2017/02/17 11:33 (Windows 8.1), Board: "Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\REMOTE\IRremote.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Here is the entire code:
#include <RFID.h>
#include <Wire.h>  // i2C Conection Library
#include <LiquidCrystal_I2C.h>  //Memanggil i2C LCD Library
LiquidCrystal_I2C lcd(0x3F, 16, 2);

#include <SPI.h>
#include <RFID.h>
#define SS_PIN 10
#define RST_PIN 9

RFID rfid(SS_PIN,RST_PIN);

const int buzzer = 7;   //Passive buzzer ke Pin D7 dan GND
const int doorLock = 8; //Driver Selenoid Door Lock/Relay input ke pin D8
int serNum[5];          //Variable buffer Scan Card

int cards[][5] = {      //ID Kartu yang diperbolehkan masuk
  {120, 181, 196 ,101, 14}

};

bool access = false;

int alarm = 0;
uint8_t alarmStat = 0;
uint8_t maxError = 5;
void setup(){
    Serial.begin(9600);
    lcd.begin();
    SPI.begin();
    rfid.init();

    pinMode(doorLock, OUTPUT);
    digitalWrite(doorLock, HIGH);

  tone (buzzer,1200);
  lcd.setCursor (0,0);
  lcd.print(F("  RFID System   "));
  lcd.setCursor (0,1);
  lcd.print(F(" Control Access "));
  delay (2000);
  lcd.clear();
  noTone (buzzer);
}

void loop(){
  if (alarm >= maxError){
    alarmStat = 1;    }

  if (alarmStat == 0){
  lcd.setCursor (0,0);
  lcd.print(F(" -System Ready- "));
  lcd.setCursor (0,1);
  lcd.print(F(" Scan Your Card "));

    if(rfid.isCard()){

        if(rfid.readCardSerial()){
            Serial.print(rfid.serNum[0]);
            Serial.print(" ");
            Serial.print(rfid.serNum[1]);
            Serial.print(" ");
            Serial.print(rfid.serNum[2]);
            Serial.print(" ");
            Serial.print(rfid.serNum[3]);
            Serial.print(" ");
            Serial.print(rfid.serNum[4]);
            Serial.println("");

            for(int x = 0; x < sizeof(cards); x++){
              for(int i = 0; i < sizeof(rfid.serNum); i++ ){
                  if(rfid.serNum[i] != cards[x][i]) {
                      access = false;
                      break;
                  } else {
                      access = true;
                  }
              }
              if(access) break;
            }
        }

       if(access){
          Serial.println("Welcome!");
          lcd.setCursor (0,0);
          lcd.print(F(" DOOR UNLOCKED!! :)"));
          lcd.setCursor (0,1);
          lcd.print("ID:");
          lcd.print(rfid.serNum[0]); lcd.print(rfid.serNum[1]);
          lcd.print(rfid.serNum[2]); lcd.print(rfid.serNum[3]);
          lcd.print(rfid.serNum[4]);
           digitalWrite(doorLock, LOW);
           tone (buzzer,900);
           delay(100);
           tone (buzzer,1200);
           delay(100);
           tone (buzzer,1800);
           delay(200);
           noTone(buzzer);
           delay(600);
           lcd.setCursor (0,0);
           lcd.print(F("WELCOME"));
           lcd.setCursor (0,1);
           lcd.print(F("AutoLock after "));
           for(int i=5; i>0; i--){
            lcd.setCursor (15,1); lcd.print(i);
            delay (1000);
           }
           digitalWrite(doorLock, HIGH);
           lcd.clear();
      } else {
           alarm = alarm+1;
           Serial.println("Not allowed!");
           lcd.setCursor (0,0);
           lcd.print(F(" ACCESS DENIED!!  "));
           lcd.setCursor (0,1);
         lcd.print("ID:");
           lcd.print(rfid.serNum[0]); lcd.print(rfid.serNum[1]);
           lcd.print(rfid.serNum[2]); lcd.print(rfid.serNum[3]);
           lcd.print(rfid.serNum[4]);
           tone (buzzer,900);
           delay(200);
           noTone(buzzer);
           delay(200);
           tone (buzzer,900);
           delay(200);
           noTone (buzzer);
           delay(500);
           lcd.clear();
       }
    }
    rfid.halt();
}
else {
  lcd.setCursor (0,0);
  lcd.print(F("-System LOCKED- "));
  lcd.setCursor (0,1);
  lcd.print(F(" Please Wait "));
for(int i=5; i>0; i--){
tone (buzzer,4000);

lcd.setCursor (13,1); lcd.print(i);
lcd.print(F("  "));delay (1000);}
noTone (buzzer);
alarmStat = 0;
alarm = 0;
  }
}

//code  of an IR REMOTE

#include <IRremote.h>

int RECV_PIN = 2; // the pin where you connect the output pin of TSOP4838
int lock =13 ;
int itsONled[] = {};
/* the initial state of LEDs is OFF (zero)
the first zero must remain zero but you can
change the others to 1's if you want a certain
led to light when the board is powered */
#define code1 26775 // code received from button 1

IRrecv irrecv(RECV_PIN);

decode_results results;

void remote()
{
  Serial.begin(9600);   // you can comment this line
  irrecv.enableIRIn();  // Start the receiver0
  pinMode(lock, OUTPUT);

}

void loop_1() {
  if (irrecv.decode(&results)) {
    unsigned int value = results.value;
    switch(value) {
       case code1:
         if(itsONled[1] == 1) {        // if first led is on then
            digitalWrite(lock, LOW);   // turn it off when button is pressed
            itsONled[1] = 0;           // and set its state as off
            Serial.println("ledl OFF");
         } else {                      // else if first led is off
             digitalWrite(lock, HIGH); // turn it on when the button is pressed
            Serial.println("led 1 ON");
             itsONled[1] = 1;          // and set its state as on
         }

          break;
    }

    Serial.println(value); // you can comment this line
    irrecv.resume(); // Receive the next value
  }
}

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem.  Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant.  Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem.

hai!! thanks for the reply , as u said i have attached my entire code to the question ... plzz help me out!!

The error message multiple definition of __vector_7 means that you have more than one interrupt handler defined for the interrupt that has interrupt vector 7.
Although the ATmega328x datasheet in a table called Interrupt Vectors in ATmega328 and ATmega328P refers to interrupt vector 7 as the Watchdog Time-out Interrupt, that probably is misleading, because only the following ISRs can be defined in Tone.cpp:
ISR(TIMER0_COMPA_vect)
ISR(TIMER1_COMPA_vect)
ISR(TIMER2_COMPA_vect)
ISR(TIMER3_COMPA_vect)
ISR(TIMER4_COMPA_vect)
ISR(TIMER5_COMPA_vect)

(These can be defined, but typically most are not.  All of them are conditional upon which MCU is selected.)
The article multiple definition of '__vector_7' at arduino.cc attributes the problem to the last of those ISRs, ISR(TIMER5_COMPA_vect).   Anyhow, in short, you might need to check what board or MCU you are compiling for, or may need to find a substitute for one of Tone or IRremote, the libraries that are both defining the ISR that has a conflict.
Edit 1: The article TimerFreeTone Library v1.5: Play tones without timers and therefore no conflicts at arduino.cc describes a TimerFreeTone v1.5 library that generates tones without using timers.  You might be able to use that library in place of the Tone library that has a conflict.

Thanks for the valuable reply ... I understood the problem  ... Can we assign a different interrupt for both the programs , my basic idea is to control doorlock with an RFID system as well as an IR REMOTE , individually both the programs with the output is working fine .. i wanted to combine both so that i can dump into a single program to access both features ... Plzz help me out with this .

@user33872, see edit 1

Thank u very much!! Compiled succesfully with both the programs , i commented all the tone libraries and added the TimerFreeTone v1.5 library to my sketch along with the program that you have attached (obatined at the article TimerFreeTone Library v1.5: Play tones without timers and therefore no conflicts at arduino.cc ) . I will go with the hands-on the hardware and get back to you! Your answers were VERY HELPFUL :)  Thanks!!

Hai very Good Morning .The combined sketch of RFID and IRremote in realtime is working absolutely fine , Thank you very much for helping me out with this .... and i encountered an another problem , i wanted a buzzer tone each and every time when i scan a vaild card and an invalid card . And after 5 times scanning an invalid card the entire system gets locked for some time(in the program 5 sec duration) .. For all these operations i wanted an buzzer tone .. how do i do it?

I don't know, due to not understanding some of the program and some of what you want to do.  By the way, have you read and understood the Blink Without Delay example? ¶ Note, in for(int x = 0; x < sizeof(cards); x++),  sizeof cards is the number of bytes in cards, that is, the number of entries times the size of each entry.  Try x < sizeof cards / sizeof cards[0]; instead.  (Parentheses are not needed after sizeof operator unless the argument is a datatype name instead of a variable name.)

You can't use tone and IRremote in the same sketch as they are both trying to use the same timer interrupt.
Don't use the hourly build.  It's not tested.  Get the latest stable version if you are working on your final project.  You don't want unknown bugs.  Let the beta testers use the hourly build.  For something like a final project you need things to work, so stick with the stable version, not the bleeding edge of development.

thanks for the reply !! so can anything be done if i want to use both tone and IRremote sketch as the single program... I s it possible to change the interrupt of which the programs are using and assign different interrupts to it ... can u guide me for this. please


text:
Digital Vibration sensor on NodeMCU ESP8266
First Post.
I'm using a NodeMCU esp8266 connected to a digital vibration sensor. My project is to detect when a pager vibrates to then trigger through the maker channel of ifttt an outcome.
I'm following this project as my base, hoping to adapt it ever so slightly, but the more I adapt the code the less it seems to work. https://blog.erindachtler.me/tutorial-a-wifi-enabled-washing-machine/

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define WIFI_SSID "wifissid"
#define WIFI_KEY "wifikey"

#define NOTIFY_URL
"https://maker.ifttt.com/trigger/myproject/with/key/mykey"

int vibration = 16; //vibration sensor
int LedPin =4; //built in led
int numberofshouts = 0;
int vibrationstate = 0;
int lastvibrationstate = 0;

void setup() {
pinMode(vibration, INPUT);
pinMode(LedPin, OUTPUT);
Serial.begin(9600);

// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);

WiFi.begin(WIFI_SSID, WIFI_KEY);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server
Serial.println("Server started");

// Print the IP address
Serial.println(WiFi.localIP());

}

void loop() {
// put your main code here, to run repeatedly:
int vibrationvalue = digitalRead(vibration);

if (vibrationvalue == HIGH)  {
  Serial.print("Vibration");
  sendDoneNotification();
}

else {
digitalWrite(LedPin, LOW);
}

}

void sendDoneNotification() {
WiFi.begin(WIFI_SSID, WIFI_KEY);

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

HTTPClient http;
http.begin(NOTIFY_URL);
int httpCode = http.GET();
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);

// file found at server
if(httpCode == HTTP_CODE_OK) {
  String payload = http.getString();
  Serial.println(payload);
}
} else {
  Serial.printf("[HTTP] GET... failed, error: %s\n",
http.errorToString(httpCode).c_str());
}
http.end();

 WiFi.disconnect();
 }

What happens is my serial just reports
[HTTP] GET... failed, error: connection refused
I don't quite get the post commands.
I basically want it to read the vibration sensor and while it's reporting no movement do nothing, but after it detects vibration for a couple of seconds it then sends the post command to the maker url that will trigger my ifttt command, thus notifying me on my phone etc.
I have created and run a serial print program to test the sensor and adjust the sensitivity so I know the sensor is working.
My NodeMCU doesn't have a D1 pin so i have it connected to D0, not sure if this is correct or not.
Any tips or advice if there is an easier way of doing this.
Many thanks and have a nice day.
Adrian.


text:
Save data from an LCD KeyPad Shield to an sd card
I'm developing a project that requires save data from a sensor that is connected in a LCD keypad shield, the information should be save in a file into SD card.
My code

#include <LiquidCrystal.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int buttons;
File myFile;
//name of the file
char nombrefichero[12];
int i = 1;
int exist = LOW ;

void setup() {
Serial.begin(9600);
//check the sd card adapter
  Serial.print("Iniciando SD ...");
  if (!SD.begin(53)) {
    Serial.println("No se pudo inicializar");
    return;
  }
  Serial.println("inicializacion exitosa");
}

void loop() {
// use the buttons of the lcd keypand shield in analog 0
buttons = analogRead(0);

//button right
if(buttons < 50){
  count ++;
  nuevo();
}

//button select
if(buttons < 790){
  capturar();
}

}

void capturar(){
  myFile = SD.open(nombrefichero, FILE_WRITE);//abrimos  el archivo

  if (myFile) {
        Serial.print("Escribiendo SD: ");
        int sensor1 = analogRead(0);
        int sensor2 = analogRead(1);
        int sensor3 = analogRead(2);
        myFile.print(millis());
        myFile.print(",");
        myFile.print(sensor1);
        myFile.print(",");
        myFile.print(sensor2);
        myFile.print(",");
        myFile.println(sensor3);

        myFile.close(); //cerramos el archivo

        Serial.print("Tiempo(ms)=");
        Serial.print(millis());
        Serial.print(",sensor1=");
        Serial.print(sensor1);
        Serial.print(",sensor2=");
        Serial.print(sensor2);
        Serial.print(",sensor3=");
        Serial.println(sensor3);

  } else {
    // if the file didn't open, print an error:
    Serial.println("Error al abrir el archivo");
  }
  delay(1000);
}

void nuevo(){

while (exist == LOW)
  {
    sprintf(nombrefichero, "M%d.txt",i); //generate autoincrement number of
file

    if(SD.exists(nombrefichero))
    {
       i = i+1;
      myFile = SD.open(nombrefichero, FILE_WRITE);
      if (myFile) {
        Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)");
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");

        myFile.close();

      } else {
        exist = HIGH;
        Serial.println("Error creando el archivo");
      }
  }

  }
}

I need capture the information of the sensor when I pressed the select button and when the right button is press create a new file in this method, in this line if(SD.exists(nombrefichero)) if I put the ! before SD.exist the files are created infinite but if I leave it as is without the ! the button does nothing
void nuevo(){

while (exist == LOW)
  {
    sprintf(nombrefichero, "M%d.txt",i);
    if(SD.exists(nombrefichero))
    {
       i = i+1;
      myFile = SD.open(nombrefichero, FILE_WRITE);
      if (myFile) {
        Serial.println("Archivo nuevo, Escribiendo encabezado(fila 1)");
        myFile.println("Tiempo(ms),Sensor1,Sensor2,Sensor3");

        myFile.close();

      } else {
        exist = HIGH;
        Serial.println("Error creando el archivo");
      }
  }

  }
}

I'm use arduino mega 2560 and SD card Adapter

Don't cross post. You already asked this on SO.


text:
Controlling two-pole contactor using Arduino
I am working with Packard C230C contactor to develop own EVSE. For a simple start i just want to toggle contactor using Arduino. OpenEVSE is already doing it. Just want to know how do they do it and some circuit explanation.
Reference : OpenEVSE Setup

the gray wires control the relay .... research how to control a relay with an Arduino .... also research how relays work  ..... btw: the link that you posted is bogus

I get grey wire controls contactor. But the voltage at that wire is around 120v while toggling a contactor state. generally relay is also +5v so question is how do you control 120~220v relay from arduino

@SurajJorwekar using a second relay that is controllable by 5V, that one doesn't need to switch a lot of power so can be a cheap one.

I use this module, controlled by 3.3 V pin of esp8266, powered with 5V to switch 10A AC http://wiki.seeedstudio.com/Grove-SPDT_Relay_30A/

Get solid state relays that have a operating voltage of 5V and can switch Mains AC


text:
LCD prints weird characters when I place the print statement in setup after pinMode statements
#include "LiquidCrystal.h"

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7)

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(22, INPUT_PULLUP); // Reed switch - Row1
  pinMode(24, INPUT_PULLUP); // Reed switch - Row2
  pinMode(26, INPUT_PULLUP); // Reed switch - Row3
  pinMode(28, INPUT_PULLUP); // Reed switch - Row4
  pinMode(32, OUTPUT);
  digitalWrite(32, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("hello");
}

When I run the above code I get weird characters in my LCD. I removed all the connections to the pins` defined in pinMode and left only the lcd connections but kept the pinMode and digitalWrite statements in the code, but am still getting weird characters. But when I remove the pinMode and digitalWrite statements from my code the lcd works fine. Can anyone help me out.
Edit:
Another weird thing happened, I removed all the pinMode and digitalWrite statements do my setup() had only Serial.begin() and lcd.begin() and I only had the lcd connections. Now I put this code to print into an function called lcdprintMove() and there were other functions too which were performing other tasks when I ran it as such I got weird characters in the LCD but when I removed all of the other functions,the lcd printed fine. From this I was able to conclude that this problem can't be because of the supply but has to be something else. But I still can't figure it out.
Problem Solved
Today I commented all the digitalWrite statements and uploaded the program and it worked! So,  I am going to connect the lcd onto a separate arduino and communicate serially. Someone suggested the solution of putting a cap to ground and buff the power of 5 v pin can you explain this in more detail.
Circuit diagram   Note: Rs is connected to pin 7 and E to 6

How is your LCD connected? Please show a schematic.

What is connected to pin 32?

all the pins defined in pinMode are connected to reed switches.

What are the reed switches connected to? Try disconnecting them, then run the program both ways again. If it works better this time, one or some of the reed switch circuits' current draw, combined with that of the LCD, may exceed the pin-drivers' capacity and drag down a voltage such that the LCD can't respond properly.

i actually just tried that,I removed everything and left only the lcd connections but kept the pinMode and digitalWrite statements there , but am still getting weird characters. but when i have only the lcd statements in setup() it works fine. I can't figure out what's happening.

I have noticed this type of behaviour when the LCD can't pull enough current.  Are you sure you power supply is adequate?  You can always add a cap to the ground and +5v pins as a buffer.  When I have noticed this in the past, it is usually when I am moving a servo at the same time as a LCD write.  LCDs seem to be quite sensitive in this regard.

What capacitor should I use?Also just to clarify by " +5v pins as buffer" did you mean that I should buffer the +5v pin for more power by using buffer chips like ULN2003A?

"I removed everything and left only the lcd connections but kept the pinMode and digitalWrite statements there , but am still getting weird characters." Edit your question to add that important information. The question should stand by itself without needing to read the comments. Without that information it seems like your circuit diagram is incomplete. With that information added I would willing to vote to reopen this

Is the LCD module's +5v supplied directly from the power supply, or off one of the Arduino's +5v pins? If the latter, try powering it directly.

it's from the arduino's 5v pins

The capacitor between 5V and GND effectively acts as a small battery. When a sudden demand in a current relatively large occurs, the system can get that extra small amount from the cap and not experience a voltage drop.


text:
Serial communication between 2 arduino's doesn't works when Sending string in a program with a lot of functions
Note :
This question is completely different from the questions that I have asked before although the code snippets might be the same, So please do not waive it as a duplicate right when you see it.
In my setup I have connected two arduino's Serially. An Arduino Mega is the one that is sending the string and a Arduino Uno is the one that's receiving it.

Arduino Mega : TX1(19),RX1(18) - Serial1
Arduino Uno : RX(10),TX(11) - using SoftwareSerial
Gnd is connecetd on both boards

Arduino UNO - code is same for both cases
#include <SoftwareSerial.h>
SoftwareSerial s(10, 11);
void setup()
{
  delay(200);
  Serial.begin(9600);
  Serial1.begin(9600);
  s.begin(9600);
  while (!Serial) ;  // wait for Arduino Serial Monitor
}
void loop()
{
  if(s.available()>0)
  {
     Serial.print("\nrec\n");
     delay(100);
     String b = s.readStringUntil('\n');
     delay(100);
     Serial.print(b);
     delay(40);
  }

}
When the code in my arduino mega has only a print statement to send a string an infinite no. of times to the Uno, The Uno is receiving the string properly.
Arduino Mega
void setup()
{
  Serial1.begin(9600);
}
void loop()
{
  Serial1.println("e2e4");
  delay(100);
}

Now when I send the string an infinite no. of times from the Arduino mega but this time the mega has a lot more functions included in the program as well. In this case the Uno does not receive the string sent.
Arduino Mega - code containing a lot of functions and sedning a string to
                  Uno
int SensorValStore_Prev[8][8] = { {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {1,1,1,1,1,1,1,1}, \
                                  {0,0,0,0,0,0,0,0}, \
                                  {0,0,0,0,0,0,0,0} };

int SensorValStore_Curr[8][8]={ {0,0,0,0,0,0,0,0}, \
                                {0,0,0,0,0,0,0,0}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,1,1,1,1,1,1}, \
                                {1,1,0,1,1,1,1,1}, \
                                {0,0,0,0,0,0,0,0}, \
                                {0,1,0,0,0,0,0,0} };
//int SensorValStore_Curr[8][8];
int sum1[8],sum2[8],temp[8][8],k,l,i,j,rank,nextRow;
String file,moveSan,Temp,bestMove;
char Buffer[20];
void doAction();
void ReadSensor();
void Difference();
void binToIntCalc();
void check();
void getMovePlayed();
void SendMove();
void getMove();

void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode(22,INPUT_PULLUP); // Reed switch - Row1
  pinMode(24,INPUT_PULLUP); // Reed switch - Row2
  pinMode(26,INPUT_PULLUP); // Reed switch - Row3
  pinMode(28,INPUT_PULLUP); // Reed switch - Row4
  pinMode(30,INPUT_PULLUP); // Reed switch - Row5
  pinMode(32,INPUT_PULLUP); // Reed switch - Row6
  pinMode(34,INPUT_PULLUP); // Reed switch - Row7
  pinMode(36,INPUT_PULLUP); // Reed switch - Row8
  pinMode(2,INPUT_PULLUP);// Push Button
  pinMode(38,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(42,OUTPUT);
  pinMode(44,OUTPUT);
  pinMode(46,OUTPUT);
  pinMode(48,OUTPUT);
  pinMode(50,OUTPUT);
  pinMode(52,OUTPUT);
  pinMode(3,OUTPUT);
  digitalWrite(38,HIGH);
  digitalWrite(40,HIGH);
  digitalWrite(42,HIGH);
  digitalWrite(44,HIGH);
  digitalWrite(46,HIGH);
  digitalWrite(48,HIGH);
  digitalWrite(50,HIGH);
  digitalWrite(52,HIGH);
  digitalWrite(3,LOW);
}

void loop()
{

  // doAction();
  delay(40);
  Difference();
  delay(40);
  binToIntCalc();
  delay(40);
  check();
  delay(40);
  getMovePlayed();
  delay(40);
  getMove();
  delay(40);
  //}
}

void Print(int matrix[8][8])
{
  for(i=0;i<8;i++)
  {
    for(j=0;j<8;j++)
    {
      Serial.print(matrix[i][j]);
      Serial.print(" ");
    }
    Serial.println();
  }
}

void doAction()
{
  nextRow = 0;
  for(i=0;i<8;i++)
  {
    digitalWrite(38 + nextRow,LOW);
    delay(40);
    ReadSensor(i);
    digitalWrite(38 + nextRow,HIGH);
    delay(40);
    nextRow +=2;
  }
}

void ReadSensor(int iter)
{
  delay(10);
  for(j=0;j<8;j++)
    SensorValStore_Curr[iter][j] = digitalRead(j+2);
}

void Difference()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
      temp[i][j] = abs(SensorValStore_Curr[i][j] - SensorValStore_Prev[i[j]);

}

void binToIntCalc()
{
  for(i=0;i<8;i++)
    for(j=0;j<8;j++)
    {
      sum1[i] += pow(2,j)*SensorValStore_Prev[i][j];
      sum2[i] += pow(2,j)*SensorValStore_Curr[i][j];
    }
 }

void check()
{
  k=0;
  l=0;
  for(i=0;i<8;i++)
  {
    if(sum2[i]>sum1[i])
      k = i;
    if(sum2[i]<sum1[i])
      l = i;
    delay(40);
  }
}

void getMovePlayed()
{
  for(j=0;j<8;j++)
  {
    if(temp[k][j] == 1)
    {
      rank =k+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp = moveSan;
    }
  }
  for(j=0;j<8;j++)
  {
    if( temp[l][j] == 1)
    {
      rank =l+1;
      file = String(char(97+j));
      delay(40);
      moveSan = file + rank;
      Temp.concat(moveSan);
    }
  }
}

void SendMove(String movePlayed)
{
  Serial.println("start");
  Serial.print(movePlayed);
  Serial.println();
}

void getMove() // SENDING STRING TO THE ARDUINO UNO
{
 while(1){
  Serial1.println("e2e4");
  delay(100);
  }
}

Note: getMove() is the function that sends the string to the arduino through Serial1

I don't see a Serial1.begin()

damn....I can't believe that I made such a ridiculous error. @chrisl should I just delete this question . Since it will have absolutely no use to this site.

My answer might not be what you'd expect but I'll try anyway.
Did you troobleshoot your serial communications ? Try doing a simple programm for both cards and try sending data from one to another.
Uno code
#include <SoftwareSerial.h>

#define rxPin 10
#define txPin 11

SoftwareSerial s(rxPin, txPin);

String buff = "";

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

void loop()
{
    if(Serial.available)
    {
        while(Serial.available())
        {
            buff += char(Serial.read());
        }
        s.print(buff);
        buff="";
    }

    if(s.available)
    {
        while(s.available())
        {
            buff += char(s.read());
        }
        Serial.print(buff);
        buff = "";
    }
}

Mega code
String buff = "";

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

void loop()
{
    if(Serial.available)
    {
        while(Serial.available())
        {
            buff += char(Serial.read());
        }
        Serial1.print(buff);
        buff="";
    }

    if(Serial1.available)
    {
        while(Serial1.available())
        {
            buff += char(Serial1.read());
        }
        Serial.print(buff);
        buff = "";
    }
}

Did you double check your connections ? Tx (mega) to rx (uno) and rx (mega) to tx(uno)
In your setup() on your arduino mega
void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode(22,INPUT_PULLUP); // Reed switch - Row1
  pinMode(24,INPUT_PULLUP); // Reed switch - Row2
  pinMode(26,INPUT_PULLUP); // Reed switch - Row3
  pinMode(28,INPUT_PULLUP); // Reed switch - Row4
  pinMode(30,INPUT_PULLUP); // Reed switch - Row5
  pinMode(32,INPUT_PULLUP); // Reed switch - Row6
  pinMode(34,INPUT_PULLUP); // Reed switch - Row7
  pinMode(36,INPUT_PULLUP); // Reed switch - Row8
  pinMode(2,INPUT_PULLUP);// Push Button
  pinMode(38,OUTPUT);
  pinMode(40,OUTPUT);
  pinMode(42,OUTPUT);
  pinMode(44,OUTPUT);
  pinMode(46,OUTPUT);
  pinMode(48,OUTPUT);
  pinMode(50,OUTPUT);
  pinMode(52,OUTPUT);
  pinMode(3,OUTPUT);
  digitalWrite(38,HIGH);
  digitalWrite(40,HIGH);
  digitalWrite(42,HIGH);
  digitalWrite(44,HIGH);
  digitalWrite(46,HIGH);
  digitalWrite(48,HIGH);
  digitalWrite(50,HIGH);
  digitalWrite(52,HIGH);
  digitalWrite(3,LOW);
}

I don't see the Serial1.begin(9600) as said by @chrisl but you mentionned it above.
I hope this helps, sorry if I've not solved your problem.

you are correct, I missed it out in my code.


text:
getting started with programming Arduino board in C/embedded c
I want to move away from Arduino IDE and start directly working with avrdude. Can anyone tell me some resources and tips on starting and moving forward with using C/embedded C to access more functionality.Would appreciate some help.

The Atmel/Microchip web site may be a place to start for AVR development.

Read the chip datasheet. It has everything you need.

Check out Atmel Studio 7.

Not an exhaustive answer, but one step would be to realize what the Arduino IDE does behind the scenes before it gives your source code to avr-gcc.
From https://github.com/arduino/arduino/wiki/build-process#pre-processing

The Arduino environment performs a few transformations to your sketch
  before passing it to the avr-gcc compiler:

All .ino files in the sketch folder (shown in the IDE as tabs with no    extension) are concatenated together, starting with the
  file that    matches the folder name followed by the others in
  alphabetical order,    and the .cpp extension is added to the
  filename.
If not already    present, #include <Arduino.h> is added to the sketch. This header    file (found in the core folder for the
  currently selected board)    includes all the definitions needed for
  the standard Arduino core.
Prototypes are generated for all function definitions in .ino files    that don't already have prototypes. In some rare cases
  prototype    generation may fail for some functions. To work around
  this, you can    provide your own prototypes for these functions.
#line directives are added to make warning or error messages reflect the original sketch layout.

No pre-processing is done to files in a sketch with any extension
  other than .ino. Additionally, .h files in the sketch are not
  automatically #included from the main sketch file. Further, if you
  want to call functions defined in a .c file from a .cpp file (like
  one generated from your sketch), you'll need to wrap its declarations
  in an extern "C" {} block that is defined only inside of C++ files.

This is handy to know if you are trying to port Arduino sketches to pure avr-gcc.
You'll also want to have the header files that define all the various registers specific to the ATMega328p that is the heart of several of the Arduino boards. They can be downloaded as part of Atmel Studio 7, which also includes avr-gcc and the various other toolchain utilities and scripts necessary.
You'll also want the processor's reference manual or datasheet. At this time, the data sheet is available at https://www.microchip.com/wwwproducts/en/ATmega328P in the "Documents" tab. This will lay out everything you ever need to know about how to use the processor, set up peripherals, rules for the order of commands, names of all the registers, etc.