body:
So I am running a USB (UART) connection from my Arduino UNO (using the serialtransfer.h library) to my pc (using the pyserial transfer library).
This how the ***INTENDED*** cycle of code goes:
I receive the list_ packet and save it to a list on the Arduino . Then the elements in the list are checked and used to control parameters of motor a using GPIO pins. Finally a return message is sent to acknowledge each transfer.

I was hoping to make the return message from Arduino as sort of a flag ; whether to wait or move onto the next transfer, this is on the python side of things.

***However this is not the case as the sending of packets from Arduino is almost instantaneous even with delay functions and before the Arduino can process the information the transfer is done.***

***1)Why doesn't delay() work ?***

***2) Why isn't code sequential ?***

***This is the Arduino side of things***
```
#include "SerialTransfer.h"

SerialTransfer myTransfer;
int motor1 = 13;
int motor2 = 10;

int obj_cordinates[9];
char reply [16] = {"Packet Recieved"};
void setup()
{
  Serial.begin(115200);
  pinMode(motor1,OUTPUT);
  pinMode(motor2,OUTPUT);

  myTransfer.begin(Serial);
}

void loop()
{
  if(myTransfer.available())
  {
    // use this variable to keep track of how many
    // bytes we've processed from the receive buffer
    uint16_t recSize = 0;
    uint16_t sendSize = 0;

    recSize = myTransfer.rxObj(obj_cordinates, recSize);
    sendSize = myTransfer.txObj(reply, sendSize);

     if( obj_cordinates[4] == 15)
    {
      digitalWrite(motor1, HIGH);
      digitalWrite(motor2, LOW);

      delay(5000);

      digitalWrite(motor1, LOW);
      digitalWrite(motor2, HIGH);
      delay(5000);
    }

    myTransfer.sendData(sendSize);
  }

}
```

***The python side of things***
```
import time
from pySerialTransfer import pySerialTransfer as txfer

def Ser_tran_list (list_):

    try:
        link = txfer.SerialTransfer('COM6')
        link.open()
        time.sleep(2) # allow some time for the Arduino to completely reset

        to_transfer = True
        while to_transfer:
            send_size = 0

            # Send a list

            list_size = link.tx_obj(list_)
            send_size += list_size

            # send a character
            str_ = 'Sending data Packet'
            str_size = link.tx_obj(str_, send_size) - send_size
            send_size += str_size
            link.send(send_size)

            while not link.available():
                if link.status < 0:
                    if link.status == txfer.CRC_ERROR:
                        print('ERROR: CRC_ERROR')
                    elif link.status == txfer.PAYLOAD_ERROR:
                        print('ERROR: PAYLOAD_ERROR')
                    elif link.status == txfer.STOP_BYTE_ERROR:
                        print('ERROR: STOP_BYTE_ERROR')
                    else:
                        print('ERROR: {}'.format(link.status))

            # Parse response string

            rec_str_   = link.rx_obj(obj_type=type(str_),
                                     obj_byte_size=16,
                                     start_pos=0)

            # Display the received data

            print('SENT: {} {}'.format(list_,str_))
            print('Recieved: {}'.format(rec_str_))

            to_transfer = False

```

title: How can I pause serial transfer and then un-pause it?

Answers: 1

body: The `delay()` function uses the milliseconds interrupt. Inside an interrupt handler, all other interrupts are suspended so the `millis()` counter doesn't count and `delay()` never ends. `delayMicroseconds()` will work in the interrupt routine because it just sits in a busy loop. Rewrite the code to eliminate the delay function, you can use millis if you want. This is telling you while in the delay function just about everything stops until it is finished.


body:
I receive the following:

    09:27:10.618 -> 0 0
    09:27:12.589 -> 0 0
    09:27:14.616 -> 0 0
    09:27:16.622 -> 0 0
    09:27:18.576 -> 0 0
    09:27:20.577 -> 0 0
    09:27:22.583 -> 0 0
    09:27:24.606 -> 0 0
    09:27:26.571 -> 0 0
    09:27:28.612 -> 0 0
    09:27:30.585 -> 0 0
    09:27:32.582 -> 0 0
    09:27:34.564 -> 0 0
    09:27:36.563 -> 0 0
    09:27:38.587 -> 0 0

When I use the following codes:
For sending:

    #include <SPI.h>
    #include <SoftwareSerial.h>
    SoftwareSerial Serial1(0, 1);
    char mystr[6] = "Hello"; //String data

    void setup() {
      // Begin the Serial at 9600 Baud
      Serial1.begin(9600);
    }

    void loop() {
      Serial1.write(mystr,6); //Write the serial data
      delay(1000);
    }

For receiving:

        char mystr[10]; //Initialized variable to store recieved data

    void setup() {
      // Begin the Serial at 9600 Baud
      Serial.begin(9600);
    }

    void loop() {
      Serial.readBytes(mystr,6); //Read the serial data and store in var
      Serial.println(mystr); //Print data on Serial Monitor
      delay(1000);
    }

Why don't I get my hello string?
NOTE: When I changed to Serial1 for the receiver code I now receive nothing. Not sure why it doesn't work.

title: receives 0 0 instead of "hello"

Answers: 0


body:
Is it possible to recover an .ino file/sketch in/for Arduino? I really need my file back, but ones i uploaded it to my device it vanished from the sketch folder, nor can I find it in the build folder; however, a ton of TMP files are left. Is it possible to use those to recover my .ino file?
They're named something like filename.ino1238437381212.TMP

title: Recover .ino file from tmp files?

Answers: 1

body: Well, stupidly enough, the missing code was inside of the TMP files... in all of them...


body:
This code works and it can fade three LEDs without any problem, obviously you can even add more of them : )

    // Pins Definition
    const int button1 = 13;
    const int button2 = 12;
    const int button3 = 11;
    const int redled = 2;
    const int greenled = 3;
    const int blueled = 4;

    // Timing States
    unsigned long ElapsedLoopTime;
    unsigned long Now;

    class LED
    {
        // Parameters
        unsigned long ParamStartFeed = 300;
        unsigned long ParamDebounce = 50;
        float ParamMinLux = 25.5;
        float ParamMaxLux = 255.0;
        float ParamFeedRamp;

        // Pins
        int led;
        int buttonpin;

        // Status Variables
        bool INDownFront;
        bool LastINValue;
        bool LedStatus;
        float Lux = 127.0;
        bool Direction = true;
        unsigned long LastPressed;
        bool INStatus;
        bool Pressed;
        float Delta;

      public:

        void Initialize(int pin, int ledpin)
        {
          led = ledpin;
          buttonpin = pin;
          pinMode(led, OUTPUT);
          pinMode(buttonpin, INPUT);
          LastINValue = digitalRead(buttonpin);
          LastPressed = millis();
          ElapsedLoopTime = millis();
        }

        void Execute(float ParamFeedRamp)
        {
          INStatus = digitalRead(buttonpin);

          INDownFront = LastINValue && !INStatus;
          Pressed = ((Now - LastPressed) > ParamStartFeed) && INStatus;

          if (INDownFront && (Now - LastPressed  < ParamStartFeed) && (Now - LastPressed  > ParamDebounce))
          {
            LedStatus = !LedStatus;
          }

          if (!INStatus) LastPressed = Now;
          LastINValue = INStatus;

          if (Pressed && LedStatus)
          {
            Delta = (ParamMaxLux - ParamMinLux) * ElapsedLoopTime / ParamFeedRamp;

            if (Direction)
            {
              Lux += Delta;
            }
            else
            {
              Lux -= Delta;
            }

            if  (Lux > 255) {
              Lux = 255;
              Direction = false;
            }
            if  (Lux < 25) {
              Lux = 25;
              Direction = true;
            }

          }
          analogWrite(led, Lux * LedStatus);
        }
    };

    LED ledblue;
    LED ledgreen;
    LED ledred;

    void setup()
    {
      Serial.begin(115200);
      ledred.Initialize(button3, redled);
      ledgreen.Initialize(button2, greenled);
      ledblue.Initialize(button1, blueled);
    }

    void loop()
    {
      Now = millis();
      ledred.Execute(3000); // 3000ms
      ledgreen.Execute(3000); // 3000ms
      ledblue.Execute(3000); // 3000ms
      ElapsedLoopTime = millis() - Now;
    }

title: Fader OOP Problem

Answers: 1

body:
I don't really know about the

    // Pins
    byte led;
    byte buttonpin;

but maybe you can try

    // Pins
    int led;
    int buttonpin;


body:
I am making a line follower car that follows the line when push button is pressed. And by using ultrasonic sensor I want the car to stop when object ahead distance is closer than 100 and then make servo motor turn to 180 degrees.

Used:

* Arduino UNO
* 2 DC motor
* cytron maker line sensor
* 1 servo motor
* 1 ultrasonic sensor
* 1 push button.

Got stuck coding, I would like some help please.

```c++
int E1 = 4;
int M1 = 5; // Right
int M2 = 6; // Left
int E2 = 7;
int trigPin = 4;
int echoPin = 5;

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

  pinMode(E1, OUTPUT);
  pinMode(M1, OUTPUT);
  pinMode(E2, OUTPUT);
  pinMode(M2, OUTPUT);

  digitalWrite(E1, HIGH);
  digitalWrite(E2, HIGH);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  float duration, distance;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = ((float)(340 * duration) / 1000) / 2;

  Serial.print("\nDIstance:");
  Serial.print(distance);
  Serial.println("mm\n");
  delay(200);

  int D1 = digitalRead(8);
  int D2 = digitalRead(9);
  int D3 = digitalRead(10);
  int D4 = digitalRead(11);
  int D5 = digitalRead(12);

  if (D1 == 0 && D2 == 0 && D3 == 1 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 1 && D3 == 1 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 80);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 1 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 60);
    analogWrite(M2, 100);
  }
  else if (D1 == 1 && D2 == 1 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 30);
    analogWrite(M2, 100);
  }
  else if (D1 == 1 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 0);
    analogWrite(M2, 100);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 1 && D4 == 1 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 80);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 1 && D5 == 0) {
    analogWrite(M1, 100);
    analogWrite(M2, 60);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 1 && D5 == 1) {
    analogWrite(M1, 100);
    analogWrite(M2, 30);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 1) {
    analogWrite(M1, 100);
    analogWrite(M2, 0);
  }
  else if (D1 == 0 && D2 == 0 && D3 == 0 && D4 == 0 && D5 == 0) {
    analogWrite(M1, 0);
    analogWrite(M2, 0);
  }
  else if (D1 == 1 && D2 == 1 && D3 == 1 && D4 == 1 && D5 == 1) {
    analogWrite(M1, 00);
    analogWrite(M2, 00);
  }
  else {
  }
}
```

title: Arduino (line follower + ultrasonic sensor + servomotor)

Answers: 1

body:
```c++
int M1 = 5; // Right
...
int echoPin = 5;
```

You appear to be trying to use one of your motors on the same pin as your return signal from the ultrasonic range finder.  When `analogWrite(M1, whatever)`, the internals of `analogWrite` will [set the pin to output][1], overriding your own `pinMode(echoPin, INPUT)` in `setup()`.

Later when you `pulseIn(echoPin, HIGH)`, you're just seeing whatever `analogWrite` is doing with it.  If you're not touching any buttons, your code is executing `analogWrite(M1, 0);`, so no "distance".

For more fun:  If all of this is correct, if you hold down the buttons to execute `analogWrite(M1, 100)`, `pulseIn` should report a value of about (1.0/980) * 100/256 or 399.  The 980 being the frequency pin 5 uses on the UNO for [analogWrite][2].  This should cause your code to print something around 66.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/wiring_analog.c#L111
  [2]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


body:
I am using a micro sd card shield with an arduino zero, and I am not sure I am using a proper circuit with it. This is the circuit I am using right now:

[![sd card circuit schematic][1]][1]
That is all it is there, just a capacitor for the power and a pullup resistor for the chipselect. The tags just go to the processor.

I have seen a lot of schematics out there with resistors in series to the processor, some times with pull up resistors, some times with pulldown resistors...

I'm not sure the pullup resistor I am using is a good idea, and I am unsure about the value.

To me something like this makes more sense:

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

Can someone teach me a proper circuit for this? what is best and why?

Right now I am not very happy with the performance of the micro SD card socket. That's why I want to improve it.

  [1]: https://i.stack.imgur.com/mRfRK.jpg
  [2]: https://i.stack.imgur.com/DVoKp.png

EDIT: Turns out I didnt really understand very well the second schematic, it was just voltage dividers to lower the 5v os arduino uno to 3V. But what about the pullup resistor of the MISO?

title: Proper Micro SD card schematic

Answers: 3

body:
As per the SD card specification:

> When an SD card is operating in SPI mode or 1-bit SD mode, the CMD and DATA (DAT0 - DAT3) lines of the SD bus must be pulled up by 10 kOhm resistors. Slaves should also have pull-ups on all above-mentioned lines (regardless of whether these lines are connected to the host) in order to prevent SD cards from entering a wrong state.

Basically you need to ensure that "everything is off" until the Arduino actively drives the SD card. Without them the SD card's inputs will be floating and doing anything they like until the Arduino starts communicating.

Resistors in-line with the signals are there really just to increase the impedance and prevent damage when hot-swapping a card.

If you have a 5V Arduino you will require logic level translation. This is a *separate* thing to the resistors. While resistors are OK for UART or simple IO logic level translation they are *not* suitable for use with an SD card. This is because the clock frequencies involved are too high and the resistors will corrupt the signal (through low pass filtering). Instead you require an active logic level translation system, such as a dual voltage, or TTL input, buffer, or active MOSFET level shifters.

body:
There's an excellent tutorial on Instructables I recommend one to read.
here's the link
https://www.instructables.com/Select-SD-Interface-for-ESP32/

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

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

body:
There are a couple of "do and don't" when designing an SPI interface.

**Do add pull-up resistors on SS or set SS HIGH for multiple-slave system**

SPI is a bus system, means that your device might not be the only one using the interface. When designing an SPI interface, you therefore has to consider the scenario where multiple SPI devices are used, and especially when some of the slaves are not coded by your system.

Without a pullup resistor, the SS line might be neither LOW nor HIGH, this might caused some of the devices on the bus to “hear” the communication on its MISO that was not intend for the device. This might explained why some of the Arduino shields or breakout boards with SPI works when used alone, but fail when used together with other SPI boards, causing by some of those boards lack of pullup resistor or the user didn't pull the SS lines in the system HIGH at the `setup()` before calling the `SPI.begin()`!

**Do ensure MISO can be tri-state in multiple-slave system**

Most SPI chips will be at tri-state on their MISO pin (but there are some chips out there requires extra external tri-state buffer chip) when their chip select signal is HIGH. Tri-stage means that it is neither HIGH nor LOW (i.e. floated) and effectively disconnect. However, A SPI device without tri-state MISO could caused potential problem on a SPI bus where multiple SPI devices are connected. If the MISO is unable to be at tri-state, it will be either HIGH or LOW, this will affect other devices connected on the same bus in receiving data.

With this in mind, it is not a good idea to add a pull-up resistor on MISO line.


body:
Been trying to figure this out for a couple hours, despite how ridiculously simple it should be. I have no idea why it's always returning 1, even when i'm pushing the button. Fritzing sketch:
[![enter image description here][1]][1]

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

My code:

    #include <Servo.h>
    #define button 3

    Servo myservo1;
    Servo myservo2;
    Servo myservo3;

    char incomingByte = "";
    int timer;
    int timer2;
    int interval;
    int numservo = 3;
    int press1 = 90;
    int letup = 0;
    int val = 0;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      myservo1.attach(9);
      myservo1.write(0);
      myservo2.attach(7);
      myservo2.write(0);
      myservo3.attach(5);
      myservo3.write(0);
      pinMode(button, INPUT_PULLUP);

    }

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

      val = digitalRead(button);
      Serial.println(val);

      //checkerthing();

        while (Serial.available() > 0) {
          incomingByte = Serial.read();
          timer  = incomingByte - '0';
          Serial.println(timer);
          timer2 = timer * 60;
          interval = timer2/numservo;

         motor1_control(press1, letup, interval);
         checkerthing();
         motor2control(press1, letup, interval);
         checkerthing();
         motor3control(press1, letup, interval);
         checkerthing();

         timer = 0;
         timer2 = 0;
         interval = 0;
        }

      }

    void checkerthing() {
      val = digitalRead(button);
      if (val == LOW){
        Serial.println("Stopped");
        timer = 0;
        timer2 = 0;
        interval = 0;

      }
      if (val == HIGH){
        Serial.println("Still going");
      }

    }
    void motor1_control(int angle, int originalangle, int lengthoftime){
        myservo1.write(angle);
        delay(1000);
        myservo1.write(originalangle);
        delay(lengthoftime * 1000);

    }

    void motor2control(int angle, int originalangle, int lengthoftime){
        myservo1.write(angle);
        delay(1000);
        myservo1.write(originalangle);
        delay(lengthoftime * 1000);

    }

    void motor3control(int angle, int originalangle, int lengthoftime){
        myservo1.write(angle);
        delay(1000);
        myservo1.write(originalangle);
        delay(lengthoftime * 1000);

    }

Basically, the point of this is to have the servo motors go off at specific intervals as given by the user in the serial monitor. The button exists so that the user can restart the timer at any point in the code. But the problem is, I can't even get it to register the button being pushed. It always returns "HIGH", which leads me to believe there's something wrong with the circuits. I've tried using some different methods, but no luck. Can anyone tell me what the issue here is?

Edit: ...I hadn't pushed the pushbutton all the way into the breadboard. I'm gonna go cry in the corner for a bit. And then get back to coding I guess lol. Thanks for the answers.

title: Anyone know why my pushbutton is always returning HIGH?

Answers: 1

body: Hadn't pushed the button all the way in lol


body:
The following code, debugs SerialUSB Native Port, *plugged* to a PC, and *connected* through a Terminal Monitor (such as *Termite*, with any bps, 8N1, RTS/CTS).

At start, the ports seeks for communication, and you see fast blinks.

If **`SerialUSB`**, **Plugged** and **Connected**, communication happens, a.k.a. slow blinks.

But if USB is **Unplugged** after **`SerialUSB`**, even if you **Disconnect** it before, the code turn into an **`Halt`** state, a.k.a. no blinks.

If you **Plug** back the USB, it returns to **`!SerialUSB`**, so if you **Disconnect** (if it were connected) and **Connect** back the terminal, it recovers the **`SerialUSB`** state, not without a `reset()` line to react.
Seems the same happens for `Serial`.

**Any clue about why the Arduino goes into that `Halt` state after a USB disconnect?**

**How should we deal with that? How one should prevent this state?**

Most people asserts this is a power source problem. This happens *with* and *without* the 5V Barrel Power Source.

    // ARDUINO DUE BLINK LED
    void setup(){
      pinMode(13,OUTPUT);
      Serial.begin(115200);
      SerialUSB.begin(115200);
      while(!Serial){
        digitalWrite(13,HIGH);delay(500);
        digitalWrite(13,LOW);delay(500);
      }
      Serial.println("System Reset");
    }
    void loop(){
      int n=0;
      while(!SerialUSB){
        Serial.println("USB Unplugged or Terminal Disconnected");
        digitalWrite(13,HIGH);delay(50);
        digitalWrite(13,LOW);delay(450);
        n=n+1;
        if (n>=5){
          Serial.println("Resetting to Connect if Disconnected");
          digitalWrite(13,HIGH);delay(450);
          digitalWrite(13,LOW);delay(50);
          rstc_start_software_reset(RSTC);
        }
      }
      SerialUSB.println("USB Plugged and Terminal Connected");
      Serial.println("USB Plugged and Terminal Connected");
      digitalWrite(13,HIGH);delay(50);
      digitalWrite(13,LOW);delay(50);
    }

title: Dealing with USB Unplugging?

Answers: 1

body: This is not possible to do because the protocol CDC/ACM don't send that type of information so you can't detect if the Arduino is connected or not, that's why it halts. (You could make a keep-alive function but I don't know if this is possible with what you're doing)


body:
On many tutorials I have looked at, they say that you should power your Arduino with a 5 - 12V external power supply, but on the Arduino, there is a voltage regulator. Is there anything wrong with powering your Arduino with power outside this range?
Solved

title: Higher than 12V Arduino Uno

Answers: 2

body:
Let me just give you an example of what happens even with 12V: One time I was working on a claw machine that I made for the Arduino and when I plugged in 12V while the 5V USB port plugged into the computer, guess what happened. Well, I'll tell you: the Arduino burned up and it was broken. I couldn't even put in the code because it was so cooked. I don't think it turned on either. You see, 7-12V is just a range. You typically want to use what is in between the voltage rating. Even with 12V, you have to be careful. So, hopefully that clarifies. Basically, it will burn up your Arduino into hot plastic, sort of like a hot glue gun. The datasheets agree if you don't believe us. You can try it, but just be aware that I warned you not to. [This is the datasheet for the Mega 2560 rev3][1] It's all because of voltage, which is a sort of pressure for electricity. You could say the same for the water specifications. What happens when you add too much pressure to a water container? It bursts, right? In a way, this can be applied to the Arduino. Thanks for reading, hopefully this helped.

  [1]: https://www.robotshop.com/media/files/pdf/arduinomega2560datasheet.pdf

body:
You could use a step-down converter to lower the voltage and also stabilize it to 12V or even lower and you wouldn't have any problem even if you power supply isn't really stable and outputs higher voltage.

(Instead of buying one you can even build it, it isn't really hard to make one)


body:
I have an AA battery holder for 9V. Two wires come out of it, one for positive and another for negative. How can I wire it up to my Arduino Uno? It kind of looks like this.[![][1]][1]

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

title: Using External Power Supply Arduino Uno

Answers: 1

body:
I would suggest a barrel jack, you know, ones on eBay. For instance, those 2.1 x 5.5mm barrel jack connectors. Just solder the positive and negative wires respectively with barrel jack. Here is a link: [eBay Barrel Jack][1]
Make sure the red or the positive goes with the red on the Barrel Jack and that the black or negative goes with the black of the Barrel Jack. Like in the image.[![This is what I mean by soldering the wires to the barrel jack.][2]][2]

  [1]: https://www.ebay.com/itm/253803093868?_trkparms=ispr=1&hash=item3b17d7df6c:g:pYMAAOSwGHxcz6-n&amdata=enc:AQAGAAACkPYe5NmHp%2B2JMhMi7yxGiTJkPrKr5t53CooMSQt2orsSg3Ye8yTWgOW7pmE1t838dpT7AD8sxbO0VOebe4CPmrZXmmDuPDQbE9XxV%2FUmz3za4AS5ntxim9hOFB2pETiXAThNaYYqnoMlalCssp2ACiM7XXERF9akKV%2F6Tq2qJdFDgLxur%2Fv4t%2Ba2pGI%2FHzRP3shGkNm2lN3jrtycgpR94QtVVMJ%2FHu1oKp8m3LtYYIzEqHmQjISkX%2BFgJ0exzhcoXEha0jgcKAiXNUfUQM0cIZBuihJCKqEQCvTvzCrjt2wQa7tlmU4AGgzYCq95nTn%2FS10%2Bf3hAqkeCqpd6TGCagQOkLqjRBHER6iU6mJAaKEqXUEtN4b3iEiVz9OfmhlpfPB%2F52U2rAxQliOYKxIPh9S8hZJtnKbLt%2FiuGHcCG%2B%2Fx3pgY9uZs6zVqsRoz%2BIhI0l9nqU2HpOuXUZ2HLcnwxoO%2FCuHq%2FeqGcIL3uSQ4D7PpAXEdBafbEDWeTMGTNWNDbTKVUtgueh4hjHHl2Lpcku879o2oC5wwIi%2FftrAGgdKHl5Yk9wK%2FqYU2eCbEAIZKKctbUln%2BE2GDw2ogZYLEuCTzoX1QLTY9LRWO04jLjv00wfzPjjiwwAXflc94l0TBQfLwL69V1kyAUJIzdu8YUC2QnCxGH1SAxG2mP6XIQk4aMYKQKgABjWJ0OCMEzQVt%2FQd7eTvMa7sDHt%2BKDKWeut9r6ZlVwkYGzOSONjk%2FAwalDqo2m4saH2cXBV4rRSQ%2FSpyLlzPeL11fvw72KSWqPFJOofdpmBz6uquwAuO0Sshh8YZgKSIuG9S17tD83X7exn80usxYzywvpuIWwCwdN8%2FfzY%2FvYwDEvRwQyy2iuIFLF|cksum:2538030938687aaa9e7bf0fe4519aef2c1b3df89dd93|ampid:PL_CLK|clp:2334524
  [2]: https://i.stack.imgur.com/i764b.jpg


body:
It seems, due *SAM-BA* (*SAM Boot Assistant*) inside ATSAM3X8E being listening to both *Native USB* and *UART USB* ports after a Reset for programming, allowing talking with *SAM-BA*, this time from your PC, through *BOSSA* (*bossac.exe*, *Basic Open Source Sam boot Assistant*), then it would make **not possible to program an Arduino Due while having both USB port connected** to a PC.

Can somebody confirm, this is the reason?

title: Can Arduino Due be programmed with both USB ports connected?

Answers: 1

body:
It should be possible to do because when you flash the microcontroller needs to be in the flashing mode that only works with the Native port, to enable that mode you have to press the erase button for around 2 seconds and then press Reset...

I made a guide on how to do this [here][1]

  [1]: https://github.com/alessandromrc/Atmel-Studio-with-Arduino-Due-board


body:
I have posted this in a few places, so sorry if you have seen it somewhere else

Im working on a battery powered led strip project,

iv put the project together and have been testing with a mains power supply

Iv run some tests and found at max I'd be pulling 4.5 amps

Averaging around 2 ish

I rounded out to about 3.5 amps, and said for 90 mins run time id be looking at the 7ah battery

7/2 = 3.5 so 2 hours runtime

I got a 7ah SLA 12v battery, running though a 12v to 5v converter to power the led strips

(Arduino is running off a usb battery pack)

However after about 45 mins I tested the battery and it said 10.9 v

Which I understand to be too low for SLA batteries (11 should be the minimum?)
 so I shut it off

My question is did I mess up somewhere and get my math wrong?

Many thanks in advance

title: Battery for WS2812 Strip? (Something's not right)

Answers: 1

body:
There are a few things that may contribute to your lower than expected battery lifetime.

**Effective capacity**: you should aim to never use more than 50% of the capacity of a lead acid battery or you will shorten its lifespan considerably.

Also, note that lead acid battery capacity is usually given for a discharge time of 20 hours (C20 rating). The “C” rating could be different but its value should be on the label of the battery.

In the case of a stated capacity of 7Ah at C20, this means the capacity has been calculated at a discharge rate of 7Ah/20h = 350mA. For higher discharge rates, such as in your application, the effective capacity will be much lower.

**Battery voltage**: measuring battery voltage under load does not say much. Measure the battery voltage “at rest”, when completely disconnected from the load for about 1 hour.

**Charging**: Are you charging the battery with a proper charger?


body:
I was wondering if it is possible to create diffrent voltages by just pulsing power into a capacitor,

Im using an esp32 which can only output 3v or nothing on its GPIO pins, and i need to make it possible for it to adjust the amount of voltage without anyone touching the device, so i thought maybe you could pulse 3v into a capacitor and the capacitor would only unload what ever the pulses would give in voltages combined, so e.g. 50% 3v 50% 0v, then it gives 1.5v, i have no idea how this would work or the physics behind it

all help would be appreciated

title: Pulsing 3v into a capacitor to create custom Voltages

Answers: 1

body:
Yes. That's basically PWM through a Low Pass Filter.

Use PWM to set the "duty cycle", which is the percentage of voltage. Then ise a low-pass filter (an inductor + capacitor, or resistor + capacitor) tuned to filter out the carrier frequency (should be around 500Hz if it's the same as an Arduino) to give you a voltage that is proportional to the duty cycle.

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

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

<!-- End schematic -->

That should filter at about 150Hz. The bigger the capacitor the smoother your output will be, but the slower it will be to respond to changes in the specified voltage.  Note that this is not going to give you large currents, but is fine for using as a reference voltage. To boost the current you can feed it into a *voltage follower*:

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

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

<!-- End schematic -->


body:
I use the RCSwitch library receive signals with a RF receiver. I really need to change the pin the receiver is connected to on my Arduino Uno.

What should I change in my sketch?
What pins can I connect the receiver to?

This is my code:
```
#include <RCSwitch.h>

RCSwitch receiver = RCSwitch();

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

  receiver.enableReceive(0);
  pinMode(1, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  Serial.println("READY");
}

void loop() {
  if (receiver.available()) {

    int value = receiver.getReceivedValue();

    Serial.println(value);

    switch(value) {
      case 1:
        digitalWrite(1, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(10, HIGH);
        break;
      case 2:
        digitalWrite(1, LOW);
        digitalWrite(9, HIGH);
        digitalWrite(10, HIGH);
        break;
      case 3:
        digitalWrite(1, HIGH);
        digitalWrite(9, LOW);
        digitalWrite(10, HIGH);
        break;
      case 4:
        digitalWrite(1, HIGH);
        digitalWrite(9, HIGH);
        digitalWrite(10, LOW);
        break;
    }
  }
}
```

title: Select pin to connect RF receiver

Answers: 1

body:
You can change

    receiver.enableReceive(0);

which uses pin 2, to

    receiver.enableReceive(1);

which is pin 3 on the Uno. These are the numbers of the external interrupt. The Uno only has two of them, which are tied to those two pins. So as long as you are using the Arduino Uno, you need to use one of these. The Arduino Mega for example has more external interrupts.

For reference also look at the [github page of the RCSwitch library][1] and it's [wiki][2], especially the [site about receiving][3], where this is described.

---

Besides that: As you are using Serial, you might want to change

    pinMode(1, OUTPUT);

to a different pin, since pins 0 and 1 are used for the Hardware Serial interface (`Serial`, which is connected to USB). So the usage of that pin collides with the serial communication.

  [1]: https://github.com/sui77/rc-switch
  [2]: https://github.com/sui77/rc-switch/wiki
  [3]: https://github.com/sui77/rc-switch/wiki/HowTo_Receive


body:
I am planning to build a project, but it's something quite embedded and I have no need for the extra features or bootloader of a standard Arduino. At the same time, I think I want to use the ATmega 328P rather than an ATTiny, which is what I'm familiar with for this.

I'm running into confusion with the boot size bits and I'm not too sure about the clock setup bits either (normally I run an ATTiny with internal clock). I'm fairly sure I bought some 16MHz crystals and capacitors for this sort of thing a while back, but I'm also sure there will be times that the internal crystal will be fine.

Does anyone have a favored fuse config for this?

I am using an external programmer over the six-pin SPI/ISP port (well, the pins that would be the equivalent of that) for a "boarduino." I only care about the power filtering and external clock (in cases where I need the latter). I'm not bothering with auto-reset or UART since, again, I'm using a programmer.

I would appreciate both configs for 16 MHz (most Arduino-like, I believe) and internal clock at 8MHz. Thanks!

Edit: Here are my settings so far: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=FF&HIGH=D6&EXTENDED=FF&LOCKBIT=FF. I think that's normal for a "regular" Arduino (minus some stuff I may have messed up in the high fuse) but I'd like to not bother with any bootloader stuff and have my code run right away.

For the internal clock version I have this so far: http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p&LOW=E2&HIGH=D6&EXTENDED=FF&LOCKBIT=FF

title: Help with understanding fuses for an embedded AVR project

Answers: 0


body:
I have been going through a tutorial about this, based on the example code for the "BTLE" Arduino Library.

This is my program:
```
#include <SPI.h>
#include <RF24.h>
#include <BTLE.h>

RF24 radio(9,10);
BTLE btle(&radio);

void setup() {
  Serial.begin(9600);
  while (!Serial) { }
  Serial.println("BTLE advertisement receiver");
  btle.begin("");
}

void loop() {
  if (btle.listen()) {
    Serial.print("Got payload: ");
    for (uint8_t i = 0; i < (btle.buffer.pl_size)-6; i++) {
      Serial.print(char(btle.buffer.payload[i]));
    }
    Serial.println("");
  }
  btle.hopChannel();
}

```
I saw a video of a person running this code, and then sending advertising information via the "nRF Connect" Android app.
In that video (https://www.youtube.com/watch?v=DGgjdBSId4Y) they would receive output in the Serial Monitor very regularly, as I would expect.
When I run my code, and start advertising, then I see the name of my phone only every other minute in the output, and between that time, there is a lot of garbage. I cannot copy the output because of too many special characters.

I would expect the string that I am advertising to show up approximately every 100ms, as that is the rate of the advertisement.

Any idea what I could be doing wrong, or how to debug this better?

title: Using BLE via NRF24L01 to communicate with Android phone

Answers: 0


body: I have a 19.5 V power adapter, can I safely connect it to my Arduino? I don't want to damage it. It is very simple, just lights some LEDs, and I don't want to burn the LEDs either.

title: Can Arduino take 19.5 V

Answers: 2

body: You can do it but you will have nothing left from the regulator for LEDs etc. The best solution is to invest in a buck converter, they are only a few dollars from your favorite china supplier, sometimes even less then a buck. While you are at it purchase two or three you can then use them to generate other voltages as you progress with the Arduino. I use this method a lot, it is a way to use my old laptop power supplies. If you do not have one your next purchase should be a multimeter, even a cheap one is better than none. Then a logic analyzer, again less than $10.00 US. You could also purchase a 8 to 12V wall wart with maybe about 2 amp output and be safe while probably costing less then the buck converter. Have fun!

body:
The Arduino Uno has a maximum voltage range of 6 to 20 v and a recommended range of 7 to 12 v

Using it at 19.5 v may work if the power supply is well regulated but it is uncomfortably close to the limits and dropping nearly 15v across the linear regulator on the Uno may cause it to get fairly hot.


body:
What I'd *like* to do is have some kind of compact (and preferably inexpensive) Arduino-compatible device emulate a USB hub, and simulates plugging in a USB keyboard, pressing a key, then simulates unplugging the keyboard.

The goal here being a USB-connected device with media-control buttons for an Android device, but since plugging in a device that acts as a keyboard disables the on-screen keyboard, the idea is that it only acts like a keyboard when a button is pressed, but keeps a connection going while it's plugged in.

Is this at all possible with any Arduino-compatible device, do I need to look for a different embedded architecture, or do I need a particular kind of USB converter chip?

title: Can at least one Arduino emulate a USB hub?

Answers: 1

body:
Since an Arduino is "just" a microcontroller with some specific bootloader and commonly programmed via the Arduino IDE, you can also program it like any other microcontroller.

There are several projects offering USB functionality as a library, in the Arduino world or outside of it. Use your favorite web search engine to find them. With such a library you should be able to tackle your task.

However, this is not a beginner's task. Please note that you might need to learn a lot.

I'd say that even the simplest AVR based Arduino should suffice.


body:
I was wondering, by the time I press the following key, it does not return to the main_screen() function. How can I fix my code?

    void loop()
      {
        int exit = 0;
        char input = customKeypad.getKey();

        main_screen();
         if (input=='A')
            {
              delay(100);
              lcd.clear();

              do{

               lcd.setCursor(1,0);
               lcd.print("Enter minutes: ");

                 if (input=='B')
                   {
                    break;
                  lcd.clear();
                   }
               }
               while(1);
           }
 }

title: Arduino Keypad: the following key does not respond

Answers: 1

body: You need to read the input again after you get `input == 'A'`.  At the moment, when you enter the `do ... while` loop, the input is always 'A', so `input == 'B'` is never true, and the loop never exits.


body:
I hope you're doing well. I have some questions regarding the PID functions.

Can you please explain to me the following commands? I shall be very thankful to you.

* `PID myPIDX(&InputX, &OutputX, &SetpointX, Kpx, Kix, Kdx, REVERSE);`
What is meant by reverse and why we used & with input, output and setpoint?

* `myPIDX.SetMode(AUTOMATIC);`
What is meant by automatic/manual?

* `myPIDX.SetOutputLimits(80, 110)`
What is meant by the values 80, 110 and what is range 0-255?

* `myPIDX.SetSampleTime(45);`
What is meant by this command? is the time in milli-seconds?

* `myPIDX.Compute();`
How is this function working? I mean what is happening at the back end of the compute function?

Best Regards!

title: Arduino PID Library

Answers: 0


body:
I want to implement a PD controller in Arduino using the PID library. Should I put Ki=0 and the rest of the constants as desired?

```c++
/*
BALL BALANCING USING A PID CONTROL with 6" resistive Touchscreen
*/
//////////////////////////////////////////////////////
///Libraries///
#include <PID_v1.h>
#include <stdint.h>
#include <TouchScreen.h>
#include <Servo.h>

//______________________________________________________________
// Definitions TOUCH PINS
#define YP A1 //brown
#define XM A2 //black
#define YM 7  //yellow
#define XP 6  //red

//______________________________________________________________
// For better pressure precision, we need to know the resistance
// between XP and XM Use any multimeter to read it
// For the 6" its 273 ohms across the X plate
#define Rx 273 //  Resistance in Ohm of Touchscreen measured in X-Direction
TouchScreen ts = TouchScreen(XP, YP, XM, YM, Rx);

// Coordinates Touchscreen
TSPoint p;
double xmin = 146.0;  //154
double xmax = 854.0;   //851
double xLength = 160.0; //Width of Touchscreen in mm at 6.0" 158

double ymin = 63.0;    //63.0
double ymax = 953.0;    //950.0
double yLength = 96.0; //Length of Touchscreen in mm at 6.0" 94

double convertX = xLength / (xmax - xmin);   // converts raw x values to mm. found through manual calibration  0.2295   0.225988
double convertY = yLength / (ymax - ymin);   // converts raw y values to mm. found through manual calibration  0.1082   0.107865

//______________________________________________________________
//Center-Position
double x0=74.35; double y0=42.71; //center  Correct: 0.5//-7     double x0=74.35; double y0=42.71
//______________________________________________________________

int state = 0;

// servos variables
Servo servoX; //X axis
Servo servoY; //Y axis

/////TIME SAMPLE
int Ts = 45;  //Delay between taking samples/measurements

unsigned long Stable=0;
unsigned int noTouchCount = 0; //variable for noTouch
//______________________________________________________________

double Kpx = 0.08;  //Kpx = 0.08; //Proportional (P) Get the ball to set point
double Kix = 0.02;  //Kix = 0.02 0.022 //Integral (I)
double Kdx = 0.035;  //Kdx = 0.035; //Derivative (D)  Stop the ball at set point

double Kpy =0.08;  //Kpy = 0.08
double Kiy =0.02; //Kiy = 0.02 0.022;
double Kdy =0.035;  //Kdy = 0.035;

//______________________________________________________________
//INIT PID
double SetpointX, InputX, OutputX; //for X
double SetpointY, InputY, OutputY; //for Y
PID myPIDX(&InputX, &OutputX, &SetpointX, Kpx, Kix, Kdx, REVERSE);
PID myPIDY(&InputY, &OutputY, &SetpointY, Kpy, Kiy, Kdy, REVERSE);
//______________________________________________________________

void setup(){
servoX.attach(9);
servoY.attach(10);

  OutputX=92;
  OutputY=100;
  servoX.write(OutputX); // Make Plate flat in X-Direction
  servoY.write(OutputY); // Make Plate flat in Y-Direction

  //INIT OF TOUSCHSCREEN
   p = ts.getPoint();

  //INIT SETPOINT, Center of Plate
  SetpointX = 0.0;
  SetpointY = 0.0;

  //Setup PID Controller
  myPIDX.SetMode(AUTOMATIC);
  myPIDX.SetOutputLimits(77, 107); // 83 107
  myPIDY.SetMode(AUTOMATIC);
  myPIDY.SetOutputLimits(85, 115); // -- 81 105

  // TIME SAMPLE
  myPIDX.SetSampleTime(Ts);
  myPIDY.SetSampleTime(Ts);
  delay(100);

  state=0;
  setDesiredPosition();

} // end of setup

void loop()
{
  while(Stable < 15)    //REGULATION LOOP
  {
   p = ts.getPoint();   //measure pressure on plate
   if (p.x > 0 ) //ball is on plate
   {
      servoX.attach(9); servoY.attach(10); //connect servos
      setDesiredPosition();
      noTouchCount = 0;
      p = ts.getPoint(); // measure actual position
      InputX = (p.x - xmin) * convertX;  // read and convert X coordinate
      InputY = (p.y - ymin) * convertY;  // read and convert Y coordinate
      if((InputX == SetpointX && InputY == SetpointY ))

          { Stable = Stable + 1;}

       myPIDX.Compute();  // action control X compute
       myPIDY.Compute();  // action control  Y compute
  }
   else //if there is no ball on plate
  {
    noTouchCount++; //increment no touch count
    if(noTouchCount == 150)
    {
     noTouchCount++;
     OutputX=92; OutputY=100;  //make plate flat
     servoX.write(OutputX); servoY.write(OutputY);
    }
    if(noTouchCount == 300) //if there is no ball on plate longer, detach servos
    { servoX.detach(); servoY.detach(); }
  }
  servoX.write(OutputX); servoY.write(OutputY);  //control

  } // END OF REGULATION LOOP

servoX.detach(); servoY.detach(); //detach servos

///STABILITY////
 while(Stable==15)    //if is stable
 { //still measure actual postiion
    setDesiredPosition();
    p = ts.getPoint();
    InputX = (p.x - xmin) * convertX;  // read and convert X coordinate
    InputY = (p.y - ymin) * convertY; // read and convert Y coordinate
    if(InputX < SetpointX || InputX > SetpointX || InputY > SetpointY || InputY < SetpointY  ) //if ball isnt close to setpoint
    {
      servoX.attach(9); //again attach servos
      servoY.attach(10);
      Stable=0; //change STABLE state
    }

  }//end of STABLE LOOP
}//loop end

//______________________________________________________________
//#### DESIRED POSITION ####
void setDesiredPosition(){
 switch(state){

// Start-Sequence
     case 0:  SetpointX = x0;
              SetpointY = y0;
              p = ts.getPoint();
              if (p.x > 0)
              {
                state = 1;
              } // if ball is on plate
              else if (p.x <= 0)
              {
                state = 0;
                setDesiredPosition();
               } // if no ball is on plate
              break;

// Center-Position
      case 1:  SetpointX = x0;
               SetpointY = y0;
               state = 1;
               break;

    default : state = 0; break;

 }  //end of switch state
}   //end of setDesiredPosition()

//______________________________________________________________
```

title: PID Arduino UNO

Answers: 1

body: Yes, you can use the PID library with `Ki=0;` to get a PD controller.


body:
I am looking to make some wireless motor controllers, and am going to use an Arduino connected to an HC-05 module as a master controller, with a potentiometer as the speed controller input. There will then be another arduino connected to an HC-06 module as a slave, with the arduino outputting to a PWM motor controller.

I am happy with programming of a single arduino with a potentiometer and the PWM motor controller as an all in one device, however what I would like to understand is how the HC-05 and HC-06 devices are spliced into the scheme. I want to be clear that I don't want someone to come up with the sketch for me as I will not learn anything that way!

I have studied lots of online tutorials about using these devices, and unfortunately they all go straight into using it for an LED blink or something like that, and as a result to my 54 year old brain I am unable to deconstruct the sketch sufficiently to understand which bits of the sketch pertain ONLY to the HC06/05 usage.

For me to understand it I am hoping that someone can point me to (or maybe do) a step by step tutorial that takes the process in three steps;

Firstly a sketch that does something (say you press a button and a buzzer sounds, all on one arduino

Secondly, a completely basic sketch that shows the minimum necessary to connect the master and slave without any actions, buttons, LED's buzzers etc.

Lastly, a sketch that combines the two, where the button is on the master, the buzzer is on the slave, and the sketches that show where those spliced in bits of code go.

In that way, I will be able to differentiate in my head which bits belong to which part of the system. I know it is not a conventional way to learn, but for me it will then allow me to attempt to construct the correct master / slave sketches required for my project. I used this method successfully for making sketched for LCD displays so I am hoping it will work again!

Happy to explain more but as I say, I want to learn for myself and would appreciate tutorials an old git can follow!

Cheers

Les

title: Understanding HC-05 and HC-06 usage

Answers: 0


body:
I want to specify a function with parameters for a function parameter, but it doesn't come together.

```
////////////////////////////////////////////////////////////////////////

// Example funch...
void fileLoad(String path, String type) {
  file = SD.open(path.c_str(), FILE_READ);
  server.streamFile(file, type) != file.size();
  file.close();
}

// This is how I want to use it, but it's not possible:
server.on("/homepage", fileLoad("app/homepage.html", "text/html") );

////////////////////////////////////////////////////////////////////////

// Currently, as it works, you need 1 extra funch...:
void homepage() {
  fileLoad("app/homepage.html", "text/html");
}
server.on("/homepage", homepage);

```

title: CPP Function param use function with multi params

Answers: 1

body:
You can find [examples of this sort of thing][1] in the library's examples.

The `on()` function [does support][2] [std::function][3] as a parameter, which in turn, means you can use a C++11-onwards [lambda expression][4] (which [Dave Newton][5] mentioned in comments) to proxy your two-argument function call through a no-argument function:

```c++
server.on("/homepage", [] () {
    fileLoad("app/homepage.html", "text/html");
});
```

The [] ("capture list") is something that would be used if you wanted to copy or refer to things within the scope of the `on` function call.  Since you're not doing that you could also just write a no-argument function which turns around and calls `fileLoad` with your two compile-time-known values.  But it is common for people using this webserver library to need to make references things in scope.

---

As as side note, I'd consider *not* using `String` as your received parameter type in `void fileLoad(String path, String type)`.  When passing in a string literal, you're just causing dynamic allocation for no particularly good reason.

  [1]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/examples/PathArgServer/PathArgServer.ino
  [2]: https://github.com/esp8266/Arduino/blob/2.7.4/libraries/ESP8266WebServer/src/ESP8266WebServer.h#L94
  [3]: https://en.cppreference.com/w/cpp/utility/functional/function
  [4]: https://en.cppreference.com/w/cpp/language/lambda
  [5]: https://arduino.stackexchange.com/users/8583/dave-newton


body:
I have esp8266. Which I am trying to set up to be a self-contained access point and server (tcp).
ESP8266 is connected to ports 2,3 of Arduino Uno. On Arduino, I want to process all information coming into esp8266.
Here is my current connection diagram:

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

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

And a simple code like this:

**ESP8266**

    /* Create a WiFi access point and provide a web server on it. */
    #include<SoftwareSerial.h>
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>

    /* Set these to your desired credentials. */
    const char *ssid = "JP_TestAP";

    int status = WL_IDLE_STATUS;
    boolean alreadyConnected = false; // whether or not the client was connected previously

    WiFiServer server(23);
    WiFiClient client;

    void setup()
    {
       delay(1000);
       Serial.begin(9600);
       Serial.println();
       Serial.print("Configuring access point...");
       /* You can remove the password parameter if you want the AP to be open. */
       WiFi.softAP(ssid);
       delay(200);
       IPAddress myIP = WiFi.softAPIP();
       Serial.print("AP IP address: ");
       Serial.println(myIP);

       Serial.println("\nStarting server...");
      // start the server:
      server.begin();
    }

    void loop()
    {
      // wait for a new client:
      if (!client) {
          client = server.available();
      }
      else
      {
         if (client.status() == CLOSED) {
          client.stop();
          Serial.println("connection closed !");
        }
        if (!alreadyConnected) // when the client sends the first byte, say hello:
        {
          // clead out the input buffer:
          client.flush();
          Serial.println("We have a new client");
          client.println("Hello, client!");
          alreadyConnected = true;
        }

        if (client.available() > 0) {
          // read the bytes incoming from the client:
          char thisChar = client.read();
          // echo the bytes back to the client:
          server.write(thisChar);
          // echo the bytes to the server as well:
          Serial.print(thisChar);
        }
      }
    }

**Arduino Uno**

    #include<SoftwareSerial.h>
    SoftwareSerial esp8266(2,3);
    String message = "";
    bool messageReady = false;
    void setup() {
      // put your setup code here, to run once:
     Serial.begin(115200);
    esp8266.begin(9600);
    }

    void loop() {
      while(esp8266.available() > 0) {
        message = esp8266.readString();
        messageReady = true;
      }
      if(messageReady) {
        Serial.println(message);
        messageReady = false;
        return;
      }

    }

Unfortunately, I am not receiving any information from the ESP8266 (just a clear log on monitor port). I don't understand where the mistake.

title: Can't transfer information from esp8266 to arduino

Answers: 0


body:
From an ESP32 example code, I extracted the following part, that just prints the flash partition list to the console.

```cpp
#include <string.h>
#include <assert.h>
#include "esp_partition.h"
#include "esp_log.h"

static const char *TAG = "example";

void setup(void)
{
    Serial.begin(115200);
    delay(200); // Otherwise, the first log entries get lost
    ESP_LOGI(TAG, "Start test");
    esp_partition_iterator_t iter = esp_partition_find(ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, NULL);
    ESP_LOGI(TAG, "Name, type, subtype, offset, length");
    while (iter != nullptr)
    {
      const esp_partition_t *partition = esp_partition_get(iter);
      ESP_LOGI(TAG, "%s, app, %d, 0x%x, 0x%x (%d)", partition->label, partition->subtype, partition->address, partition->size, partition->size);
      iter = esp_partition_next(iter);
    }

    esp_partition_iterator_release(iter);
    iter = esp_partition_find(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, NULL);
    while (iter != nullptr)
    {
      const esp_partition_t *partition = esp_partition_get(iter);
      ESP_LOGI(TAG, "%s, data, %d, 0x%x, 0x%x (%d)", partition->label, partition->subtype, partition->address, partition->size, partition->size);
      iter = esp_partition_next(iter);
    }

    esp_partition_iterator_release(iter);

}

void loop()
{
}
```

In the project folder, I also have a custom `partitions.csv` file as follows:
```
nvs,        data, nvs,      0x9000,  0x6000,
phy_init,   data, phy,      0xf000,  0x1000,
factory,    app,  factory,  0x10000, 512k,
storage,    data, ,         ,        0x40000,
```

If I run the code, it correctly shows the custom partitions with the above sizes, everything like it should be.

**However**, the build output says the program uses 207278 Bytes from a maximum of 1310720. If I change the partition scheme selection in the tools menu, the second number changes. I would expect the maximum size to be equal to the size of the `factory` partition from the custom partition scheme.

If I change the factory partition to be only 100k in size, the ESP32 fails to boot and enters a core-dump-restart-loop.

Is this a compiler bug or am I overlooking something?

title: ESP32 Partition size and maximum program size

Answers: 1

body:
This appears to be a limitation of the toolchain. The output of processing the `partitions.csv` file doesn't make it back to the compiler to generate the correct message. The different partition schemes available in the menu come from `boards.txt` of the ESP32 package. They can be updated, but would be overwritten when the toolchain is updated. For the compiler input, the setting in the menu is relevant, but the actual size of the partitions comes from the `partitions.csv` file (if it exists).

This means that one has to manually make sure that the size of the `factory` partition in the csv file is larger or equal to the actual code size. Ideally, it is also equal to the selected partition size from the menu (to get the correct message and eventually error if the binary size exceeds the allocated space).

Some testing shows that if the actual size of the `factory` partition is smaller than the code size (and smaller than the compiler size limit) the application will successfully build and upload, but fail to run. The chip will enter a startup-reboot-forever loop and not execute any user code. However, whether that is always the case is not guaranteed.


body:
I have a DS3231 RTC module.

I would like to get the time from the RTC as 24 hour format not 12 hour. The library that I'm using requires that I pass in 2 Boolean values into ```Clock.getHour()```, however changing these values does not change the returned time format.

Code;
```
/*
DS3231_test.pde
Eric Ayars
4/11

Test/demo of read routines for a DS3231 RTC.

Turn on the serial monitor after loading this to check if things are
working as they should.

*/

#include <DS3231.h>
#include <Wire.h>

DS3231 clock;
bool century = false;
bool h12Flag;
bool pmFlag;
byte alarmDay, alarmHour, alarmMinute, alarmSecond, alarmBits;
bool alarmDy, alarmH12Flag, alarmPmFlag;

void setup() {
 // Start the I2C interface
 Wire.begin();

 // Start the serial interface
 Serial.begin(57600);
}

void loop() {
 // send what's going on to the serial monitor.

 // Start with the year
 Serial.print("2");
 if (century) {   // Won't need this for 89 years.
  Serial.print("1");
 } else {
  Serial.print("0");
 }
 Serial.print(clock.getYear(), DEC);
 Serial.print(' ');

 // then the month
 Serial.print(clock.getMonth(century), DEC);
 Serial.print(" ");

 // then the date
 Serial.print(clock.getDate(), DEC);
 Serial.print(" ");

 // and the day of the week
 Serial.print(clock.getDoW(), DEC);
 Serial.print(" ");

 // Finally the hour, minute, and second
 Serial.print(clock.getHour(h12Flag, pmFlag), DEC);
 Serial.print(" ");
 Serial.print(clock.getMinute(), DEC);
 Serial.print(" ");
 Serial.print(clock.getSecond(), DEC);

 // Add AM/PM indicator
 if (h12Flag) {
  if (pmFlag) {
   Serial.print(" PM ");
  } else {
   Serial.print(" AM ");
  }
 } else {
  Serial.print(" 24h ");
 }

 // Display the temperature
 Serial.print("T=");
 Serial.print(clock.getTemperature(), 2);

 // Tell whether the time is (likely to be) valid
 if (clock.oscillatorCheck()) {
  Serial.print(" O+");
 } else {
  Serial.print(" O-");
 }

 // Indicate whether an alarm went off
 if (clock.checkIfAlarm(1)) {
  Serial.print(" A1!");
 }

 if (clock.checkIfAlarm(2)) {
  Serial.print(" A2!");
 }

 // New line on display
 Serial.println();

 // Display Alarm 1 information
 Serial.print("Alarm 1: ");
 clock.getA1Time(alarmDay, alarmHour, alarmMinute, alarmSecond, alarmBits, alarmDy, alarmH12Flag, alarmPmFlag);
 Serial.print(alarmDay, DEC);
 if (alarmDy) {
  Serial.print(" DoW");
 } else {
  Serial.print(" Date");
 }
 Serial.print(' ');
 Serial.print(alarmHour, DEC);
 Serial.print(' ');
 Serial.print(alarmMinute, DEC);
 Serial.print(' ');
 Serial.print(alarmSecond, DEC);
 Serial.print(' ');
 if (alarmH12Flag) {
  if (alarmPmFlag) {
   Serial.print("pm ");
  } else {
   Serial.print("am ");
  }
 }
 if (clock.checkAlarmEnabled(1)) {
  Serial.print("enabled");
 }
 Serial.println();

 // Display Alarm 2 information
 Serial.print("Alarm 2: ");
 clock.getA2Time(alarmDay, alarmHour, alarmMinute, alarmBits, alarmDy, alarmH12Flag, alarmPmFlag);
 Serial.print(alarmDay, DEC);
 if (alarmDy) {
  Serial.print(" DoW");
 } else {
  Serial.print(" Date");
 }
 Serial.print(" ");
 Serial.print(alarmHour, DEC);
 Serial.print(" ");
 Serial.print(alarmMinute, DEC);
 Serial.print(" ");
 if (alarmH12Flag) {
  if (alarmPmFlag) {
   Serial.print("pm");
  } else {
   Serial.print("am");
  }
 }
 if (clock.checkAlarmEnabled(2)) {
  Serial.print("enabled");
 }

 // display alarm bits
  Serial.println();
 Serial.print("Alarm bits: ");
 Serial.println(alarmBits, BIN);

 Serial.println();
 delay(1000);
}
```

How do I make this happen?

title: Get time as 24 hour format from RTC

Answers: 1

body:
> The library that I'm using requires that I pass in 2 Boolean values
> into Clock.getHour(), however changing these values does not change
> the returned time format.

You appear to be talking about the parameters [here][1], which the second is for getting the current state of the AM/PM flag and configuration and not altering the kind of value you get in the return.

There's a [setClockMode function][2] you can call which will configure the chip to report in 24-hour mode.  If you call that passing in `false`, `getHour` should begin returning 24-hour time.

  [1]: https://github.com/NorthernWidget/DS3231/blob/v1.0.7/DS3231.h#L73
  [2]: https://github.com/NorthernWidget/DS3231/blob/v1.0.7/DS3231.h#L102/DS3231.h#L106


body:
I created a custom PCB based on a 328P. The design is mainly based on the Arduino Nano schematic (3.0). The boards have arrived some days ago, and I can't get avrdude to recognize them via USBASP (or any other mean for that matter). When trying to program the board is powered via the ICSP connector. What I have tried so far:
- only soldering the essential components: CAPs for 5V rail
- soldering the Oscillator or leaving it off
- on one board I even cut all lines except 5V, GND, RST and SPI.

Still the 328p won't respond, all I get is :

    #avrdude -u -c usbasp -P COM1 -b 57600 -B 0.5 -p m8

     WARNING: Unable to detect MCU
     avrdude.exe: set SCK frequency to 1500000 Hz
     avrdude.exe: error: program enable: target doesn't answer. 1
     avrdude.exe: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.
     avrdude.exe done.  Thank you.

I will attach my schematics and my board design, I know it is not the cleanest for now... It is my first one and I am currently trying to clean it up/make it better. I also added 1k resistors in line to RX and TX, but they are not present in the board design for now.

I am thankful for any help and/or advice

I can provide the board design if needed:)

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

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

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

  [1]: https://i.stack.imgur.com/jYDHg.png
  [2]: https://i.stack.imgur.com/k8ant.png
  [3]: https://i.stack.imgur.com/zGEuM.png

title: Custom 328P-AU board not responding via ICSP

Answers: 1

body:
So you had:

> SCK frequency to 1500000

And I suggested lowering to the point where you:

> set it to 8k solved it:)

Good deal.  The thing that you were likely running afoul of is the maximum ISP clock rate, which according to the [datasheet for the ATMega328P][1] (or practically any other AVR for that matter) is determined by some rules:

> Low:> 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck ≥ 12MHz
> High:> 2 CPU clock cycles for fck < 12MHz, 3 CPU clock cycles for fck ≥ 12MHz

So your maximum ISP clock rate is dependent on the chip's clock rate.  And is either at most a quarter of a sixth of that, depending on whether or not the chip operating below or above 12MHz.

Most ordering codes of AVRs of the type that do this kind of ISP programming ship from the factory at on the internal 8 MHz oscillator with the divide-by-8 fuse enabled; So they're at 1 MHz with a maximum ISP clock rate of 250 kHz.  Had you been working with a the typical Arduino arrangement when it had already been set up for and running with a 16 MHz clock, the 1.5 MHz ISP clock rate *might* have worked.  I'd have still slowed it down, since it will only be more likely to work when doing that.

Most programmers default to a low clock rate, closer to your 8k figure.  Usually, if people have a problem with hitting the maximum ISP clock rate, it's because they have a very low system clock, either using a watch crystal or fusing for the internal 128 kHz, or either in combination with the divide-by-8-fuse.  Often when trying to go too-fast, what's holding them up is crappy wiring.

When you're programming there's a limit to how useful it is to crank the clock rate up anyway, because eventually there's going to be a lot of hurry-up-and-wait while the chip flashes sectors and the timing of that isn't dependent on the clock rate.

  [1]: https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061B.pdf


body:
I want to parse the data of the incoming buffer from the serial read bytes, but I don't really know how to get the data out of the array and save it to different variables.

This is my code:

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

    struct buf {
      byte FunctionCode;
      byte Length;
      byte Message;
      byte Checksum;
    } data;

    void loop() {
      int Length = Serial.available();
      byte Buffer[Length];
      byte IncomingData[Length];
      if (Length >= 0)
      {
        Serial.readBytes(Buffer, Length);
        data.FunctionCode = Buffer[0 - 1];
      }
    }

title: Parse the data incoming from the buffer of Serial.readBytes()

Answers: 0


body:
I'm working with an Arduino UNO and a stepper motor NEMA 17. I would like to know how to avoid the stepper motor to revert its spin direction when I apply a load in the shaft. The motor works as I spect without any load, here is the code I'm using.

I think I'm missing something in the code, not in the connections.

    // Define pin connections & motor's steps per revolution
    const int dirPin = 2;
    const int stepPin = 3;
    const int stepsPerRevolution = 45;//115

    void setup()
    {
      // Declare pins as Outputs
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
    }
    void loop()
    {

    if(true){
        // Set motor direction counterclockwise
      digitalWrite(dirPin, HIGH);

      // Spin motor quickly
      for(int x = 0; x < stepsPerRevolution; x++)
      {
        digitalWrite(stepPin, HIGH);
        delayMicroseconds(700); //670
        digitalWrite(stepPin, LOW);
        delayMicroseconds(700); //670
      }

      }
    }

External voltage: 12 v 3A max

Motor's datasheet: [17HS4401S][1]

Driver: DRV8825

Guide:https://lastminuteengineers.com/drv8825-stepper-motor-driver-arduino-tutorial/

Sketch

 [![Resource: https://lastminuteengineers.com/drv8825-stepper-motor-driver-arduino-tutorial/][2]][2]

  [1]: https://www.google.com/search?q=nema 17 17hs4401 datasheet&oq=nema 17 17h&aqs=edge.3.69i57j0l5j0i22i30.13645j0j1&sourceid=chrome&ie=UTF-8
  [2]: https://i.stack.imgur.com/bciDb.png

title: How to avoid stepper motor to revert its spin direction from code

Answers: 0


body:
Im having a problem where i got unsinged long variable and i need to increment it in eeprom everytime setup starts and it overflows at `255` back to `0`.
```cpp
unsigned long NumberOfBoots = 0UL;
#define INFO_NUMBER_OF_BOOTS_ADDR 0
#define INFO_NUMBER_OF_BOOTS_LEN sizeof(NumberOfBoots)

// in setup
EEPROM.get(INFO_NUMBER_OF_BOOTS_ADDR, NumberOfBoots);
EEPROM.update(INFO_NUMBER_OF_BOOTS_ADDR, ++NumberOfBoots);
```
My guess is that its due to `Update()` fuction. Any ideas?

title: Why does this piece of code overflow at 255?

Answers: 0


body:
I am using ``arduino-ide``2.0.0-beta.7(CLI Version:0.18.3 alpha) on Manjaro Linux and I get this error when uploading sketch to my Arduino Micro:
>avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied
Upload error: Error: 2 UNKNOWN: uploading error: uploading error: exit status 1

I checked other questions and tried:
```
sudo groupadd dialout
sudo gpasswd -a $USER dialout
sudo chmod a+rw /dev/ttyACM0
sudo usermod -a -G dialout $USER
sudo chown root:dialout -R /dev/
ls -l /dev/ttyACM0 #can see the root:dialout
```
But when I logout and get again after ``ls -l /dev/ttyACM0``:
>crw-rw-rw- 1 root uucp 166, 0  6月 13 17:06 /dev/ttyACM0

So I cannot upload the sketch. Note: I can upload sketches using ``sudo arduino-ide --no-sandbox ``, but I want to upload them from the ``user`` account.

What else can I try?

Thank you.

Answers: 1

body:
Instead of:
```
sudo usermod -a -G dialout $USER
```
I had to run:

```
sudo usermod -a -G uucp $USER
```

Thanks to @Juraj I realized that. Thanks @Juraj.


body:
So I am trying to put together a code for 4dc motors, buzzer, ultrasonic and lcd to work together,. they will together make up a small car. when the distance to the ultrasonic is smaller than 10cm, the buzzer makes a random sound, and a funny face. Meanwhile the motors will stop for 2 seconds, goes back for 2 seconds and do a turning motion for 8 seconds. However. I do not want to use the delay function for the motors since it will cause the buzzer to sound too slowly. I know I need to do a blink without delay code, I am trying to implement this but am having trouble right now: the motors will stop when I put in the motor stop function, but it will not go backwards.. I know there are some timing issues but how can I fix this?
please see attached the code and wiring diagram.

Thank you sooo much !!!!

```
#include <LiquidCrystal.h>
#include <NewTone.h>

#include<AFMotor.h>
#define trigPin A1
#define echoPin A0

AF_DCMotor motor1(1,MOTOR34_1KHZ);
AF_DCMotor motor2(2,MOTOR34_1KHZ);
AF_DCMotor motor3(3,MOTOR34_1KHZ);
AF_DCMotor motor4(4,MOTOR34_1KHZ);

LiquidCrystal lcd(8, 9, 4, 7, 12, 13);

int buzzerPin = A2;
int notes[] = {262};
int dur = 100;
int maximum = 100;
long duration;
int distance;
int distanceUltra;
unsigned long previousBuzzerMillis = 0;
unsigned long previousDCStopMillis = 0;
unsigned long previousDCBackMillis = 0;
unsigned long currentMillis = 0;
const unsigned long DCStopInterval =2000;
const unsigned long DCBackInterval =2000;

byte a[]={
  B10001,
  B10001,
  B10101,
  B10101,
  B01010,
  B00000,
  B00000,
  B00000
  };

byte b[]={
  B00000,
  B00010,
  B00100,
  B01000,
  B01000,
  B01000,
  B01000,
  B01000
  };

byte c[]={
  B00000,
  B01000,
  B01000,
  B01000,
  B01000,
  B01000,
  B00100,
  B00010
  };

byte h[]={
  B00000,
  B01000,
  B00100,
  B00010,
  B00010,
  B00010,
  B00010,
  B00010
  };

void setup() {

  Serial.begin(9600);
  lcd.begin(16,2);
  pinMode (trigPin, OUTPUT);
  pinMode (echoPin, INPUT);
  lcd.createChar(0,a);
  lcd.createChar(1,b);
  lcd.createChar(2,h);
  lcd.createChar(3,c);

  pinMode(buzzerPin, OUTPUT);
  }

void loop() {

  currentMillis = millis();
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;

  Serial.print("distance:");
  Serial.println(distance);

  lcd.clear();
currentMillis = millis();

  if (distance <= 10){

    stopDCMotorStop();
    //stopDCMotorBack();

    }

  else{
    motor1.setSpeed(100);
    motor1.run(BACKWARD);
    motor2.setSpeed(100);
    motor2.run(BACKWARD);
    motor3.setSpeed(100);
    motor3.run(BACKWARD);
    motor4.setSpeed(100);
    motor4.run(BACKWARD);
      }

  if (distance <= 10){

    lcd.setCursor(5,1);   //set lcd faces
    lcd.write((char) 3);
    lcd.setCursor(5,0);
    lcd.write((char) 1);
    lcd.setCursor(9,1);
    lcd.write((char) 201);
    lcd.setCursor(9,0);
    lcd.write(2);
    lcd.setCursor(6,0);
    lcd.write("x");
    lcd.setCursor(8,0);
    lcd.write("x");
    lcd.setCursor(7,1);
    lcd.write("o");
    }

    if (distance <= 10){
      randSound(maximum);
    }

}

void randSound(int maximum){
  NewTone(buzzerPin, random(maximum, 10*maximum),dur);
  delay(maximum);
  noNewTone(buzzerPin);
}

void stopDCMotorStop(){

  if (currentMillis-previousDCStopMillis<= DCStopInterval) {
    motor1.setSpeed(0);
    motor1.run(RELEASE);
    motor2.setSpeed(0);
    motor2.run(RELEASE);
    motor3.setSpeed(0);
    motor3.run(RELEASE);
    motor4.setSpeed(0);
    motor4.run(RELEASE);
    previousDCStopMillis =currentMillis;
    }

  }

void stopDCMotorBack(){

  if (currentMillis-previousDCBackMillis<= DCBackInterval) {
    motor1.setSpeed(100);
    motor1.run(FORWARD);
    motor2.setSpeed(100);
    motor2.run(FORWARD);
    motor3.setSpeed(100);
    motor3.run(FORWARD);
    motor4.setSpeed(100);
    motor4.run(FORWARD);
    previousDCBackMillis =currentMillis;
    }
  }

 ```

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

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

title: DC motor and buzzer blink without delay code

Answers: 0


body:
I am compiling some code I didn't write, and it bombs out with the error message

    invalid conversion from 'char' to 'const char*' [-fpermissive]

on the line

    if (loginPassword == '\0') loginPassword = "";

I don't see why that line is any different than the previous strings, and the answers I can find all have to do with variables that start as char.

What is wrong with this code, and how do I fix it?

```cpp
    void saveUnit(String tempUnit, String supportMode, String loginPassword, String minTemp, String maxTemp, String tempStep) {
      const size_t capacity = JSON_OBJECT_SIZE(6) + 200;
      DynamicJsonDocument doc(capacity);

      // if temp unit is empty, we use default celcius
      if (tempUnit == '\0') tempUnit = "cel";
      doc["unit_tempUnit"]   = tempUnit;

      // if minTemp is empty, we use default 16
      if (minTemp == '\0') minTemp = 16;
      doc["min_temp"]   = minTemp;

      // if maxTemp is empty, we use default 31
      if (maxTemp == '\0') maxTemp = 31;
      doc["max_temp"]   = maxTemp;

      // if tempStep is empty, we use default 1
      if (tempStep == '\0') tempStep = 1;
      doc["temp_step"] = tempStep;

      // if support mode is empty, we use default all mode
      if (supportMode == '\0') supportMode = "all";
      doc["support_mode"]   = supportMode;

      // if login password is empty, we use empty
      if (loginPassword == '\0') loginPassword = "";
      doc["login_password"]   = loginPassword;

      File configFile = SPIFFS.open(unit_conf, "w");
      if (!configFile) {
        // Serial.println(F("Failed to open config file for writing"));
      }

      serializeJson(doc, Serial);
      serializeJson(doc, configFile);

      configFile.close();
    }
```

title: invalid conversion from 'char' to 'const char*' [-fpermissive] on a string

Answers: 1

body:
Regardless of the findings below, you don't really want to compare a string object with a null-character this way (more on that below).  Really something like:  `if (someArduinoStringObj.isEmpty()) {` is a better idea, no matter what core you're on.

So for anyone that has landed here with this problem with code that had worked and no longer works, the answer is basically don't do that; probably shouldn't have been doing that in the first place.

If you're curious on what I found, there's material on that below.

---

So, I don't have a complete handle on this, but I do have something to report.   When we started going through this I didn't think there would be anything going on in the Arduino board support packages that would have any effect on this, but it turns out that's not the case.

We worked out that under ESP8266 Arduino core 3.0.0 the lines of the following form fail to compile and under version 2.7.4 the compile without error.  Here under 3.0.0 it was not picky about specifically `loginPassword`.

```c++
if (someArduinoStringObj == '\0') someArduinoStringObj = "some literal";
```
This can be abstracted to the somewhat nonsensical:

```c++
someArduinoStringObj == '\0';
```

Since that's the part makes the difference.  I *really* thought there was something more clever going on in the WString.h/WString.cpp code, an extra constructor or implicit conversion operator call prior to the code for the == operator.  There is an explicit constructor for `String` that takes a single char, but it's just that, it's explicit; it doesn't take part in evaluating the `==` expression above.  And there's no automatic conversion from `String` to `const char *`. It turns out that isn't anything clever going on in String class when it comes to this problem.  In fact you can boil this down to something similar so that the String class itself isn't actually involved at all, into:

```c++
void func(const char *) {}

void setup() {
  func('\0');
}

// ...
```

This will likewise pass compilation under 2.7.4 and fail with a similar error message under 3.0.0.  So, with String it is just trying to call the `operator==(const char *)`, even though it's being given a `char` type.  Before getting into that, I tested a theory, which was to find out what happens if given `== '\1';` or `== 'X')` etc, any non-zero value, because 0 has had an interesting relationship with pointers in C++ and C.  It makes more sense once you realize there's special going on in String.h.  We're basically talking about `func('\0')` vs `func('\1')` or `func('X')`  Well, under 2.7.4 these values fail where '\0' does not, but under 3.0.0 both fail.  So I got looking into the platform.txt file on both core versions, thinking maybe I'll spot a difference in compiler options.  E.g. it would make "sense" if 2.7.4 had `-fpermissive` where 3.0.0. didn't, but that's not the case.  The major difference is that 3.0.0 has -std=g++17 and 2.7.4 has -std=g++11.  Just for the hell of it I stole the command-line out of the verbose output compiling for the .ino.cpp file and replaced -std=g++17 with -std=g++11 and applied it to a cut-down file; didn't make any difference.  So, as far I tell there's some difference in default options specified between the two compiler versions in use in the two esp8266 package versions.

Constant expressions that evaluate to zero of `int` type (at least), will convert to null pointer constants.  I haven't been in the habit of using character-typed (`'\0'`) zero valued constant expressions for null pointers, and I haven't dug through the various editions of the C++ standard to see what each one has to say about them; color me unsurprised either way.  But in any case, that's is basically what's happening here: The string object is being compared to a null pointer constant, at least when it compiles.  And if that makes you go WTF, well, me too.  If you follow this out, you ultimately you [end up here][1]:

```c++
unsigned char String::equals(const char *cstr) const {
    if (len() == 0)
        return (cstr == NULL || *cstr == 0);
    if (cstr == NULL)
        return buffer()[0] == 0;
    return strcmp(buffer(), cstr) == 0;
}
```

So, roughly speaking `someArduinoString == '\0'`, *where it will compile*, is equivalent to `someArduinoString == nullptr` which is sort of the same effect as `someArduinoString == ""`.  So, what you're seeing is not exactly an implicit form of `someArduinoString == String('\0')`.

I can't picture wanting to say `someArduinoString == '\0'` over `someArduinoString.isEmpty()`, but in terms of why it doesn't work on 3.0.0, I'm still unsure.  I can tell you that it will if you plant `-fpermissive` into platform.txt, but that doesn't really explain it.  Sometime when I'm really bored I'll see what the language standard actually says and what versions of g++ did what under what options.

Even I worked that out my answer would still be: don't do that.

  [1]: https://github.com/esp8266/Arduino/blob/2.7.4/cores/esp8266/WString.cpp#L509


body:
This is more of an annoyance, but if I edit a program with the serial monitor open, click "upload",  and the compile fails, the IDE switches to the serial monitor pane, opens the serial port which triggers a reset, and the last successfully uploaded version begins execution. This can be really annoying if you don't notice there were errors in the compile because VSCode automatically switches to the monitor pane and you waste time wondering why your code changes had no effect.

Is there any way to tell VSCode/Arduino add-in not to switch to the monitor pane in the event of a failed compile?

title: Stop VSCode/Arduino add-in from sending reset signal in the event of compile errors

Answers: 0


body:
I am having issues with a code that I have been modifying.
I can change the TIME, and DATE from a keypad, and see the data on the serial monitor, but it is not recording on the SD Card. Anyone that could help me. Thank you.
```
#include <OneWire.h>
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include "RTClib.h"

LiquidCrystal_I2C lcd(0x27,20,4)

RTC_DS3231 rtc;
DateTime   now;

const byte ROWS = 4;
 const byte COLS = 4;
 char keys[ROWS][COLS] = {
 {'1','2','3','A'},
 {'4','5','6','B'},
 {'7','8','9','C'},
 {'*','0','#','D'}
 };

 byte rowPINS[ROWS] = {10,9,8,7};
 byte colPINS[COLS] = {6,5,4,11};

 int i1,i2,i3,i4;
 char c1,c2,c3,c4;
 char keypressed;

 Keypad myKeypad = Keypad(makeKeymap(keys),rowPINS,colPINS, ROWS, COLS);

#define DS18B20_PIN   A3

File dataLog;
boolean sd_ok = 0;

void setup()
{

  rtc.begin();          // initialize RTC chip

  lcd.init();     // initialize LCD module
  lcd.backlight();
  lcd.setCursor(0, 3);  // move cursor to column 0, row 3 (last row)
  lcd.print("Temp:");

// open serial communications and wait for port to open:
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

// initialize the SD card
  if ( !SD.begin() )
    Serial.println(F("initialization failed!"));  // initialization error
else {   // initialization OK
    sd_ok = 1;
    Serial.println(F("initialization done."));
    if( SD.exists("Log.txt") == 0 )   // test if file with name 'Log.txt' already exists
    {  // create a text file named 'Log.txt'
      Serial.print("\r\nCreate 'Log.txt' file ... ");
      dataLog = SD.open("Log.txt", FILE_WRITE);   // create (&open) file Log.txt
      if(dataLog) {                               // if the file opened okay, write to it:
        Serial.println(F("OK"));
        // write some texts to 'Log.txt' file
        dataLog.println("    DATE    |    TIME  | TEMPERATURE");
        dataLog.println("(dd-mm-yyyy)|(hh:mm:ss)|");
        dataLog.close();   // close the file
      }
      else
        Serial.println(F("error creating file."));
    }
  }
   Serial.println(F("\r\n    DATE    |    TIME  | TEMPERATURE"));
   Serial.println(F("(dd-mm-yyyy)|(hh:mm:ss)|"));
}

// main loop
void loop()
{
  now = rtc.now();  // read current time and date from the RTC chip
  RTC_display();    // display time & calendar

  while(keypressed == NO_KEY){

  keypressed = myKeypad.getKey();

  now = rtc.now();  // read current time and date from the RTC chip
  RTC_display();    // display time & calendar

static byte p_second;
  if( (now.second()-1==0) ||  (now.second() % 5 == 0) && (p_second != now.second()) )
  {   // read & print temperature value from sensor every 10 seconds
    unsigned int ds18b20_temp;
    char buffer1[12], buffer2[26];
    bool sensor_ok = 0;

    p_second = now.second();
    if( ds18b20_read(&ds18b20_temp) )
    {
      sensor_ok = 1;
      if (ds18b20_temp & 0x8000)           // if temperature < 0
      {
        ds18b20_temp = ~ds18b20_temp + 1;  // change temperature value to positive form
        sprintf(buffer1, "-u.u�", (ds18b20_temp/16) % 100, (ds18b20_temp & 0x0F) * 625, 223);
      }
      else
      {      // otherwise (temperature >= 0)
        if (ds18b20_temp/16 >= 100)          // if temperature >= 100.0 °C
          sprintf(buffer1, "u.u�", ds18b20_temp/16, (ds18b20_temp & 0x0F) * 625, 223);
        else      // otherwise ( 0 <= temperature < 100.0)
          sprintf(buffer1, " u.u�", ds18b20_temp/16, (ds18b20_temp & 0x0F) * 625, 223);
      }
    }
    else
      sprintf(buffer1, "   ERROR  ");

    lcd.setCursor(5, 3);
    lcd.print(buffer1);

    sprintf( buffer2, " u-u-u | u:u:u | ", now.day(), now.month(), now.year(),
                      now.hour(), now.minute(), now.second() );
    if(sensor_ok) {
      buffer1[8] = 194;   // put degree symbol
      buffer1[9] = 176;
      buffer1[10] = 'C';  // put 'C' letter
      buffer1[11] = '\0'; // put string terminator
    }
    // print data on PC serial monitor
    Serial.print(buffer2);
    Serial.println(buffer1);
    // write data to SD card
    if(sd_ok)
    {  // if the SD card was successfully initialized
      // open Log.txt file with write permission
      dataLog = SD.open("Log.txt", FILE_WRITE);
      dataLog.print( buffer2 );
      dataLog.println( buffer1 );
      dataLog.close();   // close the file
    }

  }

  delay(100);   // wait 100ms

  }

if (keypressed == '*')
             {
              lcd.clear();
              lcd.print("     Setup");
             delay(1000);
              lcd.clear();
              lcd.print("Setup year");

             char keypressed2 = myKeypad.waitForKey();
                    if (keypressed2 != NO_KEY && keypressed2 !='*' && keypressed2 !='#' && keypressed2 !='A' && keypressed2 !='B' && keypressed2 !='C' && keypressed2 !='D' )
                      {
                       c1 = keypressed2;
                       lcd.setCursor(0, 1);
                       lcd.print(c1);
                       }
                 char      keypressed3 = myKeypad.waitForKey();
                    if (keypressed3 != NO_KEY && keypressed3 !='*' && keypressed3 !='#' && keypressed3 !='A' && keypressed3 !='B' && keypressed3 !='C' && keypressed3 !='D' )
                      {
                       c2 = keypressed3;
                       lcd.setCursor(1, 1);
                       lcd.print(c2);
                       }
                   char  keypressed4 = myKeypad.waitForKey();
                   if (keypressed4 != NO_KEY && keypressed4 !='*' && keypressed4 !='#' && keypressed4 !='A' && keypressed4 !='B' && keypressed4 !='C' && keypressed4 !='D' )
                      {
                       c3 = keypressed4;
                       lcd.setCursor(2, 1);
                       lcd.print(c3);
                       }
                   char   keypressed5 = myKeypad.waitForKey();
                   if (keypressed5 != NO_KEY && keypressed5 !='*' && keypressed5 !='#' && keypressed5 !='A' && keypressed5 !='B' && keypressed5 !='C' && keypressed5 !='D' )
                      {
                       c4 = keypressed5;
                       lcd.setCursor(3, 1);
                       lcd.print(c4);
                       }

                     i1=(c1-48)*1000;        //the keys pressed are stored into chars I convert them to int then i did some multiplication to get the code as an int of xxxx
                     i2=(c2-48)*100;
                     i3=(c3-48)*10;
                     i4=c4-48;
                     int N_year=i1+i2+i3+i4;
                   delay(500);
                     lcd.clear();
                     lcd.print("Setup month");

////////////////////////////////////////////////////////////////
                     char keypressed6 = myKeypad.waitForKey();  // here all programs are stopped until you enter the four digits then it gets compared to the code above
                    if (keypressed6 != NO_KEY && keypressed6 !='*' && keypressed6 !='#' && keypressed6 !='A' && keypressed6 !='B' && keypressed6 !='C' && keypressed6 !='D' )
                      {
                       c1 = keypressed6;
                       lcd.setCursor(0, 1);
                       lcd.print(c1);
                       }
                    char   keypressed7 = myKeypad.waitForKey();
                    if (keypressed7 != NO_KEY && keypressed7 !='*' && keypressed7 !='#' && keypressed7 !='A' && keypressed7 !='B' && keypressed7 !='C' && keypressed7 !='D' )
                      {
                       c2 = keypressed7;
                       lcd.setCursor(1, 1);
                       lcd.print(c2);
                       }

                     i1=(c1-48)*10;
                     i2=c2-48;
                    int N_month=i1+i2;
                     delay(500);

                     lcd.clear();
                     lcd.print("Setup Day");

 ////////////////////////////////////////////////////////////////
                      char keypressed8 = myKeypad.waitForKey();  // here all programs are stopped until you enter the four digits then it gets compared to the code above
                    if (keypressed8 != NO_KEY && keypressed8 !='*' && keypressed8 !='#' && keypressed8 !='A' && keypressed8 !='B' && keypressed8 !='C' && keypressed8 !='D' )
                      {
                        c1 = keypressed8;
                       lcd.setCursor(0, 1);
                       lcd.print(c1);
                       }
                      char keypressed9 = myKeypad.waitForKey();
                    if (keypressed9 != NO_KEY && keypressed9 !='*' && keypressed9 !='#' && keypressed9 !='A' && keypressed9 !='B' && keypressed9 !='C' && keypressed9 !='D' )
                      {
                        c2 = keypressed9;
                       lcd.setCursor(1, 1);
                       lcd.print(c2);
                       }

                     i1=(c1-48)*10;
                     i2=c2-48;
                    int N_day=i1+i2;
                    delay(500);
                     lcd.clear();
                     lcd.print("Setup hour");

////////////////////////////////////////////////////////////////////////////////////:
                     char keypressed10 = myKeypad.waitForKey();  // here all programs are stopped until you enter the four digits then it gets compared to the code above
                    if (keypressed10 != NO_KEY && keypressed10 !='*' && keypressed10 !='#' && keypressed10 !='A' && keypressed10 !='B' && keypressed10 !='C' && keypressed10 !='D' )
                      {
                       c1 = keypressed10;
                       lcd.setCursor(0, 1);
                       lcd.print(c1);
                       }
                    char   keypressed11 = myKeypad.waitForKey();
                    if (keypressed11 != NO_KEY && keypressed11 !='*' && keypressed11 !='#' && keypressed11 !='A' && keypressed11 !='B' && keypressed11 !='C' && keypressed11 !='D' )
                      {
                        c2 = keypressed11;
                       lcd.setCursor(1, 1);
                       lcd.print(c2);
                       }

                     i1=(c1-48)*10;
                     i2=c2-48;
                    int N_hour=i1+i2;
                    delay(500);
                     lcd.clear();
                     lcd.print("Setup minutes");

////////////////////////////////////////////////////////////////////////////////////:
                    char keypressed12 = myKeypad.waitForKey();  // here all programs are stopped until you enter the four digits then it gets compared to the code above
                    if (keypressed12 != NO_KEY && keypressed12 !='*' && keypressed12 !='#' && keypressed12 !='A' && keypressed12 !='B' && keypressed12 !='C' && keypressed12 !='D' )
                      {
                        c1 = keypressed12;
                       lcd.setCursor(0, 1);
                       lcd.print(c1);
                       }
                   char    keypressed13 = myKeypad.waitForKey();
                    if (keypressed13 != NO_KEY && keypressed13 !='*' && keypressed13 !='#' && keypressed13 !='A' && keypressed13 !='B' && keypressed13 !='C' && keypressed13 !='D' )
                      {
                        c2 = keypressed13;
                       lcd.setCursor(1, 1);
                       lcd.print(c2);
                       }

                     i1=(c1-48)*10;
                     i2=c2-48;
                    int N_minutes=i1+i2;
                    delay(500);
                     lcd.clear();

                  rtc.adjust(DateTime(N_year, N_month, N_day, N_hour, N_minutes, 0));

                  RTC_display();
                  lcd.setCursor(0, 3);  // move cursor to column 0, row 3 (last row)
                  lcd.print("Temp:");

                  //myRTC.setDS1302Time(22, N_minutes, N_hour, 1, N_day, N_month, N_year); //once we're done setting the date and time we transfer to values to the RTC module
                                                                                //the 22 stands for seconds you can add a setup for it too if you want
                                                                                //the 1 stands for day of the week, as long I don't show it on the screen I don't change it
                    keypressed=NO_KEY; //the "*" key is stored in "keypressed" so I remove that value from it otherwise it will get me in the setup again
              }

}

//////////////////////////////////////// RTC functions ////////////////////////////////////////
void RTC_display()
{
  char _buffer[17];
  char dow_matrix[7][10] = {" SUNDAY  ", " MONDAY  ", " TUESDAY ", "WEDNESDAY",
                             "THURSDAY ", " FRIDAY  ", "SATURDAY "};
  lcd.setCursor(4, 0);
  lcd.print( dow_matrix[now.dayOfTheWeek()] );

  // print time
  sprintf( _buffer, "TIME: u:u:u", now.hour(), now.minute(), now.second() );
  lcd.setCursor(0, 1);
  lcd.print(_buffer);
  // print date
  sprintf( _buffer, "DATE: u-u-u", now.day(), now.month(), now.year() );
  lcd.setCursor(0, 2);
  lcd.print(_buffer);
}

////////////////////////////////////// end RTC functions //////////////////////////////////////

////////////////////////////////// DS18B20 sensor functions ///////////////////////////////////
bool ds18b20_start()
{
  bool ret = 0;
  digitalWrite(DS18B20_PIN, LOW);  // send reset pulse to the DS18B20 sensor
  pinMode(DS18B20_PIN, OUTPUT);
  delayMicroseconds(500);          // wait 500 us
  pinMode(DS18B20_PIN, INPUT);
  delayMicroseconds(100);          // wait to read the DS18B20 sensor response
  if (!digitalRead(DS18B20_PIN))
  {
    ret = 1;                  // DS18B20 sensor is present
    delayMicroseconds(400);   // wait 400 us
  }
  return(ret);
}

void ds18b20_write_bit(bool value)
{
  digitalWrite(DS18B20_PIN, LOW);
  pinMode(DS18B20_PIN, OUTPUT);
  delayMicroseconds(2);
  digitalWrite(DS18B20_PIN, value);
  delayMicroseconds(80);
  pinMode(DS18B20_PIN, INPUT);
  delayMicroseconds(2);
}

void ds18b20_write_byte(byte value)
{
  byte i;
  for(i = 0; i < 8; i++)
    ds18b20_write_bit(bitRead(value, i));
}

bool ds18b20_read_bit(void)
{
  bool value;
  digitalWrite(DS18B20_PIN, LOW);
  pinMode(DS18B20_PIN, OUTPUT);
  delayMicroseconds(2);
  pinMode(DS18B20_PIN, INPUT);
  delayMicroseconds(5);
  value = digitalRead(DS18B20_PIN);
  delayMicroseconds(100);
  return value;
}

byte ds18b20_read_byte(void)
{
  byte i, value;
  for(i = 0; i < 8; i++)
    bitWrite(value, i, ds18b20_read_bit());
  return value;
}

bool ds18b20_read(int *raw_temp_value)
{
  if (!ds18b20_start())  // send start pulse
    return(0);
  ds18b20_write_byte(0xCC);   // send skip ROM command
  ds18b20_write_byte(0x44);   // send start conversion command
  while(ds18b20_read_byte() == 0);  // wait for conversion complete
  if (!ds18b20_start())             // send start pulse
    return(0);                      // return 0 if error
  ds18b20_write_byte(0xCC);         // send skip ROM command
  ds18b20_write_byte(0xBE);         // send read command

  // read temperature LSB byte and store it on raw_temp_value LSB byte
  *raw_temp_value = ds18b20_read_byte();
  // read temperature MSB byte and store it on raw_temp_value MSB byte
  *raw_temp_value |= (unsigned int)(ds18b20_read_byte() << 8);

  return(1);  // OK --> return 1
}

```

title: RTC shield with LCD and Keypad

Answers: 0


body:
We are making a simple pulse oximeter device with an Arduino Nano and a [MAX30102][1] sensor.

The problem is the SpO2 reading and processing algorithm of the MAX30102 library literally does signal processing on the Arduino with large arrays of data and because of that, when you do BPM and SpO2, the 2kb memory of the Arduino is already full.

Can you guys give me some advice to overcome this problem?

  [1]: https://datasheets.maximintegrated.com/en/ds/MAX30102.pdf

title: Arduino Nano: MAX30102 and memory problems

Answers: 1

body: Arduino UNO is not recommended for MAX30102 as it requires a lot of processing and RAM. Consider shifting to Arduino Mega or the ESP32.