body:
I am currently working on a project which is read a digital input signal from a machine. The machine operation is as below:

when the mold close, the machine gives the "HIGH" signal, when mold is open the machine gives "LOW" signal. A cycle is counted as one cycle when from the mold close --> open --> close.

My goal is to count the cycle and cycle time of each cycle. I am struggling when the Input comes from HIGH to LOW. Appreciate your help to give me some guildance on this project.

    int MoldInput = 2;
    int MoldState = 0;
    int lastMoldState = 0;
    int CycleTimeCounter = 0;
    int CycleCount = 0;
    unsigned long CycleTime;
    volatile unsigned long TimeTemp1 = 0;
    volatile unsigned long TimeTemp2 = 0;
    void setup() {
      // put your setup code here, to run once:
      pinMode (MoldInput,INPUT);
      attachInterrupt(0, RealTimeMoldClose, RISING);
      Serial.begin(115200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.println(CycleTime);
    }
    void RealTimeMoldClose(){
      unsigned long t = millis();
      TimeTemp2 = t;
      CycleTime = TimeTemp2 - TimeTemp1;
      TimeTemp1 = TimeTemp2;
    }

title: Measure cycle count and time of Digital Input

Answers: 1

body:
You don't need to do anything on HIGH to LOW. For example, if you are counting how often a door opens you don't also need to count how often it closes, because it must close before it re-opens.

I don't see the point of the interrupt since your code is doing nothing else than checking if the interrupt occurred, so it may as well be checking if the input has changed anyway. This code is simpler:

    const int MoldInput = 2;

    int lastMoldState = 0;
    unsigned long startTime = 0;
    unsigned long TotalTime = 0;
    unsigned long CycleTimeCounter = 0;

    void setup() {
      pinMode (MoldInput, INPUT);
      Serial.begin(115200);
    }

    unsigned long lastReportedCycleCount = 0;

    void loop() {
      int MoldState = digitalRead(MoldInput);
      if (MoldState != lastMoldState) {
        if (MoldState == HIGH) {
          CycleTimeCounter++;  // count times it was high
          TotalTime += millis() - startTime;  // add up time interval
          startTime = millis ();
          delay (100);    // debounce
        }  // end of state being HIGH
        lastMoldState = MoldState;
      }   // end of state change

      if (CycleTimeCounter % 10 == 0 && CycleTimeCounter != lastReportedCycleCount)
        {
        Serial.print (F("Average time after "));
        Serial.print (CycleTimeCounter);
        Serial.print (F(" cycles is "));
        Serial.print (TotalTime / CycleTimeCounter);
        Serial.println (F(" milliseconds"));
        lastReportedCycleCount = CycleTimeCounter;
        }
    } // end of loop


body:
I am currently working on a project that has an automatic support wheel for bicycle.

The mechanism of this project is when the speed sensor is detecting the RPM of the rear bicycle wheel it will triggered the support wheel. The support wheel is oriented by the motor power. Basically, when the bicycle reaches a certain speed limit, it will activate the support wheel whether to move upwards or downwards. I have done some coding for this.

    int sensor = 11;
    unsigned long start_time = 0;
    unsigned long end_time = 0;
    int steps=0;
    float steps_old=0;
    float temp=0;
    float rpm=0;
    int motorPin = 9;

    void setup()
    {
    {
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(motorPin, OUTPUT);
       Serial.begin(9600);

      pinMode(sensor,INPUT_PULLUP);
    }
    }

    void loop()
    {
     start_time=millis();
     end_time=start_time+1000;
     while(millis()<end_time)
     {
       if(digitalRead(sensor))
       {
        steps=steps+1;
        while(digitalRead(sensor));
       }

     }
        temp=steps-steps_old;
        steps_old=steps;
        rpm=(temp/5)/60;
        Serial.print("RPM = ");
          Serial.println(rpm,DEC);
          delay (1000);
          //Restart the interrupt processing

        if (rpm==0)
        {
          digitalWrite(8, HIGH);
          digitalWrite(7,LOW);
          analogWrite(motorPin, 255);
          delay(1000);

        }

       if (rpm>0.02)
       {
          digitalWrite(8, HIGH);
          digitalWrite(7,LOW);
          analogWrite(motorPin, 255);
          delay(1000);
          digitalWrite(8, LOW);
          digitalWrite(7,LOW);
          analogWrite(motorPin, 255);

       }

       }

The problem with this code is that I do not know how to stop the motor when the `rpm>0` until the sensor read `rpm=0`. I want to make the motor rotate backwards for a few seconds and stop completely as long as the rpm is above zero (my coding will make the motor rotate forward when `rpm>0` again and again, the same goes for when `rpm=0`) and it will only rotate forward for few seconds when the `rpm=0` and stop completely until the sensor read `rpm>0`. The process continues looping.

Please help me, I'm new to Arduino and sorry for my English as I'm not really fluent in English.

title: Problem in integrating speed sensor LM393 with L298N

Answers: 0


body:
    /***************************************************
      This is our GFX example for the Adafruit ILI9341 Breakout and Shield
      ----> http://www.adafruit.com/products/1651

      Check out the links above for our tutorials and wiring diagrams
      These displays use SPI to communicate, 4 or 5 pins are required to
      interface (RST is optional)
      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Limor Fried/Ladyada for Adafruit Industries.
      MIT license, all text above must be included in any redistribution
     ****************************************************/
    #define ILI9341_BLACK       0x0000  ///<   0,   0,   0
    #define ILI9341_NAVY        0x000F  ///<   0,   0, 123
    #define ILI9341_DARKGREEN   0x03E0  ///<   0, 125,   0
    #define ILI9341_DARKCYAN    0x03EF  ///<   0, 125, 123
    #define ILI9341_MAROON      0x7800  ///< 123,   0,   0
    #define ILI9341_PURPLE      0x780F  ///< 123,   0, 123
    #define ILI9341_OLIVE       0x7BE0  ///< 123, 125,   0
    #define ILI9341_LIGHTGREY   0xC618  ///< 198, 195, 198
    #define ILI9341_DARKGREY    0x7BEF  ///< 123, 125, 123
    #define ILI9341_BLUE        0x001F  ///<   0,   0, 255
    #define ILI9341_GREEN       0x07E0  ///<   0, 255,   0
    #define ILI9341_CYAN        0x07FF  ///<   0, 255, 255
    #define ILI9341_RED         0xF800  ///< 255,   0,   0
    #define ILI9341_MAGENTA     0xF81F  ///< 255,   0, 255
    #define ILI9341_YELLOW      0xFFE0  ///< 255, 255,   0
    #define ILI9341_WHITE       0xFFFF  ///< 255, 255, 255
    #define ILI9341_ORANGE      0xFD20  ///< 255, 165,   0
    #define ILI9341_GREENYELLOW 0xAFE5  ///< 173, 255,  41
    #define ILI9341_PINK        0xFC18  ///< 255, 130, 198

    #include "SPI.h"
    #include "Adafruit_GFX.h"
    #include "Adafruit_ILI9341.h"

    // For the Adafruit shield, these are the default.
    #define TFT_CLK 13
    #define TFT_MISO 12
    #define TFT_MOSI 11
    #define TFT_DC 9
    #define TFT_CS 10
    #define TFT_RST 8
    // Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
    //Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
    // If using the breakout, change pins as desired
    Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);

    void setup() {
      Serial.begin(9600);
      Serial.println("ILI9341 Test!");

      tft.begin();

      // read diagnostics (optional but can help debug problems)
      uint8_t x = tft.readcommand8(ILI9341_RDMODE);
      Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX);
      x = tft.readcommand8(ILI9341_RDMADCTL);
      Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX);
      x = tft.readcommand8(ILI9341_RDPIXFMT);
      Serial.print("Pixel Format: 0x"); Serial.println(x, HEX);
      x = tft.readcommand8(ILI9341_RDIMGFMT);
      Serial.print("Image Format: 0x"); Serial.println(x, HEX);
      x = tft.readcommand8(ILI9341_RDSELFDIAG);
      Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);
      /*
      Serial.println(F("Benchmark                Time (microseconds)"));
      delay(10);
      Serial.print(F("Screen fill              "));
      Serial.println(testFillScreen());
      delay(500);

      Serial.print(F("Text                     "));
      Serial.println(testText());
      delay(3000);

      Serial.print(F("Lines                    "));
      Serial.println(testLines(ILI9341_CYAN));
      delay(500);

      Serial.print(F("Horiz/Vert Lines         "));
      Serial.println(testFastLines(ILI9341_RED, ILI9341_BLUE));
      delay(500);

      Serial.print(F("Rectangles (outline)     "));
      Serial.println(testRects(ILI9341_GREEN));
      delay(500);

      Serial.print(F("Rectangles (filled)      "));
      Serial.println(testFilledRects(ILI9341_YELLOW, ILI9341_MAGENTA));
      delay(500);

      Serial.print(F("Circles (filled)         "));
      Serial.println(testFilledCircles(10, ILI9341_MAGENTA));

      Serial.print(F("Circles (outline)        "));
      Serial.println(testCircles(10, ILI9341_WHITE));
      delay(500);

      Serial.print(F("Triangles (outline)      "));
      Serial.println(testTriangles());
      delay(500);

      Serial.print(F("Triangles (filled)       "));
      Serial.println(testFilledTriangles());
      delay(500);

      Serial.print(F("Rounded rects (outline)  "));
      Serial.println(testRoundRects());
      delay(500);

      Serial.print(F("Rounded rects (filled)   "));
      Serial.println(testFilledRoundRects());
      delay(500);

      Serial.println(F("Done!"));
    */
    }

    void loop(void) {
      tft.fillScreen(ILI9341_NAVY);
      tft.setCursor(0, 0);
      tft.setTextColor(ILI9341_WHITE);  tft.setTextSize(1);
      tft.println("Hello World!");
      tft.setTextColor(ILI9341_YELLOW); tft.setTextSize(2);
      tft.println(1234.56);
      tft.setTextColor(ILI9341_RED);    tft.setTextSize(3);
      tft.println(0xDEADBEEF, HEX);
      tft.println();
      tft.setTextColor(ILI9341_GREEN);
      tft.setTextSize(5);
      tft.println("Groop");
      tft.setTextSize(2);
      tft.println("I implore thee,");
      tft.setTextSize(1);
      tft.println("my foonting turlingdromes.");
      tft.println("And hooptiously drangle me");
      tft.println("with crinkly bindlewurdles,");
      tft.println("Or I will rend thee");
      tft.println("in the gobberwarts");
      tft.println("with my blurglecruncheon,");
      tft.println("see if I don't!");
      delay(5000);

    }

    unsigned long testFillScreen() {
      unsigned long start = micros();
      tft.fillScreen(ILI9341_BLACK);
      yield();
      tft.fillScreen(ILI9341_RED);
      yield();
      tft.fillScreen(ILI9341_GREEN);
      yield();
      tft.fillScreen(ILI9341_BLUE);
      yield();
      tft.fillScreen(ILI9341_BLACK);
      yield();
      return micros() - start;
    }

    unsigned long testText() {
      tft.fillScreen(ILI9341_BLACK);
      unsigned long start = micros();
      tft.setCursor(0, 0);
      tft.setTextColor(ILI9341_WHITE);  tft.setTextSize(1);
      tft.println("Hello World!");
      tft.setTextColor(ILI9341_YELLOW); tft.setTextSize(2);
      tft.println(1234.56);
      tft.setTextColor(ILI9341_RED);    tft.setTextSize(3);
      tft.println(0xDEADBEEF, HEX);
      tft.println();
      tft.setTextColor(ILI9341_GREEN);
      tft.setTextSize(5);
      tft.println("Groop");
      tft.setTextSize(2);
      tft.println("I implore thee,");
      tft.setTextSize(1);
      tft.println("my foonting turlingdromes.");
      tft.println("And hooptiously drangle me");
      tft.println("with crinkly bindlewurdles,");
      tft.println("Or I will rend thee");
      tft.println("in the gobberwarts");
      tft.println("with my blurglecruncheon,");
      tft.println("see if I don't!");
      return micros() - start;
    }

    unsigned long testLines(uint16_t color) {
      unsigned long start, t;
      int           x1, y1, x2, y2,
                    w = tft.width(),
                    h = tft.height();

      tft.fillScreen(ILI9341_BLACK);
      yield();

      x1 = y1 = 0;
      y2    = h - 1;
      start = micros();
      for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
      x2    = w - 1;
      for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
      t     = micros() - start; // fillScreen doesn't count against timing

      yield();
      tft.fillScreen(ILI9341_BLACK);
      yield();

      x1    = w - 1;
      y1    = 0;
      y2    = h - 1;
      start = micros();
      for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
      x2    = 0;
      for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
      t    += micros() - start;

      yield();
      tft.fillScreen(ILI9341_BLACK);
      yield();

      x1    = 0;
      y1    = h - 1;
      y2    = 0;
      start = micros();
      for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
      x2    = w - 1;
      for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
      t    += micros() - start;

      yield();
      tft.fillScreen(ILI9341_BLACK);
      yield();

      x1    = w - 1;
      y1    = h - 1;
      y2    = 0;
      start = micros();
      for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
      x2    = 0;
      for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);

      yield();
      return micros() - start;
    }

    unsigned long testFastLines(uint16_t color1, uint16_t color2) {
      unsigned long start;
      int           x, y, w = tft.width(), h = tft.height();

      tft.fillScreen(ILI9341_BLACK);
      start = micros();
      for(y=0; y<h; y+=5) tft.drawFastHLine(0, y, w, color1);
      for(x=0; x<w; x+=5) tft.drawFastVLine(x, 0, h, color2);

      return micros() - start;
    }

    unsigned long testRects(uint16_t color) {
      unsigned long start;
      int           n, i, i2,
                    cx = tft.width()  / 2,
                    cy = tft.height() / 2;

      tft.fillScreen(ILI9341_BLACK);
      n     = min(tft.width(), tft.height());
      start = micros();
      for(i=2; i<n; i+=6) {
        i2 = i / 2;
        tft.drawRect(cx-i2, cy-i2, i, i, color);
      }

      return micros() - start;
    }

    unsigned long testFilledRects(uint16_t color1, uint16_t color2) {
      unsigned long start, t = 0;
      int           n, i, i2,
                    cx = tft.width()  / 2 - 1,
                    cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      n = min(tft.width(), tft.height());
      for(i=n; i>0; i-=6) {
        i2    = i / 2;
        start = micros();
        tft.fillRect(cx-i2, cy-i2, i, i, color1);
        t    += micros() - start;
        // Outlines are not included in timing results
        tft.drawRect(cx-i2, cy-i2, i, i, color2);
        yield();
      }

      return t;
    }

    unsigned long testFilledCircles(uint8_t radius, uint16_t color) {
      unsigned long start;
      int x, y, w = tft.width(), h = tft.height(), r2 = radius * 2;

      tft.fillScreen(ILI9341_BLACK);
      start = micros();
      for(x=radius; x<w; x+=r2) {
        for(y=radius; y<h; y+=r2) {
          tft.fillCircle(x, y, radius, color);
        }
      }

      return micros() - start;
    }

    unsigned long testCircles(uint8_t radius, uint16_t color) {
      unsigned long start;
      int           x, y, r2 = radius * 2,
                    w = tft.width()  + radius,
                    h = tft.height() + radius;

      // Screen is not cleared for this one -- this is
      // intentional and does not affect the reported time.
      start = micros();
      for(x=0; x<w; x+=r2) {
        for(y=0; y<h; y+=r2) {
          tft.drawCircle(x, y, radius, color);
        }
      }

      return micros() - start;
    }

    unsigned long testTriangles() {
      unsigned long start;
      int           n, i, cx = tft.width()  / 2 - 1,
                          cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      n     = min(cx, cy);
      start = micros();
      for(i=0; i<n; i+=5) {
        tft.drawTriangle(
          cx    , cy - i, // peak
          cx - i, cy + i, // bottom left
          cx + i, cy + i, // bottom right
          tft.color565(i, i, i));
      }

      return micros() - start;
    }

    unsigned long testFilledTriangles() {
      unsigned long start, t = 0;
      int           i, cx = tft.width()  / 2 - 1,
                       cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      start = micros();
      for(i=min(cx,cy); i>10; i-=5) {
        start = micros();
        tft.fillTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
          tft.color565(0, i*10, i*10));
        t += micros() - start;
        tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
          tft.color565(i*10, i*10, 0));
        yield();
      }

      return t;
    }

    unsigned long testRoundRects() {
      unsigned long start;
      int           w, i, i2,
                    cx = tft.width()  / 2 - 1,
                    cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      w     = min(tft.width(), tft.height());
      start = micros();
      for(i=0; i<w; i+=6) {
        i2 = i / 2;
        tft.drawRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(i, 0, 0));
      }

      return micros() - start;
    }

    unsigned long testFilledRoundRects() {
      unsigned long start;
      int           i, i2,
                    cx = tft.width()  / 2 - 1,
                    cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      start = micros();
      for(i=min(tft.width(), tft.height()); i>20; i-=6) {
        i2 = i / 2;
        tft.fillRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(0, i, 0));
        yield();
      }

      return micros() - start;
    }

title: exit status 1, cant compile , please help

Answers: 0


body:
I am trying to do a HTTPS post on ESP8266 as shown in Postman below

[![picture from Postman][1]][1]

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

But I keep getting: 'HTTP/1.1 401 Unauthorized'.

Can someone please help me with how to build up the headers correctly in the HTTPS POST? And maybe also give a link to some documentation? I cant seem to find any...

My code is:

    const char* host = "api.dgs.com";
    const int httpsPort = 443;
    String url = "/ccs-int/v1/applicationdatalogging/1.0";
    String msg = "";

    WiFiClientSecure client;

    Serial.print("connecting to : '");
    Serial.print(host);
    Serial.println("'");
    Serial.printf("Using fingerprint '%s'\n", fingerprint);
    client.setFingerprint(fingerprint);

    client.connect(host, httpsPort);

    Serial.print("requesting URL: '");
    Serial.print(url);
    Serial.println("'");

    client.print(String("POST ") + url + " HTTP/1.1\r\n" +
     "Host: " + host + "\r\n" +
     "Connection: close\r\n" +
     "Content-Type: application/json" +
     "Authorization: Bearer " + authorization_code + "\r\n" +
     "Content-Length: " + msg.length() + "\r\n" +
     "\r\n" +
     msg + "\r\n");

    Serial.println("request sent");
    unsigned long timeout = millis();
    while (client.available() == 0) {
     if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
     }
    }

title: How to do a HTTPS post on ESP8266

Answers: 0


body:
So I have not actually experimented with the HC05 Bluetooth Module yet, but I have read up about it and watched some videos. From what I understand, you cannot use one module (master) to communicate with more than one other module (slaves), or at least its pretty difficult. But, you can use a module hooked up to an arduino to communicate to to another module hooked up to another arduino (I believe pretty simply).

However, I thought it might be possible to use an Arduino Mega (because it has multiple TX/RX pins) with 3 HC05 Bluetooth modules, to each communicate to 3 separate HC05s which would each be hooked up to an arduino nano. I know this might have to do something with running multiple Software Serials (I have no idea what that is to be honest)?

The project involves using the master arduino to "listen" for a button pressed on the slave arduino (across the room without connecting wires), then listening for another button press from one of the other slaves in some sort of sequence and within a certain time frame.

Does anyone have any idea about how this might be done, even if it doesn't use the HC05 Bluetooth Module?

Thanks!

title: Using Arduino Mega with multiple HC05 Modules as masters, communicating to multiple HC05 Modules as slaves, each connected to separate Arduino

Answers: 1

body:
Yes, this is possible. According to arduino.cc, the Arduino Mega has 4 hardware serial ports, so you can connect 3 HC-05 modules and still have 1 serial interface left. The Mega is a good choice, when you need this many serial interfaces, so at this point you don't even need `SoftwareSerial`. You will have to configure the HC-05 modules correctly from the master and command them to connect to the correct slave modules.

About `SoftwareSerial`: The serial interfaces mentioned above are "hardware" interfaces, meaning, that the itself microcontroller contains hardware, that does the main part of the receiving/transmitting by itself, without any need for code. The `Serial` library then only adds a bigger buffer for the data, wrapper functions to write to it and reacts to the interrupts, that come from the hardware interface. But since most microcontrollers only have a very limited number of hardware serial interfaces (often only 1 or even none), the `SoftwareSerial` library comes in handy. It emulates the UART protocol (which is a more professional term for the Serial interface from the Arduino world) with software (and some help from interrupts). This means, that you can use it with any pair of pins and you can even define multiple interfaces with it. But it also has drawbacks. For example: Only 1 `SoftwareSerial` interface can listen at once, you cannot use high baudrates, it uses interrupts, that you might need for an application.

---

That said, I don't think, that Bluetooth is the best way to go, if you only want to test a small number of buttons per slave. It is simply too much hassle to configure the modules and establish the connections correctly. Instead you can use 433MHz radio modules. They don't involve such a complex protocol like Bluetooth does, so it's a very simple solution. In the simplest case, you only need transmitters for the slaves and a receiver for the master. Every slave can send a short identifier, if the button was pressed. The master can then receive this data. Of course, if more than one slave sends simultaneously, the data will be garbage. But as long, as this is not a problem, you can keep it that simple.

There are many tutorials on the web, that explain how to use these modules. You can even find libraries, that are ready to use.


body:
I'm using Arduino IDE for ESP32 WROOM board. I am testing the OTA feature with the ESP32httpUpdate library. I am using the example sketch of the library with the name httpUpdate.ino
However, as soon as I change the update url with a string pointer that I declare globally, it is throwing a compile error that String does not name a type. Any ideas?

    /**
     * httpUpdate.ino
     *
     *  Created on: 27.11.2015
     *
     */
    String* FIRMWARE_UPDATE_VERSION = "1000";

    String* updateURL = "XYZ.php";

    #include <Arduino.h>

    #include <WiFi.h>

    #include <HTTPClient.h>
    #include <ESP32httpUpdate.h>

    #define USE_SERIAL Serial

    void setup() {

        USE_SERIAL.begin(115200);
        // USE_SERIAL.setDebugOutput(true);

        USE_SERIAL.println();
        USE_SERIAL.println();
        USE_SERIAL.println();

        for(uint8_t t = 4; t > 0; t--) {
            USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
            USE_SERIAL.flush();
            delay(1000);
        }

        WiFi.begin("SSID", "PASSWORD");

    }

    void loop() {
        // wait for WiFi connection
        Serial.println("Yolo");
        if((WiFi.status() == WL_CONNECTED)) {

            t_httpUpdate_return ret = ESPhttpUpdate.update(updateURL, FIRMWARE_UPDATE_VERSION);

            switch(ret) {
                case HTTP_UPDATE_FAILED:
                    USE_SERIAL.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
                    break;

                case HTTP_UPDATE_NO_UPDATES:
                    USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
                    break;

                case HTTP_UPDATE_OK:
                    USE_SERIAL.println("HTTP_UPDATE_OK");
                    break;
            }
        }
    }

title: String does not name a type

Answers: 1

body: `String` is included by Arduino.h. Before `#include <Arduino.h>` `String` is not defined. Move `#include <Arduino.h>` to the top of the file or remove it. If you remove it, the Arduino builder adds it.


body:
I bought a Logitech Attack3 joystick at a garage sale for a couple of bucks and now I want to use it for something useful, like controlling a car or my small robotic arm. This joystick has 11 buttons and three sliders. I plugged it into a Sparkfun USB shield on top of an Arduino UNO and found some code online to get it up and running. It outputs hex values that tell me the slider values and the states of all the buttons. Where I am having difficulty is that I don't know C++ at all and the event handler and serial output commands are coming from the cpp file. I think that if I can get the output from the cpp file into the main loop in the ino file, I'll be able to do what I want with the data more easily. I plan to use a radio like XBee or Bluetooth to send commands based on the joystick output.

I cut down the code as much as I thought I could get away with. I'm hoping that someone can show me how to organize the code to allow me to do all my logic in the ino file.

Here is the INO file.
<!-- language-all: lang-cpp -->

    #include <usbhid.h>
    #include <hiduniversal.h>
    #include <usbhub.h>
    #include <SPI.h>
    #include "hidjoystickrptparser.h"

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

    void setup() {
      Serial.begin(115200);
      pinMode(7, OUTPUT);
      digitalWrite(7, HIGH);
      if (Usb.Init() == -1)
        Serial.println("OSC did not start.");
      delay(200);
      if (!Hid.SetReportParser(0, &Joy))
        ErrorMessage<uint8_t > (PSTR("SetReportParser"), 1);
    }

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

   and the cpp file

    #include "hidjoystickrptparser.h"

    JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
    joyEvents(evt),
    oldButtons(0) {
            for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++)
                    oldPad[i] = 0xD;
    }

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

            // Checking if there are changes in report since the method was last called
            for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++)
                    if (buf[i] != oldPad[i]) {
                            match = false;
                            break;
                    }

            // Calling Game Pad event handler
            if (!match && joyEvents) {
                    joyEvents->OnGamePadChanged((const GamePadEventData*)buf);
                    for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++) oldPad[i] = buf[i];
            }

            uint16_t buttons = (0x0000 | buf[6]);
            buttons <<= 4;
            buttons |= (buf[5] >> 4);
            uint16_t changes = (buttons ^ oldButtons);

    }

    void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt) {
            Serial.print("Joystick X: ");
            PrintHex<uint8_t > (evt->X, 0x80);
            Serial.print("\tJoystick Y: ");
            PrintHex<uint8_t > (evt->Y, 0x80);
            Serial.print("\tTrim: ");
            PrintHex<uint8_t > (evt->Z1, 0x80);
            Serial.print("\tSW1-8: ");
            PrintHex<uint8_t > (evt->Z2, 0x80);
            Serial.print("  SW9-11: ");
            PrintHex<uint8_t > (evt->Rz, 0x80);
            Serial.println("\t");

and the header file

    #if !defined(__HIDJOYSTICKRPTPARSER_H__)
    #define __HIDJOYSTICKRPTPARSER_H__

    #include <usbhid.h>

    struct GamePadEventData {
            uint8_t X, Y, Z1, Z2, Rz;
    };

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

    #define RPT_GEMEPAD_LEN  5

    class JoystickReportParser : public HIDReportParser {
            JoystickEvents *joyEvents;

            uint8_t oldPad[RPT_GEMEPAD_LEN];
            uint8_t oldHat;
            uint16_t oldButtons;

    public:
            JoystickReportParser(JoystickEvents *evt);

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

    #endif

Here is what the output looks like in the serial monitor

    Joystick X: 80 Joystick Y: 82 Trim: 7A SW1-8: 00  SW9-11: 00
    Joystick X: 7B Joystick Y: 80 Trim: 7A SW1-8: 00  SW9-11: 00
    Joystick X: 7B Joystick Y: 7F Trim: 7A SW1-8: 00  SW9-11: 00
    Joystick X: 7B Joystick Y: 7F Trim: 7A SW1-8: 00  SW9-11: 01
    Joystick X: 7B Joystick Y: 7F Trim: 7A SW1-8: 00  SW9-11: 00

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

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

title: Interfacing Uno to Logitech Attack3 Joystick

Answers: 0


body:
Arduino sells a holder for the UNO board, but without much documentation or detailed specifications, see [this link][1].  Can anyone give the diameter of four small holes, two located on the top edge and one each on the left/right edges?   What size of screw will fit?  They are smaller than M3 / 4-40 apparently.

Also, does anyone know what material is the holder made from?

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

  [1]: https://store.arduino.cc/holder-type-uno
  [2]: https://i.stack.imgur.com/FOuTZ.png

title: Arduino uno holder

Answers: 2

body:
Arduino UNO holes are just over 3mm in diameter. Both 4-40 and M3 bolts will work well, giving you a bit of wiggle room. You will have to file down the width of the bolt head to fit against the 6 pin header near D13.

As far as the holder material, I don't know. I 3D print my own.

body:
** Self answer:

I obtained several of these holders from Arduino starter kits.  They are made from a clear, colorless plastic that seems to have been injection molded.  However, it is hard to tell exactly which plastic, since these does not have any recycle logo!  The image posted in the original question is perhaps a newer version.

The four smaller holes can accept M2.5 screws, I checked.


body:
I'm trying to use an atmega chip from an arduino on a breadboard, with minimal hardware (using the internal 8mhz clock).  I am using the article in the link provided.  When I reach the final step (burning the bootloader), I get an error telling me the device signature is wrong-

Arduino: 1.8.5 (Windows 10), Board: "ATmega328 on a breadboard (8 MHz internal clock)"

avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

Error while burning bootloader.

I am assuming the error is because the chip is from a uno clone, and uses an atmega328p-pu chip.  How am I able to override this check using -F, as described in the error message?  Or is there maybe some other way i can fix this?  Thanks in advance.

https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

title: Burning Arduino Bootloader

Answers: 1

body:
One of the parameters that you have to give avrdude is the microcontroller you are using, and then it checks the signature of the micro to ensuere that everthing is ok. this parameter is passed through -p flag
```
avrdude -p <microcontroller name>
```
For ATmega328 this parameter should be m328 and in your case, with ATmega328p this parameter should be m328p. All options avalible can be checked in man page.


body:
I using the standard example of smoothing:
<!-- language-all: lang-cpp -->

    /*
      Smoothing

      Reads repeatedly from an analog input, calculating a running average and
      printing it to the computer. Keeps ten readings in an array and continually
      averages them.

      The circuit:
      - analog sensor (potentiometer will do) attached to analog input 0

      created 22 Apr 2007
      by David A. Mellis  <dam@mellis.org>
      modified 9 Apr 2012
      by Tom Igoe

      This example code is in the public domain.

      http://www.arduino.cc/en/Tutorial/Smoothing
    */

    // Define the number of samples to keep track of. The higher the number, the
    // more the readings will be smoothed, but the slower the output will respond to
    // the input. Using a constant rather than a normal variable lets us use this
    // value to determine the size of the readings array.
    const int numReadings = 10;

    int readings[numReadings];      // the readings from the analog input
    int readIndex = 0;              // the index of the current reading
    int total = 0;                  // the running total
    int average = 0;                // the average

    int inputPin = A0;

    void setup() {
      // initialize serial communication with computer:
      Serial.begin(9600);
      // initialize all the readings to 0:
      for (int thisReading = 0; thisReading < numReadings; thisReading++) {
        readings[thisReading] = 0;
      }
    }

    void loop() {
      // subtract the last reading:
      total = total - readings[readIndex];
      // read from the sensor:
      readings[readIndex] = analogRead(inputPin);
      // add the reading to the total:
      total = total + readings[readIndex];
      // advance to the next position in the array:
      readIndex = readIndex + 1;

      // if we're at the end of the array...
      if (readIndex >= numReadings) {
        // ...wrap around to the beginning:
        readIndex = 0;
      }

      // calculate the average:
      average = total / numReadings;
      // send it to the computer as ASCII digits
      Serial.println(average);
      delay(1);        // delay in between reads for stability
    }

to calculate power consumption for a load which changes it's value frequently (sometimes it stops and the consumption goes down to couple of watts).

My only modification of the above code is to pass a calculated power (V*I) value to it instead of the analogRead(inputPin);. The input value for the power calculation works fine because without this code I get the exact good values for power. I have also increased the numreadings from 10->100 and probably will needed to be increased a lot more since I need the average for 1 minute.

There are 2 major issues with this code:

1, When a constant load is attached, which let's say draws 500W the value generated by the code is floating around 312W and never reaches 500.

2, When the load is disconnected it and the current power consumption is 1-2watts standby this code jumps to -312W. I could cast it to be an unsigned integer on the first place but that's not really a good solution.

Anyone knows how to fix this?

Thanks

title: Arduino Smoothing does not work as expected

Answers: 1

body: Yes, change the variable type to something that can hold larger numbers, because now adding up 100 measurements will overflow your variable.


body:
I'm working on a program which listens for certain bytes on serial through an if/then/elseif ladder. I want to also check if a pin (say, `A15`) has been given a HIGH state, by another Arduino with shared ground. The slave Arduino will turn a digital pin to HIGH and I want the MEGA2560 to check every time it loops if a HIGH is present from the other board. A "While button not pressed do nothing statement won't work, because that won't let the loop go. I tried doing an if statement, using something to the effect of this:
```C++
if (digitalRead(A15)==HIGH) {
  //things to do
}
```
But it seems no matter what I put, be it `HIGH`, `LOW`, `!= HIGH`, `!= LOW`, etc. or either input pinmodes, pullup or not, it always thinks the board is transmitting HIGH. In fact, it only doesn't think it's HIGH when it actually _is_ HIGH. I'm pretty stumped on this. If you ask me, digitalRead is really odd with what's HIGH and what's LOW.

title: How can I scan for a HIGH signal on digitalRead during the main loop, while running other things?

Answers: 1

body:
Simplify, and show your setup code.

First, do you have a pinMode call in your setup function:

    void setup() {
      pinMode(A15, INPUT_PULLUP);
      Serial.begin(115200);
    }

Then use test code like this:

    void loop() {
       if (digitalRead(A15) == HIGH) {
          Serial.println("Pin A15 is HIGH");
       } else {
          Serial.println("Pin A15 is LOW");
       }
    }

Connect your A15 pin directly to ground with a jumper and run the sketch above. Open the serial monitor and see what is output. It should be LOW. Then disconnect the jumper and check again. It should now be HIGH. Finally, connect the jumper between A15 and +5V and check the output again. It should still show HIGH.

That lets you troubleshoot just the software piece. Once you get that working, connect pin A15 to the remote Arduino's output pin and try again.


body:
Someone could help me?
I want to use dht11 with arduino and esp. Both will read data from dht11
the problem is that simultaneously cannot be done. So the solution will be to set one as a master and the other one as a slave.
the control will be done like so...
another wire from arduino pin->set as output ->esp pin->set as input.
if wire == 1 then dht11 will be read by arduino
if wire == 0 then esp will read dht.
with some delay ofcourse. but the problem is that i dk how to stop the communication between one board and the sensor when the other board will read it. so does it not exist any conflict

title: DHT11 + ESP plus Arduino

Answers: 2

body:
**Disclaimer:**

I've never used an ESP chip based board I know almost nothing about them. I am going to assume that it works, in software terms, like an Arduino, and base my answer on Arduino code. If the esp chip works differently, you'll need to adapt my suggestion.

---

Try something like this:

Connect a GPIO line between the microcontrollers. Also connect that line - through a 10K resistor - to +5V.

Have both microcontrollers set up it's GPIO as an input.

(We'll call the GPIO pin on both microcontrollers the "DHT_available" line. It will be HIGH when the DHT sensor is not being used by the other controller.)

When one of the microcontrollers wants to read the DHT11, have it check the GPIO line. If it's HIGH switch the GPIO line to an output and pull it low, then take a reading. When the reading is complete, switch the GPIO line back to an input.

If the GPIO line is LOW, wait and check again.

---

Alternately you could attach each of the microcontroller's GPIO lines to interrupt handlers on a rising edge. Then have the interrupt handler set the GPIO line to an output, pull it to LOW, and set a flag that means "begin reading".

Have your loop function check the "begin reading" flag, and if true, trigger a read from the DHT, and once it's complete, set the GPIO back to an input.

With the first option, each microcontroller would need to poll the "DHT_available" line continuously until it goes HIGH before beginning reading.

With the second option, as soon as one of your microcontrollers is done taking a reading, it would stop pulling the communications line LOW, the other one's rising edge interrupt would fire, and the other one would immediately begin reading.

body:
Also.. i would see a problem there. Lets say so..
Sensor data.
Gnd.
Vcc
uC 2560
uC Esp
If sensor data is linked to both uC
And  use a line dht_available btween 2560 and esp to handle the uC reading.. then..
If dht_available == HIGH then 2560 read after switch dht line to Low
If dht_available == LOW then esp read after reading dhtline》 HIGH
But the sensor wil continue to send data to both.. regqrding the dhtline is high or low.
I dk how to say to sensor.. if dhtline is LOW stop sending data to 2560 because is esp time to read.


body:
I'm trying to create a motion/fall sensing device. I have a sensor that continuously checks if motion and fall is detected in `void loop()`. If both motion and fall are detected, then I'd like to send an image to my computer. My image capture function is `camCapture()`. The problem is that once the motion and fall detected, it continuously calls `camCapture()` and repeatedly sends images to the computer given that `camCapture()` is called in `void loop()`. I'd like to only send a single image when it is triggered, and a single image every time it is triggered thereafter.
For example, if the motion and fall is triggered, then send an image once. If it detects motion and fall again after it has already gone back to LOW, then send an image again once.

I can't use `setup()` since I can only run a function once, and it defeats the purpose of what I'm trying to do. My `void loop()` code is below.

    void loop()
    {
      // Read data from accelerometer
      mma.read();
      sensors_event_t event;
      mma.getEvent(&event);

      // Store magnitude of all axis
      magnitude = calculateMagnitude(event.acceleration.x, event.acceleration.y, event.acceleration.z);

      // Motion is detected! 20 seconds will be given to detect a fall from the accelerometer
      if(digitalRead(pirSensor) == HIGH)
      {
        num_timeAtPIR = millis(); // Time that PIR sensor was activated with respect to the system time
        bool_waitForAccel = 1; // Set flag to true to wait for accelerometer
        Serial.println("Motion detected!");
        digitalWrite(buzzer, LOW);
        //delay(1000);

      }
      else if(magnitude > sensitivity)
      {
        num_timeAtAccel = millis();
        Serial.println("Fall detected!");
        Serial.print("Magnitude is: ");
        Serial.println(magnitude);
        bool_waitForPIR = 1; // Waiting for PIR
        Serial.println();

        digitalWrite(buzzer, HIGH);
        delay(4000);

      }
      else // No motion is detected
      {
        Serial.println("No motion detected! :(");
        bool_waitForPIR = 0;
        bool_waitForAccel = 0;
        Firebase.setInt(firebaseData, pirPath, 0);
        Firebase.setInt(firebaseData, accelPath, 0);
        digitalWrite(buzzer, LOW);
      }

      // Motion then Fall are detected. Alarm is activated and picture is captured and save onto server.
      if(bool_waitForAccel == 1 && (magnitude > sensitivity))
      {

        Serial.println("Motion and Fall detected!");
        Serial.print("Magnitude is: ");
        Serial.println(magnitude);
        bool_waitForAccel = 0; // No longer waiting for accelerometer
        Serial.println();

        digitalWrite(buzzer, HIGH);
        delay(4000);

        camCapture(); // Take picture!

      }

      // Fall then motion are detected. Alarm is activated and picture/video is captured to save onto website.
      else if(bool_waitForPIR == 1 && (magnitude > sensitivity))
      {
        Serial.println("Fall detected");
        Serial.print("Magnitude is: ");
        Serial.println(magnitude);
        Serial.println();

        bool_waitForPIR = 0; // No longer waiting for PIR

        digitalWrite(buzzer, HIGH);

        delay(4000);

        camCapture(); // Take picture!

      }

      // 20 second timer to check if a Fall is detected after Motion is detected.
      if(millis() > (num_timeAtPIR + period))
      {
        bool_waitForAccel = 0; // Set flag to false
      }
      else if(millis() > (num_timeAtAccel + period)) // 20 second timer to check if Motion is detected after a fall is detected
      {
        bool_waitForPIR = 0;
      }

    }

UPDATE 1: Posting the rest of the code.

    // Program header files
    #include <Wire.h>
    #include <WiFi.h>
    #include <WebServer.h>
    #include <ArduCAM.h>
    #include <SPI.h>
    #include "FS.h"
    #include "FirebaseESP32.h"
    #include "memorysaver.h"
    #include <Adafruit_MMA8451.h>
    #include <Adafruit_Sensor.h>

    //Time and Date NTP Server Header
    #include <NTPClient.h>
    #include <WiFiUdp.h>

    //Define NTP Client to get time
    WiFiUDP ntpUDP;
    NTPClient timeClient(ntpUDP);

    //Variables to save date and time
    String formattedDate = "";
    String dayStamp = "";
    String timeStamp = "";

    String logPath = "/Log";
    String tempPath = "/Log/Temperature";
    String pirPath = "/Log/PIR_Sensor";
    String accelPath = "/Log/Accelerometer";
    String pirDatePath = "/Log/pir_Date";
    String pirTimePath = "/Log/pir_Time";
    String accelDatePath = "/Log/accel_Date";
    String accelTimePath = "/Log/accel_Time";

    // Database/Wi-Fi configuration
    #define FIREBASE_HOST "host"
    #define FIREBASE_AUTH "auth"
    #define AP_SSID "apssid"
    #define AP_PASSWORD "password"

    #define WIFI_SSID "ssid"
    #define WIFI_PASSWORD "passsword"

    // Variables to keep track of previous and current time to create a delay
    unsigned long currentTime = 0;
    unsigned long prevTime = 0;

    unsigned long bool_waitForAccel = 0; // Used to flag the accelerometer
    unsigned long bool_waitForPIR = 0; // Used to flag the PIR
    unsigned long num_timeAtPIR = 0; // Used to keep track of the time the PIR sensor detected motion
    unsigned long num_timeAtAccel = 0; // Used to keep track of the time the accelerometer detected a fall
    unsigned long period = 20000; // Amount of time given to check after motion is detected

    int statusLED = 26; // Choose the pin for status LED
    int buzzer = 12; // Choose the pin for Piezzo Buzzer. Connected from MOSFET gate.
    int tempSensor = 2; // Choose pin for Temperature Sensor
    int pirSensor = 27; // Choose pin for controller PIR Sensor

    int PIR_Power = 25; // Controls Power gate for PIR Sensor
    int ArduCAM_Power = 32; // Controls Power gate for ArduCAM

    const int CS = 5; // GPIO5 as Slave Select for ArduCAM

    int wifiType = 0; // 0: Station    1: AP (Access Point)

    // Set up requests to send captured image to external server
    bool onlineMode = true;
    String start_request = "";
    String boundary = "_cam_";
    String end_request = "\n--" + boundary + "--\n";

    // Set buffer size for camera data
    static const size_t bufferSize = 2048;
    static uint8_t buffer[bufferSize] = {0xFF};
    byte buf[256];
    static int iPic = 0;
    static int kPic = 0;
    uint8_t temp = 0, temp_last = 0;
    uint32_t len = 0;
    bool is_header = false;

    // Threshhold for declaring a fall on the accelerometer
    float sensitivity = 11.0;

    float magnitude = 0.0; // Stores the calculated magnitude

    // Accelerometer, Semaphore, and Firebase instances
    Adafruit_MMA8451 mma = Adafruit_MMA8451();
    FirebaseData firebaseData;

    #if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
    ArduCAM myCAM(OV2640, CS);
    #endif

    WiFiClient client;

    void start_capture()
    {
      myCAM.clear_fifo_flag();
      myCAM.start_capture();
    }

    void camCapture()
    {
      digitalWrite(ArduCAM_Power, HIGH);

      // Flush the FIFO
      myCAM.flush_fifo();
      // Clear capture done flag
      myCAM.clear_fifo_flag();
      // Start capture
      myCAM.start_capture();

      Serial.println("Start capture!");
      while(!myCAM.get_bit(ARDUCHIP_TRIG, CAP_DONE_MASK));

      len = myCAM.read_fifo_length();
      Serial.print("The FIFO length is: ");
      Serial.println(len);

      if(len >= MAX_FIFO_SIZE) // 8M
      {
        Serial.println("Over size!");
      }
      if(len == 0) // 0KB
      {
        Serial.println("Size is 0KB");
        return;
      }

      long full_length;
      if(client.connect("xx.xx.xx.xx", 80) || onlineMode)
      {
        if(onlineMode)
        {
          while(client.available())
          {
            String line = client.readStringUntil('\r');
          }
        }

      start_request = start_request +
      "\n--" + boundary + "\n" +
      "Content-Disposition: form-data; name=\"data\"; filename=\"CAM.jpg\"\n" +
      "Content-Transfer-Encoding: binary\n\n";

      full_length = start_request.length() + len + end_request.length();
      client.println("POST /uploads.php HTTP/1.1");
      client.println("Host: xx.xx.xx.x");
      client.println("Content-Type: multipart/form-data; boundary =" + boundary);
      client.print("Content-Length: "); client.println(full_length);
      client.println();
      client.print(start_request);

      iPic = 0;

      static uint8_t buffer[bufferSize] = {0xFF};

      while (len--)
      {
        temp_last = temp;
        temp =  SPI.transfer(0x00);
        //Read JPEG data from FIFO
        if ( (temp == 0xD9) && (temp_last == 0xFF) ) //If find the end ,break while,
        {
          buf[iPic++] = temp;  //save the last  0XD9
          //Write the remain bytes in the buffer
          myCAM.CS_HIGH();
          client.write(buf, iPic);
          //Close the file
          //file.close();
          Serial.println(F("Image save OK."));
          is_header = false;
          iPic = 0;
        }
        if (is_header == true)
        {
          //Write image data to buffer if not full
          if (iPic < 256)
            buf[iPic++] = temp;
          else
          {
            //Write 256 bytes image data to file
            myCAM.CS_HIGH();
            client.write(buf, 256);
            iPic = 0;
            buf[iPic++] = temp;
            myCAM.CS_LOW();
            myCAM.set_fifo_burst();
          }
        }
        else if ((temp == 0xD8) & (temp_last == 0xFF))
        {
          is_header = true;
          buf[iPic++] = temp_last;
          buf[iPic++] = temp;
        }
      }

      // End the POST request to the server
      client.println(end_request);

      myCAM.CS_HIGH();

      // Stop the client
      client.stop();
      digitalWrite(ArduCAM_Power, LOW);
      }
      else // No connection to the server.
      {
        Serial.println("Could not connect to external server!");
        Serial.println("Please check the IP address or Port");
        return;
      }
    }

    // Calculate the magnitude with the x, y, and z axis of the accelerometer.
    // Gives an overall value that is better than just using the z-axis
    float calculateMagnitude(float x, float y, float z)
    {
      float magnitude = sqrt(sq(x) + sq(y) + sq(z));

      return magnitude;
    }

    void setup()
    {
      Wire.begin();
      Serial.begin(115200);
      SPI.begin();
      SPI.setFrequency(4000000);

      pinMode(CS, OUTPUT);
      pinMode(PIR_Power, OUTPUT); // Set mosfet gate to output for PIR Sensor
      pinMode(ArduCAM_Power, OUTPUT); // Set mosfet gate to output for ArduCAM

      pinMode(statusLED, OUTPUT);      // Declare LED as output
      pinMode(buzzer, OUTPUT);         // Declare Piezo Buzzer as output
      pinMode(pirSensor, INPUT);        // Declare PIR Sensor as input

      Serial.println();

      // Check if accelerometer is properly connected/found
      if(!mma.begin())
      {
        Serial.println("Couldn't start MMA8451 Accelerometer.");
        Serial.println("Check your connections.");
        while(1);
      }
      Serial.println("MMA8451 Accelerometer found!");

      // Set the g-range for the accelerometer. Can be adjusted to 2g, 4g, or 8g.
      mma.setRange(MMA8451_RANGE_2_G);

      // Check if camera is found
      digitalWrite(ArduCAM_Power, HIGH);
      uint8_t vid, pid;
      uint8_t temp;
      while(1)
      {
        //Check if the ArduCAM SPI bus is OK
        myCAM.write_reg(ARDUCHIP_TEST1, 0x55);
        temp = myCAM.read_reg(ARDUCHIP_TEST1);
        if (temp != 0x55) {
          Serial.println(F("SPI interface Error!"));
          delay(2);
          continue;
        }
        else
          break;
      }

      #if defined (OV2640_MINI_2MP) || defined (OV2640_CAM)
      //Check if the camera module type is OV2640
      myCAM.wrSensorReg8_8(0xff, 0x01);
      myCAM.rdSensorReg8_8(OV2640_CHIPID_HIGH, &vid);
      myCAM.rdSensorReg8_8(OV2640_CHIPID_LOW, &pid);
      if ((vid != 0x26 ) && (( pid != 0x41 ) || ( pid != 0x42 )))
        Serial.println(F("Can't find OV2640 module!"));
      else
        Serial.println(F("OV2640 detected."));
      #endif

      //Change to JPEG capture mode and initialize the OV2640 module
      myCAM.set_format(JPEG);
      myCAM.InitCAM();

      myCAM.OV2640_set_JPEG_size(OV2640_640x480);
      myCAM.clear_fifo_flag();
      // Turn off Camera
      digitalWrite(ArduCAM_Power, LOW);

      // Connect to WiFi
      if (wifiType == 0)
      {
        if(!strcmp(WIFI_SSID,"SSID"))
        {
          Serial.println(F("Please set your SSID"));
          while(1);
        }
        if(!strcmp(WIFI_PASSWORD,"PASSWORD"))
        {
          Serial.println(F("Please set your PASSWORD"));
          while(1);
        }
        // Connect to WiFi network
        Serial.println();
        Serial.print(F("Connecting to: "));
        Serial.println(WIFI_SSID);

        WiFi.mode(WIFI_STA);

        WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

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

        Serial.println();
        Serial.println(F("WiFi connected"));
        Serial.println();
        Serial.println(WiFi.localIP());
      }
      else if (wifiType == 1)
      {
        Serial.println();
        Serial.println();
        Serial.print(F("Shared AP: "));
        Serial.println(AP_SSID);
        Serial.print(F("The password is: "));
        Serial.println(AP_PASSWORD);

        WiFi.mode(WIFI_AP);

        WiFi.softAP(AP_SSID, AP_PASSWORD);

        Serial.println();
        Serial.print("AP IP Address is: ");
        Serial.println(WiFi.softAPIP());
      }

      // Initialize a NTPClient to get time
      timeClient.begin();
      timeClient.setTimeOffset(-14400);

      //If Firebase is connected, turn on the LED
      Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
      Firebase.reconnectWiFi(true);
      digitalWrite(statusLED,HIGH);

      Serial.println("------------------------------------");
      Serial.println("Path exist test...");
      if (Firebase.pathExist(firebaseData, logPath))
      {
        Serial.println("Path " + logPath + " exists");
      }
      else
      {
        Serial.println("Path " + logPath + " does not exist");
        Serial.println("Adding all necessary paths to /Log");
        Serial.println("Will have to reinitialize later once everything is set up.");

         // Initialize All  variables to 0;
        Firebase.setFloat(firebaseData, tempPath, 0.0);
        Firebase.setInt(firebaseData, pirPath, 0);
        Firebase.setInt(firebaseData, accelPath, 0);
        //Firebase.setString(firebaseData, pirDatePath, ???);
        //Firebase.setString(firebaseData, pirTimePath, ???);
        //Firebase.setString(firebaseData, accelDatePath, ???);
        //Firebase.setString(firebaseData, accelTimePath, ???);

      }
      Serial.println("------------------------------------");
      Serial.println();

      digitalWrite(PIR_Power, HIGH);

      digitalWrite(pirSensor, LOW);
      digitalWrite(statusLED, LOW);

      Serial.println("Sensors booting up...");
      delay(10000); // Let sensors boot up, 10s
      Serial.println("Sensors ready!");
    }

title: Run function when triggered

Answers: 1

body:
You need to add a state variable to your `loop()` function.

At the start of `loop()` add a variable declaration like:

    void loop()
    {
      static bool capture_sent = false;

Then change your line

      if(bool_waitForAccel == 1 && (magnitude > sensitivity))
      {

to

      if(!capture_sent && bool_waitForAccel == 1 && (magnitude > sensitivity))
      {
        capture_sent = true;

or, if you want to perform some of the logic in that stanza and just not call `camCapture()` then leave the `if` line alone and make the call to `camCapture()` conditional upon `!capture_sent`.

Then in any place in your code where you see the condition which tells you you'd want to call `camCapture()` again when triggered, reset `capture_sent` to `false. I'm leaving it up to you to decide where that goes because you understand what conditions determine that.


body:
Last week I created some code in which I can run a Ublox GPS NEO-6 and a magnetometer HMC5883L together. Which at the time worked brilliantly.
Yesterday I have attempted to run the code again, with the same connections. No modifications to the code.

The GPS NEO-6 works as expected, the magnetometer not so much. After using serial commands as breakpoints, I am able to see that it gets to the line:

    mag.getEvent(&event);

Then I bought two new HMC5883L modules and uploaded the example code, to see if the magnetometer will even run correctly.
The example code returned the basic stats on the breakout board but once again stopped at that line.

Out of curiosity, I removed the magnetometer and ran the program. It displayed exactly the same.
It's not picking up that the HMC5883L is even disconnected.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_HMC5883_U.h>
    /* Assign a unique ID to this sensor at the same time */
    Adafruit_HMC5883_Unified mag = Adafruit_HMC5883_Unified(12345);

    void displaySensorDetails(void)
    {
      sensor_t sensor;
      mag.getSensor(&sensor);
      Serial.println("------------------------------------");
      Serial.print  ("Sensor:       "); Serial.println(sensor.name);
      Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
      Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
      Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" uT");
      Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" uT");
      Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" uT");
      Serial.println("------------------------------------");
      Serial.println("");
      delay(500);
    }

    void setup(void)
    {
      Serial.begin(9600);
      Serial.println("HMC5883 Magnetometer Test"); Serial.println("");

      /* Initialise the sensor */
      if(!mag.begin())
      {
        /* There was a problem detecting the HMC5883 ... check your connections */
        Serial.println("Ooops, no HMC5883 detected ... Check your wiring!");
        while(1);
      }

      /* Display some basic information on this sensor */
      displaySensorDetails();
    }

    void loop(void)
    {
      /* Get a new sensor event */
     sensors_event_t event;
     mag.getEvent(&event);

     /* Display the results (magnetic vector values are in micro-Tesla (uT)) */
     Serial.print("X: "); Serial.print(event.magnetic.x); Serial.print("  ");
     Serial.print("Y: "); Serial.print(event.magnetic.y); Serial.print("  ");
     Serial.print("Z: "); Serial.print(event.magnetic.z); Serial.print("  ");Serial.println("uT");

     // Hold the module so that Z is pointing 'up' and you can measure the heading with x&y
     // Calculate heading when the magnetometer is level, then correct for signs of axis.
     float heading = atan2(event.magnetic.y, event.magnetic.x);

     // Once you have your heading, you must then add your 'Declination Angle', which is the 'Error' of the magnetic field in your location.
     // Find yours here: http://www.magnetic-declination.com/
     // Mine is: -13* 2' W, which is ~13 Degrees, or (which we need) 0.22 radians
     // If you cannot find your Declination, comment out these two lines, your compass will be slightly off.
     float declinationAngle = 0.22;
     heading += declinationAngle;

     // Correct for when signs are reversed.
     if(heading < 0)
       heading += 2*PI;

     // Check for wrap due to addition of declination.
     if(heading > 2*PI)
       heading -= 2*PI;

     // Convert radians to degrees for readability.
     float headingDegrees = heading * 180/M_PI;

     Serial.print("Heading (degrees): "); Serial.println(headingDegrees);

     delay(500);
    }
[![This is the hmc5883l which I use][1]][1]

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

The wires i used are about 20cm long.

title: Code stuck on mag.getEvent(&event); in HMC5833L Compass

Answers: 0


body:
I want my Arduino Micro to interact with my SIM 800 L module. But unfortunately nothing happens, may you can help me figure out where I made a mistake. Here's my wiring:

[![Arudino Board][1]][1]

[![SIM-Module][2]][2]

  [1]: https://i.stack.imgur.com/igKaR.jpg
  [2]: https://i.stack.imgur.com/KeJYv.jpg

Summary of my wiring:

 - *External Battery ---> 800L*
 - plus ---> 5VIN
 - minus ---> GND (both in POWER and UART TTL-Section)

----------

 - *Arduino ---> 800L*
 - RX ---> RXD
 - TX ---> TXD

With that setup I'm using the following code:

    #include <SoftwareSerial.h>
    #include<Arduino.h>

    //Arduino Micro
    //SIM 800l

    SoftwareSerial mySerial(1, 0); // RX, TX

    void setup()
    {
      // Open serial communication
      Serial.begin(9600);

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);

      Serial.println("Setup finished");

    }

    void loop() // run over and over
    {
      Serial.println("Sending AT command");
      mySerial.write("AT"); //OK should be returned
      delay(1000);
      //read sim-module response
      Serial.println("Response: ");
      while( mySerial.available() )
      {
        char c = mySerial.read();
        Serial.print(c);
      }

      mySerial.write("at+cmee=2"); //set sim-module into debug mode

      delay(1000);

      mySerial.write("at+cpin?"); //check if pin is necessary

      //read sim-module response
      while( mySerial.available() )
      {
        char c = mySerial.read();
        Serial.print(c);
      }

    }

But it gives me the following output as a loop:

     Sending AT command
     Response:
     Sending AT command
     Response:
     Sending AT command
     Response:

And I've noticed that a yellow LED is blinking on the Arduino while running the program so I assume there has to be some input from the SIM800 but I can't read the data at the moment. On the 800L-board itself is also an LED that blinks in an interval of about one second, wich tells you that it has no connection (I live in a relatively remote area) but even if there's no connection shouldn't it still return OK when sending AT?

If you need any further information feel free to ask. I would appreciate every idea you come up with :)

Edit: On the photo the wire goes from the Arduino directly to the 800L but I've changed it so the 800L-power comes from a battery now.

title: SIM800l doesn't respond on arduino micro

Answers: 1

body:
Here is some edit in your code

    #include <SoftwareSerial.h>
    #include<Arduino.h>

    //Arduino Micro
    //SIM 800l

    SoftwareSerial mySerial(9,10); // RX, TX

    void setup()
    {
      // Open serial communication
      Serial.begin(9600);

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);

      Serial.println("Setup finished");

    }

    void loop() // run over and over
    {
      Serial.println("Sending AT command");
      mySerial.write("AT\r\n"); //OK should be returned
      delay(1000);
      //read sim-module response
      Serial.println("Response: ");
      while( mySerial.available() )
      {
        String c = mySerial.readString();
        Serial.println(c);
      }

      mySerial.write("at+cmee=2\r\n"); //set sim-module into debug mode

      delay(1000);

      mySerial.write("at+cpin?\r\n"); //check if pin is necessary

      //read sim-module response
      while( mySerial.available() )
      {
        String c = mySerial.readString();
        Serial.println(c);
      }

    }

Change UART pins to 9,10 as 0,1 are already used in normal serial. Secondly change Seria.read() to Serial.readString() because as far as i know the response is string.


body:
Is there a way to post HTTPS body request in Arduino esp8266.
I am able to HTTPS parameter request with WifiClientSecure library,but is not safe compared to Request Body send in POST.

title: ESP8266 HTTPS post body request with WifiClientSecure

Answers: 1

body:
You do it like any other POST. It's just you happen to be using a secure client to make the connection.

1. Open the connection
2. Send the right headers, including a `Content-Type` and `Content-Length` and maybe a `Content-Encoding` if you encode it.
3. Send the body

It's not any different to an unencrypted POST request.


body:
Using a basic 1307 SetTime program, and ran into a problem (first time programming a module).

    #include <Wire.h>
    #include <Time.h>
    #include <DS1307RTC.h>

    const char *monthName[12] = {
      "Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };

    tmElements_t tm;

    void setup() {
      bool parse=false;
      bool config=false;

      // get the date and time the compiler was run
      if (getDate(__DATE__) && getTime(__TIME__)) {
        parse = true;
        // and configure the RTC with this info
        if (RTC.write(tm)) {
          config = true;
        }
      }

      Serial.begin(9600);
      while (!Serial) ; // wait for Arduino Serial Monitor
      delay(200);
      if (parse && config) {
        Serial.print("DS1307 configured Time=");
        Serial.print(__TIME__);
        Serial.print(", Date=");
        Serial.println(__DATE__);
      } else if (parse) {
        Serial.println("DS1307 Communication Error :-{");
        Serial.println("Please check your circuitry");
      } else {
        Serial.print("Could not parse info from the compiler, Time=\"");
        Serial.print(__TIME__);
        Serial.print("\", Date=\"");
        Serial.print(__DATE__);
        Serial.println("\"");
      }
    }

    void loop() {
    }

    bool getTime(const char *str)
    {
      int Hour, Min, Sec;

      if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
      tm.Hour = Hour;
      tm.Minute = Min;
      tm.Second = Sec;
      return true;
    }

    bool getDate(const char *str)
    {
      char Month[12];
      int Day, Year;
      uint8_t monthIndex;

      if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
      for (monthIndex = 0; monthIndex < 12; monthIndex++) {
        if (strcmp(Month, monthName[monthIndex]) == 0) break;
      }
      if (monthIndex >= 12) return false;
      tm.Day = Day;
      tm.Month = monthIndex + 1;
      tm.Year = CalendarYrToTm(Year);
      return true;
    }

And I got the following

    "tmElements_t tm;" does not name a type.

title: Osepp DS1307 RTC program error (tmElements_t tm; does not name a type)

Answers: 1

body:
According to example [ReadTest/ReadTest.ino][1], you have to include

    #include <TimeLib.h>

See also comment from Alexander below (unchecked by me) that Time.h needs to be referenced.

  [1]: https://github.com/PaulStoffregen/DS1307RTC/blob/master/examples/ReadTest/ReadTest.ino


body:
I get a white screen when I perform grapicstest in ili9341. I used the below code:

    #include "SPI.h"
    #include "Adafruit_GFX.h"
    #include "Adafruit_ILI9341.h"

    // For the Adafruit shield, these are the default.
    #define TFT_DC 9
    #define TFT_CS 10

    // Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
    Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
    // If using the breakout, change pins as desired
    //Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);

    void setup() {
      Serial.begin(9600);
      Serial.println("ILI9341 Test!");

      tft.begin();

      // read diagnostics (optional but can help debug problems)
      uint8_t x = tft.readcommand8(ILI9341_RDMODE);
      Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX);
      x = tft.readcommand8(ILI9341_RDMADCTL);
      Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX);
      x = tft.readcommand8(ILI9341_RDPIXFMT);
      Serial.print("Pixel Format: 0x"); Serial.println(x, HEX);
      x = tft.readcommand8(ILI9341_RDIMGFMT);
      Serial.print("Image Format: 0x"); Serial.println(x, HEX);
      x = tft.readcommand8(ILI9341_RDSELFDIAG);
      Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);

      Serial.println(F("Benchmark                Time (microseconds)"));
      delay(10);
      Serial.print(F("Screen fill              "));
      Serial.println(testFillScreen());
      delay(500);

      Serial.print(F("Text                     "));
      Serial.println(testText());
      delay(3000);

      Serial.print(F("Lines                    "));
      Serial.println(testLines(ILI9341_CYAN));
      delay(500);

      Serial.print(F("Horiz/Vert Lines         "));
      Serial.println(testFastLines(ILI9341_RED, ILI9341_BLUE));
      delay(500);

      Serial.print(F("Rectangles (outline)     "));
      Serial.println(testRects(ILI9341_GREEN));
      delay(500);

      Serial.print(F("Rectangles (filled)      "));
      Serial.println(testFilledRects(ILI9341_YELLOW, ILI9341_MAGENTA));
      delay(500);

      Serial.print(F("Circles (filled)         "));
      Serial.println(testFilledCircles(10, ILI9341_MAGENTA));

      Serial.print(F("Circles (outline)        "));
      Serial.println(testCircles(10, ILI9341_WHITE));
      delay(500);

      Serial.print(F("Triangles (outline)      "));
      Serial.println(testTriangles());
      delay(500);

      Serial.print(F("Triangles (filled)       "));
      Serial.println(testFilledTriangles());
      delay(500);

      Serial.print(F("Rounded rects (outline)  "));
      Serial.println(testRoundRects());
      delay(500);

      Serial.print(F("Rounded rects (filled)   "));
      Serial.println(testFilledRoundRects());
      delay(500);

      Serial.println(F("Done!"));

    }

    void loop(void) {
      for(uint8_t rotation=0; rotation<4; rotation++) {
        tft.setRotation(rotation);
        testText();
        delay(1000);
      }
    }

    unsigned long testFillScreen() {
      unsigned long start = micros();
      tft.fillScreen(ILI9341_BLACK);
      yield();
      tft.fillScreen(ILI9341_RED);
      yield();
      tft.fillScreen(ILI9341_GREEN);
      yield();
      tft.fillScreen(ILI9341_BLUE);
      yield();
      tft.fillScreen(ILI9341_BLACK);
      yield();
      return micros() - start;
    }

    unsigned long testText() {
      tft.fillScreen(ILI9341_BLACK);
      unsigned long start = micros();
      tft.setCursor(0, 0);
      tft.setTextColor(ILI9341_WHITE);  tft.setTextSize(1);
      tft.println("Hello World!");
      tft.setTextColor(ILI9341_YELLOW); tft.setTextSize(2);
      tft.println(1234.56);
      tft.setTextColor(ILI9341_RED);    tft.setTextSize(3);
      tft.println(0xDEADBEEF, HEX);
      tft.println();
      tft.setTextColor(ILI9341_GREEN);
      tft.setTextSize(5);
      tft.println("Groop");
      tft.setTextSize(2);
      tft.println("I implore thee,");
      tft.setTextSize(1);
      tft.println("my foonting turlingdromes.");
      tft.println("And hooptiously drangle me");
      tft.println("with crinkly bindlewurdles,");
      tft.println("Or I will rend thee");
      tft.println("in the gobberwarts");
      tft.println("with my blurglecruncheon,");
      tft.println("see if I don't!");
      return micros() - start;
    }

    unsigned long testLines(uint16_t color) {
      unsigned long start, t;
      int           x1, y1, x2, y2,
                    w = tft.width(),
                    h = tft.height();

      tft.fillScreen(ILI9341_BLACK);
      yield();

      x1 = y1 = 0;
      y2    = h - 1;
      start = micros();
      for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
      x2    = w - 1;
      for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
      t     = micros() - start; // fillScreen doesn't count against timing

      yield();
      tft.fillScreen(ILI9341_BLACK);
      yield();

      x1    = w - 1;
      y1    = 0;
      y2    = h - 1;
      start = micros();
      for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
      x2    = 0;
      for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
      t    += micros() - start;

      yield();
      tft.fillScreen(ILI9341_BLACK);
      yield();

      x1    = 0;
      y1    = h - 1;
      y2    = 0;
      start = micros();
      for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
      x2    = w - 1;
      for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
      t    += micros() - start;

      yield();
      tft.fillScreen(ILI9341_BLACK);
      yield();

      x1    = w - 1;
      y1    = h - 1;
      y2    = 0;
      start = micros();
      for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
      x2    = 0;
      for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);

      yield();
      return micros() - start;
    }

    unsigned long testFastLines(uint16_t color1, uint16_t color2) {
      unsigned long start;
      int           x, y, w = tft.width(), h = tft.height();

      tft.fillScreen(ILI9341_BLACK);
      start = micros();
      for(y=0; y<h; y+=5) tft.drawFastHLine(0, y, w, color1);
      for(x=0; x<w; x+=5) tft.drawFastVLine(x, 0, h, color2);

      return micros() - start;
    }

    unsigned long testRects(uint16_t color) {
      unsigned long start;
      int           n, i, i2,
                    cx = tft.width()  / 2,
                    cy = tft.height() / 2;

      tft.fillScreen(ILI9341_BLACK);
      n     = min(tft.width(), tft.height());
      start = micros();
      for(i=2; i<n; i+=6) {
        i2 = i / 2;
        tft.drawRect(cx-i2, cy-i2, i, i, color);
      }

      return micros() - start;
    }

    unsigned long testFilledRects(uint16_t color1, uint16_t color2) {
      unsigned long start, t = 0;
      int           n, i, i2,
                    cx = tft.width()  / 2 - 1,
                    cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      n = min(tft.width(), tft.height());
      for(i=n; i>0; i-=6) {
        i2    = i / 2;
        start = micros();
        tft.fillRect(cx-i2, cy-i2, i, i, color1);
        t    += micros() - start;
        // Outlines are not included in timing results
        tft.drawRect(cx-i2, cy-i2, i, i, color2);
        yield();
      }

      return t;
    }

    unsigned long testFilledCircles(uint8_t radius, uint16_t color) {
      unsigned long start;
      int x, y, w = tft.width(), h = tft.height(), r2 = radius * 2;

      tft.fillScreen(ILI9341_BLACK);
      start = micros();
      for(x=radius; x<w; x+=r2) {
        for(y=radius; y<h; y+=r2) {
          tft.fillCircle(x, y, radius, color);
        }
      }

      return micros() - start;
    }

    unsigned long testCircles(uint8_t radius, uint16_t color) {
      unsigned long start;
      int           x, y, r2 = radius * 2,
                    w = tft.width()  + radius,
                    h = tft.height() + radius;

      // Screen is not cleared for this one -- this is
      // intentional and does not affect the reported time.
      start = micros();
      for(x=0; x<w; x+=r2) {
        for(y=0; y<h; y+=r2) {
          tft.drawCircle(x, y, radius, color);
        }
      }

      return micros() - start;
    }

    unsigned long testTriangles() {
      unsigned long start;
      int           n, i, cx = tft.width()  / 2 - 1,
                          cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      n     = min(cx, cy);
      start = micros();
      for(i=0; i<n; i+=5) {
        tft.drawTriangle(
          cx    , cy - i, // peak
          cx - i, cy + i, // bottom left
          cx + i, cy + i, // bottom right
          tft.color565(i, i, i));
      }

      return micros() - start;
    }

    unsigned long testFilledTriangles() {
      unsigned long start, t = 0;
      int           i, cx = tft.width()  / 2 - 1,
                       cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      start = micros();
      for(i=min(cx,cy); i>10; i-=5) {
        start = micros();
        tft.fillTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
          tft.color565(0, i*10, i*10));
        t += micros() - start;
        tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
          tft.color565(i*10, i*10, 0));
        yield();
      }

      return t;
    }

    unsigned long testRoundRects() {
      unsigned long start;
      int           w, i, i2,
                    cx = tft.width()  / 2 - 1,
                    cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      w     = min(tft.width(), tft.height());
      start = micros();
      for(i=0; i<w; i+=6) {
        i2 = i / 2;
        tft.drawRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(i, 0, 0));
      }

      return micros() - start;
    }

    unsigned long testFilledRoundRects() {
      unsigned long start;
      int           i, i2,
                    cx = tft.width()  / 2 - 1,
                    cy = tft.height() / 2 - 1;

      tft.fillScreen(ILI9341_BLACK);
      start = micros();
      for(i=min(tft.width(), tft.height()); i>20; i-=6) {
        i2 = i / 2;
        tft.fillRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(0, i, 0));
        yield();
      }

      return micros() - start;
    }

title: White screen when I perform grapicstest in ili9341

Answers: 1

body:
Are you sure you have wired everything correctly? In particular:

* In most cases I have seen, the source of the problem was incorrect wiring of MOSI and SCLK. Do not trust the default constructor, better use the constructor that specifies the values of those pins.
* Check that the reset pin on your 9341 board is wired correctly.
* Power the 9341 with 5V; if you feed it 3.3V, the voltage regulator will not be able to supply a high enough voltage for the controller to work correctly.

You also haven't mentioned what you are running this on!


body:
I am developing a code on Arduino and need to implement a condition that if data is available form "serial2" then only get the input for "Serial" terminal of Arduino.

I have tried with below code, but its behavior is when I am sending something from "serial" terminal of arduino, control goes into the loop "serialEvent()" otherwise even if I am sending the data over "serial2" it is not entering in that loop.

Below is my code snippet:

    void serialEvent()
    {
      int DATAaddressMSb, DATAaddressLSb;
      digitalWrite(DIR485, LOW);
      delay(100);
      delay(10);
      while (Serial2.available()>0)
      {
        Serial.println("serial2 data available");
        int i = 0;
        int bufferIn1[9] = { int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00) };
        bufferIn1[i] = Serial2.read();
        Serial.print(bufferIn1[i], DEC);
        Serial.print(" ");
        if(i == 0){Serial.print("BUFFER VAL 0");
        Serial.print( bufferIn1[i], DEC);}
        if(i == 1){Serial.print("BUFFER VAL 1");
        Serial.print( bufferIn1[i], DEC);}
        if(i == 2){Serial.print("BUFFER VAL 2");
        Serial.print( bufferIn1[i], DEC);}
        i++;
      }

      while (Serial.available()&& pos < sizeof my_str - 1) {
        char c = Serial.read();
        if (c == '\n') {            // \n means "end of message"
                my_str[pos] = '\0';     // terminate the buffer
                pos = 0;                // reset to start of buffer
                String str((char*)my_str);    // converte char array in string
                if (str == "PCB-CODE") { Serial.println(SN_CODE); }
                if (str == "FW-VERSION") { Serial.println(FW_ver); }
                if (str == "STOP" ) { TESTcode = 0; IDcode = 999; }
                if (str == "TEST1") { TESTcode = 1; delay(6000); Serial.println("Enter ID "); }
                if (str == "TEST2") { Serial.println("Initialising Board ");  delay(6000); TESTcode = 2; }           // For all tests

                if (str == "ID0") { IDcode = 999; }
                if (str == "ID1") { delay(60); IDcode = 1; }       // Test for FW version
                if (str == "ID2") { IDcode = 2; }       // Test for 3.3V
                if (str == "ID3") { IDcode = 3; }       // Test for Main power
                if (str == "ID4") { delay(50); IDcode = 4; }       // Test for +15V
                if (str == "ID5") { IDcode = 5; }       // Test for +10V
                if (str == "ID6") { IDcode = 6; }       // Test for +8V
                if (str == "ID7") { IDcode = 7; }       // Test for +5.5V
                if (str == "ID8") { IDcode = 8; }       // Test for +1.2V
                if (str == "ID9") { IDcode = 9; }       // Test for +2.5V
                if (str == "ID10") { IDcode = 10; }     // Test for -15V
                if (str == "ID11") { IDcode = 11; }     // Test for POW_LIGHT
                if (str == "ID12") { IDcode = 12; }     // Test for +s_stab
                if (str == "ID13") {delay(50); IDcode = 13; }     // Test for +CELLA
                if (str == "ID14") { IDcode = 14; }     // Test for FPGA_GPIO
                if (str == "ID15") { IDcode = 15; }     // Test for DAC_OUT
                if (str == "ID16") { IDcode = 16; }     // Test for CURRENT_LOOP
                if (str == "ID17") {delay(50); IDcode = 17; }     // Test for Torque signal
                if (str == "ID18") { IDcode = 18; }     // Test for EXT_TRIGGER
                if (str == "ID19") { IDcode = 19; }     // Test for Encoder
                if (str == "ID20") { IDcode = 20; }     // Test for RAM
                if (str == "ID21") { IDcode = 21; }     // Test for SD Card
                if (str == "ID22") { IDcode = 22; }     // Test for Ethernet
                if (str == "ID23") { IDcode = 23; }     // Test for CAN
                if (str == "ID24") { IDcode = 24; }     // Test for I2C
         for( int i = 0; i < sizeof(my_str);  ++i )    // resetta la stringa ricevuta         // reset the received string
              my_str[i] = (char)0;
            }
            else {my_str[pos++] = c;}
      }
     }

Please guide. Thank you........

title: Is it possible to have two serialEvent() in Arduino code?

Answers: 1

body:
According to https://www.arduino.cc/en/Reference/SerialEvent

Arduino Mega handles:

    void serialEvent1(){
    //statements
    }

    void serialEvent2(){
    //statements
    }

    void serialEvent3(){
    //statements
    }

Every other Arduino has only single:

    void serialEvent(){
    //statements
    }


body:
I want to make a direction guide using green, yellow and red LEDs. The lights need to change when ever the active input1 reaches a set value, for example:

 - Green when the value is lower than 12;
 - Yellow when the value is higher than 11 and lower than 20;
 - Red when its higher than 19.

I've been searching for a few days but I couldn't find any references.

---

1 By *active inputs* I mean, a series of buttons being pressed at the same time, if there is 29 buttons then when less then 12 of them is pressed the green light would be turned on.

title: How do I make a counter that counts the amount of active inputs

Answers: 1

body:
You need something like:

    const int BUTTON_MAX = 29;
    const int button[BUTTON_MAX] = { 5, 6, 7, ... };
    const int GREEN_LED = 2;
    const int YELLOW_LED = 3;
    const int RED_LED = 4;
    int current_led;

    void setup()
    {
       // Setup inputs (buttons)
       for (int i = 0; i < BUTTON_MAX; i++) pinMode(button[i], INPUT_PULLUP);

       // Setup outputs (led)
       pinMode(GREEN_LED, OUTPUT);
       pinMode(YELLOW_LED, OUTPUT);
       pinMode(RED_LED, OUTPUT);

       // Initial state
       current_led = GREEN_LED;
       digitalWrite(GREEN_LED, HIGH);
       digitalWrite(YELLOW_LED, LOW);
       digitalWrite(RED_LED, LOW);
    }

    void loop()
    {
       // Count number of active buttons
       int count = 0;
       for (int i = 0; i < BUTTON_MAX; i++) count += digitalRead(button[i]);

       // Map number of active buttons to led
       int new_led;
       if (count < 12)
          new_led = GREEN_LED;
       else if (count < 20)
          new_led = YELLOW_LED;
       else
          new_led = RED_LED;

       // Check for change and update
       if (new_led != current_led) {
          digitalWrite(current_led, LOW);
          digitalWrite(new_led, HIGH);
          current_led = new_led;
       }

       // Add a few milli-seconds for debounce
       delay(20);
    }


body:
I am trying to replicate [Low power LED firefly project][1]. So what I'm trying to do is to do an analog read from a LED, to detect light. To simplify it a bit, I am using different pins and different leds for IN and OUT. The code:

    #define PIN1 don't use this pin! /*this is RESET*/
    #define PIN2 3
    #define PIN3 4
    #define PIN4 don't use this pin! /*this is GND*/
    #define PIN5 0
    #define PIN6 1
    #define PIN7 2
    #define PIN8 don't use this pin! /*this is VCC*/
    #define ANL1 PIN7
    #define ANL2 PIN3
    #define ANL3 PIN2

    // the setup function runs once when you press reset or power the board
    void setup() {
      digitalWrite(PIN3, LOW);
      pinMode(PIN3, INPUT);
    }

    #define BLINK true
    // the loop function runs over and over again forever
    void loop() {

      const int value = analogRead(PIN3);
      if(value>=1023) {
        pinMode(PIN2, OUTPUT);
        digitalWrite(PIN2, HIGH);
        delay(500);
        digitalWrite(PIN2, LOW);
        delay(3);
      }
      else {
        delay(1);
      }
    }

This is the setup. I am using much smaller resistor, but I'm still getting 1023 on analog read, as indicated by the output led always being on:

<!-- 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/8Bt3Y.png)

<!-- End schematic -->

What's wrong?

  [1]: https://www.seanet.com/~karllunt/fireflyLED.html

title: AtTiny analog read always 1023

Answers: 1

body:
In [this article][1] the following steps are used when using an LED as a light detector:

 1. Light up the LED by making the anode positive (logic one) and the
    cathode negative (logic zero) - this fully discharges the LED as a
    capacitor.
 2. Charge up the capacitor by making the anode negative and the cathode
    positive, as this is a small capacitor it will take no time at all
    in other words for as short a time as you can.
 3. Put the diode into the measurement mode, by making the anode
    negative (it already is) and the cathode connected to an analogue
    input.
 4. Make a measurement of the analogue voltage, this is a reference
    level to be used later.
 5. Wait while the photon current is integrated - the longer the more
    sensitive but too long and effects other than photo current
    dominate.
 6. Measure the voltage again and subtract it from the reference value
    you took before the integration time. This figure is your light
    reading.

Looking at the code in the above question it is not apparent where you switch from [forward bias][2] to [revers bias][3].  Also, it does not appear there are two samples taken and the difference between the two samples is found.

  [1]: http://www.thebox.myzen.co.uk/Workshop/LED_Sensing.html
  [2]: https://en.wikipedia.org/wiki/P–n_junction#Forward_bias
  [3]: https://en.wikipedia.org/wiki/P–n_junction#Reverse_bias


body:
I am planning to use the accelerometer of MPU6050 for a project.

I know that before using module (I am using GY-521 MPU6050), one needs to calibrate it.

I am using code by Luis Rodenas for calibration: https://sites.google.com/view/autoaero/code/auto-calibration-mpu6050

This code returns following offsets for my module:

    -1123 -4100 1562 111 8 -1

Offsets are in Ax,Ay,Az,Gx,Gy,Gz format.
I am using these offsets in MPU6050_raw.ino example of i2cdevlib after making necessary adjustments. Here is the sketch

        // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
    // 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
    // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
    //

    // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
    // for both classes must be in the include path of your project
    #include "I2Cdev.h"
    #include "MPU6050.h"

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
    // is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for InvenSense evaluation board)
    // AD0 high = 0x69
    MPU6050 accelgyro;
    //MPU6050 accelgyro(0x69); // <-- use for AD0 high

    int16_t ax, ay, az;
    int16_t gx, gy, gz;

    // uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
    // list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
    // not so easy to parse, and slow(er) over UART.
    #define OUTPUT_READABLE_ACCELGYRO

    // uncomment "OUTPUT_BINARY_ACCELGYRO" to send all 6 axes of data as 16-bit
    // binary, one right after the other. This is very fast (as fast as possible
    // without compression or data loss), and easy to parse, but impossible to read
    // for a human.
    //#define OUTPUT_BINARY_ACCELGYRO

    #define LED_PIN 13
    bool blinkState = false;

    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        // initialize serial communication
        // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
        // it's really up to you depending on your project)
        Serial.begin(115200);

        // initialize device
        Serial.println("Initializing I2C devices...");
        accelgyro.initialize();
        accelgyro.setFullScaleAccelRange(3);
        // verify connection
        Serial.println("Testing device connections...");
        Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

        // use the code below to change accel/gyro offset values

        Serial.println("Updating internal sensor offsets...");
        // -76 -2359 1688 0 0 0
        Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
        Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
        Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
        Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
        Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
        Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
        Serial.print("\n");
        accelgyro.setXGyroOffset(111);
        accelgyro.setYGyroOffset(8);
        accelgyro.setZGyroOffset(-1);
        accelgyro.setZAccelOffset(1562);
        accelgyro.setXAccelOffset(-1123);
        accelgyro.setYAccelOffset(-4100);
        Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
        Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
        Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
        Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
        Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
        Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
        Serial.print("\n");

        // configure Arduino LED pin for output
        pinMode(LED_PIN, OUTPUT);
    }

    void loop() {
        // read raw accel/gyro measurements from device
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

        // these methods (and a few others) are also available
        //accelgyro.getAcceleration(&ax, &ay, &az);
        //accelgyro.getRotation(&gx, &gy, &gz);

        #ifdef OUTPUT_READABLE_ACCELGYRO
            // display tab-separated accel/gyro x/y/z values
            Serial.print("a/g:\t");
            Serial.print(ax); Serial.print("\t");
            Serial.print(ay); Serial.print("\t");
            Serial.print(az); Serial.print("\t");
            Serial.print(gx); Serial.print("\t");
            Serial.print(gy); Serial.print("\t");
            Serial.println(gz);
        #endif

        #ifdef OUTPUT_BINARY_ACCELGYRO
            Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
            Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
            Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
            Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
            Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
            Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }

This is the output at serial monitor when module is horizontal with package letters facing up.
So have I calibrated the accelerometer properly? Please help if you can see any anomaly.
Thanks.

title: How do I know if GY-521 MPU6050 has been calibrated properly?

Answers: 1

body:
consider looking at your acceleration and gyroscope data. if you have the device perfectly flat on the table you will find the gravitational force in some axis. tilt the whole setup and check if the g force now shows up in a different axis (hopefully the one you expect) then rotate the setup by 90 degrees around any axis. (always one at a time please!) if your gyro tells you that your rotational velocity per some measure of time roughly equals pi you know that everything works as expected. this actually works for every accelerometer and gyro so also these that you find on say the sparkfun 9dof board if you should ever come across those.

your cal can be tested by comparing a non cal-ed measurement with a cal-ed one. the differences between the expected value and the measured one should get smaller then.


body:
Is it fine to use L298 N Dual H Bridge Stepper Motor Driver Module to control power of other ICs in a multiple microcontroller setup?

I intend to reduce power consumption in by powering communication ICs through the H bridge to allow switcching them off if not needed. Does a L298 based H bridge module like shown below supply clean stable DC current to someting like the ESP8266?

Module shown below contains condensators, i assume to reduce ripple effect created by L298.

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

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

title: H Bridge for microcontroller power management?

Answers: 1

body:
While it *may* be possible to bend one of those to your proposed usage, it's far from ideal, for a number of reasons:

1. It's far more expensive than the single P-FET that you need to get the job done
2. It's risky: you can easily reverse the current through your components and blow them up
3. It imposes a ground offset which can cause you communication problems.

All you need is a single P-channel MOSFET (assuming you are switching 5V with a 5V logic signal) and a single resistor (10kΩ would be fine, but any large value is ok).

<!-- 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/gGpG7.png)

<!-- End schematic -->

Pull the GPIO LOW and the power switches on. As simple as that.

If you want to switch a higher voltage then simple use an N-channel MOSFET to pull the GPIO line LOW for you - which you then switch with your GPIO signal.


body:
Looks I have a FTDI USB to TTL adapter that doesn't follow the standard Arduino FTDI pinout order. The chipset is FT232RL and here is the link to Amazon page.

https://www.amazon.com/Adapter-Serial-Converter-Development-Projects/dp/B075N82CDL#customerReviews

Please can someone tell me the right pinout to connect this to Arduino Pro Mini 3.3v Thanks!

title: FT232RL Chip pinout to flash Arduino Pro Mini

Answers: 1

body:
This is the standard FTDI Basic connections. CTS is an input to the module and is typically just connected to Gnd as seen on the right side here from the Arduino Promini schematic (so the FT232 is always Clear(ed) To Send, i.e. no flow control is used).

DTR may be broken out on one of the side holes.  RTS may work for you in place of DTR to create the reset pulse to start the bootloader code.  If not,  you may have to cut the trace and wire the RTS header pin to DTR. DTR is pin 2 on the FT232, use a meter and confirm it goes to one of the side holes, that way  you don't  have to try a solder a wire on to a pin.

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

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


body: I am using a Arduino Pro Micro as a keyboard (USB HID device). Each time I press a key, the RX LED and TX LED light up. Can I switch them off in software?

title: Arduino Pro Micro - switch off LEDs

Answers: 2

body:
Kind of.

You would need to edit the `pins_arduino.h` file for the Pro Micro board to change the definitions of the `TXLED0`, `TXLED1`, `RXLED0`, `RXLED1` and `TX_RX_LED_INIT` macros.

You want them to all be defined, but empty.

    #undef TXLED0
    #undef TXLED1
    #undef RXLED0
    #undef RXLED1
    #undef TX_RX_LED_INIT

    #define TXLED0
    #define TXLED1
    #define RXLED0
    #define RXLED1
    #define TX_RX_LED_INIT

That will remove the current definitions, and then create new empty definitions.  Without the empty definitions, you will get errors when compiling.

body:
Kind of.

You don't have to change `pins_arduino.h`.
Try the `LED_BUILTIN_TX` and the `LED_BUILTIN_RX`.
The pins are turned on and off by the code for the SerialUSB port. That can not be changed without changing the Arduino libraries. Setting that pin to INPUT in your sketch in the setup() function will turn them off:

    pinMode(LED_BUILTIN_TX,INPUT);
    pinMode(LED_BUILTIN_RX,INPUT);

If you have troubles with the `LED_BUILTIN_TX` and the `LED_BUILTIN_RX`, then you can use this as well:

    bitClear(DDRD,5);
    bitClear(DDRB,0);

The code for the SerialUSB port still writes to that pin, but once they are set as INPUT, that code will turn on and off the pullup resistor. That is no problem since those leds are connected to VCC.

To turn them on is also possible, but then those pins needs to be OUTPUT and LOW. They will **not** stay on when the SerialUSB port is used.