body:
Aside from the main website, I have noticed that it is hard to find documentation for specific Arduino add-ons, such as (This is just one example):

https://www.amazon.com/gp/product/B00OGYXN8C/ref=ppx_yo_dt_b_asin_title_o04_s01?ie=UTF8&psc=1#descriptionAndDetails

Is this fairly normal or are you just expected to "just know what to do" with every Arduino component after a while? I realize that the IDE does have samples, but they don't always help.

title: Where is all of the Arduino Documentation?

Answers: 4

body:
To be fair, you're really talking about non-Arduino (capital-A) parts from a multitude of suppliers. And yes, the documentation varies in its depth, quality of translation if it wasn't originally written in English, and even availability at all. Taking the part you linked (from a retailer that storefronts for sellers (sometimes not in this country), who sell from component builders (often not in this country, who build with of parts from supplied factories definitely not in this country, ..., you get the idea. There may or may not exist any documentation specifically for this LCD/keypad combination shield.

But just by reading Amazon's seller's part description, I found that it consists of (at least) a 1602 LCD module and an HD44780 LCD controller chip, for both of which I can quickly find and download datasheets. The sixth image to the left of the description is a schematic of the board which shows that the left, right, up, down, and select buttons are 'multiplexed onto an output called AD0. I might have confirm that that is - or isn't - the Arduino's Analog-0 pin, but in any case, now I know what I have to write to decode which button was pressed from the board's analog output.

All this, and the part costs under US$7.00. For that price (and an assumption that these shields aren't being made in huge quantities), a maker couldn't possibly be able to create a custom datasheet for the shield as a whole, but they did supply a schematic, and their board's components are identified, and those components do, in fact have datasheets online.

Slightly awkward, perhaps, especially if one is thinking in terms of parts like MCUs such as the Atmega328 family, that *are* made in huge enough quantities that its datasheet runs to nearly 700 pages of engineering-ese. Still, the information is there and accessible, without requiring a way lot of digging.

That's part of being an experimenter.

body:
I'd like to add to what JRobert said of finding the information the "hard way"(i.e. looking into the datasheet of the chip it used, and understand how it works from schematic).

In the Arduino world, a lot of hardware/shields are so called [Open Source Hardware](https://en.wikipedia.org/wiki/Open-source_hardware), meaning that many companies can produce the same hardware with the schematic that is released under Open Source hardware license. China happened to be the country where it has the complete value-chain from components, to manufacturing and cheap labour. They are good in producing such products at large quantity and selling at low price, and they are not necessary good in developing original product, and certainly not in documentation (especially in English). These products are not necessary China "knock-off" as many people call it.

Since it is open hardware products, there are multiple vendors producing it and there are many information available on the internet, and take the example you provide, it is "1602 LCD Keypad Shield", and if your google it with this phase, you will soon find [this pdf](https://media.digikey.com/pdf/Data Sheets/DFRobot PDFs/DFR0009_Web.pdf) which is not exactly from the same company of your shield, but it is remarkably similar that you can try.

This applied to many hardware/shields that are available in the market. I hope this provide a general guidance and an "easy way" to find the information in your tinkering journey. Of course, if you want to learn more, go dig out the datasheet and schematic as JRobert mentioned.

body:
With this particular board, you're quite fortunate in finding a supplier with an actual website and description: [HiLetGo LCD1602 Input/Output expansion board LCD Keypad Shield for Arduino](http://www.hiletgo.com/ProductDetail/2160390.html). The fact that the photos of the HiLetGo site show the [DFRobot](https://www.dfrobot.com/) logo — the company that hcheung already referred to — shows just how radically open Open Hardware can get! In this case, DFRobot has pretty decent documentation: [LCD KeyPad Shield For Arduino: SKU DFR0009 - DFRobot](https://wiki.dfrobot.com/LCD_KeyPad_Shield_For_Arduino_SKU__DFR0009) — but even they don't link to the official [LiquidCrystal](https://www.arduino.cc/en/Reference/LiquidCrystal) documentation, but a much older archived version.

The Arduino team admits that they “… [never entirely got to grips with Arduino documentation](https://blog.arduino.cc/2021/05/17/arduino-docs-has-all-the-info-you-ever-need-about-arduino-boards/)”. Their own "Find in Reference" tool in the IDE will sometimes dead-end to error pages on the arduino.cc site. For example, "find in reference" for *Serial* will take you to a local copy of the documentation that has [broken links](http://www.arduino.cc/en/Guide/ArduinoLeonardo) for the [Arduino Leonardo](https://store.arduino.cc/usa/leonardo) [documentation](https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro).

It's not always the case, but typically if an Arduino shield costs less than $10 on Amazon then the cost of "just know[ing] what to do" is passed on to you, the user.

body:
> **Where is all of the Arduino Documentation?**

Arduino
-------

So far as I know, the Arduino name is owned by the Italian company Arduino AG.

Arduino AG provide documentation on the website arduino.cc for the products they manufacture.

Arduino AG have no responsibilities for documenting products designed and manufactured by other businesses.

Other businesses
----------------

There are many other businesses that design and, in some cases, manufacture products that are designed to be compatible with or to work with products manufactured by Arduino AG. They don't need permission from Arduino AG unless they are using the trademarks or other intellectual property of Arduino AG. In addition, Arduino AG make many designs available under a permissive licence that does not give Arduino AG any control over or responsibility for documentation of cloned or derivative products manufactured or marketed by other businesses.

Examples include Adafruit, Sparkfun and many others.

These businesses provide documentation for the products they manufacture.

Some other businesses might choose to manufacture products without providing documentation or without providing documentation in English. For example a small Chinese manufacturer might only provide documentation in Chinese or provide none at all, expecting users to make use of documentation provided by the community or by the designer whose open-source designs they are using or whose proprietary designs their product is functionally equivalent to.

Open Source Designers
---------------------

Many hobbyists and small-scale makers provide documentation for use of their designs for products.


body:
I am trying to get two limits to or on the same while statement. Can this be done?

```c++
while (digitalRead (home_limit)) {
```

This works for one(1) limit,
But when I try using two(2) limits  is does not work. I can't find the proper configuration. I tried this.

```c++
while (digitalRead (home_limit1) || (home_limit2)) {
```

I also tried other combinations with no luck.
Does anyone know how to do an or (||) statement with a while digital read?

title: Using OR with a while loop

Answers: 1

body:
`digitalRead()` is a function. It takes one parameter (the pin number) and returns the state of that pin.  It's *that* return value that you want to OR with another. Which means you have to read the state of *both* pins, separately, and OR the results together:

```c++
while (digitalRead(home_limit1) || digitalRead(home_limit2)) {
    ....
}
```


body:
I'm trying to communicate through SPI to a Flash ROM chip (M45PE20) with an ATMEGA 2560. I'm looking to read the data off the chip, but the output I'm getting is nothing but FF's. I've checked my wiring and everything looks okay on that end, I also don't have a scope to probe the output unfortunately.

I've the crude code below:

```#include <SPI.h>
void setup() {
  Serial.begin(9600);
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);
  SPI.begin();
}

void loop() {
  Serial.println("Starting");
  Serial.println("Waiting 1s");
  delay(1000);
  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));

  digitalWrite(SS, LOW);
  Serial.println(SPI.transfer(0x03));
  Serial.println(SPI.transfer(0x00));
  Serial.println(SPI.transfer(0x00));
  Serial.println(SPI.transfer(0x00));
  for (int i = 0; i < 16384; i++) {
    Serial.print(i * 32, HEX);
    Serial.print(" ");
    for (int j = 0; j < 32; j++) {
      Serial.print(SPI.transfer(0xFF), HEX);
      Serial.print(" ");
    }
    Serial.println();
  }

  Serial.println();
  digitalWrite(SS, HIGH);
  delay(500);
  SPI.endTransaction();
  delay(5000);
}
```

Link to datasheet: https://drive.google.com/file/d/1_Zlg-hb5B08u7_m_N4_addmmjyv_nANS/view?usp=sharing

Picture of specific read command from datasheet:
![Picture of specific read command from datasheet.][1]

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

title: Reading a flash ROM chip (M45PE20) through SPI with an ATMEGA 2560 -- output only FF's

Answers: 0


body:
I have two sensors data in packet but now I want to send these two sensors data into single packet in which these two sensors data are gathered. I mean I want to have a packet in which I have oxygen, heart rate and pedometer values.  Can anyone suggest me how to do it. Code for both sensors are given below. I have already try a lot of ways but all in vain. I will be very thankful for your suggestion and time.

**For Sensor 1**

    #include <Wire.h>
    #include "MAX30105.h"
    #include "spo2_algorithm.h"

    MAX30105 particleSensor;

    #define MAX_BRIGHTNESS 255

    #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    //Arduino Uno doesn't have enough SRAM to store 100 samples of IR led data and red led data in 32-bit format
    //To solve this problem, 16-bit MSB of the sampled data will be truncated. Samples become 16-bit data.
    uint16_t irBuffer[100]; //infrared LED sensor data
    uint16_t redBuffer[100];  //red LED sensor data
    #else
    uint32_t irBuffer[100]; //infrared LED sensor data
    uint32_t redBuffer[100];  //red LED sensor data
    #endif

    int32_t bufferLength; //data length
    int32_t spo2; //SPO2 value
    int8_t validSPO2; //indicator to show if the SPO2 calculation is valid
    int32_t heartRate; //heart rate value
    int8_t validHeartRate; //indicator to show if the heart rate calculation is valid
    uint16_t checkSum = 0;

    byte pulseLED = 11; //Must be on PWM pin
    byte readLED = 13; //Blinks with each data read

    byte ledBrightness = 60; //Options: 0=Off to 255=50mA
    byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
    byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
    byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
    int pulseWidth = 411; //Options: 69, 118, 215, 411
    int adcRange = 4096; //Options: 2048, 4096, 8192, 16384

    void setup()
    {

    }

    void loop()
    {
      Serial.begin(9600);
      wait_for_Max30102();
      start_signal();
      if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed
      {
        Serial.println(F("MAX30105 was not found. Please check wiring/power."));
        while (1);
      }

      Serial.println(F("Attach sensor to finger with rubber band. Press any key to start conversion"));
      //while (Serial.available() == 0) ; //wait until user presses a key
      Serial.read();

      particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings
      bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps

      //read the first 100 samples, and determine the signal range
      for (byte i = 0 ; i < bufferLength ; i++)
      {
        while (particleSensor.available() == false) //do we have new data?
          particleSensor.check(); //Check the sensor for new data

        redBuffer[i] = particleSensor.getRed();
        irBuffer[i] = particleSensor.getIR();
        particleSensor.nextSample(); //We're finished with this sample so move to next sample

        /*Serial.print(F("red="));
        Serial.print("\t");
        Serial.print(redBuffer[i], BIN);
        Serial.print("\t");
        Serial.print(redBuffer[i], DEC);
        Serial.print("\n");
        Serial.print(F(", ir="));
        Serial.print("\t");
        Serial.println(irBuffer[i], BIN);
        Serial.print("\t");
        Serial.print(irBuffer[i], DEC);
        Serial.print("\n");*/
      }

      //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
      maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

      //Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
      while (1)
      {
        //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
        for (byte i = 25; i < 100; i++)
        {
          redBuffer[i - 25] = redBuffer[i];
          irBuffer[i - 25] = irBuffer[i];
        }

        //take 25 sets of samples before calculating the heart rate.
        for (byte i = 75; i < 100; i++)
        {
          while (particleSensor.available() == false) //do we have new data?
            particleSensor.check(); //Check the sensor for new data

          digitalWrite(readLED, !digitalRead(readLED)); //Blink onboard LED with every data read

          redBuffer[i] = particleSensor.getRed();
          irBuffer[i] = particleSensor.getIR();
          particleSensor.nextSample(); //We're finished with this sample so move to next sample

          checkSum = redBuffer[i] + irBuffer[i] + heartRate + validHeartRate + spo2 + validSPO2;

          //send samples and calculation result to terminal program through UART
          Serial.print(F("RED: "));
          Serial.print("\t");
          Serial.print(redBuffer[i], BIN);
          Serial.print("\t");
          Serial.print(redBuffer[i], DEC);
          Serial.println("");

          Serial.print(F("IR: "));
          Serial.print("\t");
          Serial.print(irBuffer[i], BIN);
          Serial.print("\t");
          Serial.print(irBuffer[i], DEC);
          Serial.println("");

          Serial.print(F("HR: "));
          Serial.print("\t");
          Serial.print(heartRate, BIN);
          Serial.print("\t");
          Serial.print("\t");
          Serial.print(heartRate, DEC);
          //Serial.println("\t");
          //Serial.print("(HRvalid = ");
          //Serial.print("\t");
          //Serial.print(validHeartRate, BIN);
          //Serial.print("\t");
          //Serial.print(validHeartRate, DEC);
          //Serial.print((" )"));
          Serial.println("");

          Serial.print(F("SPO2: "));
          Serial.print("\t");
          Serial.print(spo2, BIN);
          Serial.print("\t");
          Serial.print("\t");
          Serial.print(spo2, DEC);
          //Serial.println("\t");
          //Serial.print("(SPO2Valid = ");
          //Serial.println(validSPO2, BIN);
          //Serial.print("\t");
          //Serial.println(validSPO2, DEC);
          //Serial.print(" )");
          Serial.print("\n");
          Serial.println("");

          Serial.print(F("Checksum Byte: "));
          Serial.print("\t");
          Serial.print(checkSum, BIN);
          Serial.print("\t");
          if((byte)checkSum == (byte)(redBuffer[i] + irBuffer[i] + heartRate + validHeartRate + spo2 + validSPO2)){Serial.print("(CHECKSUM_OK)");}
          else {Serial.print("(CHECKSUM_ERROR)");}
          Serial.println("\n");
          Serial.println("\n");
          Serial.println("");
          Serial.println("");
          Serial.println("");
          delay(1000);
        }

        //After gathering 25 new samples recalculate HR and SP02
        maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

      }
      Serial.end();
    }

    void wait_for_Max30102()
    {
    delay(2000);
    }

    void start_signal(){
    pinMode(readLED, OUTPUT);
    pinMode(pulseLED, OUTPUT);
    digitalWrite(pulseLED, LOW);
    digitalWrite(readLED, LOW);
    delay(18);
    digitalWrite(pulseLED, HIGH);
    digitalWrite(readLED, HIGH);
    pinMode(pulseLED, INPUT);
    pinMode(readLED, INPUT);
    digitalWrite(pulseLED, HIGH);
    digitalWrite(readLED, HIGH);
    }

**For Sensor 2:**

    #include <Wire.h>

    #define DEVICE (0x53)    //ADXL345 device address
    #define TO_READ (6)        //num of bytes we are going to read each time (two bytes for each axis)

    #define offsetX   -10.5       // OFFSET values
    #define offsetY   -2.5
    #define offsetZ   -4.5

    #define gainX     257.5        // GAIN factors
    #define gainY     254.5
    #define gainZ     248.5

    byte buff[TO_READ] ;    //6 bytes buffer for saving data read from the device
    char str[512];                      //string buffer to transform data before sending it to the serial port

    int x,y,z, X;

    int xavg, yavg,zavg, steps=0, flag=0;
    int xval[15]={0}, yval[15]={0}, zval[15]={0};
    int threshhold = 60.0;

    uint16_t checkSum = 0;

    void setup(){}

    void loop()
    {
    for(unsigned int x = 0; x < 5; x++)
    { clv(); }
    Serial.end();
    }

    void start_signal(){
      writeTo(DEVICE, 0x2D, 0);
      writeTo(DEVICE, 0x2D, 16);
      writeTo(DEVICE, 0x2D, 8);
    }

    void clv(){
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(9600);  // start serial for output
      start_signal();
      //Turning on the ADXL345

      int regAddress = 0x32;    //first axis-acceleration-data register on the ADXL345

      readFrom(DEVICE, regAddress, TO_READ, buff); //read the acceleration data from the ADXL345

       //each axis reading comes in 10 bit resolution, ie 2 bytes.  Least Significat Byte first!!
       //thus we are converting both bytes in to one int
      x = (((int)buff[1]) << 8) | buff[0];
      y = (((int)buff[3])<< 8) | buff[2];
      z = (((int)buff[5]) << 8) | buff[4];

    //we send the x y z values as a string to the serial port
     //sprintf(str, "%d %d %d", x, y, z);
     //Serial.print(str);
     //Serial.print(10, byte());

      Serial.print("X = ");
      Serial.println(x);
      Serial.print("Y = ");
      Serial.println(y);
      Serial.print("Z = ");
      Serial.println(z);

     //write steps
      X = ArduinoPedometerSteps();
      Serial.print("steps = ");
      Serial.println(X);
      Serial.println(" ");

      //It appears that delay is needed in order not to clog the port
      Serial.print(F("X: "));
      Serial.print("\t");
      Serial.print(x, BIN);
      Serial.print("\t");
      Serial.print(x, DEC);
      Serial.print("\n");

      Serial.print(F("Y: "));
      Serial.print("\t");
      Serial.print(y, BIN);
      Serial.print("\t");
      Serial.print(y, DEC);
      Serial.print("\n");

      Serial.print(F("Z: "));
      Serial.print("\t");
      Serial.print(z, BIN);
      Serial.print("\t");
      Serial.print(z, DEC);
      Serial.print("\n");
      Serial.print(F("steps: "));
     Serial.print("\t");
     Serial.print(X, BIN);
     Serial.print("\t");
     Serial.print(X, DEC);
     Serial.println("\n");

    checkSum = x + y + z + X;

     Serial.print(F("Checksum Byte: "));
     Serial.print("\t");
     Serial.print(checkSum, BIN);
     Serial.print("\t");
     if((byte)checkSum == (byte)(x + y + z + X)){Serial.print("(CHECKSUM_OK)");}
     else {Serial.print("(CHECKSUM_ERROR)");}
     Serial.println("\n");
     Serial.println("\n");
     Serial.println("");
     Serial.println("");
     Serial.println("");
     delay(150);
    }

    //---------------- Functions
    //Writes val to address register on device
    void writeTo(int device, byte address, byte val) {
       Wire.beginTransmission(device); //start transmission to device
       Wire.write(address);        // send register address
       Wire.write(val);        // send value to write
       Wire.endTransmission(); //end transmission
    }

    //reads num bytes starting from address register on device in to buff array
    void readFrom(int device, byte address, int num, byte buff[]) {
      Wire.beginTransmission(device); //start transmission to device
      Wire.write(address);        //sends address to read from
      Wire.endTransmission(); //end transmission

      Wire.beginTransmission(device); //start transmission to device
      Wire.requestFrom(device, num);    // request 6 bytes from device

      int i = 0;
      while(Wire.available())    //device may send less than requested (abnormal)
      {
        buff[i] = Wire.read(); // receive a byte
        i++;
      }
      Wire.endTransmission(); //end transmission
    }

    //Get pedometer.

    int ArduinoPedometerSteps(){
        int acc=0;
        int totvect[15]={0};
        int totave[15]={0};
        int xaccl[15]={0};
        int yaccl[15]={0};
        int zaccl[15]={0};
        for (int i=0;i<15;i++)
        {
          xaccl[i]= x;
          delay(1);
          yaccl[i]= y;
          delay(1);
          zaccl[i]= z;
          delay(1);
          totvect[i] = sqrt(((xaccl[i]-xavg)* (xaccl[i]-xavg))+ ((yaccl[i] - yavg)*(yaccl[i] - yavg)) + ((zval[i] - zavg)*(zval[i] - zavg)));
          totave[i] = (totvect[i] + totvect[i-1]) / 2 ;
          //Serial.print("Total Average = ");
          //Serial.println(totave[i] );

          //delay(50);

          //cal steps
          if (totave[i]>threshhold && flag==0)
          {
             steps=steps+1;
             flag=1;
          }
          else if (totave[i] > threshhold && flag==1)
          {
              //do nothing
          }
          if (totave[i] <threshhold  && flag==1)
          {
            flag=0;
          }
         // Serial.print("steps=");
         // Serial.println(steps);
         return(steps);
        }
      delay(100);
     }

title: Send Multiple Sensors Data into single Packet in Arduino

Answers: 0


body:
I'm trying to figure out how to program my new Raspberry Pico with Arduino, but don't see a port to select so I can't upload the blink sketch.

Here's what I've done:

- The Pico is working, I can program it with micro Python.
- Just in case, I brought the Pico back to factory settings with the nuke file.
- Installed support for the Pico in Arduino IDE. Version 2.1.0 of Arduino MBed RP2040 is installed.
- While keeping BOOTSEL pressed, I plug in the Pico to my laptop (Ubuntu 20.04)
- The board selected is "Raspberry Pi Pico"
- But the option to select a port is greyed out :-(

It seems that I am omitting some step during the installation, but can't figure out what it is.

Any ideas?

Thanks!

title: Greyed out port for Raspberry pico in Arduino IDE - Ubuntu 20.04

Answers: 2

body:
I've come across this and this is how I worked around it (on Windows, but I suspect the problem and solution is the same).

A brand new Pico or one not programmed by the Arduino IDE does not have a serial port, which is why you can't see one. Arduino sketches are compiled with a serial port automatically, so once a serial port exists, it can be used for future uploads.

The Arduino solution is to use the 'Export compiled binary' option (for any sketch) and upload the UF2 file (which should be generated into the sketch folder) using virtual USB drive interface. When the sketch starts, the serial port will be available and can be used for future sketch uploads.

Another solution is to use an [alternative Pico core][1]. This one does not need the port selected, but will find and upload to a Pico in bootloader mode via the virtual USB drive.

  [1]: https://github.com/earlephilhower/arduino-pico

body:
Had this issue and tried everything that was described on forums.

The thing that worked for me was: I held the bootsel button until it opened pico  folder, then port button activated in the IDE and I chose UF2 port and then after upload, pico showed at COM7


body:
I've read that the Arduino String is bad as it causes memory fragmentation, so I try to avoid them mostly. But I still have some occurences where I'm not quite sure if they are ok after all.

The first is in print statements:
I have a function which prints a success or error message to the serial port, like so: `Serial.println("Success");`. Is this ok or should I (for example) pre define the String using `#define SUCCESS "SUCCESS"`?

Which leads me to the next case, defines:
I'm using MQTT and have the topics defined like above, e.g. `#define TOPIC_COLOR "light/color"`. Is this fine?

A third one is with ArduinoJSON:
I'm using Strings as keys, like so `lights["red"] = redVal;`. This call is made at multiple places so I assume the string would be created multiple times? A workaround/improvement I've thought of is using an enum defining the properties and using that as key.

Thanks for all comments, tips and explanations!

title: How to properly handle the Arduino String

Answers: 1

body:
+1 to @majenko's comments. I tend to avoid the `String` class, as I like to know what is actually going on, and I stick to `char *` and `char []` in general (and the `stdlib` functions like `sprintf`, `strlen`, etc).

Couple of notes on your question:

1. `"foo/bar"` is fine. Some characters have special meanings in the C language itself, so you need to escape them with the `\`. For example if `"` was part of your literal string, you'd write `"foo\"bar\""`

2. I tend to use `ArduinoJSON` to _parse_. If my app is just _sending_ JSON payloads, I just build it with `sprintf` or `print` which results in smaller programs. But, I guess it is a matter of choice. It is a great library.


body:
I'm not an expert about Arduino and I'm studying to create a project related to the bees remote monitoring.

I would like to monitor the internal humidity and temperature and the weight of the beehive boxes.

About the weight parameter my idea is to make a structure with 4 load cells.

I watched some video tutorials related to the creation of a weight scale with Arduino. I saw that it's necessary to calibrate the scale without any weight on the scale every time that Arduino will be started.

I'm not able to understand if there is a way to have this calibration in a different way: I mean,  I will place the beehives on my weight scales only one time and Is not possible to remove and put them back for each calibration step.

Is it really necessary or is there a way to have the calibration with the weight on the scales also?

title: Weight scale with Arduino: calibration step

Answers: 2

body:
It may be that in this application (beehive monitoring) it is not required to re-calibrate your load sensors before each use.  When a person is observing a scale to measure their own weight they will be sensitive to the scale reading zero before each use.  Even though being, say, a lb off is likely less than a 1% error when measuring their total body weight.  [This site][1] talks about load cell calibration and "recommends a yearly recalibration interval".  They also talk about temperature compensation.

As temperature and humidity will be monitored.  And nonlinear load sensor response to weight can be compensated in software, consider testing your setup under different conditions to determine what considerations need to be taken into account to provide the desired accuracy.

[![This image is from https://www.futek.com/load-cell-calibration-services][2]][2]

This image is from https://www.futek.com/load-cell-calibration-services

  [1]: https://www.futek.com/load-cell-calibration-services
  [2]: https://i.stack.imgur.com/Ed0Fa.jpg

body:
What I can find about calibrating load cells is that they are subject to "electrical influence, mechanical effects, instrumentation faults and
loose cables etc."

In the case of beehives, I'd add temperature, water, ice, snow, dirt & dust, and debris from the bees. The calibration suggestions I found were to calibrate "periodically", which suggests to me that the suggestion to calibrate at every startup assumes that the calibration will be lost at every power-down. That does not have to be the case - it can be store in a non-volatile memory such as EEPROM.

What I do think you'll need to do is calibrate each cells at 0%, 10%, ..., etc., of its full load, probably to 120% or 130% to allow for wind loading and asymmetric loading within the hive, and at a range of temperatures, make a set of force vs. cell output and temperature, from which to interpolate to get the 4 partial hive-weights.

They probably will need to recalibrated periodically, but for your application, a tare-value, measured at a reproducible hive condition, may be sufficient, if all you need is a differential weight.


body:
I created a simple sketch that just tries to list the files in SPIFFS. The SPIFFS filesystem was created with the version of mkspiffs that's part of the esp8266 package. The upload all seems to work, but it only lists the first file and not the rest.

After running the sketch I downloaded the flash memory and it compared OK so nothing is being corrupted...

    $ esptool.py --port=/dev/ttyUSB0 read_flash  0x200000 0x10000 foo
    $ cmp html.img foo
    $

If I try the same with LittleFS then I get no files reported!

I also tried upgrading to the 3.0.0 libraries (and thus also the later version of mkspiffs that came with the library)

Clearly I'm doing something stupid and wrong!

Hopefully the following (showing how I build it, upload it) will help point out my mistake!

Thanks for any assistance...

================================================================

Creating Image file
This is done using the mkspiffs that comes with the package so it should(!) match the library used by the ESP8266

    $ ~/.arduino15/packages/esp8266/tools/mkspiffs/2.5.0-4-b40a506/mkspiffs -c html html.img
    /menu_frame.html
    /change_ap.html
    /top_frame.html
    /index.html
    /main_frame.html

Compiling with 4M2M memory layout

    $ arduino-cli compile --fqbn=esp8266:esp8266:nodemcuv2:eesz=4M2M
    Executable segment sizes:
    IROM   : 265840          - code in flash         (default or ICACHE_FLASH_ATTR)
    IRAM   : 26888   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)
    DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP
    RODATA : 800   ) / 81920 - constants             (global, static) in RAM/HEAP
    BSS    : 25120 )         - zeroed variables      (global, static) in RAM/HEAP
    Sketch uses 294776 bytes (28%) of program storage space. Maximum is 1044464 bytes.
    Global variables use 27168 bytes (33%) of dynamic memory, leaving 54752 bytes for local variables. Maximum is 81920 bytes.

Uploading, writing the bin at 0x0 and the filesystem at 0x200000

    $ python ~/.arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool/esptool.py --port=/dev/ttyUSB0 write_flash 0x0 SPIFFS.esp8266.esp8266.nodemcuv2.bin 0x200000 html.img
    esptool.py v2.8
    Serial port /dev/ttyUSB0
    Connecting....
    Detecting chip type... ESP8266
    Chip is ESP8266EX
    Features: WiFi
    Crystal is 26MHz
    MAC: b4:e6:2d:67:b1:45
    Uploading stub...
    Running stub...
    Stub running...
    Configuring flash size...
    Auto-detected Flash size: 4MB
    Compressed 298928 bytes to 219676...
    Writing at 0x00034000... (100 %)
    Wrote 298928 bytes (219676 compressed) at 0x00000000 in 19.5 seconds (effective 122.7 kbit/s)...
    Hash of data verified.
    Compressed 65536 bytes to 1353...
    Writing at 0x00200000... (100 %)
    Wrote 65536 bytes (1353 compressed) at 0x00200000 in 0.1 seconds (effective 4232.8 kbit/s)...
    Hash of data verified.

    Leaving...
    Hard resetting via RTS pin...

Results:

... It shows 2M for the filesystem.

... But only one file is listed?

... If I use LittleFS instead then no files are listed!

    Starting...
    Total size of FS is: 1953282
    Used size of FS is: 2259
    File list:
    /menu_frame.html
    Finished

And, finally, the sketch

    #include <FS.h>

    void setup()
    {
      Serial.begin(115200);
      delay(500);

      Serial.println("Starting...");

      SPIFFS.begin();

      FSInfo fs_info;
      SPIFFS.info(fs_info);

      Serial.print("Total size of FS is: ");
      Serial.println(fs_info.totalBytes);

      Serial.print("Used size of FS is: ");
      Serial.println(fs_info.usedBytes);

      Serial.println("File list: ");
      Dir dir = SPIFFS.openDir("/");
      while (dir.next())
      {
        Serial.println(dir.fileName());
      }
      Serial.println("Finished");
    }

    void loop() { }

title: SPIFFS and LittleFS don't show all my files with readdir() and can't open() them

Answers: 0


body:
**Very short version:**
Looking for a way to wirelessly get STEP and DIR signals (only those two signals) from an Arduino to a DRV8825 stepper driver about a meter away:

```Arduino -> STEP and DIR IO pins -> transmitter ) ) ( ( receiver -> DRV8825```
[![enter image description here][1]][1]

**Long version:**
For a project I've mounted an Arduino to a wooden board. The Arduino has a GRBL shield (basically a breakout board to four motor drivers for stepper motors (in my case the DRV8825)). Connected to this setup is a stepper motor. The power supply (NOT on the wooden board) for the motor is 24v, and I'm using a buck converter to take it down to 5v for the Arduino.
This whole board is rotating and the 24v gets passed to it using a custom sliding-contact with two contacts (24v and gnd).

Now this all works fine, but the problem is this: I have a second motor which I want to control from the same GRBL shield. But this motor is NOT on the rotating board.
If I place the motor driver next to this motor and power it from the same power supply (parallel to the sliding-contact) I have everything I need, except for the STEP and DIR signals from the Arduino.

Because there is no way I can add 2 more contacts to the sliding-contact (plus the signal would probably be too noisy anyway) I'm looking for a way to basically add a wireless bridge between the STEP and DIR output pins on the Arduino, and the STEP and DIR input pins on the motor driver. The motor and driver are about a meter away from the Arduino, so signal strength shouldn't be a problem.

I believe those well known 433Mhz transmitters are too slow for something like this, but I read most nRF24L01 modules are faster. Before I order some for a test setup, I was wondering if anyone already knows if this could work or not, knows a useful alternative, or has some suggestions for keywords to search for when trying to find another solution. I can find a lot of 'wireless' motor drivers online, but most are completely standalone units where the microcontroller is on the board, it's just controllable over wifi/bluetooth.

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

  [1]: https://i.stack.imgur.com/Zm3Gb.png
  [2]: https://i.stack.imgur.com/lp4LT.png

title: Wirelessly (but fast) transfer STEP and DIR output from Arduino to stepper driver

Answers: 1

body:
(Moved to "answer" for space; it's definitely not an answer. Sorry all!)

Minor points:

 * It's a motor controller shield; the GRBL is on the Arduino.
 * You'll need a motor controller at each motor; not clear if that's understood.
 * I'd also consider optical comms, although it has a different set of problems.

Ultimately I might approach this in a different way: instead of a single GCode box attempting to synchronize and control itself and an (essentially) independent system, I'd consider having a single GCode box (GBOX) controlling two independent systems (M1, M2).

GBOX would be a laptop/RPi/whatever that processes the "real" GCode. Based on the GCode commands, which in the end just tell motors what to do, I'd send each GCode command to its associated M1/M2 system.

How well this works depends a lot on the GCode, however; diagonals, arcs, etc. require motor cooperation, so a command like `G02 X2Y0 R2` might cause problems, even though we can pull out the `X` and `Y` data. How the GCode is generated matters, but note that GBOX could also interpolate "tricky" commands to break them into something a dual-target system might be able to understand.

The "meaning" of the moves also matters: there's "getting from one place to another" and "getting from one place to another while drawing a line": the former may (or may not) have requirements around what that actually means, while the latter requires coordinated motion, and even if you're splitting the commands up correctly, even a fraction of a second difference in receive/action time will matter. Of course, you could also transmit both motors' commands to both motors and rely on timing or cross-M*n* synch for starting their respective commands.

In the end it may be the only real way to make this work would be to have the "independent" systems be able to synchronize *with each other*, so that they know they're (a) ready to start, and (b) starting at the same time. GBOX could also potentially handle that synchronization as a "Go!!!" command is about as deterministic as it gets, especially if M1/M2 can receive a broadcast signal at the same time.

https://www.zikodrive.com/motor-control-case-studies-and-applications-2/a-remote-controlled-and-synchronised-stepper-motor-controller/ (very) briefly discusses the issues around synchronizing remote motors where their relative positions matter.


body:
Is there a macro (#define ...) somewhere in the bowels of Arduino IDE or core header files which tells me at compile time(!), if the `double` data type for a given platform/board is a true double precision floating point number (64 bit width) or "only" an alias for a single precision float (32 bit width)?

With Arduino, both can be the case. 8-bit AVR boards have `double` equal to `float`, ARM-based boards (like Arduino Zero) support "true" double precision.

I am working on a library which implements some bit-banging of floating point numbers (both single and double precision). Due to the low-level nature of the problem, there must be separate functions for `float` and `double`. I would like to do somthing like that:

```
uint32_t function_for_float(float f) {
    // function body here...
}

#if defined(HAS_64_BIT_DOUBLE)
uint64_t function_for_double(double d) {
    // function body here...
}
#endif
```

That way, a compile time error would be generated if somebody tried to use the "double" version on platforms which do not support the "true" double data type. I *want* the compiler error to be generated, because `function_for_double()` will do silently "the wrong thing" when fed a single precision float, leading potentially to difficult-to-debug problems.

Right now, I am defining a macro constant for every relevant board I own, like this:

    #if defined(ARDUINO_SAMD_ZERO) \
     || defined(SAMD_FEATHER_M0_EXPRESS) \
     || defined(ADAFRUIT_FEATHER_M4_EXPRESS)
        #define HAS_64_BIT_DOUBLE
    #endif

But this is ugly and not future-proof (new boards can/will become available...).

Any suggestions?

title: Conditional compilation depending on sizeof(double)

Answers: 1

body:
The `double` data type is almost universally 8-bytes long, so you could
simply

```c
#if !__AVR__
# define HAS_64_BIT_DOUBLE
#endif
```

Gcc provides a more specific macro though: `__SIZEOF_DOUBLE__`, which
has the same value as `sizeof(double)`. But I do not know whether it is
provided by other compilers.


body:
I'm making a Jack-Bluetooth module so that I can send music to the car (or other devices w/ Jack plug) without an internal Bluetooth module in the car.

https://habr.com/en/post/456182/ says that I need around 44 kHz of sampling frequency to get high quality sound. Is there a BT module on the market w/ these specs?

https://arduino.stackexchange.com/questions/69034/audio-recording-using-arduino-bt-module says that the HC-05 HC-06 HC-07 are not good enough.

If there are no such cases, I think I should consider buying an Arduino that has an built-in BT/WiFi module or I can buy such a BT transmitter but beats the fun.

title: Make a Jack-Bluetooth Module for the car

Answers: 0


body:
I've tried using several libraries such as TinyGSM, SoftwareSerial, AT commands but I'm guessing the problem to be with my GET request url is https://script.google.com/macros/s/GAS_ID/exec?tag=1234&value=5678 and the Apps Script code is

       function doGet(e){
          Logger.log("--- doGet ---");

          var tag = "",
          value = "";

       try {

    // for debugging
    if (e == null){e={}; e.parameters = {tag:"test",value:"-1"};}

    tag = e.parameters.tag;
    value = e.parameters.value;

    // save the data to spreadsheet
    save_data(tag, value);

      return ContentService.createTextOutput("Wrote:\n  tag: " + tag + "\n  value: " + value);

       }
     catch(error) {
       Logger.log(error);
    return ContentService.createTextOutput("oops...." + error.message
                                            + "\n" + new Date()
                                            + "\ntag: " + tag +
                                            + "\nvalue: " + value);
            }
          }

         // Method to save given data to a sheet
        function save_data(tag, value){
        Logger.log("--- save_data ---");

        try {

        // Paste the URL of the Google Sheets starting from https thru /edit
        // For e.g.: https://docs.google.com/..../edit
         var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/SPREAD_SHEET_ID/edit#gid=0");
    var dataLoggerSheet = ss.getSheetByName("Sheet1");

    // Get last edited row from DataLogger sheet
    var row = dataLoggerSheet.getLastRow();

    // Start Populating the data
    dataLoggerSheet.getRange("A1").setValue(tag);
    dataLoggerSheet.getRange("B1").setValue(value);
      //dataLoggerSheet.getRange("C" + row).setValue(tag); // tag
           /// dataLoggerSheet.getRange("D" + row).setValue(value); // value

        }

            catch(error) {
               Logger.log(JSON.stringify(error));
             }

             Logger.log("--- save_data end---");
              }
I've already tested the HTTP GET requests on other websites so there seems to be no problem with the device.
BTW this code (Apps Script) worked perfectly with nodeMCU with appropriate libraries and arduino code.
Please help me out.

title: Error Performing HTTP GET request on google sheets (Apps Script) using TTGO T-CALL

Answers: 0


body:
I have a [small motor][1], it powers fine from the 3V3 and GND output of the arduino nano ble 33. However I need to be able to switch it on and off. My first attempt was to use an output pin, but that doesn't supply enough power. I'm trying to use a 2N3904 transistor (my first time attempting to use one, so sorry if I've done something stupid). I've tried wiring it as follows, but no luck:

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

Is this possible, or do I need something more substantial like a reed switch?

  [1]: https://www.amazon.co.uk/gp/product/B082PM8L6X
  [2]: https://i.stack.imgur.com/YsV7v.png

title: Motor not switching with 2N3904

Answers: 1

body:
+ 1st : you have to put an appropriate resistor between the output of your arduino and transistor Base pin

+ 2nd : you have to connect you motor and biased transistor to >>>> a suitable power supply (which has enough current (Amps) on it's output)

you can use this circuit instead of yours :

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

+ 3rd : don't forget to use the diode in the schematic; it protects transistors from you motor coil's spikes you can use 1n4147 ( it depends on the size of your motor but i think, it works for you ( i wasn't successful to take a look at your motor and it's specifications )

+ 4th : ignore the number of transistor, you can use your transistor (2N3904) instead of it

+ 5th :NOTICE : this circuit has a problem, you have to connect appropriate power supply and replace "arduino 5 volts" by the + of your power supply in this circuit schematic

good luck

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


body:
I have written a library that contains a statically allocated buffer (f.g. `struct taskList proc[TBL_SIZE];`)

TBL_SIZE is a macro currently defined in my .h file.

I have heard that there's a way to set or reset the define statement inside the .ino file to customize this setting for some libraries, but I don't know how to do this myself, and by the time I realized that this was a problem I had forgotten what library allowed this setting.

This would be extremely useful as currently I have to edit my library every time I build a new project (or worse, am working on several at once with different settings).

My guess was a variant on an include guard, like this
```
#ifndef TBL_SIZE
#define TBL_SIZE 16 /*(or whatever)*/
#endif
```
block, but that failed to work. I tried it during a final project, so my memory is fuzzy from lack of sleep (and time, now), but I'm fairly sure I got an "undefined" error.

I don't know what this is called to search for it otherwise, so I'm hoping someone can help.

---

Here is more information about my specific issue:

In my .h (at the top, after the regular include guard):
```
#ifndef TBL_SIZE
#define TBL_SIZE 16
#endif
```
(Note that everything works if I just set this directly without the defines)

Further down the .h, inside my class:
```
struct task processes[TBL_SIZE];
```
In the main .ino file before the library includes:
```
#define TBL_SIZE 6
#include <CoRTOS.h>
```
---

Debug output of the build (I know from experience it built with 16 instead of 6 entries in that table from the memory size. The low memory warning is another big clue.)
```
Linking everything together...
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\sketch\\ECE554_ASP.ino.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\CoRTOS\\CoRTOS.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\glcdfont.c.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_GFX.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_GrayOLED.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_SPITFT.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_BusIO_Register.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_I2CDevice.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_SPIDevice.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Wire\\Wire.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Wire\\utility\\twi.c.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_SSD1306\\Adafruit_SSD1306.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\SPI\\SPI.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\SparkFun_BME280_Arduino_Library-master\\SparkFunBME280.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/core\\core.a" "-LC:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761" -lm
C:\Users\rdrag\Documents\Arduino\libraries\CoRTOS\src/CoRTOS.h:38:7: note: array types have different bounds
 class cortos_class {
       ^
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.eep"
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.hex"
Multiple libraries were found for "Adafruit_GFX.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_GFX_Library
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit-GFX-Library-master
Multiple libraries were found for "Adafruit_I2CDevice.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO-master
Multiple libraries were found for "Adafruit_SSD1306.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306-master
Using library CoRTOS at version 0.2.0 in folder: C:\Users\rdrag\Documents\Arduino\libraries\CoRTOS
Using library Adafruit_GFX_Library at version 1.10.7 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_GFX_Library
Using library Adafruit_BusIO at version 1.7.3 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO
Using library Wire at version 1.0 in folder: C:\Users\rdrag\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3\libraries\Wire
Using library Adafruit_SSD1306 at version 2.4.5 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306
Using library SPI at version 1.0 in folder: C:\Users\rdrag\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3\libraries\SPI
Using library SparkFun_BME280_Arduino_Library-master at version 2.0.9 in folder: C:\Users\rdrag\Documents\Arduino\libraries\SparkFun_BME280_Arduino_Library-master
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf"
Sketch uses 28172 bytes (91%) of program storage space. Maximum is 30720 bytes.
Global variables use 1609 bytes (78%) of dynamic memory, leaving 439 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.
```

title: Customizing system settings with defines?

Answers: 1

body:
>I have heard that there's a way to set or reset the define statement inside the .ino file to customize this setting for some libraries, but I don't know how to do this myself

There are many ways to achieve what you want, you might not even need the `#ifndef` macro, use your library class construct to allow user to pass in the list size as an argument and but set the argument with a default value.

**YourLibrary.h**
```
class YourLibrary
{
private:
  size_t _userSize;
public:
  YourLibrary::YourLibrary(size_t listSize = 16) {
    _userSize = listSize;
  }
  ...
}
```

**User's sketch .ino**
```
#include <YourLibrary.h>

#define LIST_SIZE 32;

YourLibrary instance(LIST_SIZE);  // instance() would set the _listSize to 16

setup() {

}

loop() {

}
```


body:
I want to connect a small motor (water pump) to an arduino, and I am not sure about the circuit.

The pump is small, works with 3.3V, but consumes 0.1A so I decided to use a transistor. The one I have is BF547, an NPN type small transistor. It supports currents up to 100 mA.

I measured the hfe (beta) of the transistor, and it is 370. The Vcc is 3.3V, and the current through the motor is 0.1 A, therefore:

A. the Ib equals to Ic/hfe = 0.1A/370 giving Ib = 0,00027A

B. with the Vb at 3.3V(pin voltage) and Vbe at 0.7 (datasheet) the Rb = (Vb-Vbe)/Ib = 9558 Ohm (10kOhm)

My questions are:
1. Did I calculate the base resistance correctly?
2. Do I need any additional resistor for the collector, next to the pump? Is it possible that more current flows through the collector-emitter?
3. According to the datasheet of BF457 100mA is the max Ic it can take. Should I limit the pump by adding a small (10 Ohm) resistor to it (33 Ohm[motors resitance] + 10 Ohm for 3.3 V gives a current of 76 mA)

I am attaching the schematics (linear voltage regulator is there only to stabilise the Vcc provided by an old dc power source I found)

Thanks a lot for any suggestions!

[![circuit][1]][1]

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

title: connecting a small motor to arduino using a transistor

Answers: 2

body:
I like your thought process (even though it might not be completely correct), I've seen how little thought were put in for such simple circuit design in the Arduino community, including from some Youtuber celebrity who teaching Arduino and claims to have an EE degree.

BF547 is an RF amplifier transistor, not for switching application, it would be better to use an NPN transistor such as [2N3904](https://media.digikey.com/pdf/Data Sheets/NXP PDFs/2N3904.pdf) which is designed for switching application and has a Ice of 200mA.

Your resistor value is too high. If your motor is designed to operate at 100mA 3.3v condition, you would want your driver to provide AT LEAST that current. Assuming your are driving the transistor with 5V out from an Arduino, a 1k bias resistor would limited the Ibe to (5 - 0.7Vbe)/1000=4.3mA, take a very conservative DC current gain of 30 (it typically in the range of 30 - 80 for switching transistor, and hfe could be in the range of 100 - 300 when frequency go up, but this will not be the case for Arduino even you drive the motor using PWM), which will capable to deliver Ice of 4.3 x 30 = 129mA. This should meet your Motor requirements.

You would need a protection diode connected between 3.3V and collector with its cathode connect to 3.3V and its anode connect to the collector of the transistor. An 1N4148 (max If=200mA) would be okay for this specific motor, or even better, use any Schottky diode with current and voltage limit higher than your application).

body: 4.6V - 1.2V (2 diode drops of 0.7V) = 3.4V, close enough for the motor if you are using a MOSFET as a driver. You can use a UIS rated MOSFET with a Vgs of less than 4 and it will work perfectly. the transistor will give you an additional voltage drop of about 0.7 Volts and needs a base resistor. If you want to guarantee the motor will not start during reset and setup() add a 10K resistor from the port pin to ground.


body:
I am using VMEL6040 sensors and occasionally under bright light the read can hang, rather than using a wdt to recover I would like to ask some questions about the library.

as for debugging the sensors run stabley (several days at reads every 250 ms) in low light, but over 6k lux they can crash.

I am using wire.h here

in the header

    TwoWire *_i2cPort;

the read value calls the ReadRegister function:

    uint16_t SparkFun_Ambient_Light::_readRegister(uint8_t _reg)
    {

      uint16_t _regValue;

      _i2cPort->beginTransmission(_address);
      _i2cPort->write(_reg); // Moves pointer to register.
      _i2cPort->endTransmission(false); // 'False' here sends a restart message so that bus is not released
      _i2cPort->requestFrom(_address, static_cast<uint8_t>(2)); // Two reads for 16 bit registers
      _regValue = _i2cPort->read(); // LSB
      _regValue |= uint16_t(_i2cPort->read()) << 8; //MSB
      return(_regValue);

    }

is there a reason they are not checking the return of the `_i2cPort->endTransmission(false);`call? I am wondering if I should check that and not call the `requestFrom` if it does, i.e.:

    uint16_t SparkFun_Ambient_Light::_readRegister(uint8_t _reg)
    {

      uint16_t _regValue;

      _i2cPort->beginTransmission(_address);
      _i2cPort->write(_reg); // Moves pointer to register.
      if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released
          _i2cPort->requestFrom(_address, static_cast<uint8_t>(2)); // Two reads for 16 bit registers
          _regValue = _i2cPort->read(); // LSB
          _regValue |= uint16_t(_i2cPort->read()) << 8; //MSB
          return(_regValue);
      }
      else
          return 0;
    }

Or could my error be from the static casting do int?

title: Read from lux hangs in bright light

Answers: 1

body:
so I think I got it, the problem was that on a fail wire.read() returns an int -1
when that gets converted to a unint16 its a big number then it gets left shifted and overflows

the solution was:

    uint16_t SparkFun_Ambient_Light::_readRegisterLight(uint8_t _reg)
    {
        int lsb;
        int msb;

        _i2cPort->beginTransmission(_address);
        _i2cPort->write(_reg); // Moves pointer to register.
        if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released

            unsigned long tstamp = millis();
            while ((_i2cPort->available() < 2) && ((millis() - tstamp) < 10));

            if ((_i2cPort->available() < 2)) {
                _i2cPort->requestFrom(_address, 2); // Two reads for 16 bit registers
                lsb = _i2cPort->read(); // LSB
                msb = _i2cPort->read(); //MSB

                if ((lsb >= 0) && (lsb <= 256) && (msb >= 0) && (msb <= 256)) {
                    _regValue = lsb + msb * 256;
                }
            }

            return(_regValue);
        }
        else
            return _regValue;//last read
    }

This contains some extra error handling I added, but will leave in such as:

 1. timeout on waiting for a response
 2. checking on properly closing the bus in end transmission
 3. checking for errors from the read

I didn't do error handling as I would need to rewrite the whole library, and for my application repeating the last reading is sufficient.


body:
i have problem to upload the LCD I2c Example program to Arduino UNo. the code are shown below:

```
//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup()
{
  lcd.init();                      // initialize the lcd
  lcd.init();
  // Print a message to the LCD.
  lcd.backlight();
  lcd.setCursor(3,0);
  lcd.print("Hello, world!");
  lcd.setCursor(2,1);
  lcd.print("Ywrobot Arduino!");
   lcd.setCursor(0,2);
  lcd.print("Arduino LCM IIC 2004");
   lcd.setCursor(2,3);
  lcd.print("Power By Ec-yuan!");
}

void loop()
{
}
```
the schematic is like the below photo:

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

but i get this error:

```
Sketch uses 3382 bytes (10%) of program storage space. Maximum is 32256 bytes.
Global variables use 327 bytes (15%) of dynamic memory, leaving 1721 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```
Thank.

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

title: avrdude: stk500_recv(): programmer is not responding Arduino LCD_I2C Upload problem ( port not found and ...)

Answers: 0


body:
 Sketch
arduino-uno programming
 1 Button and 1 Potentiometer

Sketch: Each time the button is pressed, acquire the value of the potentiometer in a array of 10 positions of these values do the average and print it on the serial monitor or display.

At the end print the average (sum of values / 10)

    #define BUTTON 5
    #define ARRAY_SIZE 10
    int counter = 0;
    int valori[ARRAY_SIZE];
    int pinPotenziometro = A0;
    int statoPresenteBottone = LOW; //why so LOW?
    float media = 0.0;
    void setup() {
      Serial.begin(9600);
      pinMode(BUTTON, INPUT);
      for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
    }
    void loop() {
      if (counter > ARRAY_SIZE) {
        counter = 00;
        media = 0.0; // when we fill array fully - we start again
        for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
      }
      statoPresenteBottone = digitalRead (BUTTON);
      while (statoPresenteBottone == HIGH) {
        valori[counter] = analogRead(A0);
        media = media + valori[counter];
       Serial.print("Average: ");
       Serial.println(media / counter);
       Serial.print("Button pressed times: ");
       Serial.println(counter);
        statoPresenteBottone = LOW;
        counter++;
      }
    }

Can u guys edit the Sketch? Cuz if u try It on tinkercad with adding a potentiometer+ a button u will see he does the average after each value we acquired but i need to do that at the end...
I dont need explaining of how i should i do It cuz the teacher did that already but these are my skills D: if u guys can edit the sketch and solve this problem would be cool thx

title: 1 Button + Potentiometer

Answers: 0


body:
    #include <SoftwareSerial.h>

    const byte rxPin = 2;
    const byte txPin = 3;

    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(115200);
      ESP8266.begin(115200);
      delay(2000);
    }

    void printResponse() {
      String s="";
      while (ESP8266.available()) {
        s+=ESP8266.readStringUntil('\n');
      }

      Serial.println(s);
      // now here you can parse and look for "+IPD" look for another line ending (if there is) and then extract the numeric value.
    }

    void loop() {

      ESP8266.println("AT+CIPMUX=1");
      delay(1000);
      printResponse();

      ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
      delay(1000);
      printResponse();

      String cmd = "GET /test.html HTTP/1.1";
      ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
      delay(1000);

      ESP8266.println(cmd);
      delay(1000);
      ESP8266.println();
      delay(1000);
      printResponse();

      delay(5000);
    }

i have run this code and i am able to get this  response from server like "+ipd 4,41".... what does it mean?
here is the response after run the code in arduino......

    WIFI GOT IP
    AT+CIPLUX=1

    OK
    AT+CHPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

    4,CONNEC
    AR)CR5NB⸮b⸮⸮k

    j⸮L⸮⸮
    Recv 27 bytes

    SEND OK

    +IPD,4,41

Thanks in advance.....

title: How esp8266 gets response from server..?

Answers: 2

body:
There's two things to know here:

1. You're seeing corruption in your output because SoftwareSerial is not capable of working reliably at 115200 baud. You need to reconfigure your ESP8266 to operate at a lower baud rate (such as 9600) to be able to use it with an Arduino that doesn't have enough physical UARTs.
2. The response `+IPD,4,41` is telling you *about* the response. It's not itself the response.

It means "IP Data on channel 4 of length 41". It is then your responsibility to request that data from the ESP8266 using whatever AT command the ESP8266 requires.

Personally I would scrap the AT firmware and program the ESP8266 directly. That way you solve both problems: you can choose what baud rate to communicate at (if you even need to communicate to an Arduino at all), and you have no AT commands to parse or craft. It is a far more efficient way of working with the ESP8266 that trying to fudge things with the AT firmware and an Arduino.

body:
`SoftwareSerial` does not works well for baud rate higher than 9600bps, you need to change your Arduino and ESP8266 to operate at 9600bps.

1) Use the `AT+UART_DEF=9600,8,1,0,0` to set the ESP8266 to 9600Baud, with 8 bit, 1 stop bit and no parity. And also remember to configure the Arduino accordingly. The AT command with _DEF suffix means it will only need to be set once and the configuration will be saved in the ESP8266. [ESP8266 AT Command Set](https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf) would be handy when programming the ESP8266 with AT Commands.

2) Add longer delay after sending `AT+CIPSEND` and `Get` request as those network activities sometime take longer time to establish.

3) The `+IPD,4,41` means that Connect 4 (which you established with `AT+CIPSTART` is connected and there are 41 bytes payload waiting to be read. You can refer to [ESP8266 AT Command Examples](https://www.espressif.com/sites/default/files/documentation/4b-esp8266_at_command_examples_en.pdf) for more information.


body:
I have a electrolysis cell in which the anode is hanging using a Structure in a electrolyte. The cathode is at the bottom of the cell with electrolyte above it and anode being dipped into this electrolyte (not completely, a portion of the anode is dipped). The cell operates at 7  volts DC and 90000 amperes of current flowing through it. This is a typical electrolysis process of producing aluminium from alumina powder in a aluminium smelter. The cell is called a pot.
Now the question is I need to measure a potential drop on the anode rod. We usually take a meter to measure the potential drop on the anode rod and typically the reading are in millivolts. As the readings are in millivolts, it just indicates the drop in rod voltage due to resistance of rod. Now can I measure this millivolts drop using Arduino provided the voltage at one point of anode is 5 volts with respect to ground and the voltage at the other point is 4.95 volts with respect to ground, however the difference between these voltages is 0.5 volts and this is voltage I need to measure using Arduino and some arrangements as add on to it. How can I do this?
Can anyone help.
If you want more details, please comment. I will also provide more details.

So far I have done is tried measuring 1.5 volts on a pencil cell using Arduino by connecting A0 analog pin on Arduino to positive directly to the positive of 1.5 volts battery and ground of Arduino to the negative of Arduino.

Can I do the same for this millivolts measurements? I understand that the ground of Arduino and the 2nd point of anode measurement will not be at same potential, so shouldn't be connected together. I am scared to burn my board, so didn't try practically and wanted to get some opinion.

title: Differential voltage measurement using Arduino

Answers: 2

body:
As you do it with the multimeter: connecting ground to the lower potential (4.95 Volts in your example) and the volt probe to the higher potential (in your case 5.0 V), you can also connect the Arduino between the two potentials: Arduino GND to the lower (!) potential and A0, A1, ... or A7 to the higher (!) potential.

As long as you use the correct polarisation and the difference between the potentials is less than VCC of the ADC (5V Arduino ADCs) you should be save.

The resolution of the Arduino might be a problem. I don't know what resolution you need; 5V divided by 1024 is about 5 mV per step.

You might want to provide a reference Voltage at Vin of -let's say- 1 Volt if you need a better resolution. That would improve the resolution to about 1 mV per step. But then the meassured voltage must no exceed the 1 Volt reference voltage.

**EDIT (Gerben's comment)**

You could use the 1.1V internal reference of the ATMega328P (analogReference(INTERNAL))

And please let me give you a security advice: If the resistence in any part of your meassuring setup is significantly lower than the resistance between the messuring points (e.g you shorten the probe wires), then there is a chance that 90000 A running through this setup. That could burn away your hand, arm or even your life. Amperes kill; not Voltage. I've seen a wrench that was vaporized (ok, melted, ok glowing ;-) ) in a second, when it had fallen between the poles of a car battery (12 V; 300 Amps). An you operate with 90000 Amps. !

body: This is obviously a significant project, not something to economize on. I would recommend you use a separate difference amplifier to get a single-ended output referenced to the Arduino ground and scaled to maximize the 10-bit range use.  The diff amp can use its own supplies (+/-7.5 or +/-15, say) with the ground tied to the Arduino ground.  That way the Arduino only sees the difference, never the full 7 V no matter what.


body:
i have hosted a website on the 000webhost. And i have simply written a line in paragraph tags in html file( means i have created a html file..)

so i want to know to know how i get data that data in html file on the serial moniter through esp8266.

i have written a code in the arduino ide which is....
```cpp
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /index.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}
```

and the response on the serial moniter is
```txt
AT+CIPMUX=1

OK

AT+CIPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

4,CONNEC
AT+CIPSEND=4,28

OK
>
Recv 28 bytes

SEND OK

+IPD,4,412:HTTP/1.1 400 Bad Request
Date: Thu, 27 May 2021 18:07:45 GMT
Content-Type: text/html
Content-Length: 154
Connection: close
Server: awex
X-Xss-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Request-ID: 2eaf3c737a5348270ebe7873cab10088

<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>openresty</center>
</body>
</html>
4,CLOSED
```

what does it mean?

thanks in advance.......

title: how do i get data from the website? using arduino uno and esp8266

Answers: 0


body:
I'm trying to troubleshoot an issue with avrdude involving a Raspberry Pi and a transistor to control the reset pin on an Arduino Pro Micro (atmega32u4).

Where can I find information on the reset/programming process for the atmega32u4 or Arduino?  The atmega32u4 data sheet provides a bit of information but some of it is above my head.

For example, avrdude (and other programmers) require the microcontroller to be reset before uploading a new program or interacting (ie. fuses) with the chip.

Why is this?

The atmega32u4 specifies a minimum reset pulse of 400ns (ie. high to low to high again), but how long afterwards is the chip available for communication to avrdude?

title: What is the timing between reset and avrdude/spi communication? (re: avrdude problem)

Answers: 0


body:
I am attempting to use a stepper motor to rotate one of my split-flap displays. However despite the thing the motor is rotating weighing probably half a pound, it struggles to do so. It really can rotate the module at all.

**Why is my motor struggling so much?**

My circuit is an Arduino powered by 5V from a wall outlet, connected to a ULN2003 driver that is powered by a 12V wall outlet. The driver is connected to the stepper motor.

This is my code, it uses the Accel stepper library:
```
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <Stepper.h>

AccelStepper stepper2(AccelStepper::FULL4WIRE, 4, 5, 6, 7);

void setup()
{
    Serial.begin(9600);
    pinMode(0, OUTPUT);
    pinMode(1, OUTPUT);
    pinMode(A0, OUTPUT);
    pinMode(A1, OUTPUT);
    pinMode(A2, OUTPUT);
    pinMode(A3, OUTPUT);
    pinMode(A4, OUTPUT);
    pinMode(A5, OUTPUT);

    stepper2.setMaxSpeed(100);
    stepper2.setAcceleration(10);
    stepper2.moveTo(-24000000);

}
void loop()
{
    // Change direction at the limits
    //printletters();

    if (stepper2.distanceToGo() == 0)
        stepper2.moveTo(-stepper2.currentPosition());

    stepper2.run();
}
```
Edit: Here is the schematic, I'm sorry its terrible but I dont know how to make it better

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

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

<!-- End schematic -->

title: 12V 28BYJ-40 motor is not generating enough torque

Answers: 1

body: The grounds needed to be shared. The driver board ground needed to be connected to the Arduino ground. Otherwise your putting 17V in and only taking 12V out. Thanks to DaveNewton for this answer. I made this change and the torque was immediately fixed!


body:
I am trying to communicate with PC by using modbus TCP communicate. When I use this code I can't communicate. Dou you know guys what is the problem? My ethernet Module is working I know that because I can ping it when I use different code from EtherCard.h library. But when I try to use Ethernet and Modbus library I can't communicate. I can't ping it.

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

    int setPoint;zz
    const int setPoint_IR = 100;

    ModbusIP mb;

    void setup() {
      Serial.begin(9600);
      byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
      byte ip [] = {10, 0, 58, 37};
      mb.config (mac, ip);

      mb.addIreg(setPoint_IR);

    }

    void loop() {
      mb.task();
      setPoint = analogRead(A0);
      mb.Ireg(setPoint_IR, setPoint);
    }

    void DisplaySetPointValues(){
      String Printstr;
      Printstr = "Set point values = " + String(setPoint);
      Serial.println(Printstr);
    }

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

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

title: ARDUİNO MODBUS TCP CONNECTİON

Answers: 0


body:
Hey I'm trying to test out the CMAT/OSC library for Arduino and just want to get up and running sending SLIP encoded OSC messages. I've been able to observe the typical Serial monitor when sending OSC Messages that way, but I cannot seem to get the example code to compile:

```cpp

    #include <SLIPEncodedSerial.h>
    #include <OSCData.h>
    #include <OSCBundle.h>
    #include <OSCBoards.h>
    #include <OSCTiming.h>
    #include <OSCMessage.h>
    #include <OSCMatch.h>
    #include <SLIPEncodedUSBSerial.h>

    SLIPEncodedUSBSerial SLIPSerial( thisBoardsSerialUSB );
    // SLIPEncodedSerial SLIPSerial(Serial);

    void setup() {
      //begin SLIPSerial just like Serial
      SLIPSerial.begin(9600);   // set this as high as you can reliably run on your platform
    }

    void loop(){
      //the message wants an OSC address as first argument
      OSCMessage msg("/address");
      msg.add("Hello World\n");
    ;

      SLIPSerial.beginPacket();
      msg.send(SLIPSerial); // send the bytes to the SLIP stream
      SLIPSerial.endPacket(); // mark the end of the OSC Packet
      msg.empty(); // free space occupied by message
      delay(20);
    }
```
Furthermore this is the output error I see:
```
error: 'SLIPEncodedUSBSerial' does not name a type; did you mean 'SLIPEncodedUSBSerial_h'?
   10 | SLIPEncodedUSBSerial SLIPSerial( thisBoardsSerialUSB );
      | ^~~~~~~~~~~~~~~~~~~~
      | SLIPEncodedUSBSerial_h
exit status 1
'SLIPEncodedUSBSerial' does not name a type; did you mean 'SLIPEncodedUSBSerial_h'?
```

Could someone lend some clarity on what "thisBoardsSerialUSB" and "Serial" are in this context? I thought that the SLIPEncodedSerial / SLIPEncodedUSBSerial constructors simply take a reference. This might be trivial, but I am not sure how to properly instantiate these classes within the Arduino IDE.

Cheers!

title: Cannot instantiate SLIPSerial object used in OSC/SLIPSerial classes for Arduino

Answers: 0


body:
I'm trying to write code that should result in a click of the mouse, based on dwell time. I'm getting data from a gyroscope to move the mouse around. I'm not sure what the best way is to approach this from a coding perspective.

My current thinking in pseudocode is below. Basically it should be a rolling total of the last X sensor measurements, which is then compared to a dwell size/radius variable.

On a high level, what would be a feasible approach? I tried a couple of times with for loops and different code, but didn't get anywhere close. I would really appreciate advice about whether my high-level approach is even feasible. Thank you!

    update array with sensor measurements for (i =  dwell time) ();
     update sum of the array = + i measurement; - (i - size of the array) measurement at each sensor measurement
    if at last element of array
     if sum of the array < dwell radius; click
     loop to the beginning of the array

Though I'm not sure if `(i - size of the array) measurement` is even possible to do, since it could result in negative i values.

title: Clicking a mouse based on dwell time / how to code a rolling total of sensor measurements

Answers: 0


body:
I am experimenting with Aquaponics and since I am a software developer I found it "smart" to use arduino/raspberry in order to control the water flow and not simply use a water pump with mechanical means.

The advantage is that I am able to expand easier the system. The disadvantage is that I haven't yet met the reliability that I would lie to have.
I am a software engineer with basic knowledge in the hardware field. That is why I thought of starting with Raspberry.

Initially I made a setup with a single raspberry PI a few float sensors like this: https://www.hellasdigital.gr/electronics/sensors/humidity-sensor/tank-pool-water-level-liquid-sensor-float-switch/

and relay like this one: https://wiki.52pi.com/index.php/DockerPi_4_Channel_Relay_SKU:_EP-0099

I saw that sometimes the system was hanging with the relays open! This had the side effect to loose water. This is the most precious in aquaponics!

Thus I thought of creating a cluster. Thus I made a cluster of three Raspberrys. The two had the relays and only one PI had the sensors. In order to open the water pump both PIs should have given the green light. This worked better and when one of the PIs hanged then we lost no water.

But again I am thinking that it was not acceptable that the system was hanging so often (at least several times per week). Thus I thought maybe if I use an Arduino for this purpose then this would be better.

Thus this is what I did. I created a simple program (no cluster and a single Arduino). Unfortunately this had even worst results!!!

For the Arduino I used normal 5 Volt relays like this one: https://www.nettop.gr/index.php/hlektronika/relay/8-channel-5v-relay-module-with-light-coupling-5v.html and the same float sensors.

I do not believe that is software related the issue but it must be hardware.
The problem is that my knowledge in the hardware field is limited!
What should I do in order to prevent this? Do you think that is related with the water pumps and the relays ?

The same erroneous behavior happens at both the Raspberry and Arduino, I mean that the relay stays open and the water overflows. For Raspberry I can tell that the system stop to respond, I am sure about it. But for Arduino I cannot say for sure if the whole system was frozen or if input only for the float did not work.

I paste a link to the quick and dirty Arduino code as well for your reference.
The temperature were the systems were operating could be quite hot (30 ~ 48 degrees Celsius) for several hours.

Here is the code for the Arduino:

```c++
#define POT_1_FLOAT_SENSOR  2
#define POT_1_RELAY_1       11

#define PIPE_1_FLOAT_SENSOR  5
#define PIPE_1_RELAY_1       9

#define PIPE_2_FLOAT_SENSOR       3
#define PIPE_2_RELAY_2      10

#define PIPE_3_RELAY_3       12
#define PIPE_3_FLOAT_SENSOR       4

// pot 1
const unsigned long POT_1_MAX_WATERING_PERIOD = 120000;
const unsigned long POT_1_DRAIN_PERIOD = 70000;

unsigned long pot1StartMillis = 0;
unsigned long pot1DelayStartMillis = 0;

// Pipe 2
const unsigned long PIPE_2_MAX_WATERING_PERIOD = 300000;
const unsigned long PIPE_2_DRAIN_PERIOD = 300000;

unsigned long pipe2DelayStartMillis = 0;
unsigned long pipe2StartMillis = 0;

// Pipe 3
const unsigned long PIPE_3_MAX_WATERING_PERIOD = 760000;
const unsigned long PIPE_3_DRAIN_PERIOD = 300000;
unsigned long pipe3DelayStartMillis = 0;
unsigned long pipe3StartMillis = 0;

// Pipe 1
const unsigned long PIPE_1_MAX_WATERING_PERIOD = 180000;
const unsigned long PIPE_1_DRAIN_PERIOD = 300000;
unsigned long pipe1DelayStartMillis = 0;
unsigned long pipe1StartMillis = 0;

bool pot1RedFlag = false;
bool pot1SetStartTime = false;

bool pipe1RedFlag = false;
bool pipe1SetStartTime = false;

bool pipe2RedFlag = false;
bool pipe2SetStartTime = false;

bool pipe3RedFlag = false;
bool pipe3SetStartTime = false;

void setup()
{
  Serial.begin(9600);
  // initialize the pushbutton pin as an input:
  pinMode(POT_1_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(POT_1_RELAY_1, OUTPUT);
  digitalWrite(POT_1_RELAY_1, LOW);

  pinMode(PIPE_1_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_1_RELAY_1, OUTPUT);
  digitalWrite(PIPE_1_RELAY_1, LOW);

  pinMode(PIPE_2_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_2_RELAY_2, OUTPUT);
  digitalWrite(PIPE_2_RELAY_2, LOW);

  pinMode(PIPE_3_FLOAT_SENSOR, INPUT_PULLUP);
  pinMode(PIPE_3_RELAY_3, OUTPUT);
  digitalWrite(PIPE_3_RELAY_3, LOW);

  pot1StartMillis = millis();
  pipe1StartMillis = millis();
  pipe2StartMillis = millis();
  pipe3StartMillis = millis();
}

void loop()
{
  checkAbstractWateringTimer(pot1SetStartTime, pot1RedFlag, pot1DelayStartMillis,
                                POT_1_DRAIN_PERIOD, POT_1_MAX_WATERING_PERIOD,
                                pot1StartMillis, POT_1_FLOAT_SENSOR, POT_1_RELAY_1);

  checkAbstractWateringTimer(pipe1SetStartTime, pipe1RedFlag, pipe1DelayStartMillis,
                                PIPE_1_DRAIN_PERIOD, PIPE_1_MAX_WATERING_PERIOD,
                                pipe1StartMillis, PIPE_1_FLOAT_SENSOR, PIPE_1_RELAY_1);

  checkAbstractWateringTimer(pipe2SetStartTime, pipe2RedFlag, pipe2DelayStartMillis,
                                PIPE_2_DRAIN_PERIOD, PIPE_2_MAX_WATERING_PERIOD,
                                pipe2StartMillis, PIPE_2_FLOAT_SENSOR, PIPE_2_RELAY_2);

   checkAbstractWateringTimer(pipe3SetStartTime, pipe3RedFlag, pipe3DelayStartMillis,
                                PIPE_3_DRAIN_PERIOD, PIPE_3_MAX_WATERING_PERIOD,
                                pipe3StartMillis, PIPE_3_FLOAT_SENSOR, PIPE_3_RELAY_3);

  delay(200);
}

void checkAbstractWateringTimer(bool &abstractSetStartTime, bool &abstractRedFlag, unsigned long &abstractDelayStartMillis,
                                unsigned long abstractDrainPeriod, unsigned long abstractMaxWateringPeriod,
                                unsigned long &abstractStartMillis, int abstractFloatSensor, int abstractRelay) {
  if (!abstractSetStartTime || (abstractSetStartTime && millis() - abstractDelayStartMillis >= abstractDrainPeriod)) {

    if(digitalRead(abstractFloatSensor) == LOW && !abstractRedFlag) // Need one more condition in order to emulate the delay...
    {
      digitalWrite(abstractRelay, LOW);
      Serial.println("Pot 1 pump is open");

      // Set it only once at the beginning
      if (pot1SetStartTime) {
        abstractStartMillis = millis();
        abstractSetStartTime = false;
      }

      Serial.print("duration ");
      Serial.println(millis() - abstractStartMillis);

      if (millis() - abstractStartMillis >= abstractMaxWateringPeriod)  //test whether the MAX watering period has elapsed
      {
        // Close pump and do not oopen it again. Red Flag...
        Serial.println("Pot 1 pump is closed and the red flag is ON");
        digitalWrite(abstractRelay, HIGH);
        abstractRedFlag = true;
      }
    }
    else
    {
      Serial.println("Pot 1 Pump is closed");
      digitalWrite(abstractRelay, HIGH);
      abstractSetStartTime = true;
      abstractDelayStartMillis = millis();
    }
  }
}
```

Please any ideas, suggestions or tests that I could do are more than welcome in order to create a reliable system.

-- UPDATE --
Both when I was using Raspberry and Arduino I haven't included any resistors between the float sensor pins and the ground. Are there any chances that this is related with the instabilities that I experienced?

Maybe I should add a resistor (10K) between the float sensor pin and the ground?

Thank you

title: Arduino Uno - Raspberry PI - Float Sensors - Water pumps

Answers: 2

body:
thank you for your valuable input. I can say that now the system is stabilized.
The source of my issues was a faulty sensor but I have taken into account all advices. For example I separated the signal cables from the power cables that this was one more source of issues, I have introduced the pull up resistors, I have used separate power source for the relay module.

Generally for me ALL the comments from this thread were super important.

Thank you!

body:
As requested, I've collated my comments into an answer.

How long are the cable runs? Is there any electrically noisy equipment near the cable runs? Consider using some form of galvanic isolation to interface the float sensors to the MCU. Texas Instruments has a great series of videos on the subject of [galvanic isolation][1] which discusses inductive, capacitive and optical isolation techniques. Isolate the signals in both directions – both the inputs and the outputs.

For stronger pull-ups you could try 1K resistors, though this will use more current.

Something else to consider is debouncing the float sensor signals either in hardware with a low-pass RC filter or with a [software debouncer][2] (which I've put on GitHub).

The relays require 50 to 60 mA drive current but the Arduino pins can only supply 40 mA, so the external power supply is a good idea.

Redundancy, i.e. having multiple sensors for the same measurement, will guard against the loss of a single sensor causing chaos in a critical system, e.g. loss of precious water in a hot climate. You could have 3 float sensors for each water level at different locations, then use a voting system of >= 2 to take action. The system should also flag when sensors disagree so that someone can investigate the issue. And also route the cables via 3 different paths. This physical separation will guard against a single localised event (e.g. a wayward tractor or lightning strike) damaging all the sensors at the same time.

Also consider the fail-safe mode. For example, this could be to switch off all water valves when sensors disagree and then send an alert to someone and/or sound an alarm.

As your aquaponic farm is outside, consider lightning strike protection such as using TVS diodes on all inputs and outputs.

You could add feedback sensors to the relays to verify whether they have actually responded to the commands from the Arduino to switch on or off, i.e. compare commanded value with FB sensor value. These sensors could be pullup/pulldown resistors.

These additional relay FB sensors and the float sensors could be incorporated into the fail-safe logic. Some examples include:
1. If a relay is on when it's supposed to be off, flag the discrepancy.
2. If it takes 5 minutes to fill a tank and the inlet relay has been on for >5 minutes, it might be overflowing or dodgy sensors.
3. If the float sensors say a tank is empty, but the inlet relay has been on for >5 mins, something is wrong, e.g. leaking tank or dodgy sensors.
4. If it takes 10 mins to drain a tank but the float sensors say it's still full after 11 mins, something is wrong, e.g. blocked drain or dodgy sensors.
5. Are inlet and outlet relays on at the same time? Is this a valid condition?

There are many permutations. Happy coding...

  [1]: https://training.ti.com/ti-precision-labs-isolation-what-galvanic-isolation
  [2]: https://github.com/TimMathias/Arduino-Debouncer


body:
Im currently working on a datalogger that uses oled i2c displays and current sensors. Both of them uses adafruit libraries. To write the data, im using arduino's sd library, but somehow, the sd library interferes with my i2c components that they won't work while sd card functions work. adding any sort of code from the sd library would completely make the i2c components malfunction. To test this, i tried to view 2 different text in 2 different i2c displays.

Here's the current code where the i2c components work :

    #include <Adafruit_SSD1306.h>
    #include "SdFat.h"

    #define OLED_RESET 4
    Adafruit_SSD1306 Display1(OLED_RESET);
    Adafruit_SSD1306 Display2(OLED_RESET);

    int i, j;

    void setup()   {

      //Serial.begin(9600);

      Display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
      Display1.clearDisplay();
      Display1.display();

      Display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
      Display2.clearDisplay();
      Display2.display();

    }

    void loop() {

      Display1.setTextSize(1);
      Display1.setTextColor(WHITE, BLACK);
      Display1.setCursor(0, 0 );
      Display1.println("Hello");
      Display1.display();
      Display1.clearDisplay();

      Display2.setTextSize(1);
      Display2.setTextColor(WHITE, BLACK);
      Display2.setCursor(0, 0);
      Display2.println("There");
      Display2.display();
      Display2.clearDisplay();

    }

And here is the code where the components doesn't work

    #include <Adafruit_SSD1306.h>
    #include "SdFat.h"

    #define OLED_RESET 4
    Adafruit_SSD1306 Display1(OLED_RESET);
    Adafruit_SSD1306 Display2(OLED_RESET);
    SdFat SD;

    int i, j;

    void setup()   {

      //Serial.begin(9600);

      Display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
      Display1.clearDisplay();
      Display1.display();

      Display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
      Display2.clearDisplay();
      Display2.display();

    }

    void loop() {

      Display1.setTextSize(1);
      Display1.setTextColor(WHITE, BLACK);
      Display1.setCursor(0, 0 );
      Display1.println("Hello");
      Display1.display();
      Display1.clearDisplay();

      Display2.setTextSize(1);
      Display2.setTextColor(WHITE, BLACK);
      Display2.setCursor(0, 0);
      Display2.println("There");
      Display2.display();
      Display2.clearDisplay();

    }

Adding any sort of code that involves the sd card library like adding files or declaring the SD command itself would make the i2c components unusable, does anyone know how to fix this?

title: SD Card Library interferes with Adafruit

Answers: 0


body:
I have connected arduino nano every to my lcd display. It works perfect when i put all my code in setup() part. But when i put the code in loop() it does werid things. I have to put my code in loop(), because i am reading from load cell and displaying the values that are constantly changing. The delay can't be more than 250 ms.

This works well.
```
#include <LiquidCrystal.h>
int Contrast=30;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup(){
    analogWrite(6,Contrast);
    lcd.begin(16, 2);
    lcd.setCursor(0, 0);
    lcd.print("testing");
}

void loop(){

 }
```

When I do this next thing it works well for few seconds and then it starts to display random weird characters and stops displaying anything after some time.
```
#include <LiquidCrystal.h>
int Contrast=30;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup(){
    analogWrite(6,Contrast);
    lcd.begin(16, 2);
    lcd.setCursor(0, 0);

}

void loop(){

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(millis()/1000);
  delay(250);
 }
```

I have tried removing lcd.clear() it didn't help.
I thought it was a problem with wiring first, but it's not.
What am I doing wrong?

Any help would be great, thanks.

title: Arduino lcd displays random chracters

Answers: 1

body:
1. `lcd.setCursor(0, 0);` - you dont really need this funtion. `lcd.clear()` will always bring the cursor into the (0,0) position, automatically.

2. check your wiring. The code seems to be correct

3. Increase the delay to 500 ms or more. You don't have to write faster than 1 seconds to the LCD anyway


body:
I need to purchase a distance sensor that will be fixed in place and used to determine distance to the top of a fairly fast moving piston along the axial direction in line with the sensor. The top of the piston can be covered in whatever material works best for sensor accuracy, and the entire apparatus can operate in the dark if needed. Distance will range from 50mm to 500mm. Position measurement must have an accuracy range below 1.5mm. Update rate must be 1000hz or greater (i.e. update every 1ms or faster).

I see there are many options for me at high cost, but I'm limiting my budget to $500 and below for the next few days while I research more. This does not mean I won't spend whatever is needed however. As of now I've seen nothing acceptable for under that price, but it's hard to tell as many companies won't publish prices for these types of sensors.

I'm happy to explain more about the implementation if needed.

## UPDATE
I wish more people were reading this post, because I have great suggestions for DIYers after researching a lot of options the past few days. Currently I'm looking at offerings from Turck.com relating to reading a magnetized strip. This would read position from the side rather than from above or below as I describe in my original question. Turck calls it their "LM-2 line" and some options look pretty affordable and quite a bit under $500. Here's a brochure they provide - it documents how they read a magnetic strip: https://www.turck.us/attachment/B1027.pdf

## NOTE
There is one answer here related to a different sort of solution involving a device which reads a code every 0.5mm or 1.0mm taped to a rod which is attached to the piston. Device would read in direction perpendicular to direction of motion. This would probably be my 2nd or 3rd choice if I'm unable to find an affordable sensor as described in my question.

## NOTE 2
If I had time I'd implement the following solution which I wish I had thought of a month ago: tape a 300mm strip of reflective material which varies in reflectivity along its length. shine a laser on the tape and detect amount of light which reflects. simple solution, easy to calibrate and (if I knew where to get the tape) should be low cost.

title: Looking for an accurate and fast updating range sensor

Answers: 1

body:
Inside an inkjet printer, I've found a clear plastic strip with photo-engraved (loose approximation) lines perpendicular to the length of the strip. This strip passes through an optical pair, one side illuminates, the other reads. The strip stretches the entire width of the printer and if I recall correctly, the reading module is on the print head carriage. Consider that many printers are described as 600 dots per inch, which would create a resolution on the strip of 1/600" / 0.04 mm.

Additionally, I've discovered circular plastic encoders on which the rings of black/clear alternated the segment counts with each expanding ring. That is to say, the first ring was half black, half clear. The next ring out was 1/4 black/white alternating, the one following was 8 segments, then 16, etc.

This required a reader for each ring, but provided an absolute reference rather than a relative reference as is the case with the linear strip. One could create a linear strip which would work in a similar manner. One level would be half black, half clear, the next layer would be 1/4 black/clear, etc.

[![binary scale image][1]][1]

The requirement for 500 mm fits into a binary 512 value, which would require 9 stripes and provide for the accuracy noted in the post.

The aspect I can't answer is the speed of the encoding, although I suspect that any design based on an optical reader could be optimized to work.

I found an article at [rp-photonics.com][2]

> When light is diffracted at the traveling refractive index grating in
> an acousto-optic modulator, the diffracted light experiences a shift
> of optical frequency which is plus or minus the acoustic (or drive)
> frequency. That effect (which can be interpreted as a Doppler shift)
> is exploited in acousto-optic frequency shifters.
>
> Drive frequencies are typically between some tens and hundreds of
> megahertz, rarely more than 1 GHz. The resulting change of optical
> wavelength is quite small. For larger frequency shifts, or for
> realizing very small frequency shifts (e.g. only a few MHz), one may
> cascade two or more devices. It is also possible to use a double pass
> through a single device in order to obtain twice the frequency shift.

I think from reading that excerpt that the long strip in the inkjet printer is the traveling refractive index grating. I had not considered that a low-power laser could be substituted for a simple optical pair. Doing so would provided even better resolution.

If your project allows for a strip of sufficient length to be attached to the piston, with assurance that it won't buckle under acceleration and jam in the sensor, you'd probably make it work.

But wait, there's more. I can picture the rod on the piston alternately obscuring and uncovering a digital design, which is constantly scanned by a laser. This reduces the number of parts in close contact and possibly the moving mass.

  [1]: https://i.stack.imgur.com/4Q7Me.png
  [2]: https://www.rp-photonics.com/acousto_optic_frequency_shifters.html


body: Can Windows 10 computer use  Arduino IDE 1.8.10 sometimes, AND use Arduino IDE 2.0.0 the rest of the time?

title: Can a Windows 10 computer use Arduino IDE 1.8.10 sometimes AND use Arduino IDE 2.0.0 the rest of the time?

Answers: 0