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

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

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

        }
    }

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

title: Relay Board making Output Signal Weak

Answers: 1

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


body:
I am trying to make a delay generator. I already found an excellent example in [https://arduino.stackexchange.com/questions/34991/generating-a-short-pulse-after-a-delay][1] 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;
    }

  [1]: https://arduino.stackexchange.com/questions/34991/generating-a-short-pulse-after-a-delay

title: How to add additional millisecond delay to microsecond delay generator

Answers: 1

body:
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;

    }
    }


body:
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 <form> 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 locally][1]][1]

What I see in my browser when I load the page from the **esp8266**:
[![What I see in my browser when I load the page from the **esp8266**][2]][2]

I already check for the "*checked*" tag, in the <input> 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
    }

  [1]: https://i.stack.imgur.com/m3JB4.jpg
  [2]: https://i.stack.imgur.com/Gkle9.jpg

title: Exporting an html for esp8266

Answers: 0


body:
I have connected an FSR (Force Sensitive Resistor) to **[![Arduino Mega 2560][1]][1]** 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.
<!-- language-all: lang-cpp -->

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

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

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

title: analogRead always returns 1023 - Arduino Mega 2560

Answers: 3

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

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

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


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

title: Combining two different coding program into one sketch

Answers: 1

body:
The simplest way of combining two programs is this:

1. Copy the content of the two programs into a single new .ino (program) file
2. Rename the first setup function `setup_one`
3. Rename the first loop function `loop_one`
4. Rename the other setup and loop functions `setup_two` and `loop_two`
5. 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)


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

title: Limiting Data Output Frequency from ADXL345

Answers: 1

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


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

title: maintain state of a channel cd74hc4067

Answers: 1

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


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

    #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?

title: Arduino Zero AnalogReadFast Compiling Error

Answers: 0


body:
My question is connected with the issue as linked:
https://arduino.stackexchange.com/questions/36234/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?

title: Multiple #ifndef vs. single one #endif

Answers: 1

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


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

title: IR receiver starts giving nonsense readings in LED colour change setting

Answers: 1

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


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

title: How to use tone in two pins?

Answers: 1

body:
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()][1].

`noTone()` Stops the generation of a square wave triggered by `tone()`. Has no effect if no tone is being generated. Source: [arduino.cc - noTone()][2]

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/
  [2]: https://www.arduino.cc/reference/en/language/functions/advanced-io/notone/


body:
    #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

title: post data from node mcu to my sql database

Answers: 3

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

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

body:
My corrected code working code:

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

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


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

[![output][1]][1]

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

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

title: Minimizing Digital input code

Answers: 4

body:
This is wrong:

    if(digitalRead(k1 == LOW)

You mean:

    if(digitalRead(k1) == LOW

Ditto for a lot of other places in your code.

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

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

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

    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:

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

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

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


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

title: Reduce speed on DC motor

Answers: 1

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


body:
I want to connect an Arduino Pro Mini with ATmega328P so as to drive a [SI4463][1]. But I don't know BLK, CTS, DTR should be connected to what pins of ATmega328P.

How do I connect this?

[![enter image description here][2]][2]

  [1]: https://www.silabs.com/documents/public/data-sheets/Si4464-63-61-60.pdf
  [2]: https://i.stack.imgur.com/6ZI5q.jpg

title: FTDI and atmega328p-au

Answers: 1

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

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

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


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

title: Serial.print query

Answers: 2

body:
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][1]). 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

  [1]: https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html

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


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

title: Float magnet switch interrupts atmega328p and RN2483 sends data

Answers: 1

body:
`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
    }


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

title: "Does not name a type" error with Serial.print

Answers: 1

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


body:
Here is the code:

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

    /**  * @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:

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

    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.

title: 4WD Arduino sketch problem

Answers: 1

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


body:
I can receive serial data from my phone but I can't send serial data to the arduino using bluetooth. I can see my input from serial monitor to my Android but not the other way. I'm using [ARF7044A bluetooth module][1] if that matters. Any help would be appreciated please.

Arduino to Android: Working
Android to Arduino: Not working.

Here is the wiring: [![enter image description here][2]][2]

Here is the code:

    char state;
    void setup()
    {
    pinMode(8, OUTPUT);
    Serial.begin(9600);
    }

    void loop()
    {

      if(Serial.available())
      {
        state = Serial.read();
        Serial.println(state);
      }
      if (state == 'a')
      {
        digitalWrite(8, HIGH);
      }
      else if(state == 'b')
      {
        digitalWrite(8,LOW);
      }
    }

  [1]: http://www.farnell.com/datasheets/462686.pdf
  [2]: https://i.stack.imgur.com/mwQEs.jpg

title: Why can't my bluetooth receive serial data from my android phone, but can send serial data from my bluetooth to my android phone?

Answers: 2

body:
For a reliable solution you must move the Bluetooth device to pins other than digital 0 and 1 and use a software serial instance to communicate with it.

Digital pins 0 and 1 are for communication with the host computer, and the USB-serial chip is permanently wired to them, *even if you are not trying to communicate with the computer*.

There is on many boards a series resistor which allows an external circuit to overpower the USB-serial, but your mis-conceived level shifter has enough resistance itself that it is not able to do this.

Fortunately, while ill-conceived the level shifter is still wired with the idea that the Arduino side is the higher voltage one, so while it adds some load to the Bluetooth, it mostly just adds series resistance.  If the Arduino pin were an ordinary high-impedance once, this would probably still work.  But instead it is one which the USB-serial is trying to control through its own comparable value resistor, and the result is an invalid logic level or a tug-of-war which the USB-serial wins.

body:
Your erroneous level shifting attempt from Bluetooth TX to Arduino RX is the root of your problem.

Pins 0 and 1 are also connected to the on-board USB interface chip via a pair of 1kΩ resistors. These resistors serve two purposes:

1. To "weaken" the drive of the USB chip's UART interface (actually only needed on the USB chip's TX -> Arduino RX connection), and
2. To protect both the USB chip and the main MCU from damage should two connected pins be set to opposing levels, which would cause high currents to flow through both output drivers.

The TX pin of the USB chip is actively driven HIGH all the time when idle (stupid design by Arduino, it should be Hi-Z when the port is not open), and the RX pin is pulled up by the internal pullup resistor in the USB chip.  Further, when the Arduino's `Serial` is in use the TX pin of the Arduino is actively driven HIGH when idle (or LOW when transmitting a "1" bit).

The actual circuit you have looks more like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/Pw1yT.png)

<!-- End schematic -->

Transmitting from the Arduino to the BT module is straight forward enough - the "high" point of the circuit is the Arduno's TX pin at 5V when idle.  Current flows through R2 to the USB RX pin, and through R5 to the BT RX pin, with a portion split off to ground, which is what you want for your level shifting.

Communication in the other direction, however, is different, because you have two balanced "high" points in your circuit - one at the USB TX and one at the Bluetooth TX - and the fact you have 1kΩ resistors in both branches means that neither transmitter is "stronger" than the other. This means that when the BT TX is LOW (0V) you have around 2.5V at the Arduino RX pin (5V over two 1kΩ resistors = 2.5V in the center tap - see [here](https://en.wikipedia.org/wiki/Voltage_divider)).

Since 2.5V is neither within the Arduino's HIGH nor LOW voltage ranges (which are more than 3.5V for HIGH and less than 1.5V for LOW when running from 5V) the input is completely ignored.

The 3.3V transmitted by the Bluetooth module is a little under the *official* threshold for a HIGH signal on an Arduino, but in practice, it usually is detected fine. So remove the resistor network from the Bluetooth's TX pin and connect it directly to the Arduino. Since the input threshold voltage is a function of the supply voltage (0.7 * Vcc) it depends very much on your power supply as to whether it will work reliably or not. If you find it doesn't, you should use some *upward* level shifting.  There are simple MOSFET based bi-directional level shifters available cheaply that are a better solution than resistors, and will allow proper operation in both directions, shifting a high voltage to a low one and a low voltage to a high one. These are good for lower frequency communications such as UART. If you should need higher frequency, or you find a simple MOSFET based shifter isn't working for you then a 74HCT08 or similar chip (be sure to use the HCT range not the HC range) or a dedicated level shifting chip may be in order.


body:
I'm trying to build a transmission frame for a workshop library for the Arduino Uno. I have the byte frame inside an array, give it to another function that builds a bit frame and then want to transmit that bit frame.

When I try to print out the arrays using the serial monitor, I get the correct results for the entire byte array and correct results for the bit array up to a certain point. However, since my output (that I'm checking using a logic analyzer) had also more incorrect values when trying to print the values, I suspect it might have to do with timing issues from my transmission and `Serial.print`.

I thus tried to make another pointer (in the code below `frameCheck`) to print that out _after_ I'm done transmitting my frame, which still leaves me with results that are different from what my logic analyzer tells me from a certain point onwards.

My byte array is as follows:

    10100101  // Preamble
    10000000  // First line of my image
    00100000
    00010000
    01000000
    00000000
    00000000
    00000000
    00000000  // Last (8th) line of my image
    11110000  // Checksum

These values are also represented in the bit array (before assignment to what in my code be called `_frame` as well as after that). However, when I read the values from the logic analyzer, the checksum is transmitted as `11111111` instead of `11110000`.

Here is my code in the .cpp file:

    Transmitter::Transmitter()
    {
      [...]
      _frame = new uint8_t[90];
      frameCheck = _frame;
      [...]
    }

    [...]

    int Transmitter::prepFrame(LEDBitmap image) {
      if(_busy) return -1; //no Data can be sent right now since the transmitter is already busy
      if(!_pin) return -2;
      /** construct the frame that is to be transmitted
        *
        * frame structure is
        * 1 byte preamble (0xA5) | 8 byte payload | checksum
        *
        * the image will be transmitted in rows
        * with one row being one byte
        *  1  2  3  4  5  6  7  8   <-- 1st byte
        *  9 10 11 12 13 14 15 16   <-- 2nd byte
        * 17 18 19 20 21 22 23 24   <-- 3rd byte
        * ...                           ...
        */
      uint8_t size = 10;
      uint8_t frame[size];
      uint8_t checksum = 0x00;

        for(uint8_t h = 0; h < image.getHeight(); h++) {
          uint8_t value = image.getBitmap()[h];
          checksum = (checksum + value) % 255;
          frame[h+1] = value;
        }

        for(uint8_t h = image.getHeight(); h < 8; h++) {
          frame[h+1] = 0x00;
        }

      // building the frame
      frame[0] = PREAMBLE;
      frame[size-1] = checksum;

    //The byte frame "frame" is correct at this point

      _frame = buildBitFrame(frame, size);

    //The frame built by this function (see below) as well as the bit frame "_frame" have the correct checksum

      frameCheck = _frame;  // <-- This is the checkFrame which I print in my .ino which gives me false results.

      // set the transmitter into busy mode so the idle pattern will no longer
      // be transmitted but instead the frame will be sent out.
      _busy = true;
      _pos = 0;

      return 1; //preperation was successful
    }

    uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
      _frameSize = size*8;
      uint8_t bitFrame[_frameSize];
      int pos = 0;
        for (size_t byte = 0; byte < size; byte++) {
          for (size_t bit = 0; bit < 8; bit++) {
            bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
            pos++;
          }
        }

      return bitFrame; // <-- This frame is correct as well.
    }

    void Transmitter::transmitBit() {
      if(_active) {
        // Preperation
        // only change the state when the manchester bit is completely transmitted.
        if(!_manHalf) {
          if(_busy) {
            // if there is currently a transmission running
            // read the next bit from the frame
            _state = _frame[_pos];
            if(_pos >= _frameSize) {
              _busy = false;
              _state = 0;
              _pos = 0;
            }
            _pos++;
          } else { // else transmit the idle pattern
            _state = 0;
          }
        }
        // Transmission
        if (!_manHalf) {
          digitalWrite(_pin, !_state);
        } else {
          digitalWrite(_pin, _state);
        }
        _manHalf = !_manHalf;
      } else {
        digitalWrite(_pin, HIGH);
      }
    }

    [...]

The corresponding, relevant lines in the header file are as follows:

    [...]

    class Transmitter
    {
      public:
        Transmitter();

      public: //methods
        int sendData(LEDBitmap image);
        void transmitBit();
        [...]
        uint8_t* frameCheck;

      private: //members
        uint8_t _state;
        uint8_t* _frame;
        [...]

        int prepFrame(LEDBitmap image);
        uint8_t* buildBitFrame(uint8_t* frame, uint16_t size);
        [...]

    };

    [...]

The function `transmitBit()` is called every 1ms via a ISR.

Last but not least, here is my arduino sketch:

    [...]

    Transmitter transmitter;

    [...]

    int smallData[] = {1, 0, 0, 0,
                       0, 0, 1, 0,
                       0, 0, 0, 1,
                       0, 1, 0, 0};

    LEDBitmap small(4, 4, smallData);

    void setup() {
      Serial.begin(2000000);
      transmitter.setPin(4);
      transmitter.start();
      delay(200);
      pinMode(5, OUTPUT);
      digitalWrite(5, HIGH);
      transmitter.sendData(small);
      delay(1000);
      for(int a = 0; a < 88; a++) {
        Serial.println(transmitter.frameCheck[a]);
      }
    }

The loop is currently empty.

Now onto the weird results I'm getting from printing checkFrame (which I have also already gotten when trying to print the full arrays inside my cpp). This is what it printed (already grouped in bytes):

    1 0 1 0 0 1 0 1
    1 0 0 0 0 0 0 0
    0 0 1 0 0 0 0 0
    0 0 0 1 0 0 0 0
    0 1 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0
    0 0 0 0 0 0 0 0        // Up to here everything is fine.
    0 0 0 0 0 2 149 0      // On the logic analyzer this line reads 0x00 as it should
    221 5 15 0 2 149 0 1   // On the logic analyzer this line reads 0xff instead
    1 222 0 98 2 149 8 218 // This line is irrelevant as it is only a buffer I added to see if the problem lies within my array not having enough space

Now onto my questions!

Do you have an idea what could cause this? Did I do the array assignment wrong? Could this just be an issue with the timing of the `Serial.print`s and my transmitter going off every 1ms? But why does my logic analyzer say that the last line is `0xff` then? Do you have any idea how to fix this?

I'd be super glad if you responded as quickly as possible.
Thanks in advance!

**EDIT:** After increasing the initial value of `a` in my sketch to 64, I found out that the 8th byte is still `00000000` as it says on the logic analyzer. However, the checksum still was a mess. This did also not improve a lot after increasing it to 72. It then was `1 1 2 149 8 218 5 15`. These last few values did also not change when I increased `a` again to 74.

title: Assigning Pointers to arrays - incorrect results?

Answers: 1

body:
    uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
      _frameSize = size*8;
      uint8_t bitFrame[_frameSize];
      int pos = 0;
        for (size_t byte = 0; byte < size; byte++) {
          for (size_t bit = 0; bit < 8; bit++) {
            bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
            pos++;
          }
        }

      return bitFrame; // <-- This frame is correct as well.
    }

You are returning a pointer to a function-local array which was allocated on the stack. After the function exists the stack for that function gets de-allocated and the array becomes invalid.

It may be valid for a short time after the function exists, but as soon as new functions are called and variables are allocated on the stack, this gets overwritten.

See https://www.fayewilliams.com/2015/06/30/a-challenge-discussion-returning-pointers-to-local-variables/

In cases like these (especially with a constant maximum frame length), you should re-write your memory management to use statically allocated buffers within your class.

For example:

    uint8_t* _frame;

to

    #define SOME_MAX_SIZE 128
    uint8_t _frame[SOME_MAX_SIZE];

And then re-write functions to write into these buffers instead of allocating new memory every time.

Dynamic memory allocation in general should be avoided at all costs on a microcontroller due to heap fragmentation.

If you really want to keep doing it you could also allocate a `new` frame of the required length **and** make sure to **delete** it after usage!

    uint8_t* Transmitter::buildBitFrame(uint8_t* frame, uint16_t size) {
      _frameSize = size*8;
      uint8_t* bitFrame = new uint8_t[_frameSize];
      int pos = 0;
        for (size_t byte = 0; byte < size; byte++) {
          for (size_t bit = 0; bit < 8; bit++) {
            bitFrame[pos] = (frame[byte] >> (7 - bit)) & 0x01;
            pos++;
          }
        }

      return bitFrame; //return pointer to malloced array, okay now.
    }