body:
I have problem in using 2 fingerprint scanner in arduino mega, every time I need to register I need to go and register my fingerprint on each fingerprint module,

> what i am planning to do is when I registered on 1 fingerprint scanner
> then the other fingerprint module automatically registered the
> fingerprint and vise versa.

 Can anyone help me with my project thanks. btw my project was already working but I have problems in registration of bio-metrics.

here is my code in verifying the registered fingerprint

    #include <Adafruit_Fingerprint.h>
    int door1 = 8;
    int door2 = 11;
    Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&Serial2);
    //fplabas
    Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&Serial3);
    void setup() {
    Serial.begin(9600);

    pinMode(door2, OUTPUT);
      pinMode(door1, OUTPUT);
    //  pinMode(Buzzer, OUTPUT);
    //
      digitalWrite(door2, HIGH);
      digitalWrite(door1, HIGH);

     finger1.begin(57600);
      finger2.begin(57600);
        if (finger1.verifyPassword() || finger2.verifyPassword()) {
        Serial.println("Found fingerprint sensors!");
      } else {
        Serial.println("Did not find any fingerprint sensors :(");
        while (1) { delay(1); }
      }

      finger1.getTemplateCount();
      finger2.getTemplateCount();

      Serial.print("Fingerprint Sensor1 contains "); Serial.print(finger1.templateCount); Serial.println(" templates");
      Serial.print("Fingerprint Sensor2 contains "); Serial.print(finger2.templateCount); Serial.println(" templates");
      Serial.println("Waiting for valid finger...");
    }

    void loop () {
      getFingerprintdoor2();
      delay(50);
      //Fingerprint Sensor Labas
      getFingerprintdoor1();
      delay(50);
    }

    uint8_t getFingerprintdoor2() {
      uint8_t p = finger1.getImage();
      switch (p) {
        case FINGERPRINT_OK:
          //Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
         // Serial.println("No finger detected");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
        //  Serial.println("Communication error");
          return p;
        case FINGERPRINT_IMAGEFAIL:
          //Serial.println("Imaging error");
          return p;
        default:
          //Serial.println("Unknown error");
          return p;
      }
      // OK success!

      p = finger1.image2Tz();
      switch (p) {
        case FINGERPRINT_OK:
          //Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          //Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
         // Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
         // Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
         // Serial.println("Could not find fingerprint features");
          return p;
        default:
          //Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      p = finger1.fingerFastSearch();
      if (p == FINGERPRINT_OK) {
        Serial.println("Found a print match!");
        digitalWrite(door2, LOW);
    //    sendsms(textForSMS + " Noah", f1001);
    //    Serial.println(textForSMS);
    //    Serial.println("message sent.");
        delay(3000);
        digitalWrite(door2, HIGH);
        delay(1000);
       // Serial.print(finger1.fingerID);
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        //Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_NOTFOUND) {
    //    Serial.println("Did not find a match");
    //    digitalWrite(Buzzer,LOW);
    //    delay(1000);
    //    digitalWrite(Buzzer,HIGH);
        return p;
      } else {
        //Serial.println("Unknown error");
        return p;
      }

      return finger1.fingerID;
    }

    uint8_t getFingerprintdoor1() {
      uint8_t p = finger2.getImage();
      switch (p) {
        case FINGERPRINT_OK:
          //Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
         // Serial.println("No finger detected");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
        //  Serial.println("Communication error");
          return p;
        case FINGERPRINT_IMAGEFAIL:
          //Serial.println("Imaging error");
          return p;
        default:
          //Serial.println("Unknown error");
          return p;
      }

      // OK success!

      p = finger2.image2Tz();
      switch (p) {
        case FINGERPRINT_OK:
          //Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          //Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
         // Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
         // Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
         // Serial.println("Could not find fingerprint features");
          return p;
        default:
          //Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      p = finger2.fingerFastSearch();
      if (p == FINGERPRINT_OK) {
        Serial.println("Found a print match!");

        digitalWrite(door1, LOW);

       delay(5000);
        digitalWrite(door1, HIGH);

      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        //Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_NOTFOUND) {

        return p;
      } else {
        //Serial.println("Unknown error");
        return p;
      }

      // found a match!
      return finger2.fingerID;
    }

And here is the problem code where I need to register on both Fingerprint scanner:

    #include <Adafruit_Fingerprint.h>
    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial2);

    Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&Serial3);

    uint8_t id;

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);  // For Yun/Leo/Micro/Zero/...
      delay(100);
      Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

      // set the data rate for the sensor serial port
      finger.begin(57600);

      if (finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) { delay(1); }
      }
    }

    uint8_t readnumber(void) {
      uint8_t num = 0;

      while (num == 0) {
        while (! Serial.available());
        num = Serial.parseInt();
      }
      return num;
    }

    void loop()
    {
      Serial.println("Ready to enroll a fingerprint!");
      Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");

     if (Serial.available()>0)
       switch(Serial.read())
      {
        case 'A':

            id = readnumber();
            if (id == 0) {
               return;
            }
            Serial.print("Enrolling ID #");
            Serial.println(id);

            while (!  getFingerprintEnroll1() );

          break;

           case 'B':

            id = readnumber();
            if (id == 0) {
               return;
            }
            Serial.print("Enrolling ID #");
            Serial.println(id);

            while (!  getFingerprintEnroll2() );

          break;

    }

    }

    uint8_t getFingerprintEnroll1() {

      int p = -1;
      Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger.image2Tz(1);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      Serial.println("Remove finger");
      delay(2000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER) {
        p = finger.getImage();
      }
      Serial.print("ID "); Serial.println(id);
      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.print(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger.image2Tz(2);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      Serial.print("Creating model for #");  Serial.println(id);

      p = finger.createModel();
      if (p == FINGERPRINT_OK) {
        Serial.println("Prints matched!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_ENROLLMISMATCH) {
        Serial.println("Fingerprints did not match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      Serial.print("ID "); Serial.println(id);
      p = finger.storeModel(id);
      if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
      } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
    }

    uint8_t getFingerprintEnroll2() {

      int p = -1;
      Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
      while (p != FINGERPRINT_OK) {
        p = finger2.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger2.image2Tz(1);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      Serial.println("Remove finger");
      delay(2000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER) {
        p = finger2.getImage();
      }
      Serial.print("ID "); Serial.println(id);
      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK) {
        p = finger2.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.print(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger2.image2Tz(2);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      Serial.print("Creating model for #");  Serial.println(id);

      p = finger2.createModel();
      if (p == FINGERPRINT_OK) {
        Serial.println("Prints matched!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_ENROLLMISMATCH) {
        Serial.println("Fingerprints did not match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      Serial.print("ID "); Serial.println(id);
      p = finger2.storeModel(id);
      if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
      } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
    }

Please help I am stuck in this situation..

title: 2 Fingerprint scanner using 1 arduino

Answers: 1

body:
The library, that you are using, doesn't seem to support exporting or importing fingerprints. Though if you look into the [user manual][1] of the fingerprint sensor at the Adafruit site, there are two commands mentioned, that seem to do what you need:

> 6.2.2 Upload image:  UpImage

> Description: to  upload  the  image  in Img_Buffer  to  upper  computer.  Refer  to  1.1.1  for  more  about image buffer.

> 6.2.3 Download the image: DownImage
>
> Description: to download image from upper computer to Img_Buffer. Refer to 1.1.1 for more about the image buffer.

These commands can be used to read or write the image buffer, where an image is stored, when it was taken by the sensor (this is only about the image data, not about the recognition or enrolling; that has to be done after loading the image to the buffer). I could not find corresponding functions in the library, so I guess it doesn't support this. So, to get what you need, you need to stop using the library and handle the things yourself (or - maybe better - extend the library to incorporate that feature).

The manual has no good documentation about these functions and the datasheet, that Adafruit has, is in Chinese, so I couldn't read it. You will need to try it out and see, what you get, when issuing the mentioned commands (unless you can read Chinese and there is more useful information in that datasheet).

I guess after requesting the upload of the current image, the module will send data packets in the configured package size, until it has transferred the whole image (Note, that it will only send 4 bits for every pixel over UART, meaning 16-greyscale image). After than you could request the download on the other module. After the acknowledgement packet, I guess you need to send the image data in the same format, as you received it from the first module, in packets with the configured packet size.

When configured to the same packet size, you could request upload and download at the same time for each module and simply let the packets pass through. After transferring the image, you can start the recognition on both modules.

[1]: https://cdn-shop.adafruit.com/datasheets/ZFM+user+manualV15.pdf


body:
I'm attempting to control a DC vacuum pump to turn off when it hits a BMP-280 reads a set pressure lower than when it spins up (guesstimate pressure, I've got it hooked up to tweak in person). Everything works fine for pressure until I get to the `runPump()` subroutine, when the pressure callouts go from pascal to very large odd numbers.  I've tried variations of INT/FLOAT/LONG but I still either get a 0 pascal reading or an OVF. The BMP later in runPump does return pressure in pascal.
<!-- language-all: lang-cpp -->

    #include <Wire.h>    //This library allows you to communicate with I2C devices (BMP280)
    #include "i2c.h"     //same
    #include "i2c_BMP280.h"   //same
    BMP280 bmp280;
    int inches = 0;
    int motorPin2 = 10;
    int motorPin1 = 9;
    int triggerPin = 7;  // For ultrasonic sensor
    int echoPin = 4;    // For Ultrasonic sensor
    long duration;
    long distance;

    void setup() {

      pinMode(triggerPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);

      Serial.begin(9600);
      Serial.print("Probe BMP280: ");
      if (bmp280.initialize()) Serial.println("Sensor found");
      else
      {
        Serial.println("Sensor missing");
        while (1) {}
      }

      // onetime-measure:
      bmp280.setEnabled(0);
      bmp280.triggerMeasurement();
    }

    void trig() {
      Serial.println("Ping!");
      digitalWrite(triggerPin, LOW);
      delay(2);
      digitalWrite(triggerPin, HIGH);
      delay(10);
      digitalWrite(triggerPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      inches = (duration / 2) / 74;
      Serial.print("Inches: ");
      Serial.println(inches);
      delay(250);
    }

    void runPump() {
      //  Serial.println("Running Pump!!!!!!");
      //  #include <Wire.h>    //This library allows you to communicate with I2C devices (BMP280)
      //  #include "i2c.h"     //same
      //  #include "i2c_BMP280.h"   //same
      //  BMP280 bmp280;
      //  int motorPin1 = 10;
      //  int motorPin2 = 9;

      bmp280.awaitMeasurement();
      float  pascal;
      bmp280.getPressure(pascal);
      bmp280.triggerMeasurement();

      float runningpressure;
      float deflatepressure;
      runningpressure = (int) pascal;
      deflatepressure = (runningpressure - 600); //pascal minus a bit
      Serial.print("Starting pressure: ");
      Serial.println(pascal);
      Serial.print("Goal pressure: ");
      Serial.println(deflatepressure);

      while (runningpressure > deflatepressure) {
        Serial.println("Engaging Vacuum Pump!!!");
        digitalWrite(motorPin1, HIGH);
        digitalWrite(motorPin2, HIGH);
        delay(250);
        bmp280.awaitMeasurement();
        bmp280.getPressure(pascal);
        bmp280.triggerMeasurement();
        Serial.print("Current pressure: ");
        Serial.println(runningpressure);
        Serial.print("Goal pressure:");
        Serial.println(deflatepressure);
        Serial.print(runningpressure - deflatepressure);
        Serial.println(" more to go.....");
        delay(250);
      }
      //  else{
      Serial.println("Shutting Down!!!!!!!!!!!!!!");
      digitalWrite(motorPin1, LOW);
      digitalWrite(motorPin2, LOW);
      delay(2000);
      //  }
    }

    void loop() {

      bmp280.awaitMeasurement();
      float  pascal;
      bmp280.getPressure(pascal);
      bmp280.triggerMeasurement();
      Serial.print("Pressure: ");
      Serial.print(pascal);
      Serial.println(" Pa;");
      trig();

      if (inches > 4 && inches < 10) {
        runPump();
      } else
        digitalWrite(motorPin1, LOW);
      digitalWrite(motorPin2, LOW);
      delay(5);
    }

    //  Serial.println("Extruding Glove!@!!!");
    //  digitalWrite(motorPinR, HIGH);  //extrudes gloves
    //  delay(500);                      // waits .5 seconds
    //  digitalWrite(motorPinR, LOW);   // stops extruding

title: BMP280 pressure as a DC motor switch - issues

Answers: 0


body:
I am trying to make a psudo drum kit with my Arduino Due and a couple Force Sensitive Resistors (activated with my fingers, no drum sticks). So far in my testing I'm only using one FSR. I've attached an SD Card reader and put a WAV File on there (44100 Hz, 16-bit, stereo). In my 'Loop', I read in the resistance of the FSR to know if it's been triggered, then I play the WAV file accordingly. It works but its not that fast. If this project is going to work, the response time needs to be much faster.

Here's my code:

    #include "SD.h" //Lib to read SD card
    #include "SPI.h" //SPI lib for SD card
    #include <Audio.h>

    #define SD_ChipSelectPin 2

    const int FSR_PIN = A0; // Pin connected to FSR/resistor divider

    const float VCC = 4.875;
    const float R_DIV = 10000.0;

    void setup()
    {
      Serial.println("Starting Drum Kit!");
      Serial.begin(9600);
      while (!Serial) {}

      pinMode(FSR_PIN, INPUT);
      pinMode(LED_PIN, OUTPUT);

      Serial.print("Initializing SD Card...");
      if (!SD.begin(SD_ChipSelectPin)) {
        Serial.println("FAILED!");
        while(true);
      }
      Serial.println("done");

      // 44100kHz stereo => 88200 sample rate
      // 100 mSec of prebuffering.
      Audio.begin(88200, 100);

      void loop()
    {
      File snare_file;
      short snare_buffer[1024];
      int fsrADC = analogRead(FSR_PIN);
      if (fsrADC > 20) // If the analog reading is non-zero
      {
        Serial.println(String(fsrADC));

        snare_file = SD.open("606snare.wav");
        while (snare_file.available()) {
          snare_file.read(snare_buffer, 1024);
          Audio.prepare(snare_buffer, 1024, 1024);
          Audio.write(snare_buffer, 1024);
        }
        snare_file.close();
      }
    }

If I hold down the sensor (constant triggering), the fastest that the file plays is about every half second. Here's the Serial output:

    15:12:28.453 -> Initializing SD Card...done
    15:12:28.487 -> 1023
    15:12:28.930 -> 1023
    15:12:29.510 -> 1023
    15:12:30.050 -> 1023
    15:12:30.628 -> 1023
    15:12:31.136 -> 1023
    15:12:31.744 -> 1023
    15:12:32.328 -> 1023
    15:12:32.834 -> 1023
    15:12:33.411 -> 1023
    15:12:33.955 -> 1023

I've tried playing around with loading the file and buffer in the `setup` section but I can't get it to work properly. There's not a whole lot of documentation on the `Audio` library either.

If you know of a better way to speed this up, or if I should be using a different library, please let me know.

title: Home made drum kit - How can I speed up the response time after my sensor gets triggered?

Answers: 1

body:
This is not really a 'solution', but it might help you in finding out where the real problem is.

Check out which of the statements in the `loop` function uses up the most time, probably;

1. int fsrADC = analogRead(FSR_PIN);
2. Serial.println(String(fsrADC));
3. snare_file = SD.open("606snare.wav");
4. while (snare_file.available()) {
5. snare_file.read(snare_buffer, 1024);
6. Audio.prepare(snare_buffer, 1024, 1024);
7. Audio.write(snare_buffer, 1024);
8. snare_file.close()

Try improving the most time consuming item if possible.

Some possibilities you can try in the steps above:

1. Do not use AnalogRead but direct port commands
2. Remove this completely or at least remove the String instance.
3. Not much you can do here, except not using a file system but raw SD read (you might have problems getting the files on your SD) without a dedicated program on your PC
4. Not sure about improving this one
5. Read less bytes, although it might even worsen things. Or read the bytes BEFORE waiting on the trigger (if you know which sample will be played).
6. Execute the prepare as before the trigger as 5 if possible.
7. Not sure about this... High likely you cannot keep too many files open at the same time.

Afaik in my synthesizer (Korg Kronos), it reads from all samples the initial part, meaning it can startup the data from RAM, while the rest is read through SSD (in your case SD). However, you might not have enough memory in an Arduino for that.


body:
I am trying to write a sketch wherein the led brightness increases in increments of 15 until it reaches 255. At that point I want to make decrements of 15 until it reaches 0. The increment part of the program works well but the decrement part goes haywire. It gets stuck between 255 & 240. I am not sure how can I fix it. Could you please tell how can I make it work?

Here is my sketch:

    int led = 9; //led pin
    int fade = 0; // pwm value

    void setup() {
      // put your setup code here, to run once:

      Serial.begin(9600);
      pinMode(led, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:

       analogWrite(led,fade);
       fade += 15;
       Serial.println(fade);
       delay(250);

      if (fade >= 240){
        fade = fade - 15;
        analogWrite(led, fade);
        Serial.println(fade);
        delay(250);
      }

    }

title: problem with decrement in a loop

Answers: 2

body:
The problem is that you add 15, and than if it's >= 240, you decrease 15, so it will not change  (I wouldn't consider it haywire though).

You can better use a direction sign. Below is only the relevant code (not the GPIO functionality). What it does in the loop is, in case up is true, it adds fifteen, otherwise it subtracts 15. When 255 is reached, it starts counting down (`up` is false), when reaching 0, it starts counting up (`up` is true). This only works if 255 / the amount to add/subtracts reaches exactly 255, otherwise you have to check for <= 0 and >= 255.

    bool up = true;
    int fade = 0;

    void loop()
    {
        fade += up ? 15 : -15;
        if (fade == 0)
        {
          up = true;
        }
        else if (fade == 255)
        {
          up = false;
        }
    }

**Not considered good coding practices:**

The last `if` statement can be substituted for the following line, which means: if going up and 255 is reached, go down, else if going down and 0 is reached, go up, otherwise don't change `direction`. But it is much less readable, so I prefer the longer `if` statement.

    up = (up && (fade == 255)) ? false : ((!up && (fade == 0)) ? true : up);

Another version: if `fade` is 0 or 255 (only two possibilities), go up if 0 is reached, else (can only be 255) go down, else don't change.

    up = (fade % 255 == 0) ? (fade == 0) : up;

body: The `if` condition is causing the issue. When the global variable `fade` reaches `240`, upon entering the `loop()`, you are incrementing it by `15`, making `fade = 255`. So, the `if` condition becomes `true` and `15` is subtracted from `255` making `fade` to be equal to `240` again. This keeps repeating and hence the value `fade` variable is stuck between the values `240` and `255`.


body:
I'm trying out the AP mode of the device, where it can serve as its own server. Most of the tutorials have been loading the html from the SD card. I can do the same, but the bootstrap of the website is not working. It just loads the basic version of the website. How can I fix this?

### APMode.ino ###
```cpp
#include <SPI.h>
#include <SD.h>
#include <WiFiNINA.h>
#define WEBHTM "SERVER/index.htm"

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "MKRTEST";        // your network SSID (name)
char pass[] = "PASS";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;                // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
WiFiServer server(80);

File webFile;

void setup()
{

    //Initialize serial and wait for port to open:
    Serial.begin(9600);
    while (!Serial);

    Serial.println("Access Point Web Server");

    // check for the WiFi module:
    if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
    }

    if(!SD.begin(4))
    {
        Serial.println("SD card not found!");
        while(1);
    }

    if (!SD.exists(WEBHTM))
    {
        Serial.println("missing index.htm!");
        while(1);
    }

    String fv = WiFi.firmwareVersion();
    if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
    }

    // by default the local IP address of will be 192.168.4.1
    // you can override it with the following:
    // WiFi.config(IPAddress(10, 0, 0, 1));

    // print the network name (SSID);
    Serial.print("Creating access point named: ");
    Serial.println(ssid);

    // Create open network. Change this line if you want to create an WEP network:
    status = WiFi.beginAP(ssid);
    if (status != WL_AP_LISTENING) {
    Serial.println("Creating access point failed");
    // don't continue
    while (true);
    }

    // wait 10 seconds for connection:
    delay(10000);

    // start the web server on port 80
    server.begin();

    // you're connected now, so print out the status
    printWiFiStatus();
}

void loop() {
  // compare the previous status to the current status
  if (status != WiFi.status()) {
    // it has changed update the variable
    status = WiFi.status();

    if (status == WL_AP_CONNECTED) {
      // a device has connected to the AP
      Serial.println("Device connected to AP");
    } else {
      // a device has disconnected from the AP, and we are back in listening mode
      Serial.println("Device disconnected from AP");
    }
  }

  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("new client");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();
            webFile = SD.open(WEBHTM);
            if (webFile)
            {
              while (webFile.available())
              {
                client.write(webFile.read());
              }
              webFile.close();
            }

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          }
          else {      // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        }
        else if (c != '\r') {    // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
        if (currentLine.endsWith("POST /enterCredentials")) {
        //   digitalWrite(led, HIGH);               // GET /H turns the LED on
        Serial.println("Hello there!");
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

void printWiFiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in a browser:
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);

}
```

### index.htm

```xml
<!DOCTYPE html>
<html lang="en">
<head>
  <title>LPS Server</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>

<div class="jumbotron text-center" style="margin-bottom:0">
  <h1>Low Power Sensor (LPS) Server</h1>
</div>

<div class="container" style="margin-top:30px" id="WifiDetails">
  <h3>Please enter needed Credentials</h3>
  <form action="/enterCredentials.htm" method="post"><label for="SSID">SSID:</label><input type="text" class="form-control" name="SSID"><label for="PASS">PASS:</label><input type="password" class="form-control" name="PASS"><label for="BROKER">Broker/Host:</label><input type="text" class="form-control" name="BROKER"><label for="DEVID">Device ID:</label>
    <input type="text" class="form-control" name="DEVID"><input type="hidden" name="eof" value="#EOF"><br><button type="submit" class="btn btn-primary btn-block" value="Submit">SUBMIT</button></form>
</div>

<div class="jumbotron text-center" style="margin-bottom:0"><p>All Rights Reserved 2020</p></div></body>
</html>
```

title: Bootstrap not working: Arduino MKR WiFi 1010 AP mode

Answers: 0


body:
My progress so far:

```
#include <SoftwareSerial.h>

SoftwareSerial ttySerial(10, 11); // RX, TX
byte buffer;

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

  Serial.println("Serial Initialized");

  //Set the data rate for the SoftwareSerial port
  ttySerial.begin(115200);
  ttySerial.println("tty Initialized");
}

void loop()
{
  ttySerial.listen();
  while (ttySerial.available())
    //byte buffer = ttySerial.read();
    //Serial.write(buffer);
    Serial.write(ttySerial.read());

//    if (Serial.available())
//      ttySerial.write(Serial.read());
}
```

I am really confused because if I write the data as the as the buffer I have defined, the serial monitor goes crazy. If I upload the code as shown, I don't get anything weird in the monitor but the behavior is not what I expect.

I am writing to the software-serial on RX10 & TX11 (from javascript) the following data:
Buffer.from(`[0, 0, 4, 0, 0, 0, 0, 0]`) (keystroke "a")

The `Buffer.from` method comes from `node` using the `serialport` `npm` module. (This is basically irrelevant since sending the data from `Buffer.from('test')` works and is output to the monitor.

As you can see, the buffer is 1 byte (the array forming the 8 bits). Why is the buffer not read as "a" in the monitor? Is it because the Micro has an abstract HID report descriptor (see below)?

Additionally, what does `Serial.write(...)` represent? I.e. when I close the Arduino IDE serial monitor, will my Arduino Micro automatically assume its HID function and write the data as an HID device? S

I know there are already `keyboard` and `mouse` HID libraries but I already have code that generates the raw HID data that I would prefer to utilize. Note that the buffer described above comes from the HID report descriptor for a generic keyboard i.e. the "4" is not merely the ASCII code for "a". [Explained Here](https://www.rmedgar.com/blog/using-rpi-zero-as-keyboard-report-descriptor) Maybe I can use https://www.arduino.cc/en/Reference/HID ?

Thanks in advance!

EDIT 1:
This is the output I see from the code as shown (without the monitor "going crazy")
```
19:51:03.017 -> Serial Initialized
19:51:13.932 -> //Where I was hoping to see "a"
```

EDIT 2: I found the report descriptor in `Keyboard.cpp`:

```
  //  Keyboard
    0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)  // 47
    0x09, 0x06,                    // USAGE (Keyboard)
    0xa1, 0x01,                    // COLLECTION (Application)
    0x85, 0x02,                    //   REPORT_ID (2)
    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)

  0x19, 0xe0,                    //   USAGE_MINIMUM (Keyboard LeftControl)
    0x29, 0xe7,                    //   USAGE_MAXIMUM (Keyboard Right GUI)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x01,                    //   LOGICAL_MAXIMUM (1)
    0x75, 0x01,                    //   REPORT_SIZE (1)

  0x95, 0x08,                    //   REPORT_COUNT (8)
    0x81, 0x02,                    //   INPUT (Data,Var,Abs)
    0x95, 0x01,                    //   REPORT_COUNT (1)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x81, 0x03,                    //   INPUT (Cnst,Var,Abs)

  0x95, 0x06,                    //   REPORT_COUNT (6)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x25, 0x73,                    //   LOGICAL_MAXIMUM (115)
    0x05, 0x07,                    //   USAGE_PAGE (Keyboard)

  0x19, 0x00,                    //   USAGE_MINIMUM (Reserved (no event indicated))
    0x29, 0x73,                    //   USAGE_MAXIMUM (Keyboard Application)
    0x81, 0x00,                    //   INPUT (Data,Ary,Abs)
    0xc0,                          // END_COLLECTION
```
I will need to compare this to the data I would be sending to `Keyboard.write()`

title: Reading Buffer from Software-Serial & Writing to Serial

Answers: 1

body:
Don't use listen() this way. It clears the receive buffer. You loose the data received before listen() call.

You have only one SoftwareSerial instance so you don't need to call listen(). The listen() function clears the receive buffer because there is only one buffer for all SoftwareSerial instances.


body:
I wrote the following scope-based timer to help me profile my code and improve its efficency, but in testing I found that it reports durations far shorter than it should:

```c++
class CodeTimer {
 public:
  CodeTimer(const String& name) : _name(name) {
    Serial.println("Begin execution of \"" + _name + "\".");
    _begin = micros();
  }

  ~CodeTimer() {
    unsigned long duration = micros() - _begin;
    Serial.println("\"" + _name + "\" execution took " + duration + "µs.");
  }

 private:
  unsigned long _begin;
  String _name;
};
```

For example, I'd use it like so in my sketch:

```c++
void setup() {}

void loop() {
  CodeTimer("void loop()");
  int begin = millis();

  delay(100); // Simulation of work that takes 100ms.
  Serial.println(millis() - begin);
}
```

Then, when I go to run the above sketch on my Blue Pill board (*STM32F103C8*), I get something like this printed to the terminal:

```
Begin execution of "void loop()".
"void loop()" execution took 4µs.
100
Begin execution of "void loop()".
"void loop()" execution took 3µs.
101
Begin execution of "void loop()".
"void loop()" execution took 4µs.
100
```

Something is very wrong with when the destructor to `CodeTimer` is being called, and I'm not exactly sure what it is.

title: Why does this scope-based timer not work as intended?

Answers: 0


body:
So, I tried making an Arduino Project(Controlling Motors by Remote and Ultrasonic Sensor would activate Servo when the distance is less than 50cm).
I am trying to build a project, A remote controlled car, which will pick up objects when it encouters an object within 50cm. The remote controlled car works fine, but, to pick up objects i am trying to make it work with ultrasonic sensor, but to no avail

First when I just build the circuit for Remote Controled Motors the circuit worked fine, but after adding an Ultrasonic Sensor and Servo the circuit is not working)

This is the code without Ultrasonic and Servo:

    #include <IRremote.h>      //including the remote library

    #define Next_button 16615543  // code received from next button
    #define Prev_button 16619623  // code received from previous button
    #define left_button 16591063  // code received from left button
    #define right_button 16607383 // code received from right button
    #define Stop_button 16580863   // code received from stop button

    int receiver_pin = 12;      //output pin of IR receiver to pin 2 of arduino
    //initializing the pins for leds
    int left_motor1 = 2;      //pin 6 of arduino to pin 7 of l293d
    int left_motor2 = 3;      //pin 7 of arduino to pin 2 of l293d
    int right_motor1  =4;      //pin 5 of arduino to pin 10 of l293d
    int right_motor2 = 5;      //pin 4 of arduino to pin 15 of l293d

    IRrecv receiver(receiver_pin); //Arduino will take output of IR receiver from pin 2
    decode_results output;

    void setup() {
      Serial.begin(9600);
      receiver.enableIRIn(); // Start to take the output from IR receiver
      //initializing all the pins where we have connected the led's as output pins
      pinMode(left_motor1, OUTPUT);
      pinMode(left_motor2, OUTPUT);
      pinMode(right_motor1, OUTPUT);
      pinMode(right_motor2, OUTPUT);
    }

    void loop() {
      if (receiver.decode(&output)) {
        unsigned int value = output.value;
        switch(value) {
          case Next_button:
               digitalWrite(left_motor1,LOW);
               digitalWrite(left_motor2,HIGH);
               digitalWrite(right_motor1,HIGH);
               digitalWrite(right_motor2,LOW);
               break;
          case Prev_button:
               digitalWrite(left_motor1,HIGH);
               digitalWrite(left_motor2,LOW);
               digitalWrite(right_motor1,LOW);
               digitalWrite(right_motor2,HIGH);
               break;
          case left_button:
               digitalWrite(left_motor1,LOW);
               digitalWrite(left_motor2,HIGH);
               digitalWrite(right_motor1,HIGH);
               digitalWrite(right_motor2,HIGH);
               break;
          case right_button:
               digitalWrite(left_motor1,HIGH);
               digitalWrite(left_motor2,HIGH);
               digitalWrite(right_motor1,HIGH);
               digitalWrite(right_motor2,LOW);
               break;
          case Stop_button:
               digitalWrite(left_motor1,LOW);
               digitalWrite(left_motor2,LOW);
               digitalWrite(right_motor1,LOW);
               digitalWrite(right_motor2,LOW);
               break;
        }
        receiver.resume();
      }
    }
[![Circuit Successfully Working][1]][1]

This is the code with Ultrasonic and Servo:

    #include <IRremote.h>      //including the remote library
    #include <Servo.h>

    #define Next_button 16615543  // code received from next button
    #define Prev_button 16619623  // code received from previous button
    #define left_button 16591063  // code received from left button
    #define right_button 16607383 // code received from right button
    #define Stop_button 16580863   // code received from stop button
    #define trigPin 11
    #define echoPin 10

    int receiver_pin = 12;      //output pin of IR receiver to pin 2 of arduino
    //initializing the pins for leds
    int left_motor1 = 2;      //pin 6 of arduino to pin 7 of l293d
    int left_motor2 = 3;      //pin 7 of arduino to pin 2 of l293d
    int right_motor1  =4;      //pin 5 of arduino to pin 10 of l293d
    int right_motor2 = 5;      //pin 4 of arduino to pin 15 of l293d
    Servo servo;

    IRrecv receiver(receiver_pin); //Arduino will take output of IR receiver from pin 2
    decode_results output;

    void setup() {
      Serial.begin(9600);
      receiver.enableIRIn(); // Start to take the output from IR receiver
      //initializing all the pins where we have connected the led's as output pins
      pinMode(left_motor1, OUTPUT);
      pinMode(left_motor2, OUTPUT);
      pinMode(right_motor1, OUTPUT);
      pinMode(right_motor2, OUTPUT);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      servo.attach(8);
    }

    void loop() {
      if (receiver.decode(&output)) {
        unsigned int value = output.value;
        switch(value) {
          case Next_button:
               digitalWrite(left_motor1,LOW);
               digitalWrite(left_motor2,HIGH);
               digitalWrite(right_motor1,HIGH);
               digitalWrite(right_motor2,LOW);
               break;
          case Prev_button:
               digitalWrite(left_motor1,HIGH);
               digitalWrite(left_motor2,LOW);
               digitalWrite(right_motor1,LOW);
               digitalWrite(right_motor2,HIGH);
               break;
          case left_button:
               digitalWrite(left_motor1,LOW);
               digitalWrite(left_motor2,HIGH);
               digitalWrite(right_motor1,HIGH);
               digitalWrite(right_motor2,HIGH);
               break;
          case right_button:
               digitalWrite(left_motor1,HIGH);
               digitalWrite(left_motor2,HIGH);
               digitalWrite(right_motor1,HIGH);
               digitalWrite(right_motor2,LOW);
               break;
          case Stop_button:
               digitalWrite(left_motor1,LOW);
               digitalWrite(left_motor2,LOW);
               digitalWrite(right_motor1,LOW);
               digitalWrite(right_motor2,LOW);
               break;
        }
        receiver.resume();
      }
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) / 29.1;
      if (distance < 50) {
        Serial.println("the distance is less than 5");
        servo.write(90);
      }
      else {
        servo.write(0);
      }
      if (distance > 60 || distance <= 0) {
        Serial.println("The distance is more than 60");
      }
      else {
        Serial.print(distance);
        Serial.println(" cm");
      }
    }

[![Overall Circuit][2]][2]
[![Close up][3]][3]

  [1]: https://i.stack.imgur.com/2tMjL.png
  [2]: https://i.stack.imgur.com/Dl8FC.png
  [3]: https://i.stack.imgur.com/xFHTT.png

title: Motors working with Ultrasonic Sensor and Servo as expected?

Answers: 0


body:
I am using 74hc595 in several projects where I need more I/O and always worked fine using arduino pro mini or arduino mega. Now I connected same 2 of 74hc595 to an esp32 and does not work.
Is there any special things to do for esp32?

Wiring is exactly the same like here https://www.arduino.cc/en/tutorial/ShiftOut on chapter 2 (Connect the 2 registers.). If I use this with an arduino mega on pins 10,9,8 (see commented in code) is working perfect.

Then I replace arduino mega with esp32 and using pins 23,18,5 and does nothing. I get in serial monitor on/off prints but nothing changes to the relays.

Code

    int SER_Pin = 23;//10; //pin 14 on 75hc595 //data pin
    int RCLK_Pin = 18;//9; //pin 12  //latch
    int SRCLK_Pin = 5;//8; //pin 11  //clock

    #define number_of_74hc595s 2

    #define numOfRegisterPins number_of_74hc595s * 8

    boolean registers[numOfRegisterPins];

    void setup() {
      Serial.begin(9600);
      pinMode(SER_Pin, OUTPUT);
      pinMode(RCLK_Pin, OUTPUT);
      pinMode(SRCLK_Pin, OUTPUT);

      clearRegisters();
      writeRegisters();
    }

    void clearRegisters() {

      for (int i = numOfRegisterPins -1; i >= 0; i--) {
        registers[i] =HIGH;
      }
    }

    //Set and display registers
    //Only call after all values are set how you would like
    void writeRegisters() {
       digitalWrite(RCLK_Pin, LOW);

       for (int i = numOfRegisterPins -1; i >= 0; i--) {
          digitalWrite(SRCLK_Pin, LOW);
          int val = registers[i];

          digitalWrite(SER_Pin, val);
          digitalWrite(SRCLK_Pin, HIGH);
    }
      digitalWrite(RCLK_Pin, HIGH);

    }

    //set an individual pin high or low
    void setRegisterPin (int index, int value) {
      registers[index] = value;
    }

    void c_on() {
      Serial.println("on");
      setRegisterPin(13,LOW);
      writeRegisters();
      delay(50);
    }

    void c_off() {
      Serial.println("off");
      setRegisterPin(13,HIGH);
      writeRegisters();
      delay(50);
    }

    void loop() {

    c_on();
    delay(1000);
    c_off();
    delay(1000);

    }

Is there any special thing to do for using esp32?

Thank you very much

title: Esp32 and 74hc595 problem

Answers: 0


body:
I'm new into this domain field. My principal occupation is as a .NET developer.
I'm trying to do a personal project in which a AtMega328 takes some output from a scale using HX711 and sends a SMS via SIM800L GSM module. Before creating the whole module I tested each part separately with Arduino and the specific modules directly on breadboard. Everything works fine.I created a standalone using the guide from Arduino website(16Mhz crystal, 2x22 picoFarad capacitors, 10k Resistor to PIN1, RX/TX connected to PIN2/3). I designed the circuit using EasyEDA, printed it into pcb and assembled it. The only issue is that, when the standalone is not connected to the Arduino, and powered up by an external 5V source, unless I connected the pin1 to Arduino(connectd to PC)RESET pin, it's not working. I tried to attach a button for RESET to PCB, and connected it to PIN1 and GND, but like this I cannot upload to Atmega328, unless i disconnect the button from 10k Resistor/PIN1 and GND. In the first picture is the standalone which is not working if powered by an externalSource, unless I remove the button and add wire between Arduino-RESET and Atmega-PIN1. In the 2nd picture is my circuit, without HX711 module and in the 3rd picture is my circuit, working only because I connected the ARDUIN-RESET to Atmega328-PIN1 .[![ATmega328 powered by wallplug, not working][2]][2][![PCB Schema, not working][3]][3][![PCB schema, working, after connecting PIN1 to Arduino RESET][4]][4]enter image description here][5]][5][![enter image description here][1]

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

  [3]: https://i.stack.imgur.com/yiFKY.jpg

title: Atmega328 standalone not working unless Pin1 connected to Arduino RESET

Answers: 1

body: So, the comments went to chat. Somebody recommended to use decoupling caps as close as possible near the VCC/GND of Atmega. I have 10uF in my workbench, so I used on of these caps and the issue was solved.


body:
I try to display the transmitted information from CAN bus on ESP32 web server. I saved the ```CAN.read()``` in a buffer ```receivedChars[i]``` and try to display the data by  ```client.println(receivedChars[i]);} ```. However, nothing shows on the webserver... The complete code shows below,

```
// Copyright (c) Sandeep Mistry. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#include <CAN.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Replace with your network credentials
const char* ssid     = "NGW_2.4G";
const char* password = "NextGW2018";

// Set webserver port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

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

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  delay(2000);
  display.clearDisplay();
  display.setTextColor(WHITE);

  Serial.println("CAN Receiver");
  CAN.setPins(16, 17);
  // start the CAN bus at 500 kbps
  if (!CAN.begin(500E3)) {
    Serial.println("Starting CAN failed!");
    while (1);
  }

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop() {

    char receivedChars[10];
  // try to parse packet
  int packetSize = CAN.parsePacket();

  if (packetSize) {
    // received a packet
    Serial.print("Received ");

    if (CAN.packetExtended()) {
      Serial.print("extended ");
    }

    if (CAN.packetRtr()) {
      // Remote transmission request, packet contains no data
      Serial.print("RTR ");
    }

    Serial.print("packet with id 0x");
    Serial.print(CAN.packetId(), HEX);

    if (CAN.packetRtr())
    {
      Serial.print(" and requested length ");
      Serial.println(CAN.packetDlc());
    }
    else
    {
      Serial.print(" and length ");
      Serial.println(packetSize);

      // only print packet data for non-RTR packets
      while (CAN.available())
      {
         for (int i=0; i<5; i++)
         {
           receivedChars[i] = (char)CAN.read();
           Serial.print(receivedChars[i]);
         }
      }
      Serial.println();
    }

    Serial.println();
  }

   WiFiClient client = server.available();   // Listen for incoming clients
   if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the table
            client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial;}");
            client.println("table { border-collapse: collapse; width:35%; margin-left:auto; margin-right:auto; }");
            client.println("th { padding: 12px; background-color: #0043af; color: white; }");
            client.println("tr { border: 1px solid #ddd; padding: 12px; }");
            client.println("tr:hover { background-color: #bcbcbc; }");
            client.println("td { border: none; padding: 12px; }");
            client.println(".sensor { color:white; font-weight: bold; background-color: #bcbcbc; padding: 1px; }");

            // Web Page Heading
            client.println("</style></head><body><h1>Can bus</h1>");
            client.println("<tr><td>text: </td><td><span class=\"sensor\">");

         for (int i=0; i<5; i++)
         {
           receivedChars[i] = (char)CAN.read();
           client.println(receivedChars[i]);
         }

            client.println(" .</span></td></tr>");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}
```

title: How to display CAN BUS information on EPS32 web server?

Answers: 1

body: It looks like the CAN-BUS can not be activated in web server session, I save the transmitted information in a buffer before starting the web server session, and print out the information from the buffer.


body:
I am trying to make an Indoor positioning system using ESP8266 as a beacon, how do I get the transmission package timestamp from router to ESP8266 and vice-versa?

Thank you in advance for any advice

title: How to get Transmission package Timestamp from ESP8266

Answers: 1

body:
You can use timestamp from NTP client and attach it

Install NTPclient library from Arduino library manager
This library uses WiFiUdp library to connect to the NTP server, so download that too

Then you can just update the time every time your sending/receiving something and log it as and how you see fit!


body: The program was running fine, a few days ago, but now it just wouldn't read/write to the database. I'm running on ArduinoJson 5.13.5 and using FirebaseArduino library. I have set all the rules to true, would love to know how to debug this error. Also Firebase.error() does not give any output at all!

title: Firebase.failed() returns 0 after Firebase.begin(), but returns 1 while reading or writing from/to firebase from ESP8266

Answers: 1

body:
Apparently the Firebase's fingerprint has changed recently and has caused the above issue!

from here get [the latest finger print][1] and change it in the ```...\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient.h```

In the file mentioned above: update the value of ```static const char kFirebaseFingerprint[]``` to the new one mentioned above.

P.S. One issue going forward for me(planing on implementing it on a long term basis) is how to be ahead of this issue in the future, so that I can get the data uninterrupted!

  [1]: https://github.com/FirebaseExtended/firebase-arduino/issues/476#issuecomment-591931886


body:
We are trying to send a message using NRF24L01, raspberry pi as transmitter and arduino uno as receiver. Our concern is, the receiver arduino might not be working because we are not getting the proper output message on the serial monitor.
Code for the transmitter side (python code):

    import RPi.GPIO as GPIO
    from lib_nrf24 import NRF24
    import time
    import spidev

    GPIO.setmode(GPIO.BCM)

    pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

    radio = NRF24(GPIO, spidev.SpiDev())
    radio.begin(0, 17)

    radio.setPayloadSize(32)
    radio.setChannel(0x76)
    radio.setDataRate(NRF24.BR_1MBPS)
    radio.setPALevel(NRF24.PA_MIN)

    radio.setAutoAck(True)
    radio.enableDynamicPayloads()
    radio.enableAckPayload()

    radio.openWritingPipe(pipes[0])
    radio.openReadingPipe(1, pipes[1])
    radio.printDetails()
    #radio.startListening()

    message = list("GETSTRING")
    while len(message) < 32:
        message.append(0)

    while True:
        start = time.time()
        radio.write(message)
        print("Sent the message: {}".format(message))
        radio.startListening()

        while not radio.available(0):
            time.sleep(1/100)
            if time.time() - start > 2:
                print("Timed out.")
                break

        receivedMessage = []
        radio.read(receivedMessage, radio.getDynamicPayloadSize())
        print("Received: {}".format(receivedMessage))

        print("Translating our received Message into unicode characters...")
        string = ""

        for n in receivedMessage:
            if (n >= 32 and n <= 126):
                string += chr(n)
        print("Our received message decodes to: {}".format(string))

        radio.stopListening()
        time.sleep(1)

Code used for the receiver side (arduino):

    #include<SPI.h>
    #include<RF24.h>

    // ce, csn pins
    RF24 radio(9, 10) ;

    void setup(void){
      while (!Serial) ;
      Serial.begin(9600) ;

      radio.begin() ;
      radio.setPALevel(RF24_PA_MAX) ;
      radio.setChannel(0x76) ;
      radio.openWritingPipe(0xF0F0F0F0E1LL) ;
      const uint64_t pipe = 0xE8E8F0F0E1LL ;
      radio.openReadingPipe(1, pipe) ;

      radio.enableDynamicPayloads() ;
      radio.powerUp() ;

    }

    void loop(void){
      radio.startListening() ;
      Serial.println("Starting loop. Radio on.") ;
      char receivedMessage[32] = {0} ;
      if (radio.available()){
        radio.read(receivedMessage, sizeof(receivedMessage));
        Serial.println(receivedMessage) ;
        Serial.println("Turning off the radio.") ;
        radio.stopListening() ;

        String stringMessage(receivedMessage) ;

        if (stringMessage == "GETSTRING"){
          Serial.println("Looks like they want a string!") ;
          const char text[] = "Hello World!" ;
          radio.write(text, sizeof(text)) ;
          Serial.println("We sent our message.") ;
        }

      }
      delay(100) ;
    }

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

title: Project concerning wireless communication between raspberry pi (transmitter) and arduino uno(receiver) using nrf24l01. Receiver not working

Answers: 0


body:
I am trying to create an arduino system with radio-transmitters and radio-receivers. The system runs from a rechargable battery that is charged with a solar panel. I am using a __1.1W 6V solar panel__.

My problem is that I don't know how to make such a connection and I don't know what batteries to choose to power the arduino, assuming that I need it to run for __5-7 days__ without solar power and that the solar panel is good enough to recharge the batteries while they power the arduino. We are also assuming that the solar panel has __8 hours of sunlight__.

To the arduino are connected the following sensors:

 - __Flame Sensor__
 - __Light Resistor x2__
 - __Smoke Sensor__
 - __Radio Transmitter__
 - __Radio Receiver__
 - __DHT11 Temperature & Humidity Sensor__

I am also looking to see if I can power down most sensors and power them on later if an event occurs. So probably all the sensors could be sleeping except the __DHT11__ and the __Radio Receiver__. Preferably though, if at all possible, the rest of the sensors should be on, if we can handle __5-7 days _without_ the solar panel__. I don't know if more information is needed but I'd be pleased to help out in the comments, or provide more information by editing the question. :)

title: Use Low Power Arduino with Solar Panel

Answers: 1

body:
You have far too many variables and unknowns there. Primarily you need to know what the average current draw for your circuit is. Secondly you need to decide how long the solar powers are allowed to take to recharge the battery. You have to think not only about runtime but also charge time. The charge time dictates the maximum capacity of the battery, and that then dictates the runtime of the Arduino. So here's some napkin maths to illustrate:

Assuming you want the battery to charge from almost flat to full within 8 hours, and with a 1.1W 6V solar cell, that gives you a peak of 183mA.

Assuming the Arduino circuit takes 83mA on average (let's give ourselves nice round numbers here) that leaves 100mA peak for charging the battery.

If you're charging at, say, 0.2C, that gives a full charge in 5 hours. 100mA / 0.2C = 500mAh capacity (at *peak sunlight and current*).

At 500mAh capacity and 83mA average current draw that would give you (0.5/0.083) 6 hours of runtime without the solar panels.

So that's just not going to work.  It'll be dead by morning.

Now assume that you can turn off *everything* for 99% of the time.  That effectively reduces our average current draw to 0.083*0.01 = 830µA. Let's plug that into the same reasoning as above.

* Current draw = 0.00083A
* Incoming peak current = 0.183
* Available charge current = 0.183-0.00083 = 0.18217
* Charge at 0.2C = 910mAh.
* 1Ah battery would charge in about 5.5 hours of peak sunlight.
* 1Ah would last about 1200 hours, or 100 days.

None of this takes into account varying light levels or light incidence angles. As a rule of thumb, take the light as averaging 50% over the course of the 8 hour period. You will only get 1.1W when the angle of incidence is 90° to the solar panel. At all other times it will be reduced. So if we reduce the current from 183mA to, say, 100mA, the charge capacity changes to:

* Incoming peak current = 0.100
* Available charge current = 0.100-0.00083 = 0.099
* Charge at 0.2C = 496mAh
* A 500mAh battery would charge in about 5 hours.
* A 500mAh battery would run for about 50 days at 830µA average current.

So you see everything really hinges around the current consumption of the Arduino. How much current it consumes dictates how much is available to charge the battery, which in turn dictates the size of battery you can support, which dictates the amount of current you can draw for your desired runtime, which in turn dictates the amount of charge current available, which determines the size of battery you can support, which dictates ... etc.  You get the idea.

You can support larger batteries, of course - I illustrated this at 0.2C charge rate (that's 20% charge per hour to give a 5 hour charge time). As long as the net charge over time increases (so during the periods between the 5-7 days of complete darkness you gain more charge than is expended during the dark period - something which has not been specified) then it should function fine.

Also note that your battery voltage should be below your solar panel voltage. A 6V solar cell would be able to charge a 4.5V lead acid battery (assuming low dropout schottky protection diodes). Also the capacity of the battery depends also on what you determine your "cut-off" voltage to be. That's how low the battery voltage is allowed to go before your system is determined to be unworkable. This could be at a point where the battery is in danger of being damaged by over-discharge, or at a point where your circuit no longer receives enough voltage to function (which could be linked to oscillator frequency on ATMega chips), etc. For this reason it is often better to choose a board that is designed to run at a lower voltage (3.3V) and use high efficiency switching regulation to get the most out of your battery. A 5V Arduino is seldom a great choice.

Finding that right balance is now entirely up to you.

And, in answer to your other question, yes there are ways to turn things on and off. You can "sleep" the Arduino. You can use high efficiency power circuits. You can add power switching circuits (P-MOSFETs) to switch power on and off to other modules. All things can (and mostly should) be done to save power when running on batteries.


body:
I bumped into `byte` datatype recently. My knowledge of C/C++ is shallow, but I know `char` and I couldn't find much on `byte` in C++ docs. I looked it up in the [Arduino docs](https://www.arduino.cc/reference/en/language/variables/data-types/char/):
> It’s recommended to only use char for storing characters. For an
> unsigned, one-byte (8 bit) data type, use the byte data type.

Is `byte` datatype a solely Arduino construct? If so, why is it recommended over `char`? Both are 8-bit so why would it make any difference?

title: Why does Arduino IDE recommend storing 0-255 numbers in "byte" instead of "char"?

Answers: 2

body:
> Is byte datatype a solely Arduino construct?

Yes. Much of the Arduino "language" is "bent" to look like Java, since it originated from Processing, which is Java. So we have data types the "look like" Java ones, including "byte" for "unsigned char" and "boolean" for "bool".

> If so, why is it recommended over char?

Personally I don't ever recommend using it, since it's non-standard. Instead you should use `uint8_t` which is essentially the same thing, but portable.

It is recommended to use "hard signedness" data types for portability.  The problem with `char` is that whether it is signed or not is entirely down to the compiler implementation. Some systems have it as signed, some as unsigned. By using `byte` (or better, `uint8_t`) you are always going to get an unsigned 8-bit value.

For just storing of binary data it doesn't really make any difference, but when it comes to doing mathematics with the stored data you may find you suddenly have negative values when you don't want negative values (a `char` *might* be storing your number as -128 to +127, not 0 to 255).

body:
Just a little add-on to Majenko's answer:

If a function has a char* parameter, it's usually expecting a zero-terminated text.

If a function has a byte* parameter, it's usually any binary data, eventually containing '\0' bytes. The buffer size needs to be an additional parameter in this case.

If there's nothing else to consider, why not use that for your variable definition too:
Use `char` only if it contains an 8bit character. Or something like `char text[]="hello";`
For binary data it might be relevant if it's signed (int8_t) or unsigned (uint8_t).

----------
"usually" implies of course that you *should* read the doc.


body:
I want to use my Arduino with this: VAC8010F measure unit. It communicates with NRF24L01. The problem is I simply don't know which band or information it is receiving. Can somebody help me with this?

Thanks for any suggestions!

title: Arduino with NRF24L01. Getting correct data from unkown transmitter

Answers: 2

body:
Don't have full details yet. But the VAC8010F uses modbus RS485 protocol.
My research shows that the NRF24 just transmitts and receives the MODBUS protocol to and from master/slave. I have found modbus libs and samples of code on the net. There is a command driven program to communicate with MODBUS free for linux, which is the o/s I use. I don't know about win. Anyway, once I receive the MAX485TTL interface for my ARDUINO MEGA I will write code for data  logging to p.c. then modify to use the NRF24, as I should be able to extract the ADDRESS, and CHANNELS etc, and packet construct.

Hope this is of some help.

Patrick

body:
Nordic has an app to connect to nRF
[https://www.instructables.com/Send-Data-to-Mobile-Using-NRF24L01-Using-NRF-As-a-/][1]

The app is available for all platforms.
Did not try it myself. Hope this helps.
I going to do the same, but want receive it on Android.

If you got some news, please let me know.
Thanks

  [1]: https://www.instructables.com/Send-Data-to-Mobile-Using-NRF24L01-Using-NRF-As-a-/


body:
I am thinking of making a wireless speaker using the ESP8266 chip. I have some questions regarding this.

1.  Which pin of the ESP8266 chip can be used as I²S output? I have an ESP chip of this type :
![enter image description here](https://i.stack.imgur.com/bVgel.jpg)

2. Which ESP chip would be the best choice for this purpose?

2. I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?

3. I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

title: Streaming audio to ESP8266 over WiFi

Answers: 1

body:
> Which pin of the ESP8266 chip can be used as I²S output?

I uses GPIOs 2, 3, and 15. You only have GPIO2 available, and that's also one half of the UART interface.  Also you usually need to generate a "master" clock (usually something like 256x the bit clock) for oversampling. So you can't with that module.

> Which ESP chip would be the best choice for this purpose?

ESP32, without a shadow of a doubt.

> I know about the MAX98357A which is used to convert digital I²S data to analog. But, for stereo output I need to use 2 of those. Is there any alternative to this chip which supports stereo output by default?

Yes, there are plenty. The search term you want is "CODEC". Personally I use the TLV320DAC3101.

You never use two separate mono CODECs for stereo, since I²S is a (normally) stereo protocol for connecting to a stereo CODEC. Reliably splitting a stereo I²S stream into two mono ones is not easy.

> I have found many tutorials which shows how to play audio from SD card of ESP8266. But, how can I stream audio over standard WiFi connection?

By implementing a suitable protocol, and that depends entirely on what your audio is and how it is generated.


body:
An implementation function from the nice little Wiegand library [YetAnotherArduinoWiegandLibrary](https://github.com/paulo-raca/YetAnotherArduinoWiegandLibrary) prints a hexadecimal representation of a facility # & card # (8-bit facility #, 16-bit card #) — 24 bits of a 26-bit stream that comes across the wire.

Example encoded 24-bit number: 7111097 (decimal). Hex equivalent: 6C81B9. The 6C portion is the facility # (decimal: 108). 81B9 is card # (decimal 33209).

This function from the library's example usage serial prints the hexadecimal format of the number:

    void receivedData(uint8_t* data, uint8_t bits, const char* message) {
        Serial.print(message);
        Serial.print(bits);
        Serial.print("bits / ");
        //Print value in HEX
        uint8_t bytes = (bits+7)/8;
        for (int i=0; i<bytes; i++) {
            Serial.print(data[i] >> 4, 16);  //1st, 3rd, 5th hex digit
            Serial.print(data[i] & 0xF, 16); //2nd, 4th, 6th hex digit
        }
        Serial.println();
    }

What I've tried to do unsuccessfully so far is to loop over the bits to also serial print the two decimal formatted numbers (facility:card) in the final output form:  **108:33209**

title: Print 2 numbers stored in 24-bits in decimal format

Answers: 1

body:
Your code loops from the high order byte to the low order byte, printing each byte as 2 hex digits.

If you want instead to print the first byte as a decimal value, and then the remaining bytes as another decimal value, then do this:

Print byte 0 in base 10:

        Serial.print(data[0]);  //first byte
        Serial.print(":");

Then loop through the remaining bytes, building a result as a decimal value, and print that:

    unsigned long total = 0;
    for (int i=1; i<bytes; i++) //Skip the first byte
    {
        total = total << 8;  //Shift the previous total by 8 bits.
                             //(The same as multiplying by 256, but faster)
        total += data[i];    //Add in the new value
    }
    Serial.println(total);

The sample code you posted is written to handle a variable number of bytes. The code above does the same thing with decimal results. It's much simpler if you know you will always have 3 bytes or 4 bytes:

For 3 bytes:

        Serial.print(data[0]);  //first byte
        Serial.print(":");
        long total = long(data[1])*256 + data[2]);
        Serial.println(long(total);


body:
I have digital pin 7 when set to High it does and when set to low it does not.

The only way I can get consistent High or Low is to use a 2 position 3 pin switch with my pin 7 in the middle and ground on one side and 5v on the other.

Is there a way I can use an simple Open/Close switch and still get the same function?

As of not if I dont "pull" pin 7 to ground I get both open and close randomly.

title: How to set a not plugged in pin to ground or Low

Answers: 1

body:
Seems like you already found the solution. Without a pull-down of pull-up resistor, the voltage at pin 7 will float to some random voltage, when the switch is open.

Either add an (external) pull-down resistor. Or flip things around and use the **internal** pull-up resistor inside the ATMega328p. Then connect the other side of the switch to GND. Whenever the switch is pressed, your digitalWrite gives you a LOW.

To use the internal pull-up use `pinMode(7, INPUT_PULLUP);`


body:
    // After 2 seconds have passed, stop ignoring the button.
      // If the button is pressed, call the checkbutton function.
      if (millis() > ignore && digitalRead(0) == LOW)
      {
        checkbutton();
      }
    }
    // This function waits for the button to be released,
    // then waits for it to be pressed to start the next run.
    void checkbutton(){
      delay (50);  // Button pressed, debounce.
      while (digitalRead(0) == LOW) // While button is pressed,
      {}                            // do nothing while waiting.
      delay (50);                   // Button pressed, debounce.
      while (digitalRead(0) == HIGH)// While button is released,
      {}                            // do nothing while waiting.

      ignore = 2000 + millis();     // Set the now ignore time,
    }                              // and return to the main loop.

title: when i compile my code i get th is error stating "checkbutton" not declared in this scope

Answers: 1

body:
You are using `checkbutton()` before you have told the program what `checkbutton()` is.

You need to move the whole method definition `void checkbutton(){ ... }` more to the top, i.e. in front of any call to it (`checkbutton();`).

Another option would be a [forward declaration](https://en.wikipedia.org/wiki/Forward_declaration), but I doubt it's widely used in Arduino projects.


body:
Nano 33 IOT is not detecting by windows . When i plug the usb cable only green light on the board.
Board is installed from the board manager. the cable is usb DATA cable and not charging cable. I tried the double press on the reset button but nothing happen. The L light is Off and the green light isnt flashing.
I plugged the board into another usb port, the same issue. I tried the board on my friend computer also but no luck. I dont have ATmel ICE or any other debugger like j-link.
https://www.youtube.com/watch?v=C0tXa0uxv5c

I hope someone can explain what is the issue, is it hardware or software.

title: Arduino Nano 33 IOT issue

Answers: 2

body:
If you upload to a SAMD board like the MKR boards or the Nano 33 IoT **with Nano 33 BLE selected in Tools menu** of Arduino IDE, **the upload** is executed and **deletes the bootloader of the SAMD** MCU.

The problem is that bossac uploader doesn't check the chip, because it was developed only for the SAMD chips, but Arduino created a bootloader for the Nano 33 BLE nRF52 MCU to use the SAMD bossac uploader.

The SAMD boards use the native USB support of the MCU, so without a bootloader or good sketch running the USB doesn't work.

You have to restore the bootloader on Nano 33 IoT. It is done over the SWD pads on the bottom side of the board. You can use a SWD programmer or other Arduino board with the Adafruit DAP library.

You can use your Nano 33 BLE or some other board and a SD card with Adafruit DAP library as programmer.

I had this problem with MKR Zero and I used a LPC-Link2 programmer to burn the bootloader. Once before I lost the bootloader for other reason and back then I didn't have the programmer so I used the Adafruit DAP library with an Arduino M0.

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

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

  [1]: https://microchipdeveloper.com/atmelice:connecting-atmel-ice-to-a-swd-target
  [2]: https://i.stack.imgur.com/x4cTO.png
  [3]: https://i.stack.imgur.com/dEzWF.jpg

body:
After I waited to get my order on ebay. I managed to restore the bricked board.
The issue was related to bootloader fail. either the producer shipped it without a bootloader or some kind of static discharge caused to erase or stop the booloader from working and that why windowws didnt detect the board.
I used a converted cortex m3 to swd programmer debugger and one line cmd command.

Thank for all who contributed  solutions.
If anyone experience the same hardware failure, it is due to missing or corrupted bootloader.


body:
I have the following code:

```
#include <SoftwareSerial.h>
#include <Keyboard.h>

SoftwareSerial ttySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only
  }

  Serial.println("Serial Initialized");

  //Set the data rate for the SoftwareSerial port
  ttySerial.begin(115200);
  ttySerial.println("tty Initialized");

  Keyboard.begin();
}

void loop()
{
  while (ttySerial.available())
    //Serial.write();
    Keyboard.write(ttySerial.read());

//    if (Serial.available())
//      ttySerial.write(Serial.read());
}
```

my problem is that `ttySerial.read()` is an `int` and I thought that the `Keyboard.write` method could hand integer arguments: [`Keyboard.write(32)`](https://www.arduino.cc/en/Reference.KeyboardWrite) should write "< space >" not "32".

Any ideas what is going on?

title: Keyboard.write writing ASCII integer value as a String

Answers: 1

body:
write will treat an int as a number and assume you want it converted to ascii.  Try casting that to char:

    Keyboard.write((char)ttySerial.read());

The print class treats char variables as if they are already ascii codes.


body:
I'm using millis () function to control the timer of my LED. It is a very basic code that I used from the example libraries. The code worked well for 6 hours (On for 6 h, Off for the following 6 h and continues), however, when I set it up for 12 hours, the light failed to turn off when I checked on it. The designed time should have fit into the 2^32 bits for unsigned long which I have defined beforehand.
Can someone please help on this issue? Thank you!

    /*
      Blink without Delay

      Turns on and off a light emitting diode (LED) connected to a digital pin,
      without using the delay() function. This means that other code can run at the
      same time without being interrupted by the LED code.

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

      created 2005
      by David A. Mellis
      modified 8 Feb 2010
      by Paul Stoffregen
      modified 11 Nov 2013
      by Scott Fitzgerald
      modified 9 Jan 2017
      by Arturo Guadalupi

      This example code is in the public domain.

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

    // constants won't change. Used here to set a pin number:
    const int ledPin =  7;// the number of the LED pin

    // Variables will change:
    int ledState = LOW;             // ledState used to set the LED

    // Generally, you should use "unsigned long" for variables that hold time
    // The value will quickly become too large for an int to store
    unsigned long previousMillis = 0;        // will store last time LED was updated

    // constants won't change:
    unsigned long interval = 12*60*60*1000UL;           // interval at which to blink (milliseconds)

    void setup() {
      // set the digital pin as output:
      pinMode(ledPin, OUTPUT);
    }

    void loop() {
      // here is where you'd put code that needs to be running all the time.

      // check to see if it's time to blink the LED; that is, if the difference
      // between the current time and last time you blinked the LED is bigger than
      // the interval at which you want to blink the LED.
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
      }
    }

title: Millis () funtion fails to perform for extended period of time

Answers: 2

body:
Did you try to change your variables so that the calculations would be in seconds instead of milliseconds ? IOW add "/1000" after millis() and reduce your constants accordingly.

millis() is overflowing periodically, but it only happens every 49 days or so, and that even shouldn't play a role in the way you use it (the difference will also kind of overflow in the other direction).

body:
In C++, the multiplication operator is “left-associative”. This means
that the expression

```c++
12*60*60*1000UL
```

is interpreted as

```c++
((12*60)*60)*1000UL
```

The left factor, namely `(12*60)*60`, is computed using the `int` data
type, but the result overflows that format, resulting in the problem you
see.

The simple solution is to make one of the factors of the _first_ product
be an `unsigned long`. For example

```c++
1000UL*60*60*12
```

Then, `1000UL*60` is computed with the `unsigned long` data type. Since
the result is itself an `unsigned long`, the next multiplication is also
done as `unsigned long`, and likewise for the last one.

If you find this technique somewhat obscure, you can also add the `UL`
suffix to every single factor. This would avoid implicit conversions by
the compiler, making all the types explicit.


body:
I am reading the docs on [DigitalRead()](https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/) and wondering why it stores seemingly boolean `HIGH` and `LOW` inputs in `int` data type variable.

I have two issues with that:

1. `int` is 2-byte, while `bool` and `uint8_t` are 1-byte so it seems like a waste of memory for no benefit whatsoever.
2. It gets me confused when reading the code about whether the input came from digital or analog since `int` can have a wide range.

Is there any particular reason for storing digital inputs as `int`?

EDIT: `bool` and `uint8_t` are out of the question as per the answer below. **`int8_t`** still looks suitable for the purpose though.

title: Can I use 1-byte datatypes to store digital input?

Answers: 4

body:
You receive the data as `int`, but you store it as `byte`.

For example, when you call the serial library function to receive a data byte, the library will return either the data or a -1 if a problem has occurred.

The binary value of -1 is a byte 11111111 or int 1111111111111111.

The binary value of 255 is a byte 11111111 or int 0000000011111111.

I think that you can see the problem if you use `byte` data and the data is 255.

So, if you receive an `int` -1, then you do not process the data.  Otherwise you `cast` the `int` to `uint8_t`.

You could receive `byte` data, but then the value of 255 would be undefined.

body:
I did not check the internals a while, but in early days there was a

     #define HIGH 1
meaning that HIGH is a `const int`.

Perhaps someone did not want to disable some TRI-STATE digital logic in the beginning, and since then nobody wanted to change the basics.

But of course `bool` is a more appropriate data type for HIGH/LOW and of course you can always treat them this way, for example like

    if (! digitalRead(pin) ) { // pin is LOW
       ...
    }

----------
jsotola's answer why Serial.read() returns  an `int` is a different issue. And correct of course.

body:
The smallest unit in most languages is a byte (8 bits), whether signed or unsigned.
So returning a byte, even if it only returns three different values, is the smallest and most efficient unit available, that I'm aware of.

If you want to store later, you can assign each bit of a byte as a high or low, thus giving you 8 storage spots.

body:
One could always store the value of digitalRead() as a bit in a variable, compacting the data from say 8 pins down into 1 byte

    // read an input and store it, say the reads of D2 thru D9 are stored in byte bits9to2
    // 9,8,7,6,5,4,3,2
    // first clear the state for 2
    bits9to2 = bits9to2 && 0b11111110; // two && for bit manipulation? Or just 1?
    // then map in the new value
    if (digitalRead(D2) == HIGH){
    bits9to2 = bits9to2 || 0b00000001;// two || for bit manipulation? Or just 1?
    }
    else{
    // leave it as 0
    }

Then to use it later on:

    if ((bits9to2 && 0b00000001) != 0){
    // bit is set (HIGH), do whatever
    }
    else {
    // bit is clear (LOW), do whatever, or maybe do nothing
    }

Can use an unsigned int and store 16 bits compacted that way, or unsigned long for 32 bits.


body:
I am doing a project which monitors vibrations using an ADXL355 sensor and an Arduino. I have used the MPU-9250 sensor before.

I am not able to find a library or tutorials for calibrating, filtering, and reading accurate data from the sensor. Can anyone who has worked previously with the sensor help me? I am mechanical engineer new to the field of electronics.

If library files are not available, how can I use the datasheet to write the entire code myself? Is there any tutorial available for this?

Sorry if the post seems confusing..

title: ADXL355 accelerometer code

Answers: 1

body:
I had a similar learning path  as yours and I also tried to use ADXL345 and ADXL355. The latter was a pain for the issues described in many posts like [this](https://ez.analog.com/mems/f/q-a/109925/adxl355-latch-up-condition).

I couldn't find any good tutorial on this topic and had to learn all by myself.

I also use a different approach because I program ESP32-wrover devices with MicroPython. Nevertheless the logic is the same for translating DataSheets -> code.

1. You have to decide which serial interface to use
   * I2C if you are constrained to limited wires
   * SPI for high frequency measures

1. in both cases you write/read to/from registers of the device which are identified by an address, indicated in the datasheet (look for the registers map section). In each address you read/write a byte, that is 8 bits (0 or 1), that are packed into an hexadecimal format (e.g. you can set power mode to 'measure' writing 0x01 in register with address 0x2d)

1. with both you normally have a library that implement 3 main methods:
    1. init() for initializing the interface with the parameters you find in the datasheet:
       * SPI: polarity, phase, max_clock_frequency, first bit MSB or LSB
       * I2C: max_clock_frequency
    1. read(register_address, nbytes) -> bytearray
    1. write(register_address, bytearray)
1. before reading accelerations you must set range (e.g. ±2g), output data rate (e.g. 1000Hz), power mode (e.g. measure mode)
1. then you read acceleration data from corresponding registers. Consider that you can read multiple registers in one transaction reading multiple bytes starting from an address (e.g. you can read x,y,z measure in one transaction by starting from the first byte of x data and then reading 9 bytes = 3 axes * 3 bytes)
1. Then you have to convert from bytes to g units: in this accelerometer the value of one axis consist of 20 bits that are split in 3 bytes. You have to join the 3 bytes, shift away the trailing 4 bits, then apply two's components (that is for allowing negative numbers, look at [this guide](https://www.youtube.com/watch?v=4qH4unVtJkE)), then multiply by the scale factor indicated in the datasheet.


body:
I have an arduino uno and an accelerometer connected reading vibrations. I want to be able to send the serial data or serial plot wirelessly from the arduino to any program(recommendations will be considered) on the pc without using the USB port on the pc. Is it possible?

I have an arduino ethernet shield, bluetooth modules HC-05 and HC-10 all at hand if they will be helpful.
please help, any help would be greatly appreciated.

title: How to transfer serial data or plot wirelessly on an arduino?

Answers: 0


body:
I made a program using the Arduino Atmega32U4.

As a security issue, I tried to extract the hex code because I wanted to know if this program was duplicated.

avrdude -C"\avrdude.conf" -v -V -patmega32u4 -carduino -PCOM15 -b9600 -D -Uflash:w:C:\test\sketch_jun07b.ino.hex:i

This is what I executed in Command Line.

Avrdude ended with the following error: avrdude: stk500_getsync () attempt 1 of 10: not in sync:

Can you tell me if there is no risk of extracting and duplicating hex code from beetle or chipset unlike arduino board?

title: arduino atmega32u4 beetle extract hex code

Answers: 0