body:
simplified my goal is to display a transitional Background and some shapes. This shapes are not moving hard rasterized by 1 pixel, more like .1 each cycle. So I need a way to interpolate the movement between the surrounding Neopixels.

Background works fine, so it's not relevant for now.

For the shapes the **first try** was to show a smooth movement of a square hardcoded. This works suitable, even its not bug free. I put the Code of the first attempt at the very end.

**After** that I wanted to implement an bitmap mask to show something more complex . That's where I am at currently. First of this attempt is to assume the whole mask is completly filled (again hardcoded).

The LEDs mostly keep completely on or off.

How do I get them fade them in an out at the outer sides?

I use an AI Thinker ESP 32 and 200 WS2812Bs.

Please ask any more infos that are required. Of course if you spot that my approach is unsuitable to begin with, pls tell me.

Infos for the Code: don't get lost on the "circle" variables. At the eary steps I showed a circle and soon realized its easier to step back to a Circle while working at the interpolation.

My Code with the bitmap
```
#include <Adafruit_NeoPixel.h>

#define PIN_NEO_PIXEL  13
#define NUM_PIXELS     400
#define num_row 20
#define num_col 20
#define circle_size_body 4
#define circle_size_border 5
#define circle_size_corona 7
#define DELAY_INTERVAL  100

float circle_PosX = 10;
float circle_PosY = 10;
int circle_direction = 1;
enum eIntersectingPart { None, Body, Border, Corona };

Adafruit_NeoPixel NeoPixel(NUM_PIXELS, PIN_NEO_PIXEL, NEO_GRB + NEO_KHZ800);

void setup()
{
  NeoPixel.setBrightness(100);
  NeoPixel.begin();
  Serial.begin(115200);           // set up Serial library at 9600 bps
}

float backgroundShift = 0;
float worldSpeed = .05;

void loop()
{
  if(circle_PosY <= 0 && circle_direction < 0
     || circle_PosY >= 10 && circle_direction > 0)
    circle_direction *= -1;
  circle_PosY += worldSpeed * circle_direction;
  circle_PosX += worldSpeed * circle_direction;
    Serial.print("circle_PosX ");
    Serial.print(circle_PosX);
    Serial.print(", circle_PosY ");
    Serial.print(circle_PosY);
 NeoPixel.clear();
    //Hintergrund setzen
    // setBackgroundColor();

 //Kreis malen
 drawCircle();

  // Serial.print("bgShift: ");
  // Serial.flush();
  NeoPixel.show(); // send the updated pixel colors to the NeoPixel hardware.
  // Serial.println(backgroundShift);
  backgroundShift += worldSpeed;
  delay(100);     // off time
}

uint32_t setBackgroundColor() {

  for(int led = 0; led < NUM_PIXELS; led++) {
    int coordinates[2];
    coordinateByLed(coordinates, led);

 byte ambientColors[3] = { 0, 0, 255 };
    int ambientCcolorS = (int)( sin( 0.3 * coordinates[0] + backgroundShift) * 127.0 );
    int ambientCcolorC = (int)( cos( 0.3 * coordinates[1] + backgroundShift) * 128.0);
    int amberC = (ambientCcolorS + ambientCcolorC + 255) / 2;

    NeoPixel.setPixelColor(
        led,
        NeoPixel.Color(amberC, amberC ,255));
  }
}

bool firstIteration = false;
void drawCircle() {
 //   x     y       Anteil
 byte bitmap[circle_size_corona + 1][circle_size_corona + 1];

 float startPositonX = circle_PosX - .5f * (float)circle_size_corona;
 float startPositonY = circle_PosY - .5f * (float)circle_size_corona;

 int lowerStartX = floor(startPositonX);
 int upperStartX = ceil(startPositonX);
 int lowerStartY = floor(startPositonY);
 int upperStartY = ceil(startPositonY);

 float proportionForLowerX = abs(upperStartX - startPositonX);
 float proportionForUpperX = 1 - proportionForLowerX;
 float proportionForLowerY = abs(upperStartY - startPositonY);
 float proportionForUpperY = 1 - proportionForLowerY;

 firstIteration = true;

 for(byte x = 0; x < circle_size_corona; x++) {
  for(byte y = 0; y < circle_size_corona; y++) {
   float proportion = 0;

   int lowerLedX = lowerStartX + x;
   int lowerLedY = lowerStartY + y;
   int upperLedX = upperStartX + x;
   int upperLedY = upperStartY + y;

   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
    byte currentX = x;
    byte currentY = y;
    proportion = proportionForLowerX * proportionForLowerY;
    bitmap[currentX][currentY] += (byte)(proportion * 100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);

    if(lowerLedX == 6 && lowerLedY == 6) {
     Serial.print(", x ");
     Serial.print(x);
     Serial.print(", y ");
     Serial.print(y);
     Serial.print(", partialProportion ");
     Serial.print(proportion);
     Serial.print(", newBitmapVal ");
                  byte newBitmapVal = bitmap[currentX][currentY];
     Serial.print(newBitmapVal);
     Serial.print(" || ");
    }
   }
   if(upperLedX >= 0 || upperLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
    byte currentX = x + 1;
    byte currentY = y;
    proportion = proportionForUpperX * proportionForLowerY;
    bitmap[currentX][currentY] += (byte)(proportion * 100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);
    if(upperLedX == 6 && lowerLedY == 6) {
     Serial.print(", x ");
     Serial.print(x);
     Serial.print(", y ");
     Serial.print(y);
     Serial.print(", partialProportion ");
     Serial.print(proportion);
     Serial.print(", newBitmapVal ");
                  byte newBitmapVal = bitmap[currentX][currentY];
     Serial.print(newBitmapVal);
     Serial.print(" || ");
    }
   }
   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    upperLedY >= 0 || upperLedY < num_row) {
    byte currentX = x;
    byte currentY = y + 1;
    proportion = proportionForLowerX * proportionForUpperY;
    bitmap[currentX][currentY] += (byte)(proportion * 100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);
    if(lowerLedX == 6 && upperLedY == 6) {
     Serial.print(", x ");
     Serial.print(x);
     Serial.print(", y ");
     Serial.print(y);
     Serial.print(", partialProportion ");
     Serial.print(proportion);
     Serial.print(", newBitmapVal ");
                  byte newBitmapVal = bitmap[currentX][currentY];
     Serial.print(newBitmapVal);
     Serial.print(" || ");
    }
   }
   if(upperLedX >= 0 || upperLedX < num_col
    &&
    upperLedY >= 0 || upperLedY < num_row) {
    byte currentX = x + 1;
    byte currentY = y + 1;
    proportion = proportionForUpperX * proportionForUpperY;
    bitmap[currentX][currentY] += (byte)(proportion * 100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);
    bitmap[currentX][currentY] = min(bitmap[currentX][currentY], (byte)100);
    if(upperLedX == 6 && upperLedY == 6) {
     Serial.print(", x ");
     Serial.print(x);
     Serial.print(", y ");
     Serial.print(y);
     Serial.print(", partialProportion ");
     Serial.print(proportion);
     Serial.print(", newBitmapVal ");
                  byte newBitmapVal = bitmap[currentX][currentY];
     Serial.print(newBitmapVal);
     Serial.print(" || ");
    }
   }

   firstIteration = false;
  }
 }

 firstIteration = true;
 for(int x = 0; x < circle_size_corona + 1; x++) {
  for(int y = 0; y < circle_size_corona + 1; y++) {
   int lowerLedX = lowerStartX + x;
   int lowerLedY = lowerStartY + y;
   int upperLedX = upperStartX + x;
   int upperLedY = upperStartY + y;

   if(
   // firstIteration
    lowerLedX == 6 && lowerLedY == 6
                  ||
     upperLedX == 6 && lowerLedY == 6) {
    Serial.print(", startPositonX ");
    Serial.print(startPositonX);
    Serial.print(", x ");
    Serial.print(x);
    Serial.print(", y ");
    Serial.print(y);
    Serial.print(", lowerLedX ");
    Serial.print(lowerLedX);
    Serial.print(", lowerLedY ");
    Serial.print(lowerLedY);
   }

   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
    setLedColorWithProportion(lowerLedX,lowerLedY, .01f * bitmap[x][y]);
   }

   firstIteration = false;
  }
 }

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

void setLedColorWithProportion(
 int coordX, int coordY,
 float proportion)
{
 int led = ledByCoordinate(coordX, coordY);
 uint32_t ledColor = NeoPixel.getPixelColor(led);
 uint8_t partialColor = (uint8_t)((proportion ) * 255.0f );

 uint8_t white = (ledColor>>24) & 255;
 uint8_t red = (uint8_t)((1.0f - proportion) * ((ledColor>>16) & 255))
  + partialColor;
 uint8_t green = (ledColor>>8) & 255;
 uint8_t blue = ledColor & 255;

 if(
 // firstIteration
 coordX == 6 && coordY == 6
 ) {
  Serial.print(", prop ");
  Serial.print(proportion);
  Serial.print(", redValOld ");
  Serial.print(((ledColor>>16) & 255));
  Serial.print(", redValNew ");
  Serial.print(red);
 }

 ledColor = white;
 ledColor = (ledColor<<8) + red;
 ledColor = (ledColor<<8) + green;
 ledColor = (ledColor<<8) + blue;
 NeoPixel.setPixelColor(
  led,
  ledColor);
}

int ledByCoordinate(byte column, byte row) {
  return (row  * num_col) + (column);
}

void coordinateByLed(int coordinates[2], int led) {
  coordinates[0] = led % num_col;
  coordinates[1] = led / num_col;
}

```
[![neoopixel][1]][1]

---

First attempt without bitmap
```
#include <Adafruit_NeoPixel.h>

#define PIN_NEO_PIXEL  13
#define NUM_PIXELS     400
#define num_row 20
#define num_col 20
#define circle_size_body 4
#define circle_size_border 5
#define circle_size_corona 7
#define DELAY_INTERVAL  100

float circle_PosX = 10;
float circle_PosY = 10;
int circle_direction = 1;
enum eIntersectingPart { None, Body, Border, Corona };

Adafruit_NeoPixel NeoPixel(NUM_PIXELS, PIN_NEO_PIXEL, NEO_GRB + NEO_KHZ800);

void setup()
{
  NeoPixel.setBrightness(100);
  NeoPixel.begin();
  Serial.begin(9600);           // set up Serial library at 9600 bps
}

float backgroundShift = 0;
float worldSpeed = .01;

void loop()
{
  if(circle_PosY <= 0 && circle_direction < 0
     || circle_PosY >= 10 && circle_direction > 0)
    circle_direction *= -1;
  circle_PosY += worldSpeed * circle_direction;
  circle_PosX += worldSpeed * circle_direction;
    // Serial.print("circle_PosX ");
    // Serial.print(circle_PosX);
    // Serial.print(", circle_PosY ");
    // Serial.print(circle_PosY);
 NeoPixel.clear();
    //Hintergrund setzen
    // setBackgroundColor();

 //Kreis malen
 drawCircle();

  // Serial.print("bgShift: ");
  // Serial.flush();
  NeoPixel.show(); // send the updated pixel colors to the NeoPixel hardware.
  // Serial.println(backgroundShift);
  backgroundShift += worldSpeed;
  //delay(100);     // off time
}

uint32_t setBackgroundColor() {

  for(int led = 0; led < NUM_PIXELS; led++) {
    int coordinates[2];
    coordinateByLed(coordinates, led);

 byte ambientColors[3] = { 0, 0, 255 };
    int ambientCcolorS = (int)( sin( 0.3 * coordinates[0] + backgroundShift) * 127.0 );
    int ambientCcolorC = (int)( cos( 0.3 * coordinates[1] + backgroundShift) * 128.0);
    int amberC = (ambientCcolorS + ambientCcolorC + 255) / 2;

    NeoPixel.setPixelColor(
        led,
        NeoPixel.Color(amberC, amberC ,255));
  }
}

bool firstIteration = false;
void drawCircle() {
 float startPositonX = circle_PosX - .5f * (float)circle_size_corona;
 float startPositonY = circle_PosY - .5f * (float)circle_size_corona;

 int lowerStartX = floor(startPositonX);
 int upperStartX = ceil(startPositonX);
 int lowerStartY = floor(startPositonY);
 int upperStartY = ceil(startPositonY);

 float proportionForLowerX = abs(upperStartX - startPositonX);
 float proportionForUpperX = 1 - proportionForLowerX;
 float proportionForLowerY = abs(upperStartY - startPositonY);
 float proportionForUpperY = 1 - proportionForLowerY;

 // int endX = lowerStartX + circle_size_corona;
 // int endY = lowerStartY + circle_size_corona;

 firstIteration = true;

 for(int x = 0; x < circle_size_corona; x++) {
  for(int y = 0; y < circle_size_corona; y++) {
   int lowerLedX = lowerStartX + x;
   int lowerLedY = lowerStartY + y;
   int upperLedX = upperStartX + x;
   int upperLedY = upperStartY + y;

   /*if(firstIteration) {
    Serial.print(", startPositonX ");
    Serial.print(startPositonX);
    Serial.print(", x ");
    Serial.print(x);
    Serial.print(", y ");
    Serial.print(y);
    Serial.print(", lowerLedX ");
    Serial.print(lowerLedX);
    Serial.print(", lowerLedY ");
    Serial.print(lowerLedY);
   }*/

   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
     setLedColorWithProportion(lowerLedX,lowerLedY, proportionForLowerX * proportionForLowerY);
   }
   if(upperLedX >= 0 || upperLedX < num_col
    &&
    lowerLedY >= 0 || lowerLedY < num_row) {
     setLedColorWithProportion(upperLedX,lowerLedY, proportionForUpperX * proportionForLowerY);
   }
   if(lowerLedX >= 0 || lowerLedX < num_col
    &&
    upperLedY >= 0 || upperLedY < num_row) {
     setLedColorWithProportion(lowerLedX,upperLedY, proportionForLowerX * proportionForUpperY);
   }
   if(upperLedX >= 0 || upperLedX < num_col
    &&
    upperLedY >= 0 || upperLedY < num_row) {
     setLedColorWithProportion(upperLedX,upperLedY, proportionForUpperX * proportionForUpperY);
   }

   firstIteration = false;
  }
 }
 // Serial.print(" ");
 // Serial.println();
}

void setLedColorWithProportion(
 int coordX, int coordY,
 float proportion)
{
 int led = ledByCoordinate(coordX, coordY);
 uint32_t ledColor = NeoPixel.getPixelColor(led);
 uint8_t partialColor = (uint8_t)((proportion ) * 255.0f );

 uint8_t white = (ledColor>>24) & 255;
 uint8_t red = (uint8_t)((1.0f - proportion) * ((ledColor>>16) & 255))
  + partialColor;
 uint8_t green = (ledColor>>8) & 255;
 uint8_t blue = ledColor & 255;

 ledColor = white;
 ledColor = (ledColor<<8) + red;
 ledColor = (ledColor<<8) + green;
 ledColor = (ledColor<<8) + blue;
 NeoPixel.setPixelColor(
  led,
  ledColor);
}

int ledByCoordinate(byte column, byte row) {

 /*if(firstIteration) {
  Serial.print(", column ");
  Serial.print(column);
  Serial.print(", row ");
  Serial.print(row);
  Serial.print(", ergebis ");
  Serial.print(((row  * num_col) + (column)));
 }*/
  return (row  * num_col) + (column);
}

void coordinateByLed(int coordinates[2], int led) {
  coordinates[0] = led % num_col;
  coordinates[1] = led / num_col;
}
```

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

title: WS2812b - Interpolate pixels on neopixel matrix with mask

Answers: 1

body:
thanks for your advice. I stepped back to a 1D model, simplified, altered and it worked, with complex models (in 1D XD), a hard coded Array. So finally I went on for 2D and extended the code. Now it works.

Yes, it's kind of anti-aliasing.

For next I am thinking how to display multiple Elements with transparency (caused by anti aliasing or pregiven transparency).

Thats all for now.

For all who may be interested, heres my current Code.

    #include <Adafruit_NeoPixel.h>

    #define PIN_NEO_PIXEL  13
    #define NUM_PIXELS     200
    #define num_col 20
    #define num_row 10
    #define DELAY_INTERVAL  100

    float circle_PosX = 6;
    float circle_PosY = 6;
    int circle_direction = 1;

    Adafruit_NeoPixel NeoPixel(NUM_PIXELS, PIN_NEO_PIXEL, NEO_GRB + NEO_KHZ800);

    void setup()
    {
      NeoPixel.setBrightness(255);
      NeoPixel.begin();
      // Serial.begin(115200);           // set up Serial library at 9600 bps
    }

    float worldSpeed = .01;

    void loop()
    {
     if(circle_PosX <= 0 && circle_direction < 0
      || circle_PosX >= 20 && circle_direction > 0
      || circle_PosY <= 0 && circle_direction < 0
      || circle_PosY >= 10 && circle_direction > 0)
     circle_direction *= -1;
     circle_PosX += worldSpeed * circle_direction;
     circle_PosY += worldSpeed * circle_direction;

     NeoPixel.clear();

     //Kreis malen
     drawCircle();

     NeoPixel.show(); // send the updated pixel colors to the NeoPixel hardware.
     // delayMicroseconds(500);     // off time
     // readInput();
    }
    uint8_t bitmap[5][5] = {
     {0,0,1,0,0},
     {0,1,0,1,0},
     {1,0,0,0,1},
     {0,1,0,1,0},
     {0,0,1,0,0},
    };

    void drawCircle() {
     for(uint8_t pixelX = 0; pixelX < 5; pixelX++) {
      for(uint8_t pixelY = 0; pixelY < 5; pixelY++) {
       if(bitmap[pixelY][pixelX] == 1) {
        writeCircleToLEDs(
         pixelX + circle_PosX,
         pixelY + circle_PosY);
       }
      }
     }
    }

    uint8_t writeCircleToLEDs(float circlePosX, float circlePosY) {
     int lowerLedX = floor(circlePosX);
     int upperLedX = ceil(circlePosX);
     int lowerLedY = floor(circlePosY);
     int upperLedY = ceil(circlePosY);

     float upperLedXAmount = circlePosX - lowerLedX;
     float lowerLedXAmount = 1.0 - upperLedXAmount;
     float upperLedYAmount = circlePosY - lowerLedY;
     float lowerLedYAmount = 1.0 - upperLedYAmount;

     float amountLowerXLowerY = lowerLedXAmount * lowerLedYAmount;
     float amountUpperXLowerY = upperLedXAmount * lowerLedYAmount;
     float amountLowerXUpperY = lowerLedXAmount * upperLedYAmount;
     float amountUpperXUpperY = upperLedXAmount * upperLedYAmount;

     setColorOfLed(lowerLedX, lowerLedY, amountLowerXLowerY);

     // if(lowerLedX != upperLedX)
     {
      setColorOfLed(upperLedX, lowerLedY, amountUpperXLowerY);
     }
     // if(lowerLedY != lowerLedX )
     {
      setColorOfLed(lowerLedX, upperLedY, amountLowerXUpperY);
     }
     // if(lowerLedY != upperLedY )
     {
      setColorOfLed(upperLedX, upperLedY, amountUpperXUpperY);
     }
     /*
     Serial.print("circlePosX ");
     Serial.println(circlePosX);
     Serial.print("lowerLedX ");
     Serial.println(lowerLedX);
     Serial.print("lowerLedXAmount ");
     Serial.println(lowerLedXAmount);
     Serial.println("--------------------");*/

    }

    void setColorOfLed(uint8_t ledX, uint8_t ledY, float amount) {
     int ledNumber = ledByCoordinate(ledX, ledY);
     uint32_t  baseColor = NeoPixel.getPixelColor(ledNumber);
     uint8_t newRedColor = ((baseColor >> 16) & 255);
     newRedColor += (255 * amount);

     baseColor &= ~(255 << 16);
     baseColor |= (newRedColor << 16);

     NeoPixel.setPixelColor(
      ledNumber,
      baseColor);
    }

    uint8_t ledByCoordinate(uint8_t coordinateX, uint8_t coordinateY) {
     return coordinateX + num_col * coordinateY;
    }

    uint8_t rowReadPosY = 0;
    void readInput() {
     bool changed = false;
     uint8_t rowReadPosX = 0;

     while(Serial.available() > 0) {
      char input = Serial.read();

      if(!isDigit(input)) continue;

      bitmap[rowReadPosY][rowReadPosX] = atoi(&input);

      rowReadPosX++;
      if(rowReadPosX >= 5) {
       rowReadPosY = ++rowReadPosY % 5;
       rowReadPosX = 0;
      }

      changed = true;
     }

     if(changed) {
      Serial.println("Ergebnis: ");

      for(uint8_t pixelX = 0; pixelX < 5; pixelX++) {
       for(uint8_t pixelY = 0; pixelY < 5; pixelY++) {
        Serial.print(bitmap[pixelY][pixelX]);
       }
       Serial.println();
      }

      Serial.print("Aktueller Cursor: (x,y) {");
      Serial.print(rowReadPosX);
      Serial.print(", ");
      Serial.print(rowReadPosY);
      Serial.println("}");
     }
    }


body:
Im trying too make an RGB LED that keeps changing color's randomly, and makes the brightness fade at the same time with an LDR, yet I keep getting an error that says too many arguments to functions.

could anyone possibly help me?

EDIT:
(this is the correct code sorry)

     const int LED_D_RGB_G_PIN = 11;
    const int LED_D_RGB_B_PIN = 10;
    const int LED_D_RGB_R_PIN = 9;
    const int LDR = A1;

    int inputval=0;
    int outval =0;

    void setup() {
      pinMode(LED_D_RGB_R_PIN, OUTPUT);
      pinMode(LED_D_RGB_G_PIN, OUTPUT);
      pinMode(LED_D_RGB_B_PIN, OUTPUT);
      pinMode(LDR, INPUT);

    }

    void loop() {
        inputval = analogRead(LDR);
        outval = map(inputval, 0, 380, 255, 0);

        int lightval = constrain(outval, 0,255);

        analogWrite(LED_D_RGB_R_PIN, lightval, random(0,255));
        analogWrite(LED_D_RGB_G_PIN, lightval, random(0,255));
        analogWrite(LED_D_RGB_B_PIN, lightval, random(0,255));
        delay (50);
    }

title: RGB LED randomized colors and LDR fading at the same time

Answers: 1

body:
I will assume that you can correct any errors in your code and I want to get at a suggestion for a possibly better approach to what I think that you are trying to do.

When you are setting the "color", you are setting the brightness of each of the LEDs; R,G,B, or at least you are trying to do that when you generate a random PWM using analogWrite https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/.

Then, you are trying to set the brightness again, presumably based on the ambient light value from the LDR AND it is set for the **combined** output of the 3 LEDs which are likely at different intensity values, since intensity was randomly chosen. The problem is, how can you scale the values perfectly so that you get the same color but at a lower intensity? I think that is much more difficult than you might believe...for a bunch of reasons.

I would suggest you try something along these lines, but keep some low expectations....

1. Use a variable called maxb, which changes the **maximum possible** value used in the analogWrite() values so that it it not always 255. You can adjust that value based on reading the LDR. You will have to do some experimenting and don't expect a huge range of values. Now, your color will still be picked at random, but with an adjustment for intensity.

2. You *"should"* try to use resistors on each of the RGB LEDs that will produce something close to equivalent brightness. This will vary somewhat between RGB LEDs. Below is a graph of where I looked at this for a color fader project many years ago. I used an old BH1750 ambient light sensor to get the lux values. That dashed line is for the equivalent brightness of the individual LEDs by resistor value (ohms) used [220-Red, 750-Green, 470-Blue]. This is not an ideal way, but it is easy.

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

3. That might get you near where you want to be, but for "extra credit", note that brightness scaling is not an equal interval scale. So, a PWM value of 250 is NOT 10 times brighter than a PWM value of 25. Brightness is, more or less, on an exponential scale except for very dim values, which are, again, more-or-less, linear. Look into the CIE 1931 perceived lightness formula and Weber and Stevens and so on. Since this is not a psychophysics lab, let me cut to the chase. The array below represents an intensity scale as I have described and includes values of 0 and 255 as per an 8 bit width (which is what analogWrite uses). You could use a minimum value of 4 or 8 instead of 0 if you wanted to guarantee a visible output every time. Test that out, but for the sake of discussion, let's assume you are using all values in the array.

A[13]{0,1,2,4,8,17,32,51,75,106,145,194,255};

You would scale your LDR range to 13 possible values (0-12) and then get your maximum value for analogWrite from the array. Then, you would pick a random value for 0 to maxb for each of your analogWrites to the RGB.

4. I don't know how brightness is represented by your LDR and you should consider that when you are determining your ambient light intensity values - ideally, you would want 13 equal intensity values from your LDR - right?. I suppose something about that is probably in the data sheet.

That is how I would do it anyways :)

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


body:
I acquired a bread-making machine. See control board image.
I want to use the machine for other purposes and control the buttons, paddle, heater & 7-segment display with an Uno.
As it stands, the machine provides 0V, -5V & -11V to the control board.

Is it possible to connect 0V to Uno VIN and -5V to Uno GND pins?

My initial idea was to replace the PENTALPHA-BV30K with an Uno and mapping the pins accordingly. I couldn't find any datasheet for the BV30K, however I'm reverse engineering the control board anyway.

Control board findings:
 - -11V is used to drive the A/B/C/D/E/F/G/DP segments of the LED display
 - BV30K only uses 0V & -5V

[![bread machine control board][1]][1]

I added an image of the transformer based power supply board so that I could check the supply there. The larger heatsink is for the 7905 IC and the smaller heatsink is for the BTA06 Triac.

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

  [1]: https://i.stack.imgur.com/MmJ5c.jpg
  [2]: https://i.stack.imgur.com/wP2e9.jpg

title: Can the Arduino Uno use a negative supply voltage (0V & -5V)

Answers: 1

body:
As you describe the system, you can connect the system's ground to 5V of the Uno, and the system's -5V to Uno's ground.

Please note that you cannot reverse-feed 5V through the pin with the same label, it is an output. You can use the USB connector. You might want to solder wires at its pins instead of cannibalizing an old USB cable. Alternatively you can try VIN, as there is a LDO, but measure the resulting voltage. The specification demands at least 7V there.

If you want to power the Uno during development by the USB connection, you can disconnect any of -5V or ground, but not both, because you need a reference connection.

In contrast, you cannot use the -11V supply and use VIN and GND of the Uno, because the Uno's voltage regulator uses the lower level as reference and will set Uno's "high" (5V) to about -6V with reference to the system's ground. See:

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

---

Concerning the separation of power-line and the controller: Well, I'm just worrying about your health.

If you are sure that all is done well, go ahead. With a working separation you can even dare to connect the development PC to your Uno while the power-line is connected.

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


body:
I am trying to connect Grove 16x2 LCD (White on Blue) to my Arduino uno rev 2 wifi.
So far, I've tried hd44780 library's ioClass examples, but nothing worked. I've then decided to scan ports and when LCD was connected to rev 2 SDA/SCL pins I've got (Unknown error at address 0x3E). So it recognizes that something is connected, but doesn't recognize the LCD. I've also tried to run I2CexpDiag, which also returned "Unknown error at address 0x3E".
I tried the same LCD with Arduino UNO and mkr1010, both work flawlessly. I've also tried connecting the SDA/SCL pins to A4/A5, but nothing there either.
Any ideas what could be the problem?

title: Grove LCD display not working with arduino rev 2 wifi (Unknown error at address 0x3E)

Answers: 0


body:
I am trying to have a header file to handle all my pin definitions and pinmodes.

This is the header:

    #ifndef __HEADER_TESTER__
    #define __HEADER_TESTER__

    #include <SoftwareSerial.h>
    const byte rxPin = 2;
    const byte txPin = 3;
    SoftwareSerial mySerial(rxPin, txPin);

    pinMode(LED_BUILTIN, OUTPUT);

    #endif

However, when I compile this, I get an error on the `pinMode(LED_BUILTIN, OUTPUT);` line:

    expected constructor, destructor, or type conversion before '(' token

title: Setting pinmode() in header file

Answers: 1

body:
The `pinMode()` statement is executable code and can not be executed outside of a function - setup(), loop(), or some other function defined by you. One could imagine defining a function in your header (.h) file to set your pin modes but defining code in a header will cause a different kind of problem (multiple definitions) if you ever add another code module, a .cpp file, for instance, that also includes this same .h file.

Pin modes are usually set in the setup() function, once per execution of the sketch. There really isn't much value to having them in the .h file. If it is for documentation purposes, you could #define in the .h file, a symbol that expands to all of the pinMode() calls you need, then write that symbol at the appropriate place in your setup() function where it's expansion will be syntactically correct. This would accomplish the documentation, but at the cost of a reader of your code having to search for the definition of that symbol to find out what code is being executed there. That's pretty roundabout for what seems like little to no gain.


body:
I have a generic Arduino Nano board that uses the old bootloader. I have the printer and the Arduino connected like so:

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

This is my code:

    #include "Adafruit_Thermal.h"

    // Here's the new syntax when using SoftwareSerial (e.g. Arduino Uno) ----
    // If using hardware serial instead, comment out or remove these lines:

    #include "SoftwareSerial.h"
    #define TX_PIN 5 // Arduino transmit  YELLOW WIRE  labeled RX on printer
    #define RX_PIN 6 // Arduino receive   GREEN WIRE   labeled TX on printer

    SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
    Adafruit_Thermal printer(&mySerial);     // Pass addr to printer constructor
    // Then see setup() function regarding serial & printer begin() calls.

    // Here's the syntax for hardware serial (e.g. Arduino Due) --------------
    // Un-comment the following line if using hardware serial:

    //Adafruit_Thermal printer(&Serial1);      // Or Serial2, Serial3, etc.

    // -----------------------------------------------------------------------

    void setup() {

      // This line is for compatibility with the Adafruit IotP project pack,
      // which uses pin 7 as a spare grounding point.  You only need this if
      // wired up the same way (w/3-pin header into pins 5/6/7):
      // pinMode(BUILTIN, OUTPUT); digitalWrite(7, LOW);

      // NOTE: SOME PRINTERS NEED 9600 BAUD instead of 19200, check test page.
      mySerial.begin(9600);  // Initialize SoftwareSerial
      //Serial1.begin(19200); // Use this instead if using hardware serial
      printer.begin();        // Init printer (same regardless of serial type)

      // The following calls are in setup(), but don't *need* to be.  Use them
      // anywhere!  They're just here so they run one time and are not printed
      // over and over (which would happen if they were in loop() instead).
      // Some functions will feed a line when called, this is normal.

      // Font options
      printer.setFont('B');
      printer.println("FontB");
      printer.println("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
      printer.setFont('A');
      printer.println("FontA (default)");
      printer.println("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

      printer.sleep();      // Tell printer to sleep
      delay(3000L);         // Sleep for 3 seconds
      printer.wake();       // MUST wake() before printing again, even if reset
      printer.setDefault(); // Restore printer to defaults
    }

    void loop() {
    }

When I run my code or reset no prints get sent to the print.

Here's what I've tried.

 - Ensure power is on on both devices
 - Try baud rate 19200
 - Swop Tx and Rx cables around
 - Tried D5 and D6 for Tx and Rx

Any help would me much appreciated.

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

title: How to connect Arduino Nano to Thermal Printer via serial connection

Answers: 1

body:
Your additional info about your printer tells me that it has a Bluetooth and a USB interface - but I can not see any other serial connection port.

So there is no way connecting this printer as-is to the arduino nano by some digital port pins.

You may decide to either buy the Thermal printer offered by Adafruit our search for a Thermal printer that clearly states that is has a "Serial Interface" or "Serial RS232 Interface" - no matter if that comes with "TTL" or not like the Adafruit printer.

The printer is intended to be connected to a USB host port (of an PC or RPi or so) or via Bluetooth (to an PC or Android phone).

It may offers a virtual serial interface over both USB and Bluetooth, but that is a speculation.

*It may be possible to hack your printer. I think the Adafruit printer was modded by Adafruit. They may have bought a stock-printer and added the connector for the TTL interface. This may also be possible with the printer you have, but that is not in the scope of your question and highly speculative.*


body:
For the arduino Nano 33 BLE Sense board, the standard `avr/wdt.h` is not available. And it seems that no standard library provides it. How to use the watchdog system for this board ? I found no full information about it.

I've found the page [https://www.mysensors.org/apidocs/group__avr__watchdog.html][1] which allow to configure the reboot mode. And it works. But no way to configure the interruption mode with `ISR()` function. Moreover, there's no explanation about the manipulation of used register/variables for any fine configuration.

  [1]: https://www.mysensors.org/apidocs/group__avr__watchdog.html

Simple code example with regular asynchronous stuff using the watchdog ISR() mechanism. It which works well with ATmega328 (e.g.UNO). But I do not find equivalent configuration for the Nano 33 BLE using the nRF52840.

```C
# include <avr/wdt.h>

volatile byte led;
int k;

ISR(WDT_vect) {
  Serial.println("Asynchronous stuff in ISR() function");
  digitalWrite(LED_BUILTIN,led);
  led=!led;
}

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  led=0;

  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("== R E B O O T ==");

  WDTCSR = ( 1 << WDE ) | ( 1 << WDCE );
  WDTCSR = ( 1 << WDP2 ) | ( 1 << WDP0 ) | ( 1 << WDIE ) ; // Interruption and timeout  1/2 s
}

void loop() {
  Serial.print("Loop #");
  Serial.println(k);
  if (k++%2) {
    Serial.println("Some stuff (even branch)");
    delay(1200);
  }
  else {
    Serial.println("Some stuff (odd branch)");
    delay(4800);
  }
}
```
Thks.

title: How to configure watchdog for the arduino Nano 33 BLE Sense board?

Answers: 2

body: You do not want to update your watchdog in an ISR. It is possible to get stuck but the ISR is continually triggered. I have seen this happen many times especially when a bad transient hits it. I normally use an external one so it will force a reset on the whole package. I do this by power cycling everything. Not all watchdog timers in processors will do an external reset.

body:
In fact, for the RF52940, I'm not sure that the watchdog can provide the needed interruption mechanism despite it exists the INTENSET bit for interruption according to the chipset doc https://content.arduino.cc/assets/Nano_BLE_MCU-nRF52840_PS_v1.1.pdf). But the good way is for sure the use of timers (and one can use more than just one, quite good).

For a similar behaviour as the code given for the UNO before, here is the code one can write for the Nano BLE using a timer interrupt (see https://github.com/khoih-prog/NRF52_MBED_TimerInterrupt for full and usefull doc).

```C
#include "NRF52_MBED_TimerInterrupt.h"

volatile byte led;
volatile uint32_t count=0;
NRF52_MBED_Timer myTimer(NRF_TIMER_1);
unsigned k=0;

void myHandler() {
  digitalWrite(LED_BUILTIN,led);
  led=!led;
  count++;
}

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  led=0;

  Serial.begin(9600);
  while(!Serial) {}
  Serial.println("== R E B O O T ==");

  if (myTimer.attachInterruptInterval(500*1000, myHandler)) // each 1/2 second
    Serial.println("myTimer launched");
  else
    Serial.println("Can not set the timer");
}

void loop() {
  Serial.print("Loop #");
  Serial.print(k);
  Serial.print(" and nb times in Handler : ");
  Serial.println(count);
  if (k++%2) {
    Serial.println("Some stuff (even branch)");
    delay(1200);
  }
  else {
    Serial.println("Some stuff (odd branch)");
    delay(4800);
  }
}
```


body:
I want to transfer 8 lists from a python script, via Serial Monitor to the Arduino. I can get the strings to Arduino and Arduino saves them as String array, but I can't change it to integer (it shows as 0.00 - I then convert it to float, because I need to divide it by 10 to get back real numbers)

I changed the lat and long in the api link because of privacy. Change it to an actual value (example latitude=42.234, longitude=20.000).

Python code:
```
import requests
from datetime import datetime
import serial
import numpy as np
import time

url = "https://api.open-meteo.com/v1/forecast?latitude=xx.xxx&longitude=yy.yyy&hourly=temperature_2m&hourly=windspeed_10m&hourly=windspeed_80m&hourly=windspeed_120m&hourly=windspeed_180m&hourly=winddirection_10m&hourly=winddirection_80m&hourly=winddirection_120m&hourly=winddirection_180m"
now = datetime.now()

stavek_veter = "Vetrne karakteristike"

ser = serial.Serial("COM3", 115200)

tr_cas = int(now.strftime("%H"))-1

response = requests.get(url).json()
vremenski_podatki = response["hourly"]

temp2m = vremenski_podatki["temperature_2m"]
cas = vremenski_podatki["time"]

paket = str(ser.readline())

hitr_vetra_10m = vremenski_podatki["windspeed_10m"]
hitr_vetra_80m = vremenski_podatki["windspeed_80m"]
hitr_vetra_120m = vremenski_podatki["windspeed_120m"]
hitr_vetra_180m = vremenski_podatki["windspeed_180m"]
smer_vetra_10m = vremenski_podatki["winddirection_10m"]
smer_vetra_80m = vremenski_podatki["winddirection_80m"]
smer_vetra_120m = vremenski_podatki["winddirection_120m"]
smer_vetra_180m = vremenski_podatki["winddirection_180m"]

hitr_vetra_10m_zmn = list(np.array(hitr_vetra_10m)*10)
hitr_vetra_80m_zmn = list(np.array(hitr_vetra_80m)*10)
hitr_vetra_120m_zmn = list(np.array(hitr_vetra_120m)*10)
hitr_vetra_180m_zmn = list(np.array(hitr_vetra_180m)*10)

hitr_vetra_10m_zmn = list(map(int, hitr_vetra_10m_zmn))
hitr_vetra_80m_zmn = list(map(int, hitr_vetra_80m_zmn))
hitr_vetra_120m_zmn = list(map(int, hitr_vetra_120m_zmn))
hitr_vetra_180m_zmn = list(map(int, hitr_vetra_180m_zmn))

if stavek_veter in paket:
    time.sleep(1.7)
    ser.write((str(hitr_vetra_10m_zmn[tr_cas: (tr_cas+6)]) + "\n").encode("utf-8"))
    time.sleep(0.5)
    ser.write((str(hitr_vetra_80m_zmn[tr_cas: (tr_cas+6)])+ "\n").encode("utf-8"))
    time.sleep(0.5)
    ser.write((str(hitr_vetra_120m_zmn[tr_cas: (tr_cas+6)])+ "\n").encode("utf-8"))
    time.sleep(0.5)
    ser.write((str(hitr_vetra_180m_zmn[tr_cas: (tr_cas+6)])+ "\n").encode("utf-8"))
    time.sleep(0.5)
    ser.write((str(smer_vetra_10m[tr_cas: (tr_cas+6)])+ "\n").encode("utf-8"))
    time.sleep(0.5)
    ser.write((str(smer_vetra_80m[tr_cas: (tr_cas+6)])+ "\n").encode("utf-8"))
    time.sleep(0.5)
    ser.write((str(smer_vetra_120m[tr_cas: (tr_cas+6)])+ "\n").encode("utf-8"))
    time.sleep(0.5)
    ser.write((str(smer_vetra_180m[tr_cas: (tr_cas+6)])+ "\n").encode("utf-8"))
    time.sleep(0.5)

print("Cas ob rezultatih: \n")
print(str(cas[tr_cas: (tr_cas+6)])+ "\n")
print("Hitrost vetra 10m \n")
print(str(hitr_vetra_10m[tr_cas: (tr_cas+6)])+ "\n")
print("Hitrost vetra 80m \n")
print(str(hitr_vetra_80m[tr_cas: (tr_cas+6)])+ "\n")
print("Hitrost vetra 120m \n")
print(str(hitr_vetra_120m[tr_cas: (tr_cas+6)])+ "\n")
print("Hitrost vetra 180m \n")
print(str(hitr_vetra_180m[tr_cas: (tr_cas+6)])+ "\n")
print("Smer vetra 10m \n")
print(str(smer_vetra_10m[tr_cas: (tr_cas+6)])+ "\n")
print("Smer vetra 80m \n")
print(str(smer_vetra_80m[tr_cas: (tr_cas+6)])+ "\n")
print("Smer vetra 120m \n")
print(str(smer_vetra_120m[tr_cas: (tr_cas+6)])+ "\n")
print("Smer vetra 180m \n")
print(str(smer_vetra_180m[tr_cas: (tr_cas+6)])+ "\n")

while True:
    paket = str(ser.readline())
    print(paket.encode("utf"))
```
Arduino code:
```
#include <Wire.h>
//#include <WireIMXRT.h>
//#include <WireKinetis.h>

int hitr_vetra_10m[6], hitr_vetra_120m[6], hitr_vetra_80m[6], hitr_vetra_180m[6];
int smer_vetra_10m[6], smer_vetra_80m[6],smer_vetra_120m[6], smer_vetra_180m[6];
float hitr_vetra_10m_ko[6], hitr_vetra_120m_ko[6], hitr_vetra_80m_ko[6], hitr_vetra_180m_ko[6];

int n, k;

String ser_string[8];

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

  Serial.println("Vetrne karakteristike");
  delay(2000);

  for(n = 0; n<=8; n++){
    if(Serial.available()>=14){
      ser_string[n] = Serial.readStringUntil("\n");
      Serial.flush();
      Serial.println(ser_string[n]);

      if(n==0){
        while(ser_string[n].indexOf(",")!=-1){
          hitr_vetra_10m[k] = ser_string[n].substring(0,ser_string[n].indexOf(",")).toInt();
          k++;
        }
        hitr_vetra_10m[k]=ser_string[n].toInt();
      }

      k=0;
      if(n==1){
        while(ser_string[n].indexOf(",")!=-1){
          hitr_vetra_80m[k] = ser_string[n].substring(0,ser_string[n].indexOf(",")).toInt();
          k++;
        }
        hitr_vetra_80m[k]=ser_string[n].toInt();
      }
      k=0;

      if(n==2){
        while(ser_string[n].indexOf(",")!=-1){
          hitr_vetra_120m[k] = ser_string[n].substring(0,ser_string[n].indexOf(",")).toInt();
          k++;
        }
        hitr_vetra_120m[k]=ser_string[n].toInt();
      }
      k=0;

      if(n==3){
        while(ser_string[n].indexOf(",")!=-1){
          hitr_vetra_180m[k] = ser_string[n].substring(0,ser_string[n].indexOf(",")).toInt();
          k++;
        }
        hitr_vetra_180m[k]=ser_string[n].toInt();
      }
      k=0;

      if(n==4){
        while(ser_string[n].indexOf(",")!=-1){
          smer_vetra_10m[k] = ser_string[n].substring(0,ser_string[n].indexOf(",")).toInt();
          k++;
        }
        smer_vetra_10m[k]=ser_string[n].toInt();
      }
      k=0;

      if(n==5){
        while(ser_string[n].indexOf(",")!=-1){
          smer_vetra_80m[k] = ser_string[n].substring(0,ser_string[n].indexOf(",")).toInt();
          k++;
        }
        smer_vetra_80m[k]=ser_string[n].toInt();
      }
      k=0;

      if(n==6){
        while(ser_string[n].indexOf(",")!=-1){
          smer_vetra_120m[k] = ser_string[n].substring(0,ser_string[n].indexOf(",")).toInt();
          k++;
        }
        smer_vetra_120m[k]=ser_string[n].toInt();
      }
      k=0;

      if(n==7){
        while(ser_string[n].indexOf(",")!=-1){
          smer_vetra_180m[k] = ser_string[n].substring(0,ser_string[n].indexOf(",")).toInt();
          k++;
        }
        smer_vetra_180m[k]=ser_string[n].toInt();
      }
      k=0;

      delay(500);
    }

  }
  n=0;

  for(int b = 0; b<=5;b++){
    hitr_vetra_10m_ko[b]=hitr_vetra_10m[b]/10.0;
    hitr_vetra_80m_ko[b]=hitr_vetra_80m[b]/10.0;
    hitr_vetra_120m_ko[b]=hitr_vetra_120m[b]/10.0;
    hitr_vetra_180m_ko[b]=hitr_vetra_180m[b]/10.0;
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  for(int j = 0; j<=5; j++){
    Serial.println(hitr_vetra_10m_ko[j]);
  }
  delay(5000);

}
```

Why does it only write out 0.0 for every place in the array (example: [0.0,0.0,0.0,0.0,0.0,0.0]?

Thanks in advance for all help.

EDIT:

I've changed the last part of python code to this
```

while True:
    paket = str(ser.readline().decode("utf"))
    print(paket.encode("ASCII"))

```
and I get the following result when I print what is coming from Serial monitor (whatever data I print in python and the show it in VScode terminal.)

```
Cas ob rezultatih:

['2023-02-13T18:00', '2023-02-13T19:00', '2023-02-13T20:00', '2023-02-13T21:00', '2023-02-13T22:00', '2023-02-13T23:00']

Hitrost vetra 10m

[2.1, 3.1, 1.3, 1.9, 2.3, 2.6]

Hitrost vetra 80m

[0.4, 1.1, 2.5, 0.5, 1.8, 1.8]

Hitrost vetra 120m

[0.7, 0.7, 3.3, 1.1, 1.0, 1.8]

Hitrost vetra 180m

[1.3, 1.0, 4.0, 2.5, 0.8, 0.4]

Smer vetra 10m

[211, 249, 146, 248, 219, 214]

Smer vetra 80m

[360, 252, 98, 225, 217, 217]

Smer vetra 120m

[360, 180, 84, 90, 225, 217]

Smer vetra 180m

[34, 135, 85, 90, 63, 180]

b'[21,31,13,19,23,26]\n'
b'[4,11,25,5,18,18]\n'
b'[7,7,33,11,10,18]\n'
b'[13,10,40,25,8,4]\n'
b'[211,249,146,248,219,214]\n'
b'[360,252,98,225,217,217]\n'
b'[360,180,84,90,225,217]\n'
b'[34,135,85,90,63,180]\n'
b'\r\n'
b'[21,31,13,19,23,26]\n'
b'[4,11,25,5,18,18]\n'
b'[7,7,33,11,10,18]\n'
b'[13,10,40,25,8,4]\n'
b'[211,249,146,248,219,214]\n'
b'[360,252,98,225,217,217]\n'
b'[360,180,84,90,225,217]\n'
b'[34,135,85,90,63,180]\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'[21,31,13,19,23,26]\n'
b'[4,11,25,5,18,18]\n'
b'[7,7,33,11,10,18]\n'
b'[13,10,40,25,8,4]\n'
b'[211,249,146,248,219,214]\n'
b'[360,252,98,225,217,217]\n'
b'[360,180,84,90,225,217]\n'
b'[34,135,85,90,63,180]\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
b'\r\n'
```

title: Converting more strings from serial monitor to int arrays

Answers: 0


body:
I'm loading a buffer with different data recorded by sensors and sending them to a server. But I also wanted to log when the data was sent on the client side, so I formatted the time of my RTC clock and tried to include it in the buffer, but this caused a problem. The data returned by the sensors are floating point numbers, but the timestamps are integers. When trying to send the buffer including both the datatypes, it is not received by the server. Under is the code which puts the data into the buffer:

```
char buffer[256] = {};

sprintf(buffer, "path?myfile.txt,d/d/d d:d:d,Temp=%lf,Humidity=%lf,Pressure=%lf,Light=%lf",rtc.getDay(),rtc.getMonth(),rtc.getYear(),rtc.getHours(),rtc.getMinutes(),rtc.getSeconds(),temperature,humidity,pressure,illuminance);
```
I am pretty sure the mixing of the data types or the formatting is the problem. I know it's not the buffer size because I have tested it with multiple sizes. The weird thing is that I can print the buffer out in the serial monitor without any problem. It is also formated the right way in the serial monitor:

> "path?myfile.txt,10/02/23 17:05:16, Temp=26.863487,Humidity=24.886541,Pressure=99.868286,Light=8.387096

I have never experienced a situation where one buffer is sent successfully and another one is not.
If I for example send this buffer instead:
```
sprintf(buffer, "/cgi-bin/tof.cgi?zuluz.txt,Temp=%lf,Humidity=%lf,Pressure=%lf,Ligth=%lf",temperature,humidity,pressure,illuminance);
```
Everything works as it should. What do you think the problem is? And is there a good workaround for this? If this problem comes from the server itself, I can not do anything about it since I have no access to its backend code.

My board is the MKR NB 1500 using a MKR ENV shield to log the data.

**Edit:**
Here is the full function which actually writes to the server:
```
void write_server()
{
    Serial.println("Sending the buffer");
    char buffer[256] = {};

    client.print("GET ");
    sprintf(buffer, "path?myfile.txt,d/d/d d:d:d,Temp=%lf,Humidity=%lf,Pressure=%lf,Light=%lf",rtc.getDay(),rtc.getMonth(),rtc.getYear(),rtc.getHours(),rtc.getMinutes(),rtc.getSeconds(),temperature,humidity,pressure,illuminance);
    Serial.println(buffer);
    client.print(buffer);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
    Serial.println("Buffer sent");
}
```
The only diffrence from the actual code is the path on the server and the file name in which the data is stored.

title: Why is this buffer not being sent to the server?

Answers: 0


body:
I have a NodeMCU esp32-s board and I'm trying to connect My 16x2 lcd with PCF8574T I2C bus to the esp32 , the problem is that the lcd doesn't show anything and the WireScan sketch can't recognize the lcd too,but when I use arduion uno ,it's recognized and work perfectly ,I hope somebody can help me,the schematic for the connection is :
[![enter image description here][1]][1]

the schematic for the connection of the lcd with the bus is below with the bus module part number [![enter image description here][2]][2]:

  [1]: https://i.stack.imgur.com/FjBC1.png
  [2]: https://i.stack.imgur.com/0NXcS.png

title: an lcd with I2C is not recognized by esp32

Answers: 1

body: You can run the PCF8574 on 5V and the EXP on 3V3 just be sure the I2C is pulled up to the 3V3 and NOT the 5V. I do this a lot and have never had a problem. The reason it works is the bus is driven by open collector/drain drivers which do not source any voltage.


body:
i just experimented with the timing accuracy of my Arduino Uno R3 using this code:

    unsigned long beginTime;
    unsigned long endTime;

    void setup() {
      Serial.begin(9600); // open a serial port
    }

    void loop() {
      beginTime = micros();
      delayMicroseconds(200);
      endTime = micros();
      delay(500);
      Serial.println(endTime-beginTime);
      delay(500);
    }

The results I got are (just an excerpt):
```
200
204
200
200
204
204
204
200
212
208
212
204
204
```
I tried to understand this behavior, read this link [Can I make delayMicroseconds more accurate?][1].

Due to the timing of `micros` (4 µs) I would understand values between 200 and 208. **But why do I get occasional values of 212 microseconds?** I'm kinda curious, since I bought the Arduino because of bare-metal programming and bounded execution times.

  [1]: https://arduino.stackexchange.com/questions/37387/can-i-make-delaymicroseconds-more-accurate

title: delayMIcroseconds and micros execution time not explainable

Answers: 1

body:
The Arduino core uses hardware Timer0 with its ISR (Interrupt Service Routine) for timekeeping. While `delayMicroseconds()` directly uses the value of the hardware timer, `delay()` and `millis()` are handled by the ISR. It will be called regularly.

If the ISR is getting executed during your measurement, then the execution time of the ISR will add to the execution time of your measured code. Thus you get a higher count occasionally.

To prevent this you can either deactivate all interrupts (via `noInterrupts()`) or deactivate this specific interrupt, either by stopping Timer0:

    TCCR0B &= ~( (1 << CS02) | (1 << CS01) | (1 << CS00) );

or by letting the timer run, but deactivating its interrupts:

    TIMSK0 = 0;

For details about this have a look at the [datasheet of the Atmega328p][1], which is the microcontroller on the Arduino Uno.

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


body:
currently trying to implement a watchdog into my project. I am using the WDTZero library for controlling the watchdog on my MKR NB 1500. The program is trying to measure data, send it to a server, go to sleep, wake up, and repeat the process. Sometimes the code can hang if it can't connect to the NTP server or the server on which the data is being stored, I want the watchdog to reset the program in cases in which this happens.

A sketch of the program is below. The reason why the NB network is often after different connections is that the NB 1500 is not able to connect to another server if the GPRS connection is already open, so I always reset it before trying another connection.

```
void setup()
{
    setup_watchdog(); //Sets up the watchdog timer
    delay(1000);
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    request_NTP(); //Requests epoch1970 from the NTP server and then closes the connection
    timezone_adjustment(); //Adjusts the epoch time to my timezone (in Norway)
    set_RTC(); //Activates the SAMD21 RTC with this timezone adjusted time
    disconnect_NB(); //Disconnects from the NB network
    delay(2000);
    MyWatchDoggy.clear(); //Resets the watchdog timer
    }

void loop()
{
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    get_ENV_data(); //Takes measurements using the MKR NB ENV shield
    connect_to_server(); //Connects to the server in which the data will be stored
    write_to_server(); //Writes the data on the server
    disconnect_from_server(); //Disconnects from the server
    disconnect_NB(); //Disconnects from the NB network

    LowPower.deepSleep(300000); //Goes to deep sleep for 5 minutes
    delay(3000);
    MyWatchDoggy.clear(); //Resets the watchdog timer
}

```
All the functions above are written in other .cpp files and imported thru header files into the main file. Here is the code for activating and configuring the watchdog:
```
#include "watchdog.hpp"
#include "GPRS_NB_connection.hpp"

WDTZero MyWatchDoggy;

void setup_watchdog()
{
    MyWatchDoggy.attachShutdown(NVIC_SystemReset); //calls reset function
    MyWatchDoggy.setup(WDT_SOFTCYCLE8M); //8 minute watchdog timer
}
```
The program works fine in the way described at the top of the post when the watchdog is not included. But when including the watchdog, it bites after 30 seconds when the dog only should have bit after 8 minutes. I see this because data is being sent about every 25-30 seconds to the server.
At first, I thought I had not activated the watchdog in the right way, so I wrote another program to test it:
```
#include <Arduino.h>
#include <WDTZero.h>
#include <RTCZero.h>

WDTZero MyWatchDoggy;
RTCZero rtc;

void set_RTC()
{
    rtc.begin();
    rtc.setYear(0);
    rtc.setMonth(0);
    rtc.setDay(0);
    rtc.setHours(0);
    rtc.setMinutes(0);
    rtc.setSeconds(0);
}

void shutdown()
{
    Serial.println("Shutting down");

}

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

    }
    Serial.println("Starting up Arduino");
    MyWatchDoggy.attachShutdown(shutdown);
    MyWatchDoggy.setup(WDT_SOFTCYCLE8M);
    set_RTC();

}

void loop()
{
    Serial.print(rtc.getMinutes());
    Serial.print("/");
    Serial.print(rtc.getSeconds());
    Serial.println("");
    delay(1000);
}
```
But in this program the watchdog bites after about 8 minutes as it should.

I have not included the code for the functions described in the first code since I know they work without the watchdog and the code itself is very long. But if you think the problem could be caused by these functions for some reason, I will edit the post and include all the function codes.

title: Why is the watchdog biting to quickly?

Answers: 1

body:
In the WDTZero library the long watchdog times are achieved by restarting the watchdog timer in watchdog interrupt until the required time is reached.

This doesn't work if the MCU sleeps.


body:
On ESP32 I'm trying to build the [Minimal I2C][1] example of the [MFRC522 library][2]:
But I get errors on the first declarations:

    TwoWire i2cBus = TwoWire(0);
    MFRC522_I2C dev = MFRC522_I2C(RST_PIN, 0x28, i2cBus);
    MFRC522 mfrc522 = MFRC522(dev); // <--- error

Here the build output:

    src/rfid.cpp:6:30: error: no matching function for call to 'MFRC522::MFRC522(MFRC522_I2C&)'
     MFRC522 mfrc522 = MFRC522(dev);
                                  ^
    In file included from include/rfid.h:5,
                     from src/rfid.cpp:1:
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:348:2: note: candidate: 'MFRC522::MFRC522(byte, byte)'
      MFRC522(byte chipSelectPin, byte resetPowerDownPin);
      ^~~~~~~
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:348:2: note:   candidate expects 2 arguments, 1 provided
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:347:2: note: candidate: 'MFRC522::MFRC522(byte)'
      MFRC522(byte resetPowerDownPin);
      ^~~~~~~
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:347:2: note:   no known conversion for argument 1 from 'MFRC522_I2C' to 'byte' {aka 'unsigned char'}
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:346:2: note: candidate: 'MFRC522::MFRC522()'
      MFRC522() DEPRECATED_MSG("use MFRC522(MFRC522_BUS_DEVICE bus_device)");
      ^~~~~~~
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:346:2: note:   candidate expects 0 arguments, 1 provided
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:343:2: note: candidate: 'MFRC522::MFRC522(MFRC522_BUS_DEVICE*)'
      MFRC522(MFRC522_BUS_DEVICE * dev);
      ^~~~~~~
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:343:2: note:   no known conversion for argument 1 from 'MFRC522_I2C' to 'MFRC522_BUS_DEVICE*'
    In file included from include/rfid.h:5,
                     from src/rfid.cpp:1:
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:152:7: note: candidate: 'constexpr MFRC522::MFRC522(const MFRC522&)'
     class MFRC522 {
           ^~~~~~~
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:152:7: note:   no known conversion for argument 1 from 'MFRC522_I2C' to 'const MFRC522&'
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:152:7: note: candidate: 'constexpr MFRC522::MFRC522(MFRC522&&)'
    .pio/libdeps/MyProject/MFRC522-spi-i2c-uart-async/src/MFRC522.h:152:7: note:   no known conversion for argument 1 from 'MFRC522_I2C' to 'MFRC522&&'

Unfortunately there is no way to open an issue on the repository.
Why the official example does not work?

UPDATE
--

Here the compatibility declaration for ESP32:

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

  [1]: https://github.com/MakerSpaceLeiden/rfid/blob/master/examples/Minimal-I2C/Minimal-I2C.ino
  [2]: https://github.com/makerspaceleiden/rfid
  [3]: https://i.stack.imgur.com/XNCFk.png

title: Cannot compile MFRC522 minimal I2C example

Answers: 1

body:
if you look, it says, "Candidate expects 2 inputs, one provided."

so in the arduino IDE hover over the function and see what it expects.

(What your putting in `MFRC522(byte resetPowerDownPin);` what it expects: `MFRC522(byte resetPowerDownPin, Something else);`)


body:
I am using the following device: https://www.aliexpress.com/item/1005003152097545.html?spm=a2g0o.order_list.order_list_main.119.222218028PapM6

I am trying to make an IoT sound-measurer which will send an SMS, once a sound above a certain threshold has been registered for a certain amount of time. Furthermore, it should send a "pulse" SMS every Nth hour, to ensure, that the module is still alive.

To achieve the SMS-part of this project I am using the TinyGSM module. It worked for a long time, and then suddenly it wouldn't work anymore. The only related event I can think of that happened before this, is that I tried to use the modem on the ESP-IDF, and I tried to use the GPS capabilities of the modem, once again on the ESP-IDF.

I believe this might have had something to do with the settings I had sat on the ESP-IDF, which are defined through the following AT-commands:
"AT+CFUN=0\r", "AT+CPIN=\"1234\"\r", "AT+COPS=0,0,\"Telenor DK Telenor DK\",7\r", "AT+CMGF=0\r".

But after running "AT+CRESET" and "AT+CPOF" and rerunning the Arduino script, I am still stuck with the original error.

The error occurs, when I try to run the sendText method, and the message (With my phone number redacted) is:

    AT+CMGF=1
    AT+CMGF=1

    ERROR
    AT+CSCS="GSM"
    AT+CSCS="GSM"

    ERROR
    AT+CMGS="+REDACTED"
    AT+CMGS="+REDACTED"

    ERROR

The full Arduino code (Where I've once again written REDACTED instead of my actual IRL phone number):

    //SIMKORT indstillinger

    // Pincode for simkortet
    #define GSM_PIN "\"1234\""

    // GRPRS credentials for simkortet
    const char apn[]  = "Telenor Internet";     //SET TO YOUR APN
    const char gprsUser[] = "";
    const char gprsPass[] = "";

    // Nummer til SMS samt besked
    #define SMS_TARGET_NOISY  "+REDACTED"
    #define SMS_TARGET_PULSE "+REDACTED"
    #define SMS_MESSAGE_NOISY "B"
    #define SMS_MESSAGE_PULSE "L"

    //Netværks indstillinger fra Debugging 1 koden
    #define NETWORK_MODE 2
    #define PREFFERED_NETWORK_MODE 2

    //Modem indstillinger
    #define TINY_GSM_MODEM_SIM7600 //Om du bruger SIM7000 eller SIM7600 (TTGO'en er 7600)
    #define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
    #define SerialAT Serial1

    //Libraries
    #define DUMP_AT_COMMANDS  //Bruges til debugging

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

    #ifdef DUMP_AT_COMMANDS  // if enabled it requires the streamDebugger lib
      #include <StreamDebugger.h>
      StreamDebugger debugger(SerialAT, Serial);
      TinyGsm modem(debugger);
    #else
      TinyGsm modem(SerialAT);
    #endif

    //ESP32-Modem Forbindelser Indstillinger
    #define uS_TO_S_FACTOR 1000000ULL  // Conversion factor for micro seconds to seconds

    #define UART_BAUD   115200
    #define PIN_DTR     25
    #define PIN_TX      27
    #define PIN_RX      26
    #define PWR_PIN     4

    //SD Kort forbindelser
    #define SD_MISO     2
    #define SD_MOSI     15
    #define SD_SCLK     14
    #define SD_CS       13
    #define LED_PIN     12

    int counter, lastIndex, numberOfPieces = 24;
    String pieces[24], input;

    //Indstillinger for dBAMåleren
    #define VREF 3.3 //Voltagen som din MCU bruger, Arduino = 5
    #define soundSensorPin 25 //Den pin på MCU'en, der er forbundet til outputtet på dBA måleren
    #define analogMaxRange 4096 //Analog max range for din MCU, esp32: 4096, Arduino: 1023

    //Funktionelle indstillinger
    #define dBAMax 3.0 //Hvornår der skal sendes en SMS
    #define errorMeasurement 0.0 //Fejlmarginen
    #define waitBeforeSendingtext (10*1000) //Målt i millisekunder, tid før vi sender noisySMS
    #define waitBeforeGoingIdle (100*1000) //Hvor lang tid dBAMeasurement må være under vores dBAMax, før vi går tilbage til idle stadiet
    #define waitIntervalBetweenPulseText (1000*1000) //Antal millisekunder i mellem, at vi sender en pulse SMS

    //Variable vedrørende FSMD'en - MÅ IKKE ÆNDRES
    //States:
    //Idle 0, dBA above Max 1, dBA momentarily below max 2, send noisy text 3, send pulse text 4
    int state = 0; //Initialiserer stadiet ved 0
    float dbAMeasurement;
    unsigned long timeSinceLastIdle; //Bruges til at triggere loudSMS
    unsigned long timeSinceLastPulse = 0; //Bruges til at pulseSMS
    unsigned long timeSincedBAMax; //Tid der er gået siden, vi optog vores første dBAMax i denne omgang

    //Funktioner

    void sendText(String SMSTarget,String message,TinyGsm modem){
        modem.sendSMS(SMSTarget, message);
    }

    float getdBAMeasurement(){
      float dbAMeasurement = ((analogRead(soundSensorPin) / 4096.0 * VREF)*50.0); //Slipper for at bruge clock cycluser på at definere variable
      delay(125); //Sampling cyclus delay for stabilitet
      return dbAMeasurement;
    }

    bool isAbovedBAThreshold(){
      float dbAMeasurement = getdBAMeasurement();
      if(dbAMeasurement>(dBAMax - errorMeasurement)){
        return true;
      }else{
        return false;
      }
    }

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

      //Opstart af Modem
      // Set LED OFF
      pinMode(LED_PIN, OUTPUT);
      digitalWrite(LED_PIN, HIGH);

      pinMode(PWR_PIN, OUTPUT);
      digitalWrite(PWR_PIN, HIGH);
      delay(300);
      digitalWrite(PWR_PIN, LOW);

      //Tjekker for SD kort
      SPI.begin(SD_SCLK, SD_MISO, SD_MOSI, SD_CS);
      if (!SD.begin(SD_CS)) {
        Serial.println("SDCard MOUNT FAIL");
      } else {
        uint32_t cardSize = SD.cardSize() / (1024 * 1024);
        String str = "SDCard Size: " + String(cardSize) + "MB";
        Serial.println(str);
      }

      Serial.println("\nWait...");

      delay(1000);

      SerialAT.begin(UART_BAUD, SERIAL_8N1, PIN_RX, PIN_TX);

      // Restart takes quite some time
      // To skip it, call init() instead of restart()
      Serial.println("Initializing modem...");
      if (!modem.restart()) {
        Serial.println("Failed to restart modem, attempting to continue without restarting");
      }

      // Unlock your SIM card with a PIN if needed
      if ( GSM_PIN && modem.getSimStatus() != 3 ) {
          modem.simUnlock(GSM_PIN);
      }
      modem.sendAT("+CFUN=0 ");
      if (modem.waitResponse(10000L) != 1) {
        DBG(" +CFUN=0  false ");
      }
      delay(200);

      /*
        2 Automatic
        13 GSM only
        38 LTE only
        51 GSM and LTE only
      * * * */
      String res;
      // CHANGE NETWORK MODE, IF NEEDED
      res = modem.setNetworkMode(NETWORK_MODE);
      if (res != "1") {
        DBG("setNetworkMode  false ");
        return ;
      }
      delay(200);

      /*
        1 CAT-M
        2 NB-Iot
        3 CAT-M and NB-IoT
      * * */
      // CHANGE PREFERRED MODE, IF NEEDED
      res = modem.setNetworkMode(PREFFERED_NETWORK_MODE);
      if (res != "1") {
        DBG("setPreferredMode  false ");
        return ;
      }
      delay(200);

      /*AT+CBANDCFG=<mode>,<band>[,<band>…]
       * <mode> "CAT-M"   "NB-IOT"
       * <band>  The value of <band> must is in the band list of getting from  AT+CBANDCFG=?
       * For example, my SIM card carrier "NB-iot" supports B8.  I will configure +CBANDCFG= "Nb-iot ",8
       */
      /* modem.sendAT("+CBANDCFG=\"NB-IOT\",8 ");*/

      /* if (modem.waitResponse(10000L) != 1) {
           DBG(" +CBANDCFG=\"NB-IOT\" ");
       }*/
       delay(200);

      modem.sendAT("+CFUN=1 ");
      if (modem.waitResponse(10000L) != 1) {
        DBG(" +CFUN=1  false ");
      }
      delay(200);

      SerialAT.println("AT+CGDCONT?");
      delay(500);
      if (SerialAT.available()) {
        input = SerialAT.readString();
        for (int i = 0; i < input.length(); i++) {
          if (input.substring(i, i + 1) == "\n") {
            pieces[counter] = input.substring(lastIndex, i);
            lastIndex = i + 1;
            counter++;
           }
            if (i == input.length() - 1) {
              pieces[counter] = input.substring(lastIndex, i);
            }
          }
          // Reset for reuse
          input = "";
          counter = 0;
          lastIndex = 0;

          for ( int y = 0; y < numberOfPieces; y++) {
            for ( int x = 0; x < pieces[y].length(); x++) {
              char c = pieces[y][x];  //gets one byte from buffer
              if (c == ',') {
                if (input.indexOf(": ") >= 0) {
                  String data = input.substring((input.indexOf(": ") + 1));
                  if ( data.toInt() > 0 && data.toInt() < 25) {
                    modem.sendAT("+CGDCONT=" + String(data.toInt()) + ",\"IP\",\"" + String(apn) + "\",\"0.0.0.0\",0,0,0,0");
                  }
                  input = "";
                  break;
                }
              // Reset for reuse
              input = "";
             } else {
              input += c;
             }
          }
        }
      } else {
        Serial.println("Failed to get PDP!");
      }

      Serial.println("\n\n\nWaiting for network...");
      if (!modem.waitForNetwork()) {
        delay(10000);
        return;
      }

      if (modem.isNetworkConnected()) {
        Serial.println("Network connected");
      }

    }

    void loop() {

      switch(state){
        case 0:  // Idle: Venter på at dbAMeasurement går over dbAMax - Error
          Serial.println("Back in state 0");
          dbAMeasurement = getdBAMeasurement();
          timeSinceLastIdle = millis(); //Millisekunder siden start
          Serial.println(dbAMeasurement);
          Serial.println(timeSinceLastIdle);
          Serial.println(timeSinceLastPulse);

          if((timeSinceLastIdle - timeSinceLastPulse) > waitIntervalBetweenPulseText){ //Vi vil hellere sende pulse SMS'en, før vi advarer
            state = 4;
          }
          if ((dbAMeasurement>(dBAMax - errorMeasurement))&(state != 4)){ //If we go above the allowed dBAMeasurement, we start counting until we send noisySMS
            state = 1;
          }

          break;
        case 1:  // We're counting up to sending the loudSMS
          Serial.println("Back in state 1");

          dbAMeasurement = getdBAMeasurement();
          Serial.println(dbAMeasurement);

          timeSincedBAMax = millis() - timeSinceLastIdle;
          Serial.println(timeSincedBAMax);
          if(timeSincedBAMax>waitBeforeSendingtext){
            state = 3; //SendnoisySMS
          }
          if(dbAMeasurement<(dBAMax - errorMeasurement)){
            state = 2; //Momentært under dBAMax
          }

          break;
        case 2:  // Hvis vi momentært går under dBAMax
          Serial.println("Back in state 2");
          dbAMeasurement = getdBAMeasurement();

          if((millis() - timeSincedBAMax)> waitBeforeGoingIdle){ //Når der er gået lang nok tid, hvor vi ikke måler en høj nok lyd, så genstarter vi timeren for at sende noisySMS
            state = 0;
          }

          if(dbAMeasurement>(dBAMax - errorMeasurement)){ //Vi går igen over vores threshold og går tilbage til tælle op til at sende noisySMS uden at genstarte timeren
            state = 1;
          }

          break;
        case 3:  // Send noisySMS
          sendText(SMS_TARGET_NOISY,SMS_MESSAGE_NOISY,modem);
          Serial.println("Back in state 3");
          state = 0;
          break;

        case 4:
          Serial.println("Back in state 4");
          timeSinceLastPulse = millis();
          sendText(SMS_TARGET_PULSE,SMS_MESSAGE_PULSE,modem);
          state = 0; //Go back to idle
          break;
      }
    }

The odd thing here however, is that if I manually send the AT commands over UART using the ESP-IDF, I can make it send text messages without a hick.

title: Can't Send Text Messages Using TinyGSM Module, but it works if I do it manually using the ESP-IDF Environment - Sim7600

Answers: 0


body:
I'm new to the field: I'm trying to drive a TFT ST7735S display (this is the model I'm currently using: https://www.amazon.it/dp/B078JBBPXK/ref=pe_24968671_487022601_TE_SCE_dp_1) with an Arduino Mega following this video (https://www.youtube.com/watch?v=iPeukOK6stk&ab_channel=Artigiano2.0-AlessioRomanelli). Once the hardware is set up and the code is written, when I run the example script "graphictest" of the Adafruit library for st7735 and st7789, the display shows stripes on the background as shown in the picture below:

[![enter image description here][1]][1]
(Note that the strange effect is not camera's fault)

Reading online I thought that the problem could be the fact that the display is powered with 5V instead of 3.3V, but I've also tried powering it with 3.3V (Arduino Mega 3.3V) with little to no changes. I've changed the `tft.initR(INITR_BLACKTAB);` to `tft.initR(INITR_GREENTAB);` too, as suggested by a user i this thread (https://forum.arduino.cc/t/bugged-1-8-inch-tft-diplay/1012166/5) and i've also tried powering the display with 5V but using 4.7k resistors in series to reduce the voltage as suggested in the same post, but it still doesn't work.

Moreover the strange effect that the image shows does only appear, if I use a 5V supply, just when the program executes the `void setup()` function, then becomes sharp (this does not happen if I power the display using the Arduino Mega 3.3V output supply: in fact in this case the stripes are still present even when entering the `void loop()` function)

As I said before, the program and the hardware setup arethe same as the video I was talking about.
One thing I noticed is that, when I press the reset button on the Arduino Mega, an instant before the program is reloaded, the stripes disappear leaving the image as sharp as it should have been, without any strange background effect. Does anyone have any idea on how to solve this issue?

Thank you in advance for any eventual answer!

**EDIT**:

This is the picture of the modified verison of the connections, running the graphictest program with the suggested code:

    #else
      // For the breakout board, you can use any 2 or 3 pins.
      // These pins will also work for the 1.8" TFT shield.
      #define TFT_CS        10
      //#define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
      #define TFT_RST        8 // Or set to -1 and connect to Arduino RESET pin
      #define TFT_DC         9
    #endif

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.

    #define TFT_MOSI 11  // Data out
    #define TFT_SCLK 13  // Clock out

    // For ST7735-based displays, we will use this call
    Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

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

Hopefully every connection is visible

  [1]: https://i.stack.imgur.com/KZFIm.jpg
  [2]: https://i.stack.imgur.com/ESFzz.jpg

title: TFT display shows black stripes

Answers: 2

body:
Adafruit made that graphictest program for screens that they sell. The screen that you have is not sold by Adafruit and there is no reason why they should support that screen.

Still, you can get it to work, if it is not bricked. After you see enough variants, you get an idea about what you need to get them to work. So, I suggest the following.....

Go here https://www.arthurwiz.com/software-development/177-inch-tft-lcd-display-with-st7735s-on-arduino-mega-2560 and hook up the screen to your mega just exactly as in their table. You will make 8 connections. Download and execute their 'Hello World' program from the tutorial. If that runs ok, then you know that the connections are correct. Note that the constructor is:

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

Also, don't worry if the screen is not rotated correctly - you can add one line in setup() to fix that:

      tft.initR(INITR_BLACKTAB);
      tft.setRotation(1); // <---added
      tft.fillScreen(ST7735_BLACK);

Now on to graphictest. Find these lines and change them to how I have them. I left one line commented out to illustrate. You do this to identify which GPIO go with which function. Yes, I could have started here, but going through the first tutorial successfully means you have not bricked the screen and you have the connections correct.

    #else
      // For the breakout board, you can use any 2 or 3 pins.
      // These pins will also work for the 1.8" TFT shield.
      #define TFT_CS        10
      //#define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
      #define TFT_RST        8 // Or set to -1 and connect to Arduino RESET pin
      #define TFT_DC         9
    #endif

You will use Option 2 and the constructor as stated previously - so

    // OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
    // tradeoff being that performance is not as fast as hardware SPI above.
    #define TFT_MOSI 11  // Data out
    #define TFT_SCLK 13  // Clock out

    // For ST7735-based displays, we will use this call
    Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

    // Use this initializer if using a 1.8" TFT screen:
      tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

Note that even though my screen still has a green tab, if I use the green tab initializer, I will have offset problems.

Make sure you haven't left any other configuration lines uncommented. I have the same screen and just hooked it up and tested all of this and everything works fine.

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

Let us know how it goes.

Edited to add:

You do not need to add ANY external resistors. Your Mega has connections for both 3V and 5V and you need to use both voltages.

Your initial pic (see below) shows that both pin 2 and pin 8 are connected to the same +V on the rail of the breadboard. This is incorrect. As shown in the table I linked, Pin 2 on the LCD goes to 5V on the Mega and pin 8 on the LCD goes to 3.3V on the Mega.

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

  [1]: https://i.stack.imgur.com/Lgkr5.jpg
  [2]: https://i.stack.imgur.com/IQcP1.jpg

body:
I had the exact same issue, and tested the things here but it did not help.
Then I pressed the reset button on my UNO with the same result as Luke__ had (the screen looked nice as long as I pressed the reset). After doing that a few times the display started to work as it should.

Strange, but resolved my issue.


body:
```json
String str = {"timestamp": "2023-02-08 16-37-31" ,"cpcb_device": [{"Station" : "832","Para": [{"tag_name": "COD","tag_value": "35.5","tag_unit": "mg/l"},{"tag_name": "BOD","tag_value": "13.7","tag_unit": "mg/l"},{"tag_name": "TSS","tag_value": "24.8","tag_unit": "mg/l"},{"tag_name": "pH","tag_value": "6.5","tag_unit": "pH"}]}]}
```

title: How can i separate values from the full string, incoming string always changes its positions?

Answers: 1

body:
You can use substring() and indexOf() to get parts of the string at certain positions. for example:
```
String test = "timestamp: 123 value: test";

int val = test.indexOf("timestamp:"); //gives you the index for the beginning of "timestamp:"
int start = test.indexOf(" ", val)+1; //get index of the space starting at our 'val' index
int end = test.indexOf(" ", start); //get index of the next space, we added 1 to the previous value so it doesn't pick up the first space
timestamp = test.substring(start, end); //get the characters between these two index values
```
Try it out and see how it works for you, obviously getting the index of separating characters that make more sense, such as a comma or colon rather than a space.\
Also you could do it like this:
```
String search = "timestamp:";
int start = test.indexOf(search)+search.length();
//etc...
```


body:
I have: 2 arduinos UNO, 2 ESP01 transivers. But if that's not enough, I'm ready to buy something else
I need to use one of Arduinos as a wifi hot spot, and the second as a modem. They should just be connected to each other :)
P.S. This is for my school project! Subsequently, I will put some obstacles between the Arduinos to see how much the signal strength degrades.

title: How can I connect 2 Arduinos using ESP8266 transiver: ESP01

Answers: 1

body:
Here is the ESP8266 WiFi library:\
https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi

In there You'll find an example for a WiFi access point:\
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino

And an example for WiFi client:\
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino

That should provide enough information for you to build your project.

To get the signal strength without connecting, you can use WiFiScan:\
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino


body:
I'm using the MKR NB 1500 for server sending, an ENV shield for measuring the environment, and an external lithium battery to power the circuit. The internal RTC and WDT on the NB 1500 are used.

The program is trying to measure data, send it to a server, go to sleep, wake up, and repeat the process. Under is a scetch of how the program is set up in main.cpp:

```
void setup()
{
    setup_watchdog(); //Sets up the watchdog timer with a 32 s bite time
    delay(1000);
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    request_NTP(); //Requests epoch1970 from the NTP server and then closes the connection
    timezone_adjustment(); //Adjusts the epoch time to my timezone (in Norway)
    set_RTC(); //Activates the SAMD21 RTC with this timezone adjusted time
    disconnect_NB(); //Disconnects from the NB network
    delay(2000);
    disable_watchdog(); //Disables the WDT in its entirety

void loop()
{
    setup_watchdog(); //Sets up the watchdog timer with a 32 s bite-time
    connect_GPRS_NB(); //Connects to the NB network and opens a GPRS connection
    get_ENV_data(); //Takes measurements using the MKR NB ENV shield
    connect_to_server(); //Connects to the server in which the data will be stored
    write_to_server(); //Writes the data on the server
    disconnect_from_server(); //Disconnects from the server
    disconnect_NB(); //Disconnects from the NB network
    watchdog_reset(); //Resets the watchdog timer

    disable_watchdog(); //Disables the WDT in its entirety
    LowPower.deepSleep(300000); //Goes to deep sleep for 5 minutes
    delay(2000);
}

```
All the functions above are written in other .cpp files and imported thru header files into the main file. The reason I'm using the RTC is because I want to log the time at which the data was sent to the server on the client side.

I set the circuit outside yesterday night and it actually sent data to the server the entire night. But the RTC did not function as I had hoped. Under is a clip-out of the data which was written on the server yesterday night:

```
nyktertest1.txt,11-02-23I23:39:40,Temp=22.593750,Fuktighet=31.063698,Trykk=1014.553223,Lys=9.677420
nyktertest1.txt,11-02-23I23:54:40,Temp=26.049343,Fuktighet=27.074978,Trykk=1014.549561,Lys=10.322580
nyktertest1.txt,11-02-23I23:56:34,Temp=24.909540,Fuktighet=29.182085,Trykk=1014.637695,Lys=9.032258
nyktertest1.txt,01-01-00I00:05:14,Temp=24.873356,Fuktighet=29.023129,Trykk=1012.826172,Lys=5.161290
nyktertest1.txt,01-01-00I00:10:29,Temp=22.231909,Fuktighet=34.242844,Trykk=1013.905762,Lys=5.161290
nyktertest1.txt,01-01-00I00:15:43,Temp=15.881580,Fuktighet=38.981991,Trykk=1014.769043,Lys=5.161290
nyktertest1.txt,12-02-23I00:18:39,Temp=19.047699,Fuktighet=38.823032,Trykk=1014.885742,Lys=10.967742
nyktertest1.txt,01-01-00I00:05:15,Temp=18.975330,Fuktighet=34.083885,Trykk=1015.005371,Lys=9.677420
nyktertest1.txt,01-01-00I00:10:30,Temp=20.350330,Fuktighet=33.440662,Trykk=1016.046631,Lys=3.225806
nyktertest1.txt,01-01-00I00:15:45,Temp=21.291119,Fuktighet=36.523697,Trykk=1014.721191,Lys=3.225806
nyktertest1.txt,01-01-00I00:20:59,Temp=15.338817,Fuktighet=43.358864,Trykk=1014.953369,Lys=3.225806
nyktertest1.txt,01-01-00I00:26:15,Temp=10.689146,Fuktighet=47.306919,Trykk=1015.068359,Lys=3.870968
nyktertest1.txt,01-01-00I00:31:30,Temp=8.011514,Fuktighet=48.974121,Trykk=1015.034424,Lys=3.870968
nyktertest1.txt,01-01-00I00:36:44,Temp=6.600330,Fuktighet=49.428818,Trykk=1015.172363,Lys=3.870968
nyktertest1.txt,01-01-00I00:41:59,Temp=5.731909,Fuktighet=49.321609,Trykk=1015.128174,Lys=3.870968
nyktertest1.txt,01-01-00I00:47:14,Temp=5.207238,Fuktighet=48.792984,Trykk=1015.133057,Lys=3.870968
nyktertest1.txt,01-01-00I00:52:28,Temp=4.791119,Fuktighet=48.171944,Trykk=1015.092529,Lys=3.870968
nyktertest1.txt,01-01-00I00:57:46,Temp=4.375002,Fuktighet=47.377159,Trykk=1015.114258,Lys=4.516129
nyktertest1.txt,01-01-00I01:03:01,Temp=4.157896,Fuktighet=46.929855,Trykk=1015.123535,Lys=4.516129
nyktertest1.txt,01-01-00I01:08:15,Temp=4.013159,Fuktighet=46.194218,Trykk=1015.161133,Lys=3.870968
nyktertest1.txt,01-01-00I01:13:29,Temp=3.832237,Fuktighet=45.754311,Trykk=1015.314209,Lys=3.870968
nyktertest1.txt,01-01-00I01:18:43,Temp=3.705593,Fuktighet=45.044548,Trykk=1015.297852,Lys=3.870968
nyktertest1.txt,01-01-00I01:23:57,Temp=3.560856,Fuktighet=44.948437,Trykk=1015.371582,Lys=3.870968
nyktertest1.txt,01-01-00I01:29:11,Temp=3.416119,Fuktighet=44.164742,Trykk=1015.308350,Lys=3.870968
nyktertest1.txt,01-01-00I01:34:25,Temp=3.307568,Fuktighet=43.883793,Trykk=1015.287842,Lys=3.870968
nyktertest1.txt,01-01-00I01:39:39,Temp=3.307568,Fuktighet=43.458672,Trykk=1015.299072,Lys=3.870968
nyktertest1.txt,01-01-00I01:45:10,Temp=3.162830,Fuktighet=42.959621,Trykk=1015.257324,Lys=3.225806
nyktertest1.txt,12-02-23I02:08:19,Temp=3.217106,Fuktighet=42.833935,Trykk=1015.262695,Lys=3.870968
nyktertest1.txt,12-02-23I02:13:33,Temp=3.180922,Fuktighet=42.416210,Trykk=1015.253418,Lys=3.870968
nyktertest1.txt,12-02-23I02:18:49,Temp=3.144737,Fuktighet=42.331184,Trykk=1015.185059,Lys=3.225806
nyktertest1.txt,12-02-23I02:24:03,Temp=2.945724,Fuktighet=42.268341,Trykk=1015.238281,Lys=3.870968
nyktertest1.txt,12-02-23I02:29:18,Temp=2.855265,Fuktighet=41.983696,Trykk=1015.152832,Lys=3.870968
nyktertest1.txt,12-02-23I02:34:32,Temp=2.782896,Fuktighet=42.016968,Trykk=1015.135742,Lys=3.870968
```

The list goes on until the morning. I was not able to only copy the time column of the datasheet, but you can see the time column on the right side of "nyktertest1.txt" which was the file I was writing the data to at the server. The three numbers on the left represent the date, so 11-02-23 is the 11 of February 2023. And the time is right next to the date, a | was used the separate the time and the date. So the data in the first row was logged at 23:39:40, which would be 11:39:40 PM.

But if you look further down the time column, only the minutes and seconds were logged correctly for a good while. It seems like the RTC values where just zeroed out. But after a while, the time was corrected again.

Here is the function for doing the NTP request:
```
void request_NTP()
{
    Serial.println("Starting connection to 'no.pool.ntp.org'");

    Udp.begin(localPort);
    sendNTPpacket(); // send an NTP packet to a time server
    // wait to see if a reply is available
    delay(1000);

    if ( Udp.parsePacket() )
    {
    Serial.println("Packet received");
    // We've received a packet, read the data from it
    Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);

    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;

    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    UNIX_1970 = secsSince1900 - seventyYears;
    Udp.stop();
    Serial.println("UDP Closed");
    }

    else
    {
        Serial.println("No packets where recieved");
        ///Av en eller annen grunn vil programmet stoppe her dersom en kun lukker UDP tilkoblingen
        Udp.stop();
        Serial.println("UDP Closed");
        Serial.println("Trying again..");
        delay(2000);
        request_NTP();
    }
}
```
This is the sendNTPpacket() function which was used in the request_NTP() function above:
```
void sendNTPpacket()
{
    //Serial.println("1");
    // set all bytes in the buffer to 0
    memset(packetBuffer, 0, NTP_PACKET_SIZE);
    // Initialize values needed to form NTP request
    // (see URL above for details on the packets)
    //Serial.println("2");
    packetBuffer[0] = 0b11100011;   // LI, Version, Mode
    packetBuffer[1] = 0;     // Stratum, or type of clock
    packetBuffer[2] = 6;     // Polling Interval
    packetBuffer[3] = 0xEC;  // Peer Clock Precision
    // 8 bytes of zero for Root Delay & Root Dispersion
    packetBuffer[12]  = 49;
    packetBuffer[13]  = 0x4E;
    packetBuffer[14]  = 49;
    packetBuffer[15]  = 52;

    // all NTP fields have been given values, now
    // you can send a packet requesting a timestamp:
    Udp.beginPacket(NTP_server, NTP_port); //NTP requests are to port 123

    Udp.write(packetBuffer, NTP_PACKET_SIZE);
    Udp.endPacket();
    delay(1000);
}
```
This is the function for adjusting the UNIX time to my own timezone:
```
void timezone_adjustment()
{
    TimeChangeRule NoCET = {"CET", Fourth, Sun, Oct, 3, +60};
    TimeChangeRule NoCEST = {"CEST", Fourth, Sun, Mar, 2, +120};
    Timezone Norway(NoCET, NoCEST);
    UNIX_adjusted_No = Norway.toLocal(UNIX_1970);
}
```
This is the function for setting up the RTC:
```
void set_RTC()
{
    const int RTC_second = second(UNIX_adjusted_No);
    const int RTC_minute = minute(UNIX_adjusted_No);
    const int RTC_hour = hour(UNIX_adjusted_No);
    const int RTC_day = day(UNIX_adjusted_No);
    const int RTC_month = month(UNIX_adjusted_No);
    const int RTC_year = year(UNIX_adjusted_No)0;

    /// Starter RTC klokken
    rtc.begin();
    //rtc.setTime(RTC_hour, RTC_minute, RTC_second);
    //rtc.setDate(RTC_day, RTC_month, RTC_year);
    rtc.setYear(RTC_year);
    rtc.setMonth(RTC_month);
    rtc.setDay(RTC_day);
    rtc.setHours(RTC_hour);
    rtc.setMinutes(RTC_minute);
    rtc.setSeconds(RTC_second);
}

```
And this is the buffer being sent to the server:
```
sprintf(buffer,"/cgi-bin/tof.cgi?nyktertest1.txt,d-d-dId:d:d,VannTemp=%lf,LuftTemp=%lf,Fuktighet=%lf,Trykk=%lf,Lys=%lf",rtc.getDay(),rtc.getMonth(),rtc.getYear(),rtc.getHours(),rtc.getMinutes(),rtc.getSeconds(),water_temp,air_temp,humidity,pressure,illuminance);
```
I don't think the RTC is just half its values. I think the watchdog might have bit on the third loop, meaning the program had to do an NTP request at startup to initialize the RTC. But the UNIX time was not successfully received from the server, so the RTC was initialized with all clock values being 0. The program continued to log for a couple of cycles as you can see on the datasheet. But then the watchdog bit again and the circuit was reset. But the NTP request was done successfully this time, and therefore the time was logged correctly until the morning when I picked it up.

This is only my theory though and I am not sure of it. What to you think is happening? And what would be a fix?

Another problem that I noticed in the morning was that the RTC seemed to be lagging over 5 minutes behind the real-time. Is this a normal issue with the SAMD21 RTC? Because im planning to eventually have this Arduino log data for weeks or months without me touching it. Having the clock fall behind after longer time periods would then be a huge problem.

**Edit:**
Under is the write_to_server() function:
```
void write_to_NTNU_server()
{
    Serial.println("Sending the buffer");
    char buffer[256] = {};
    client.print("GET ");
    sprintf(buffer,"/cgi-bin/tof.cgi?nyktertest1.txt,d-d-dId:d:d,VannTemp=%lf,LuftTemp=%lf,Fuktighet=%lf,Trykk=%lf,Lys=%lf",rtc.getDay(),rtc.getMonth(),rtc.getYear(),rtc.getHours(),rtc.getMinutes(),rtc.getSeconds(),water_temp,air_temp,humidity,pressure,illuminance);
    Serial.println(buffer);
    client.print(buffer);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(NTNU_server);

    client.println("Connection: close");
    client.println();
    Serial.println("Buffer sent");
}
```
Here is the code for creating the client object from the NBClient class:
```
NBClient client;
```

title: RTC problems after longer time periods

Answers: 0


body:
**Problem:**

I have a ESP32 and I've been trying to flash it with the Arduino IDE, however it's been giving me Python error messages :/ when I'm trying C/C++ code to flash the Arduino.

**Question:**

How can I setup the board below so I can flashi it with C/C++ from the Arduino IDE?

**Error Message:**

      [6909] Error loading Python lib '/var/folders/wm/_tds7_0s6_j9587rbm54nfv00000gn/T/_MEIli4AzL/libpython3.8.dylib': dlopen: dlopen(/var/folders/wm/_tds7_0s6_j9587rbm54nfv00000gn/T/_MEIli4AzL/libpython3.8.dylib, 10): Symbol not found: ____chkstk_darwin
      Referenced from: /var/folders/wm/_tds7_0s6_j9587rbm54nfv00000gn/T/_MEIli4AzL/libintl.8.dylib (which was built for Mac OS X 11.0)
      Expected in: /usr/lib/libSystem.B.dylib
      in /var/folders/wm/_tds7_0s6_j9587rbm54nfv00000gn/T/_MEIli4AzL/libintl.8.dylib

      exit status 255

      Compilation error: exit status 255

**ESP32:**

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

**References Used/Due Diligence:**

 - [Installing the ESP32 Board in Arduino IDE (Windows, Mac OS X, Linux)][2]
 - [Getting Started with the ESP32 Development Board][3]
 - [ESP32 Bluetooth Classic with Arduino IDE – Getting Started][4]

**Version Numbers:**

 - MAC OS Version: macOS High Sierra Version 10.13.6

 - Arduino Version: Version 2.0.4-nightly-20230119 CLI Version: 0.29.0

  [1]: https://i.stack.imgur.com/ds0Di.jpg
  [2]: https://randomnerdtutorials.com/installing-the-esp32-board-in-arduino-ide-windows-instructions/
  [3]: https://randomnerdtutorials.com/getting-started-with-esp32/
  [4]: https://randomnerdtutorials.com/esp32-bluetooth-classic-arduino-ide/

title: Arduino IDE for ESP32: Compilation Error: Exist status 255

Answers: 1

body: I don't have Mac but I am working on Linux and I also had issues with Arduino IDE v2 (in the past). Because of this I'm still using IDE v1 with no issues and that's my suggestion: try older version of the IDE on your mac, you can still download it. If it won't work you can turn to PlatformIO or VSCode IDEs.


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

I want to read my lithium battery voltage.

1) I WANT TO CREATE A FUNCTION TO READ MY 3.7~4.2V,1200mAH BATTERY VOLTAGE THROUGH A MICROCONTROLLER (ARDUINO OR ATTINY44).

2) THEN I WANT TO CALL THE CREATED BATTERY FUNCTION IN THE FORMULA TO READ PRECISE SENSOR VALUE

        int voltage = ((CALLING BATTERY FUNCTION) * (READ SENSOR VALUE)) / 1023;

3) I AM USING INTERNAL REFERENCE VOLTAGE 1.1V.
NOTE: I want the whole system to run on lithium battery ( I am just creating a prototype on Arduino, if it works, ill be editing the code for my attiny44 using 8mhz external crystal).

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

        void loop() {
          //REFS1 AND REFS0 to 1 1 -> internal 1.1V refference
          ADMUX |= B11000000;
          //We read A1 (MUX0)
          ADMUX |= B00000001;
          // Start AD conversion
          ADCSRA |= B11000000;
          // Detect end-of-conversion
          while (bit_is_set(ADCSRA,ADSC));
          float val = ADCL | (ADCH << 8);
          val = val * 5.7; //Multiply by the inverse of the divider
          Serial.println(val);
        }

**This code is working but it is reading from analog Pin. Is there any possibility to do it without using AnalogPin because I dont have any spare pin on my attiny.**

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

title: adc arduino using reference voltage to read stable/constant lithium battery voltage

Answers: 1

body:
> I want the whole system to run on lithium battery

If you power the Arduino from the battery, then you can indirectly read the battery voltage by reading the internal voltage reference. This requires no pins - just connect the battery across the Arduino ground and the 5V pin. Here is more explanation on why this works...

https://wp.josh.com/2014/11/06/battery-fuel-guage-with-zero-parts-and-zero-pins-on-avr/

Note: Do not connect more than 5 volts or less than 0 volts to the `5V` Arduino pin. This pin is connected directly to the AVR without any overvoltage or reverse polarity protection. Your  3.7~4.2V battery should be fine.


body:
I Have a problem with the connection between two hc 05 modules. The bluetooth modules are paired using AT commands. But when I run the code I cant get any data from the reciever. The bluetooth modules blink together but no data is displayed in the reciever. This is for a RC car that is controlled by a remote controller.

This is the code for the remote
```
void setup() {

  Serial.begin(38400);
}

void loop() {
  Serial.write("Hello!");
  delay(1000);
}
```

I have made sure all the baudrates are 38400 and when I just type the numbers in the serial monitor of the reciver it works fine. I have switched the bluetooth modules but It didn't work either. Boath remote and car has TX - RX and RX - TX wiring.

This is the code of the reciever

```
int data = 0;

void setup() {

  Serial.begin(38400);
}

void loop() {
  if(Serial.available() > 0){
    data = Serial.read();

    Serial.print(data);
  }
}
```
I used softwere serial as well but It gave me the same result. The reciever is an arduino mega and the transmitter is an arduino nano
Pls help.
Thank you.

title: Communication between two hc 05 Bluetooth modules not working

Answers: 0