message:
How to send float numbers from python3 with struct to arduino

I have searched several questions and through google but could not find a solution. I am simply trying to send a float number from python3 with struct to arduino or if there is any other ways other than processing a char array at the arduino side because it is very slow in my opinion..

My arduino code:

    void setup() {
      // initialize the serial communication:
      Serial.begin(9600);
    }

    void loop() {

      unsigned long t = millis();
      float x = analogRead(A3);
      float y = analogRead(A2);
      float c = Serial.read();
      Serial.println(c);
      //Serial.print(t/1000.0);
      //Serial.print(" , ");
      //Serial.print(x);
      //Serial.print(" , ");
      //Serial.println(y);

      // wait a bit for the analog-to-digital converter to stabilize after the last
      // reading:
      //delayMicroseconds(200);
      //delay(2);
      delay(250);
    }

My python3 code :

    import serial

    import struct

    arduino = serial.Serial('/dev/ttyACM0', 9600)
    data = arduino.write(struct.pack('f', 111.32))
    while True:
    #    arduino.write(b"123")
        data = arduino.write(struct.pack('f', 111.32))

Getting the serial output as :

    163.00
    222.00
    66.00
    215.00
    163.00
    222.00
    66.00
    215.00
    163.00
    222.00
    66.00
    215.00
    163.00

How can i solve my problem ?

EDIT : I changed the arduino code according to the answer the new arduino code is

    float f;
    void setup(){
      Serial.begin(9600);
    }

    void loop(){
      while(Serial.available() >= 3){

        f = Serial.read() << 24;
        f = ((unsigned long) f) | (Serial.read() << 16);
        f = ((unsigned long) f) | (Serial.read() << 8);
        f = ((unsigned long) f) | Serial.read();
        Serial.println(f);
      }
      Serial.println(f);
    }

However, the output is now as such:

    ovf
    ovf
    ovf
    ovf
    ovf
    ovf
    ovf
    4294941184.00
    4294941184.00
    4294941184.00
    4294941184.00
    4294941184.00
    4294941184.00
    4294941184.00

body:
There is no way around dealing with serial bytewise, since the communication over serial relies on bytes as a unit. You can write the received bytes directly to the float variable. That is faster, than save them to a char array first:

    float f = Serial.read() << 24;
    f = ((unsigned long) f) | (Serial.read() << 16);
    f = ((unsigned long) f) | (Serial.read() << 8);
    f = ((unsigned long) f) | Serial.read();

With this the bytes of the float value have to be send with the order from most significant to least significant. I don't know, how the data is formatted, if you send a struct over python. The casting to `unsigned long` is important here to do the bitwise OR (`unsigned long` and `float` have both 4 bytes). (I tried it and it works for me)

Also be aware, that you shouldn't read from Serial, when there is no received byte in the buffer. You can check this with `Serial.available()`. If there is no new byte in the buffer the `Serial.read()` function returns an integer with value `-1`

EDIT:
The code above works, if you transmit the data directly as byte. In your comment you wrote, that you want to write `arduino.write(b"111.32")` in python. Here you are transmitting an ASCII string representation of the float number `111.32`. This is not as fast as transmitting byte data (since you may need way more bytes for one float than 4). In this case you can use either `Serial.parseFloat()` to get the float from the serial buffer (but ensure, that all bytes for this number have been received with `Serial.available()`) or you can save the bytes to a string and using `String.toFloat()` to get the float out of it.

Since you wanted to do it the fast way, you should transmit the numbers as byte data. To do this in python, have a look at the answer of [this question][1]. It explains the python code for it (be sure, that you get the ordering of the bytes the same in python and Arduino).

  [1]: https://arduino.stackexchange.com/questions/3753/how-to-send-numbers-to-arduino-uno-via-python-3-and-the-module-serial


sender: user

sender: assistant

body:
I found a better way dealing with the conversion from char to float (note that you yourself have to add the `setup()` function for initiating Serial):

    float f;
    byte *fdata = (byte *) &f;
    int num = 0;

    void loop()
    {
      if(Serial.available()){
        char c = Serial.read();
        if(c == 'B'){
          fdata[3] = c;
          num = 1;
        } else if(num == 1){
          fdata[2] = c;
          num++;
        } else if(num == 2){
          fdata[1] = c;
          num++;
        } else if(num == 3){
          fdata[0] = c;
          num = 0;
          Serial.write(fdata, 4);
          Serial.println(f);
        }
      }
    }

First we are defining our float variable `f` and then a pointer of type `byte` named `fdata`. We are setting this pointer to point to our float variable. Now you can treat this pointer as an array. Since the type of the pointer is `byte`, we can access the first byte of `f` with typing `fdata[0]`. The other bytes can be accessed through `fdata[1]`, `fdata[2]` and `fdata[3]`.

In the loop example we are checking, if there is any byte in the buffer and read it. If it is the value of the character 'B' (which I used as a trigger, that your float starts, since the float number `111.32` starts with this value) we copy it to the last (most significant) byte of the array (aka float variable `f`). One after another we are doing the same with the other bytes.

When we received the last of the 4 bytes, we write the value back to Serial, once as pure byte data and once as ASCII encoded string.

In Python you can use the code, you already used:

<!-- language: lang-py -->

    arduino.write(struct.pack('>f',111.32))

You can read the output of the above sketch back with

<!-- language: lang-py -->

    arduino.readline()

PS: From my tries I guess the previous problem with getting `ovf` was, that the byte order was reversed (which simply would have been solved by using `<f` for the struct in python). But I personally like this way better, because it uses less casting.


message:
One port of motor shield doesn't operating stepper motor

1. One port of my motor shield (i.e M1 & M2) is not driving the stepper motor as it should.stepper motor jitters at its position.
2. While the other port (M3 & M4) works fine but it makes stepper motor too hot and also it's respective motor driver L293D IC.
3. While all the ports of motor shield works fine with DC Motor.

I am making CNC plotter using this setup.
I am powering motor shield with 12 V adapter and Arduino is connected with USB cable.

This is the code I am using :

    #include <Servo.h>
    #include <AFMotor.h>

    #define LINE_BUFFER_LENGTH 512

    char STEP = MICROSTEP ;

    // Servo position for Up and Down
    const int penZUp = 115;
    const int penZDown = 83;

    // Servo on PWM pin 10
    const int penServoPin =10 ;

    // Should be right for DVD steppers, but is not too important here
    const int stepsPerRevolution = 48;

    // create servo object to control a servo
    Servo penServo;

    // Initialize steppers for X- and Y-axis using this Arduino pins for the L293D H-bridge
    AF_Stepper myStepperY(stepsPerRevolution,1);
    AF_Stepper myStepperX(stepsPerRevolution,2);

    /* Structures, global variables    */
    struct point {
      float x;
      float y;
      float z;
    };

    // Current position of plothead
    struct point actuatorPos;

    //  Drawing settings, should be OK
    float StepInc = 1;
    int StepDelay = 0;
    int LineDelay =0;
    int penDelay = 50;

    // Motor steps to go 1 millimeter.
    // Use test sketch to go 100 steps. Measure the length of line.
    // Calculate steps per mm. Enter here.
    float StepsPerMillimeterX = 100.0;
    float StepsPerMillimeterY = 100.0;

    // Drawing robot limits, in mm
    // OK to start with. Could go up to 50 mm if calibrated well.
    float Xmin = 0;
    float Xmax = 40;
    float Ymin = 0;
    float Ymax = 40;
    float Zmin = 0;
    float Zmax = 1;

    float Xpos = Xmin;
    float Ypos = Ymin;
    float Zpos = Zmax;

    // Set to true to get debug output.
    boolean verbose = false;

    //  Needs to interpret
    //  G1 for moving
    //  G4 P300 (wait 150ms)
    //  M300 S30 (pen down)
    //  M300 S50 (pen up)
    //  Discard anything with a (
    //  Discard any other command!

    /**********************
     * void setup() - Initialisations
     ***********************/
    void setup() {
      //  Setup

      Serial.begin( 9600 );

      penServo.attach(penServoPin);
      penServo.write(penZUp);
      delay(100);

      // Decrease if necessary
      myStepperX.setSpeed(600);

      myStepperY.setSpeed(600);

      //  Set & move to initial default position
      // TBD

      //  Notifications!!!
      Serial.println("Mini CNC Plotter alive and kicking!");
      Serial.print("X range is from ");
      Serial.print(Xmin);
      Serial.print(" to ");
      Serial.print(Xmax);
      Serial.println(" mm.");
      Serial.print("Y range is from ");
      Serial.print(Ymin);
      Serial.print(" to ");
      Serial.print(Ymax);
      Serial.println(" mm.");
    }

    /**********************
     * void loop() - Main loop
     ***********************/
    void loop()
    {

      delay(100);
      char line[ LINE_BUFFER_LENGTH ];
      char c;
      int lineIndex;
      bool lineIsComment, lineSemiColon;

      lineIndex = 0;
      lineSemiColon = false;
      lineIsComment = false;

      while (1) {

        // Serial reception - Mostly from Grbl, added semicolon support
        while ( Serial.available()>0 ) {
          c = Serial.read();
          if (( c == '\n') || (c == '\r') ) {             // End of line reached
            if ( lineIndex > 0 ) {                        // Line is complete. Then execute!
              line[ lineIndex ] = '\0';                   // Terminate string
              if (verbose) {
                Serial.print( "Received : ");
                Serial.println( line );
              }
              processIncomingLine( line, lineIndex );
              lineIndex = 0;
            }
            else {
              // Empty or comment line. Skip block.
            }
            lineIsComment = false;
            lineSemiColon = false;
            Serial.println("ok");
          }
          else {
            if ( (lineIsComment) || (lineSemiColon) ) {   // Throw away all comment characters
              if ( c == ')' )  lineIsComment = false;     // End of comment. Resume line.
            }
            else {
              if ( c <= ' ' ) {                           // Throw away whitepace and control characters
              }
              else if ( c == '/' ) {                    // Block delete not supported. Ignore character.
              }
              else if ( c == '(' ) {                    // Enable comments flag and ignore all characters until ')' or EOL.
                lineIsComment = true;
              }
              else if ( c == ';' ) {
                lineSemiColon = true;
              }
              else if ( lineIndex >= LINE_BUFFER_LENGTH-1 ) {
                Serial.println( "ERROR - lineBuffer overflow" );
                lineIsComment = false;
                lineSemiColon = false;
              }
              else if ( c >= 'a' && c <= 'z' ) {        // Upcase lowercase
                line[ lineIndex++ ] = c-'a'+'A';
              }
              else {
                line[ lineIndex++ ] = c;
              }
            }
          }
        }
      }
    }

    void processIncomingLine( char* line, int charNB ) {
      int currentIndex = 0;
      char buffer[ 64 ];                                 // Hope that 64 is enough for 1 parameter
      struct point newPos;

      newPos.x = 0.0;
      newPos.y = 0.0;

      //  Needs to interpret
      //  G1 for moving
      //  G4 P300 (wait 150ms)
      //  G1 X60 Y30
      //  G1 X30 Y50
      //  M300 S30 (pen down)
      //  M300 S50 (pen up)
      //  Discard anything with a (
      //  Discard any other command!

      while( currentIndex < charNB ) {
        switch ( line[ currentIndex++ ] ) {              // Select command, if any
        case 'U':
          penUp();
          break;
        case 'D':
          penDown();
          break;
        case 'G':
          buffer[0] = line[ currentIndex++ ];          // /!\ Dirty - Only works with 2 digit commands
          //      buffer[1] = line[ currentIndex++ ];
          //      buffer[2] = '\0';
          buffer[1] = '\0';

          switch ( atoi( buffer ) ){                   // Select G command
          case 0:                                   // G00 & G01 - Movement or fast movement. Same here
          case 1:
            // /!\ Dirty - Suppose that X is before Y
            char* indexX = strchr( line+currentIndex, 'X' );  // Get X/Y position in the string (if any)
            char* indexY = strchr( line+currentIndex, 'Y' );
            if ( indexY <= 0 ) {
              newPos.x = atof( indexX + 1);
              newPos.y = actuatorPos.y;
            }
            else if ( indexX <= 0 ) {
              newPos.y = atof( indexY + 1);
              newPos.x = actuatorPos.x;
            }
            else {
              newPos.y = atof( indexY + 1);
              indexY = '\0';
              newPos.x = atof( indexX + 1);
            }
            drawLine(newPos.x, newPos.y );
            //        Serial.println("ok");
            actuatorPos.x = newPos.x;
            actuatorPos.y = newPos.y;
            break;
          }
          break;
        case 'M':
          buffer[0] = line[ currentIndex++ ];        // /!\ Dirty - Only works with 3 digit commands
          buffer[1] = line[ currentIndex++ ];
          buffer[2] = line[ currentIndex++ ];
          buffer[3] = '\0';
          switch ( atoi( buffer ) ){
          case 300:
            {
              char* indexS = strchr( line+currentIndex, 'S' );
              float Spos = atof( indexS + 1);
              //         Serial.println("ok");
              if (Spos == 30) {
                penDown();
              }
              if (Spos == 50) {
                penUp();
              }
              break;
            }
          case 114:                                // M114 - Repport position
            Serial.print( "Absolute position : X = " );
            Serial.print( actuatorPos.x );
            Serial.print( "  -  Y = " );
            Serial.println( actuatorPos.y );
            break;
          default:
            Serial.print( "Command not recognized : M");
            Serial.println( buffer );
          }
        }
      }

    }

    /*********************************
     * Draw a line from (x0;y0) to (x1;y1).
     * int (x1;y1) : Starting coordinates
     * int (x2;y2) : Ending coordinates
     **********************************/
    void drawLine(float x1, float y1) {

      if (verbose)
      {
        Serial.print("fx1, fy1: ");
        Serial.print(x1);
        Serial.print(",");
        Serial.print(y1);
        Serial.println("");
      }

      //  Bring instructions within limits
      if (x1 >= Xmax) {
        x1 = Xmax;
      }
      if (x1 <= Xmin) {
        x1 = Xmin;
      }
      if (y1 >= Ymax) {
        y1 = Ymax;
      }
      if (y1 <= Ymin) {
        y1 = Ymin;
      }

      if (verbose)
      {
        Serial.print("Xpos, Ypos: ");
        Serial.print(Xpos);
        Serial.print(",");
        Serial.print(Ypos);
        Serial.println("");
      }

      if (verbose)
      {
        Serial.print("x1, y1: ");
        Serial.print(x1);
        Serial.print(",");
        Serial.print(y1);
        Serial.println("");
      }

      //  Convert coordinates to steps
      x1 = (int)(x1*StepsPerMillimeterX);
      y1 = (int)(y1*StepsPerMillimeterY);
      float x0 = Xpos;
      float y0 = Ypos;

      //  Let's find out the change for the coordinates
      long dx = abs(x1-x0);
      long dy = abs(y1-y0);
      int sx = x0<x1 ? StepInc : -StepInc;
      int sy = y0<y1 ? StepInc : -StepInc;

      long i;
      long over = 0;

      if (dx > dy) {
        for (i=0; i<dx; ++i) {
          myStepperX.onestep(sx,STEP);
          over+=dy;
          if (over>=dx) {
            over-=dx;
            myStepperY.onestep(sy,STEP);
          }
        delay(StepDelay);
        }
      }
      else {
        for (i=0; i<dy; ++i) {
          myStepperY.onestep(sy,STEP);
          over+=dx;
          if (over>=dy) {
            over-=dy;
            myStepperX.onestep(sx,STEP);
          }
          delay(StepDelay);
        }
      }

      if (verbose)
      {
        Serial.print("dx, dy:");
        Serial.print(dx);
        Serial.print(",");
        Serial.print(dy);
        Serial.println("");
      }

      if (verbose)
      {
        Serial.print("Going to (");
        Serial.print(x0);
        Serial.print(",");
        Serial.print(y0);
        Serial.println(")");
      }

      //  Delay before any next lines are submitted
      delay(LineDelay);
      //  Update the positions
      Xpos = x1;
      Ypos = y1;
    }

    //  Raises pen
    void penUp() {
      penServo.write(penZUp);
      delay(penDelay);
      Zpos=Zmax;
      digitalWrite(15, LOW);
        digitalWrite(16, HIGH);
      if (verbose) {
        Serial.println("Pen up!");

      }
    }
    //  Lowers pen
    void penDown() {
      penServo.write(penZDown);
      delay(penDelay);
      Zpos=Zmin;
      digitalWrite(15, HIGH);
        digitalWrite(16, LOW);
      if (verbose) {
        Serial.println("Pen down.");

      }
    }

This are the connections I made:

[![connections][1]][1]

I tried replacing motors with each other but the case remains same just the motor now connected to the port(which is not working ) starts jittering and another one works but gets too hot.

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

body:
I ran into the same issue yesterday. The problem is that one of the pins of the M1 Port touches the housing of the usb-jack and shortens Vcc to Gnd. Try to put some tape around the housing...

bye

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

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


message:
Read CID from SD card with ESP8266

I would like to get the serial numbers of SD cards, with follow code:

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

    #include <SPI.h>
    #include <SD.h>

    // set up variables using the SD utility library functions:
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    cid_t cid;  // *****at the top with the other globals (for get cid)

    // change this to match your SD shield or module;
    // Arduino Ethernet shield: pin 4
    // Adafruit SD shields and modules: pin 10
    // Sparkfun SD shield: pin 8
    const int chipSelect = 4;

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.print("\nInitializing SD card...");

      // we'll use the initialization code from the utility libraries
      // since we're just testing if the card is working!
      if (!card.init(SPI_HALF_SPEED, chipSelect)) {
        Serial.println("initialization failed. Things to check:");
        Serial.println("* is a card inserted?");
        Serial.println("* is your wiring correct?");
        Serial.println("* did you change the chipSelect pin to match your shield or module?");
        return;
      } else {
        Serial.println("Wiring is correct and a card is present.");
      }

      // print the type of card
      Serial.print("\nCard type: ");
      switch (card.type()) {
        case SD_CARD_TYPE_SD1:
          Serial.println("SD1");
          break;
        case SD_CARD_TYPE_SD2:
          Serial.println("SD2");
          break;
        case SD_CARD_TYPE_SDHC:
          Serial.println("SDHC");
          break;
        default:
          Serial.println("Unknown");
      }

      // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
      if (!volume.init(card)) {
        Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        return;
      }

      // print the type and size of the first FAT-type volume
      uint32_t volumesize;
      Serial.print("\nVolume type is FAT");
      Serial.println(volume.fatType(), DEC);
      Serial.println();

      volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
      volumesize *= volume.clusterCount();       // we'll have a lot of clusters
      volumesize *= 512;                            // SD card blocks are always 512 bytes
      Serial.print("Volume size (bytes): ");
      Serial.println(volumesize);
      Serial.print("Volume size (Kbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);
      Serial.print("Volume size (Mbytes): ");
      volumesize /= 1024;
      Serial.println(volumesize);

      Serial.println();

      // *****list all files in the card with date and size
      //Serial.println("\nFiles found on the card (name, date and size in bytes): ");
      //root.openRoot(volume);
      //root.ls(LS_R | LS_DATE | LS_SIZE);

      card.readCID(&cid);
      Serial.print("Serial number: "); Serial.println(cid.src); // psn is the serial number field of the struct

    }

    void loop(void) {

    }

I tried to get serial from SD card but I only get this "Serial number: 2065301974". I really need it in hex format, for example "0x0033515c".

Also, I would like to get the complete CID like this:

    CID: 0x1B, 0x53, 0x4D, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x45, 0x5D, 0x04, 0xE5, 0x00, 0xF9, 0x69

body:
To print the serial number in hex [Serial.println][1] accepts a format parameter:

    Serial.println(cid.psn, HEX);

The cid variable is a struct so you can access the the other fields via the structure. But if you really want to access the raw bytes you could cast cid to a pointer then access the individual bytes:

    uint8_t *rawcid = reinterpret_cast<uint8_t*>(&cid);
    Serial.println(*(cid+3), HEX); // print the 4th byte

Be aware that casting like this can be tricky and you will likely shoot yourself in the foot more than once.

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/println/


body:
`cid_t` is a structure that has all sorts of information in it in different formats.  The serial number (`psn`) is just a 32-bit unsigned integer.  You can print it as hex by printing it as hex.

    Serial.println(cid.psn, HEX);

If you want to get the raw data of the structure (which I assume may correspond to the raw data read from the card, but don't quote me on that) you can access the struct as 8-bit values:

    uint8_t *p = (uint8_t *)&cid;
    for (int i = 0; i < sizeof(cid); i++) {
        Serial.print("0x");
        Serial.print(p[i], HEX);
        Serial.print(" ");
    }
    Serial.println();


message:
Can't identify + or - in the 5v USB wall adapter, does it matter?

[![Power from 5V USB wall adapter][1]][1]

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

I want to power the UNO with the USB power adapter (the charger of a phone), the adapter delivers 5.0 volts and comes from the wall (in the photo a regulator is added). However, the legs of the USB adapter look the same, can I plug it to the wall indistinctly like I do when I charge the phone, or do I need to know which leg is + and which one is - ? (I don't have measurement equipment).

body:
It does not matter which orientation you plug it into the mains plug.

The power supply produces the same 5V regardless, and the USB plug has a fixed/standard polarity on the pinout.


body:
Power (which comes from your wall outlet), is AC, which means alternating current. It changes 50 or 60 times per second from direction, so this is the reason it does not matter if you plug it reversed or not. Some countries have plugs which can be plugged in normally or 180 degrees rotated (but you cannot see what is 0 or 180 degrees since these are symmetrical).

The circuit inside the adapter makes sure the AC is converted to DC, where it matters what is Plus or Minus.


message:
How to create a device with buttons that records when they are pressed

I want to build a very simple device, which has a bunch of buttons for switching "settings" and LED lights to show which "setting" it is on.  I also want it to record the times of the transitions between settings so that I can later connect it to a computer through USB and retrieve the timestamps of the setting changes, i.e. when the buttons were pressed.

What is the best way to do this?  Is it with Arduino or some other way?  If it is with Arduino, what would I need to buy, and what would I need to read?

body:
Arduino is ideal for it. Buy Arduino or Genuino UNO with Starter Kit. Starter kits contain buttons, LEDs, resistors, breadboard and example projects brochure.

link: [Getting Started with Arduino][1]

  [1]: https://www.arduino.cc/en/Guide/HomePage


body:
All is reasonably easy.

- Buttons: use separate buttons, or think about a small 4x4 matrix keypad.
- LED: WS8212 etc or use your own separate LEDs (very cheap)
- Record times: store them on a SD card
- USB: It is possible to send texts via USART which can connect via USB; also you can consider putting the SD card directly in your computer.


message:
other interrupts in rc channel reader

I have the sketch from James Waldby ([Read RC receiver channels using Interrupt instead of PulseIn][1]) working beautifully. I want to use a switch on my TX to start and stop a sequence of lights (emulating guns firing on a ship model). But first, I need the delayed flash routine to work. I have tried a loop counting millis() differences to separate the sequences, but the delays don't delay.

     void loop(){
      rc_read_values();//Mr. Waldby's interrupt routine
      currentMillis = millis();
      previousMillis = currentMillis;
      if(fireGun ==1){
        interval = 3000;
      }else{
        interval = 1500;
      }
      interval = 3000;
      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

    //if(fireGun ==1){
      analogWrite(led, 255);
      delay(50);
    /* a real gun flash doesn't cut right off; it fades away.
      This sequence simulates that  */
      while(brightness > 0){

        // change the brightness for next time through the loop:
        brightness = brightness - fadeAmount;
        analogWrite(led, brightness);
        delay( 7);
      }
      brightness = 80;
    }

  [1]: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein

The intention here is to flash the led every 3 seconds. The flash loop works fine, but the 3 second delay doesn't.

The delay routine works ok in a sketch by itself.

Any thoughts about what I might be doing wrong?

body:
>       currentMillis = millis();
      previousMillis = currentMillis;

So currentMillis and previousMillis will always be exactly the same, right?

>       if (currentMillis - previousMillis >= interval) {

So if `0 >= interval` (which it won't be) do something?

Therefore your fading code will never be executed.


message:
Selecting different arrays using a list of pointers

I have different arrays of different sizes, and a list of pointers to the addresses of each array. How do I select each array using the list of pointers, and access it's elements. On Teensy 3.2 board.

    int * arr_list[3];
    const int arr_sizes[3] = {3,4,5};  // array of the array sizes
    const int ar1[3] = {12,2,8};       // arrays of  different sizes
    const int ar2[4] = {41,3,6,47};
    const int ar3[5] = {9,32,1,5,7};

    void map_arrays(){          // list of pointers with the addresses of the
                                // arrays
    arr_list[0] = (int*) &ar1;
    arr_list[1] = (int*) &ar2;
    arr_list[2] = (int*) &ar3;
    };

    int arr_number = 1;          // select array
    int a = arr_sizes[arr_number];    // the size of the selected array
    int *b = arr_list[arr_number];
    int test = 0;

    void setup() {

    Serial.begin(57600);  //serial monitor

    }

    void loop() {

    for (int i=0; i<a; i++) {     // for the selected arr_number iterate and
    test = b[i];                  // return the index elements

    }

    Serial.println("size =");
    Serial.println(a);
    Serial.println();
    delay(1000);
    Serial.println("index =");
    Serial.println(test);
    Serial.println();
    delay(500);

     }

body:
You have it right, only fix initialization of test variables:

1. you do not call map_arrays() in setup()
2. you assign uninitialized arr_list item to b

>     const int* arr_list[3];
>     const int arr_sizes[3] = { 3, 4, 5 };  // array of the array sizes
>     const int ar1[3] = { 12, 2, 8 };       // arrays of  different sizes
>     const int ar2[4] = { 41, 3, 6, 47 };
>     const int ar3[5] = { 9, 32, 1, 5, 7 };
>
>     void map_arrays() {          // list of pointers with the addresses of the
>     // arrays
>       arr_list[0] = ar1;
>       arr_list[1] = ar2;
>       arr_list[2] = ar3;
>     }
>
>     int arr_number = 1;          // select array
>     int a = arr_sizes[arr_number];    // the size of the selected array
>     const int *b;
>     int test = 0;
>
>     void setup() {
>
>       Serial.begin(57600);  //serial monitor
>
>       map_arrays();
>
>       b = arr_list[arr_number];
>
>       for (int i = 0; i < a; i++) {     // for the selected arr_number iterate and
>         test = b[i];                 // return the index elements
>         Serial.println(test);
>       }
>
>       Serial.println("size =");
>       Serial.println(a);
>       Serial.println();
>       delay(1000);
>       Serial.println("index =");
>       Serial.println(test);
>       Serial.println();
>       delay(500);
>
>     }
>
>     void loop() {
>     }


message:
Can't re-write Arduino Pro Mini

I am just getting started with arduino, but I am having an issue with some 3.3V, 8Mhz Arduino Pro Minis. I am using a SparkFun FT232RL USB to Serial breakout (https://www.sparkfun.com/products/12731) to communicate with the board, using Windows 7 and the Arduino IDE.

The Pro Minis were blank when I got them, I am able to upload a single program (Blink), which runs successfully, but I am unable to upload subsequent programs. I get the error:

    avrdude: stk500_recv(): programmer is not responding

Any idea what might be going on?

body: Connect the DTR pin from the FT232 to the Promini as well, that will allow the software autoreset to work. Promini has a 0.1uF cap between the DTR pin and Reset already.


message:
parse intel hex into SPI commands for arduino ICSP AVR

I'm attempting to use the arduino as an ICSP AVR to flash hundreds of ATMEGA's 90USB162.  I'm having some difficulties when trying to do the actual flashing of the chip.  I've go all the wires done properly and I'm able to read the signature.  My source is an Intel hex file and I'm reading it properly as I'm able to see each by as it is read from the arduino's memory.  Where I'm getting lost is the documentation states that I need to set the low byte first before I set the high byte for the same memory address.  Using the following as an example (underscores to break the data up) could someone help me descern what my SPI transaction bytes would look like?

    :_20_0000_00_16C100003CC100003AC1000038C1000036C1000034C1000032C1000030C10000_48

I know the colon is the start code, 20 is the hex value of number of data bytes,  0000 is the address, 00 is the record type,  the next 32 bytes is my data followed by the checksum.

I thought that I would loop over the data portion and increment the address every other byte

    uint16_t addr = 0;

    while (recordtype != endOfFile)
    {
      auto data[] = parseData();

      for(uint8_t index = 0; index < 32;)
      {
        SPITask.Send(0x40, 0x00, addr, data[index++]);//send low byte
        SPITask.Send(0x48, 0x00, addr, data[index++]);//send high byte
        SPITask.Send(0x4C, addr, addr, 0x00);//commit new bytes to address
        addr++;
      }
    }

I don't think this is right and some examples i'm loosely following comment that they are changing the address byte into a word, which makes some sense based on the command layouts of the data sheet (page 260) [90USB162 Data sheet][1].  Can anyone please provide some guidance in how to break up this data into high and low bytes.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/doc7707.pdf

body:
I have some code that does [exactly what you want on GitHub](https://github.com/nickgammon/arduino_sketches/blob/master/Atmega_Hex_Uploader_Fixed_Filename/Atmega_Hex_Uploader_Fixed_Filename.ino).

Amongst other processors, it supports the At90USB162 chip. The code reads from an SD card in Intel hex format and writes to the chip at the press of a switch. This effectively is what you are trying to do.

Arduino forum moderator "Crossroads" (who has recently also [joined Stack Exchange](https://arduino.stackexchange.com/users/42539/crossroads)) has made [a board to do the programming](http://www.crossroadsfencing.com/BobuinoRev17/Programmer.html), hold the SD card, and have some status LEDs:

[![Board programmer][1]][1]

Here is my code to write to the flash:

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

    // execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
    //  processor may return a result on the 4th transfer, this is returned.
    byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
      {
      noInterrupts ();
      BB_SPITransfer (b1);
      BB_SPITransfer (b2);
      BB_SPITransfer (b3);
      byte b = BB_SPITransfer (b4);
      interrupts ();
      return b;
      } // end of program

    // write a byte to the flash memory buffer (ready for committing)
    void writeFlash (unsigned long addr, const byte data)
      {
      byte high = (addr & 1) ? 0x08 : 0;  // set if high byte wanted
      addr >>= 1;  // turn into word address
      program (loadProgramMemory | high, 0, lowByte (addr), data);
      } // end of writeFlash

---

Your loop looks a bit strange, the page size (before you need to commit) is 128 bytes (64 bytes), not 2 bytes.

See the datasheet:

[![Flash page size][2]][2]

  [1]: https://i.stack.imgur.com/NxuA3.jpg
  [2]: https://i.stack.imgur.com/41P7t.png


message:
Arduino Reaction LED game

I have this code and it is a reaction light game. When you press the button on pin 11 it starts the game and the lights should osculate back and forth. The main goal is to press the button when it hits the middle led and the osculating will slow down. I cannot get the leds to turn on help?

        int ledPin;
        int direction;
        int isChanging;
        unsigned long lastChange;

    void setup() {
       //set pins 2 to 10 to be output
      // and LEDs off
       int pin;
        for (pin = 2; pin <= 10; pin++) {
           pinMode(pin, OUTPUT);
           digitalWrite(pin, LOW);
        }
         //set pin 11 to be input
         pinMode(11, INPUT);

         ledPin = 2;
         direction = 1;
         lastChange = millis();
      }

     void loop() {
        if (isChanging) {
        if (millis() - lastChange > 500) {
            //turn off old LED
            digitalWrite(ledPin, LOW);
            //reset time
            lastChange = millis();
            //change the led
            ledPin = ledPin + direction;
            if (ledPin > 10) {
              direction = -1;
            ledPin = 9;
          } else (ledPin < 2); {
            direction = +1;
            ledPin = 3;
         }

           //turn on new LED
            digitalWrite(ledPin, HIGH);
         }
           //check for button
           if (digitalRead(11)) {
            isChanging = 0;
         }
         }
        else {
           //wait for them to let go of the button
           while (digitalRead(11)) {
         }
           //wait for it to be pressed again
           while (!digitalRead(11)) {
         }
           //wait for them to let go of the button
           while (digitalRead(11)) {
         }
        }
       }`

body:
Your are not explicitly initializing the variable `isChanging`, so the compiler sets it to `0`. This means, that your code will directly go to the last else statement and cannot at any time reach the LED code, because you are not changing the variable in the else statement.

But I don't really understand, why you were using this variable in the first place. Try to use purely non-blocking code. For checking the button you can do something like this:

    boolean button_pressed = false;
    unsigned long button_timestamp = 0;

    void loop(){
      ...
      if(!button_pressed && digitalRead(11)){
        button_pressed = true;
        button_timestamp = millis();
      }
      if(button_pressed && millis() - button_timestamp > 50){
        if(digitalRead(11)){ // real button press
          button_pressed = false;
          // check, if the middle LED is ON and act accordingly
          // or, if the game hasn't started yet, start it
        } else { // just a bounce of the button, not a real button press
          button_pressed = false;
        }
      }

      // LED CODE
      if (millis() - lastChange > 500) {
        ...
      }
    }

Note, that this code will not wait for the button to be released, but reacting, when the button was held down for 50ms. You can change this value, to a one, that is more fitting your used button, but it is a good start point.

Also in your LED code, you have to replace the 500 in the millis statement with a variable, since you want to change the speed.

For handling starting the game with the same button, you can use a state variable, which contains a value of means "Game Stopped" or "Game Started".


message:
arduino didn't working properly

![enter image description here](https://i.stack.imgur.com/oMzIX.jpg) arduino didn't working properly. When i using a alarm program on pin 6 and a blinking led on pin 2 alarm sound beeps once and then goes down but when using only alarm program it works perfectly. I see that arduino can handle one pin perfectly but when it comes to use two pins together it can't handle properly

    float sinVal;
    int toneVal;
    void setup(){
        pinMode(7, OUTPUT);
        pinMode(2, OUTPUT);
    }
    void loop(){
        for(int x=0; x<180; x++)
            { //convert angle of sinusoidal to radian measure
            sinVal = (sin(x*(3.1412/180)));
            //generate sound of different frequencies by sinusoidal value
            toneVal = 2000+(int(sinVal*1000));
            //Set a frequency for Pin-out 8
            tone(7, toneVal);
            delay(2); }
        digitalWrite(2, HIGH);
        delay(100);
        digitalWrite(2, LOW);
        delay(200);
    }

body: with this wiring setting pin 2 HIGH shorts pin 2 to ground and Arduino dies. you must use a resistor in series with LED. and better use one with the speaker too.


message:
Write to EEPROM before shutdown

I'm currently designing a battery operated device that has to write data to an EEPROM before shutting down, or in regular intervals to save data. Would it damage the EEPROM if it had to shut down while it is being written to?

The first possible case is when it is transmitting the data over I2C. That shouldn't affect it much. But if it gets powered down while it is actually writing the byte to its memory, I don't know whether it would save it correctly or corrupt it.

body: According to the datasheet, an EEPROM write takes 3.3mS. If power drops below the level needed to complete the write, the data will be corrupted.


message:
SoftwareSerial runs out of "text" space on ATtiny

I have an ATtiny and am trying to send a very large byte array stored in a separate `.h` file over SoftwareSerial:

    for (int i=0; i<numElements; i++) {
        softSerial.println(myList[i]);
    }

I imagine it will very slow, which is fine, but I'm getting a cryptic error when compiling:

    Firmware.ino.elf section `.data' will not fit in region `text'

It seems that this is due to the `println()` command running out of memory for some reason – if I comment out the `println()` command everything works fine. How to fix this?

body:
Your sketch doesn't fit into program memory of the ATtiny. If you comment out the `println` of the array, the compiler evaluates that the array is not used and doesn't attach it to the program. Then the program fits into memory.

**EDIT**
Chad suggests some good alternatives below, if you need to store more data than flash or `PROGMEM` will allow.


body:
There is not enough room in program memory for 140KB. ATiny only has 8KB for the whole program. So there is no way to fix this with your current hardware.

Options-

add a storage device (SD card, sram module, others....) where you can store the data, and then read it in small chunks and send it out

possibly use a arduino mega. It has 256KB of program space. you will still have to make sure you are not trying to store the whole byte array in an array since that would get stored in sram (which there is still only 8KB) but it could again to written in chunks to avoid this problem.


body:
The ATTiny only has a limited amount of RAM. A lot less that flash-memory.

Using a normal array, the entire contents of the array are placed into RAM (during initialization). Which is very limited.

I'd suggest, looking into [PROGMEM](https://www.arduino.cc/reference/en/language/variables/utilities/progmem/). This is a way to read the data directly from the flash-memory.


message:
Has pt.h library been removed from arduino?

I'm trying to get a program to use protothreading and I've got an error at the include statement for the pt.h library stating that there is no such file or directory. This is how it's written in the program:

    #include <pt.h>

body:
`pt.h` has never, and will never, be part of the Arduino core distribution.  It is a completely separate third party library that you have to install yourself.

I think the library you want is [this one.](https://github.com/fernandomalmeida/protothreads-arduino)


message:
Did I overheat my Arduino while soldering to perfboard?

So this is the second time that I've had a circuit that worked perfectly on a breadboard, but as soon as I connected it to a perfboard and soldered the joints together, the Arduino stopped working and wouldn't let me upload sketches (though I could see a COM port for it).

I'm using lead-free solder for the first time, and had the temperature at 750 deg Fahrenheit, and I'm thinking that while I had quick joints to connect the Arduino to the perfboard, when bridging two joints with solder, the iron might have been heating the header pin for 4-10 seconds... Is that enough to break the board?

[![my perfboard joints][1]][1]

(note - I'm using jumper wires on the other side to connect everything up, and I've already checked the board's connections using a multimeter and they're all as intended, and there are no accidental shorts/bridges)

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

body:
Bridging adjacent pins by heating for 10 seconds is not a great way of doing things. You are trying to cross the "solder resist" with solder, so you are basically fighting something.

I normally use some tinned copper wire to cross gaps like that. You should be able to keep the soldering times down to a couple of seconds.

> Did I overheat my Arduino ... ?

We can't really say from where we sit, but maybe.

> I could see a COM port for it

The Pro Mini doesn't have a USB chip, so how are you programming it?

---

> I am using an FTDI breakout board to program the Pro Mini, which then attaches to a USB cable.

Right, well you are seeing the COM port from the FTDI breakout board, not the Arduino as such. You would see that even if there was no Arduino there at all.

---

The soldering on one of your pins (5th from the bottom, on the right) looks a bit dodgy. It might just be the light.

As I said earlier, you possibly overheated the processor chip. I would use the technique I described rather than a 10-second heat.

See my question/answer: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board - that describes various tests you can do to check if the processor is still good.


body:
>I would like to clarify that my only question in ENTIRE post was: "Is that enough to break the board?"

The answer to that narrow question is that *heat from soldering with an iron* is extremely unlikely to have done this.  IC's are in practice (vs data sheet) quite heat tolerant, and further the pins you are soldering on are not even the pins of the IC or any electronic components, but rather those of the module headers.  You'd be more likely to melt the plastic web between those headers pins, but even that won't be a great problem since they are already in place. Or if you were soldering directly on the board, lifting a pad or trace - but you were not doing that.

Your actual problem is something else, *what that might be* is presently unanswerable due to the lack of detail in your question.


message:
expected primary expression before ')' token

#define ANALOG_IN 0

    void setup() {

      Serial.begin(19200);

      analogReference(INTERNAL);

    }

    void loop() {

      int val = analogRead(ANALOG_IN);

      Serial.print(0xff, byte);

      Serial.print( (val >> 8) & 0xff, byte);

      Serial.print( val & 0xff, byte);

    }

This is my code and I'm getting this error for all 3 Serial.print commands. Please help.

body:
Why are you putting `byte` there? That isn't in the [Serial.print reference page](https://www.arduino.cc/reference/en/language/functions/communication/serial/print/).

This compiles OK:

    #define ANALOG_IN 0

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

    void loop() {
      int val = analogRead(ANALOG_IN);
      Serial.print(0xff);
      Serial.print( (val >> 8) & 0xff);
      Serial.print( val & 0xff);
    }


message:
How to know the external interrupt origin from the ISR

I'd like to know if there is any way to know what is the origin of an external interrupt by programming inside the ISR.

I know I can use a different ISR for each external interrupt and that works but I'm thinking if it's possible to use the same ISR for all external interrupts

If you check the origin pin and trigger condition inside ISR it's not a reliable way to do.

Is there any memory record which store the external interrupt activation?

This is a general question for any AVR microcontroller.

body:
> Is there any memory record which store the external interrupt
> activation?

There is, but I do not think it will be easy to exploit.

At low level, each interrupt is handled by a different ISR. So you will
have `INT0_vect` handling external interrupt 0 and `INT1_vect`
handling interrupt 1. These ISRs are all defined by the Arduino
core library. In your case, they will both call the same handler that
you defined. Thus, the information about which ISR fired is now on the
stack: it is the return address of your function.

The reason this information will not be easy to use is that you do not
know how far it is from the stack pointer. It depends on how much stuff
your own handler pushed onto the stack. You could disassemble it and
count, but then your code will be fragile, as the smallest change in the
handler (or compiler version) may change this count.

An easier approach may be to define your own `INT0_vect` and
`INT1_vect`, overriding those from the Arduino core. These new ISRs
will both call your handler, but they will pass it an argument to tell
which interrupt fired.

Or you can register a different handler for each interrupt, each calling
a common function. But this adds an extra level of function calls.


message:
remove weird chars from char array ESP32

When I'm converting a string to a char array there are always some weird chars at the end.
I have to do it manualy because the convertTochar function crashes my ESP.

      String sssid = module.getCssid(); //String is stored in the eeporm
      char cssid[sssid.length()];
      Serial.println(sssid.length()); //prints correct length of 6
      //convert do ssid
      for( int i = 0; i<sizeof(cssid);i++){
        cssid[i] = sssid[i];
      }
      Serial.println(cssid); //prints myssid⸮?⸮2⸮?
    enter code here

If I'm printing the value directly fromm eeprom there are no wired characters.
Also the max eeprom size for the string is 10 bytes...

Why are these characters at the end of string?

body:
You forgot to add one more character to the array to place a \0 (0 value byte) in. This denotes the end of a string. If you forget this, the string will continue until it finds the first 0 byte, which will probably be after the original string copy. This can be dangerous, because it might be in memory that is not containing useful data, and those weird character can be many if there is not a 0 soon or at all.

Note that the 6 bytes you get are the bytes EXCLUDING this 0 byte, so you need to allocate 7 bytes to store a string of length 6.

Instead of the for loop you can use the strcpy function which copies a function including the 0 string.

See [description][1]:

Description

The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest.

Declaration

Following is the declaration for strcpy() function.
char *strcpy(char *dest, const char *src)

Parameters

dest − This is the pointer to the destination array where the content is to be copied.

src − This is the string to be copied.

Return Value

This returns a pointer to the destination string dest.

Example

The following example shows the usage of strcpy() function.

    #include <stdio.h>
    #include <string.h>

    int main () {
       char src[40];
       char dest[100];

       memset(dest, '\0', sizeof(dest));
       strcpy(src, "This is tutorialspoint.com");
       strcpy(dest, src);

       printf("Final copied string : %s\n", dest);

       return(0);
    }

  [1]: https://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm


message:
Use LoLin V3 pins starting with 'S' in Arduino

I have this LoLin NodeMcu V3 board:

[![LoLin NodeMcu V3][1]][1]

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

What are the pins S3, S2, S1, SC, S0, SK?
Can I use them as GPIO in Arduino?

Thank you for your help!

body:
My guess is those are the SDIO pins. They're meant for use with an SD card - 4 data pins, a clock pin, and a select pin.

To find out what more you can do with them you should ignore the fact that it's a "LoLin" and instead just look for documentation on the ESP8266 or ESP32 (whatever it is on there) that powers that board.


body:
These pins have 2 functions: They are the connections to an SD card and/or to its internal flash chip. The ESP8266 has the feature of when you set GPIO15 HIGH during bootup, it will load the program from SD card and execute it. See [here][1] for reference. On the normal board, these pins are however connected to an internal flash chip.

Signal name meanings:

* SK: Serial Clock
* SC: SPI Chip Select
* S0 to S3: Data lines (Quad-I/O mode).

This picture found [here][2] explains the pins:
[![lolinv3][3]][3]

But as @Majenko already said, only the chip documentation matters, which is here:

[![esp12][4]][4]

Now to answer the actual question: Can you use these pins for arbitrary purposes? That depends. On the board they are all internally connected to a Quad-SPI flash chip. If you re-assign these pins to GPIO pins during normal operation in Quad-SPI mode, the chip hang up as the you just cut off one of the important lines to flash chip. **However**, if you really want you can modify your chip and cut two connections from the flash chip. Quad-SPI uses 4 data lines, but you can also operate the chip in Dual-SPI with 2 data lines (refer to [here][5]).

That means that you are able to cut 2 of the 4 data lines, GPIO9 (SPI_HD, S2 on the board) and GPIO10 (SPI_WP, S3 on the board) on the PCB from the ESP8266 to the flash chip and then use these two GPIO pins arbitrarily. This is to avoid interference with the flash chip when you are driving random signals to it while the lines are still physically conencted to the flash chip. You will ofcourse need to tell your flash tool (`esptool.py`) to use Dual-SPI mode for all subsequent firmwares. See [here][6] for that.

All other Flash GPIO pins can not be re-purposed, these conenctions (such as SCLK, MISO, MOSI, CS) are always needed for the flash chip.

GPIO15, which is D8 on the board, is easier to repurpose: You just need to make sure it's LOW during startup as to not trigger the SD card bootup by using a pulldown resistor. After flash bootup you can re-purpose it for input and output. This is already done on the board for you and you just need to use `pinMode` to set it as INPUT or OUTPUT. This is also described in [here][1].

Obviously that's a lot of trouble to get 2 GPIO pins. If you just want more GPIO, you will find an I²C GPIO port expander such as the [MCP23017][7] much more suitable for that -- 16 more GPIOs at the cost of 2 GPIO pins (the I2C bus). If you're already using the I2C bus in a project then you don't even loose additional GPIOs, it's just one more device on the bus.

  [1]: https://www.forward.com.au/pfod/ESP8266/GPIOpins/index.html
  [2]: https://www.lelong.com.my/arduino-iot-lolin-nodemcu-v3-lua-based-esp8266-wifi-development-board-littlecraft-193816300-2019-07-Sale-P.htm
  [3]: https://i.stack.imgur.com/3wTDt.jpg
  [4]: https://i.stack.imgur.com/xkSjR.png
  [5]: https://electronics.stackexchange.com/questions/28792/what-is-dual-quad-i-o
  [6]: http://smarpl.com/content/esp8266-esp-201-module-freeing-gpio9-and-gpio10
  [7]: https://www.adafruit.com/product/732


message:
If an I2C connection is lost for a short period of time will it work if the connection is live again?

I'm using an ESP8266 with the Arduino library to read from a sensor([MPU9250][1] specifically). The readings are done via I2C but I'm using a library that abstracts these methods.

The wires are not soldered together so temporary disconnections are possible and after these disconnects the sensor readings freeze. I'm new to the world of I2C so my questions are:

- Do I have to re-init the connection after it disconnects or is there a way to continue on re-connection immediately?
- Is there a way to prevent this to happen (for example to stop reading when there's no connection) or should I just solder together the pins?

  [1]: https://www.invensense.com/wp-content/uploads/2015/02/RM-MPU-9250A-00-v1.6.pdf

body:
When an I2C master starts a transmission or a request from a slave, it sends the slaves address and then check for an acknowledgement (ACK) from the slave (SDA LOW, when the clock has a HIGH pulse). When no slave is connected, or there is no slave with this address, then there isn't any circuit to pull SDA to LOW on the clock pulse, that is generated by the master. This is interpreted as No acknowledgement (NACK) and the transmission/request fails and should exit. So a disconnection between the transmission should not freeze your code (though I don't know what your library is doing exactly).

A quick google search gives me, that the esp8266 does not have hardware I2C, so your library does a pure software I2C. There are many pitfalls, which can block the I2C bus (especially, if one the lines is hold LOW by one of the involving circuits). Your library may or may not implement the correct I2C protocoll.

So to clearly answer your questions:

 1. You don't have to reinit connection. Your master transmission fails, if there is no slave, and should give you an error as return value. But be sure, that there isn't happening anything on the SDA or SCL lines, when it starts up again after reconnection. Master or slave can interpret voltage spikes as signal.
 2. If the library is implemented correctly, it will exit, when there is no ACK from the slave.

Look into the documentation of your library how it handles these events. And check the state of SDA and SCL, when a block occures. You can refer to [this site][1] for further information about I2C. It also gives some advice if your bus is blocked.

  [1]: http://www.i2c-bus.org/i2c-primer/analysing-obscure-problems/blocked-bus/


message:
my arduino uno board is not working

at once, when i connect arduino uno to my computer, my computer shuts down, after that i cannot upload programs to my computer,the board is not working but the led is ON. Before this, i upload programs 4 to 5 times continuously. i upload program with no physical connections in arduino except motor shield which is also not connected to anything.
i used three boards, all of them got damaged.

my computer's USB port and USB cable is in good codition.
i already updated my drivers.

computer spec: dell inspiron 15 3567
               windows10 x64 bit

body:
Computer shutting down is often an indication that excess power is being drawn.
If you measure  between +5 and Gnd on the unpowered board with a meter set for resistance, do you get a reading in the 5Kohm range? Or something much lower? Much lower would be bad.


message:
Arduino: using digital pins to emulate USB device

Is there any "easy" way to emulate USB keyboard or gamepad using digital pins on Arduino Mega? I looked at Uno-Joy/Mega-Joy, but I dont find firmware changes appealing.

body:
There is (or was) an implementation of software-only USB for the Arduino. I think it was called V-USB, though I am having trouble finding it now.

I think it may be [this library](https://github.com/gloob/vusb-for-arduino) though nothing has happened with that for a number of years.

Personally, I wouldn't recommend it, though, and would suggest using a board with a real USB interface, such as the Arduino Leonardo, chipKIT Lenny, or Teensy 3.x.


message:
Arduino - Finite State Machine does not start in the initial state

I'm building a state machine using 6 flip-flopsD, and an G input coming from an infrared sensor. This circuit should count from 0-35.
The problem is that it always starts in state 111111. That is, after it passes through Flip-flop D A, B, C, D, E, F = 1;

Here's my code:

    #include "flipflopD.h"

    boolean a1,b1,c1,d1,e1,g1;//display 1
    boolean a2,b2,c2,d2,e2,f2,g2;//display 2
    boolean Aa=false;
    boolean Bb=false;
    boolean Cc=false;
    boolean Dd=false;
    boolean Ee=false;
    boolean Ff=false;
    boolean A=false;
    boolean B=false;
    boolean C=false;
    boolean D=false;
    boolean E=false;
    boolean F=false;
    boolean G=false;//receiver

    void setup() {

        //DISPLAYS
        pinMode(A0, OUTPUT);
        pinMode(2, OUTPUT);
        pinMode(3, OUTPUT);
        pinMode(4, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(6, OUTPUT);
        pinMode(7, OUTPUT);
        pinMode(8, OUTPUT);
        pinMode(9, OUTPUT);
        pinMode(10, OUTPUT);
        pinMode(11, OUTPUT);
        pinMode(12, OUTPUT);
        pinMode(13, OUTPUT);

        pinMode(A2, INPUT);// IR RECEIVER
    }

    void loop() {
        //  Counter
        G = digitalRead(A2);
        Aa = flipflopD((A||!B||!C||!D && !A||B||C||D||E||F||G), A, G);
        Bb = flipflopD((!A||B||!C||G && !A||B||F||!G && !A||B||E||!F && !A||B||D||!E && !A||B||C||!D && !A||!B||C||D||E||F||G), B, G);
        Cc = flipflopD((!A||C||!D && !A||C||!E && !A||C||!F && !A||C||!G && !A||!C||D||E||F||G), C,G);
        Dd = flipflopD((!A||D||!E && !A||D||!F && !A||D||!G && !A||!B||!C||D && !A||!D||E||F||G && !A||!B||C||!E||!F||!G), D, G);
        Ee = flipflopD((!A||E||!F && !A||E||!G && !A||!E||F||G && A||!B||!C||!D||E && !B||!C||!D||!E||F||G), E, G);
        Ff = flipflopD((!A||!F||G && !A||F||!G && !B||!C||!D||!F||G && !B||!C||!D||F||!G && A||!B||!C||!D||E||G), F, G);

        A=Aa;
        B=Bb;
        C=Cc;
        D=Dd;
        E=Ee;
        F=Ff;

        //   ABCDEF TO 7 Segments
        a1 = !A||B||D && !A||B||C & A||!B||!C||!D;
        b1 = !A||B && !A||C||E && !A||C||D && A||!B||!C||!D;
        c1 = !A||!B||C||E && !A||!B||C||D && !A||C||D||E && !A||B||!C||!D + A||!B||!C||!D;
        d1 = !A||B||D && !A||B||C && A||!B||!C||!D;
        e1 = !A||B||!C||D && !A||B||D||!E && !A||B||C||!D;
        g1 = !A||B||D && !A||B||C & A||!B||!C||!D;

        a2 = (!A||!C||E  &&  !A||!B||!D||!F  &&  !A||!B||D||F && !A||!B||C||!E && !A||C||D||!E && !A||B||!C||!F && !A||B||!D||F && !A||B||E||!F && !B||!C||!D||E||F && A||!B||!C||!D||!E);
        b2 = (!A||B||D && !B||!C||!D||!E && !B||!C||!D||!F && !A||!B||!E||!F && !A||!C||!D||F && !A||!C||!D||E && !A||!C||E||F && !A||!D||E||F && !A||!B||C||!E && !A||!B||C||!F && !A||C||!E||!F);
        c2 = (!A||F && !A||!D||!E && !A||C||E && !A||B||!D && !A||B||!E && !B||!C||!D||F && !A||!B||!C||D && A||!B||!C||!D||E);
        d2 = (!A||!B||!C||!D||!F && !A||!B||!C||E||!F && !B||!C||!D||E||F && !A||!C||D||!E||F && !A||!B||C||!D||!E && !A||!B||C||!E||!F && !A||C||!D||!E||!F && !A||!B||C||E||F && !A||C||!D||E||F && !A||C||D||E||!F && !A||B||!C||!E||F && !A||B||!D||E||!F && !A||B||!C||D||!E && !A||B||!C||D||F && !A||B||D||!E||F && A||!B||!C||!D||!E);
        e2 = (!A||!C||!D||!F && !A||!C||E||!F && !A||!D||E||!F && !A||B||D||!F && !B||!C||!D||!E||!F && !A||!B||C||!E||!F);
        f2 = (!A||!C||!E||!F && !A||C||!D||!E && !A||C||E||!F && !A||B||C||!E && !A||!B||!C||D||!E && !A||!B||!C||D||!F && !A||!B||C||D||E && !A||B||!C||!D||E && A||!B||!C||!D||E);
        g2 = (!A||C||!E && !A||!C||!D||E && !A||!C||E||!F && !A||!B||D||!E && !A||!B||C||D && !A||B||!D||!F && !A||B||!C||E && A||!B||!C||!D);

        // OUTPUTS

        //DISPLAY 2
        digitalWrite(A0,a2);
        digitalWrite(2,b2);
        digitalWrite(3,c2);
        digitalWrite(4,d2);
        digitalWrite(5,e2);
        digitalWrite(6,f2);
        digitalWrite(7,g2);

        //DISPLAY 1
        digitalWrite(8,a1);
        digitalWrite(9,b1);
        digitalWrite(10,c1);
        digitalWrite(11,d1);
        digitalWrite(12,e1);
        digitalWrite(13,g1);
    }

Here's my Flip-FlopD:

    boolean flipflopD(boolean D, boolean Q, boolean CLK){
      boolean Qo=false;
        if (CLK=true) {
          Qo=D;
        } else {
      Qo=Q;
      }
      return Qo;
    }

Can someone tell me what's wrong?

body:
One potential error source: In your D-Flip-Flop code, you have

    boolean flipflopD(boolean D, boolean Q, boolean CLK){
      boolean Qo=false;
        if (CLK=true) {
          Qo=D;
        } else {
      Qo=Q;
      }
      return Qo;
    }

You probably want to do a comparison with double `==` instead of an assignment with `=` in the line

    if(CLK=true)

This causes the `if` to always evaluate to `true` and set `Qo=D`.

Also, I am not really sure if this is what you want:

    a1 = !A||B||D && !A||B||C & A||!B||!C||!D;

First, you're mixing `&&` (logical-and) with the bitwise `&` here. Next, C++ [operator precedence][1] dictates that the `&& `has a higher priority than `||`. This looks like a conjunctive-normal-form of some boolean function, thus I would group the AND terms in parenthesis, like

    a1 = (!A||B||D) && (!A||B||C) && (A||!B||!C||!D);

In the `c1` expression you are also suddenly using the `+` operator in a chain of logical expressions, which looks wrong.

Overall I don't quite get how this should work. If you have an IR receiver connected to A2, from which you read the "CLK" input, it will get some 39kHz input wave when you point a IR remote at it and press a button. And you want that on each CLK rise/fall the Arduino reacts to it by calculating the output for a seven-segment display? Your Arduino Uno/Nano with its 16MHz will take some time to execute each of the statements in the loop, sequentally. So what you're doing is actually sampling the A2 input every now and then -- how often exactly, I don't know, maybe with a few kilohertz. Your Arduino might sample the input at the wrong time or not fast enough to react the way you expect. `digitalRead` and `digitalWrite` are notoriously slow, maybe try direct port access or an interrupt-based approach. Of course, calculating all these AND, OR and NOT expressions will take some processing time, too.

This sort of combinational logic is more suited for an FPGA implementation, not for an Arduino.

  [1]: https://en.wikipedia.org/wiki/Operators_in_C_and_C++#Operator_precedence


message:
sbi() and cli() implementation

I've often seen `cli()` and `sbi()` in Arduino code. I usually don't mind them as I know what they do (clear or set the bit given as second argument in the register of the microcontroller given as first). I've always thought that those functions where only a clear way to perform simple bit manipulation, which can be quite error-prone. Something like that:
`#define cli(reg,bit) (*reg &= ~(1 << bit) ` and `#define sbi(reg,bit) (*reg |= (1 << bit))`.

Then I found out that the actual implementation is as follows:

    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

It's quite like I used to think... but with two extra macros.
I looked for them in the Arduino libraries:

    #define _BV(bit) (1 << (bit))

and

    #define _SFR_BYTE(sfr) _MMIO_BYTE(_SFR_ADDR(sfr))

which contains

    #define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

and

    #if _SFR_ASM_COMPAT
    #if (__SFR_OFFSET == 0x20)
    #define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)
    #elif !defined(__ASSEMBLER__)
    #define _SFR_ADDR(sfr) (_SFR_IO_REG_P(sfr) ? (_SFR_IO_ADDR(sfr) + 0x20) : _SFR_MEM_ADDR(sfr))
    #endif
    #else  /* !_SFR_ASM_COMPAT */
    #define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)

Further research took me to definitions I couldn't understand (for example because they are explained in comments using a lot of acronyms I don't know).
So I have the following questions:

* Why is `sfr` casted to `*(volatile uint8_t *)`?
* What do the acronyms used in that code mean? (`ASM`, `SFR`, `MMIO`)
* Under what circumstances is `__ASSEMBLER__` defined, and where (in which file)?
* Why can't we simply write `#define cli(reg,bit) (*reg &= ~(1 << bit) ` and `#define sbi(reg,bit) (*reg |= (1 << bit))`?

body:
> Why is sfr casted to *(volatile uint8_t *)?

Because you want the *content* (the first `*`) of a memory address that you specify, and you need it volatile so it doesn't cache it. Oh, and it's an 8-bit value.

> What do the acronyms used in that code mean? (ASM, SFR, MMIO)

ASseMbly, Special Function Register and Memory Mapped Input/Output

* ASM means assembly language.
* A Special Function Register is something like DDRB.
* Memory Mapped IO is a way of interacting with peripherals by reading from and writing to locations in the normal memory address space.

> Under what circumstances is `__ASSEMBLER__` defined, and where (in which file)?

It is defined by the compiler when you are compiling an assembly file.

> Why can't we simply write `#define cli(reg,bit) (reg &= ~(1 << bit)` and `#define sbi(reg,bit) (reg |= (1 << bit))`?

Because `reg` is just an address. You need to convert that into a variable in memory that you can reliably access (hence the *volatile*). Further to that, not all chips use MMIO for all peripherals - some can be accessed by more efficient IO instructions. That said, in many cases yes you can just use simpler code. After all, things like `DDRB |= 0x04` works fine. It all depends on how the value to pass as `reg` is defined originally. By forcing a specific `volatile` cast you can ensure that whatever way it was defined (with or without volatile, etc) it will work.


body:
On Atmel (now Microchip) AVR microcontrollers, the sbi, cbi, sbis, and sbic assembly language instructions can only address the 32 IO ports at addresses between 0x20 and 0x3f. The Atmega168 and 328 (used in Arduinos prior to the Leonardo) has WAY more than 32 IO registers, so only a subset of them can be addressed by sbi and cbi (the AVR instruction set was nailed down YEARS ago, when 32 IO registers seemed like more than enough).

As a result, operations that set or clear a single bit in those 32 IO registers can be performed by a single instruction which executes in two clock cycles, but the same operations on the remaining IO registers require a full-blown load-operate-store sequence that takes at least three cycles to execute.

From what I recall, AVRlibC had multiple macros that did almost the same thing, but had different use cases:

* One would compile to the fastest and most efficient instruction(s) available for that particular IO address.

* One would always compile to sbi/cbi, and would throw a compiler error if you tried to access a register outside of 0x20-0x3f

* One would ALWAYS compile to the load-act-store sequence, without regard to whether or not it could have used sbi/cbi instead.

* One would always compile to the load-act-store sequence, but would throw a compiler error if you tried using it on an address between 0x20 and 0x3f.

Basically, the choice enabled you to decide between optimized (but variable) performance, uniformly-slow (but deterministic) execution time, or the fastest-possible (but deterministic-at-compile-time) variant [which required that the programmer be aware of whether the register in question was within or above 0x20-0x3f].


message:
Getting the voltage of an 18650 battery with an Arduino

I'm using a Arduino Pro Mini (5v) to sense the voltage of an 18650 battery. The battery (that is being sensed)is also used to power the Pro Mini but the MCU is behind a boost-converter which outputs 5.05v. Would I be able sense the right voltage of the battery?

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

<!-- End schematic -->

The boost converter has an input voltage ranges to 0.9 to 5 volts and current of 600mA.

body:
Yes, if Vin- and Vout- are joined together inside the boost converter or share a common ground on the boost converter circuit board such as this one:

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

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

  [1]: https://i.stack.imgur.com/ANX1b.png
  [2]: https://i.stack.imgur.com/1zNkF.png


message:
How can i check for valid fingerprint and no finger detected?

i am working in arduino fingerprint sensor with adafruit. i am using two leds to check if fingerprint is valid. my problem is that i need three cases instead of two.
1 case: when fingerprint is valid. turn on green led and turn off red led.
2 case: when fingerprint is not valid. turn on red led and turn off green led. i put a finger but was a not valid finger.
3 case: when there is no finger detected, turn off both leds.
Is there a way to do that?

i am using adafruit library and fingerprint sensor, with fingerprint.ino and using pin 11 and 12 for output.

body:
When there is no finger on the sensor, the function `Adafruit_Fingerprint.getImage()` from the Adafruit Fingerprint library returns the constant `FINGERPRINT_NOFINGER`. You can execute the function in a loop and setting the LED outputs in a `switch` statement according to the return value. Refer to the examples of the [Adafruit Fingerprint Sensor Library][1]. There you have directly the code for checking the sensor (since the full check for a valid fingerprint is longer than this one function call, you can use the `getFingerprintIDez()` function from the `fingerprint` example, or a variation of it).

  [1]: https://github.com/adafruit/Adafruit-Fingerprint-Sensor-Library


message:
How to delay properly inside ISR

I am currently working on a little code which needs to react fast. Here is what I am trying to accomplish:

Using a sine wave phase detector I am detecting every zero crossing and feeding that pulse into the Arduino.

Using an ISR the Arduino detects this zero crossing pulse using RISING. Once one pulse has been detected AND I have pressed a button, I need there to be a delay of 0 - 10ms before switching on an output.

If I don't use an ISR and set a delay of up to 10ms inside the loop, it won't really be 10ms and it will be some other delay, nothing consistent. (I checked with an oscilloscope).

Only when using an ISR and using delayMicrosenconds() inside the ISR I can delay the output consistently for up to 10 ms everytime.

Now I have read that doing this is wrong...Even though it works perfectly. Which better way could I use?

Thanks!

EDIT: While 100% accuracy may not be possible, it needs to be as precise as possible. More important is the repeatability. Using my method I could reproduce the outcome everytime with an accuracy in the nano seconds range.

body:
It's quite simple: You don't.

Instead you use your initial ISR to configure and enable one of the ATMega's Timer peripherals. Set that to the length of your required delay - then the ISR exists.

When the chosen time has passed the timer interrupt triggers, and you use *that* interrupt to turn on your output.


message:
Peer to Peer using Ethernet Module

I'm beginner here at arduino stuff. i just started learning arduino and i have this small homework where i NEEDED to connect 2 arduino using ethernet shield or module ONLY over a distance of 20 meters.

I don't have my modules yet but i want to atleast study it now while i'm waiting for it. I can't seem to see any tutorials about it nor anyone tried it. How can i do this? i hope you can help me and give some insights, links, etc reference. Thanks :)

EDIT:
I had in mind where these arduino will have their own identity, 1st arduino will be receiving only some data coming from 2nd arduino. The 2nd arduino will have sensors and read them then sends them to 1st arduino. Now, i like my 2nd arduino to have a power source coming from the 1st arduino to save power supply installation and since it'll be like a remote arduino. Thus has anyone has experience applying PoE on arduino?

body:
You will need a [crossover cable][1] to connect two Ethernet shields peer to peer.

Then you configure the Ethernet library to use static IP address. Use 192.168.1.1 and .2 address. (Or other 192.168.x.x address). Set subnet 255.255.255.0. Gateway should be the IP address of the other Arduino.

  [1]: https://en.wikipedia.org/wiki/Ethernet_crossover_cable


message:
Every loop other case

I need to achieve that in every loop my Arduino do other thing. Say in first loop do one thing, in second do second thing and in third loop do third thing. And again. And while doing one thing, other things are dead.

Not sure what approach to use.
This is just my 50 cents:

    for(int x=0; x<2; x++)
      {
      switch (x) {
        case 0:
          //do something
          break;
        case 1:
          //do something
          break;
        case 2:
          //do something
          break;
      }
      delay(1);
    }

I tried this from above but it stuck at case 0

Any point or link to explanation would be nice.

body:
Your implementation is in principle correct. However, tradionally, you don't incrementally loop over all states from 0 to end using a `for` loop. The implementation is more flexible if it allows the state to go to any other state if it needs to. This would be a normal *finite state machine* (FSM).

    #include <Arduino.h>
    /* How many states are possible? */
    #define MAX_STATES 2
    /* global state variable */
    int currentState = 0;

    /* prototypes */
    void Action1();
    void Action2();

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

    void AdvanceStateByOne() {
     currentState = (currentState + 1) % MAX_STATES;
    }

    void loop() {
     //Execute the action dictated by the current state
     switch(currentState) {
      case 0:
       Action1();
       break;
      case 1:
       Action2();
       break;
      default: //Catch for un-implemented states
       break;
     }
     //Go to next state, incrementally.
     //This could also be modified in one of the functions above
     //Loop back to zero state after MAX_STATES using modulo operator
     AdvanceStateByOne();

     //for testing, introduce some delay
     delay(1000);
    }

    void Action1() {
     Serial.println("Action 1");
    }

    void Action2() {
     Serial.println("Action 2");
    }

This prints out "Action 1" and "Action 2" in a loop forever.

Now you could take this further and instead of using pure numbers for your states, you can use an `enum` representation of those to make the code clearer:

    enum state_t {
     STATE_DO_ACTION_1 = 0,
     STATE_DO_ACTION_2,
     STATES_END
    } ;

And then act on those accordingly. You can also use the C++ feature of a `enum class` to give you a nice notation like `State::SomeState1`.


message:
What is best way to get data from sensors if arduino is slave?

Im working on a project where i have motor controller(arduino nano) being i2c slave. Its job is to get RF24 data and control motor and at same time send data to master about motor... Currently i have 2 ultrasonic sensors for distance sensing and if they are too close it will stop motor. I want to add 2-4 more but it adds a lot of delay because of

    pulseIn();

command. I want to use attiny as sensor reader and just dump current data when requested.

Is it possible for arduino nano to be i2c slave (hardware i2c) and at same time i2c master (software i2c/please library without using timers... im short on them) or there is way to dump data in less than 2ms via serial or some other protocol? SPI is already used for RF24 and i need RF24 to be up all the time.

body:
On simultaneous master/slave: Yes and no. You can initiate the `Wire` library as slave and despite of than using `Wire.beginTransmission()` and it's siblings to send as a master. The library will configure the hardware as master only for the time it needs to send. But there are 2 problems:

 1. When you have multiple masters on the same bus, they have to continuously watch the bus, so that they are only starting a transmission, when the bus is free. The `Wire` library doesn't seem to do that.
 2. If two masters start their transmission at the same time, the data will be good, as long all transmitted bits are equal. For other cases the I2C protocol has a rule: When 2 masters start a transmission at the same time, the first one to write a `1` to the bus (HIGH value) has to immediately back of to slave mode. (This is because to write a `1` to the data line the pullup resistors are used. When another master tries to write `0` to the bus (LOW value on SDA) he wins against the pullups, effectively writing `0` to the port, and not `1`)

As mentioned on this [Github issue][1] there are some workaround, though I haven't tested them myself until now. All in all I2C multi-master may be to complex at this point.

As another option, you can use an extra line, connecting master and slaves (use the internal pullup on the masters side). Any slave can at any time write a `LOW` to this line, triggering the master to request data from all slaves (maybe via external interrupt or pin change interrupt).

Note: I don't know, for what purposes you used all your timers, but maybe there is a way to share one of them with other hardware, so that you don't have to use the blocking `pulseIn()` function. Or maybe you can tweak the timeout value of the function to a fitting value.

  [1]: https://github.com/arduino/Arduino/issues/1313


message:
Arduino - Push Button State Problem

My problem is I want the buzzer to stop after a certain amount of time, regardless if it is still pressed or not.

I have tried to implement a boolean statement to the code but to no avail(I'm not very good at this)

Can someone shed some light as to how I do this?

The code already times out after 1000ms when your finger is lifted off the buttin so I got that far but cant get any further.

Here is what I have.

Any other suggestions are also welcome as I know its not the prettiest or best implemented but i was just happy it worked for me.

    // Setting The Pin Numbers
    const int touchsensor = 2;                      // the number of the touchsensor pin
    const int buzzer =  4;                          // the number of the LED pin

    // variables:
    int touchsensorState = 0;                       // variable for reading the
    touchsensor status
    unsigned long timestamp = 0;
    unsigned long timeout = 1000;

    void setup() {

      pinMode(buzzer, OUTPUT);                      // initialize the buzzer as an output
      pinMode(touchsensor, INPUT);                  // initialize the touchsensor as an input
     }
    void loop() {

       touchsensorState = digitalRead(touchsensor);  // read state of the pushbutton value:

       if (touchsensorState == HIGH) {                 // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
         digitalWrite(buzzer, HIGH);                 // buzzer will emit sound:
         timestamp = millis();                       // Timing button press
       }

       if(millis() - timestamp > timeout) {
       digitalWrite(buzzer, LOW);                  // buzzer will not sound:
       }
    }

body:
you will need to implement a edge sensor. Add a `previousTouchsensorState` to the globals and replace the if where you check the sensor state with:

    if(previousTouchsensorState == LOW && touchsensorState == HIGH) {
         // check if the touch sensor is pressed and wasn't the last time though the loop.
         // If it is, the touchsensorState is HIGH and previousTouchsensorState is LOW:
         digitalWrite(buzzer, HIGH); // buzzer will emit sound:
         timestamp = millis();       // Timing button press
    }
    previousTouchsensorState  = touchsensorState;


message:
DHT 11 sensors and i2c LCD to Wemos Wifi not Working

Its my first time make arduino project. I make wemos d1  project using DHT11 temperature sensor and LCD 20x4 with i2c. **The temperature data will display in LCD and sending to the bot telegram.** **For sending to the bot telegram it works, but why the data cannot display to the LCD?** When I tried common charachter like "Hello World!" in the LCD it works. Can you help me? What should I do? Thanks before.

    #include "DHT.h"
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE);
    #define DHTPIN D14
    #define DHTTYPE DHT11

    byte degree[8] = {
      0b00110,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000
    };

    DHT dht(D14, DHT11);

    void setup() {
      lcd.createChar(0, degree);
      Serial.begin(115200);
      Serial.println("DHT11 test!");
      lcd.begin (20, 4);
      dht.begin();
    }

    void loop() {
      delay(2000);
      float h = dht.readHumidity();
      float t = dht.readTemperature();

      lcd.setCursor(0, 0);
      lcd.print("Humi : ");
      lcd.print(h);
      lcd.print(" %");

      lcd.setCursor(0, 1);
      lcd.print("Temp : ");
      lcd.print(t);
      lcd.print(" C");
    }

body:
Constant `D14` is for Wemos D1 and other esp8266 dev boards mapped in arduino core to esp8266 io pin 4. Pin 4 is used as I2C SDA pin. The LCD uses I2C so pin 4 (D14) can't be used for the sensor.

from `pins_arduino.h` for Wemos D1 R1:

    #define PIN_WIRE_SDA (4)
    #define PIN_WIRE_SCL (5)

    static const uint8_t D14  = 4;
    static const uint8_t D15  = 5;

The origin of this confusing esp8266 io pin to Dx constants mapping is the big Wemos D1. There are esp8266 pins mapped to standard Uno pinout.

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

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


message:
WS2812 HELP. Need name of Unkown component

https://i.stack.imgur.com/pbYn6.png

I need to know what the little "thing" that i marked in blue is and how it works.

Thanks.

picture taken here: https://www.sparkfun.com/products/13282

body:
It's a capacitor. Specifically a decoupling capacitor of somewhere around 100nF to 1uF.

It works by storing an electrical charge in two plates with a dielectric between them. That specific type is a Multi-Layer Ceramic Capacitor and looks to be 0603 in size.


body: It's a capacitor connected between 5V and GND and it smooths out voltage spikes for a cleaner power supply to the chip. A cleaner power supply means the circuitry in the chip can more easily pick out the data signal (i.e., the reference voltage is more constant, so the actual signal appears more stage.)


body:
It's most likely a decoupling capacitor meant to smooth out the voltage supply to the internal control chip.

This is standard practice to add to any chip. Power cables create a small bit of parasitic inductance in relation to the area between the lines. This inductance can induce voltage spikes when current draw changes significantly. A capacitor shrinks the effective area between the power lines.

This is also why the general advice for decoupling capacitors is to put them as close to the chip as physically possible.


message:
Fade out lightbulb 220V

I am trying to make a lightbulb fade to dark and back to light, for which I found the following tutorial online:
[http://bildr.org/2012/03/rfp30n06le-arduino/][1]

Unfortunately, the tutorial makes use of a 60V light source while my intention is to use the system on 220V. Would it be enough to solve my problem to replace the 60V MOSFET in the system with one of 220V?
What would otherwise be a solution?

Thank you very much for your help!

  [1]: http://bildr.org/2012/03/rfp30n06le-arduino/

body:
Absolutely not. Not under any circumstances.

Dimming AC is a considerably harder task, and doing it with 220VAC can be deadly.

To do it you need:

* A zero-crossing detection circuit
* A TRIAC driver circuit
* A suitable TRIAC to do the switching
* Software that will use the zero crossing information to time the switch-on of the TRIAC to a certain point in the waveform.

And most importantly:

**Good knowledge of working with mains electricity - without which you will probably kill yourself or those around you.**


body:
You can buy 220V dimmer modules controllable with 5V PWM from Arduino. [Here is one][1] controllable with [this PWM digital potentiometer module.][2]

I use Kemo 4000VA regulator module with that M150 digital pot module controlled with Arduino PWM for heater regulation.

[![enter image description here][3]][3]

  [1]: https://www.kemo-electronic.de/en/Transformer-Dimmer/Controller/Modules/M012-Power-Control-110-240-V-AC-1200-VA.php
  [2]: https://www.kemo-electronic.de/en/Transformer-Dimmer/Converter/M150-DC-pulse-converter.php
  [3]: https://i.stack.imgur.com/YoVjt.jpg


message:
How do I use digital pin on sensor to analog on arduino uno

I am working on a autonomous fire extinguisher.i have run out of pins.I have the following question in my mind while working on my project

Is it necessary that the DO pin in a flame sensor must be in a PWM digital pin in Arduino.i have this doubt since when I connected it to non PWM pin it didn't worked.

Secondly it is possible for me to use the analog pin in Arduino for the DO pin of the flame sensor or trigger/echo pins of the ultrasonic sensor.

Thanks.

body:
PWM stands for Puls Width Modulation and is only available when the Digital Pin is in OUTPUT mode.

And **YES**, you can connect the flame sensor's D0 to any digital pin on the Arduino.

And yes it is possible to connect the flame sensor's D0 to a analog pin, but why not use the A0 from the flame sensor and connect it toi a analog pin on the Arduino?


body:
You can use the analog pins (A0-A5, but not A6 and A7) also as digital pins. So you can set one of them as digital input, connecting it with the D0 pin of your fire sensor. You can read this pin with `digitalRead(pin)`.

Regarding your problem with PWM:
There is no "PWM input" on an Arduino Nano (because PWM hardware in a microcontroller means pulse with modulated output). The example code of your sensor uses an analog input (ADC: Analog Digital Converter) (with usage of `analogRead()`). If you want to use this functionality you have to connect the A0 pin of your sensor to one of A0-A7 and reading it with `analogRead()` to get the fires intensity/distance.


message:
Is checking an if statement every loop/while iteration inefficient?

I have code that changes a bool only time in the setup(), and in my loop() I have

    if (setupBool) {
    // ...
    } else {
    // ...
    }

Is checking the bool every loop slower than having a while(true) with the same code?

And what about checking it in every loop in a while(true)?

Is there any reason I shouldn't do those?

body:
Of course an if statement cost time, although very little. However, it changes (although once), so if you need to vary depending on the value, you have to use the if statement.

A while(true) also cost a little time (a little bit less), but less than 1 us, same as the if statement. You can do perfectly do an if statement within the while(true), but remember, the loop itself is behaving like a while(true) already.

However, I wouldn't concern at all about optimizing performance, unless:

- You know beforehand you will need the fastest code possible
- You have already performance issues

Always prefer readability/maintainability about performance.


body:
The actual full structure of the loop function is like this:

* while(true)
   * Call loop()
      * if (condition)
         * Run your code
      * else
         * Run your other code
   * Check for serial data

By putting a `while(true)` inside your `if` you:

* Remove the overhead of calling `loop()` every time
* Remove the overhead of checking for serial data (that is what the `SerialEvent` system is all about)
* Remove the overhead of checking the `if` every iteration.

So the executing part of your code now looks like:

* while(true)
   * Run your code.

If your code needs to run in a tight loop it can provide some speed improvements, yes, but at the cost of:

* No SerialEvent processing (normal Serial works, but the SerialEvent system breaks)
* Harder to "get out" of the loop to do something else (although `break` can help with that).
* On ESP8266 boards the watchdog will time out unless you manually `yield()` regularly.

Would I suggest doing it? Well, there are times when it can be beneficial, but those times are few and far between. If you don't *need* to do it then, in general, don't do it.


message:
Arduino Nano joystick x2 / potentiometer

will i be able to connect up all these parts to an arduino Nano
i noticed i will need to connect to the nanos v5 to the 2 joysticks and potentiometer slider if i share the voltage will it still function as intended
[![enter image description here][1]][1]
**Parts**

x1 = USB Arduino Nano V3.0 ATMEGA328P CH340G 5V 16M Micro-Controller Arduino

x2 = 3D Analog Joystick for Sony PSP 1000 Consol
+5v (possible 10kOhm resistance)

x1 = Electronic slider 10K potentiometer Slider Module for Arduino
Voltage: 3.3V or 5V / Resistance: 10K

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

body:
Yes, this should work. The potentiometer slider will source about 5mA and each joystick axis about 50mA. In total this gives you 205mA. Here it is important, that your power source can provide enough current. If you are using an USB port from your computer, this would result in 500mA maximum that can be drawn from the bus. Since this is shared with the Arduino you can externally use about 400mA

For more information about current ratings refer to [this question][1]

EDIT: Since your previous resistance values were not correct, I edit my answer.

When all potentiometers have 10kOhm resistance (and this seems to be more likely the right values), each one draws about 5mA from the 5V pin (You can calculate this with Ohm's Law `U = R * I`, which gives you `I = U / R`. So you have to divide the voltage by the resistance.). So you aren't getting anywhere near the problematic currents. These potentiometers are designed this way. They don't want to draw a high amount of power, but only setting a certain voltage to the output pin.

  [1]: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins


message:
Error in code (define a function)

I try to use this code, but it shows that I need to define again the last void turn_mer (int direction) function. How can I fix this?

    #include <Servo.h> //create servo object to control a servo.
    Servo myservo;

    //pin configuration.
    const byte servoPin = 2; const byte motorLeft = 5; const byte motorRight = 6;
    const byte echoPin = 12; const byte trigPin = 13; const byte echoPin2 = 8; const byte trigPin2 = 9; // LET OP DE HOOFDLETTERS: echopin en echoPin
    //delay determines how long the MER turns, increase to make the turning angle larger.
    const int turnDelay = 500;
    //standard angle for looking straight ahead, compensate for construction errors.
    const int standardAngle = 90;
    //angle in degrees that controls the direction in which the sensor looks.
    const int viewAngle = 40;
    //delay to let servo turn, not optimized; for smaller angles smaller delay could be used.
    const int servoDelay = 250;
    //object distance in cm at which the MER decides to look around and turn another way.
    const int lineOfSight = 40;
    //pwm duty cycle of the motor, use a value from 0 (no movement) to 255 (full speed).
    const int motorSpeed = 90;

    //const int lineDownSight = 35;
    void setup() //setup pin configuration and initialize the sensor position.

    { delay(3000); //delay to give us some time to place the MER on the ground.
      myservo.attach(servoPin); //initialize the servo and look straight ahead.
      turn_servo(standardAngle);
      pinMode(motorLeft, OUTPUT); pinMode(motorRight, OUTPUT);
      pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); drive_mer();
    } //start the mer.
    void drive_mer() //this function lets the MER drive forward.
    {
      analogWrite(motorLeft, motorSpeed);
      analogWrite(motorRight, motorSpeed);
    }
    void stop_mer() //this function stops the mer.
    {
      digitalWrite(motorLeft, LOW);
      digitalWrite(motorRight, LOW);
    }
    void turn_servo(int angle)
    //turn servo to given angle, do not return until angle is reached.
    //if the servo is already at the correct angle, we don't have to do anything.
    { if (angle == myservo.read()) {
        return;
      }
      else {
        myservo.write(angle);
        delay(servoDelay);
      }
    }

    int look1() //looking function, returns distance in the observed direction as an integer.
    { int duration, distance;
      digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH);
      delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1; return distance;
    }
    //turning function: makes MER turn in preferred direction. 0 for left and 1 for right.
    void turn_mer(int direction)

    { if (direction == 0) {
        digitalWrite(motorLeft, LOW);
        digitalWrite(motorRight, HIGH);
      }
      else {
        digitalWrite(motorLeft, HIGH);
        digitalWrite(motorRight, LOW);
      }
      delay(turnDelay); stop_mer();
    }//stop the engines when the MER has turned far enough.

    //this function turns the MER depending on the observed distances.
    void handle_measurements(int distanceLeft, int distanceStraight, int distanceRight)// int distanceDown

    { if (distanceLeft < lineOfSight and distanceStraight < lineOfSight and
          distanceRight < lineOfSight) {
        stop_mer();
      }

      else if (distanceLeft < lineOfSight) {
        turn_mer(1);
        drive_mer();
      }

      else if (distanceStraight < lineOfSight) {
        if (distanceRight > distanceLeft)
        {
          turn_mer(1);
        } else {
          turn_mer(0);
        } drive_mer();
      }

      else if (distanceRight < lineOfSight) {
        turn_mer(0);
        drive_mer();
      }
     //if (distanceDown > lineDownSight) {
      //  stop_mer();
      }

      void loop()
      { int distanceLeft, distanceStraight, distanceRight;

        turn_servo(standardAngle + viewAngle); distanceLeft = look1();
        turn_servo(standardAngle); distanceStraight = look1();
        turn_servo(standardAngle - viewAngle); distanceRight = look1();
           handle_measurements(distanceLeft, distanceStraight, distanceRight);}

    /*  void handle_measurements(lineDownSight)
       {(distanceDown > lineDownSight) {
        stop_mer();
      }*/
      //                                                                                sensor 2
      //______________________________________________________________________________________________________________________________________________________________________________________________________

     const int lineDownSight = 35;

      void handle_measurements (int distanceDown)

    {if (distanceDown > lineDownSight) {
        stop_mer();}}

      int look2() //looking function, returns distance in the observed direction as an integer.
      { int duration, distance;
        digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH);
        delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH);
        distance = (duration / 2) / 29.1; return distance;
      }
      //turning function: makes MER turn in preferred direction. 0 for left and 1 for right.
    void turn_mer (int direction)

    {handle_measurements(distanceDown)}

body:
But the main problem is that in C, you can only define a function with the same name once.

Halfway you defined the function turn_mer already, and again at the end.

Also, you are missing an end colon in:

    {handle_measurements(distanceDown)}

It's better to align your code like:

    {
        handle_measurements(distanceDown);
    }