text:
What is the best way to communicate with ESP8266-01 in LAN?
I've been working on this small project, not that small for me though, for a while. Because I also had classes and exams I didn't really have time for it. But almost everything was done except that I couldn't figure out the proper way of communicating with the ESP8266-01 and I need your help or guidance or any idea that may help.
Here is what I am trying to do:
I have an Arduino Uno, an L298N motor driver, an ESP8266-01 and a small DC motor, all connected properly to my Arduino. Besides that, I also have a gamepad for PC, which I would like to control the DC motor with over the ESP8266-01.
Here is what I've done so far:
I've used the SDL library in C to get the analog stick input from my gamepad and I am able to increase and decrease the speed with my gamepad.
I've also connected the ESP8266-01 to my WiFi and I can change the motor speed from terminal using telnet (via port 80). But not accurately.
What is left is to find a proper way to communicate with the ESP8266-01 so that it responds to every request and to connect these two together so that my project is done and I can control the DC motor with my gamepad.
I was searching for a proper way to communicate with the ESP8266-01 through the terminal. I've tried using telnet (via port 80) but sometimes for some reason the ESP8266-01 won't respond my request or sometimes I lose the connection and I get a respond like below:

telnet: Unable to connect to remote host: Connection refused

Below is the code that I am using for my Arduino to control the motor speed and also the direction of it.
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial esp8266(2, 3); //Rx, Tx
void espsend(String);
String sendData(String command, const int timeout, boolean debug);

void setup()
{
  Serial.begin(9600);    //For Serial monitor
  esp8266.begin(9600);   //ESP Baud rate
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(9, OUTPUT);    //for speed of the DC motor
  analogWrite(9, LOW);
  digitalWrite(12,HIGH); //for direction of the DC motor
  digitalWrite(13, LOW); //for direction of the DC motor

  sendData("AT+RST\r\n", 5000, DEBUG); // reset module
  sendData("AT+CWMODE=1\r\n", 5000, DEBUG); // configure as STA

  sendData("AT+CIPMUX=1\r\n", 3000, DEBUG); // configure for multiple connections
  sendData("AT+CWJAP=\"wifiID\",\"wifiPW\"\r\n", 3000, DEBUG);
  sendData("AT+CIFSR\r\n", 5000, DEBUG); // get ip address
  sendData("AT+CIPSERVER=1,80\r\n", 5000, DEBUG); // turn on server on port 80

}

int connectionId;
void loop()
{
  int velocity;
  char direction[]="direction=";
  char speed[]="speed=";
  char ipd[]="+IPD,";
  if (esp8266.available())
  {
    if(esp8266.find(ipd)){

    delay(1000);
    connectionId = esp8266.read() - 48;
    esp8266.find(speed);
    if(velocity = esp8266.parseInt()){
      analogWrite(9, velocity);
    }
    if(esp8266.find(direction)){
        delay(300);
        int direction2= esp8266.parseInt();
        if(direction2 == 1){
          digitalWrite(12,HIGH);
          digitalWrite(13,LOW);
    }else{
      digitalWrite(12,LOW);
      digitalWrite(13,HIGH);
    }
}
  String closeCommand = "AT+CIPCLOSE=";  //close the socket connection
  closeCommand += connectionId; // append connection id
  closeCommand += "\r\n";
  sendData(closeCommand, 2000, DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug)
  {
    Serial.print(response); //displays the esp response messages in arduino Serial monitor
  }
  return response;
}

After uploading this code to my Arduino Uno, from the terminal I connect to the ESP8266-01 through telnet 192.168.1.40 80, then I send something like +IPD,1,speed=40. This works but not always and sometimes I lose connection.
What is the best way to communicate with the ESP8266-01 in this situation? I've searched on the Internet but I didn't really get anything useful. Using telnet is not always working and I don't know how fast my ESP8266-01 could respond to those requests, as I will be sending them like in miliseconds.

Program the ESP to receive values over TCP or WebSockets, and send it over Serial to the Arduino. Don't use AT commands.

@tttapa Do you mean to program the ESP using a USB to serial converter and using the ESP8266WiFi libraries on GitHub? Do you have links related to this or a generic topic name that I can search for? Thank you. :)

Yes. A Beginner's Guide to the ESP8266 and Programming the ESP8266 using an Arduino UNO

@tttapa Thank you sooo much! :) I couldn't program the ESP directly because I don't have a USB to UART converter but I will get it as soon as possible and try as you suggested.

Did you read the second article? You don't need a USB-to-Serial converter. Although, it'll be easier if you have one. But then again: why spend $2.50 on a USB-to-Serial adapter if you can get a Wemos D1 mini for $3.50 that has a USB-to-Serial converter built-in, and gives you access to all of the ESP8266's IO pins?

@tttapa Well I just did. And you are right, I just didn't want to mess with it but your guide seems clear enough so I can follow it through. Only thing I need is a regulator now I guess. By the way, about the ATmega16U2, I am using a clone one, so would that differ anyhow?

It should work with different chips than the ATmega16U2 as well, but maybe check that there is indeed a 1k resistor on its TX pin.

If you are actually finding that the ESP is turning OFF unexpectedly, you can try to upload a new firmware AT_v0.50_on_esp_iot_sdk_v1.4.0_150918 using the official firmware tool Espressif Official Flash download tool from http://bbs.espressif.com/viewtopic.php?f=57&t=433.

Well, if that is what "connection refused" means then I will try it too. Thanks for the suggestion. :)


text:
Relay Board making Output Signal Weak
I am using an Arduino Uno and Relay Shield (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/), and using a code similar to the Teapot Demo, in which an LED blinks when movement is detected. When I connect the shield, the LED blinks at the normal brightness when uploading the code, but blinks extraordinarily dimly when indicating movement. This is both the external and internal LED display for the Arduino.
This is my current setup:

I think it must be a code issue because the LED clearly has the ability to blink on and off normally.
Any suggestions as to what is wrong or what I should do?
Below is my code:
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif
MPU6050 mpu;
// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
#define OUTPUT_TEAPOT

//----------------------------------------------------------------------------------------------

const int LED_PIN = 13; // (Arduino is 13, Teensy is 11, Teensy++ is 6)
const int buzzerPin = 12;

bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200); // this is a "Baud" rate
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

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

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

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

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

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, INPUT);
    pinMode(buzzerPin, INPUT);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            int Mag;
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\n");
            Mag = sqrt((aaReal.x*aaReal.x) + (aaReal.y*aaReal.y));
            Serial.print("Accel. Mag. is ");
            Serial.print(Mag);
//            Serial.print("\t");
//            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED and sound buzzer to indicate activity
        if (Mag > 120) {
          blinkState = !blinkState;
          digitalWrite(LED_PIN, blinkState);
//          delay(1000);
          tone(buzzerPin, 100);
        }
        else if (Mag <= 120) {
          digitalWrite(LED_PIN, LOW);
          noTone(buzzerPin);
        }

    }
}

If it gets dimmed when you're trying to switch the relay on, you don't have power supply powerfull enough to drive it. USB is too weak for this.

I thought this may be the case - I am also using a wall wart to supply 12V of power. It is not changing the output brightness though. Is there another component missing?

Without seeing your code, it is hard to tell you directly what the problems is. If you can, please post your code.
Based on the information in your question, I can see two possible causes for this.
Firstly, it could be that there isn't enough power from your supply to power everything. So when the Arduino tries to turn on the relay, it doesn't have enough grunt and the voltage drops too low and the Arduino resets, de-energising the relay. This happens many times a second and shows up as a dull LED.
This can be proven by disconnecting the relay from the Arduino output. Run the sketch again, and if everything works at full brightness without the relay connected, then it is almost certainly not enough power.
My second theory is that it is a bug in your code. Some cycles it detects movement and so it turns the LED on.  Others cycles it doesn't detect a change in movement so it turns the LED off. This happens many thousand times a second. It would be visible on an oscilloscope if you have one.
The simple thing you could do for this scenario is to add a delay (eg delay(1000);) straight after the LED is turned on when movement is detected. This should leave the LED on for at least a second after movement is detected.

You're probably right. I added a delay and the LED was dimly glowing even when using the wall wart. I have another wall wart that has bare wires so that I can use it as an external power source. Do you think this would work? If so, should I just hook the LED up directly to one end and ground the other?

What is the current output of the wall warts? What you suggest is what I would look into. I would just be cautious doing so. Examine the schematics of each to make sure that one doesn't feed into the other.

The current output is 800mA. I got the larger LED to glow, which was the main goal, so it may have just been due to faulty wiring on my part. Thank you for your help!

source: Stack Exchange

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

sort: votes


text:
How to add additional millisecond delay to microsecond delay generator
I am trying to make a delay generator. I already found an excellent example in Generating a short pulse after a delay that works in the range from ~5-32767 microseconds (it is limited by a 16 bit microsecond counter divided by 2).
How would I go about extending that range into the millisecond range (say up to 1s or so)? Since this example is interrupt-based, adding delay() statements do not really seem to work.
I have also tried changing the timer prescaler, but then the jitter is also scaled up in an unacceptable way.
This is the code I have now. Send commands via the arduino serial console, D500 for 500µs delay, L100 for a 100µs long pulse. Letters M and N change the prescaler.
uint16_t pulse_delay = 10; //half-microseconds
uint16_t pulse_length = 10;
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
long read_value = 0;
long ms_delay = 0;

void printvals() {
  Serial.print(F("Delay: "));
  Serial.print(pulse_delay / 2);
  Serial.println(F(" µs"));
  Serial.print(F("Length: "));
  Serial.print(pulse_length / 2);
  Serial.println(F(" µs"));
}
long getcommandvalue(String inputstring) {
  inputString.remove(0,1);
  return inputString.toInt();
}
void setup(){
  pinMode(8, INPUT);
  pinMode(9, OUTPUT);
  TCCR1A = 0;
  TCCR1B = _BV(ICNC1)  //input capture noise cancel
      | _BV(ICES1) //positive edge
      | _BV(CS11); // /8 prescaler
  TIMSK1 = _BV(ICIE1); //enable input capture interrupt
  Serial.begin(9600);
  inputString.reserve(200);
  Serial.println(F("RDY"));
  printvals();
}
void loop(){
  if (stringComplete) {
      switch(inputString.charAt(0)) {
        case 10: //\n (Newline; Line Feed)
          // previous line ending was CRLF, so now LF was carried to the next string
          break;
        case 63: //?
          //print current vales
          printvals();
          break;
        case 68: //D (Delay)
          read_value = getcommandvalue(inputString);
          if (read_value >= 1) {
            pulse_delay = 2 * read_value;
            printvals();
          }
          break;
        case 76: //L (Length)
          read_value = getcommandvalue(inputString);
          if (read_value >= 1) {
            pulse_length = 2 * read_value;
            printvals();
          }
          break;
        case 77: //M (additional prescaling)
          TCCR1B = _BV(ICNC1)  //input capture noise cancel
            | _BV(ICES1) //positive edge
            | _BV(CS10) // 64 prescaler
            | _BV(CS11); // /8 prescaler
          break;
        case 78: //N (8x prescaling)
          TCCR1B = _BV(ICNC1)  //input capture noise cancel
            | _BV(ICES1) //positive edge
              | _BV(CS11); // /8 prescaler
          break;
        case 79: //O
          ms_delay = getcommandvalue(inputString);
          // I don't know where to execute this ms_delay
          break;
      }
      inputString = "";
      stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:Z
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if ((inChar == '\n') or (inChar == '\r')) {
      stringComplete = true;
    }
  }
}

ISR(TIMER1_CAPT_vect){
  TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
  TIFR1 = _BV(OCF1A);  // clear interrutp flag
  TIMSK1 |= _BV(OCIE1A); //enable match interrupt
  OCR1A = pulse_delay; //pulse begin time

  TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                        //the interrupt isn't run immediately
}
ISR(TIMER1_COMPA_vect){
  TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
  TCCR1A = _BV(COM1A1); //clear OC1A on match
  OCR1A = pulse_delay + pulse_length;
}

Put it in a loop and run it multiple times.  But also consider the loop overhead.

You could count timer compare matches.  The following illustrates the principle, maybe not accurate as written but I am sure the counter loop will be precise enough for your needs, considering you want to use an Arduino.  Depending on the time resolution you want, you may be able to run other code while the software counter is active.
The following can count to several seconds, depending on values of OCR1A and counter_target.
unsigned int state, pulse_delay;
byte counter[3]={0,0,0}; // 24 bit counter, you can make it longer in principle

byte counter_target[3]={0,0,0}; // defines length of delay you want

void setup(){
state=0;
TCCR1A=0;
TCCR1B=0;
}

void loop(){
switch (state){
case 0: // idle state machine // you other code here
counter_target[0]=0; // For example
counter_target[1]=0;
counter_target[2]=1; // corresponds to (1+65536)*pulse_delay/clock_scaler
// when you are ready to start counting
state=1;
break;

case 1: // setup timer
counter[0]=0; // Zero the 24-bit counter
counter[1]=0;
counter[2]=0;
OCR1A = pulse_delay; // number of pulses to count = 1+OCR1A
OCR1B = OCR1A+1;
ICR1  = OCR1A+1;    // Just to make sure these don't cause compare match
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
state=2;
TCCR1A = B00000011; // Fast PWM mode 15 on UNO, OCR1A=TOP
TCCR1B = B00011001; // Clock prescaler 1
break;

case 2: // Counting up
loop_until_bit_is_set(TIFR1,OCF1A);
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
counter[0]+=1; // Increment counter by 1
if(counter[0]==0x00){counter[1]+=1;
if(counter[1]==0x00){counter[2]+=1;}} // etc

if(counter[0]==counter_target[0] && counter[1]==counter_target[1] && counter[2]==counter_target[2]){state=0;}  // Check if we have reached the target delay
break;

}
}

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


text:
Exporting an html for esp8266
EDIT: Added "web page source" ("In the end", :D )
(Please, sorry if this question isn't in the right place, feel free to move it to that place)
Here I have a problem:
In my house I have a self-arming alarm (through hour(RTC) ) made by me, using an Arduino Nano, an RTC1307 and some sensors (PIRs and magnetic). It works well, with its buttons, relays and LEDs to indicate.
All right, now I want to pass it to a esp8266, to be able to manage the alarm from the local network of my house using HTML and some  structures. I'm stuck in the construction part of the website, I mean: I already have the web page, at least opening the website from the browsers of the PC and my smartphone (locally), the question comes when I put the site inside the esp8266, It does not do what it has to do.
I have my webpage sectioned into 3 pieces using the HTML tags   and some CSS styles, to see the sections in the form of tabs but when I load them to the esp8266 it is as if I do not recognize the tabs, it does not let me click them.
I leave you the code here... please help:

String getPage(){
  String page = "<!DOCTYPE HTML>";
  page += "";
  page += "";
  page += "<meta charset=\"utf-8\">";
  page += "<meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">";

  page += "<title>Alarma</title>";
  ///////////////
  ////ESTILOS////
  //////////////
  page += "";
  page += "";

  ///////////////
  ////BODY  ////
  //////////////
  page += "";
  page += "
";
  page += "
";
  page += "
Página de configuración de la Alarma
";
  page += "
";

  page += "
";
  page += "<input class=\"input\" id=\"sensores\" type=\"radio\" name=\"tabs\" checked>";
  page += "Sensores activados";

  page += "<input class=\"input\" id=\"hora_interna\" type=\"radio\" name=\"tabs\">";
  page += "Hora Interna";

  page += "<input  class=\"input\" id=\"hora_activacion\" type=\"radio\" name=\"tabs\">";
  page += "Hora de Auto-Armado/Desarmado";

  page += "
";
  //Formulario para sensores
  page += "<FORM action=\"/\" method=\"post\">";
  page += "Sensores activados
";
  page += "
<input type=\"checkbox\" name=\"M1\" id=\"M1\"";
  if (m1 == true){
    page += "checked";}
  page += "> M1
";
  page += "<input type=\"checkbox\" name=\"M2\" id=\"M2\"";
  if (m2 == true){
    page += "checked";}
  page += "> M2
";
  page += "<input type=\"checkbox\" name=\"M3\" id=\"M3\"";
  if (m3 == true){
    page += "checked";}
  page += "> M3
";
  page += "<input type=\"checkbox\" name=\"M4\" id=\"M4\"";
  if (m4 == true){
    page += "checked";}
  page += "> M4
";
  page += "<input type=\"checkbox\" name=\"PIR\" id=\"PIR\"";
  if (pir == true){
    page += "checked";}
  page += "> PIR
";
  page += "<INPUT class=\"btn\" type=\"submit\" value=\"Enviar\"> <INPUT class=\"btn\" type=\"reset\" value=\"Resetear\">";
  page += "</FORM>";
  page += "
";

  page += "
";
  //Formulario para PONER la hora
  page += "<FORM action=\"/\" method=\"post\">";
  page += "
Hora interna: <input type=\"time\" name=\"poner_hora\" id=\"poner_hora\" value=\"";
    if (hora_interna < 10){
      page += "0";
      }
  page += hora_interna;
  page += ":";
    if (minutos_interna < 10){
      page += "0";
      }
  page += minutos_interna;
  page += ":00\" size=\"5%\" max=\"23:59\" min=\"00:00\">";
  page += "<INPUT class=\"btn\" type=\"submit\" value=\"Enviar\"> <INPUT class=\"btn\" type=\"reset\" value=\"Resetear\">";
  page += "</FORM>";
  page += "
";

  page += "
";
  //Formulario para hora de auto-armado
  page += "<FORM action=\"/\" method=\"post\">";
  page += "
";
  page += "
Activación: <input type=\"time\" name=\"ontime\" id=\"ontime\" value=\"";
    if (hora_activacion < 10){
       page += "0";}
   hora_activacion;
   page += ":";
    if (minutos_activacion < 10){
       page += "0";}
   minutos_activacion;
   page += ":00 size=\"5%\" max=\"23:59\" min=\"00:00\">
";
   page += "
Desactivación: <input type=\"time\" name=\"offtime\" id=\"offtime\" value=\"";
    if (hora_desactivacion < 10){
       page += "0";
      }
   hora_desactivacion;
   page += ":";
    if (minutos_desactivacion < 10){
      page += "0";
      }
   minutos_desactivacion;
   page += ":00 size=\"5%\" max=\"23:59\" min=\"00:00\">

";
  page += "<INPUT class=\"btn\" type=\"submit\" value=\"Enviar\"> <INPUT class=\"btn\" type=\"reset\" value=\"Resetear\">";
  page += "</FORM>";
  page += "
";
  page += "
";
  page += "
";

  page += "";
  page += "";
  return page;
  }

What I see in my browser locally:

What I see in my browser when I load the page from the esp8266:

I already check for the "checked" tag, in the  tag...
The "web page source" (apparently the browser put some "3D" before the quotes ("), any reason for that?)
From: <Saved by Blink>
Subject: Alarma
Date: Wed, 5 Jun 2018 21:28:15 -0000
MIME-Version: 1.0
Content-Type: multipart/related;
    type="text/html";
    boundary="----MultipartBoundary--T8oNZJiKHmz7Uqtp7zBLZVTRAAqlj41o9li9KHDGiV----"

------MultipartBoundary--T8oNZJiKHmz7Uqtp7zBLZVTRAAqlj41o9li9KHDGiV----
Content-Type: text/html
Content-ID: <frame-2-73f97ce7-1d30-423c-a8b1-c57104e83c66@mhtml.blink>
Content-Transfer-Encoding: quoted-printable
Content-Location: http://192.168.43.5/

<!DOCTYPE html><meta http-equiv=3D"Content-Type" content=3D"tex=
t/html; charset=3DUTF-8"><meta name=3D"viewport" content=3D"width =3D devic=
e-width, initial-scale =3D 1.0"><title>Alarma</title></he=
ad>

P=C3=A1gi=
na de configuraci=C3=B3n de la Alarma

<input class=3D"input" id=3D"sensores" type=3D"radio" name=3D"tabs" checke=
d=3D"">Sensores activados<input class=3D"in=
put" id=3D"hora_interna" type=3D"radio" name=3D"tabs">Hora Interna<input class=3D"input" id=3D"hora_activacion" ty=
pe=3D"radio" name=3D"tabs">Hora de Auto-Arma=
do/Desarmado
<f=
orm action=3D"http://192.168.43.5/" method=3D"post">Sensores activados
<=
p><input type=3D"checkbox" name=3D"M1" id=3D"M1" checked=3D""> M1
<input=
 type=3D"checkbox" name=3D"M2" id=3D"M2" checked=3D""> M2
<input type=3D=
"checkbox" name=3D"M3" id=3D"M3" checked=3D""> M3
<input type=3D"checkbo=
x" name=3D"M4" id=3D"M4" checked=3D""> M4
<input type=3D"checkbox" name=
=3D"PIR" id=3D"PIR" checked=3D""> PIR
<input class=3D"btn" type=3D"submi=
t" value=3D"Enviar"> <input class=3D"btn" type=3D"reset" value=3D"Resetear"=
>
</form>

<form =
action=3D"http://192.168.43.5/" method=3D"post">
Hora interna: <input typ=
e=3D"time" name=3D"poner_hora" id=3D"poner_hora" value=3D"10:40" size=3D"5%=
" max=3D"23:59" min=3D"00:00"><input class=3D"btn" type=3D"submit" value=3D=
"Enviar"> <input class=3D"btn" type=3D"reset" value=3D"Resetear">
</form=
>

<form action=
=3D"http://192.168.43.5/" method=3D"post">

Activaci=C3=B3n: <input type=3D"time" name=3D"ontime" id=3D"o=
ntime" value=3D"10:40" size=3D"5%" max=3D"23:59" min=3D"00:00">

Desactivaci=C3=B3n: <input type=3D"time" name=3D"offtime=
" id=3D"offtime" value=3D"=08:40"" size=3D"5%" max=3D"23:59" min=3D"00=
:00">

<input class=3D"btn" type=3D"submit" value=3D"Env=
iar"> <input class=3D"btn" type=3D"reset" value=3D"Resetear"></form></secti=
on>

------MultipartBoundary--T8oNZJiKHmz7Uqtp7zBLZVTRAAqlj41o9li9KHDGiV------

I´ll add my entire code:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

//Definir el led
#define LED 2

//Variables de apoyo
bool m1 = true;
bool m2 = true;
bool m3 = true;
bool m4 = true;
bool pir = true;

//SSID and Password of your WiFi router
const char* ssid = "asd";
const char* password = "12345678";

ESP8266WebServer server(80);

//////////////////////////////////////////////
//                 Index                    //
/////////////////////////////////////////////
String getPage(){
  String page = "<!DOCTYPE HTML>";
  page += "";
  page += "";
  page += "<meta charset=\"utf-8\">";
  page += "<meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0\">";

  page += "<title>Alarma</title>";
  ///////////////
  ////ESTILOS////
  //////////////
  page += "";
  page += "";

  ///////////////
  ////BODY  ////
  //////////////
  page += "";
  page += "
";
  page += "
";
  page += "
Página de configuración de la Alarma
";
  page += "
";

  page += "
";
  page += "<input class=\"input\" id=\"sensores\" type=\"radio\" name=\"tabs\" checked>";
  page += "Sensores activados";

  page += "<input class=\"input\" id=\"hora_interna\" type=\"radio\" name=\"tabs\">";
  page += "Hora Interna";

  page += "<input  class=\"input\" id=\"hora_activacion\" type=\"radio\" name=\"tabs\">";
  page += "Hora de Auto-Armado/Desarmado";

  page += "
";
  //Formulario para sensores
  page += "<FORM action=\"/\" method=\"post\">";
  page += "Sensores activados
";
  page += "
<input type=\"checkbox\" name=\"M1\" id=\"M1\"";
  if (m1 == true){
    page += "checked";}
  page += "> M1
";
  page += "<input type=\"checkbox\" name=\"M2\" id=\"M2\"";
  if (m2 == true){
    page += "checked";}
  page += "> M2
";
  page += "<input type=\"checkbox\" name=\"M3\" id=\"M3\"";
  if (m3 == true){
    page += "checked";}
  page += "> M3
";
  page += "<input type=\"checkbox\" name=\"M4\" id=\"M4\"";
  if (m4 == true){
    page += "checked";}
  page += "> M4
";
  page += "<input type=\"checkbox\" name=\"PIR\" id=\"PIR\"";
  if (pir == true){
    page += "checked";}
  page += "> PIR
";
  page += "<INPUT class=\"btn\" type=\"submit\" value=\"Enviar\"> <INPUT class=\"btn\" type=\"reset\" value=\"Resetear\">";
  page += "</FORM>";
  page += "
";

  page += "
";
  //Formulario para PONER la hora
  page += "<FORM action=\"/\" method=\"post\">";
  page += "
Hora interna: <input type=\"time\" name=\"poner_hora\" id=\"poner_hora\" value=\"";
    if (hora_interna < 10){
      page += "0";
      }
  page += hora_interna;
  page += ":";
    if (minutos_interna < 10){
      page += "0";
      }
  page += minutos_interna;
  page += ":00\" size=\"5%\" max=\"23:59\" min=\"00:00\">";
  page += "<INPUT class=\"btn\" type=\"submit\" value=\"Enviar\"> <INPUT class=\"btn\" type=\"reset\" value=\"Resetear\">";
  page += "</FORM>";
  page += "
";

  page += "
";
  //Formulario para hora de auto-armado
  page += "<FORM action=\"/\" method=\"post\">";
  page += "
";
  page += "
Activación: <input type=\"time\" name=\"ontime\" id=\"ontime\" value=\"";
    if (hora_activacion < 10){
       page += "0";}
   hora_activacion;
   page += ":";
    if (minutos_activacion < 10){
       page += "0";}
   minutos_activacion;
   page += ":00 size=\"5%\" max=\"23:59\" min=\"00:00\">
";
   page += "
Desactivación: <input type=\"time\" name=\"offtime\" id=\"offtime\" value=\"";
    if (hora_desactivacion < 10){
       page += "0";
      }
   hora_desactivacion;
   page += ":";
    if (minutos_desactivacion < 10){
      page += "0";
      }
   minutos_desactivacion;
   page += ":00 size=\"5%\" max=\"23:59\" min=\"00:00\">

";
  page += "<INPUT class=\"btn\" type=\"submit\" value=\"Enviar\"> <INPUT class=\"btn\" type=\"reset\" value=\"Resetear\">";
  page += "</FORM>";
  page += "
";
  page += "
";
  page += "
";

  page += "";
  page += "";
  return page;
  }

//////////////////////////////////////////////
//          REDIRECCIONAMIENTO             //
/////////////////////////////////////////////
void handleNotFound(){
  server.sendHeader("Location", "/",true);   //Redirect to our html web page
  server.send(302, "text/plane","");
}

//////////////////////////////////////////////
//      handleSubmit                        //
/////////////////////////////////////////////
void handleSubmit(){
  //Atencion a sensores
  if (server.arg("M1") == "on"){
      m1 = !m1;
      Serial.println("Se activo el sensor M1");
      }
  if (server.arg("M2") == "on"){
      m2 = !m2;
      Serial.println("Se activo el sensor M2");
      }
  if (server.arg("M3") == "on"){
      m3 = !m3;
      Serial.println("Se activo el sensor M3");
      }
  if (server.arg("M4") == "on"){
      m4 = !m4;
      Serial.println("Se activo el sensor M4");
      }
  if (server.arg("PIR") == "on"){
      pir = !pir;
      Serial.println("Se activo el sensor PIR");
    }

  //Atencion a establecimiento de la hora
//  if (server.hasArg("poner_hora")){
//    Serial.println(server.arg("poner_hora"));
//    }

  server.send(200, "text/plain", getPage());       //Response to the HTTP request

}

//////////////////////////////////////////////
//      handleRoot                          //
/////////////////////////////////////////////
void handleRoot() {
 Serial.println("You called root page");

  if (!server.args() ) {
    Serial.println("Hay algun argumento valido");
    handleSubmit();
    } else {
      server.send(200, "text/html", getPage());
      }
}

//////////////////////////////////////////////
//                SETUP                     //
/////////////////////////////////////////////

void setup() {
  delay(1000);
  Serial.begin(115200);
  Serial.println("Sistema iniciando");

  //Initialize AP Mode
  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  //Onboard LED port Direction output
  pinMode(LED,OUTPUT);
  //Power on LED state off
  digitalWrite(LED,HIGH);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);

  server.begin();
  Serial.print("Conectate a ");
  Serial.println(WiFi.localIP());
}

//////////////////////////////////////////////
//                LOOP                      //
/////////////////////////////////////////////
void loop() {
  server.handleClient();         //Handling of incoming requests
}

But have you checked the page source?

Yeap, at first I see some garbage (I also checked other webpage to make sure), something like "ContentType" and stuff like that...

please post the "web page source" from the esp8288

Don't use Strings. Save the file in the SPIFFS. Make it static, and fetch dynamic data using JavaScript.

What is SPIFFS? Let me do some research

Does the webserver on the ESP support all the features you are trying to use?  0x3D is the ASCII code for =, is there some encoding issue with you code?

@CodeGorilla I really don't know. How can I know if my ESP (Wemos D1 R1) has support for these CSS code? And why I see the 3D ASCII code? I have reviewed the entire code once and once again, with the same result. Rigth now I continue working without the CSS code... pure HTML, but is ugly!!!

It looks like you page source that is being rendered is email content. The 3D is from the email encoding and I have seen that on Gmail a lot(presumably Gmail parses the = out). What is the way in which you are delivering the webpage from the ESP to an end user? As a reference: https://en.m.wikipedia.org/wiki/Quoted-printable

Hi @RSM, I don't understand your question: what do you mean when you say: "What is the way in which you are delivering the webpage from the ESP to an end user?"? And why the navigator from my phone can even think that the content of the webpage is some kind of email?
(Sorry for the late answer, I don't have a free internet access)

@k.Cyborg The web page source you pasted in has the headers of an email. So at some point, the web page is being made into an email. What why are you using to access the webpage from your phone. Are you using a library to show the page.    Or did you email a copy of the webpage source to be able to past it on the website.  Would you be able to post your code you running ?

HI @RSM, the web page "source" that I pasted is what the navigator (Chrome) from my cell-phone (Xioami RedMi Note4) see, the way I found to "see" what I pasted here (the "source") is downloading the page from my phone and opening it with SublimeText(3.x). I post me entire code, but I'm no using any specific library, just the standart ESP8266WebServer, ESP8266WiFi and the WiFiClient... all of them (and the code, obviosuly) is using the Arduino IDE 1.8.5... any more information that you need? I appreciate any help!

@k.Cyborg Sorry for not replying earlier. Can you try change all the server.send() to use "text/html" and see if that shows anything as you have set it to plain text so the browser might not be interpreting it properly


text:
analogRead always returns 1023 - Arduino Mega 2560
I have connected an FSR (Force Sensitive Resistor) to  as per image(edited name for avoiding mismatch). When I measure the voltage b/w two pins of fsr, voltage changing as per pressure applied. But analogRead always returns 1023. But my another Mega works good with same code and configurations. Can someone guide me to correct it. Thanks in advance.

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

void loop() {
  int num1 = analogRead(A15);
  Serial.println(num1);
  delay(1500);
}

Your code doesn't check the same pin that your schematic shows being connected.   2.  That LED with no current limiting resistor can cause bad things to happen to your board.  That may have something to do with it.

image is just for reference. In our scenario we connected to A15  and used Mega. Please ignore the LED part and UNO

So basically the picture is just a total lie that has nothing to do with the question?  Why post it then?  Why not post the actual circuit you used?

You can't ignore the LED.  It may be the thing causing your problem.

I dont't know how to make the circuit diagram like the above one.

Really?  Get a pencil and a piece of paper and draw a schematic.  take a picture and upload.  What's hard about that?  It might not be so pretty but at least it will be right.  And what do you think is more important, that it be pretty or that it be accurate?

basic debugging includes switching components around ... have you done that? (switch the +5V and the GND connections)

do some research about voltage dividers

If mega a works and mega b doesn't with the same circuit then mega b must be broken.

I had a similar problem when I ported my code from an Arduino Due to an Arduino Mega. I was able to solve this problem by adding the following call in the setup function.
analogReference(DEFAULT);

It seems that in some other Arduinos, the analog reference will be selected automatically, but at least the Arduino Mega needs it.

I had the same problem when simulating a similar circuit in proteus software. I was able to solve it by supplying power with an external dc input terminal to the arduino board 5v pin.

It sounds like your Arduino Mega 2560 is broken.

If mega a works and mega b doesn't with the same circuit then mega b must be broken. – Majenko

You can confirm this theory by creating a voltage divider circuit (or use a potentiometer as a voltage divider) and get your Arduino Mega to read that in. It is good practice to measure the voltage using a multi-meter as well. This will help you verify that the voltage read in correspond with the voltage measured and will also help so you do not go over-voltage.
If you are constantly getting 1023 then change it to another analog input. If that still does not work, then try the other Arduino Mega.


text:
Combining two different coding program into one sketch
Im working on project that uses a relay module,arduino atmega328 and a 2 motor 12vdc. based on coding i give, the first code is the motor 1 will run based on the input switch. and the second code the motor will run based on the delay time. what im doing is, im going to combine these two coding into one sketch hoping these two coding will run together. but im confused on how to combine.
`int motorPin = 10; // pin that turns on the motor
int blinkPin = 9; // pin that turns on the LED
int watertime = 5; // how long to water in seconds
int waittime = 60; // how long to wait between watering, in minutes

void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // set pin 13 to an output so we can use it to turn on the LED
}

void loop()
{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  delay(watertime*3000);        // multiply by 1000 to translate seconds to milliseconds

  digitalWrite(motorPin, LOW);  // turn off the motor
  digitalWrite(blinkPin, LOW);  // turn off the LED
  delay(waittime*6000);        // multiply by 60000 to translate minutes to milliseconds
}`

this is the coding to run the motor by using delay time
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == LOW) {
    // turn LED on:
    digitalWrite(ledPin, LOW);
  } else {
    // turn LED off:
    digitalWrite(ledPin, HIGH);
  }
}

this is the code which the motor will run based on the switch
for now, i dont have idea on how to combine these two coding.
the idea of my project is when switch is LOW(pin 3)  the Motor 1(pin 13) will HIGH until the switch is HIGH, the motor 1 will be LOW and stop.  At the same time,  there will be time delay for 10 second and the Motor 2 (pin 10)will active soon after switch is LOW and delaying time for 10 seconds and the Motor 2 will be active with time for 25 second  and stop and the next active for another 60 minutes

You won't have any idea until you learn to understand what those two individual codes are doing on each line.  Once you learn that then combining them becomes trivial.  So the thing to do is to go learn what all those lines of code mean and do.

If you want someone here to be able to help you then you might want to consider telling what the combined code should do.

@Delta_G okay i just edited what the code should do

Can you edit it again and be specific about what you want it to do?  How many seconds is "several seconds".  Should I write a routine to come up with a random number for that?  Or did you have some number in mind?  Can you see how frustrating it can be to try to help someone who doesn't even know what they want?

You will need to change the delay sketch to use non-blocking code. During execution of delay() the Arduino is just busy waiting and there is nothing like doing things at the same time on Arduino. You have to use code that runs fast enough sequentially to let it seem, as it is doing things simultaneously. Refer to the BlinkWithoutDelay example of the Arduino IDE. Learn how to use it, there are hundreds oft tutorials on the internet, including the Arduino documentation.

This question has been asked a number of times. Please see an old answer: https://arduino.stackexchange.com/questions/17277/altering-code-to-run-a-timer-while-checking-for-a-data-input/24644#24644

The simplest way of combining two programs is this:

Copy the content of the two programs into a single new .ino (program) file
Rename the first setup function setup_one
Rename the first loop function loop_one
Rename the other setup and loop functions setup_two and loop_two
Add the following code to the bottom of that file.

Code:
void setup()
{
  setup_one();
  setupr_two();
}
void loop ()
{
  loop_one();
  loop_two();
}

This is a very simplistic approach and it won't work for all cases.  It will work in this case, but you will find it will do program one then program two.  It will work because your constants don't clash (at the top of the program) you aren't using the same pin in the different programs, etc.
You need to learn what the code does though to really merge the programs, you will see better ways of doing it.  The best way to learn is to right down, in your native language, what each line of code does, so in the case of program one:
turn on the motor
turn on the LED
wait for 'watertime' seconds
turn off the motor
turn off the LED
wait for 'waittime' minutes

For program 2:
  read the state of the pushbutton value:
  If the button is in state low
    Turn off the LED -- Not sure  this might be on
  else
    Turn on the LED -- Not sure this might be off

Hopefully you should recognise those descriptions (they are the comments) and when you read through the descriptions you will realise why the code you put together using the above method "doesn't work".  It does, you just need to wait for 'waittime' minutes before you get a few microseconds to press the button.
If you want the motor to respond to the button then rearrange the natural language description to do what you want and then replace the English with the code and you should have a program that is close to working.  (Hopefully)


text:
Limiting Data Output Frequency from ADXL345
I have a working ADXL345 connected to an Arduino UNO, I need to limit the rate at which the ADXL345 takes in readings. I am using the SparkFun library for this sensor. I have read about the delay function and it works in the loop function but I was wondering if there might be a better way that is much more efficient?

Everytime you get a value from the sensor (for example with getX() or others) the library communicates with the sensor over I2C or SPI. So you can limit the usage of these function in your sketch. One way is with using delay(), but this is considered unefficient in most cases, since you are basically busy waiting during execution of delay(). You will not be able to do anything else in the future during this time span (if you want to add functionality to your device).
It's better to use non-blocking code, that only checks, if it is time to do something and if not going further through the program. Image like you yourself would bake a pizza. You would not stare at the clock for 20 min, until the time is up. You would periodically check, if the time has come to take the pizza out.
You can achieve this on an Arduino with use of the millis() function, which returns the number of milliseconds since the last powerup/reset. (Note that it overflows after about 50 days). There are plenty of tutorials for that out there. You can start with the BlinkWithoutDelay example from the Arduino IDE, which perfectly shows, how this is to be coded.
Note: If you are using the sensor with a battery, then you might want to limit its power usage. For this the library can set the corresponding registers in the sensor to set the datarate in the sensor (The rate at which the data in the sensor is updated). A smaller rate will lower the power consumption. So you can set the rate at about the rate of the reading in your sketch.


text:
maintain state of a channel cd74hc4067
I have this code to change channels.
void setMuxChannel(byte channel) {
   digitalWrite(muxS0, bitRead(channel, 0));
   digitalWrite(muxS1, bitRead(channel, 1));
   digitalWrite(muxS2, bitRead(channel, 2));
   digitalWrite(muxS3, bitRead(channel, 3));
}

I have this code to write a value in a channels, but when I change to a new channel, the previous channel returns to LOW.
I want to turn on LEDs using multiplexer, however the LEDs do not stay on since the channel they are connected to does not keep its value.
  setMuxChannel(1);
  digitalWrite (muxSIG,a);
  delay(5);
  setMuxChannel(2);
  digitalWrite (muxSIG,b);
  delay(5);
  setMuxChannel(3);
  digitalWrite (muxSIG,c);
  delay(5);
  setMuxChannel(4);
  digitalWrite (muxSIG,d);

What are the values of the variables a to d? And what LEDs? How have you connected them? Provide a schematic for this

You don't want a mux for this job. A shift register would be better.

You can't do that with a multiplexer, unless you scan across all channels really fast.

The whole point of a multiplexer is to only connect ONE channel at a time to the input. It is designed to send many different signals through one wire by time sharing. Normally data in some form is send, and not the direct control current of a simple load. So you will not be able to drive more than one channel at a given time.
You can cycle very fast through the channels to let it seem, as if the LEDs were on simultaneously, but this will decrease their light intensity.
If you just want to drive some LEDs without using too mich of the IO pins, you should follow Majenkos comment and use a shift register instead. They can drive all outputs at the same time if wanted. Also often they can be daisy-chained to simply controlling multiple shift registers through a single output of the Arduino.


text:
Arduino Zero AnalogReadFast Compiling Error
#include <Streaming.h>
#include <StopWatch.h>
#include <Albert.h>
#include "avdweb_AnalogReadFast.h"

const byte adcPin = A1;

void setup(void)
{ Serial.begin(9600);
  while(!Serial);
  Serial << "\nanalogRead_10bit us1 analogRead_12bit us2 analogReadFast_10bit us3 analogReadFast_12bit us4";
  for(int i=0; i<10; i++) testAnalogRead();
}

void testAnalogRead()
{ static Stopwatch stopwatch(micros);
  //delay(1000);

  stopwatch.start();
  int adc1 = analogRead(adcPin); // default resolution 10bit 425us on SAMD21
  stopwatch.stop(); int t1 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc2 = analogRead(adcPin); // 425us on SAMD21
  stopwatch.stop(); int t2 = stopwatch.interval;

  analogReadResolution(10);
  stopwatch.start();
  int adc3 = analogReadFast(adcPin); // 23us on SAMD21
  stopwatch.stop(); int t3 = stopwatch.interval;

  analogReadResolution(12);
  stopwatch.start();
  int adc4 = analogReadFast(adcPin); // 24us on SAMD21
  stopwatch.stop(); int t4 = stopwatch.interval;

  Serial << endl << adc1, t1, adc2, t2, adc3, t3, adc4, t4;
  analogReadResolution(10); // restore default
}

void loop(void)
{
}

When I try to compile this code in the Arduino Zero, it throws out the following errors:
/Users/RAJU/Documents/Arduino/libraries/avdweb_AnalogReadFast/Test_AnalogReadFast_SAM/Test_AnalogReadFast_SAM.ino:1:23: fatal error: Streaming.h: No such file or directory
 #include <Streaming.h>
                       ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Zero (Programming Port).

Can anyone help to resolve this error?

install the library that contains Streaming.h ... the error message tells you that the compiler cannot find it

You can find the Streaming library here at Github


text:
Multiple #ifndef vs. single one #endif
My question is connected with the issue as linked:
Is there any good working MODBUS TCP master library available for Arduino?
An example of Modbus TCP master library as suggested in the post above. A part of ModbusTCP.h file:
#ifndef Modbus_TCPIP_h
#define Modbus_TCPIP_h

#ifndef WIZNET_W5100
#define WIZNET_W5100  0       /**< define 1 if  WIZNET W5100 IC is used, otherwise 0 */
#ifndef ENC28J60
#define ENC28J60      1       /**< define 1 if  ENC28J60 IC is used, otherwise 0     */
#ifndef ESP8266
#define ESP8266       0

//...The entire code of the header

#endif // Just a single one occurence of the #endif in the last line of the header code! 8-|

When I've run the compilation of it in my Arduino IDE, I've got an error as follows: unterminated #ifndef. Mentioned error has a four ocurrences in the error log and it is linked to: Modbus_TCPIP_h, WIZNET_W5100 and ENC28J60.
What should be modified in the header file?

These of course each need to be matched by an ending, as they are fully independent.  Are you confusing this with else clauses?

It's a bug in the library. Someone submitted a PR: https://github.com/goddland16/Modbus-TCP/pull/2 and the library owner merged it. Apparently neither of them bothered to test the code or even give it a quick look. That doesn't give me much confidence in the quality of their work. My advice is to look for an alternative library of higher quality.

you might have figured it out yourself if you asked why is ESP8266 not getting an error

Dear All. As per per1234 suggestion I would place the main question ones again: Is there any good working and also tested and proven MODBUS TCP master library available for Arduino?

The code is missing "#endif". Should look something like this:
#ifndef WIZNET_W5100
#define WIZNET_W5100  0       /**< define 1 if  WIZNET W5100 IC is used, otherwise 0 */
#endif
#ifndef ENC28J60
#define ENC28J60      1       /**< define 1 if  ENC28J60 IC is used, otherwise 0     */
#endif
#ifndef ESP8266
#define ESP8266       0
#endif

Cheers!

A new error available:modbusTCPlib_enc28j60:23: error: token "=" is not valid in preprocessor expressions
#define ENC28J60     = 1

Did you accept the answer above? And now adding a new question. Fun!

I'm trying fix the bugs in the code. In the moment nothing works. All trails brings nothing. So I would ask ones again. Is there any good working and also tested and proven and error free MODBUS TCP master library available for Arduino? Thank you in advance.

Have you read how to use this site? https://arduino.stackexchange.com/tour I recommend that you follow this procedure. It will give you more answers and friends.


text:
IR receiver starts giving nonsense readings in LED colour change setting
First of all, I'm very new to this so sorry if it's a dumb question.
I have an IR module which I'm using to control an LED strip. I have set buttons 1–3 on the remote to select three basic static colours and up and down to adjust brightness. So far so good.
I have set button 4 to gradually shift through different colours. Once I activate this code, the IR receiver appears to stop working, and Serial.print shows that it's now reporting random values whatever button I press on the remote.
I have tried Vishay TSOP4838 and KY-022 type receivers, and tried varying combinations of resistors and capacitors on the receiver power supply. I've tried powering it from 3.3V and 5V.
The code that I'm using is only changing numerical values to adjust the colour, so short of there being 'noise' somewhere in the hardware I'm at a loss as to why only this code breaks it. The LED is powered by a 12V adaptor. The IR receiver is the only thing powered by the Arduino.
My full code is as follows, I know it's untidy. I am a noob:
Thank you
#include "IRremote.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

//To change the LED/IR reciever pins, you just need to change these values
#define PIN 13 //LED strip
int receiver = 10; //IR receiver

unsigned long debouncing = 0;
unsigned long rotatedelay = 6;
unsigned long fadegap = 5;
byte state = 0; //maintains function based on last button press
byte red = 0;
byte blue = 0;
byte green = 0;
byte brightness = 250;
byte rotate = 0; //used for cycling through colours in state 4

Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, PIN, NEO_GRB + NEO_KHZ800);

//Declare IR objects
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'

//Setup IR buttons with names
void translateIR() // takes action based on IR code received

// Naming remote IR codes and assigning a 'state'

{

  switch(results.value)

  {
  case 0xFFA25D: state = 10; Serial.println("POWER"); break;
  case 0xFF629D: state = 11; Serial.println("VOL+"); break;
  case 0xFFE21D: state = 12; Serial.println("FUNC/STOP"); break;
  case 0xFF22DD: state = 13; Serial.println("FAST BACK");    break;
  case 0xFF02FD: state = 14; Serial.println("PLAY/PAUSE");    break;
  case 0xFFC23D: state = 15; Serial.println("FAST FORWARD");   break;
  case 0xFFE01F: Serial.println("DOWN");    break;
  case 0xFFA857: state = 17; Serial.println("VOL-");    break;
  case 0xFF906F: Serial.println("UP");    break;
  case 0xFF9867: state = 19; Serial.println("EQ");    break;
  case 0xFFB04F: state = 20; Serial.println("ST/REPT");    break;
  case 0xFF6897: state = 0; Serial.println("0");    break;
  case 0xFF30CF: state = 1; Serial.println("1");    break;
  case 0xFF18E7: state = 2; Serial.println("2");    break;
  case 0xFF7A85: state = 3; Serial.println("3");    break;
  case 0xFF10EF: state = 4; Serial.println("4");    break;
  case 0xFF38C7: state = 5; Serial.println("5");    break;
  case 0xFF5AA5: state = 6; Serial.println("6");    break;
  case 0xFF42BD: state = 7; Serial.println("7");    break;
  case 0xFF4AB5: state = 8; Serial.println("8");    break;
  case 0xFF52AD: state = 9; Serial.println("9");    break;
  case 0xFFFFFFFF: Serial.println("REPEAT");break;

  default:
    Serial.println(" other button   ");

  }// End Case

} //END translateIR

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the IR receiver
  strip.begin();
  colorBlock(strip.Color(0, 0, 0));
  strip.show(); // Initialize all pixels to 'off'

//Fades LED strip light in at startup
for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, 255 * b/255, 255 * b/255, 255 * b/255);
     }

     strip.show();
     delay(5); //speed of fade in (20 x 255 = total time)
  };
}

void loop() {

//IR detection code
//if (irrecv.decode(&results) && millis() - debouncing > 1000) // have we     received an IR signal? ignores button press if less than a second after previous
if (irrecv.decode(&results)) // have we received an IR signal?
{
    translateIR();
    irrecv.resume(); // receive the next value
    Serial.println(results.value, HEX);

if (state == 1){
  rotate = 0;
  red = 0; blue = 255; green = 0;
colorBlock(strip.Color(red, blue, green));
}

if (state == 2){
  rotate = 0;
  red = 0; blue = 0; green = 255;
colorBlock(strip.Color(red, blue, green));
}

if (state == 3){
  rotate = 0;
  red = 255; blue = 0; green = 255;
colorBlock(strip.Color(red, blue, green));
}

//brightness
if (results.value == 16769055 && brightness > 0){
  brightness = brightness - 10;
  strip.setBrightness(brightness); strip.show();
  Serial.println(brightness);
}

if (results.value == 16748655 && brightness < 241){
  brightness = brightness + 10;
  strip.setBrightness(brightness); colorBlock(strip.Color(red, blue, green));     strip.show();
  Serial.println(brightness);
}
}

//rotating colours
if (state == 4){
  //Serial.println (state);
  //Serial.println (rotate);
  //Serial.print ("red"); Serial.print (red); Serial.print ("blue"); Serial.print (blue); Serial.print ("green"); Serial.println (green);
  //Serial.println (rotatedelay);
}

if (state == 4 && rotate == 0 && red < 255 && millis() - rotatedelay > 1){
  red = red + fadegap;
  if (blue >= 1){
    blue = blue - fadegap;}
  if (green >= 1){
    green = green - fadegap;}
  colorBlock(strip.Color(red, blue, green));
  rotatedelay = millis();
}

if (state == 4 && rotate == 0 && green > 0 && millis() - rotatedelay > 1){
  green = green - fadegap;
  colorBlock(strip.Color(red, blue, green));
  rotatedelay = millis();
}

if (state == 4 && rotate == 0 && red == 255 && green == 0 && blue == 0 &&         millis() - rotatedelay > 1){
  rotate = 1;
}

if (state == 4 && rotate == 1 && blue < 255 && millis() - rotatedelay > 1){
  blue = blue + fadegap;
  if (red >= 1){
    red = red - fadegap;}
  if (green >= 1){
    green = green - fadegap;}
  colorBlock(strip.Color(red, blue, green));
  rotatedelay = millis();
}

if (state == 4 && rotate == 1 && red == 0 && green == 0 && blue == 255 &&     millis() - rotatedelay > 1){
  rotate = 2;
}

if (state == 4 && rotate == 2 && green < 255 && millis() - rotatedelay > 1){
  green = green + fadegap;
  if (red >= 1){
    red = red - fadegap;}
  if (blue >= 1){
    blue = blue - fadegap;}
  colorBlock(strip.Color(red, blue, green));
  rotatedelay = millis();
}

if (state == 4 && rotate == 2 && blue == 0 && red == 0 && green == 255 &&     millis() - rotatedelay > 1){
  rotate = 0;
}
}

//Solid colour
 void colorBlock(uint32_t c) { //This seems to be the way to colour the whole strip
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    }
 }

Perhaps build two alternate test setups: one where the IR receive can "see" the LED strip but there is no electrical connection of any sort (ie, a second setup with another Arduino on a different computer).  Another with your typical electrical connections, but where the IR receiver is fully shielded from any sight of the LEDs - wrapped in multiple layers of electrical tape or something like that.

remove all code from inside of if (state == 4 && statements and insert Serial.println( statements for debugging

tip: you can use code like this if (blue >= 1) blue -= fadegap;

I've had some problems of the LED's PWM interfering with the IR signal. Or so it seemed at least. In theory, the receiver should have a 38 kHz band pass filter. Also, your code doesn't compile: there's a missing '}' at the end of your loop function.

Thank you for the ideas. I tried isolating the light from the receiver and no luck. Perhaps it's PWM, I need to read up on how the filter works. Oh and the code compiles, it was just a copy/paste error. Thanks

Before the lines
//rotating colours
if (state == 4){

You have an extra closing brace.  IF that is in you real code, I'm not sure how it is compiling.
Assuming it isn't that then you might want to change you code to make it more readable.  This is just part of you code from the same place mentioned before:
if (state == 4)
{
    if (millis() - rotatedelay > 1)
    {
        if (rotate == 0)
        {
            checkFadeGap (red, blue, green);

            if (green > 0)
            {
                green -= fadegap;
                colorBlock(strip.Color(red, blue, green));
                rotatedelay = millis();
            }//if (green > 0)
            if (red == 255  && green == 0 && blue == 0)
            {
                rotate = 1;
            }//if (red == 255)
        }
        if (rotate == 1)
        {
            checkFadeGap (blue, red, green);
            if (red == 0 && green == 0 && blue == 255)
            {
                rotate = 2;
            }//if (blue == 255)
        }
        if (rotate == 2)
        {
            checkFadeGap (green, reb, blue);
            if (red == 0  && green == 255 && blue == 0)
            {
                rotate = 0;
            }//if (green == 255)
        }
    }//if (millis() - rotatedelay > 1)
}    // end of if (state == 4)

This function removes some of the complexity in the code above.
void checkFadeGap (byte& inc, byte& dec1, byte& dec2)
{
    if (inc < 255)
    {
        inc += fadegap;
        if (dec1 > 0)
            dec1 -= fadegap;
        if  (dec2 > 0);
            dec2 -= fadegap;
        colorBlock(strip.Color(red, blue, green));
        rotatedelay = millis();
    }
}


text:
How to use tone in two pins?
I have a buzzer and an IR led emitter so I have to use the tone function to sound the buzzer and to modulate the output of the LED.
I have connected the led pin 5 of the arduino, the buzzer pin A0.
int tones[] = {261, 277, 294, 280, 230};
const int pinBuzzer = A0;
const int cr_pin = 5;

void setup(){
  Serial.begin(1200);
  tone(cr_pin, 38000);  /* For modulation at 38kHz */
  pinMode(pinBuzzer, OUTPUT);
}

void soundBuzzer() {
  for (int i = 0; i < sizeof tones; i ++) {
    tone(pinBuzzer, tones[i]);
  }
    noTone(pinBuzzer);
}

void irLED() {
  Serial.println("Hello");
}

This is my code but I can not make the led and the buzzer work at the same time, apparently the buzzer is affected by the tone line (cr_pin, 38000); / * For modulation at 38kHz * /.
I tried to remove (cr_pin, 38000); / * For modulation at 38kHz * /. of the setup and leave code in the following way.
int tones[] = {261, 277, 294, 280, 230};
const int pinBuzzer = A0;
const int cr_pin = 5;

void setup(){
  Serial.begin(1200);
  pinMode(pinBuzzer, OUTPUT);
}

void soundBuzzer() {
  for (int i = 0; i < sizeof tones; i ++) {
    tone(pinBuzzer, tones[i]);
  }
    noTone(pinBuzzer);
}

void irLED() {
tone(cr_pin, 38000);  /* For modulation at 38kHz */
      Serial.println("Hello");
noTone(cr_pin);
    }

In the first code the LED works but not the buzzer and in the second code the buzzer now works but not the LED.

Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to tone() will have no effect. If the tone is playing on the same pin, the call will set its frequency. Source: arduino.cc - tone().
noTone() Stops the generation of a square wave triggered by tone(). Has no effect if no tone is being generated. Source: arduino.cc - noTone()


text:
post data from node mcu to my sql database
#include <ESP8266WiFi.h>

const char* ssid = "xxxx";
const char* password = "xxxxxxxxxx";

const char* host = "192.168.43.18";
const int ldr = A0;
int val = 0;

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

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  val = analogRead(ldr);
  WiFiClient client;

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 80))
  {
    Serial.println("connected]");
    client.println("POST /past.php HTTP/1.1");
    client.println("Host: 192.168.43.10");
    client.print(val);
    Serial.println(val);
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

I have uploaded this code to node mcu but it get's working but the uploaded data in my database is not shown please any one help me out

I'd expect one empty line after the headers, and also Content-Length header with actual length of val (its string representation, not sizeof int!).

and stop the client after the request

@Juraj In this case I'd expect the destructor takes care about it. If not, it's definitely a bug in the library.

yes the destructor closes the connection. and why do you close it in else? :-)

the ip addresses are not same

My corrected code working code:
#include <ESP8266WiFi.h>

const char* ssid = "vathsal";
const char* password = "1234567890";

const char* host = "wwwkprstaffcom.000webhostapp.com";
const int ldr = A0;
int val = 0;
String data;
void setup()
{
  Serial.begin(9600);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  val = analogRead(ldr);
  data = "ldr=";

  data.concat(val);
  WiFiClient client;

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 80))
  {
    Serial.println("connected]");
    client.println("POST /add.php HTTP/1.1");
    client.println("Host: wwwkprstaffcom.000webhostapp.com");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    Serial.println(val);
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}

Generally speaking, just dropping code does not make an answer.  To constitute an answer, you really should start with an explanation of what you changed and why.

You are using the WIFIClient to send data to a HTTP server.  I don't think the WiFiClient knows how to format HTTP requests properly so you need to do that.  I think there is a HTTPClient which may do more for you.
There is a blank line between the header and body of the message and a blank line at the end of the body. you need to have a line that say `client.println();
Does the "SQL server" accept a message that just contains a number?  How does it know what the number relates to?  If you have some PHP site on the front if the DBS that handles all that then please ignore that question.
You might want to see if you can run Wireshark (or similar) on your PC and see what the MCU is sending, you might also want to look at the Chrome add ins, I believe there are some where you can create raw packets and send those to you server to ensure it responds as expected.
As a final resort you could probably knock up a very quick and dirty C# program using Visual Studio Community Edition (Free) and get that to send a packet to the server.  Using this in combination with wireshark might be easier than using the MCU until you know what you should be doing.

println writes /r/n

Good, because it looks ugly with all those \r\ns in :)  Still need  blank lines though, which can just be two println("");

yes there is HTTP client but it doesn't work so tat i am using wifi client.the wifi client can be used  to send data from from node mcu to http server because we are making the node mcu to act as client at this place  we are naming the website as host because as we know the host can act as both server r as client based on service so in my corrected code u could see that i am naming as host

please refer my corrected code for reference since it is working

You are not actually posting any data.
After client.println("POST /past.php HTTP/1.1");
Add another line(s) like ...
client.println("?myvar=65dcsagh&anothervar=ghsadjkj78");
Also the page on the server (past.php) needs to be able to get and process the sent data.
If using PHP will be soemthing like..
$data = $_GET[myvar];
And then the PHP code need to connect to your SQL database and insert it using mySQL

there is client.print(val);

opps sorry didn't see that then does the second part of my answer help?

he doesn't ask about the php part

No but he does say the data is not entered into the database so without knowing what is in past.php that could be the problem part

guys actually i didn't concatenate the data so tat's wat the problem without concatenate we cannot send the data else if we do the php code which is written on other side will not recognise it

This actually does look to be making an important point.


text:
Minimizing Digital input code
I am making a device which can multiply the analog input signal with respect to the selected gain from the digital inputs. Here I have used two digital inputs(from which I can have four selections) but I am planing to add two inputs more(then I can have 16 selections). I made the code with if else statements is there any shorter way to do that? or else the code is getting huge.
here is the code:
#define sensor A0
#define resetPin 3
#define measurePin 2
#define k1 3
#define k2 4

float A = 0;
float J = 0;
int resetstatus = 0;
int measurestatus = 0;

void setup() {
  Serial.begin(9600);
  pinMode(sensor,INPUT);
  pinMode(resetPin,INPUT_PULLUP);
  pinMode(measurePin,INPUT_PULLUP);
  pinMode(k1,INPUT_PULLUP);
  pinMode(k2,INPUT_PULLUP);
  Serial.println("INITIALAIZING");
  delay(3000);
  Serial.println("Ready to begin");
  delay(200);
  }

void loop()
{
  resetstatus = digitalRead(resetPin);
  measurestatus = digitalRead(measurePin);
  if(resetstatus == LOW)
  {
    reset();
    delay(200);
  }
  if(measurestatus == LOW)
  {
    if(digitalRead(k1 == LOW) && digitalRead(k2 == LOW))
    {
    J = 1.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1 == LOW) && digitalRead(k2 == HIGH))
    {
    J = 2.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1 == HIGH) && digitalRead(k2 == LOW))
    {
    J = 3.0;
    measure();
    delay(50);
    }
    if(digitalRead(k1 == HIGH) && digitalRead(k2 == HIGH))
    {
    J = 4.0;
    measure();
    delay(50);
    }
  }
}
void measure()
{
  A = analogRead(sensor);
  float sumA = A * J;
  Serial.println(sumA);
}
void reset()
{
  Serial.println("reset");
}

I am having a problem with the output from this code
(I am using a potentiometer to feed the arduino an analog value)

I dont know why the output is showing 993 and 3972 at each cycle. can someone explain?

I made the code with if else statements is there any shorter way to do that?

j = 1 + (digitalRead(k1) | (digitalRead(k2) << 1) | (digitalRead(k3) << 2) | (digitalRead(k3) << 3));

or
j = 1 + digitalRead(k1) + 2*digitalRead(k2) + 4*digitalRead(k3) + 8*digitalRead(k4)

dont know why the output is showing 993 and 3972 at each cycle. can someone explain?

the printed values are off because of the error addressed in Nick's answer

If k1 = 0, k2 = 1 the original code selects 2.0, but your code computes 3.0. If k1 and k2 were switched it would be right. However, for more general values a lookup table or array for the J values should be used.

@MaximilianGerhardt, it is no importand which kx is which button. it would be strange if I switch k1 and k2 in the formula

This is wrong:
if(digitalRead(k1 == LOW)

You mean:
if(digitalRead(k1) == LOW

Ditto for a lot of other places in your code.

I made the code with if else statements is there any shorter way to do that?
  or else the code is getting huge.

Yes, there is a way of simplification. As @Juraj already noted, it can in this special case even be expressed as a binary representation:
if(digitalRead(k1) == LOW && digitalRead(k2) == LOW)
{
J = 1.0;
measure();
delay(50);
}
else if(digitalRead(k1) == LOW && digitalRead(k2) == HIGH)
{
J = 2.0;
measure();
delay(50);
}
else if(digitalRead(k1) == HIGH && digitalRead(k2) == LOW)
{
J = 3.0;
measure();
delay(50);
}
if(digitalRead(k1) == HIGH && digitalRead(k2) == HIGH)
{
J = 4.0;
measure();
delay(50);
}

What you are doing here is the following pattern:

read the state of the buttons
depending on which combinations of buttons is pressed, assign a different value to J

We can generalize this concept of "get the J value for a certain button combination" by doing the following:

aggregate the entire "button states" into a single, unique number
search for the associated J value

If we name the input button states "k1" and "k2", we see that you have the following logic:
| k1 | k2 | J   |
| 0  | 0  | 1.0 |
| 0  | 1  | 2.0 |
| 1  | 0  | 3.0 |
| 1  | 1  | 4.0 |

We simply concatenate the button inputs to a signle bitstring "k1|k2" and we see
| (k1,k2) | J   |
| 00      | 1.0 |
| 01      | 2.0 |
| 10      | 3.0 |
| 11      | 4.0 |

If we re-write the binary indices to decimal numbers:
| (k1,k2) | J   |
| 0       | 1.0 |
| 1       | 2.0 |
| 2       | 3.0 |
| 3       | 4.0 |

So we see that we can use this (k1,k2) number as an index from 0 to 3 to get us a J value as such:
//Aggregate all button inputs to single number
//using bitshifts
int index = (digitalRead(k2) << 1) | digitalRead(k1);

//All used J values in the right order
const float J_values[] = {
        1.0f, 2.0f, 3.0f, 4.0f
};

//get the right J value
J = J_values[index];

//measure and delay
measure();
delay(50);

This replaces all your 4 if-else statements and does exactly the same.
Now if you were to add more inputs, you can simply expand the way you construct the index number and your J_values array. Write down the "function table" for your wanted J values as above, construct the bit strings, order the indices in ascending order and write down the array values accordingly.
Referenecs:

https://www.cprogramming.com/tutorial/bitwise_operators.html
https://www.arduino.cc/reference/en/language/structure/bitwise-operators/bitshiftleft/

Put all 4 pins on one port then do a port read.
Say you used D2,3,4,5
Then
switches = (PIND && 0b00111100) >> 2;
then switches = 0 to 15 and you can do a branch on that.

yes +1, this low level solution should be mentioned here as answer too


text:
Reduce speed on DC motor
The Arduino starter kit came with a DC motor. I want to have it rotate at a slow speed so it can be on a reel and automatically dispense and wind wire, however, I don't know how I can slow it down.
Giving it an analog value of 1 is still way too fast.
Is there any way to control or reduce the speed. Like a 360 degree turn in a second rather than milliseconds?
Thanks

Remember if you are using a UNO or similar there is no Analog Output, the output is PWM (Look that up).
If its DC motor then it needs to work from a DC (constant voltage) and will spin at a fixed speed.
Motors usually have a RPM (speed) specification.
Speed can be reduced with gears and rotation detected with rotary encoders and or sensors like Infra Red Switches or Reed Switches.
You can also get Motor Controllers like...
https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
AC Motors can be speed controlled by changing drive frequency, this is usually called an inverter.
NOTE reducing DC voltage will result in less torque and higher current.
Hope this helps.


text:
FTDI and atmega328p-au
I want to connect an Arduino Pro Mini with ATmega328P so as to drive a SI4463. But I don't know BLK, CTS, DTR should be connected to what pins of ATmega328P.
How do I connect this?

If you're trying to build an ATmega circuit and asking about it on the Arduino site, shouldn't you review the published schematic of a comparable Arduino, ie, one using the same 5-pin FTDI header???  Additionally you should probably consider prototyping this with a modular Arduino before making a board - the Si4463 is non-trivial in complexity even if on a module, and in addition to helping prove your plans, a prototype around an Arduino will let you get started on the software tasks while your PCB is being fabricated.

BLK is ground.
CTS is generally not used. I leave it unconnected on my boards.
DTR goes to the auto-reset circuit.
Update:

Can I let DTR directly connect with RESET ?

Auto-reset circuits use a .1uf capacitor between the DTR (or RTS, depends on which one your cable supplies) and the reset pin. (The exact value probably isn't too important). Without it, the reset circuit is likely pick up noise and randomly reset the Arduino.

Can I let DTR directly connect with RESET ?

You can’t connect it directly, because it is low when a connection is made.  So it will keep the Arduino in reset-mode all the time. So the bootloader will never run, and you can’t upload any new code or run existing code.

Also a good idea to have a diode in parallel with the resistor - cathode to 5V.  Keeps any high voltage spikes on the Reset line from kicking off the High Voltage programming sequence and the chip then acting hung.


text:
Serial.print query
is it even possible to print a variable output with 4 digits before and one digit after decimal in serial monitor?
my pot reading is shown in the above output
value   -   1.2
value   -   51.5
value   -   61.8
value   -   546.6
value   -   255.0
value   -   1235.9

to this
value   -   0001.2
value   -   0051.5
value   -   0061.8
value   -   0546.6
value   -   0255.0
value   -   1235.9

There are some implementations of printf() kicking around in some libraries.  If they are fully implemented you could use the command printf ("value   -  %04.1f\n", value); and that will give you 4 digits before the DP padded with zeros and one after the DP.

stdio sprintf and co. are build in, but without %f support. simplest is to code print of necessary count of zeros

%f specified does not work with Arduino provided functions like snprintf.

@MaximilianGerhardt, those are AVR libraries, not Arduino. http://nongnu.org/avr-libc/user-manual/modules.html

@Juraj Sorry I misread the comment. I somehow read that they are supported, not that they are not. my mistake.

While the libraries are not Arduino, the decision to link the full or miniature one not supporting floating point is an Arduino one.

You basiscally want a format string which includes %f. However on Arduino, that only returns a ? (not included to to space reasons). Refer to https://stackoverflow.com/q/27651012/5296568.
However the alternative is dtostrf (double-to-string-formatted). The function takes the double / float value, the total wanted width of the string and the decimal places you want to have.
However it fills the string with spaces to the left until the total width is met. You need an additional pass to replace it with 0.
#include <Arduino.h>

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

    const float vals[] = {
            1.2, 51.5, 61.8,
            546.6, 255.0,
            1235.9
    };

    //allocate 8 byte buffer
    //biggest string is "-9999.9\0" (with NUL)
    char buf[8];

    int numVals = (int) (sizeof(vals) / sizeof(*vals));

    for(int i=0; i < numVals; i++) {
        //format correctly
        dtostrf(vals[i], 4+1+1, 1, buf);

        //convert left-appended spaces to zeroes
        for(size_t j=0; j < sizeof(buf); j++){
            if(buf[j] == ' ')
                buf[j] = '0';
        }

        //print buffer
        Serial.println(buf);
    }
}

void loop() {
}

Prints
0001.2
0051.5
0061.8
0546.6
0255.0
1235.9

Edit: You can also offload it into a function and then feed it with the ADC values.
Example:
#include <Arduino.h>

void printValueFormatted(float value, int numDecimalPlaces, int totalWidth) {
    //format correctly
    char buf[16];
    //prevent buffer overflow
    if(totalWidth >= (int) sizeof(buf))
         return;
    dtostrf(value, totalWidth, numDecimalPlaces, buf);

    //convert left-appended spaces to zeroes
    for(size_t j=0; j < sizeof(buf); j++){
        if(buf[j] == ' ')
            buf[j] = '0';
    }

    //print buffer without newline
    Serial.print(buf);
}

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

void loop() {
    float val = analogRead(0);
    Serial.print("ADC Count: ");
    Serial.print(val);
    Serial.print("  -- Voltage: ");
    val = val * 5.0f / 1023.0f;
    printValueFormatted(val, 1, 4+1+1);
    //print newline
    Serial.println();
    delay(100);
}

Prints
ADC Count: 719.00  -- Voltage: 0003.5
ADC Count: 718.00  -- Voltage: 0003.5

What if i want to change the input analog value to this type of format! then what should I do?

@PeouseDutta I updated the code a bit, do you understand now?

Yes that was very helpful. :)

Why it is not working when I am printing it on a LCD?
it is showing 13.800 instead of 0013.8

@PeouseDutta Can you pastebin the code you're running?

i posted the entire code have a look

@PeouseDutta OK since this is quite lengthy I think it might be best if you asked this as an new question and delete your 'answer' here (because it is not an answer). Also include what it prints in the serial console there.

if(val < 1000){Serial.print('0');}
if(val < 100){Serial.print('0');}
if(val < 10){Serial.print('0');}
Serial.println(val, 1);

This is going to fail for values just under powers of 10.  Consider 999.99 - that is indeed less than 1000, so a leading zero gets printed, but the value itself rounds to 1000.0 when limited to one digit after the decimal point.  You end up with 01000.0, one character too many.  (The idea would work just fine with integer values.)

As is, this isn't going to work. However, it does suggest a strategy of pre-converting to an integer type and a fraction, being careful to get those correctly rounded, and then printing them in an individually formatted manner.


text:
Float magnet switch interrupts atmega328p and RN2483 sends data
It was so easy to my mind but it is really not. I have a float switch which goes high when water is floating. So I connect the switch to INT0 pin of MCU. So when water is not floating everything is OK. When the water is floating I send data. I declare the interrupt as follows:
attachInterrupt (digitalPinToInterrupt (switch), float, RISING);

Where float is
void float()
{
detachInterrupt(0);
digitalWrite (LED, HIGH);
txReturn = myRN.txCnf("1");
}

And my main loop is
attachInterrupt (digitalPinToInterrupt (BUTTON), switchPressed, RISING);
digitalWrite (LED, LOW);
LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

I can't understand why my led is not going LOW and why I interrupt is useless after the first successful time. I am aware that I must keep interrupts routines short and by txReturn.txCnf("1"); I don't but I can not understand where my logic is wrong.

txCnf might itself depend on interrupts. So your code will hang. Set a Boolean flag in the interrupt routine. The in the loop, if the flag is set, send the data and clear the interrupt.

float switch which goes high .... what do you mean by goes high? .... switches usually open or close

float is already defined for floating point number, so you cannot use it for your function that detects when the sensor is floating on water.  Try calling it something else.
Also, instead of detaching and reattaching the interrupt, use a state machine.  When the interrupt is triggered, you will be able to run different code in the main loop.
unsigned int state;
void setup(){
  state=1;
  attachInterrupt(0,changestate,RISING);
}
void loop(){

switch (state) {
case 1: // do something
// add code here
break;

case 2: // do something else
// add code here
break;
}
}

void changestate(){
if(state==1){state=2;} // interrupt changes state
}

Okay your approach makes more sense and seems to be more efficient. I' ll give it a try.


text:
"Does not name a type" error with Serial.print
I am getting an error that I have never seen before and don't know how to fix. Basically I am trying to print a string (stored in thermistor) to the serial monitor. When I run the code I get an error message that says: exit status 1
'Serial' does not name a type.
What can I do fix this error?
void setup() {
Serial.begin(9600);
pinMode(4, OUTPUT);
pinMode(6, OUTPUT);
pinMode(8, OUTPUT);

}

void loop() {

} <==== ERROR: loop() ENDS TOO EARLY
String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
String lilyPad = codeWrite(6, HIGH, LOW, LOW);
String thermistor = codeWrite(8, HIGH, HIGH, LOW);
Serial.println(thermistor);
delay(1000);

String codeWrite(int pin, char output1, char output2, char output3)
{
  digitalWrite(pin, output1);
  int A = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output2);
  int B = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output3);
  int C = digitalRead(pin);
  delay(11);
  String code = String(A) + String(B) + String(C);
  <==== ERROR: MISSING RETURN STATEMENT
}

If you move this code into loop(), the sketch will compile.
String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
String lilyPad = codeWrite(6, HIGH, LOW, LOW);
String thermistor = codeWrite(8, HIGH, HIGH, LOW);
Serial.println(thermistor);
delay(1000);

EDIT:
The sketch should look like this:
void setup() {
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  String heartMonitor = codeWrite(4, HIGH, LOW, HIGH);
  String lilyPad = codeWrite(6, HIGH, LOW, LOW);
  String thermistor = codeWrite(8, HIGH, HIGH, LOW);
  Serial.println(thermistor);
  delay(1000);
}

String codeWrite(int pin, char output1, char output2, char output3)
{
  digitalWrite(pin, output1);
  int A = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output2);
  int B = digitalRead(pin);
  delay(1);
  digitalWrite(pin, output3);
  int C = digitalRead(pin);
  delay(11);
  String code = String(A) + String(B) + String(C);
}

The issue is the code can not be outside of a function.

What do you mean? That code is in void loop(). Should it be moved to a loop with a different type?

Thanks, I completely missed that my brackets were out of place.


text:
4WD Arduino sketch problem
Here is the code:
/**  * @file         Arduino UNO Autonomous Robot  * @author       Calin Dragos for intorobotics.com  * @version      V1.0  * @date
      13.10.2016  * @description  This is an Arduino sketch for an autonomous robot able to detect and avoid obstacles  */
#include <AFMotor.h>
#include <Servo.h>
#include <NewPing.h>
Servo myservo;
int ENABLE_A = 6;
int PIN_A1 = 3;
int PIN_A2 = 2;
int ENABLE_B = 11;
int PIN_B1 = 5;
int PIN_B2 = 4;
int SENSOR_DISTANCE;
int LEFT_SENSOR_DISTANCE;
int RIGHT_SENSOR_DISTANCE;
int SNZ_DISTANCE_L;
int SNZ_DISTANCE_R;
int LFT_SNZ_DIS;
int RGT_SNZ_DIS;
#define TRIG_PIN 7
#define ECHO_PIN 8
#define MIN_DISTANCE 40
#define MAX_DISTANCE 200
#define INTERVAL 200
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
  //pin mode for the DC motors
  pinMode (ENABLE_A, OUTPUT);
  pinMode (PIN_A1, OUTPUT);
  pinMode (PIN_A2, OUTPUT);
  pinMode  (ENABLE_B, OUTPUT);
  pinMode (PIN_B1, OUTPUT);
  pinMode (PIN_B2, OUTPUT);
  //pin mode for the ultrasonic sensor
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  //for servo motor
  myservo.attach(9);
  //set the ultrasonic sensor to center
  sensorCenter();
  //stop the motors
  stopMotors();
}

void loop() {
  SENSOR_DISTANCE = sensorDistance();
  Serial.print("Front sensor distance is: ");
  Serial.println(SENSOR_DISTANCE);
  if (SENSOR_DISTANCE >= MIN_DISTANCE || SENSOR_DISTANCE == 0) {
    goForward();
    Serial.println("Go forward");
  }
  else {
    //stop the motors
    stopMotors();
    LFT_SNZ_DIS = toTheLeft();
    RGT_SNZ_DIS = toTheRight();
    if (LFT_SNZ_DIS >= MIN_DISTANCE && LFT_SNZ_DIS >= RGT_SNZ_DIS)
    {
      int NEW_SNZ_DIS_LFT;
      //try three times to escape
      for (int i = 1; i <= 3; i++) {
        goLeft();
        Serial.println("Go left");
        delay(300);
        //stop the motors
        stopMotors();
        NEW_SNZ_DIS_LFT = sensorDistance();
        if (NEW_SNZ_DIS_LFT >= MIN_DISTANCE)
        {
          break;
        }
      }
      sensorCenter();
    }
    else if (RGT_SNZ_DIS >= MIN_DISTANCE && RGT_SNZ_DIS >= LFT_SNZ_DIS)
    {
      int NEW_SNZ_DIS_RGT;
      //try three times to escape
      for (int j = 1; j <= 3; j++) {
        goRight();
        Serial.println("Go right");
        delay(300);
        //stop the motors
        stopMotors();
        NEW_SNZ_DIS_RGT = sensorDistance();
        if (NEW_SNZ_DIS_RGT >= MIN_DISTANCE)
        {
          break;
        }

      }
      sensorCenter();
    }
    else
    {
      goBackward();
      Serial.println("Go backward");
      delay(500);
      //stop the motors
      stopMotors();
      sensorCenter();
    }
  }
}

void stopMotors() {
  analogWrite (ENABLE_A, 0);
  analogWrite (ENABLE_B, 0);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, LOW);
  digitalWrite (PIN_B1, LOW);
  digitalWrite (PIN_B2, LOW);
}

int sensorDistance() {
  int distance;
  int uS = sonar.ping();
  distance = uS / US_ROUNDTRIP_CM;
  if (distance != 0) {
    return distance;
    delay(300);
  }
}

void goForward() {
  analogWrite (ENABLE_A, 255);
  digitalWrite (PIN_A1, HIGH);
  digitalWrite (PIN_A2, LOW);
  analogWrite (ENABLE_B, 255);
  digitalWrite (PIN_B1, HIGH);
  digitalWrite (PIN_B2, LOW);
}

void goBackward() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, HIGH);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1, LOW);
  digitalWrite (PIN_B2, HIGH);
}

void goLeft() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, HIGH);
  digitalWrite  (PIN_A2, LOW);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1,  LOW);
  digitalWrite (PIN_B2, HIGH);
}

void goRight() {
  analogWrite  (ENABLE_A, 180);
  digitalWrite (PIN_A1, LOW);
  digitalWrite (PIN_A2, HIGH);
  analogWrite (ENABLE_B, 180);
  digitalWrite (PIN_B1, HIGH);
  digitalWrite (PIN_B2, LOW);
}

void sensorCenter() {
  myservo.write(90);
  delay(500);
}

void turnSensorLeft() {
  myservo.write(120);
  delay(500);
}

void turnSensorRight() {
  myservo.write(60);
  delay(500);
}

int leftSensorDistance() {
  int LEFT_SENSOR_DISTANCE;
  LEFT_SENSOR_DISTANCE = sensorDistance();
  return LEFT_SENSOR_DISTANCE;
}

int rightSensorDistance() {
  int RIGHT_SENSOR_DISTANCE;
  RIGHT_SENSOR_DISTANCE = sensorDistance();
  return RIGHT_SENSOR_DISTANCE;
}

int toTheLeft() {
  int LEFT_SENSOR_DISTANCE;
  turnSensorLeft();
  LEFT_SENSOR_DISTANCE = leftSensorDistance();
  Serial.print("Left sensor distance is: ");
  Serial.println(LEFT_SENSOR_DISTANCE);
  return LEFT_SENSOR_DISTANCE;
}

int toTheRight() {
  int RIGHT_SENSOR_DISTANCE;
  turnSensorRight();
  RIGHT_SENSOR_DISTANCE = rightSensorDistance();
  Serial.print("Right sensor distance is: ");
  Serial.println(RIGHT_SENSOR_DISTANCE);
  return RIGHT_SENSOR_DISTANCE;
}

Here is the error that I am getting:
Arduino: 1.8.6 Hourly Build 2018/05/28 09:33 (Windows 8.1), Board: "Arduino/Genuino Uno"
In file included from C:\arduino-nightly\hardware\arduino\avr\cores\arduino/Arduino.h:257:0,
                 from sketch\intorobotics.ino.cpp:1: C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:57:19:
error: expected unqualified-id before numeric constant
#define PIN_A1 (15)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:17:5:
note: in expansion of macro 'PIN_A1'
int PIN_A1 = 3;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:57:19:
error: expected ')' before numeric constant
#define PIN_A1   (15)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:17:5:
note: in expansion of macro 'PIN_A1'
int PIN_A1 = 3;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:58:19:
error: expected unqualified-id before numeric constant
#define PIN_A2 (16)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:18:5:
note: in expansion of macro 'PIN_A2'
int PIN_A2 = 2;
     ^ C:\arduino-nightly\hardware\arduino\avr\variants\standard/pins_arduino.h:58:19:
error: expected ')' before numeric constant
#define PIN_A2   (16)
                   ^ C:\Users\Zeeshan786\Documents\Arduino\intorobotics\intorobotics.ino:18:5:
note: in expansion of macro 'PIN_A2'
int PIN_A2 = 2;
     ^ 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.

I was going to answer your question but instead I had to spend that time cleaning up the garbage formatting you dumped on us by using quote markup instead of code markup on your code and error message. Super disrespectful to the people you're asking for free help.

I'm so sorry....I tried but was getting bold and heading texts

It looks like you've chosen names for your variables that are being used by the core.  Pick different names for those variables.