message:
Conflict between SD card shield and accelerometer

I'm trying to get the SD card (Adafruit microshield SD card) and an MPU6050 accelerometer to work at the same time. When I connect the SD card to the Arduino (without the accelerometer), it's ok; When I connect the accelerometer to the Arduino (without the SD card), it's also ok. The codes for the accelerometer and SD card work fine separately. But when I connect the shield to the Arduino, and then connect the accelerometer, and try to run a combined code, it's problematic. I've included the code I'm currently working on below.  I would really appreciate if you could help me find where the problem lies, and how to solve it.

    #include <SPI.h>
    #include <SD.h>
    #include <Wire.h>
    #include "RTClib.h"
    #include "I2Cdev.h"
    #include "MPU6050_6Axis_MotionApps20.h"
    //#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    //    #include "Wire.h"
    //#endif

    // A simple data logger for the Arduino analog pins

    // how many milliseconds between grabbing data and logging it. 1000 ms is once a second
    #define LOG_INTERVAL  1000 // mills between entries (reduce to take more/faster data)

    // how many milliseconds before writing the logged data permanently to disk
    // set it to the LOG_INTERVAL to write each time (safest)
    // set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
    // the last 10 reads if power is lost but it uses less power and is much faster!
    #define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
    uint32_t syncTime = 0; // time of last sync()

    #define ECHO_TO_SERIAL   1 // echo data to serial port
    #define WAIT_TO_START    0 // Wait for serial input in setup()

    // the digital pins that connect to the LEDs
    #define redLEDpin 4
    #define greenLEDpin 3

    // The analog pins that connect to the sensors
    //(not sure which pins on the accelerometer are the analog pins that connect to the sensor. Insert here!!)

    #define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;
    #define OUTPUT_READABLE_YAWPITCHROLL
    //#define OUTPUT_READABLE_QUATERNION
    //#define OUTPUT_READABLE_EULER
    //#define OUTPUT_READABLE_REALACCEL
    //#define OUTPUT_READABLE_WORLDACCEL

    RTC_DS1307 RTC; // define the Real Time Clock object

    // for the data logging shield, we use digital pin 10 for the SD cs line
    const int chipSelect = HIGH;

    // the logging file
    File logfile;

    void error(char *str)
    {
      Serial.print("error: ");
      Serial.println(str);

      // red LED indicates error
      digitalWrite(redLEDpin, HIGH);

      while(1);
    }

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

      // use debugging LEDs
      pinMode(redLEDpin, OUTPUT);
      pinMode(greenLEDpin, OUTPUT);

    #if WAIT_TO_START
      Serial.println("Type any character to start");
      while (!Serial.available());
    #endif //WAIT_TO_START

      // initialize the SD card
      Serial.print("Initializing SD card...");
      // make sure that the default chip select pin is set to
      // output, even if you don't use it:
      pinMode(10, OUTPUT);

      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
        error("Card failed, or not present");
      }
      Serial.println("card initialized.");

      // create a new file
      char filename[] = "LOGGER00.CSV";
      for (uint8_t i = 0; i < 100; i++) {
        filename[6] = i/10 + '0';
        filename[7] = i + '0';
        if (! SD.exists(filename)) {
          // only open a new file if it doesn't exist
          logfile = SD.open(filename, FILE_WRITE);
          break;  // leave the loop!
        }
      }

      if (! logfile) {
        error("couldnt create file");
      }

      Serial.print("Logging to: ");
      Serial.println(filename);

      // connect to RTC
      Wire.begin();
      if (!RTC.begin()) {
        logfile.println("RTC failed");
    #if ECHO_TO_SERIAL
        Serial.println("RTC failed");
    #endif  //ECHO_TO_SERIAL
      }

      logfile.println("Hello,World,!!!");
    #if ECHO_TO_SERIAL
      Serial.println("Hello,World,!!!");
    #endif //ECHO_TO_SERIAL

      // If you want to set the aref to something other than 5v
      analogReference(EXTERNAL);
    }

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

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

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }
     #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        Serial.begin(9600);
        while (!Serial); // wait for Leonardo enumeration, others continue immediately
     // initialize device
        Serial.println(F("Initializing I2C devices..."));
        mpu.initialize();
        pinMode(INTERRUPT_PIN, INPUT);

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

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

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

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

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

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

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

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

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

    void loop(void){

     if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
            if (mpuInterrupt && fifoCount < packetSize) {
              // try to get out of the infinite loop
              fifoCount = mpu.getFIFOCount();
            }

      DateTime now;

      // delay for the amount of time we want between readings
      delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));

      digitalWrite(greenLEDpin, HIGH);

      // log milliseconds since starting
      uint32_t m = millis();
      logfile.print(m);           // milliseconds since start
      logfile.print(", ");
    #if ECHO_TO_SERIAL
      Serial.print(m);         // milliseconds since start
      Serial.print(", ");
    #endif

      // fetch the time
      now = RTC.now();
      // log time
      logfile.print(now.unixtime()); // seconds since 1/1/1970
      logfile.print(", ");
      logfile.print('"');
      logfile.print(now.year(), DEC);
      logfile.print("/");
      logfile.print(now.month(), DEC);
      logfile.print("/");
      logfile.print(now.day(), DEC);
      logfile.print(" ");
      logfile.print(now.hour(), DEC);
      logfile.print(":");
      logfile.print(now.minute(), DEC);
      logfile.print(":");
      logfile.print(now.second(), DEC);
      logfile.print('"');
    #if ECHO_TO_SERIAL
      Serial.print(now.unixtime()); // seconds since 1/1/1970
      Serial.print(", ");
      Serial.print('"');
      Serial.print(now.year(), DEC);
      Serial.print("/");
      Serial.print(now.month(), DEC);
      Serial.print("/");
      Serial.print(now.day(), DEC);
      Serial.print(" ");
      Serial.print(now.hour(), DEC);
      Serial.print(":");
      Serial.print(now.minute(), DEC);
      Serial.print(":");
      Serial.print(now.second(), DEC);
      Serial.print('"');
    #endif //ECHO_TO_SERIAL

      analogRead(photocellPin);
      delay(10);
      int photocellReading = analogRead(photocellPin);

      analogRead(tempPin);
      delay(10);
      int tempReading = analogRead(tempPin);

      logfile.print(", ");
      logfile.print(photocellReading);
      logfile.print(", ");
      logfile.print(temperatureF);
    #if ECHO_TO_SERIAL
      Serial.print(", ");
      Serial.print(photocellReading);
      Serial.print(", ");
      Serial.print(temperatureF);
    #endif //ECHO_TO_SERIAL

    }

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

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

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

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

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

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

            #ifdef OUTPUT_READABLE_QUATERNION
                // display quaternion values in easy matrix form: w x y z
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                Serial.print("quat\t");
                Serial.print(q.w);
                Serial.print("\t");
                Serial.print(q.x);
                Serial.print("\t");
                Serial.print(q.y);
                Serial.print("\t");
                Serial.println(q.z);
            #endif

            #ifdef OUTPUT_READABLE_EULER
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetEuler(euler, &q);
                Serial.print("euler\t");
                Serial.print(euler[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(euler[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(euler[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                Serial.print("ypr\t");
                Serial.print(ypr[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[2] * 180/M_PI);
            #endif

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

            #ifdef OUTPUT_READABLE_WORLDACCEL
                // display initial world-frame acceleration, adjusted to remove gravity
                // and rotated based on known orientation from quaternion
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
                Serial.print("aworld\t");
                Serial.print(aaWorld.x);
                Serial.print("\t");
                Serial.print(aaWorld.y);
                Serial.print("\t");
                Serial.println(aaWorld.z);
            #endif

      logfile.println();
    #if ECHO_TO_SERIAL
      Serial.println();
    #endif // ECHO_TO_SERIAL

      digitalWrite(greenLEDpin, LOW);

      // Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
      // which uses a bunch of power and takes time
      if ((millis() - syncTime) < SYNC_INTERVAL) return;
      syncTime = millis();

      // blink LED to show we are syncing data to the card & updating FAT!
      digitalWrite(redLEDpin, HIGH);
      logfile.flush();
      digitalWrite(redLEDpin, LOW);

    }

body:
Based on the information that you've provided, it's quite likely that your problem  lies with how your SD card and accelerometer connect via the SPI bus.

The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.  The 'datasheet'/tutorial for the [Micro SD Card Breakout Board][1] (which is the device that I assume you mean when you say *Adafruit microshield SD card*), has the following schematic:

![schematic][2]

Which doesn't appear to include a tri-state buffer.

I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer (in that case, I used a [74HC125][3] 4-channel tri-state buffer) in the MISO line for each of the SPI devices.

<hr>

This page on [Better SPI Bus Design in 3 steps][4] is what finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).

  [1]: https://cdn-learn.adafruit.com/downloads/pdf/adafruit-micro-sd-breakout-board-card-tutorial.pdf
  [2]: https://i.stack.imgur.com/nWaPy.png
  [3]: https://assets.nexperia.com/documents/data-sheet/74HC_HCT125.pdf
  [4]: https://www.dorkbotpdx.org/blog/paul/better_spi_bus_design_in_3_steps


sender: user

message:
How to use -F option while Burn bootloader for ATtiny 85 using Arduino IDE

I'm very new to Arduino. I tried programming Attiny 85 module using Arduino as ISP. It worked fine few times. after that i'm getting below error.

    Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.

I understand that i can override this step using -F option. But really cannot figure out how to use -F option in Arduino IDE. Please Help!

sender: assistant

body:
For what I know there is no easy way to pass custom options to `avrdude` via the Arduino IDE, but [Sloeber][1] (to which I'm a contributor) does.

Beware though, the `-F` [option of `avrdude` command][2] doesn't **solve** the problem, just forces to skip the device signature verification, but if your Attiny is returning such signature something else is wrong and you'll end up with a failed firmware upload anyway.

If the device was working and suddenly stopped it's more than probably a wiring issue, as already suggested in the comments. The second most probable cause, in my experience, would be a hardware issue: you might have accumulated some static charge and then touched the Attiny or any wire connected to it, destroying one of the ISP pins...

My bet is on the former: my experience with the latter is you get changing signatures in the form of `0xFFFF00`, `0x0000FF` and `0xFFFFFF` but, luckily for me, this didn't occur so often to accumulate a true knowledge.

  [1]: https://sloeber.io
  [2]: https://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions


message:
How to / is it possible to change Vendor Name in ESP8266-12E?

I am aware of that it is possible to change hostname for ESP8266 but I want to change vendor name also so that it lists my company/product name in routers/firewalls.

Is it possible?

[![][1]][1]

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

body:
No. The Vendor Name is associated with the OUI.  The OUI is the first three parts of the MAC address.

The OUI's are all registered with IEEE [here](http://standards-oui.ieee.org/oui.txt) and Espressif's entries are:

    18-FE-34   (hex)  Espressif Inc.
    24-0A-C4   (hex)  Espressif Inc.
    24-B2-DE   (hex)  Espressif Inc.
    2C-3A-E8   (hex)  Espressif Inc.
    30-AE-A4   (hex)  Espressif Inc.
    3C-71-BF   (hex)  Espressif Inc.
    54-5A-A6   (hex)  Espressif Inc.
    5C-CF-7F   (hex)  Espressif Inc.
    60-01-94   (hex)  Espressif Inc.
    68-C6-3A   (hex)  Espressif Inc.
    80-7D-3A   (hex)  Espressif Inc.
    84-0D-8E   (hex)  Espressif Inc.
    84-F3-EB   (hex)  Espressif Inc.
    90-97-D5   (hex)  Espressif Inc.
    A0-20-A6   (hex)  Espressif Inc.
    A4-7B-9D   (hex)  Espressif Inc.
    AC-D0-74   (hex)  Espressif Inc.
    B4-E6-2D   (hex)  Espressif Inc.
    BC-DD-C2   (hex)  Espressif Inc.
    C4-4F-33   (hex)  Espressif Inc.
    CC-50-E3   (hex)  Espressif Inc.
    D8-A0-1D   (hex)  Espressif Inc.
    DC-4F-22   (hex)  Espressif Inc.
    EC-FA-BC   (hex)  Espressif Inc.

The ESP8266 does not advertise the vendor. The router / other device maintains a list of OUI to Name mappings (on Linux it's stored in `/usr/share/ieee-data`) and uses them to create a pretty display.

You would need to

* Change the ESP8266's MAC address somehow
* Subscribe to IEEE and pay the relevant fees
* Be allocated an OUI
* Hope that every device in the world that would ever talk to your hardware updates its OUI mappings (which they seldom do).


body: You can change the MAC address in software, using `wifi_set_macaddr()`. Then you have the problem of storing that address in EEPROM and making sure every piece of code that you write for your product knows how to access it. You also need to add a step in your product release process that figures out what to store, and stores it, or you need to burn a different image in each unit that you sell. Plus you need to keep track of all the mac addresses you've ever issued so you don't issue duplicate ones. Plus, as @Majenko said, you would need to register your own OUI, which costs a few thousand dollars. So unless you plan to sell tens of thousand of your units, it's not worth doing.


message:
How to connect ESP8266-01 (AT-commands) to its web server using AJAX

I am just new on using AJAX in web server, I got an error on declaring "server" I am confused about this because I just used only a AT commands to used the ESP8266-01 (wifi-module) I hope you can help me, I want to get the data (distance) to print in the web server(page) in real-time(no refresh). So I used the AJAX for it but this code is still error. Advance thanks on anyhelp :)

     #include "NewPing.h"
     #include <SoftwareSerial.h>
     #define DEBUG true

     SoftwareSerial esp8266(10,11);
     #define TRIGGER_PIN 4
     #define ECHO_PIN 3
     #define MAX_DISTANCE 400

     NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

     void setup() {
     Serial.begin (9600);
     Serial.println("START");
     esp8266.begin(9600);

     server.on("/",WebsiteContent);
     server.on("/xml",XMLcontent);
     server.begin();

     pinMode(TRIGGER_PIN, OUTPUT);
     pinMode(ECHO_PIN, INPUT);

     sendData("AT+RST\r\n",2000,DEBUG);
     sendData("AT+CWMODE=2\r\n",1000,DEBUG);
     sendData("AT+CIFSR\r\n",1000,DEBUG);
     sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
     sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);

    }

    void javascriptContent(){
    Javascript ="\n";

    }
    void WebsiteContent(){
    javascriptContent();

     Website="\n";
     Website+="\n";
     Website+="";
     Website+="
"+data+"
";
     Website+=Javascript;
     server.send(200,"text/html",Website);
     }
     void XMLcontent(){

     XML ="<?xml version='1.0'?>";
     XML+="<data>";
     XML+=data;
     XML+="</data>";

     server.send(200,"text/xml",XML);

     }
     void loop()
     {

     delay(2000);
     digitalWrite(TRIGGER_PIN, LOW);
     delayMicroseconds(2);
     digitalWrite(TRIGGER_PIN, HIGH);
     delayMicroseconds(10);
     digitalWrite(TRIGGER_PIN, LOW);

     long duration,distance;
     duration= pulseIn(ECHO_PIN,HIGH);

     distance = duration/58.2;

     data=(String)distance;
     delay(500);

     server.handleClient();

     if(esp8266.available())
     {
     if(esp8266.find("+IPD,"))
     {
     delay(1000);
     int connectionId = esp8266.read()-48;

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";
     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId;
     closeCommand+="\r\n";
     sendData(closeCommand,3000,DEBUG);

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

body:
You're trying to mix code that is intended to run directly on an ESP8266 using ESP8266-specific libraries on an Arduino.  It can't ever work.

Likes like:

    server.on("/",WebsiteContent);
    server.on("/xml",XMLcontent);
    server.begin();

are for use with the ESP8266's ESP8266WebServer library which doesn't run on an Arduino. To use these kind of constructs you have to program the ESP8266, not the Arduino, and then you don't have the AT commands available.

So, either:

* Do it *all* with AT commands only, or
* Ditch the Arduino and program the ESP8266 directly instead.


message:
Teensy 2.0 usb xinput device

So I came across a [library][1] that lets you turn your TeensyLC/3.X into an xinput device. I only have a 2.0 on hand. I spend the past few hours messing around with the LC example to see if I could hack it over to work on a 2.0 board. Admittedly, it will take much more time analyzing everything before I can make a more educated attempt. I saw [another project][2] that is able to use the 2.0 as xinput devices but the firmware is only available in its hex form.

So I'm wondering what would be the best way to go here... all of the xinput code is in the `/core/teensy3` directory. It has many spidering dependencies which will take a lot of time to go through and try and port(would that even work?). Is there a super "lite" version of the core that lets you fill out device descriptors/handshake/etc? If there is, the xinput just becomes a task of emulating the xinput packets.

Anyway, as this is my first usb input project, any suggestions would be greatly appreciated. Again, I already have the 2.0 and I know its possible so just getting a LC/3.X I'd like to avoid. I'm more just looking for direction on the best way to get started.

  [1]: https://github.com/zlittell/MSF-XINPUT
  [2]: https://github.com/matlo/GIMX/tree/master/loader/firmware

body:
The Teensy 2.0 is a completely different MCU from the 3.0 with very different libraries.

USB on the 32U4 on the 2.0 typically uses the [LUFA library][1] for USB.

So to answer your question: I doubt it will be possible to port code written for the 3.0 SAMD based teensy to the AVR based 2.0 teensy without basically rewriting it from scratch.

The Arduino Leonardo also uses a 32U4 so you might want to look for examples code written for the Leonardo.

The examples from the LUFA library may be useful but they are not designed to be used with the Arduino IDE.

**UPDATE** From the comments, there is this project:
https://github.com/bootsector/XInputPadMicro that uses LUFA and targets the Leonardo.

  [1]: http://www.fourwalledcubicle.com/LUFA.php


message:
Problem sending string with Python to Arduino through serial port

I want to send string 50 to Arduino through serial port, the Arduino UNO seems it communicates with port COM25 but it doesnt receive the string properly:

    import serial # if you have not already done so

    ser = serial.Serial('COM25')
    ser.baudrate = 9600
    ser.write(b'50')
    ser.close()

Btw Arduino code is correct I checked it with other serial com programs. How can I fix the above code?

body:
The AVR Arduinos (Uno, Nano, Mega) have auto-reset function. At opening of USB connection the circuit around USB resets the MCU. After reset the bootloader waits a second for a new upload. If the upload doesn't happen the bootloader starts the current sketch.

The `serial.Serial()` command in python opens the USB connection. With that the Arduino is reset and waits in bootloader while you send the data. The data doesn't arrive in your sketch. Add a two seconds wait time after Python's `serial.Serial()`.


message:
Powering Adafruit motor shield

Making sure not to blow anything up before testing.

I have an adafruit motor shield and an arduino Uno. The arduino uno has a power input and I was hoping to use it to power the motor shield, a nema-17 motor, and an I2C connection. Currently I'm using the power connection on the  motor shield to power the nema-17 motor and a serial connection to power the arduino.

Can I just connect a power supply to the input port on the ardiuno uno and power the motor shield and nema-17 step motor?

body:
You should not power the motor shield (and thus the motor itself) through the Arduino. The motor draws a high current (depending on the exact product - there are many versions of the nema-17 - I found current in the range of 1 - 2A) and the voltage regulator (or the diode in the path) are not rated for this much current (for the Uno the absolute maximum is 200mA, including the Uno itself). You will fry these components, if you try to draw more than the rated current.

But you can use the same power supply and provide the power to Arduino and motor shield in parallel. This way the current for the motor does not have to pass through the Arduino.


message:
Why is the Arduino IDE ignoring my replacement start up code?

I am trying to replace the standard startup code to save flash space.

I've put the new `startup.s` in my `core` directory and added the `-nostartfiles` parameter to the linker reciepe in my `platform.txt`.

When I compile with the IDE, it does not include my start code at all.

When I use Atmel Studio or a makefile, the code assembles and is included just fine.

How can I get the Arduino IDE to use my new start up code?

body:
The Arduino builder is case sensitive and will only see files that end in `.S` and not files that end in `.s`.

Renaming the new start up file to `startup.S` and then deleting the precomplied core archive fixed the problem.

Note that committing this change to git [slightly complicated][1]!

  [1]: https://stackoverflow.com/questions/17683458/how-do-i-commit-case-sensitive-only-filename-changes-in-git


message:
Attaching Microcontroller to DAC evaluation board

For an independent undergraduate research project I'm trying to construct a digital feedback loop. I have never used an Arduino, or done much electrical/computer engineering, so I'm just taking things one thing at a time.
I've been given this
[microcontroller][1]
and this [DAC eval board][2], and now I'm just trying to put them together.

From reading, I need to  attach jumper cables from #16 here to
[![micro-controller schematic][3]][3]
the pins on the Eval Board here,
[![Digital Input Pin Description][4]][4]

but I don't know where to find information on them, so I don't know which to plug into what. Any advice?

  [1]: https://store.digilentinc.com/uc32-arduino-programmable-pic32-microcontroller-board/
  [2]: https://www.analog.com/en/design-center/evaluation-hardware-and-software/evaluation-boards-kits/eval-ad5780.html
  [3]: https://i.stack.imgur.com/bSAai.png
  [4]: https://i.stack.imgur.com/sH411.png

body:
Your DAC uses the SPI protocol.  For that you want to connect it to the SPI header. That's the 6-pin (3x2) header numbered 11 on the uC32.

Connect:

* The uC32's SCK pin to the DAC's SCLK
* The uC32's SDO pin (MOSI) to the DAC's SDIN pin.
* The uC32's SDI pin (MISO) to the DAC's SDO pin.

The other pins (I am not sure what they all do off hand, but the datasheet details them) can connect to any GPIO pins you like (except pins 11-13 which duplicate the SPI header - so you could use those instead if you prefer - 11=MOSI, 12=MISO, 13=SCK).


message:
How to fix "expected ; before ) token" error?

I am in the early stages of writing my program, but I have run into a problem. I am fairly new to Arduino so I'm not sure if there is something I am trying to do that doesn't work, but I am getting an error message

> expected ; before ) token

 on the line `for(count <= 10)`.

I would really appreciate if someone could let me know why I am getting this error.

    #include<EEPROM.h>
    const int LED = 12;
    const int SWITCH = 4;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);

      pinMode(LED, OUTPUT);           //LED is always outputting information
      pinMode(LED_BUILTIN, OUTPUT);   //Built in LED is always outputting information
      pinMode(SWITCH, INPUT_PULLUP);  //Switch inputs value when in/out of ground
    }

    void loop() {
      // put your main code here, to run repeatedly:
      int addr = 0;     //Declaring variables
      int count = 0;
      int seconds;

      if (digitalRead(SWITCH) == LOW) {
    Serial.println("----Recording----");

        for (count <= 10) {
          while (digitalRead(SWITCH) == LOW) {
            count = count + 1;
            digitalWrite(LED, LOW);
            delay(50);
          }
          else {
            count = count + 1;
            digitalWrite(LED, HIGH);
            delay(50);
          }
        } else {
          digitalWrite(LED_BUILTIN, HIGH);        //Internal LED blinks
          delay (300);
          digitalWrite(LED_BUILTIN, LOW);
          delay(300);
        }
      }
    }

body:
Welcome to arduino.stackexchange.
Compiler informs you about the problems with your code. In your case there is a problem with **for** loop.
Remember, the for loop is one of basic concepts in c/c++ (and many others) programming language.
Syntax is:

    for ( init-expression ; cond-expression ; loop-expression )
        statement;
Description of above:

*init-expression*:
Before any other element of the for statement, init-expression is executed only once. Control then passes to cond-expression.

*cond-expression:*
Before execution of each iteration of statement, including the first iteration. statement is executed only if cond-expression evaluates to true (nonzero).

*loop-expression:*
At the end of each iteration of statement. After loop-expression is executed, cond-expression is evaluated.

For example:

    for(int count=0; count<10; count++){
        if (count%2) {
            digitalWrite(LED, LOW);
            }
        else{
            digitalWrite(LED, HIGH);
            }
        }

Add some extra code when needed.

To see more description of for loop see [here][1].

  [1]: https://msdn.microsoft.com/en-us/library/b80153d8.aspx


body:
Also, only 'if' statements have 'else' clauses; loop statements do not. If you didn't get an error for the 'else' at first, it is because the compiler got lost in the for-loop with only one argument.

'while()' statements have a boolean expression inside the parentheses. Each time the boolean evaluates TRUE, the statement or block following the loop executes once, until the loop evaluates FALSE. Regardless of how many times it executes, even zero, the following code will be executed.

'for()' statements have three expressions. Any of the three may be absent but the places for all three must be shown.

 - The first expression is executed once at the beginning of the loop. It typically initializes a loop variable, but may do anything, or be absent.
 - The second expression is a boolean expression that works exactly like the only argument in a 'while()' loop (the loop is only executed if, and for as long as, the expression is TRUE).
 - The third expression is executed after all of the statements in the loop. It typically advances the loop variable, but may do anything.
 - Like the 'while()' loop, whatever follows the 'for()' loop will be executed regardless of whether the loop did anything.

Though any of the 'for()' loop's expressions may be left out, both semi-colons must still be present to make it clear *which* expressions were left out.

Note that 'for(;;)' is an idiom in C that means "forever" - i.e., an infinite loop. Some other construct needs to be executed within the loop to cause it to end, if it not meant to execute perpetually.


message:
D1 Robot... lights up but nothing

I have the Arduino shield described here, I have run the example code compiled to the device, both v1 and 1.1 example, and it shows nothing whatsoever on the screen.

https://www.dfrobot.com/wiki/index.php/Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)

Is there a special trick to initializing this or did I yet again get a lemon that will not display anything?

body:
Like many cheap online shields, this one is a dud, in fact it looks like extended use would fry it if it did work - according to test code this chip is bad.
https://forum.arduino.cc/index.php?topic=96747.0


body: I got one of the D1 Robot version 1 from AllElectronic and I had to adjust the contrast before I could see the words on the display.


message:
Turn on Indicator LED if Moisture Sensor Value >= MaxDryness for longer than 20 min

Hi so I am making a self watering flower pot with a moisture sensor and a peristaltic pump, the code is as follows:

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

I want to add an indicator LED which turns on if the sensor value has been equal to or greater than MaxDryness for longer than twenty minutes.

How would I alter the code to do that?

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

body:
Following is an example how it could be coded.

Remember that the soil is dry by setting `DrySoil = true`.

Register the time at which a dry period starts in DrySoilBegin.

Check at each 'dry' reading whether DrySoil was true for more than 20 minutes.

Set `DrySoil = false` at every 'not dry' reading.

The `ul` after the constant `1200000` makes it an unsigned long value. This because `millis()` returns a `unsigned long` result. I am not 100% sure this is necessary (maybe the compiler takes care of this automatically).

As I don't have a plant watering system I couldn't verify the proper working..

    #define WATERPIN 10
    #define READSOILPIN A0
    #define LEDPIN 13

    // higher number is more dry
    #define MAXDRYNESS 700

    #define WATERDELAY 10000
    #define WATERPOSTDELAY 5000

    bool DrySoil = false; // State of soil
    unsigned long DrySoilBegin; // Time when DrySoil became true

    void setup() {
      Serial.begin(9600);
      pinMode(READSOILPIN, INPUT);
      pinMode(WATERPIN, OUTPUT);
      pinMode(LEDPIN, OUTPUT);
    }

    void loop() {
      int SensorValue = analogRead(READSOILPIN); //take a sample
      Serial.print(SensorValue);
      Serial.print(" ־ ");

      if(SensorValue >= MAXDRYNESS) {
        // Soil is too dry
        // Check if soil was already in a dry state
        if(DrySoil){
          // If already in a dry state check the duration
          if((millis()-DrySoilBegin) > 1200000ul){
            // If duration is longer than 20 minutes switch LED on
            //   or keep LED switched on
            digitalWrite(LEDPIN, HIGH);
          }
        }
        else{
          // First 'dry' result after 'wet' result(s)
          DrySoil = true; // Set DrySoil in true state
          DrySoilBegin = millis(); // Set beginning of DrySoil period
        }
        // start watering for 10 seconds then
        //    wait for 5 seconds before monitoring again
        Serial.println("Soil dry start watering");
        digitalWrite(WATERPIN, HIGH);
        delay(WATERDELAY); // wait until WATERDELAY milliseconds have passed
        digitalWrite(WATERPIN, LOW);
        delay(WATERPOSTDELAY); // wait until WATERPOSTDELAY milliseconds have passed
      }
      else{
        // Soil is not too dry
        DrySoil = false; // Set or keep DrySoil in state false
        digitalWrite(LEDPIN, LOW); // Switch LED off, or keep it switched off
        delay(50); // Wait 50 ms before next sampling
      }
    }


body:
Here's a little example how to do it. Adapt this way(if you want) by yourself.

    // GLOBAL VARIABLES
    unsigned long lowSensorTick = 0;
    bool dry = false;

    void loop()
    {
     if (analogRead(/* PIN */) > /* THRESHOLD VALUE */)
     {
      // DRY
      if (dry == false)
            {
                lowSensorTick = millis();
                dry = true;
            }
            else
      {
       if (millis() - lowSensorTick > 720000) // 720000ms = 12min * 60000ms (1s = 1000ms)
       {
        digitalWrite(LED_PIN, HIGH); // LED GOES HIGH/ON
       }
      }
     }
     else
     {
      // WET
      dry = false;
      digitalWrite(LED_PIN, LOW); // LED GOES LOW/OFF
     }
    }


message:
HTTP request as bytes

I need to send this line of HTTP request as bytes. What is the correct way?

    client.write(byte(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>dsadasdasdas</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>"));

To be more clear this is my C# code for the request

    byte[] data = encoder.GetBytes(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>" + textBox1.Text + "</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");

This is my full C# working code

     ServicePointManager.Expect100Continue = false;
            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] data = encoder.GetBytes(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>" + textBox1.Text + "</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");
            Uri a = new Uri("http://192.168.0.64");
            HttpWebRequest request = WebRequest.Create("http://192.168.0.64/ISAPI/System/Video/inputs/channels/1/overlays") as HttpWebRequest;
            request.Method = "PUT";
            request.Credentials = new NetworkCredential("admin", "12345qwerty");
            request.ContentLength = 888;
            request.ContentType = "application / x - www - form - urlencoded; charset = UTF - 8";
            request.ContentLength = data.Length;
            request.GetRequestStream().Write(data, 0, data.Length);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            response.Close();

This is the Arduino version

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

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = { 192, 168, 0, 177 };
    byte server[] = { 192,168, 0, 64}; // Google
    String big_string="<?xml versiding='rlay>";
    EthernetClient client;

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

      delay(1000);

      Serial.println("connecting...");

      if (client.connect(server, 80)) {
        Serial.println("connected");
        client.println("POST /ISAPI/System/Video/inputs/channels/1/overlays HTTP/1.0");
        client.println("Host: 192.168.0.64");
        client.println("User-Agent: arduino-ethernet");
        client.println("Authorization: Basic YWRtaW46MTIzNDVxd2VydHk=");
       client.println("Content-Type: application / x - www - form - urlencoded; charset = UTF - 8");

        client.println("content-length:888");
        // client.println();
        //client.println(big_string.length());
        client.write(" <? xml version: '1.0' encoding='utf-8'?><VideoOverlay><normalizedScreenSize><normalizedScreenWidth>704</normalizedScreenWidth><normalizedScreenHeight>576</normalizedScreenHeight></normalizedScreenSize><attribute><transparent>false</transparent><flashing>false</flashing></attribute><fontSize>adaptive</fontSize><frontColorMode>auto</frontColorMode><alignment>customize</alignment><TextOverlayList><TextOverlay><id>1</id><enabled>true</enabled><displayText>dsadasdasdas</displayText><positionX>0</positionX><positionY>480</positionY></TextOverlay></TextOverlayList><DateTimeOverlay><enabled>true</enabled><positionY>544</positionY><positionX>0</positionX><dateStyle>MM-DD-YYYY</dateStyle><timeStyle>24hour</timeStyle><displayWeek>true</displayWeek></DateTimeOverlay><channelNameOverlay><enabled>true</enabled><positionY>64</positionY><positionX>16</positionX></channelNameOverlay></VideoOverlay>");

         //client.println();
        //client.print(big_string);
        // client.println();

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

    void loop()
    {
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      if (!client.connected()) {

        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
        for(;;)
          ;
      }
    }

body:
Characters are bytes. ASCII codes of characters are the values. There is no difference between `client.print(str)` and `client.write(str, strlen(str))`. And `client.write(str)` is the same too.

In C# or Java the constant string is of type String. It is an object. You must call a method of the object to get the raw char/byte array. In Arduino a constant string is of type `const char*` a.k.a. `const char[]` which is on low level the same as `const byte*` or `const byte[]`

Equivalent of C#

`byte[] data = encoder.GetBytes("some string");`

for ASCII characters (not UTF) in C is

`byte data[] = "some string";`


message:
Serial Communication between 2 Arduinos for analogRead value

I have an optical sensor connected to A0 on Arduino #1 (Nano) giving me values from 200 to 1010. I need to receive these values in Arduino #2 (Nano) through serial communication. I have used a simple code for sending and receiving bytes, but I don't understand how to get the actual sensor values as int. I found some examples showing single values, but as far as I can understand variable values are more complex.

**Transmitter Code:**
<!-- language-all: lang-cpp -->

    void setup() {
      pinMode(A0, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
    }

**Receiver Code:**

    void setup() {
            Serial.begin(9600);
    }
    void loop() {
            if (Serial.available() > 0) {
            int incomingByte = Serial.read();
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);
            }
    }

body:
You'll want to get familiar with the standard C function sscanf().  It does exactly what you're looking for, converts an ASCII string into whatever type you like.

[sscanf() API ][1]

  [1]: http://www.cplusplus.com/reference/cstdio/sscanf/

The code to read an integer from the serial port would look something like this:

      char recv_buf[10];  int recv_int;
      Serial.readBytesUntil('\n', recv_buf, 9);
      recv_buf[9] = 0;  // make sure it's null terminated
      sscanf(recv_buf, "%d", &recv_int);
      Serial.print("I received: ");
      Serial.println(recv_int);


body:
One byte is 8 bits so 2^8 is equal to 255. One byte can hold value up to 255. Since you have value of 1023(max possible) you have to split value into two bytes.
Here's an example:

    unsigned byte highValueByte(int value)
    {
     return (value >> 8);
    }

    unsigned byte lowValueByte(int value)
    {
     return (value - (highValueByte(value) << 8));
    }

    int giveValue(unsigned byte highByte, unsigned byte lowByte)
    {
        return ((highByte << 0) & 0xFF) + ((lowByte << 8) & 0xFFFF);
    }

    void loop()
    {
     int senValue = analogRead(/* PIN NUMBER */);
     int byteOne = highValueByte(senValue);
     senValue = lowValueByte(senValue);
    }

Your code Works for one byte(try it), but it doesn't for two bytes value. Because you have two bytes, you have to introduce some kind of buffer.
Example:
`unsigned byte buffer[2] = { 0, 0 };`
Also be sure you connected pins properly. RX from Arduino #1 goes into TX from Arduino #2 and vice versa.

[About serial communation sync](https://forum.arduino.cc/index.php?topic=445518.0)


message:
Can I make the BT module disconnect with a BT module and connect with another in the code?

I am working on a project that requires a connection between two BT modules (HC-05) and a mobile phone. Later on, I encountered a problem: I can't connect two BT modules to one at the same time, So I thought about the possibility of ending a connection and starting the other one when needed. If that was possible, how can I do that in an arduino code?

One of the BT modules is a master which means it can't connect to the phone and it has to be a master because it must be connected to the other slave BT module.

body:
Send `AT+ROLE=1` to BT module to set module into master role.
To set module back to slave mode, send `AT+ROLE=0`

Also check [this video](https://www.youtube.com/watch?v=1i-6cz4KHXE), you have source code in the description. It will help you understand how to do it.


message:
What's the function of this transistor on Arduino Mega?

I am trying to get information about the transistor on the Arduino Mega board below:

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

It says "340P" on the transistor. I want be able to know which model transition is this so that I can check its documentation. It also want to know what it is driving or its function on the Arduino board.

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

body:
It's a P-channel MOSFET.  It's job is to act as a "dropless" diode.

The principle is this:

* MOSFETs have a built-in diode across them in reverse bias (an effect of the chemistry)
* The P-channel MOSFET is connected backwards in series with the incoming USB power.
* The internal diode conducts power when there is +5V in to the USB to give power to the board.
* The diode imposes a voltage drop, but there is enough voltage still to run the circuitry.
* An op-amp compares the incoming voltage from the barrel jack (divided by 2) against 3.3V.  If it's less than 3.3V (6.6V incoming) or not there at all, it turns on the P-channel MOSFET
* The MOSFET then short circuits the internal diode removing the voltage drop, giving the full 5V from the USB to the rest of the board.

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

<!-- End schematic -->

Note: diode shown is internal to the MOSFET.

The MOSFET is designated T2 in [the schematic](https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf), and is a FDN340P on the reference design, although the actual model is not that critical, as long as the threshold voltage is above about -3V and it can happily handle 500mA or more.


message:
NRF51822 ± Arduino Uno / ATmegaXXX?

Hello I want to make a simple home automation project and I'd like to use an arduino uno for prototyping and later a atmega for deployment. I need some sort of a mesh communication method. I was thinking about the NRF51822 chip but I can't find any arduino libraries for it.

body:
You can use the NRF51822 as module with AT firmware attached to Arduino. Then you need only the AT commands reference and some examples how to send AT commands and parse the response.

Or you can use the 32-bit ARM cortex-m0 micro-controller inside NRF51822 with [Arduino nrf5 package][1]. It requires a programmer/debugger hardware for sketch upload.

  [1]: https://github.com/sandeepmistry/arduino-nRF5


message:
What components do I need to build Arduino based water pump controller?

I have situation at my home which is causing us a lot of headache. We get drinking water only at midnight and someone has to wake up and switch on electric pump. This electric pump will pump water from water tank present at ground floor to the water tank present on the terrace.

I want to automate this electric pump operation and I have come up with following rules for it:

 1. When water tank at ground floor is almost full then automatically turn on the pump which will push water from ground floor to the tank on the terrace.
 2. When water tank on the terrace is full then switch off motor.

I am a professional software engineer and I have vast experience in Java, Scala, REST API, Big Data and all but I am totally new to Arduino so I do not know which Arduino components I need to build the above mentioned system.

Any guidance will be deeply appreciated.

Thanks,
Chandra

body:
The easiest to build would be to use a real-time clock shield for time-keeping (examples: [make][1] or [buy][2]) and a relay- or solid-state switch shield (popular item - many choices) for switching the pump. A simple wall power supply providing 5volts to run the Arduino completes it. Oh, yes - an Arduino board, too!

  [1]: https://duino4projects.com/an-arduino-real-time-clock-shield/
  [2]: https://www.bananarobotics.com/shop/Velleman-RTC-Shield-for-Arduino


body: If you are controlling an AC pump, you might look into a PowerTail switch, which allows you to control AC power easily and relatively safely, but of course, if you are working with anything around water, be careful!  http://www.powerswitchtail.com/


message:
how to code LED turning signals on smart car

this question is regarding how to add turn led signals on arduino powered smart car. I have 4 leds to give turn indications on my smart car(line follower, obstacle avoider, Bluetooth mobile controlled and also IR remote controlled)

can someone help me to modify the code in such a way that I can add led turn signals?(I'm completely new to arduino)

 want two front leds high at the same time when the car moves forward and when the car moves backward i need two back leds high at the same time.
i also need two right leds high at the same time when it turns right and I need two left leds high at the same time when it turns left .

this is the code

    #include <IRremote.h>
    #include <Servo.h>

    //Pin assignments and global variables per function. Customize if needed
    //*******Pin assignments Motor board and IR receiver********************
    const int MotorRight1 = 7;
    const int MotorRight2 = 8;
    const int MotorLeft1 = 9;
    const int MotorLeft2 = 10;
    const int MotorRightPWM = 6;
    const int MotorLeftPWM = 11;
    const int irReceiverPin = A5;
    const int servoPin = A4; //orange wire
    int iSpeed = 255; //speed, range 0 to 255
    const int LedPin=13;

    //******Infrared key bindings********************************************
    const long IRfront = 16730805;      //go straight: button up
    const long IRback = 16718055;       //go back    : button down
    const long IRturnright = 16734885;  //turn right : button right
    const long IRturnleft = 16716015;   //turn left  : button left
    const long IRstop = 16726215;       //stop       : button OK
    const long IRcny70 = 16754775;      //CNY70 automatic mode: button EQ
    const long IRAutorun = 16750695;    //Ultrasonic mode : button play/pause
    //******Track following pin assignments and signals**********************
    const int SensorLeft = 5;      //
    const int SensorMiddle = 4 ;   //
    const int SensorRight = 3;     //
    IRrecv irrecv(irReceiverPin);  // IRrecv signal
    decode_results infrared;       // decode result
    //*******Ultrasonic pin assignments and signals**************************
    const int echoPin = 12; // ultrasonic receive=echo pin
    const int triggerPin = 13; // ultrasonic send=trigger pin
    Servo myservo; // define myservo
    const int degreesForward = 130; //nr degrees to look forward
    const int degreesLeft = 60; //nr degrees to look left
    const int degreesRight = 180; //nr degrees to look right
    const int delay_time = 250; // servo motor delay
    const int Fgo = 8; // go straight
    const int Rgo = 6; // turn right
    const int Lgo = 4; // turn left
    const int Bgo = 2; // go back
    //*****Bluetooth signals**************************************************
    char val; //stores received character. Needs to be global to perform continuous movement

    //*********General SETUP: activate pins***********************************
    void setup() {
      //start receiving serial infor
      Serial.begin(9600);
      //motor connections
      pinMode(MotorRight1, OUTPUT);  //

      pinMode(MotorRight2, OUTPUT);  //

      pinMode(MotorLeft1,  OUTPUT);  //

      pinMode(MotorLeft2,  OUTPUT);  //
      pinMode(MotorRightPWM, OUTPUT); //enable for right side motor
      pinMode(MotorLeftPWM, OUTPUT); //enable for right side motor
      irrecv.enableIRIn();      // start infrared decode
      myservo.write(degreesForward);       // will make head look in front

      //black track following
      pinMode(SensorLeft, INPUT);
      pinMode(SensorMiddle, INPUT);
      pinMode(SensorRight, INPUT);

      //Ultra sonic
      //digitalWrite(2,HIGH); //what is this pin for?
      pinMode(echoPin, INPUT);
      pinMode(triggerPin, OUTPUT);
      myservo.attach(servoPin);
    }

    //**************Movement functions******************************
    void advance(int d) { //go straight
      digitalWrite(MotorRight1, HIGH);
      digitalWrite(ledrightfrontindicator, HIGH);
      digitalWrite(MotorRight2, LOW);
      digitalWrite(ledrightfrontindicator, LOW);
      digitalWrite(MotorLeft1, HIGH);
      digitalWrite(ledleftfrontindicator, HIGH);
      digitalWrite(MotorLeft2, LOW);
      digitalWrite(ledleftfrontindicator, LOW);
      analogWrite(MotorRightPWM, iSpeed);
      analogWrite(MotorLeftPWM, iSpeed);
      delay(d * 10);
    }
    void right(int d) { //turn right (single wheel)
      digitalWrite(MotorLeft1, LOW);
      digitalWrite(MotorLeft2, HIGH);
      digitalWrite(MotorRight1, LOW);
      digitalWrite(MotorRight2, LOW);
      analogWrite(MotorRightPWM, iSpeed);
      analogWrite(MotorLeftPWM, iSpeed);
      delay(d * 10);
    }
    void left(int d) {//turn left(single wheel)
      digitalWrite(MotorRight1, LOW);
      digitalWrite(MotorRight2, HIGH);
      digitalWrite(MotorLeft1, LOW);
      digitalWrite(MotorLeft2, LOW);
      analogWrite(MotorRightPWM, iSpeed);
      analogWrite(MotorLeftPWM, iSpeed);
      delay(d * 10);
    }
    void turnR(int d) {//turn right (two wheels)
      digitalWrite(MotorRight1, HIGH);
      digitalWrite(MotorRight2, LOW);
      digitalWrite(MotorLeft1, LOW);
      digitalWrite(MotorLeft2, HIGH);
      analogWrite(MotorRightPWM, iSpeed);
      analogWrite(MotorLeftPWM, iSpeed);
      delay(d * 10);
    }
    void turnL(int d) {//turn left (two wheels)
      digitalWrite(MotorRight1, LOW);
      digitalWrite(MotorRight2, HIGH);
      digitalWrite(MotorLeft1, HIGH);
      digitalWrite(MotorLeft2, LOW);
      analogWrite(MotorRightPWM, iSpeed);
      analogWrite(MotorLeftPWM, iSpeed);
      delay(d * 10);
    }
    void stopp(int d) { //stop
      digitalWrite(MotorRight1, LOW);
      digitalWrite(MotorRight2, LOW);
      digitalWrite(MotorLeft1, LOW);
      digitalWrite(MotorLeft2, LOW);
      analogWrite(MotorRightPWM, iSpeed);
      analogWrite(MotorLeftPWM, iSpeed);
      delay(d * 10);
    }
    void back(int d) { //go back
      digitalWrite(MotorRight1, LOW);
      digitalWrite(MotorRight2, HIGH);
      digitalWrite(MotorLeft1, LOW);
      digitalWrite(MotorLeft2, HIGH);
      analogWrite(MotorRightPWM, iSpeed);
      analogWrite(MotorLeftPWM, iSpeed);
      delay(d * 10);
    }

    //************Ultrasonic distance calculator*************************************
    //detect distance for given angles and print char + direction
    float getDistance(int degrees, char dir) {
      myservo.write(degrees);
      digitalWrite(triggerPin, LOW); // ultrasonic echo low level in 2us
      delayMicroseconds(2);
      digitalWrite(triggerPin, HIGH); // ultrasonic echo high level in 10us, at least 10us
      delayMicroseconds(10);
      digitalWrite(triggerPin, LOW); // ultgrasonic echo low level
      float distance = pulseIn(echoPin, HIGH); // read time
      distance = distance / 5.8 / 10; // turn time to distance
      Serial.print(dir); //
      Serial.print(" distance: "); //
      Serial.print(int(distance)); //  output distance (mm)
      Serial.print("\n");
      return distance;
    }
    //*************Ultrasonic direction decision making******************************
    //measurements three angles (front, left, right
    int getDirectionFromdetection() {
      int Fspeedd = 0; // front distance
      int Rspeedd = 0; // right distance
      int Lspeedd = 0; // left distance
      int delay_time = 250; //
      int directionn =0;

      //get front distance
      Fspeedd = getDistance(degreesForward, 'F');

      // if distance is less than 10mm
      if (Fspeedd < 10) {
        stopp(1); //  clear output
        directionn = Bgo;
      }
      // if distance less than 25 mm
      else if (Fspeedd < 25) {
        stopp(1); // clear output
        Lspeedd = getDistance(degreesLeft, 'L'); // detection distance on left side
        delay(delay_time); // waiting for the servo motor to become stable

        Rspeedd = getDistance(degreesRight, 'R'); // detection distance on right side
        delay(delay_time); // waiting for servo motor to be stable

        // if left distance greater than right
        if (Lspeedd > Rspeedd) {
          directionn = Lgo; // go left
        }

        if (Lspeedd <= Rspeedd) {//if left distance less than right
          directionn = Rgo; //go right
        }

        if (Lspeedd < 15 && Rspeedd < 15) { //if distance less 10mm both right and left
          directionn = Bgo; //go back
        }
      }
      else {
        directionn = Fgo; //go straight
      }
      return directionn;
    }

    void autoRunUsingUltraSonic() {
      bool stopPressed;
      int directionn = 0; // front=8, back=2, left=4, right=6
      while (IRAutorun) {
        myservo.write(80); // make the servo motor reset
        directionn = getDirectionFromdetection();
        stopPressed = stopCommandPressed();
        if (stopPressed) {
          break;
        }
        else if (directionn == Fgo) { //go straight
          infrared.value = 0;
          advance(5); //
          Serial.print(" Advance "); //
          Serial.print(" ");
        }
        else if (directionn == Bgo) { //go back
          infrared.value = 0;
          back(8); //
          turnL(3); //
          Serial.print(" Reverse "); //
        }
        else if (directionn == Rgo) { //turn right
          infrared.value = 0;
          back(1);
          turnR(60); //
          Serial.print(" Right "); //
        }
        else if (directionn == Lgo) { //turn left
          infrared.value = 0;
          back(1);
          turnL(60);
          Serial.print(" Left ");
        }
      }
      infrared.value = 0;
    }

    //*************************Bluetooth functionality***********************
    //Bluetooth commands
    void bluetoothCommand() {
      if (Serial.available()) { //check if bluetooth command available
        val = Serial.read();
        Serial.write(val);
      }
      if (val == 'F') { // Forward
        advance(10);
      }
      else if (val == 'S') { // Stop Forward
        stopp(10) ;
        val = Serial.read(); //read value again, otherwise can't continu with infrared
      }
      else if (val == 'B') { // Backwards
        back(10);
      }
      else if (val == 'R') { // Right
        turnL(10);
      }
      else if (val == 'L') { // Left
        turnR(10);
      }
      else if (val == 's') { // Stop, not used though
        stopp(10 ) ;
      }
      else if (int(val) >= 49 && int(val) <= 57) { //set speed
        iSpeed = (int(val)-48)*26;
        Serial.println("Speed set to: " + iSpeed);
      }
      else if (val == 'q') { //set speed
        iSpeed = 255;
        digitalWrite(LedPin,HIGH);
        Serial.println("Speed set to: " + iSpeed);
      }
      else if (val == 'W') {
        digitalWrite(LedPin,HIGH);
      }
      else if (val == 'w') {
        digitalWrite(LedPin,LOW);
      }
    }

    //Check if stop command on remote is pressed (button 5)
    bool stopCommandPressed(){
      bool stopPressed = false;
      if (irrecv.decode(&infrared)) {
        irrecv.resume();
        Serial.println(infrared.value, HEX);
        if (infrared.value == IRstop) {
          stopp(10);
          stopPressed = true;
        }
      }
      return stopPressed;
    }

    void followBlackLine() {
      bool stopPressed;
      int SL;  //sensor left
      int SM;  //sensor middle
      int SR;  //sensor right
      while (IRcny70) {
        SL = digitalRead(SensorLeft);
        SM = digitalRead(SensorMiddle);
        SR = digitalRead(SensorRight);

        if (SM == HIGH) {//middle sensor in black area
          if (SL == LOW & SR == HIGH) {//left sensor in black area, right sensor in white, turn left
            left(0);
          }
          else if (SR == LOW & SL == HIGH) {//left white, right black, run right
            right(0);
          }
          else { // left and right both in white, go straight
            advance(0);
          }
        }
        // middle sensor in white area
        else {
          if (SL == LOW & SR == HIGH) { // left black ,right white, turn left
            left(0);
          }
          else if (SR == LOW & SL == HIGH) {
            right(0);
          }
          else {  //left and right both in white, stop
            stopp(0);
          }
        }
        stopPressed = stopCommandPressed();
        if (stopPressed) {
          break;
        }
      }
      infrared.value = 0;
    }

    //**************************************MAIN LOOP***************************************
    void loop() {
      //bluetooth commands
      bluetoothCommand();
      //************************************normal remote control mode ********
      // decoding success 'receive infrared signal
      if (irrecv.decode(&infrared))  {
        if (infrared.value == IRfront) {
          advance(0); //go straigt
        }
        else if (infrared.value ==  IRback) {
          back(0); //go back
        }
        else if (infrared.value == IRturnright) {
          turnR(0); // go right
        }
        else if (infrared.value == IRturnleft) {
          turnL(0); // go left
        }
        else if (infrared.value == IRstop) {//stop
          stopp(0);
        }
        //********************follow black line********cny70 automatic mode********
        else if (infrared.value == IRcny70) {
          followBlackLine();
        }
        //***********************ultrasonic automatic mode***************************
        else if (infrared.value == IRAutorun ) {
          autoRunUsingUltraSonic();
          myservo.write(degreesForward);       // will make head look in front
        }
        //********************wait a little before continuing**************************
        irrecv.resume();
        delay(300);
      }
      else {
        stopp(0);
      }
    }

body:
Like chrisl suggested, add the led code to the functions advance, back, left, and right

    const int LedFrontRight = 21;//change pin numbers
    const int LedFrontLeft = 22;
    const int LedBackRight = 23;
    const int LedBackLeft = 24;

    // ...

    void setup() {
      // ...
      pinMode(LedFrontRight, OUTPUT);
      pinMode(LedFrontLeft , OUTPUT);
      pinMode(LedBackRight , OUTPUT);
      pinMode(LedBackLeft  , OUTPUT);
    }

    //**************Movement functions******************************
    void advance(int d) { //go straight
      digitalWrite(LedFrontRight, HIGH);
      digitalWrite(LedFrontLeft , HIGH);
      digitalWrite(LedBackRight , LOW);
      digitalWrite(LedBackLeft  , LOW);
      //...
    }
    void right(int d) { //turn right (single wheel)
      digitalWrite(LedFrontRight, HIGH);
      digitalWrite(LedFrontLeft , LOW);
      digitalWrite(LedBackRight , HIGH);
      digitalWrite(LedBackLeft  , LOW);
      //...
    }
    void left(int d) {//turn left(single wheel)
      digitalWrite(LedFrontRight, LOW);
      digitalWrite(LedFrontLeft , HIGH);
      digitalWrite(LedBackRight , LOW);
      digitalWrite(LedBackLeft  , HIGH);
      //...
    }
    void turnR(int d) {//turn right (two wheels)
      digitalWrite(LedFrontRight, HIGH);
      digitalWrite(LedFrontLeft , LOW);
      digitalWrite(LedBackRight , HIGH);
      digitalWrite(LedBackLeft  , LOW);
      //...
    }
    void turnL(int d) {//turn left (two wheels)
      digitalWrite(LedFrontRight, LOW);
      digitalWrite(LedFrontLeft , HIGH);
      digitalWrite(LedBackRight , LOW);
      digitalWrite(LedBackLeft  , HIGH);
      //...
    }
    void stopp(int d) { //stop
      digitalWrite(LedFrontRight, LOW);
      digitalWrite(LedFrontLeft , LOW);
      digitalWrite(LedBackRight , LOW);
      digitalWrite(LedBackLeft  , LOW);
      //...
    }
    void back(int d) { //go back
      digitalWrite(LedFrontRight, LOW);
      digitalWrite(LedFrontLeft , LOW);
      digitalWrite(LedBackRight , HIGH);
      digitalWrite(LedBackLeft  , HIGH);
      //...
    }


message:
Newbie question - Biltong Box Project

I am a newbie to electronics, but I do have experience working with electrical wiring in the UK, so I am comfortable working with 240V reasonably safely. I have also built a camper including all the 12V electrics from scratch. I am fairly technically able, as a building physicist and academic researcher. However, my expertise is in mechanical engineering and physics rather than electronics or electrical engineering.

**The Project**

I am designing a new generation [biltong][1] box. My previous biltong boxes had electrical devices wired individually into plugs and then manually switched.

For those who dont know 'biltong' is the South African equivalent of US jerky. We simply dry the raw beef as opposed to light cooking.

[![enter image description here][2]][2]
*Image 1 - first generation manually switched biltong box*

The first generation boxes worked great - they were a test bed for the physics - airflow/heat and drying rates. However, they lacked finesse and were technologically challenged. So I have set myself the goal of building a new smaller box, laser cut from acrylic and packed with more intelligence.

My inspiration is drawn from [this great project][3]

**Technical details**

The biltong dryer design currently comprises of:

 - 1no 240V AC 60W tubular heater - [this one specifically][4]. I might want to add another in the future.
 - 2no 12V DC 14.4W axial fans - [these ones][5]
 - 1no 12V LED strip light - not yet selected

**What I want to do / Problem Statement**

I would like to have an Arduino based system, to facilitate the following features:

 1. 2no temperature and humidity sensors (one at the inlet at the bottom and one at the outlet at high level)
 2. Touch screen to: 1. display temperature and humidity over time, 2. enable manual control of the heater, fans and LED light, 3. allow me to modify the temperature and humidity setpoints
 3. The ability for the Arduino to control the heater (on/off) and the fans (ideally variable) based on setpoints for temperature and humidity. But also to allow me to operate the heater and fans individually from the touchscreen - on / off / auto for all.

**Please help**

I know all the kit I am trying to control and how I want to do it (conceptually). Now I need some advice on how to make this happen please.

To kick things off I have purchased an Arduino MEGA 2560 board and kit and have experimented with a few small projects. I now want to use this to control the above.

**Questions**

 1. Is my idea sensible and achievable (technically)?
 2. I know that I will need a 240V relay to control the heater. Is this safe and reliable? ** This is my biggest concern. What can you recommend for this - there are so many available on the market.
 3. I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?
 4. Can I control the speed of the proposed 12V fans? And how is this achieved?

Huge thanks in advance.

**First Edit**

My calculated current for the heater is 60W / 240V = 0.25A

Questions:

 1. So for a SSR - [this looks like a good option][6] - what do you think?
 2. [Found a four channel, four route MOSFET][7] - what do you think? Once I have the switching working, i will consider working out the PWM. But switching will be fine for now.
 3. How do I go about designing the circuitry - are there any good online Arduino resources for this?

**Second Edit**

[![enter image description here][8]][8]

Not sure where to go from here!

Also, cannot find MOSFET's in Fritzing.

  [1]: https://en.wikipedia.org/wiki/Biltong
  [2]: https://i.stack.imgur.com/fB1Iy.jpg
  [3]: https://www.youtube.com/watch?v=iv-7xxXpNaA
  [4]: https://www.toolstation.com/shop/Ventilation+&+Heating/d290/Electric+Heaters+&+Dryers/sd3168/Tubular+Heater/p32265
  [5]: https://uk.rs-online.com/web/p/axial-fans/7980824/
  [6]: https://www.ebay.co.uk/itm/5V-1-Channel-Solid-State-Relay-SSR-240V-2A-Module-for-Arduino-Raspberry-Pi/162935613097?epid=6006918314&hash=item25efb826a9:g:ZT0AAOSwX2xaoSbf:rk:3:pf:0
  [7]: https://www.ebay.co.uk/itm/Four-Channel-4-Route-MOSFET-Button-IRF540-V4-0-MOSFET-Switch-Module-Arduino-Pi/292475525555?hash=item4418e659b3:g:jL0AAOSw9iNaoPlf:rk:4:pf:0
  [8]: https://i.stack.imgur.com/TNFm1.png

body:
> Is my idea sensible and achievable (technically)?

Yep, sure is. It's not really much different to a DIY Reflow Toaster Oven.

> I know that I will need a 240V relay to control the heater. Is this safe and reliable? ** This is my biggest concern. What can you recommend for this - there are so many available on the market.

I would suggest an SSR instead of a mechanical relay. Easier to drive, and less electrical noise.

> I think I will also need 3 more additional relays for the 2no fans and LED strip light. Is this the best way to control the 12V fans and LED light?

No. Use MOSFETs for those. You can drive those with PWM to change the speed / brightness.

> Can I control the speed of the proposed 12V fans? And how is this achieved?

Yes - see above.

As far as control goes you may want to investigate PID as your calculation method.


message:
Fail programing a Sonoff Dual with Arduino IDE

1) I have a Sonoff Dual, which I wish to upload a Sketch.

2) Other Sonoff basic devices programed the same way, with succes.
But when uploading  the sketch the ( even the generic `Blink` sketch ) - I do not get any response from the Sonoff device.

3) pins were soldered correctly according [this tutorial][1]

4) Uploading the sketch succeeds, using [FTDI][2] set to 3.3v.

What might be the reason for it ? What can I do more to check it ? my only guess is that something has happened to Sonoff device - but it uploads successfully.

Guy

**Code (edit2)**

        /*
      Blink

      Turns an LED on for one second, then off for one second, repeatedly.

      Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
      it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
      the correct LED pin independent of which board is used.
      If you want to know what pin the on-board LED is connected to on your Arduino
      model, check the Technical Specs of your board at:
      https://www.arduino.cc/en/Main/Products

      modified 8 May 2014
      by Scott Fitzgerald
      modified 2 Sep 2016
      by Arturo Guadalupi
      modified 8 Sep 2016
      by Colby Newman

      This example code is in the public domain.

      http://www.arduino.cc/en/Tutorial/Blink
    */
    #define LED_BUILTIN 12
    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
      Serial.begin(9600);
      delay(2000);
      Serial.println("HELLLLLLO");
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

**Upload**

    Build options changed, rebuilding all
    Sketch uses 251224 bytes (50%) of program storage space. Maximum is 499696 bytes.
    Global variables use 28080 bytes (34%) of dynamic memory, leaving 53840 bytes for local variables. Maximum is 81920 bytes.
    Erasing 0x80000 bytes starting at 0x00000000
    Uploading 255376 bytes from /tmp/arduino_build_214375/Blink.ino.bin to flash at 0x00000000
    ................................................................................ [ 32% ]
    ................................................................................ [ 64% ]
    ................................................................................ [ 96% ]
    ..........                                                                       [ 100% ]

**Addede1: Port Selection:**

[![snapshot from IDE][3]][3]

note: when taken port was not connected ( connects to USB0)

**edit3: erasing using `esptool.py`:**

    guy@desktop:~$ esptool.py --port /dev/ttyUSB0 --chip esp8266 erase_flash
    esptool.py v2.5.0
    Serial port /dev/ttyUSB0
    Connecting....
    Chip is ESP8285
    Features: WiFi, Embedded Flash
    MAC: 60:01:94:ad:bf:34
    Uploading stub...
    Running stub...
    Stub running...
    Erasing flash (this may take a while)...
    Chip erase completed successfully in 2.4s
    Hard resetting via RTS pin...

  [1]: https://github.com/arendst/Sonoff-MQTT-OTA-Arduino/wiki/Compile-and-Upload
  [2]: https://www.aliexpress.com/item/Free-Shipping-FT232RL-FTDI-USB-3-3V-5-5V-to-TTL-Serial-Adapter-Module-forArduin-Mini/32519490747.html?spm=a2g0s.9042311.0.0.27424c4d37Npn5
  [3]: https://i.stack.imgur.com/mHyfc.png

body:
Your code is not good to detect if it  works.

The esp8266 Serial needs some time until it prints. First print after the Serial.begin() isn't printed. I guess the reason is the USB chip.

According to [schematic][1], the LED in Sonoff Dual is on pin 12

  [1]: https://www.itead.cc/wiki/images/6/69/Sonoff_Dual_schematic_1.pdf


message:
Arduino clone woks only with USB - NOT with external power

I have an Arduino UNO ch430 clone. It works with USB power supply, I can upload a Sketch and it works just fine. With external power supply, doesn't work. What do I mean? No LED lights up, *high* pins output  ~ 0V. I'm using that barrel jack plug with 9V (6 x 1,5V batteries). Input voltage is measured OK. The AMS1117 regulator has Vin pin = Vout pin; i mean it gets no input Voltage. On the other hand, the M7F rectifier diode that comes between the jack and the regulator takes all voltage. I don't understan why, given that the anode is at higher voltage than the cathode (+9V). It shouldn't block current flow.
I tried jumping the rectifier and getting the jack +pin directly to the Vin at the regulator: current starts to flow, but apparently so much that the ams1117 heats a lot and really fast. Well i don't know why it suddendly gets so much current, I have absolutely nothing pluged to the board and I couldn't find any stain or damaged spot on it.

I can't figure out what is happening. I hope you can help me, and thanks in advance.

---
This is an exact (i'm pretty sure) schematic of my board.
[Link](http://www.electronoobs.com/images/Arduino/tut_31/arduino_uno_scheamtic_ch340.png)

body:
It sounds like there's some form of short, or the AM1117 regulator is dead. Too much current being drawn by the regulator (as it gets so hot) has caused the diode to blow.

You will need to replace both the regulator and the diode and hope it works - or use a separate external regulator into the 5V pin instead.

Personally, I'd use a switch-mode regulator (UBEC regulators are cheap and easy to get hold of) since it is far more efficient than the LM1117.


message:
Reading values with HC-05 and sending commands at the same time working inconsistently

Not good at coding at all, so I'm at a total loss here.

But I'm doing a project that involves controlling a larger DC voltage through a mosfet.
What I'm doing is I'm using a HC-05 to transmit data between a phone and the Arduino Uno. Seeing the value within a couple of seconds is necessary.

However, sending the mosfet gate a command to open or close up work very inconsistently. Sometimes never and sometimes it takes up to 30 seconds for it to register.

The code here is a short version of the project that I'm working on, but behaves similarly.

    #define mosfet 11
    int state = 0;
    int gate = 0;
    int maxgate = 255;
    int mingate = 0;

    void setup() {
      delay(2000);
      pinMode(mosfet, gate);
      analogWrite(mosfet, 0);   //starts closed
      Serial.begin(9600);
    }

    void loop() {
      while(Serial.available() > 0){
        state = Serial.read();

        for (int y=0; y <= 5; y+=5){
          delay(500);
          Serial.println("testphase 1");
          delay(500);
        }

        for (int y=5; y >= 0; y--){
          delay(250);
          Serial.println("testphase 2");
          delay(250);
        }

        if (state == '0') {
        gate = gate + 1;
        if(gate > maxgate) gate = maxgate;
        analogWrite(mosfet, gate);
        Serial.println(int(gate));Serial.print(", +1");
        state = 0;
        }

      if (state == '1') {
        gate = gate + 10;
        if(gate > maxgate) gate = maxgate;
        analogWrite(mosfet, gate);
        Serial.println(int(gate));Serial.print(", +10");
        state = 0;
        }
    }
    }

When sending 'State == 1', for example it will go through both for loops multiple times and the maybe sometimes do gate + 10. Sometimes the commands goes completely ignored.

I have no idea how I would interrupt a loop to execute the given command and then go back.

body:
Actually got it working myself, but thank you so much for your help @chrisl

Ditched the for loop completely just to try things out and reorganized my code a bit. Surprisingly it started to work well enough.

Basically just moved my measuring stuff outside the while loop*(and now that I think about it, why would it ever be withing the while loop? Literally makes no sense)* and to the end of the whole void loop part, and only polled for state changes within the while loop while the BT connection was active.

Doesn't miss a command as far as I can tell, and the adjustment is within 2 seconds when using my whole code, which is perfect. Also the whole program doesn't just freeze itself while trying to think what happened when the change set was send.

Here's a short version, should somebody bump into this thread in the future.

    void loop() {
       while(Serial.available() > 0){
        state = Serial.read();

      if (state == '0') {stuff happens here,
        }
        }  //End of the while loop.

      sensors.requestTemperatures();
      delay(1000);
      Celcius=sensors.getTempCByIndex(0);
    }


message:
Transient buttons control non-transient behaviour of LEDs

Imagine a system where you have two transient non-exclusive buttons and two LEDs.

When you press button 1, the LED 1 is HIGH and LED 2 is LOW (and stays that way).

When you press button 2, the LED 1 is LOW and LED 2 is HIGH (also stays that way).

Which C++ code allow me, to keep the LED 1 turned on indefinitely (until button 2 is pressed)?

Basically, my problem is, that the buttons are transient and the behaviour of LEDs shouldn't be.

Here is code, that would work for pernament exclusive buttons, but doenst work for transient non-exclusive buttons.

    if (digitalRead(button1) == HIGH)
    {
        led1 = HIGH;
    }
 else
    {
        led2 = LOW;
    }
    if (digitalRead(button2) == HIGH)
    {
        led2 = HIGH;
    }
 else
    {
        led2 = LOW;
    }

body:
Something like this:

    if (digitalRead(button1) == HIGH)
    {
        led1 = HIGH;
        led2 = LOW;
    }
    if (digitalRead(button2) == HIGH)
    {
        led2 = HIGH;
        led1 = LOW;
    }


body:
Don't react to the button by changing the LED; change a state-variable in memory, instead. That saves the information of which button was most recently pressed. Then, each time through your loop, set your LED's according to the contents of that persistent variable. Remember that it will have to be a static variable (global or static local), as an automatic one will disappear and reappear after each exit and re-entry to loop(), and you cannot count on its contents when that happens.

Update:

> How do I prevent overwriting the state variable with different input ?

You don't prevent it - you must over-write it. The purpose of the state variable is to remember which button was last pressed. I had in mind something like the following, where `lastButton` saves the number of the most recent button:

    void setup(){
       pinmode(LED1PIN, OUTPUT);
       pinmode(LED2PIN, OUTPUT);
       pinmode(BUTN1PIN, INPUT_PULLUP);  // you might not want the pullup
       pinmode(BUTN2PIN, INPUT_PULLUP);  //  depending on your wiring.
    }

    void loop(){
       static uint8_t lastButton = 0;

       // Save the number of the last button pressed.
       if (digitalRead(button1) == HIGH)
          lastButton = 1;
       else if (digitalRead(button2) == HIGH)
          lastButton = 2;

       // Set the LEDs according to most recent button
       // Note that at program-start, when no button has
       // been pressed yet, this code leaves both LED's off.
       if (lastButton == 1)
       {
          digitalWrite(LED1PIN, HIGH);
          digitalWrite(LED2PIN, LOW);
       }
       else if(lastButton == 2)
          digitalWrite(LED1PIN, LOW);
          digitalWrite(LED2PIN, HIGH);
       }
    }


message:
how to simplify code

I am as new as new can be to the Arduino world and have been playing around with them.  I have a few "Arduino Uno" boards that I purchased and have successfully loaded sketches to them.  However I am having problems figuring out how to write code in a simple manner.

I am  using a LED strip of [WS2812 LEDs][1] (similar to [this][2]). Here is what I would like to achieve:

I would like to be able to light  "lets say"  LEDs  `1, 3, 5, 7`.  Then light LEDs `2, 4, 6, 8`  or any other combination of "multiple LEDs", by that I mean maybe LEDs `0, 14, 15, 36, 37, 52, 54`.  I am sure you get the idea.

Can I write a single line code to light these LEDs or do I have to write out each line.

Sorry if this is a simplistic question, but I have searched and have not seen anything that may accomplish this, or I just over looked it.

Thanks in advance for your help

  [1]: https://cdn-shop.adafruit.com/datasheets/WS2812.pdf
  [2]: https://www.adafruit.com/product/1138?length=1

body:
I have to say that I do not have any experience with the ws2812 led strip but basically it is used with the Adafruit_Neopixel library where you have the function `pixel_obj.setPixelColor(pixel_number,pixel_obj.Color(R,G,B)`
and the function `pixel_obj.show()`.
Now you basically want to make the code in `void loop()` clean and there is a wide choice of possibilities and techniques to use. The simplest is not to do it, but if you want you can write a library to do it or write a function that takes the number of the pins and light 'em up (all with the same color), like this

`void light_pixel(int pixels[],int Red,int Green,int Blue){
    for(int i=0;i<NUMPIXELS;++i){
        pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
    }
    pixel_obj.show();
}`

This works assuming you have declared pixel_obj in the outermost scope, and you will call the function like this:

    #include <Adafruit_NeoPixel.h>
    #define PIN //Whatever you pin is
    #define NUMPIXELS //Thenumber of the pixels in your strip
    Adafruit_NeoPixel pixel_obj = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
    // You may have to modify the third parameter Rationale: You didn't
    // specified anything about your led strip
    void setup(){
    pixel_obj.begin();
    pinMode(PIN, OUTPUT);
    }
    void light_pixel(int pixels[],int Red, int Green, int Blue){
    for(int i=0;i<NUMPIXELS && pixels[I]!=-1 ;++i){
        pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
    }
    pixel_obj.show();
    }
    void loop(){
    int my_pixels[NUMPIXELS]={1,3,5,7,-1}; // Using -1 as terminator
    // Initialize the array . Disclaimer: this is not optimised and you might use
    // new opearator or better pass the reference of a vector to the function so
    // that you can modify the range of the vector and have a more concise function
    light_pixel(my_pixels,255,255,255);
    delay(1000);
    light_pixel(my_pixels,0,0,0);
    }
Then you can change the number of my_pixels with a smile array assignment
This function is just a sample to get the job done but I'd recommend you to study further the C/C++ programming language in general in order to write better code

Good Luck!


message:
Random characters generated by LCD during serial.read()

I am using the following codes to print characters on LCD display....

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

    #include <LiquidCrystal.h>

    const int rs = 8, en = 9, d0 = 4, d1 = 5, d2 = 6, d3 = 7;
    LiquidCrystal lcd(rs, en, d0, d1, d2, d3);

    void setup() {
      lcd.begin(16, 2);
      Serial.begin(9600);
    }

    void loop() {
      if (Serial.available()) {
        delay(100);
        lcd.clear();
        while (Serial.available() > 0) {
          lcd.write(Serial.read());
        }
      }
    }

but in the end it is generating an unwanted character also..
[![enter image description here][1]][1]

kindly help me with the problem

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

body:
The character to the right of the 'A' on your LCD display does not correspond to any of the built-in character bitmap definitions (either on a EU or Chinese display).  This random pattern is likely one of the 8 programmable character bitmaps supported by the LCD that has not been defined yet (ASCII codes 0 to 7).

So, you're likely sending the LCD a character with a value between 0 and 7.  It's probably a good idea to filter out invalid characters before attempting to display them on your LCD.

Filtering Example:

    char c = Serial.read();
    if ((c >= 32) && (c <= 128))
      lcd.write(c);


message:
How millis() resets itself to 0

Looking at the documentation for the [`millis()`][1] function , it says:

> Returns the number of milliseconds since the Arduino board began
> running the current program. This number will overflow (go back to
> zero), after approximately 50 days.

How's this possible? Is Arduino detecting when `millis()` overflow then resets the value to 0? If so, how does it do it? I just want to know what exactly is going on under the hood with the variable that is being returned by the `millis()` function.

  [1]: https://www.arduino.cc/reference/en/language/functions/time/millis/

body:
It is not an exclusive property of `millis()`. Any counter with a limited number of digits eventually returns to zero. For example, a 4 digit tally counter returns to zeros after `9999`.

Under the hood, the variable for `millis()` is of type `unsigned long`, which is 32 bits on the Arduino. In this case, the 32 bits (binary 0's and 1's) are similar to the digits (0 thru 9) on the tally counter.

The maximum is `11111111 11111111 11111111 11111111`. Once there, `millis()` returns to zero when you add `1`.  The maximum (32 "ones") is `2^32 - 1`, which equals `4294967295` in the decimal number system. The maximum value for the counter is, therefore, 4,294,967,295 milliseconds.   Converted to days you get approximately 49.71 days.

[![tally couter][1]][1]

  [1]: https://images-na.ssl-images-amazon.com/images/I/51QV97B6lPL.jpg


message:
Library Compiler Error - ArduinoJson

I have installed via the Arduino Library Manager a library called ArduinoJson.  It seems to install fine and I have included the library in my sketch using:

    #include "ArduinoJson.h"

But when I compile the sketch I get the following error:

    "C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10807 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\mega" "-IG:\\My Drive\\Personal\\jdeation\\Arduino\\libraries\\HX711-0.1" "-IG:\\My Drive\\Personal\\jdeation\\Arduino\\libraries\\ArduinoJson\\src" "C:\\Users\\jason\\AppData\\Local\\Temp\\arduino_build_7871\\sketch\\counting_machine.ino.cpp" -o nul

    In file included from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/JsonBufferBase.hpp:7:0,

                     from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/DynamicJsonBuffer.hpp:7,

                     from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:9,

                     from G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                     from G:\My Drive\Personal\jdeation\Arduino\counting_machine\counting_machine.ino:32:

    G:\My Drive\Personal\jdeation\Arduino\libraries\ArduinoJson\src/ArduinoJson/Deserialization/JsonParser.hpp:7:29: fatal error: ../JsonBuffer.hpp: No such file or directory

    compilation terminated.

I'm very new to Arduino programming,  can someone point me in the right direction.

Thanks.

body:
Go through the library manager and make sure your version is 5.14.3 and not higher. The higher ones are Beta versions and there has been changes that are not compatible with the previous non-Beta versions.

This is an annoyance because you would think that the latest would be the best. But that is not always the case.


message:
could not convert 'digitalWrite(8u, 1u)' from 'void' to 'bool'

I am trying to make some LED lights to turn on when i flick a switch on my RC crontroller. I will connect the signal wire from RC controller to pin 8. The plan is: if i flick the swich, the LED's (pin 12,11,10,9) will turn on, and if i don't flick the swich the LED's wont turn on. This is a Arduino nano what will be connected on a drone.I found another question [HERE][1], but there was no real answers.
 I get a error that say:

> exit status 1
could not convert 'digitalWrite(8u, 1u)' from 'void' to 'bool'

How can i fix this? Should i write the code another way?

Arduino Code:

        void setup() {

      pinMode(4, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(8, INPUT);

    }

    void loop() {

      if (digitalWrite(8, HIGH));
        digitalWrite(12, HIGH);
        digitalWrite(11, HIGH);
        digitalWrite(10, HIGH);
        digitalWrite(9, HIGH);
      else
        digitalWrite(12, LOW);
        digitalWrite(11, LOW);
        digitalWrite(10, LOW);
        digitalWrite(9, LOW);

      digitalWrite(4,HIGH);
      delay(1500);
      digitalWrite(4,LOW);
    }

  [1]: https://arduino.stackexchange.com/questions/17006/arduino-ide-says-fcould-not-convert-pinmodebuttonsinti-0u-from-void

body:
This line of code is the source of your problem.

>     void loop() {
>
>       if (digitalWrite(8, HIGH));

If expressions expect a boolean (true/false), but if you check [the documentation for `digitalWrite()`](https://www.arduino.cc/reference/en/language/functions/digital-io/digitalwrite/), you’ll see it returns “Nothing” (i.e. `void`).

You need to use [`digitalRead()`](https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/) to check the current state of the pin.


body:
You should be using `digitalRead(8)` instead of `digitalWrite(8, HIGH)`. Your sketch is also missing some curly brackets.

    void setup(){
      pinMode(4, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(8, INPUT);
    }

    void loop(){
      if(digitalRead(8) == HIGH){
        digitalWrite(12, HIGH);
        digitalWrite(11, HIGH);
        digitalWrite(10, HIGH);
        digitalWrite(9, HIGH);
      }
      else{
        digitalWrite(12, LOW);
        digitalWrite(11, LOW);
        digitalWrite(10, LOW);
        digitalWrite(9, LOW);
      }
      digitalWrite(4,HIGH);
      delay(1500);
      digitalWrite(4,LOW);
    }

The use of `delay()` will block the sketch from doing anything else, and should be replaced with a `millis()` timer. Have a look at the `BlinkWithoutDelay` example in the IDE.