body:
I've just tried the edited code but now the LED's won't work at all?? I'm sure its something I've done wrong.

~~~~~~~
#include <Adafruit_NeoPixel.h>

#define PIN 3

#define LED_NUMBER_OF (3*188)

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(188, PIN, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

// Set up Variables
 unsigned long timeOut=60000; // timestamp to remember when the PIR was triggered.
 int downUp = 0;              // variable to rememer the direction of travel up or down the stairs
 int alarmPinTop = 5;        // PIR at the top of the stairs
 int alarmPinBottom =7;      // PIR at the bottom of the stairs
 int alarmValueTop = LOW;    // Variable to hold the PIR status
 int alarmValueBottom = LOW; // Variable to hold the PIR status
 int ledPin = 13;           // LED on the arduino board flashes when PIR activated
 int LDRSensor = A0;        // Light dependant resistor
 int LDRValue = 0;          // Variable to hold the LDR value
 int colourArray[LED_NUMBER_OF];      // An array to hold RGB values
 int change = 1;            // used in 'breathing' the LED's
 int breathe = 0;           // used in 'breathing' the LED's

void setup() {
   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
   Serial.begin (9600);  // only requred for debugging
   pinMode(ledPin, OUTPUT);  // initilise the onboard pin 13 LED as an indicator
   pinMode(alarmPinTop, INPUT_PULLUP);     // for PIR at top of stairs initialise the input pin and use the internal restistor
   pinMode(alarmPinBottom, INPUT_PULLUP);  // for PIR at bottom of stairs initialise the input pin and use the internal restistor
   delay (100); // it takes the sensor 2 seconds to scan the area around it before it can
   //detect infrared presence.
   for (int i=0 ;i < LED_NUMBER_OF; i++)  { // initilise the colourArray to zero
   colourArray[i]=0;
   }
}

void loop() {

  LDRValue = analogRead(LDRSensor);
  Serial.println(LDRValue);

  if (timeOut+57000 < millis()) {        // idle state - 'breathe' the top and bottom LED to show program is looping

     breathe = breathe + change;
     strip.setPixelColor(0,0,0,breathe);
     strip.setPixelColor(187,0,0,breathe);
     strip.show();
     if (breathe == 100 || breathe == 0) change = -change;      // breathe the LED from 0 = off to 100 = fairly bright
     if (breathe == 100 || breathe == 0) delay (300);           // Pause at beginning and end of each breath
     delay(25);
  }

  if (LDRValue > 1010) {        // only switch on LED's at night when LDR senses low light conditions - you may have to change the number for your circumstances!

    alarmValueTop = digitalRead(alarmPinTop);        // Constantly poll the PIR at the top of the stairs
    alarmValueBottom = digitalRead(alarmPinBottom);  // Constantly poll the PIR at the bottom of the stairs

    if (alarmValueTop == HIGH && downUp != 2)  {      // the 2nd term allows timeOut to be contantly reset if one lingers at the top of the stairs before decending but will not allow the bottom PIR to reset timeOut as you decend past it.
      timeOut=millis();  // Timestamp when the PIR is triggered.  The LED cycle wil then start.
      downUp = 1;
      topdown();         // lights up the strip from top down
    }

    if (alarmValueBottom == HIGH && downUp != 1)  {    // the 2nd term allows timeOut to be contantly reset if one lingers at the bottom of the stairs before decending but will not allow the top PIR to reset timeOut as you decend past it.
      timeOut=millis();    // Timestamp when the PIR is triggered.  The LED cycle wil then start.
      downUp = 2;
      bottomup();         // lights up the strip from bottom up
    }
    if (timeOut+10000 < millis() && timeOut+15000 < millis()) {    //switch off LED's in the direction of travel.
       if (downUp == 1) {
          colourWipeDown(strip.Color(0, 0, 0), 50); // Off
       }
       if (downUp == 2)  {
        colourWipeUp(strip.Color(0, 0, 0), 50);   // Off
       }
      downUp = 0;
      //   for (int i=0 ;i < 350; i++)  {          // Depending on your preference you may want to include this loop to clear out the colourArray
      //    colourArray[i]=0;
      // }
    }

    if (timeOut+15000 < millis() && timeOut+54999 > millis()) waterfall();    // Waterfall effect to play between these times after a PIR trigger.

    if (timeOut+55000 < millis() && timeOut+56999 > millis()) fade();   // Fade/switch off LED's
  }
}

 void topdown() {
    Serial.println ("detected top");                // Helpful debug message
    colourWipeDown(strip.Color(50, 50, 30), 10);    // Warm White
    for(int i=0; i<3; i++) {                        // Helpful debug indication flashes led on Arduino board twice
      digitalWrite(ledPin,HIGH);
      delay(200);
      digitalWrite(ledPin,LOW);
      delay(200);
    }
 }

 void bottomup() {
    Serial.println ("detected bottom");          // Helpful debug message
    colourWipeUp(strip.Color(50, 50, 30), 10);   // Warm White
    for(int i=0; i<3; i++) {                     // Helpful debug indication flashes led on Arduino board twice
      digitalWrite(ledPin,HIGH);
      delay(200);
      digitalWrite(ledPin,LOW);
      delay(200);
    }
  }

 // Fill the dots one after the other with a color
 void colourWipeDown(uint32_t c, uint8_t wait) {
   for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
 }

 // Fill the dots one after the other with a color
 void colourWipeUp(uint32_t c, uint8_t wait) {
   for(uint16_t i=strip.numPixels(); i < -1; i--) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
 }

 // Play the Waterfall effect
 void waterfall(){
    for(int i= 350; i>-1; i--) {            // Shift the RGB colours down in the colourArray[]
        colourArray[i+3]=colourArray[i];
        }
      colourArray[0] = random(0,20);        // Genearate the red component of the 1st LED at the top of the stairs
      colourArray[1] = random(0,40);        // Genearate the green component of the 1st LED at the top of the stairs
      colourArray[2] = random(10,70);       // Genearate the blue component of the 1st LED at the top of the stairs

      for (int k=0; k<350; k=k+3)   {       // Set and send the colours to the strip
       uint32_t c = strip.Color(colourArray[k],colourArray[k+1],colourArray[k+2]);
       strip.setPixelColor(((k+3)/3)-1,c);
       }

      strip.show();      // and display the result
      delay(35);         // delay to simulate running water
 }

 // Play the LED fade out
 void fade(){
 for (int j = 0; j <70; j++) {
   for(int i=350; i>-1; i--) {
     colourArray[i]=colourArray[i]-1;      // reduce intensity of light by 1
     if (colourArray[i] <= 0 ) colourArray[i] = 0;
   }
   for (int k=0; k<351; k=k+3)   {
     uint32_t c = strip.Color(colourArray[k],colourArray[k+1],colourArray[k+2]);
     strip.setPixelColor(((k+3)/3)-1,c);
   }
  strip.show();
  delay(60);
  }
 breathe = 0;
 change = 1;
 }
~~~~~~


sender: user

message:
Need function to convert bool array to int- why doesnt this work?

Hey I wrote this function to convert an bool array to int:
(Math Lob included):

    bool b_array[5];

    int convertToInt(start_index,stop_index){
        int run=0;
        int result=0;
        for(int id=start_index;id<=stop_index;id++){
            result+=b_array[id] * pow(2.0,run);
            run++;
        }
        return result;
    }

but it doesnt this work?

Thanks and kind regards
Nic

sender: assistant

body:
Assuming little-endian bools (least significant bool first), you should use simple bit-shifting, not floating point power calculations:

    for(int id=start_index;id<=stop_index;id++){
        result |= b_array[id] ? (1 << run) : 0;
        run++;
    }

The *ternary* operation (`b_array[id] ? (1 << run) : 0`) means:

* If `b_array[id]` is true,  then
  * Or `result` with 1 left-shifted `run` times and store in `result`
* otherwise
  * Or `result` with 0 and store the result (no-operation).


message:
Disable interrupts when doing critical things?

I've got a few functions like this that log, or do more critical things like get/save configuration variables.

    /**
       Write weather data to csv
       commit: datetime,minHumidity,maxHumidity,minTemperature,maxTemperature,rainfall,irrigationRan
    */
    void writeWeatherData() {
      noInterrupts();
      DBG_OUTPUT.println(F("[WEATHER DATA] Attempting to save weather data..."));
      bool writeHeader = SPIFFS.exists("/weather_data.csv") ? false : true;
      File file = SPIFFS.open("/weather_data.csv", "a");
      if (!file) {
        addPrintError("[WEATHER DATA] There was an error opening weather_data.csv for writing.");
        interrupts();
        return;
      }
      String data = "";
      if (writeHeader) {
        data += "datetime,minHumidity,maxHumidity,minTemperature,maxTemperature,rainfall,irrigationRan\r\n";
      }
      DateTime now = rtc.now();
      char buf[] = "MM/DD/YY hh:mm:ss";
      String t = now.toString(buf);
      float rainfall = getRainfall();
      data += t + "," + minHumidity + "," + maxHumidity + "," + minTemperature + "," + maxTemperature + "," + rainfall + "," + irrigationRan + "\r\n";
      if (file.print(data)) {
        DBG_OUTPUT.println(F("[WEATHER DATA] File was written."));
      } else {
        addPrintError("[WEATHER DATA] File write failed.");
      }
      file.close();
      DBG_OUTPUT.println(F("[WEATHER DATA] Task completed."));
      interrupts();
    }

I surround  code with `noInterrupts` and `interrupts` however I am not sure if it is required. Assume that an interrupt is triggered at the exact moment when the above function is saving something, what exactly happens if I didn't have `noInterrupts` .etc.?

body:
Interrupts happen all the time and code works just fine without locking them out. It doesn't matter if it's at the exact moment that a function is saving something - a properly written interrupt handler will save any necessary state so that whatever was interrupted can continue without problems. If it doesn't, the software will crash hard.

You should lock out interrupts as little as possible. Interrupts are used for critical timing functions and for network and other communications. Locking them out will cause these functions to be unreliable and may disrupt network connections.

The only time you should disable interrupts is when a data structure that an interrupt handler needs to use is in an inconsistent state. If an interrupt handler needs to use a shared data structure, disable interrupts before beginning to modify it outside of the interrupt handler, and re-enable them when you're done. Make sure it's as brief as possible.

Interrupt handlers should do as little as possible. They definitely should not call SPIFFS, should not call the real time clock, should not allocate or instantiate objects and should not do i/o operations. And you should not be disabling interrupts around calls to SPIFFS in hopes of making it safe for your interrupt handler to also call SPIFFS.

Take this as an example: suppose you want to use SPIFFS in both an interrupt handler and outside the interrupt handler. So you think you'll be clever and disable interrupts before you call SPIFFS outside the interrupt handler. Do you know exactly how SPIFFS works? Do you know whether SPIFFS uses any other functions that you might need to disable interrupts for in other parts of your code so that the interrupt handler won't disrupt them? Do you know for certain that SPIFFS doesn't allocate memory temporarily? Imagine that it does - now you also need to find every place in your code that might allocate memory and lock out interrupts around it, too. And maybe SPIFFS doesn't allocate memory - but do you know that SPIFFS in the future will never allocate memory?

You can't make assumptions about exactly how modules that you call are implemented, or how they'll be implemented in the future.

Unless you seriously know what you're doing, on microcontrollers like Arduinos, the ESP8266 and the ESP32, the best thing an interrupt handler can do is just set a flag to indicate that the interrupt occurred, and let code in the `loop()` check for the flag. The flag should most likely just be a simple Boolean variable declared as volatile so that the C compiler is aware that its value may suddenly change:
```
volatile boolean interrupt_flag = false;
```
It's safe to set that `interrupt_flag` to `true` inside the interrupt handler and it's safe to check the value in `loop()`, reset it to `false` and do whatever work was needed. Don't do more than this unless you know what you're doing.


body:
John Romkey provided you an _excellent_ answer. I am adding this just to
provide another perspective, hopefully complementary.

Interrupts are meant to handle the most time-critical tasks. Those tasks
that cannot wait for the next `loop()` iteration, such as counting a
pulse from an encoder, or getting a byte out of the UART receive buffer.
If you delay them too much, they may miss their deadline, resulting in
unreliable operation of the whole program (counter missing pulses, UART
missing bytes...).

Sometimes you have a piece of code that cannot afford being interrupted.
Maybe it is extremely time-critical, like the generation in software of
a pulse that is exactly 0.5 µs wide. More commonly it will be
reading data from memory that is being modified by an interrupt handler,
and you don't want that data to be modified in the middle of the read
operation. Such pieces of code are called _critical sections_, and you
keep them safe in between `noInterrupts()` and `interrupts()`. If an
interrupt request fires while the program is running a critical section,
the request is put on hold and serviced only when the critical section
is done. This adds some **latency** to the interrupt which, if
excessive, can lead to the interrupt missing its deadline. This is the
reason critical sections should be kept as short as possible.

You have been told that interrupt handlers should be kept as short as
possible, but I am not sure you know _why_ it is so. The fundamental
reason is that _interrupt handlers are themselves critical sections_.
While a handler is running, other interrupts are blocked. On some
architectures (notably _not_ AVR, I don't know about the ESP), only
interrupts of lower priority are blocked, but it is still an issue. The
rationale for keeping those handlers short applies equally to _any_
critical section.

Now, just to provide an example of the sort of bad things that can
happen if you block interrupts unnecessarily, consider this piece of
code:

```c++
noInterrupts();
Serial.println("Inside critical section.");
interrupts();
```

What this does is put the string `"Inside critical section."` in a
software buffer. Not a huge task you may say. Actually pushing the bytes
out to the UART is the job of an interrupt handler, triggered by the
UART when it is ready to accept a new byte. But then what happens if
there is not enough free space in the buffer for the string? In this
case, `Serial.println()` waits in a busy loop. It waits for the
interrupt to move bytes out of the buffer and make space for the new
string. But wait, we have just disabled interrupts... See the problem?
This is the reason it is generally advised to never `Serial.print()`
inside an interrupt handler. The same applies to any critical section.

**Edit**: As Juraj points out in a comment, the `HardwareSerial` code
now [implements a workaround against this problem][workaround]: if it
detects it has to wait with interrupts disabled, it takes care of
calling the interrupt handler itself. This is a (relatively) late
addition to the `HardwareSerial` code. Their authors presumably
witnessed too many beginners doing debug prints from interrupt handlers
and being bitten by this issue. Note that it is a workaround, not a
solution: it will often make the critical section last for an
unreasonably long time.

I wouldn't rely on similar APIs, or even on other cores, systematically
implementing this kind of safeguards though: some library authors just
trust the user to not do silly things.

[workaround]: https://github.com/arduino/ArduinoCore-avr/commit/dbe23685c27cb1467dc84140e4899a0bf8e23248


message:
Adafruit_LSM303 tilt compensated compass

I am having troubles with tilt compensating my compass.

I am using the LSM303DLHC accelerometer/compass in combination together with the Adafruit_LSM303_U.h.

I was able to get my compass to the right direction withthis little snippet:

      float heading = (atan2(event.magnetic.y,event.magnetic.x) * 180) / Pi;

I also was able to get my roll and tilt angle with converting my X and Y of my accelerometer to angles:

       headingNew = asin(eventA.acceleration.x/10);
       float tilt = headingNew*180/PI/90*100;
       headingNew = asin(eventA.acceleration.y/10);
       float roll = headingNew*180/PI/90*100;

Now I need to compensate my angle to get a new x and y for inside my heading calculation but the problem is that I can't seem to get the right functions.
Online I found the functions below from a large tutorial about the sensor but this gives me completely wrong values.

        //Xh = event.magnetic.x*cos(tilt)+event.magnetic.z*sin(tilt);
        //Yh = event.magnetic.x*sin(roll)*sin(tilt)+event.magnetic.y*cos(roll)-event.magnetic.z*sin(roll)*cos(tilt);

or in the code itself:

       Xh = event.magnetic.x*(eventA.acceleration.z/10)+event.magnetic.z*(eventA.acceleration.x/10);
       Yh = event.magnetic.x*(eventA.acceleration.y/10)*(eventA.acceleration.x/10)+event.magnetic.y*(eventA.acceleration.z/10)-event.magnetic.z*(eventA.acceleration.y/10)*(eventA.acceleration.z/10);

I actually get the right angle on a flat surface. But it is even more inaccurate at an angle as the normal heading.
Does anybody have any experience with this sensor? Already a big thanks for the help.

body:
The `sin()` and `cos()` functions expect their arguments to be in
_radians_. If you feed them with anything else, be it degrees, percent
slope, or whatever, expect the result to be just crap.

------------------------------------------------------------------------

**Edit**: The OP changed the question, invalidating my answer. So here
comes a new answer...

You have mistaken `eventA.acceleration.y` for `cos(tilt)`,
`eventA.acceleration.x` for `sin(tilt)`, and so on. _They are not the
same_. You may think they are the same up to some multiplicative factor,
and that's right. However, the factor doesn't cancel out as soon as you
do computations like `sin(roll)*sin(tilt)`. Don't rush your math: if you
want to transform known-good formulas to more practical ones, check every
step of the transformation carefully.


body:
Via this [Youtube movie][1] I found a different [library][2] and made this code:

    #include <SPI.h>
    #include <Wire.h>
    #include <LSM303.h>
    const int centreX  = 160;
    const int centreY  = 120;
    const int diameter = 100;
    #define STMPE_CS 8
    #define TFT_CS 10
    #define TFT_DC 9

    int last_dx, last_dy, dx, dy;
    LSM303 compass;
    void setup(){
    Serial.begin(9600);
    Serial.println("meters Test"); Serial.println("");
    Wire.begin();
    compass.init();
    compass.enableDefault();

    compass.m_min = (LSM303::vector<int16_t>){-602, -704, -511}; //values from
    cailbration.
    compass.m_max = (LSM303::vector<int16_t>){+557, +436, +529}; //values from
    cailbration.
    last_dx = centreX;
    last_dy = centreY;
    }
    void loop() {
    compass.read();
    double angle;
    float heading = compass.heading();

    angle= heading; //use heading from compass
    dx = (diameter * cos((angle-90)*3.14/180)) + centreX;    // calculate X position
    dy = (diameter * sin((angle-90)*3.14/180)) + centreY;    // calculate Y position
    last_dx = dx;
    last_dy = dy;
    Serial.print("angle:"); Serial.println(angle);
    Serial.println("tilt:"); Serial.println(compass.a.x);
    delay(25);
    }

  [1]: https://www.youtube.com/watch?v=HHJEaB1iS30
  [2]: https://github.com/pololu/lsm303-arduino

Now everything works. Sometimes you just need to choose your battles.


message:
What pins can be used for chip select (CS, CC) on the Arduino nano every?

I’ve checked the nano’s tech specs but I can’t seem to find any information regarding it. I’ve tried setting it to pin 26 (digital output)

body:
The following answer assumes the Arduino is the master.

You can use any pin for that (at least any GPIO pin).

Multiple SPI devices can be connected to a SPI peripheral on an Arduino (in principle).

Every SPI device should have their own CS/CC pin, and is mandatory when you use multiple SPI devices.

For this reason, there is no single pin the SPI can define for being used as CS/CC pin. However, it should give a GND or VCC value, thus a CS/CC pin should typically be configured as a digital input pin (as master) for each slave.
(See remark of KIIV too); as slave the CS/CC pin should be a digital output pin.

For the other pins (MOSI, MISO, CLK), the Arduino uses a fixed set of pins because all SPI devices will be connected to these pins.

So the CS pin is configurable, and the other spi pins are fixed.


message:
Why are embedded C codes are ending with "while(1)"?

I always see while(1); at the end of the C codes such as:

    #include <stdio.h>

    int main(void)
    {

        //Some code here...

        while(1);

    }

If I'm not wrong that it always exists, what is the function of that?

edit:

    #include <stdio.h>

    int main(void)
    {

         while(1);
        //Some code here...

    }

body:
It's because in non-embedded systems, when `main()` finishes it returns to the operating system and the program is removed from memory. In embedded systems there's no operating system to return to, and the program can't be removed from memory.  So... what do you do when the program is finished?  Simple: you do nothing. Forever.  And that's what `while(1);` does.

Some compilers and C libraries automatically add `while(1);` in the `exit()` routine, but not all do - so it's better to do it explicitly than rely on something that may or may not be there.


body:
    while(1);

should actually be read as

    while(true)
    {
      // No statements
    }

    // Statements following here will never be executed

The result is: while the condition is true, it performs no statements. Since the condition `true` is always true, it keeps performing the statements within the { and }, which are no statements, resulting that no statement is executed but it will also not executing statements after the while.


body:
The line while(1) in a C program creates an infinite loop- this is a loop that never stops executing. It executes over and over and over again, unless the program is intentionally stopped or there is some condition under this loop that gets met that takes the program out of this infinite loop.

Let's take the following C program.

include <stdio.h>

void main()
{
printf("Hello World");
while(1);
}

This program prints the words "Hello World" to the standard output, which is most likely a serial port.

After it prints it, it goes to execute the next line, while(1). This line makes the microcontroller sit and wait, forever or until the microcontroller is reset.


message:
integer overflow in expression [-Woverflow] - TinyCircuit

I have a tiny circuit Bluetooth shield and I was testing out the sample code that was provided by tinycircuit. However, when I tried uploading the sample code into the board, I kept having the following error. How can I solve this error?

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

this is the piece of code where there error seems to be happening.

    #define  ADV_INTERVAL_MIN_MS  50
    #define  ADV_INTERVAL_MAX_MS  100

    void setConnectable(void)
    {
      tBleStatus ret;

      const char local_name[] = {AD_TYPE_COMPLETE_LOCAL_NAME, 'B', 'l', 'u', 'e', 'N', 'R', 'G'};

      hci_le_set_scan_resp_data(0, NULL);
      PRINTF("General Discoverable Mode.\n");

      ret = aci_gap_set_discoverable(ADV_IND,
                                     (ADV_INTERVAL_MIN_MS * 1000) / 625, (ADV_INTERVAL_MAX_MS * 1000) / 625,
                                     STATIC_RANDOM_ADDR, NO_WHITE_LIST_USE,
                                     sizeof(local_name), local_name, 0, NULL, 0, 0);

      if (ret != BLE_STATUS_SUCCESS)
        PRINTF("%d\n", (uint8_t)ret);

    }

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

body:
You can specify the type of a number using suffixes such as `L`, `LL`,
`UL` and such. If you don't specify the type this way, all integers that
are small enough to fit in an `int` will be of type `int`. When you
write

```c++
ADV_INTERVAL_MIN_MS * 1000
```

it gets expanded by the preprocessor to

```c++
50 * 1000
```

Since both arguments are of type `int`, the compiler will use this type
to compute the result. However, the result is 50,000, and on 16-bit
systems the largest number that can fit in an `int` is 32,767, thus the
overflow.

As suggested by Majenko, the simple solution is to add the `L` suffix
(for `long`) to either operand. The compiler will then do the
arithmetics using the `long` data type.


message:
Baudrate is set to 9600 automatically even if specifying a different value

You initialize the serial communication via USB with

```c++
Serial.begin(baudrate);
```

where baudrate is a `long` specifying the number of symbols you want to send over the connection per second. You can put pretty much any number in there, but not every number makes sense.

One thing that I found odd though is that I can't seem to actually use a different baudrate than 9600. The sketch compiles and uploads just fine, but if I check the actual speed of the serial port via
```
setserial -ag port
```
where `port` is the port of my Teensy 4.0 board (that command is something you can use in the terminal of Linux) or with
```c++
Serial.baud();
```
directly in the sketch it always says 9600. I suspect that this is caused by something inside the code behind `Serial.begin()` since I can manually set the baudrate via the terminal in Linux using
```
stty speed baudrate < port > port
```
where (again) `baudrate` is the speed I want to use and `port` is the port of my board (checking it with the first terminal command: it works). But when restarting the program on the board the baudrate reverts to 9600.

Does anyone know why this is and how to fix this?

body:
The whole concept of Baud Rate with USB communication is completely meaningless.  There is no such thing as "baud rate" over USB.

What there is, and what you are confusing with "baud rate" is a configuration item which the host can send to the device which is a "I would like you to communicate with other devices at this speed" configuration item.

This is intended for use with USB to UART adaptors where it is used to configure the baud rate of a physical UART interface for downstream communication.

When you set the baud rate in your code it is ignored, since it has no meaning.

When you set the baud rate on your computer it sends it as this configuration value, which you can then retrieve, should you have an interest in that value, using the `Serial.baud()` function.


body:
The problem may be in flow control, as LukasFun suggested. Obviously, a low speed RS232 device will not be able to handle a continuous data stream at 1.5 Mbps

A quick look at this paper may help.
https://www.usconverters.com/index.php?main_page=page&id=49&chapter=0


message:
ESP8266 stops working when I use 2x static const char(PROGMEM)

*Sdk version: 2.2.2-dev(5ab15d1)
*Core Version: 2_6_1

This is the error returned:

    Exception 3: LoadStoreError: Processor internal physical address or data error during load or store PC: 0x4000bf64 EXCVADDR: 0x4024e963
    Decoding stack results
    0x4020175d: HTML1(String) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266/WString.h line 128
    0x40238c26: umm_info(void*, int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\umm_malloc/umm_info.c line 164
    0x40100278: millis() at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\core_esp8266_wiring.cpp line 188
    0x40238c26: umm_info(void*, int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\umm_malloc/umm_info.c line 164
    0x4020af74: String::copy(char const*, unsigned int) at C:\Users\b.yuzo\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.1\cores\esp8266\WString.cpp line 214
    0x40201a3c:

Code:

    static const char HTML1[] PROGMEM = R"=====(
    <!DOCTYPE HTML><html><head>
    <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
    )=====";

    static const char HTML2[] PROGMEM = R"=====(
    <button type='button' onclick='sendData(2)'>Test2</button>
    )=====";

    String html_return = HTML1;
    html_return += "<button type='button' onclick='sendData(1)'>Test</button>";
    Serial.println("Before Second Const Char");
    html_return += HTML2; //<< ESP stops working here

body:
See [Guide to PROGMEM on ESP8266 and Arduino IDE](https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html#functions-to-read-back-from-progmem).

Since you put your char array into `PROGMEM`, special functions must be used to load it from flash into RAM; so to load it into a `String` object, the `FlashHelper` class must be used. You can simply use the macro `FPSTR(progmem_ptr)`.

    #include <Arduino.h>

    void setup() {
     Serial.begin(115200);
     Serial.println("\nStart firmware");

     static const char HTML1[] PROGMEM = R"=====(
     <!DOCTYPE HTML><html><head>
     <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
     )=====";

     static const char HTML2[] PROGMEM = R"=====(
     <button type='button' onclick='sendData(2)'>Test2</button>
     )=====";

     String html_return = HTML1;
     html_return += "<button type='button' onclick='sendData(1)'>Test</button>";
     Serial.println("Before Second Const Char");
     //html_return += HTML2; //crashes
     html_return += FPSTR(HTML2); //works
     Serial.println("Result");
     Serial.println(html_return);
    }

    void loop() {

    }

Outputs

    Start firmware
    Before Second Const Char
    Result

            <!DOCTYPE HTML><html><head>
            <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
            <button type='button' onclick='sendData(1)'>Test</button>
            <button type='button' onclick='sendData(2)'>Test2</button>


message:
How to Use Function Code 6 Modbus RTU library

I'm trying to communicate with a temperature controller using Modbus RTU.
I used [this][1] Arduino library.

I was able to read PV(current temperature value) using below code. It uses Function code 4.

I want to set SV value(Set Value) using **Function code 6**

I replaced `telegram.u8fct = 0x04;` to `telegram.u8fct = 0x06;` and `telegram.u16RegAdd = 0x03E8;` to relevant address for SV. But, I couldn't get success.

How can I implement Function Code 6 in this library ?

Code for read PV as below. Its working properly.

        #include <ModbusRtu.h>

        // data array for modbus network sharing
        uint16_t au16data[16];
        uint8_t u8state;

        /**
            Modbus object declaration
            u8id : node id = 0 for master, = 1..247 for slave
            u8serno : serial port (use 0 for Serial)
            u8txenpin : 0 for RS-232 and USB-FTDI
                         or any pin number > 1 for RS-485
        */
        //TRANSMISSION CONTROL PIN - 8
        //HADWARE SERIAL NUMBER - 2
        Modbus master(0, 2, 8); // this is master and RS-232 or USB-FTDI

        /*
           This is an structe which contains a query to an slave device
        */
        modbus_t telegram;

        unsigned long u32wait;

        void setup() {
          Serial.begin(9600);
          master.begin(9600); // baud-rate at 9600
          master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
          u32wait = millis() + 1000;
          u8state = 0;
        }

        void loop() {
          switch ( u8state ) {
            case 0:
              if (millis() > u32wait) u8state++; // wait state
              break;
            case 1:
              telegram.u8id = 0x01; // slave address
              telegram.u8fct = 0x04; // function code (this one is registers read)
              telegram.u16RegAdd = 0x03E8; // start address in slave [CHANNEL 1 PV]
              telegram.u16CoilsNo = 0x01; // number of elements (coils or registers) to read
              telegram.au16reg = au16data; // pointer to a memory array in the Arduino

              master.query( telegram ); // send query (only once)
              u8state++;
              break;
            case 2:
              master.poll(); // check incoming messages
              if (master.getState() == COM_IDLE) {
                u8state = 0;
                u32wait = millis() + 100;
                Serial.println(au16data[0]);//PRINT TEMPARATURE VALUE
              }
              break;
          }
        }

  [1]: https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino

body:
I managed to change SV value.

According to the library, when using function code 6, It get sending data(temperature value) from `au16regs[0]`as below piece of code of library file.
Need to setup that value before requesting.

(ModbusRtu.h - line number 601)

    case MB_FC_WRITE_REGISTER: //if cunction code 6
        au8Buffer[ NB_HI ]      = highByte(au16regs[0]);
        au8Buffer[ NB_LO ]      = lowByte(au16regs[0]);


message:
MP3 File through ARDUINO

Hey question is that it is possible to play MP3 file in arduino without changing it into .wav file if possible ,then your suggestions are welcome
Thanks

body:
This little device is really good and easy to set up.
https://www.dfrobot.com/product-1121.html

You can use a pin and set it to ground with a resistor between to change songs if you don't need something fancy.


message:
Position Feedback for Stepper Motor

I want to rotate a gearwheel with a stepper motor. While Arduino is on everything is well.

My gearwheel transfer its power to a gear worm. The worm will go 10th cm and back repeatedly. When I cut the power, Stepper Motor stops where its last step and position. When the power is on Stepper starts from last position but steps starts from the first step.

Assume that 2038 steps are rotating the Motor one revolution. For example, when 1500 step pass and power cut. Worm is on 6th cm now. And the power is on. Stepper is working from 6th cm and is going 2038 steps. Now it is on 16th cm.

If I use servo, when the power is on, I can write the motor to the 0 position. But I have to use stepper motor. How can I fix this?

Stepper Motor: 28 BYJ 48
Driver: ULN2003A

The cod is here;

    int State;
    int Wait;

    void setup() {

      pinMode(8,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(10,OUTPUT);
      pinMode(11,OUTPUT);

      digitalWrite(8,LOW);
      digitalWrite(9,LOW);
      digitalWrite(10,LOW);
      digitalWrite(11,LOW);
      State = 8;
      Wait = 2;
    }

    void loop() {

      turnRight(2038);
      delay(1000);
      turnLeft(2038);
      delay(1000);

      }

    void turnRight(int Step) {
        for (int i = 0; i < Step ; i++){
          digitalWrite(State,HIGH);
          delay(Wait);
          digitalWrite(State,LOW);
          IncreaseState();
        }
    }

    void IncreaseState() {
      State++;
      if (State==12){
        State=8;
      }
    }

    void turnLeft(int Step) {
    for (int i = 0; i < Step ; i++){
          digitalWrite(State,HIGH);
          delay(Wait);
          digitalWrite(State,LOW);
          DecreaseState();
        }

    }

    void DecreaseState() {
      State--;
      if(State==7){
        State=11;
      }
    }

body:
There are multiple ways to to this. The easiest and most commonly used way is to use a limit switch as home position sensor. At startup the device will first drive the motor in the direction of the limit switch, until the switch get's activated. Now the the absolute position on this axis is known and you can go on from there. (CNC machines and 3D printers mostly work that way. Often they retract again from the limit switch and approach the switch again with less speed, to increase the accuracy). For this you just need a micro switch on the axis and connect it to one input pin. In `setup()` you are driving the stepper motor in the direction of the limit switch, until it gets activated. Then you are on position zero and can go on with your sketch.

A more difficult way is to introduce a measurement of position into your device. A servo incorporates a potentiometer connected to the axis. By measuring the voltage on this potentiometer (it is basically a voltage divider), the servos electronics can always know, where it currently is. There are also fader potentiometers, where you don't rotate a knob, but you slide a fader over a linear rail. You might find a fader potentiometer, that fits your scale (10cm is not that much, there might be some).

Or you could save the current position to a non-volatile memory (like EEPROM) and retrieve it, when you start up. But since a power-cut during writing of the position may corrupt the data, you would have to go a more complex way. Something like sensing, that the power was cut, providing the Arduino with power through a big capacitor, so that, when it senses power loss, it still has enough time to write the current position to a non-volatile memory. (This is also better for the EEPROM, than continuously writing to it, since EEPROM has limited write cycles).

All in all I would suggest using the first mentioned method (limit switch). It is used in many devices for a reason. Though it depends on your exact project requirements.


body:
Another answer chrism didn't mention is to use an "absolute position rotary encoder". It's a device that outputs a bit pattern using "gray code" or "grays binary" that tells you the position of the shaft. The more bits in the encoder, the more precisely you can measure the position. The "gray code" bit pattern enables you to read the changing position without false reading due to contact/sensor bounce.

However, if you want to uniquely detect 2038 separate steps you'd need a 12 bit rotary encoder, which would be a little expensive and take a lot of interface pins.


message:
How to prevent counter increment when holding the button

I am a newbie and also a noobie. Kindly assist this poor boy over here.
I am looking for a way to increment a variable by one each time a button is pressed. Current approach is the following :
```C
void buttonLoop() {
  int win = 0;
  while (win ==0) {
  display.setCursor(0, 0);
  //getButtons() function can be used to test if any button is pressed, or used like:
  //getButtons(TSButtonUpperLeft) to test a particular button, or even like:
  //getButtons(TSButtonUpperLeft|TSButtonUpperRight) to test multiple buttons
  //results are flipped as you would expect when setFlip(true)
  if (display.getButtons(TSButtonUpperLeft)) {
    display.println("Pressed!");
    score++;
    updateScore();
  } else {
    display.println("          ");
  }
  display.setCursor(0, 54);
  if (display.getButtons(TSButtonLowerLeft)) {
    display.println("Pressed!");
    score++;
    updateScore();
  } else {
    display.println("          ");
  }
  display.setCursor(95 - display.getPrintWidth("Pressed!"), 0);
  if (display.getButtons(TSButtonUpperRight)) {
    display.println("Pressed!");
    score++;
    updateScore();
  } else {
    display.println("          ");
  }
  display.setCursor(95 - display.getPrintWidth("Pressed!"), 54);
  if (display.getButtons(TSButtonLowerRight)) {
    display.println("Pressed!");
    score++;
    updateScore();
  } else {
    display.println("          ");
  }
}
}
```
In my case, the counter will keep increasing if I do not let go of the button. How do I make it so that the counter will only increase by 1 even if i continue holding onto the button.

Thank you for all the kind souls in this society :)

body:
See my answer in this thread:

https://arduino.stackexchange.com/questions/70415/how-to-connect-big-dome-button-with-arduino

That thread explains how to wire up a switch and write code that increments a counter each time a button is pressed.

The bits you care about:

Connect one lead of the switch to a digital input, and the other lead to ground.

Then set your switch pin to `INPUT_PULLUP` mode. Now your switch will read HIGH until it's pressed, then it will read LOW.

create a variable at the top of your code called buttonState:

    byte buttonState = HIGH;

Also define an unsigned long variable nextReadMillis:

    unsigned long nextReadMillis = 0;

and a pressCount variable:

    unsigned int pressCount = 0;

And define a debounceTime:

    #define debounceTime 50

In your loop, do something like this:

    void loop() {
        //Get the new millis(value)
        unsigned long newMillis = millis();

        //only look at the new button value if enough time has elapsed.
        if (newMillis >= nextReadMillis) {
           byte newButtonState = digitalRead(buttonPin);

           //Only do something if the button state has changed
           if (buttonState != newButtonState) {
              buttonState = newButtonState;
              nextReadMillis = newMillis + debounceTime;
              //If the button is now in the pressed (LOW) state, increment the count
              if (buttonState == LOW) {
                  pressCount++;
              }
           }
        }
    }

That's pseudo-code. It likely has syntax errors. It's not meant to be copy/pasted. Use it as a guide for your project.

The code using `millis()` is a version of "software debouncing." Electrical switches tend to "jitter" or "bounce" between their on and off states very rapidly when they are first pressed/released. By only checking for state changes after a brief delay, you ignore the jitter in the readings.

You can adjust the value of debounceTime up or down a little. A value of 50 is 1/20th of a second, which should make your button presses quite responsive, but still debounce the switch well. If you find your count sometimes increases by more than one for a button press, you can increase the value to 100 or even 500, although at 500 (1/2 second) the button won't respond to really rapid presses


message:
Debouncing Switch Issue

I’m trying to use a LDR to monitor the light levels and if the LDR is covered and the button is pressed, the LED should switch on. I’m in the process of adding debouching but every time I run the code, the it goes in the if (val > 421) part the led is on, but the button hasn’t been pressed and the code stops.

I’m suspecting it may be a logic issue with the states. I’m using the millis function for the debouncing so the code should ignore the first 200ms of when the button is pressed. I just help in regard to the debouncing so when the LDR is covered and the switch is pressed , the LED should turn on.

The code is shown below:

    const int buttonPin = 8;
    const int ldrPin = 0;
    const int LEDPin = 13;

    boolean buttonState = 0;
    boolean NEWbuttonState = 0;
    boolean LEDState = 0;
    int bounce_time = 200;
    unsigned long my_time;

    boolean on;

    int val = 0;

    void showValue(float myval)
    {
      Serial.print(myval);
      Serial.print(" lightstatus ");
      Serial.println(LEDState);
    }

    void setup()
    {
      pinMode(buttonPin, INPUT);
      pinMode(LEDPin, INPUT_PULLUP);
      on = false;
      analogReference(DEFAULT);
      pinMode(ldrPin, INPUT);
      Serial.begin(9600);
      my_time = millis();
    }

    void loop()
    {

      val = analogRead(ldrPin);

      NEWbuttonState = digitalRead(buttonPin);

      if ((millis() - my_time) > bounce_time)
      {
        digitalWrite(LEDPin, LOW);

        if (buttonState != NEWbuttonState)
        {
          buttonState = NEWbuttonState;

          //if button is pressed
          if (NEWbuttonState == 1 && LEDState == 0)
          {
            buttonState = NEWbuttonState;

            if (val > 421)
            {
              my_time = millis();

              digitalWrite(LEDPin, 1);
              LEDState = 1;
              showValue(val);
              Serial.print("button press");
            }

            if (val < 420)
            {
              my_time = millis();

              digitalWrite(LEDPin, 0);
              LEDState = 0;
              showValue(val);
            }
            buttonState = 1;
          }
          else
          {
            if (NEWbuttonState == 0)
            {
              buttonState = 0;

            }
          }
        }
      }
    }

body:
Bouncing of a mechanical switch happens in very few milliseconds, faster than you can see a led shine.

So, for your task, you don't need any debouncing.

The description or your task lacks what should happen "if not". I assume the led should shine while both button is pressed and ldr is covered. If either button is not pressed, or ldr is lit, the led should remain off.

This one is too simple:

    void loop() {
      bool ldrDark = analogRead(A0) < MAX_LDRBRIGHT;
      digitalWrite(led, ldrDark && digitalRead(buttonPin));
    }

To add a delay (led goes on only when button is pressed some time) is easy as well.

    const byte LED = LED_BUILTIN; // 13 on UNO

    const byte BUTTON = 8;  // Button connects to GND
    const byte PRESSED = LOW; // due to INPUT_PULLUP
    const int DELAY = 300; // ms
    bool btnState; // true = HIGH when presse

    const byte LDR = A0; // LDR to 5V, Resistor to GND : Low values when dark
    const int MIN_LDRBRIGHT= 420; // depends on resistor and LDR

    void setup() {
       pinMode (LED, OUTPUT);
       pinMode (BUTTON, INPUT_PULLUP);
    }

    void loop() {
      static unsigned long lastOpen;
      if (digitalRead(BUTTON) == PRESSED) {
        if (millis() - lastOpen > DELAY)
          btnState = HIGH;
        else btnState = LOW;
      } else {
          lastOpen = millis(); // to remember last moment button was released
          btnState = LOW;
      }

      bool ldrDark = analogRead(A0) < MIN_LDRBRIGHT;

      digitalWrite(LED, ldrDark && btnState);
    }


message:
MQTT on nano with Ethernet shield not working

I'm using an arduino nano with an [ethernet shield][1] (ENC28J60), and  ethernet eem to be working (I can create a webserver with **Ethercard** library).However, i'm stuck when i try to connect to a MQTT server.

I tried **NanodeMQTT** (stuck at waitforlink), **Adafruit MQTT Library** + Ethernet.h ( MQTT_connect() : Connection failed, endlessly retrying), **PubSubClient** + Ethernet.h (client.connect return 0) and some others.

At this point i am wondering if i am doing the right configuration each time:

>when asked an ip, i set the static one i want for my arduino : 192.168.1.50
>
>when asked an gwip, i set one of wy internet router : 192.168.1.254
>
>when asked for a server, i set it to my mqtt server ipv4 : 192.168.1.185 (and port is 1883)
>
>when asked for a mac adress, i keep the one in the example, or just write a random one

Do you know what can cause the ethernet.h or mqtt library to fail, but still ethercard is working fine ?

  [1]: https://www.amazon.fr/diymore-Blindage-Ethernet-ENC28J60-Webserver/dp/B01LANEBAA/ref=sr_1_2_sspa

body:
Thanks to Juraj pointing me that UIPEthernet is just a replacement for the Ethernet library, I finnally found [this article][1] Which works just fine.

  [1]: https://www.instructables.com/id/A-Simple-MQTT-PubSub-Node-With-Arduino-UNO-and-ENC/


message:
How to connect Big Dome Button with arduino

I am quite new to arduino and for a project I want to use big dome button which when pressed it will count how many times has been pressed.It is using 12 volts.The button is this https://www.sparkfun.com/products/9181

body:
As others have said, the 12V powers the switch's internal LED.

----
## EDIT:
Switches don't need power. If you skip **all** power to the switch it will still work but it won't light up.
## End of edit:

----

If you want the switch to light up, connect the V in to 12V, or if you connect it to 5V, it will be dim, but -probably- still light. (You are certain to have a 5V pin on your Arduino board. Using that means you don't need a separate 5V supply.)

Now connect one lead of the switch to a digital input, and the other lead to ground.

Then set your switch pin to `INPUT_PULLUP` mode. Now your switch will read HIGH until it's pressed, then it will read LOW.

create a variable at the top of your code called buttonState:

    byte buttonState = HIGH;

Also define an unsigned long variable nextReadMillis:

    unsigned long nextReadMillis = 0;

and a pressCount variable:

    unsigned int pressCount = 0;

And define a debounceTime:

    #define debounceTime 50

In your loop, do something like this:

    void loop() {
        //Get the new millis(value)
        unsigned long newMillis = millis();

        //only look at the new button value if enough time has elapsed.
        if (newMillis >= nextReadMillis) {
           byte newButtonState = digitalRead(buttonPin);

           //Only do something if the button state has changed
           if (buttonState != newButtonState) {
              buttonState = newButtonState;
              nextReadMillis = newMillis + debounceTime;
              //If the button is now in the pressed (LOW) state, increment the count
              if (buttonState == LOW) {
                  pressCount++;
              }
           }
        }
    }

That's pseudo-code. It likely has syntax errors. It's not meant to be copy/pasted. Use it as a guide for your project.

The code using `millis()` is a version of "software debouncing." Electrical switches tend to "jitter" or "bounce" between their on and off states very rapidly when they are first pressed/released. By only checking for state changes after a brief delay, you ignore the jitter in the readings.

Note that if you want your LED to only light when the button is pressed, you could control it with another digital pin. You'd assign a different pin to controlling the LED output, set that pin to OUTPUT mode, and switch the pin based on button state inside the body of the `if (buttonState != newButtonState)` if statement.

If your LED draws ≤20mA at 5V, you could connect it directly to your output pin. If it draws more than that, you will need a transistor to drive it so you don't draw too much current from your output pin and burn it out. Wiring a transistor driver is beyond the scope of this post however.


message:
ESP32 saving data to SD card in .csv doesnt format correctly

i want to save a vector to a .csv file on a SD Card.

I watched [this][1] tutorial on how to do it and it describes it perfectly even though its kinda dated.

My Problem is that everything is saved into the first cell of the .csv file so it gets constantly overwritten.
It should save only the first vector into the first cell, then the second vector into the second cell and so on.
I just get all three vectors with the commas into the first vector like this:

 8, 9, 10

Also the header which should appear at the top is also gone.

I would really appreciate some help. Thanks!

Here is my setup and loop:

```
#include <iostream>
#include <string>
#include <vector>
#include "SD.h"
#include "SPI.h"
#include "EKG_data_transmision.h"

#define CS_Pin 5 // Chip Select Pin

EKG_data_transmision EKG_data_transmision;

std::vector<unsigned short> vector_1 = {1,2,3,4,5,6,7,8,9,10};
std::vector<unsigned short> vector_2 = {2,3,4,5,6,7,8,9,10,11};
std::vector<unsigned short> vector_3 = {3,4,5,6,7,8,9,10,11,12};
unsigned int for_x = 0;

void setup() {
  // open serial
  Serial.begin(9600);
  Serial.print("Init SD Card...");
  pinMode(CS_Pin, OUTPUT);

  if(!SD.begin(CS_Pin))
  {
    Serial.println("Card failed or not present");
    return;
  }

  EKG_data_transmision.vectorData = SD.open("/data.csv", FILE_WRITE);  //erstelle data.csv datei

  if(EKG_data_transmision.vectorData)
  {
    EKG_data_transmision.vectorData.println(", , , ,");
    String header = "ID, Value, Time, Whatever";
    EKG_data_transmision.vectorData.println(header);
    EKG_data_transmision.vectorData.close();
    Serial.println(header);
    Serial.println("card init sucess");
  }
  else
  {
    Serial.println("Couldnt open vector data file");
  }

}

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

  while(for_x <= 8){
    for_x++;
    EKG_data_transmision.write_vector_to_SD(vector_1, vector_2, vector_3);
    delay(1000);
  }

  delay(10000);
}
```
Here is my function that should save everything to the SD Card:

```
bool  EKG_data_transmision::write_vector_to_SD(std::vector<unsigned short> vector_ADC_1, std::vector<unsigned short> vector_ADC_2, std::vector<unsigned short> vector_ADC_3) // Übertrage
{
  dataString = String(vector_loc) + "," + String(vector_ADC_1[vector_loc]) + "," + String(vector_ADC_2[vector_loc]) + "," + String(vector_ADC_3[vector_loc]); // + "\r\n"

  vectorData = SD.open("/data.csv", FILE_WRITE);

  if(vectorData){
    //sd karte immer noch da und schau ob data.csv exisitiert
    vectorData.println(dataString);
    Serial.println("This is vector:");
    Serial.println(vector_loc);
    Serial.println("Im actually writing this:");
    Serial.println(dataString);
    vectorData.close(); // close the file
    }

  else{
    Serial.println("Error writing to file !");
}
  vector_loc++;

  return 0;
}
```

  [1]: https://www.youtube.com/watch?v=5v5A3j7Rrco

body:
In Arduino SD library FILE_WRITE constant instructs the function to open the file for append, but in the esp32 SD library it opens the file for rewrite. Use FILE_APPEND to open the file for append.

    File file = SD.open(path, FILE_APPEND);


message:
config file for Arduino Uno installed on Raspberry PI

The Arduino code shown runs successfully. My problem is configuring the Arduino IDE so it fits within the Raspberry Pi window. The second image, the built-in serial port /dev/ttyAMA0, is produced. It is blank.

   The Arduino Menu bar cannot be accessed. Therefore, the **Tools** button and other buttons for running the code are not available. The user can adjust the width of the Arduino IDE window but cannot move it around the screen or up or down.

   The /boot/config file is setup up for a Adafruit 5" Backback monitor. No other app, Thonny Pi, or the terminal has these problems.

It appears to me that the config file needs some work. That is only a guess.

    Any suggestions will be greatly appreciated.

[![Arduino Window is too big for the Raspberry Pi screen.][1]][1]

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

body:
In Linux you can move things around in different ways. For example:

1. Hold ALT and click and drag anywhere in the window. The whole window will move and you can get to the edge to resize it.
2. Press ALT-Space then M and you can use the cursor keys to move the window around
3. Press ALT-Space then X and it will maximise the window to the screen size


body:
What you can do is set the default IDE window size by editing preferences.txt:

Click the link on the line following File > Preferences > More preferences can be edited directly in the file.

This will open the Arduino15 (or similar folder name) folder.

Close the Arduino IDE.

Open the file preferences.txt in a text editor

Change the editor.window.height.default and editor.window.width.default properties to your desired window size.

Save the file.


message:
How to execute commands over desired amount of time

I have a program that receives 4 commands on 4 channels to change the color of an LED using mqtt communication. Lets just focus on two of the channels, the time and the red.

I am sending a length of time that I would like to complete the color change by, and a new color value.

I have ran my test runs to calculate the amount of time it seems to take to update a single value. I calculate this by setting the intervalRed value to 0.01
with a duty cycle of 1024, commanding the led to go from its starting value to its ending value of fully on, by the interval value would be 10,240 ticks.
when I send that command, take the resulting execution time ( 287ms ) and calculate the time to update a single tick I get a value of 0.028027 ms to complete a single increment.
When I set the hardcoded tickTime to that value: 0.028027
and I send a color change from off to on/vice-versa with a requested completion time of 1000ms, the actual execution time varies.

the larger the requested execution time varies, causes a greater difference between the actual and requested time.

I ran many test trials with a set interval to gain a value for the length of time for a single tick but no matter when value I use, there are still discrepancies. I dont believe using a hardcoded value for the length of time for a single tick is the correct way to assure the color change will occur over a given time.

I am happy to provide the terminal output for any attempts to show the output of values used in my calculations if needed (But I believe I need a difference approach all together)

What is the best way to assure the color change completes in the requested amount of time?
Perhaps some calculation based on the amount of time passed rather then calculating a hardcoded value for the time of a single tick?

        #include <ESP8266WiFi.h>
    #include <PubSubClient.h>

    #define CLIENT_NAME "ESP8266_1" // just a name to identify this client
    WiFiClient wifiClient;
    PubSubClient mqttClient("10.0.0.131", 1883, wifiClient);

    //set rgb led pins
    int pinGreen = 4;
    int pinBlue = 12;
    int pinRed = 14;

    float currentRed = 1024;
    float currentGreen = 1024;
    float currentBlue = 1024;

    int nextRed = -1;
    int nextGreen = -1;
    int nextBlue = -1;

    float intervalRed = -1;
    float intervalGreen = -1;
    float intervalBlue = -1;

    //the float time was calculated by
    //IntervalValue(set to 0.01)/Value Change (1024 when going from on to off) = 10,240 ticks
    //ExecutionTime (beginning time - end time) /# of ticks = 0.0347643
    // I seem to be getting varying execution times so I have tried values between 0.028 and 0.04
    float tickTime = 0.028027;
    int executionTime = 1;
    int showTime = 1;
    int beginningReceivedData;

    void setup()
    {
      Serial.begin(9600);
      //set rgb led pins to output

      pinMode(pinRed, OUTPUT);
      pinMode(pinGreen, OUTPUT);
      pinMode(pinBlue, OUTPUT);
      digitalWrite(pinRed, HIGH);
      digitalWrite(pinGreen, HIGH);
      digitalWrite(pinBlue, HIGH);

      mqttClient.setCallback(callback);
      WiFi.begin("partyHouse", "whatsthepassword");
      connectToWiFiAndBroker();
    }

    void connectToWiFiAndBroker()
    {
      Serial.print("\nConnecting to WIFI");
      while (WiFi.status() != WL_CONNECTED)
      {
        Serial.print(".");
        delay(500);
      }
      Serial.println("Connected to WIFI!");

      Serial.println("Connecting to broker");
      while (!mqttClient.connect(CLIENT_NAME))
      {
        Serial.print(".");
        delay(500);
      }
      Serial.println("Connected to broker!");

      mqttClient.subscribe("InterestingTopics/#");
    }

    void loop()
    {
      if (!mqttClient.connected()) {
        connectToWiFiAndBroker();
      }
      mqttClient.loop();

      updateColors();
    }
    //------------------------------------------------------------------------------------------------------------------------
    //The CallBack for processing incoming data
    //------------------------------------------------------------------------------------------------------------------------
    //the topic is the path based on the subscription
    void callback(char* topic, byte* payload, unsigned int length)
    {
      //for tracking the time it takes to process the data, as well as the time it takes to complete updating the colors over the desired time
      beginningReceivedData = millis();
      char commandValue[length+1];
      for (int i = 0; i < length; i++)
      {
        commandValue[i] = (char)payload[i];
      }
      commandValue[length+1] = '\0';
      if (strcmp(topic, "InterestingTopics/time") == 0) {
        executionTime = atoi(commandValue);
      }
      if (strcmp(topic, "InterestingTopics/red") == 0) {
        showTime = 1;
        nextRed = atoi(commandValue);
        intervalRed = (nextRed - currentRed)/(executionTime/tickTime);
        //manual Interval value used for calculating the tickTime
        if (nextRed < currentRed) {
          intervalRed = -0.1;
        } else {
          intervalRed = 0.1;
        }

        Serial.print("next: ");
        Serial.print(nextRed);
        Serial.print(" Current: ");
        Serial.print(currentRed);
        Serial.print(" Interval: ");
        Serial.println(intervalRed, 10);

        Serial.print("time to process incoming single value (red): ");
        Serial.println(millis() - beginningReceivedData);
      }
      if (strcmp(topic, "InterestingTopics/green") == 0) {
        nextGreen = atoi(commandValue);
        intervalGreen = (nextGreen - currentGreen)/(executionTime/tickTime);
      }
      if (strcmp(topic, "InterestingTopics/blue") == 0) {
        nextBlue = atoi(commandValue);
        intervalBlue = (nextBlue - currentBlue)/(executionTime/tickTime);
      }
    }

    void updateColors() {
      //------------------------------------------------------------------------------------------------------------------------
      //Updating the Red
      //------------------------------------------------------------------------------------------------------------------------
      if (currentRed != nextRed && nextRed > -1) {
        currentRed = currentRed + intervalRed;
        //if value decreasing and it passes the next value, set values equal to prevent passing
        if (intervalRed < 0 && currentRed < nextRed) {
          currentRed = nextRed;
        }
        if (intervalRed > 0 && currentRed > nextRed) {
          currentRed = nextRed;
        }
        analogWrite(pinRed, (int)currentRed);
        //this else exists just to print the different in time from receiving the value to the time it took to update
      } else if (currentRed == nextRed && nextRed > -1 && showTime == 1) {
        //showTime set to zero to only print the time once
        showTime = 0;
        Serial.print("full color change has completed taking this much time: ");
        Serial.println(millis() - beginningReceivedData);
      }
      //------------------------------------------------------------------------------------------------------------------------
      if (currentGreen != nextGreen && nextGreen > -1) {
        currentGreen = currentGreen + intervalGreen;
        //if value decreasing and it passes the next value, set values equal to prevent passing
        if (intervalGreen < 0 && currentGreen < nextGreen) {
          currentGreen = nextGreen;
        }
        if (intervalGreen > 0 && currentGreen > nextGreen) {
          currentGreen = nextGreen;
        }
        analogWrite(pinGreen, (int)currentGreen);
      }
      if (currentBlue != nextBlue  && nextBlue > -1) {
        currentBlue = currentBlue + intervalBlue;
        //if value decreasing and it passes the next value, set values equal to prevent passing
        if (intervalBlue < 0 && currentBlue < nextBlue) {
          currentBlue = nextBlue;
        }
        if (intervalBlue > 0 && currentBlue > nextBlue) {
          currentBlue = nextBlue;
        }
        analogWrite(pinBlue, (int)currentBlue);
      }
    }

body:
Don't assume an update takes a fixed time and blast constant changes. Write code that calculates change/millisecond. Then record the starting millis() value when you begin a sequence, and each time through your loop, calculate `float(millis()-startTime)/sequenceTime`. That will give you the % of color change to apply now. Then use that percentage to calculate the interpolated color value.

That will give you an adaptive system that will set the color value to the approximate desired color for the current stage in your animation, regardless of how long each iteration the loop takes. If the loop lags for some reason, you will get more coarse changes between color values, but it will still track your desired pacing.


message:
How to program Arduino LCD shield with Python?

so I want to run a Arduino LCD shield with Python code..But after having some research on the Internet, I can not found any tutorial, some just give some basic code with LED.

And one things that how can I add a LCD library (LyquidCrystal.h in Arduino code) if i program in Python.

Thank you guys very much.

body:
It's like @chrisl wrote in the comments. You cannot program Arduino with python.

You can however upload an open source [Firmata][1] protocol implementation onto the Arduino and then write python code on your PC that will send commands to the Arduino by USB cable to tell it what to do.

This way you actually execute your code on PC, but control Arduino pins. Only drawback is that you need to have a PC connected to the Arduino at all times. This is not very practical.

There is a really nice tutorial [here][2]

Example python code looks like this:

    import pyfirmata
    import time

    board = pyfirmata.Arduino('/dev/ttyACM0')
    while True:
        board.digital[13].write(1)
        time.sleep(1)
        board.digital[13].write(0)
        time.sleep(1)

I'm afraid that only solution to controlling LCD shield this way without writing any C is to write the entire LCD library in python basing on pyfirmata calls to control the Arduino pins. It's not as hard as it sounds, and even a beginner could easily succeed.

  [1]: https://github.com/firmata/protocol
  [2]: https://realpython.com/arduino-python/


message:
LCD Blinking after inserting code : A medication reminder system using Arduino Uno

RTC DS3231,Arduino Uno and 4 push buttons, 10K potentiometer, 4 of 10K resistor and a buzzer. I decided to follow from an online source and encounters a few problems which already fixed but this one puzzles me. Would really appreciate your help. The RTClib.h library is already installed.LCD Blinking after inserting code and it shows blocks instead of characters.

There's other picture in this link too.

https://drive.google.com/open?id=1OzHqZlS7mnkngMx-EIiqIgzdHZaTsHr8

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

    #include <LiquidCrystal.h>
    #include <Wire.h>
    #include <RTClib.h>
    #include <EEPROM.h>

    RTC_DS3231 rtc;

    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;                 // lcd pins
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    int buzz = 13;
    int addr=17;

    const int buttonPin2 = 9;
    const int buttonPin3 = 8;
    const int buttonPin1 = A0;
    const int buttonPin4 = 7; // the pin that the pushbutton is attached to
    int val2 = 0;
    int val3=0;
    int pushVal;
    int bS1 = 0;         // current state of the button
    int lBS1 = 0;     // previous state of the button

    int bS2 = 0;         // current state of the button
    int lBS2 = 0;

    int bS3 = 0;         // current state of the button
    int lBS3 = 0;

    int bS4 = 0;         // current state of the button
    int lBS4 = 0;

    // configure the pins to the right mode
    int buzz8amHH = 8;          //    HH - hours         ##Set these for reminder time in 24hr Format
    int buzz8amMM = 00;          //    MM - Minute
    int buzz8amSS = 00;          //    SS - Seconds

    int buzz2pmHH = 8;          //    HH - hours
    int buzz2pmMM = 1;          //    MM - Minute
    int buzz2pmSS = 00;          //    SS - Seconds

    int buzz8pmHH = 8;          //    HH - hours
    int buzz8pmMM = 2;          //    MM - Minute
    int buzz8pmSS = 00;          //    SS - Seconds

    int nowHr, nowMin, nowSec;

    void gwsMessege(){               // print get well soon messege
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Stay Healthy :)");     // Give some cheers
        lcd.setCursor(0, 1);
        lcd.print("Get Well Soon :)");// wish
    }

    void helpScreen() {              // function to display 1st screen in LCD
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Press Buttons");
        lcd.setCursor(0, 1);
        lcd.print("for Reminder...!");
     }

    void timeScreen() {              // function to display Date and time in LCD screen
      DateTime now = rtc.now();             // take rtc time and print in display
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Time:");
        lcd.setCursor(6, 0);
        lcd.print(nowHr = now.hour(), DEC);
        lcd.print(":");
        lcd.print(nowMin = now.minute(), DEC);
        lcd.print(":");
        lcd.print(nowSec = now.second(), DEC);
        lcd.setCursor(0, 1);
        lcd.print("Date: ");
        lcd.print(now.day(), DEC);
        lcd.print("/");
        lcd.print(now.month(), DEC);
        lcd.print("/");
        lcd.print(now.year(), DEC);
        delay(500);
    }

    void setup()
    {
    Wire.begin();
      rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));            // uncomment this to set the current time and then comment in next upload when u set the time
      //rtc.adjust(DateTime(2019, 1, 10, 7, 59, 30));                // manual time set

      lcd.begin(16, 2);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Welcome To Our");                                      // print a messege at startup
      lcd.setCursor(0, 1);
      lcd.print("Medicine Reminder");
      delay(1000);
      gwsMessege();
      delay(3000);
      helpScreen();
      delay(2000);
      timeScreen();
      delay(3000);
      lcd.clear();

      pinMode(buttonPin1, INPUT);
      pinMode(buttonPin2, INPUT);
      pinMode(buttonPin3, INPUT);
      pinMode(buttonPin4, INPUT);
      pinMode(buzz, OUTPUT);
      Serial.begin(9600);
    }

    void ValSet(){
      Serial.println(EEPROM.read(addr));
      val2 = EEPROM.read(addr);                         // read previosuly saved value of push button to start from where it was left previously
      switch (val2) {
        case 1:
          lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Reminder set ");
        lcd.setCursor(0, 1);
        lcd.print("for Once/day !");
          pushVal = 1;
          delay(500);
          break;
        case 2:
          lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Reminder set ");
        lcd.setCursor(0, 1);
        lcd.print("for Twice/day !");
          pushVal = 2;
          delay(500);
          break;
        case 3:
          lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Reminder set ");
        lcd.setCursor(0, 1);
        lcd.print("for Thrice/day !");
          pushVal = 3;
          delay(500);
          break;
      }
    }

    // the main loop will constantly check to see if the button has been pressed
    // if it has, a counter is incremented, and then some action can be taken
    void loop()
    {                                         //call to set thrice/day
        if (pushVal == 1) {                                // if push button 1 pressed then remind at 8am
        at8am();                                           //function to start uzzing at 8am
      }
      else if (pushVal == 2) {                             // if push button 2 pressed then remind at 8am and 8pm
        at8am();
        at8pm();                                           //function to start uzzing at 8mm
      }
      else if (pushVal == 3) {                             // if push button 3 pressed then remind at 8am and 8pm
        at8am();
        at2pm();                                            //function to start uzzing at 8mm
        at8pm();
      }
      // read the state of the button
      bS1 = digitalRead(buttonPin1);
      bS2 = digitalRead(buttonPin2);
      bS3 = digitalRead(buttonPin3);
      bS4 = digitalRead(buttonPin4);

      // check to see if it different than the last time we checked

    if (bS2 != lBS2) {
        // either the button was just pressed or just released
        if (bS2 == HIGH) {
          // it was just pressed
          Serial.println("n02");
          EEPROM.write(17,1);
          push1();
          delay(1000);
        }
      }
      lBS2 = bS2;

    if (bS3 != lBS3) {
        // either the button was just pressed or just released
        if (bS3 == HIGH) {
          // it was just pressed
          Serial.println("no3");
          EEPROM.write(17,2);
          push2();
          delay(1000);
        }
      }
      lBS3 = bS3;

    if (bS4 != lBS4) {
        // either the button was just pressed or just released
        if (bS4 == HIGH) {
          // it was just pressed
          Serial.println("no4");
          EEPROM.write(17,3);
          push3();
          delay(1000);
        }
      }
      lBS4 = bS4;

    if (bS1 != lBS1) {
        // either the button was just pressed or just released
        if (bS1 == HIGH) {
          val3=EEPROM.read(addr);
          EEPROM.write(17,0);
          digitalWrite(buzz, LOW);
          pinstop();
          EEPROM.write(17,val3);
        }
      }
      lBS1 = bS1;

      timeScreen();
      ValSet();
    }
    void push1() {                   // function to set reminder once/day                                           //save the state of push button-1
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Reminder set ");
        lcd.setCursor(0, 1);
        lcd.print("for Once/day !");
        delay(1200);
        lcd.clear();
      }

    void push2() {                      //function to set reminder twice/day
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Reminder set ");
        lcd.setCursor(0, 1);
        lcd.print("for Twice/day !");
        delay(1200);
        lcd.clear();
      }

    void push3() {                    //function to set reminder thrice/day
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Reminder set ");
        lcd.setCursor(0, 1);
        lcd.print("for Thrice/day !");
        delay(1200);
        lcd.clear();
      }

    void pinstop(){                   //function to stop buzzing when user pushes stop push button
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Take Medicine  ");
        lcd.setCursor(0, 1);
        lcd.print("with Warm Water");
        delay(5000);
        lcd.clear();
      }
    void at8am() {                      // function to start buzzing at 8am
      DateTime t = rtc.now();
      if (int(t.hour()) == buzz8amHH && int(t.minute()) == buzz8amMM  && (int(t.second()) == buzz8amSS || int(t.second()) < buzz8amSS+10)) {
            /////////////////////////////////////////////////////
            digitalWrite(buzz,HIGH);
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("Time to take ");
            lcd.setCursor(0, 1);
            lcd.print("Morning medicines.");
            delay(5000);

            /////////////////////////////////////////////////////
          }
    }

    void at2pm() {                          // function to start buzzing at 2pm
      DateTime t = rtc.now();
      if (int(t.hour()) == buzz2pmHH && int(t.minute()) == buzz2pmMM  && (int(t.second()) == buzz2pmSS || int(t.second()) < buzz2pmSS+10)) {
            /////////////////////////////////////////////////////
            digitalWrite(buzz,HIGH);
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("Time to take ");
            lcd.setCursor(0, 1);
            lcd.print("Afternoon medicines.");
            delay(5000);

            /////////////////////////////////////////////////////
          }
    }

    void at8pm() {                           // function to start buzzing at 8pm
    DateTime t = rtc.now();
      if (int(t.hour()) == buzz8pmHH && int(t.minute()) == buzz8pmMM  && (int(t.second()) == buzz8pmSS || int(t.second()) < buzz8pmSS+10)) {
            /////////////////////////////////////////////////////
            digitalWrite(buzz,HIGH);
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("Time to take ");
            lcd.setCursor(0, 1);
            lcd.print("Night medicines.");
            delay(5000);

            /////////////////////////////////////////////////////
          }
    }

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

body:
Your wiring image is difficult to see. I recommend checking one by one.

Firstly, you connect Arduino with LCD only, make it work first. And then try the next.

I took at a glance at your code. There are some points you should check or change:

1. DO NOT use delay() function, if you uses delay() function, many pressing events will be missed. You should use timestamps instead. I recommend using [ezButton library][1] to avoid the blocking or implement timestamp by yourself (refer to [BlinkWithoutDelay][2] example).

2. Seemingly, you are using the external pull-up/pull-down for buttons. I recommend using the internal pull-up to reduce the complexity of wiring.

For LCD, please refer to [this tutorial][3]

  [1]: https://github.com/ArduinoGetStarted/button
  [2]: https://arduinogetstarted.com/tutorials/arduino-led-blink-without-delay
  [3]: https://arduinogetstarted.com/tutorials/arduino-lcd


body:
Some troubleshooting ideas:

**1**. does turning the potentiometer change the brightness of the LCD?

A. If not, there is a (1) power problem (2) wiring problem.

**2**. Do you ever get strange characters on the LCD or just the "shows blocks instead of characters"?

A. If you only get the blocks.  THe data is probably not making it to the LCD.  THe LCD will display blocks by default.

   B. If you get strange character data too, then data lines probably are't wired properly.

**3**. Upload a program which only does the following:

A. Initializes the LCD

B. prints one line of output every time in the loop()  This is the easiest way to determine if it is your wiring.  If you don't see anything on the LCD then there is a high probability you have a wiring problem.
This is also very easy to try because you just open up a new sketch, create it and upload it to your device.

**LCD Example**

Try this [official Arduino LCD Example][1] (just make sure your data lines match -- you can change the values in the sample code so they are appropriate for your situation.

If it is a wiring problem I'd start looking at

1.  if you are getting the needed amount of current / voltage to the LCD

2. is each data line connected properly.  Unhook power and use a meter to check continuity from your Arduino to your LCD pins.

  [1]: https://www.arduino.cc/en/Tutorial/HelloWorld?from=Tutorial.LiquidCrystal


message:
How to retrieve a page from a web-server using ESP8266 with the program running on Arduino instead of the ESP module?

I have connected an ESP8266-01 module to an Arduino as in the following schematic with the RX and TX pins changed to pins 8 and 9 instead of 0 and 1:

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

I am using the ESP8266wifi library at the following link:

https://github.com/ekstrand/ESP8266wifi

I have looked at the ESP8266HTTPClient library but that is for the ESP8266 board. <b>I want my code to run on the Arduino Uno and not on the ESP8266!</b> I have written the following code:

    #include <SoftwareSerial.h>
    #include <SerialESP8266wifi.h>

    const String API_PASSWORD = "stn1234";

    #define RX_PIN    8 // RX of Arduino (connected to TX of ESP8266)
    #define TX_PIN    9 // TX of Arduino (connected to RX of ESP8266)
    #define ESP_RESET_PIN  12

    #define SERVER_IP   "192.168.43.234"
    #define SERVER_PORT   "80"
    #define WIFI_SSID    "MyWIFI"
    #define WIFI_PASSWORD   "myWifiPassword"

    uint8_t wifi_started = false;

    const char RST[] PROGMEM = "RST";
    const char IDN[] PROGMEM = "*IDN?";

    #define CHANGE_DELAY   5000

    void initializeWifi();
    void transmitData(String);
    String getResponse();
    void transmitStatus();

    SoftwareSerial swSerial =  SoftwareSerial(RX_PIN, TX_PIN);
    SerialESP8266wifi wifi(swSerial, swSerial, ESP_RESET_PIN, Serial);

    void setup()
    {
     Serial.begin(9600);
     Serial.println("Initializing...");
        initializeWifi();
        Serial.println("Initialization complete");
    }

    void loop()
    {
     transmitStatus();
     Serial.print("Transmission complete, ");
     int s = (CHANGE_DELAY/1000);
     Serial.print(s);
     Serial.println("s until next cycle");
     delay(CHANGE_DELAY);
    }

    void transmitStatus()
    {
     int a = (int)random(100);
     int b = (int)random(100);
     String url = "/LocalWebProject/api/testConnection.php?a=" + String(a) + "&b=" + String(b);

     transmitData(url);
     String response = getResponse();
     Serial.print("Reply received: ");
     Serial.println(response);
    }

    void initializeWifi()
    {
     swSerial.begin(115200);
     Serial.println("Starting Wifi");
     wifi.setTransportToTCP();
     wifi.endSendWithNewline(false);  // Will end all transmissions with a newline and carrage return ie println.. default is true

     wifi_started = wifi.begin();
     if(wifi_started)
     {
      Serial.println("Wifi started, connecting to AP...");
      wifi.connectToAP(WIFI_SSID, WIFI_PASSWORD);
      Serial.println("Connected to AP");
     } else {
      Serial.println("ESP module not working");
     }
    }

    void transmitData(String url)
    {
     Serial.println("Connecting to server...");
     wifi.connectToServer(SERVER_IP, SERVER_PORT);

     String data = String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + wifi.getIP() + "\r\n" +
               "Connection: close\r\n\r\n";

     Serial.println("Connected. Transmitting data...");
     wifi.send(SERVER, data);
    }

    String getResponse()
    {
     while(1)
     {
      Serial.println("Waiting for response...");
      WifiMessage in = wifi.listenForIncomingMessage(6000);
        if(in.hasData)
        {
          if(in.channel == SERVER)
          {
             Serial.print("Reply received from the server: ");
           Serial.println(in.message);
        return in.message;
          }
        }

        delay(1000);
        Serial.print("Retrying, ");
     }
    }

I have an Apache server running on Ubuntu 18.10 with a PHP project running on port 80. The testConnection.php page takes 2 GET parameters (integers) and returns the sum.

Problem:
It says that ESP module is not working. The AP in my case is a local hotspot on my mobile.

I have tried running the given example "SerialESP8266_library_test" and confusingly enough, it prints that it has successfully connected to my AP, but on my phone I do not see it connected. Only 1 device is visible as connected, which is my laptop which is running the Apache server and the web project. Also connectToAP returns 1, and connectToServer returns 0.

What am I doing wrong? I know that the ESP module requires power and the Arduino 3V3 is insufficient but I am just testing the code right now and I will do the required changes later on. Due to this, I am placing my Android phone just beside the ESP module so that it has no problems connecting to it.

Any help would be greatly appreciated! Thanks in advance.

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

body: Finally it is working by setting baud rate to 9600 and shortening the GET URL. Maybe there is a length restriction in the library.


message:
Why NRF24L01+ pipe has 5 byte address

I am studying NRF24L01+ module. I see, that only 6 receivers can be connected with the transmitter, via their unique pipes. What I can’t get is why the pipe id (address) has 5 long bytes.

As to me,1 byte would be much more than enough.
What is the purpose in 5-byte address in 5 bidirectional communications?

body:
5 bytes = more than 1 million million unique addresses, although not all addresses (as the nRF24L01 datasheet points out) are advised, for instance because they mimic the nRF's preamble packet.

**So what is the purpose of addresses?**
The purpose is to ensure that radio transmissions are received at the intended radio module.  Consider a radio network where you have 1 transmitter (TX) and 3 receivers (RXs) within range of one another, all using the same radio frequency (channel).  Now all receivers will detect a message sent by the transmitter, but only act upon it, such as raising an interrupt flag, it if the TX and RX addresses match.  To avoid chaotic communication, failed packets or on-air collisions you need each receiver to have a unique address.  Consider these like a postal address.  You should have an intuition of what would happen to your mail if both you and your neighbor had the exact same address.  Since the 2.4 GHz band can be extremely busy in public places with WiFi and Bluetooth traffic (which as an aside, Bluetooth is based on the nRF protocol), having 40 address bits seems quite sensible, as the probability of matching addresses by chance is almost zero.

**So what are pipes?**
If you read the nRF datasheet, you will see that in TX mode the radio can only send on using one address.  In RX mode, the radio will listen for messages on up to 6 different addresses.  Why 6?  This is likely arbitrary - a balance between register memory allocation, most probable number of nRF modules being used simultaneously and the likelihood of more efficient network topologies (such as star/tree networks) that do not require huge numbers of pipes.  A pipe represents one of these 6 addresses that a radio can receive the message and send and an ACK packet if requested.  That's all.

I hope this answer clears any confusion you had between nRF addresses and pipes.


body:
> I see, that only 6 receivers can be connected with the transmitter,

That depends on how you define "connected".  It is only possible for one transmitter to, at any one time, send data to up to 6 other devices (one per pipe). However, that is something that is very rarely done.

In practice no more than 2 pipes are needed for you to communicate with thousands of devices.

In general:

* Pipe 0 is the pipe you send data on
* Pipe 1 is the pipe you listen for incoming data on

You should always send on pipe 0 because that is the pipe that any ACK messages will be received on (set pipe 0's address to the address you are sending to).

With pipe 1 set to the receive address you are always ready to receive data from elsewhere.

The transmitter doesn't need to know about *every* other device - only the one device it is sending data to at any one moment in time.

You can set up multiple addresses on other pipes if you want to receive data that is being sent *to* different addresses, though there's not many circumstances where you'd want to do that (such as if you want to communicate with different pipe widths to different groups of nodes, effectively bridging between two separate networks).

In summary:

* Pipe 0's address changes all the time depending on who you are *sending* to (assuming you are using Auto ACK)
* Pipe 1's address is static and is *your* address that you will receive on.

To illustrate it more:

* Node A has address "NODEA".
* Node B has address "NODEB".
* Node C has address "NODEC".

----

* Node A has pipe 1 address set to "NODEA".
* Node B has pipe 1 address set to "NODEB".
* Node C has pipe 1 address set to "NODEC".

----

* Node A sets pipe 0 address to "NODEC"
* Node A sends a packet through pipe 0
* Node C receives the packet on pipe 1 since it's addressed to "NODEC"
* Node C responds with an ACK to its own address ("NODEC")
* Node A receives the ACK on pipe 0 since it's address is "NODEC".

----

* Node A sets pipe 0 address to "NODEB"
* Node A sends a packet through pipe 0
* Node B receives the packet on pipe 1 since it's addressed to "NODEB"
* Node B responds with an ACK to its own address ("NODEB")
* Node A receives the ACK on pipe 0 since it's address is "NODEB".

----


message:
need to compare if a byte is less than 80 hex

I am using an infrared sensor called OTI301. In its data sheet it says that in order to obtain object temperature and ambient temperature values I need to extract the binary information from the sensor and use the binary information in given formulas. I have done all that but for some reason I am not getting the right values for the object temperature. The ambient temperature seems to work well but when I put a hot object, more than 320 F, the formula returns a random negative number. Also the the sensor can go up to 780 F so I know the temperature has not been capped. Please see pictures for important data sheet information, or here are the links for the complete data sheets
https://drive.google.com/file/d/1XMRDCNzY3fn0q6lkGejs5D-pqksfRuZ8/view?usp=sharing.
https://drive.google.com/file/d/1mmdkHkNbwC5VgQxGMrq07XolajNvgBkN/view?usp=sharing. Lastly, here is the part of the code where I extract the information and apply formulas.

         void loop()
     {
       if (Wire.read()) // On success, read() will return 1, on fail 0.
       {
         buttonState = digitalRead(button);
         //Serial.println(buttonState);
         Wire.beginTransmission(DEVICE_ADDRESS);
         Wire.write(0x80);  // readout command
         Wire.endTransmission(false);
         Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
         uint8_t data[6];
         for (int i = 0; i < 6; i++) {
             data[i] = Wire.read();
         }

          //Calculate Object Temperature
         if(data[5] < 0x80) {
           TA = (data[3]+ data[4]*256+data[5]*65536)/200;
         }
         else {
           TA = (((data[3]+ data[4]*256+data[5]*65536)) - 16777216) /200;
         }

         //Calculate Ambient Temperature
         if(data[2] < 0x80) {
           TA = (data[0]+ data[1]*256+data[2]*65536)/200;
          }
         else {
           TA = (((data[0]+ data[1]*256+data[2]*65536)) - 16777216) /200;
         }

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

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

body:
You said "I defined TA as a float." That doesn't matter. In C/C++, expressions are only "promoted" to a larger/different data type AFTER they are evaluated. Your calculations are being done using 16-bit ints, which overflow, and **then** cast to a float.

(C/C++ evaluates expressions from the inner-most outward, and if one of the operands to an operator is a larger type, it will "promote" the other operand to the larger type before doing a calculation. It **won't** notice that a calculation will overflow and promote the operands to fix that problem however.)

Try this:

       TA = (data[3]+ data[4]*256+uint64(data[5])*65536)/200;

That version of the code forces data[5] to an unsigned long **before** multiplying it by 65536.

Do the same thing to the value that you multiply by 65536 in all of your expressions and you should avoid overflow.


body:
The rules of integer arithmetics are tricky in C++. There are rules that
give the type of integer literals:

 * `256` and `200` are of type `int`, which is the default type for
   integer literals. On the Nano, this type is 16-bits, and covers the
   range from −32,768 to +32,767.

 * `65536` being too large for the `int` type, it is implicitly
   considered a `long int`. This type is 32-bits on the Nano, and covers
   roughly ±2.15×109.

Then there are rules for the types used in arithmetic operations. No
computation is ever done on a type smaller than `int`: anything smaller
is promoted to `int`. Then, if you combine two operands of different
types, the larger type “wins” and the compiler implicitly converts the
other operand to the larger type. Note that if two types have the same
bit size, the unsigned one is considered “larger”.

Let's go now through your formula, and see the types of the different
terms:

```text
data[3]       = uint8_t
data[4]*256   = uint8_t * int → int
data[5]*65536 = uint8_t * (long int) → long int
```

Now you may see the problem. Your calculation will eventually overflow,
but the overflow is _not_ in `data[5]*65536`, as one may naively expect.
What happens is than when the temperature reaches 163.84 °C (≈ 327 °F),
`data[4]` becomes 128, and `data[4]*256` is 32,768, just too large for
an `int`. The result overflows to −128, hence the negative values you
see.

The simplest solution is to force 256 to be a `long int`, by appending
the `L` suffix to the number. Then the multiplication will be performed
with the `long int` type, and there will be no overflow:

```c++
TA = (data[3] + data[4]*256L + data[5]*65536) / 200;
```

------------------------------------------------------------------------

On a final note, it is worth noting that the numbers 256, 65536 and
16777216 used in the formula are all powers of two. Even powers of 256.
You may notice that, save for the division by 200, what this formula
describes is the coding of an integer as a 24-bit, little-endian, [two's
complement][2c] number. This format (two's complement little-endian) is
exactly what the Arduino uses internally for representing numbers. You
could then avoid all those calculations and get your result by just
telling the compiler that what those memory cells are actually holding
is a 24-bit integer:

```c++
float TA = *(__int24*)&data[3] / 200.0;
```

This works for both positive and negative temperatures, but it has the
drawback of breaking some C++ rules (aliasing rules), and using the
non-standard type `__int24`. A safest way to achieve the same is to
build a 32-bit integer by putting the bits in place using bitwise
operations. But note that then a sign-extension byte is needed to
convert the 24-bit number to 32 bits:

```c++
uint8_t sign_extension = data[5] & 0x80 ? 0xff : 0x00;
int32_t reading = (uint32_t) data[3] <<  0
                | (uint32_t) data[4] <<  8
                | (uint32_t) data[5] << 16
                | (uint32_t) sign_extension << 24;
float TA = reading / 200.0;
```

[2c]: https://en.wikipedia.org/wiki/Two's_complement


message:
Will an Arduino UNO operating at 16mHz communicate with UART / I2C with an STM32 operating at a different frequency?

I plan to connect Arduino UNO via I2C / UART with a controller based on STM32F334K8T6, whose frequency will be about 20mHz or higher.

Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them?

The tire speed will be equal. (UART 115200 Baud / I2C 100kHz)

body:
> Tell me, does the difference in clock frequencies of microcontrollers affect the operation of buses between them?

No it doesn't. Or not much any way. It may affect the *accuracy* of clock generation1, which may have an affect at very high asynchronous baud rates, but other than that, no.

For synchronous communication it's all synchronised to the communication protocol's clock, so processor clocks are irrelevant.

----

1: Baud rates are usually generated as an integer division of the system clock. Different system clocks give different results for baud rate divisor calculations, yielding marginally different baud rates. Different baud rates will have different *error percentages* on different system clocks. At low speeds this has no noticeable affect. At high speeds (millions of bits per second) it can cause errors to creep in.


message:
Understanding analog pins in pinMode

When passing the pin number in pinMode its possible to use A0 - A7, does it apply only to that methode?
How can pinMode expect a number (is it int?) type in case of digital pin another (is it then string?) in case of analog pin?
I want to use that in my class methode, is there a way to use that and have my code more readable or should I use the pin numbers?
P.S. I have tried to read the source code but I don't understand the uin8_t (I know its a byte, but not how it can understand A5 as an int)

Tnx a lot

body:
pinMode is actually declared as `void pinMode(uint8_t, uint8_t);`  in arduino.h

A0 is a defined as a number (somewhere depending on the actual hardware), on an Uno/Nano it translates to 14, and when executing pinMode it translates to the appopriate bit in the correct DDRx register.


message:
4:1: error: expected initializer before 'void'

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

    int button

    void setup()
    {
     pinMode(13, OUTPUT);
     pinMode(12, OUTPUT);
     button 4;
     pinMode(4=INPUT);
    }

    void loop()
    {
      if(digitalRead(4)== LOW);
      {
      digitalWrite (13, HIGH);
      delay (250);
      digitalWrite (13, LOW);
      digitalWrite (12, HIGH);
      delay (250);
      digitalWrite (12, LOW);
      }
     }

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

  [1]: https://i.stack.imgur.com/dWiSg.png
  [2]: https://i.stack.imgur.com/ashwG.png

body:
There's significant syntax errors in your code. I think I've caught them all.

 ``` c
    //int button;

    void setup() {
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      // button 4;
      pinMode(4, INPUT);
    }

    void loop() {
      if (digitalRead(4) == LOW) {
        digitalWrite (13, HIGH);
        delay (250);
        digitalWrite (13, LOW);
        digitalWrite (12, HIGH);
        delay (250);
        digitalWrite (12, LOW);
      }
    }
```


message:
srd-05vdc-sl-c and coil operating time

I'm using Arduino UNO to control an imatic relay board with 16 relays model [srd-05vdc-sl-c][1].
I use all the relays to control some linear actuators and everything is working fine.

My only question is: are the coils used for these relays for **continuous** use? I mean, can I continue to give power to some coils for more than 30 minutes? Or will they be destroyed?
Should I write a specific Arduino routine to power off all the coils when not used, or can I leave them powered for 30 or more minutes?

I checked the relays and they do not overheat.

  [1]: http://www.circuitbasics.com/wp-content/uploads/2015/11/SRD-05VDC-SL-C-Datasheet.pdf

body: You can leave them energized for more than 30 minutes. My 16 year old car with 250,000 km still has the original fuel pump relay. I can't imagine how many hours of continuous use it received over this period of time. The relay in my car is not the same make / model as the relays you are using, so you should check with the manufacture to see if there is a "service lifetime" specification.