body:
I'm building a system as follows:

* There are two pumps which lower and raise the level of the water
* There is an ultrasound detector which measures the level of the water
* While the water is too high, water is pumped out
* While it's too low, water is pumped in

There are thresholds to prevent micro-adjustments, the system doesn't flip-flop back and forth.

However after a short while the ultrasound sensor stops working, until I power the system off and on again. My electronics knowledge is *extremely* rudimentary, but I know motors can be nasty to other components?

I've included my circuit diagram, should I be doing anything about that? I'm using reed switches to turn them off and on, but the ground and 5v rails are all tied together, and powering the arduino too via VIN.

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

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

title: Is this circuit damaging my arduino/components?

Answers: 2

body:
Motors are inductive loads (they contain coils) that generate voltage spikes when switched off. These voltage spikes can indeed be nasty to other components.
You need to add a **[flyback diode][1]** in parallel with the motor, with the cathode connected to Vcc.
It will normally not conduct current, but when the motor is switched off, because the voltage spike is negative, it will provide a path for the current and allow to dissipate it through the coil's internal resistance.

As pointed out in the comments, it's also a good idea to (always) add an electrolytic capacitor (> 100 µF) close to the ultrasonic detector to filter out this kind of spikes.

  [1]: https://en.wikipedia.org/wiki/Flyback_diode

body: Hopefully you are powering the Arduino Vin with at least 7 volts. We know the Arduino a power supply it is NOT so where does the 5V come for the motors? You need to post technical links to the hardware items you are using. Are you calling relays reed switches? D11 and D12 sound like port pins, normally they cannot drive relays unless they are designed appropriately. I would suggest you either buy another set of electronic parts or stop using it until the problems can be determined. As far as a circuit diagram does not show the information needed. A schematic, not a frizzy thing is much better.


body:
My project is to control a servo with a joystick using nRF24L01. I have this code working well, but the problem is that I want to add a lamp in the receiver side, and a switch in the transmitter side. I had tried so many codes from the internet, but nothing works. When I implement the code for the led, the servo and the joystick will stop working unfortunately.
Maybe the problem could be solved by transmitting on 2 channels each channel has a command.  But, the question is how this is the transmitter code that is working normally :

 Transmitter Code

```c++
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";

void setup() {

  radio.begin();
  radio.openWritingPipe(address); // 00002
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
delay(5);

 radio.stopListening();
  int potValue = analogRead(A0);
  int angleValue = map(potValue, 0, 1024, 0, 23.5);
 radio.write(&angleValue, sizeof(angleValue));

  delay(5);
  radio.startListening();

}
```

and this is the receiver code:

 Receiver Code

```c++
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>

RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
boolean button_state = 0;

Servo myServo;

void setup() {

    Serial.begin(9600);
  myServo.attach(5);

  radio.begin();

  radio.openReadingPipe(0, address); // 00002
  radio.setPALevel(RF24_PA_MIN);

}

void loop() {

  delay(5);
  radio.startListening();

  if ( radio.available()) {
while (radio.available()) {

      int angleV = 0;
      radio.read(&angleV, sizeof(angleV));
     myServo.write(angleV);
      }

    delay(5);
    radio.stopListening();

  }}
```

title: How can I send 2 orders using nRF24L01

Answers: 0


body:
[![Schematic resume][1]][1]
Hi everyone,
first time here on the forum, so, apologies if I'm doing anything incorrectly.
Long story short, I built a device that takes voltages in and transform them into midi data. I used an ATMega328P PU and midi data exit through the TX pin of the chip, into an optoisolator and then go to a jack. Everything works great.
I decided to make the next step, switching to an ATMega32u4, my main goal is to have those midi data exiting simultaneously out from the jack and from the USB which also act as a power source for the device.
The device is now recognized by my laptop as a usb device, so I assume all the USB wiring are correct, however, I have no midi data exiting from any of the jack or usb and I don't understand why. Of course I changed all the pin assignment according to the ATMega32u4 datasheet.
I use Arduino IDE for programming and the device is recognized by the IDE as "Arduino Leonardo": it has to be said that I've always used Arduino UNO and Nano, so I don't know if there are any differences in terms of code when it comes to different boards.

My assumption is that, for some reason, TX pin remains silent. I guess there must be something wrong with my code setup: I simply typed

    Serial.begin(9600);

Are there any specific Leonardo libraries I have to be aware of?

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

title: ATMega32u4 - Sending and receiving data through TX and RX

Answers: 0


body:
Hi there I want to send a request to the server with get method with URL parameters, when a key is pressed with nodemcu. But I Can't Do This Work, I Got the Below Error From Serial Monitor:

I Get This Error From Serial Monitor

     ets Jan  8 2013,rst cause:4, boot mode:(3,7)

    wdt reset
    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v951aeffa
    ~ld
**My Main Code**
```
#include <ESP8266WiFi.h>
const char* ssid = "MobinNet1365";
//replace with your own wifi ssid
const char* password = "G12229M1Q64"; //replace with your own //wifi ssid password
const char* host = "webhook.site";

const int button = 8;
int temp = 0;

void setup() {

  Serial.begin(115200);
  pinMode(button, INPUT);
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

  temp = digitalRead(button);
  if (temp == HIGH) {
    Serial.println(host);
    WiFiClient client;
    const int httpPort = 80;

    String url = "/df35c8cd-0398-4c92-b55f-b9e36629b309";
    url += "?switche=";
    url += "1";

    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  }
}
```

my request sending code is below:

```
#include <ESP8266WiFi.h>
const char* ssid = "your-ssid";
const char* password = "your-password";
const char* host = "";

void setup() {
 Serial.begin(115200);
 delay(10);
 Serial.println();
 Serial.print("Connecting to ");
 Serial.println(ssid);
 WiFi.mode(WIFI_STA);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED)
 {
  delay(500);
  Serial.print(".");
 }

 Serial.println("");
 Serial.println("WiFi connected");
 Serial.println("IP address: ");
 Serial.println(WiFi.localIP());
}
int value = 0;
void loop() {
 delay(5000);
 ++value;
 Serial.print("connecting to ");
 Serial.println(host);
 WiFiClient client;
 const int httpPort = 80;
 if (!client.connect(host, httpPort)) {
  Serial.println("connection failed");
  return;
 }

 String url = "/";
 /* url += "?param1=";
 url += param1;
 url += "?param2=";
 url += param2;
 */
 Serial.print("Requesting URL: ");
 Serial.println(url);
 client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
 unsigned long timeout = millis();
 while (client.available() == 0) {
  if (millis() - timeout > 5000)
  {
   Serial.println(">>> Client Timeout !");
   client.stop();
   return;
  }
 }

 while (client.available())
 {
  String line = client.readStringUntil('\r'); Serial.print(line);
 }

 Serial.println();
 Serial.println("closing connection");
}
```

And My Key Press Code Detector Is below:

```
const int button = 8;
int temp = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button, INPUT);
}

void loop() {
  temp = digitalRead(button);

   if (temp == HIGH) {
      Serial.println("LED Turned ON");
      delay(1500);
   }
   else {
      Serial.println("LED Turned OFF");
      delay(1500);
   }
}
```

And My Circuit Is:

NodeMcu => MicroSwitch

VIN => C

D0 => NO

G => 10k => NO

How Can I Make It When That Key Pressed It Send Request?

title: Send Request With NODEMCU When A Key Press

Answers: 1

body:
IMHO, some consideration :

1. const int button = 8;
const int button = 5; // CHANGE TO Pin "D1 GPIO5"

GPIO8 is used to connect the flash chip, you may change to Pin "D1" which is GPIO 5.
* Check with your board's pinout.

2. to prevent non-stop keep calling within in the loop, you may use millis();

for example :

```
void GetUrl() {
    temp = digitalRead(button);
  if (temp == HIGH) {
    Serial.println(host);
    WiFiClient client;
    const int httpPort = 80;

    String url = "/df35c8cd-0398-4c92-b55f-b9e36629b309";
    url += "?switche=";
    url += "1";

    String link = String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n";
//    Serial.println( "link : " + link );
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  }
}

unsigned long previousMillis = 0;
const long interval = 1000 * 0.5; // 500ms (0.5 sec)

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    GetUrl();
  }
}
```

Reference :

https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay

https://iotbyhvm.ooo/gpio-pins-esp8266/


body:
I would like to read data from a rs232 device (SL-5868P Sound Level Meter).
protocol and more : https://sigrok.org/wiki/Colead_SL-5868P.

I already have a Python script to read the data with a TTL to USB converter (without Arduino). Now I also want to be able to read the meter via the Arduino.

I've bought a RS232 to TTL Converter (MAX3232). I get either very weird characters (baud rate set correctly), or not logical numbers. With the MAX chip I get no data at all.

1. To see if there is data ready, 0x10 must be sent by the meter.
2. To get the data, send 0x20.

Would someone be willing to help me out a bit? That would be really nice. Maybe there is someone who has experience with reading (and writing to) RS232. The only thing that matters is how I can retrieve the data. I know the rest what needs to be done with software (conversion, etc.). I'm not that familiar with Arduino's .

The code below is an example from SoftwareSerial (a little bit modified). I'm using the Arduino Uno.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

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

      Serial.println("Goodnight moon!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(2400);
    }

    void loop() { // run over and over
      if (mySerial.read() == 0x10) {
        //mySerial.write(0x20);
        Serial.println("Data available");
        Serial.println(mySerial.read());
      }

      if (Serial.available()) {
        mySerial.write(Serial.read());
      }
      //delay(300);
    }

And the current schematic (sorry for my drawing skills)

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

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

title: How to read from and write to rs232 device from/to Arduino

Answers: 2

body:
You didn't show how you connected the MAX3232, so I cannot say anything about that. But I can write something about your code and how the data gets received on the PC.

- **On the PC:** Here it is important how you are reading the serial data on the PC. The Serial Monitor for example expects ASCII encoded text. It cannot correctly display binary data. That is the reason, that you get weird characters with the correct baudrate. The data is correctly received, but it doesn't represent ASCII characters. It is just binary data and interpreting it as ASCII characters will not make any sense.

    Also it just sends ASCII encoded text, no binary data. So when you are sending "10" it will send the bytes `0x31` and `0x30`, plus any line ending, that you have selected (`\n` aka `0x0A` if you selected newline as line ending). As your device speaks in binary data you might wanna speak binary to it. So you either need to decode the ASCII data on the Arduino, before sending it to the device, or you need to use a different serial program, which can handle binary data.

- **Your code:** First look at this line

        Serial.println(mySerial.read());

    Here you are reading exactly **one byte** from the SoftwareSerial interface and then you are printing it. `Serial.read()` or `SoftwareSerial.read()` only read one single byte from the buffer, but the data from your device spans over multiple bytes, as described on the wiki page, that you linked. Look at the table titled "Data structure". The returned data consists of 10 bytes in total (numbered from 0 to 9), where bytes 3 to 7 contain the actual data. The rest gives configuration and status data, a header as packet start and a checksum to check for transmission errors. So reading only one byte isn't enough you need to read all of them.

    Then you are `Serial.print()`ing the data. The `print()` function and its siblings are formatting the data human readable. That might help you here, but you need to make sure, that the resulting output is really readable for you, especially when you are reading multiple bytes (as you need to do, as explained above). Here you need to make a decision: Either

    * you could decode and format the binary data from the device on the Arduino and send the human readable format over Serial
    * or you could send the binary data straight to the PC and decode it there with a fitting program (either a Serial program, which can handle binary data, or your own program, for example with python or processing)

    If you go the first way, you should first read the different parts of the message and then print these parts with additional text, that explains, what data means what. Otherwise you would have just a long line of numbers, which are also rather difficult to read. Also you might wanna decide on a number base. I think only decimal or hexadecimal are really relevant here. For that you could use `Serial.print(value, DEC)` or `Serial.print(value, HEX)`, which tells the Serial library to use the specified number base.

    **Now about the actual data format:** The data format is described with

    > BCD-encoded value, one byte per digit 0x00-0x09. 0x0a means ignored digit. The last digit represents the decimal.

    on the linked wiki site. So while this is still binary data (not ASCII encoded), each byte represents a decimal digit of the actual value. You could decode it accordingly. So I guess a byte sequence of `0x01 0x00 0x02 0x09 0x07` would mean `1029.7`. As you wrote, that you already know how to convert the data, I will not go deeper about this here.

    And lastly you need to rethink your program structure. The workflow with your device is the following:

        Arduino waits for device to send data ready byte (0x10)
        device sends 0x10
        Arduino sends 0x20 (command to send data)
        Arduino waits for device to send at least 10 bytes of data
        device sends a complete data packet with 10 bytes
        Arduino interprets the data in the received packet and acts accordingly
        repeat

    You need to follow this workflow and also anticipate, that the data transmission takes some time (especially at the really slow 2400 baud). For this a Finite State Machine (FSM) is a good fit (there are many extended descriptions about FSMs on this site, for example my answer to [this question][1] or [this question][2], though there are many more, which you just need to search for). We just track at which part of the workflow we are currently and execute the according code. Something like this:

        enum ReceiveState {IDLE, RECEIVING};
        ReceiveState rec_state = IDLE;

        void loop(){
            if(mySerial.available()){
                switch(rec_state){
                    case IDLE:
                        if(mySerial.read() == 0x10){
                            // data is ready, command to send data
                            mySerial.write(0x20);
                            // change state to receiving
                            rec_state = RECEIVING;
                        }
                        break;
                    case RECEIVING:
                        if(mySerial.available() >= 10){// only read data, if a full packet was received, at least 10 bytes
                            // Here you need to decode the binary data and handle it accordingly (for example printing in the wanted format)
                            // Reset rec_state afterwards to be ready for the next time, that data is ready to read
                            rec_state = IDLE;
                        }
                        break;
                    }
                }
            }
        }

    That might seem like a bit of overkill, but the concept is very important in the Arduino world and it is very powerful. Also it makes it easier to accommodate workflow structures.

  [1]: https://arduino.stackexchange.com/questions/70544/how-do-i-repeat-else-if-cmd-3-until-i-press-another-cmd/70545#70545
  [2]: https://arduino.stackexchange.com/questions/63488/wanted-to-control-2-servos-with-serial-read/63491#63491

body:
Hi and welcome to the wonderful world of Arduino. It appears that you have picked-up Arduino with ease. Your program is almost there. Your wiring connection diagram looks to be correct.

When I am doing a project like this, I won't write my full application first. Instead I write a series of test programs to make sure each chunk is performing exactly as I want it to.

I would start by writing a program that just passes the serial information recieved from the Sound Level Meter and displays it on the serial monitor. Something similar to this:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup()
    {
      // Open USB serial communications
      Serial.begin( 2400 );
      Serial.println("USB Serial is up and running");

      // set the data rate for the SoftwareSerial port
      mySerial.begin( 2400 );
    }

    void loop()
    {
      if ( mySerial.available() )
      {
        // Write the serial from the S.L.M. to the USB (debug) serial port
        Serial.write( mySerial.read() );
      }

      if ( Serial.available() )
      {
        // Write the serial from the USB (debug) serial port to the S.L.M.
        mySerial.write( Serial.read() );
      }
    }

This program should be enough to communicate with the Sound Level Meter. But this leads me to my first concern - choice of serial monitor.

While the Arduino built in serial monitor is adequate it is only really good for sending/recieving text. (Plus it sends a CR/LF every time you hit enter.) I can see straight away that you require to send/recieve hex numbers. Hex numbers won't display well on the serial monitor.

Instead I prefer to use a terminal program by "der-hammer" called [hterm][1]. ([Screenshot here][2]). It lets you view the input in ASCII, hex, bin and decimal. Likewise it lets you send ASCII, hex, bin and decimal or a mixture of each. When sending information, you can configure it so that it finishes the data with either a line feed, a carriage return, both or none.

By the sound of it, you don't want a CR or LF at the end of the data you send. So in the "Input Options" set the "Send on enter" to "None".

For the recieved data, you need to view that in hex so make sure the "hex" box is checked just above the recieved data. (Uncheck "ASCII".)

You could create a loop-back test by removing the Sound Level Meter and instead link the RS232 Rx to the RS232 Tx. This will allow you to see on hterm exactly what the Sound Level Meter sees when you send data.

----

**Issues with your program**

      if (mySerial.read() == 0x10) {
        //mySerial.write(0x20);
        Serial.println("Data available");
        Serial.println(mySerial.read());
      }

The section of code will only read one byte of data after it has detected `0x10` (See the [Serial.Read() reference page][3]). Anything more than that will get consumed by the next time the `if` statement checks the serial line for `0x10`.

I notice in the line `Serial.println(mySerial.read());` that you are reading the data in (which is in hex format) but then trying to write it out in ASCII by using the `println()` function. This will not give you the output you desire.

Also, after detecting `0x10` it reads the software serial line for one more byte - meaning if there is nothing following the `0x10` then the `mySerial.Read()` command will hang for 1s until it timeouts.

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

As others have pointed out, using the serial monitor will send this as ASCII characters (and include a CR/LF character(s)) instead of the hex value that you want. Kudos is given to you, that you chose `mySerial.write()` instead of `mySerial.println()`.

----

**My Take on Your Program**

*The follwoing code is untested.*

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(2400);
      // The wait for serial port to connect is not needed for Arduino Uno
      Serial.println("USB Serial is up and running");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(2400);
    }

    void loop()
    {
      if ( mySerial.available() )
      {
        int recievedByte = mySerial.read();
        Serial.write(recievedByte);    // Send to USB serial - assuming using hterm in hex
        if ( recievedByte == 0x10 )
        {
          mySerial.write(0x20);
        }
      }

      // You could remove the following code - data must be in hex.
      if ( Serial.available() )
      {
        mySerial.write(Serial.read());
      }
    }

  [1]: http://der-hammer.info/pages/terminal.html
  [2]: https://www.der-hammer.info/terminal/bilder/term_071linux_large.png
  [3]: https://www.arduino.cc/reference/en/language/functions/communication/serial/read/


body:
Hii I have a big project, and found this when I tried to remove all the test code.

To summarize:

 1. I have a variable that I use as a buffer for string operations called **char internalbuffer[32]** declared in my file **[xstrings.h][1]**, it is very important and it is used a lot in the other files.
 2. If I call, in Setup, **Serial.println(internalbuffer) twice or more**, the arduino will **run normally**.
 3. If I call, in Setup, **Serial.println(internalbuffer) once or not at all**, the arduino **will NOT run** any code.
4. I tried, with no result, referencing in other ways internalbuffer.

You can see the main.cpp file **[here][2]**. (you can check the entire repo **[here][3]**)

My setup:

 - [Arduino Nano][4] (Clone) Old bootloader
 - [SSD1306 (Clone) Oled 128x32][5] with **[ss_oled][6]** library as controller
 - 3 DIY Buttons
 - [VS Code][7] with [platformio][8] installed.

I've been trying to fix this myself for 2 days now, but got nothing and I'm pretty new to c++ and arduino, any tips or guidance is accepted.

Edit:

**What I have tried:**

 - Replacing the 2 `Serial.println(internalbuffer)` to printing any string, didn't work.
 - Instead of the serial prints, add a `delay(x)`, tried from 10ms to 5000ms didn't work either.
 - Removing `while(!Serial)` seems to have no effect, so I removed it.

**New things I've discovered:**
 - Moving the serial prints out of the `if (rc != OLED_NOT_FOUND)` that checks for the oled initialization is not working, so that's new.
 - **There is a special place, that if I place the prints there, the arduino keeps calling setup like it was the loop function or something.**

I´ve created a **[pastebin][9]** showing these last 2 items more clearly.

  [1]: https://github.com/Tilation/nanorpg/blob/main/src/xstrings.h
  [2]: https://github.com/Tilation/nanorpg/blob/main/src/main.cpp
  [3]: https://github.com/Tilation/nanorpg
  [4]: https://nakamaelectronica.com.ar/169-thickbox_default/arduino-nano-5.jpg
  [5]: https://images-na.ssl-images-amazon.com/images/I/41X4YLwaQXL._AC_SY355_.jpg
  [6]: https://www.arduino.cc/reference/en/libraries/ss_oled/
  [7]: https://code.visualstudio.com/
  [8]: https://platformio.org/
  [9]: https://pastebin.com/eVB6kubV

title: Arduino freezes if I do NOT do Serial.println() at least TWICE

Answers: 0


body: Hi guys I’m new to this forum and also not much experience about led lights question already asked but didn’t get any detailed answer I want to know can I provide working data signal to 2 different 5v and 12v addressable led strips or what should I do to work them in same patterns at same time it will be really big help please and thanks in advance I’m sure I’m at right forum because usually I get all my answers by you guys without even asking

title: How to use 5v and 12v addressable led strip together

Answers: 0


body:
I'm looking to calibrate a load cell and for some reason, when I open both the serial monitor and plotter, they both come up blank. My plotter is set to the corresponding 9600 baud, however, this doesn't seem to change anything.

here is the code below:

```
#include "HX711.h"
#include <Servo.h> // Include the Servo library

#define calibration_factor -7050.0 //This value is obtained using the SparkFun_HX711_Calibration sketch

#define LOADCELL_DOUT_PIN  3
#define LOADCELL_SCK_PIN  2
int servoPin = 5; // Declare the Servo pin

HX711 scale;

Servo Servo1; // Create a servo object
float units;

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 scale demo");

  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale(calibration_factor); //This value is obtained by using the SparkFun_HX711_Calibration sketch
  scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0

  Serial.println("Readings:");

  Servo1.attach(servoPin);  // We need to attach the servo to the used pin number
}

void loop() {
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
  Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
  Serial.println();

 Serial.print("Reading: ");

 units = scale.get_units(10);
     if (units > 3.35 && units < 3.45)
     {
       Servo1.write(180);
       delay(1000);
       Serial.print("Success. Door is now OPEN!");
     }

       else
     {
       Servo1.write(0);
       delay(1000);
       Serial.print("Success. Door is now CLOSED!");
     }

}
```

here are screenshots of the potter and monitor:

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

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

  [1]: https://i.stack.imgur.com/0lMPQ.jpg
  [2]: https://i.stack.imgur.com/LFBcy.jpg

title: Serial monitor and plotter coming up blank

Answers: 0


body:
I have a HC-05 module, directly connected to an STM32 via UART interface and connected simultaneously to a mobile application in order to exchange
real time data. I am trying to reduce the power consumption of my HC-05 BT module. After few researches, I discovered that if I set the command AT+IPSCAN and
put the Query duration (2nd parameter) and the Call duration (4th parameter) to 1, the current dramatically decreases. Thus, the energy which the BT
module consumes decreases as well. My problem is I didn't understand how and why it decreases ? What are exatly the parameters AT+IPSCAN and what each one
does mean ?
Thank you for providing me a detailed description of the AT+IPSCAN command as well as its parameters.

title: AT+IPSCAN HC-05 Command

Answers: 0


body:
I am trying to have a 2way serial communication between LabVIEW and Arduino. I tried to make a basic program to grasp the concept but it does not seem to work.

Labview (2 int values) >> Arduino read

Arduino (1 int value) >> Labview read

Here, my LabVIEW program has 2 double variables which I put in numbers (they will later be cast to an int). Then, it is put into an array and converted to a comma-separated integer string. This is then written to the VISA port.

On the Arduino side, the serial port is read using the serial.parseInt function. Then the int is then converted into a 2-byte array which is then written to the serial port.

This is then read by the LabVIEW with VISA read and the string is converted to a byte array and reconstructed into an I16 integer.

Currently, the results are as follows:
The sent number are 80 and 80 and after being received by the Arduino and relayed back, the results displayed is 6961 as a string and 26977 in int form.

The arduino program works with the serial monitor where if the number 19789 was put in, it would output MM.

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

```
void setup() {
  Serial.begin(9600);
  while(!Serial){;}
  Serial.println("serial ready");
}

int input;
int input2;
void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available()>0){
    input = Serial.parseInt();
    input2= Serial.parseInt();
  }

 byte buff[2];
  if (Serial.read() == -1){
    buff[1] = (byte)input;
    buff[0] = (byte)(input>>8);
    Serial.write(buff,2);
  }
  delay(100);
}
```

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

  [1]: https://i.stack.imgur.com/9e1fN.png
  [2]: https://i.stack.imgur.com/ILEn9.png

title: arduino labview basic serial communication

Answers: 0


body: I am asking how to enter from the data mode to the AT command mode without restarting and disconnecting any power supply. In other words, I am trying to make a driver to handle HC-05 module and now I have to switch between DATA mode to AT mode. When I try to switch backwards, it worls ( by putting off the EN pin and then send “AT+RESET” ) but from DATA mode to AT Mode I can’t reset the module. Anyhelp please ?

title: How to switch HC-05 from DATA mode to AT mode?

Answers: 1

body:
I am pretty certain there is no way to enter command mode from data mode without resetting the whole module.  The only way to enter command mode is by setting the KEY pin high, and that pin is only read during the initialization phase of the module - and that means either a power cycle / reset, or a command-initiated reset.

You could either:

* Provide a power control circuit which turns the module on and off (MOSFETs are good for this), or
* Modify the module to attach a wire to pin 11, the RESET pin, and pulse that LOW to reset into command mode (I assume LOW, since that's the most common, though I haven't found anything to confirm it yet).


body:
I have a fairly complex autonomous robot program that is getting into trouble when executing controlled turns.  I constructed a very small program to test just the turns, and this works fine.  When I port the turn algorithm into the main program, however, it behaves erratically, and I suspect the culprit is a TIMER5 interrupt ISR that is in the main program but not in the test program.

To troubleshoot, I added the TIMER5 ISR code to the test program, and I want to be able to enable and disable the ISR using keyboard commands, to see if I can cause the anomalous behavior with the ISR enabled, and prevent it by disabling the ISR.

From reading about TIMER interrupts, it appears that setting TIMSKx (TIMSK5 in my case) to 0 will disable the ISR, and setting bit 0 to 1 (using TIMSKx |= OCIExA) will enable it. I have a 'CheckForUserInput()' routine which allows me to input commands from the keyboard, so I added a 'T' command, as follows:

    switch (incomingByte)
    {
    case 0x54: //ASCII 'T'
    case 0x74: //ASCII 's'
     Serial.println(F("Toggle TIMER5 Enable/Disable"));
     if (TIMSK5 == 0)
     {
      Serial.println(F("Enable TIMER5"));
      TIMSK5 |= OCIE5A;
      mySerial.printf("TIMSK5 = %x\n", TIMSK5);
     }
     else
     {
      Serial.println(F("Disable TIMER5"));
      TIMSK5 = 0;
      mySerial.printf("TIMSK5 = %x\n", TIMSK5);
     }
     break;

I have an LED set up to blink each time the ISR fires, and I can see that I can stop the ISR from firing reliably with the first 'T' input, but I can't reliably restart it with the second 'T' command, even though I can tell from the printouts that the proper piece of code executed, like in the following output

    Opening port
    Port open

    Checking for MPU6050 IMU at I2C Addr 0x69
    MPU6050 connection successful
    Initializing DMP...
    Enabling DMP...
    DMP ready! Waiting for MPU6050 drift rate to settle...
    MPU6050 Ready at 0.52 Sec
    End of test - Stopping!
    I received: 63
    ENTERING COMMAND MODE:
    0 = 180 deg CCW Turn
    1 = 180 deg CW Turn
    A = Back to Auto Mode
    S = Stop
    F = Forward
    R = Reverse

           Faster
     8
    Left 4 5  6 Right
     2
           Slower
    Got D
    Got A
    Got 74
    Toggle TIMER5 Enable/Disable
    Disable TIMER5
    TIMSK5 = 0
    Got D
    Got A
    Got 74
    TEnabling DMP...
    DMP ready! Waiting for MPU6050 drift rate to settle...
    MPU6050 Ready at 0.52 Sec
    End of test - Stopping!
    I received: 63
    ENTERING COMMAND MODE:
    0 = 180 deg CCW Turn
    1 = 180 deg CW Turn
    A = Back to Auto Mode
    S = Stop
    F = Forward
    R = Reverse

           Faster
     8
    Left 4 5  6 Right
     2
           Slower
    Got D
    Got A
    Got 74
    Toggle TIMER5 Enable/Disable
    Disable TIMER5
    TIMSK5 = 0
    Got D
    Got A
    Got 74
    Toggle TIMER5 Enable/Disable
    Enable TIMER5
    TIMSK5 = 1
    Got D
    Got A

I'm sure I'm doing something wrong in the way I am attempting to re-enable the TIMER5 ISR, but I really can't see it.  Anyone have a clue?

TIA,

Frank

title: How do I temporarily disable TIMER5 Interrupts?

Answers: 1

body:
You wrote:
> ```c++
> TIMSK5 |= OCIE5A;
> ```

You mean

```c++
TIMSK5 |= _BV(OCIE5A);
```

or, equivalently,

```c++
TIMSK5 |= 1 << OCIE5A;
```


body:
I am reading from loadcell and calculating the average of last 10 readings. But when the load cell reads something more than 3800 g the average gets negative, how? The mass I read are not negative numbers. I have been trying to find my mistake but I am not able to. Any help?

```
#include "HX711.h"

const int numReadings = 10;
const int LOADCELL_DOUT_PIN = 8;
const int LOADCELL_SCK_PIN = 10;
int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
int mass  =0;
long reading = 0;

HX711 scale;

float a = 0.0088;
float b = 2009.7;

void setup() {
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
}

void loop() {
  if (scale.is_ready()) {
    // read from the sensor:
    reading = scale.read();
    // convert to mass
    mass = int((a*reading)-b);
    // subtract the last reading:
    total = total - readings[readIndex];

    Serial.print(int((a*reading)-b));
    readings[readIndex] = mass;
    // add the reading to the total:
    total = total + readings[readIndex];
    // advance to the next position in the array:
    readIndex = readIndex + 1;

    // if we're at the end of the array...
    if (readIndex >= numReadings) {
      // ...wrap around to the beginning:
      readIndex = 0;
    }

    // calculate the average:
    average = total / numReadings;
    // send it to the computer as ASCII digits

    Serial.print("   ");
    Serial.print(average);
    Serial.println("");
    delay(1000);        // delay in between reads for stability
  }
  else{
    Serial.print("loadcell not found!");
  }
}
```

title: Average of 10 readings, wrong

Answers: 2

body:
As already commented by Majenko, the problem in integer wraparound. One solution would be to get rid of that `total` variable and calculate every new average based on the previous average and the mass you are replacing in the array, using this formula:

    new_average = old_average + (mass - readings[readIndex]) / numReadings

So your code would look like:

      if (scale.is_ready()) {
        // read from the sensor:
        reading = scale.read();
        // convert to mass
        mass = int((a*reading)-b);

        // calculate the new average:
        new_average = average + (mass - readings[readIndex]) / numReadings;

        Serial.print(int((a*reading)-b));
        readings[readIndex] = mass;

        // advance to the next position in the array:
        readIndex = readIndex + 1;

        // if we're at the end of the array...
        if (readIndex >= numReadings) {
          // ...wrap around to the beginning:
          readIndex = 0;
        }

        // set the average:
        average = new_average;

        // send it to the computer as ASCII digits
        Serial.print("   ");
        Serial.print(average);
        Serial.println("");
        delay(1000);        // delay in between reads for stability
      }

Just don't forget to add a declaration for `new_average` to the beginning of your code.

body: Another option would be use 'long' as a variable type for total.   Depending on your application, you also might look into an exponentially weighted moving average (EWMA); it can de-emphasize older data points, if that is an issue.


body:
I'm trying to simulate dynamic temperature using a small set of data with ESP32. I've just realized that the relay doesn't change the status if there is some variation of the temperature upper or lower the threshold.

If the temperature starts below the modeled temperature, the relay will turn on but, once it reaches the model's temperature or exceeds it, the status doesn't change, and the system will warm up till the next model.

Am I missing something in my code?

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <NTPClient.h>
    #include <WiFi.h>
    #include <WiFiUdp.h>

    WiFiUDP ntpUDP;

    NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 7200, 60000); //UTC+1 (Europe)

    unsigned long current_time;

    #define WIFI_AP "xxxxx"
    #define WIFI_PASSWORD "xxxxx"
    //WiFi SETUP
    WiFiClient wifiClient;
    int status = WL_IDLE_STATUS;
    unsigned long lastSend;

    const int oneWireBus1 = 0;
    OneWire oneWire1 (oneWireBus1);
    DallasTemperature sensors1 (&oneWire1);

    const int relay1 = 02;

    struct SetPoint {
      unsigned long time;
      float temperature;
    };

    #define DATA_SIZE  17

    SetPoint scen1[DATA_SIZE] = {
      {1622652330,26.97},//18h
      {1622652390,25.62},
      {1622678400,24.87},
      {1622689200,24.16},
      {1622700000,23.86},
      {1622710800,25.17},
      {1622721600,26.41},
      {1622732400,27.22},
      {1622743200,26.78},
      {1622754000,25.83},
      {1622764800,25.1},
      {1622775600,24.6},
      {1622786400,24.24},
      {1622797200,26.81},
      {1622808000,29.35},
      {1622818800,29.38},
      {1622829600,30.5}
    };

    unsigned int pos = 0;

    void setup() {
      Serial.begin(115200);
      sensors1.begin();
      pinMode(relay1, OUTPUT);
      InitWiFi();
      lastSend = 0;
      timeClient.begin();

    void loop() {

      sensors1.requestTemperatures();
      float temperature1 = sensors1.getTempCByIndex(0);

      timeClient.update();

      long current_time =  timeClient.getEpochTime();

      if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
        if (temperature1 < scen1[pos].temperature) {
          digitalWrite (relay1, HIGH);
        }
        else if (temperature1 > scen1[pos].temperature) {
          digitalWrite (relay1, LOW);
        }
        pos++;
      }

      Serial.println(timeClient.getEpochTime());
      Serial.println(timeClient.getFormattedTime());
      Serial.println(pos);
      Serial.println(scen1[pos].temperature);
      Serial.println(scen1[pos-1].temperature);
      Serial.print("Temperature Censius - Sensor 1: ");
      Serial.print(temperature1);
      Serial.println(" ºC ");
      delay(3000);

    }

(UPDATE)

Replacing the first `if` with `while` doesn't change anything.

The code works when taking `if` / `else if` out of nested `if`, but in this case I'm not able to increase time (the `pos++` is also commented), and define limits according to the array size.

    //  if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
        if ((temperature1 < scen1[pos].temperature)&& (current_time >= scen1[pos].time)) {
          digitalWrite (relay1, HIGH);
        }
        else if ((temperature1 > scen1[pos].temperature)&&(current_time >= scen1[pos].time)) {
          digitalWrite (relay1, LOW);
        }
    //    pos++;
    //  }

title: Error trying to simulate temperature dynamically

Answers: 1

body:
I have to remove the `pos++` from if statement to have digitalWrite working again according to captured temperature:

      if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
        if (temperature1 < scen1[pos].temperature) {
        digitalWrite (relay1, HIGH);
        }
        else if (temperature1 > scen1[pos].temperature) {
        digitalWrite (relay1, LOW);
        }
       }

Obviously this isn't updating time and the system gets stuck at time 0 of the array.

(UPDATE)

As well observed by Dave Newton, the previous observation is pointless to really fix the problem.

The problem was fixed taking the `if` statement that control the relay from inside the one controlling the time.

Now I can simulate a time interval defined with the array and use the temperature (also present in the array) to turn on/off the relay that controls the heater and simulates environment temperature:

First I created a function that will work as a thermostat:

    void set_thermostat() {
      sensors1.requestTemperatures();
      float temperature1 = sensors1.getTempCByIndex(0);

      if (temperature1 < scen1[pos].temperature) {
        digitalWrite (relay1, HIGH);
      }
      else if (temperature1 > scen1[pos].temperature) {
        digitalWrite (relay1, LOW);
      }
    }

Then I can it at the `loop` function, outside the statement that increases the time, based on the one defined by the array:

      if (pos < DATA_SIZE && current_time >= scen1[pos].times) {
        pos++;
      }

      set_thermostat();

This reproduces exactly what I've been looking for, with real-time control of the temperature comparing the environmental one with the model.


body:
I would like to power my arduino nano with a 9V battery, but I would also like to measure the voltage of the battery to know its charge level.
Can I use the [MAX471 Voltage Current Sensor][1] module by connecting the VIN pin to my battery and VOUT to my arduino ?

  [1]: https://aliexpress.com/item/32672702701.html?src=google&albch=shopping&acnt=248-630-5778&isdl=y&slnk=&plac=&mtctp=&albbt=Google_7_shopping&aff_platform=google&aff_short_key=UneMJZVf&&albagn=888888&isSmbAutoCall=false&needSmbHouyi=false&albcp=10191220517&albag=107473525088&trgt=743612850874&crea=fr32672702701&netw=u&device=c&albpg=743612850874&albpd=fr32672702701&gclid=Cj0KCQjw2NyFBhDoARIsAMtHtZ60kZjqZf6Pn0b21O_8pnOQl4r2uiEo-iRub2k4lLdjbPr-t_sww7MaAvAQEALw_wcB&gclsrc=aw.ds

title: Measuring the battery level powering the arduino

Answers: 1

body: If you want measuring a "battery level" in mAh for example, you must measure Voltage AND Current, so INA219 is a better deal (it is a I2C control).


body:
[![How can i draw a diagram out of this?][1]][1]

  [1]: https://i.stack.imgur.com/ohTYt.png
I need help to draw a diagram of this picture
the project include an Arduino nano, dht11 sensor, power module IRF520, 12V power supply and a fan

title: How can i draw an electronic diagram of this?

Answers: 1

body:
See [Rules and guidelines for drawing good schematics](https://electronics.stackexchange.com/q/28251/2191) on electronics.stackexchange.com.

I'm no expert but perhaps some of what I have found will be of help.

To produce a clear easy-to-read useful schematic it doesn't really matter what tools you use. This website has a reasonable schematic editor so I suggest you could try that to start with.

Other tools I have tried include KiCAD, EasyEDA and Fritzing. KiCAD is maybe a bit hard to start with and Fritzing I find is very troublesome - It's good for the kind of breadboard layout diagram it was originally designed for. I have really enjoyed using EasyEDA. Other notable tools include Eagle. All these are free or have free versions for hobbyists. Beyond that are more capable and sophisticated professional tools.

Drawing a good schematic is an art and taking care of small details makes a big difference to how useful the diagram is.

The main features that I find make schematics for me to read are

- Ground connections at bottom edge of diagram.
- Positive voltage connections at top edge of diagram.
- Left to right flow for signals and power (e.g. battery at left, microprocessor in middle, LEDs, motors etc at right)
- Avoid having wires cross. Adjust the pin positions on an IC symbol to make this possible.
- Label everything clearly but don't let text overlap with anything else.

<!-- 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/0RdSj.png)

<!-- End schematic -->

The way you appear to be powering these modules seems a bit eccentric but this would be how I might draw that as a block-level schematic.


body:
I need to modify an existing library that relies on being able to detrmine what board / processor the code is being run on. To do this, it uses definitions such as this for an Arduino Mega:
```cpp
// Arduino Mega
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
```
I need to update the library for a further 2 boards, namely the Raspberry pi pico (mbed os) and the Robotis OpenCR.

I can't seem t find where the processor name is actually defined. If someone could point me in the right direction, that would be great. Thanks.

Edit:
If anyone knows what the equivelent define is for the raspbery pi pico - rp2040, that would be fantastic!

title: Where are the programatic definitions for different processors stored?

Answers: 1

body:
They are defined by the compiler itself, and based on the name of the microcontroller passed to the compiler as (for AVR GCC) `-mcpu=<mcu name>`.

You can list the defines for a version of GCC using (for example for AVR gcc):

```
avr-gcc -mmcu=atmega328p -dM -E - < /dev/null
```

Not sure what you'd use on Windows for `/dev/null`. Different target compilers use different flags to define the MCU, and you of course need to know the MCU the board uses to pass to the compiler.

You will have to investigate what relevant flags are passed to the compiler for your desired chips, and you can find those by looking in the platform.txt file for the core associated with the board.


body:
I am building a project using bluetooth control as well as an ir sensor. The logic behind my program is when I press a key I want my robot to execute a series of program and while the program is executing if an obstacle is detected I need the motors to stop and then continue from the same point after the obstacle is removed. I am uploading my code for ref.

    #include <Servo.h>
    #include <AFMotor.h>
    #include <Servo.h>
    int obstaclePin = 12;
    int obstacle = LOW;
    AF_DCMotor motor1(1);
    AF_DCMotor motor2(2);
    AF_DCMotor motor3(3);
    AF_DCMotor motor4(4);
    Servo myservo1;
    Servo myservo2;
    int pos = 0;

    char bt='S';
    void setup()
    {
      Serial.begin(9600);
      pinMode(obstaclePin,INPUT);
      myservo1.attach(10);
      myservo2.attach(9);
      motor1.setSpeed(100);
      motor2.setSpeed(100);
      motor3.setSpeed(100);
      motor4.setSpeed(100);
      Stop();
    }

    void loop() {
     bt=Serial.read();
      if(bt=='F')
    {
      forward();
      delay(2000);
      backward();
      delay(2000);
      left();
      delay(2000);
      right();
      delay(2000);
      Stop();
    }

    if(bt=='B')
    {
    forward();
     delay(8000);
     left();
     delay(1500);
     ServoControl();
     delay(500);
     backward();
     delay(1000);
     right();
     delay(3000);
     forward();
     delay(8000);
     Stop();
    }

    if(bt=='L')
    {
     forward();
     delay(10000);
     left();
     delay(1500);
     ServoControl();
     delay(500);
     backward();
     delay(1000);
     right();
     delay(3000);
     forward();
     delay(10000);
     Stop();
    }

    if(bt=='R')
    {
     forward();
     delay(12000);
     left();
     delay(1500);
     ServoControl();
     delay(500);
     backward();
     delay(1000);
     right();
     delay(3000);
     forward();
     delay(12000);
     Stop();
    }

    if(bt=='S')
    {
     Stop();
    }
    if(bt=='O')
    {
      servoOpen();
    }
    if(bt=='C')
    {
      servoCLose();

    }

    }
    void forward()
    {
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
    }

    void backward()
    {
      motor1.run(BACKWARD);
      motor2.run(BACKWARD);
      motor3.run(BACKWARD);
      motor4.run(BACKWARD);
    }
    void left()
    {
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(RELEASE);
      motor4.run(RELEASE);
    }
    void right()
    {
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
    }
    void Stop()
    {
      motor1.run(RELEASE);
      motor2.run(RELEASE);
      motor3.run(RELEASE);
      motor4.run(RELEASE);
    }
    void servoOpen()
    {
      for (pos = 0; pos <= 100; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo1.write(pos);
        myservo2.write(pos);
      }
    }

    void servoCLose()
    {

      for (pos = 100; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo1.write(pos);
        myservo2.write(pos);
      }
    }
    void ServoControl()
    {
      for (pos = 0; pos <= 100; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        myservo1.write(pos);
        myservo2.write(pos);
        delay(40);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 100; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo1.write(pos);
        myservo2.write(pos);
        delay(40);                       // waits 15ms for the servo to reach the position
      }
    }
    void obstacleD()
    {
      obstacle = digitalRead(obstaclePin);
       if(obstacle == HIGH)
      {
        Stop();
      }
    }

I don't know where to add the obstacle detection so it would work like an interrupt. the main problem I was experiencing was that whenever I tried running the code on my Arduino it would completely change the logic and noting would work even if I put the command in the serial monitor until an obstacle was detected. I'm a newbie at programming and using Arduino.

title: I need help with my final year project

Answers: 1

body:
Your main problem is, that you are using many blocking calls, especially `delay()`. During that the Arduino cannot do anything else. You need to use a non-blocking coding style, doing multiple things one after another in fast succession. Here the style from the `BlinkWithoutDelay` example using `millis()` is very useful. There are lots of tutorials about that online (on this site or many others), so I will not go into detail, how that works.

---

**Quick fix:** If you just need a quick fix and the code structure of your project is not relevant for your grade, you can do the following:

Replace the `obstacleD()` function with one, that will also wait for a specific time and also check the IR sensor during that time. Something like this:

    void obstacleD(unsigned long wait, void (*function)(void)){
        unsigned long start_time = millis();
        unsigned long already_waited = 0;
        while(millis()-start_time < wait-already_waited){
            if(digitalRead(obstaclePin)){
                already_waited += millis()-start_time;
                Stop();
                while(digitalRead(obstaclePin));
                start_time = millis();
                function();
            }
        }
    }

Then in the rest of your code instead of `delay(1000)` (or similar) you are calling

    obstacleD(1000, forward);

The first parameter is the waiting time, the second one is the function, that was lastly called (since we need to recall it, if an obstacle is found and then removed). We are noting the start time of the function into `start_time`. The first while loop will loop, until we waited as long as provided (difference between current time and start time will then be greater than the wait time minus the time we already waited). In that loop we are checking the IR sensor pin. If it reads HIGH, we add the elapsed time to our `already_waited` variable, stop and then loop while the IR sensor pin stays high. When the pin goes LOW again we leave this inner while loop, update to our new `start_time` and again execute the function to start the motors again. The code should continue the path like without an obstacle, even if multiple time an obstacle is placed during one path element.

Note, that the above code is not tested in any way. You might need to make minor changes.

---

**Interrupt quick fix:** You could implement the stopping on obstacle with an actual interrupt. Something like this:

    void obstacle_detected(){
        while(digitalRead(obstaclePin));
    }

    void setup(){
        ...
        attachInterrupt(obstaclePin, obstacle_detected, RISING);
    }

Though this is also not a good solution, since you totally block any other code, until the obstacle is removed, including receiving serial data (one byte is received by the hardware, but that has to be read by an interrupt. If another byte is send before that, the original byte is lost). Normally you would only set a flag in the ISR (interrupt service routine), but your main code isn't ready for using that flag correctly.

---

**The good-structured-code way:** To get the desired behavior with a good structured code, you need to completely restructure/rewrite your current code. As mentioned above you need to create a code, that does not block for long times, but only does things, if they need to be done at that time, and otherwise execute other code. You need to learn the usage of `millis()`.

Also your code would greatly benefit from a Finite State Machine (FSM), as Majenko already wrote in a comment. Here you first draw a diagram with your complete behavior structure, divided up into states, that do exactly one thing. The states are connected by state transitions (arrows from one state to another) (and we can even repeat a state by drawing an arrow from a state back to itself). Then you can convert that into a code structure using a state variable (integer or enum) and a `switch` statement, where each case has the code for one state. You can look at my answer to [this question][1] for more information. Or you can search for the term "finite state machine" or "FSM" on this site or google (for google you maybe should add "arduino" to the search query to get relevant results).

All in all you would create a code, that handles the wanted behavior without any hardware interrupts (not really needed here) and which is easily extendable, without getting problems with the program flow.

---

Note:

The for loop in `servoCLose()` is totally unnecessary. You don't have any delay to slow it down, so it will go to the end position in way less time, than the motor needs to even start moving. Just use `Servo.write()` one single time there with the desired angle. That is enough, unless you want it to move slowly. Then you would need a way to delay between the writes (either `delay()` or with `millis()`, depending on your then overall approach).

  [1]: https://arduino.stackexchange.com/questions/63488/wanted-to-control-2-servos-with-serial-read/63491#63491


body:
I have high current usage For my circuit as you can see below ([link][1]):

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

 I like to power Arduino when it is not connected to PC by **USB Connection**, So I want to add **one external power supply** and connect it's **GND** And **5V** to Arduino **GND** And **5V** pins.

So with this new circuit, I have **two power supply** for **Arduino uno** as you can see below: :

1-USB Connection to PC

2- Powering the Arduino by External Power Supply and LM7805

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

So I Asked here about connecting two power supply for Arduino (external power supply and PC USB Connection) and check this circuit Safeness for USB Port of PC or the Arduino.

Thanks.

  [1]: https://github.com/Startup-Data/UN-Hakim-PCR/tree/main/Arduino/Temperature
  [2]: https://i.stack.imgur.com/6SlOW.jpg
  [3]: https://i.stack.imgur.com/y6exq.png

title: USB and LM7805 both to power Arduino

Answers: 0


body:
I want to be able to control multiple LED strip via bluetooth with one arduino.
I coded my own android app and everything work fine with one or two led strip with few pixel. But as soon as I had to many pixel data send by BT is missing a few byte (ex "colfff5dff" instead of "color fff5dff"). It doen't happen every time but it's unrealiable.
I feel like sending data to the led strip take so many time that it skip some letter.

I'm ussing dsd tech hc-05 with an arduino UNO R3 and a esp8266 led strip.

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

#ifdef __AVR__
 #include <avr/power.h>
#endif

//SoftwareSerial blueTooth(13,12);

#define PIN       5
#define SIZE      200

#define BRIGHTNESS 200

enum MODE {FIXED, LOOP_RGB, RUNNING, RAINBOW};
enum MODE mode = FIXED;

Adafruit_NeoPixel strip(SIZE, PIN, NEO_RGB + NEO_KHZ800);

int lastTime;

uint32_t color;
char Incoming_value = 0;
char bufferStr[100];
int bufferIndex = 0;

void setup() {

  Serial.begin(9600); //open the serial port
  Serial.setTimeout(10);
  strip.begin();
  strip.show();
  strip.setBrightness(50);

  color = Adafruit_NeoPixel::Color(0, 255 ,0 );
}

void loop() {
  if(Serial.available() > 0)
  {
    String s = Serial.readString();
    Serial.print(s);

    //I've tried some other way like read();  readString();  readBytes(); readBytesUntil();

    /*
     * ---- not needed for the issue
     */
  }
  switch (mode){
    case FIXED : fixedMode(); break;
    case RUNNING : runningLights(); break;
    case RAINBOW : rainbow(); break;
    }
    showAll();
}

void parseBlueTooth(){
  //---- not needed for the issue
}

void fixedMode(){
  setAll(color);
  showAll();
}

void rainbow(){
  //---- not needed for the issue
}

void runningLights() {
  //---- not needed for the issue
}

void setAll(byte r, byte g, byte b) {
  setAll(Adafruit_NeoPixel::Color(r,g,b));
}

void setAll(uint32_t color) {
  strip.fill(color, 0, SIZE);
}

void showAll(){
  long curTime = millis();
  if(curTime - lastTime >16){
    if(strip.canShow()) {
      strip.show();
    }
    lastTime = curTime;
  }

}
```

title: Issue with bluetooth and a large number LED strip

Answers: 3

body:
I am working with HC-05 also and retrieving files over it.
I send commands and get files back over Bluetooth.  The speed of bluetooth _should_ be fine.  (Although you need to set it faster -- mine's at 38400)

Up in your `setup()` loop do:

    Serial.begin(38400)

Also your code to read off serial is a bit different.

You just need the following:

    while (Serial.available()){
        command = Serial.read();
    }

I was sending String-based commands but just today I decided to change them to 1 byte commands because it is much easier to deal with in a switch statement.  In the code above my `command` variable is a `byte`.

Then my switch looks like the following in loop():

    switch (command){
        case 49: { // ASCII Char 1 - get Temperature
          SW_Serial.print(getString(currentRoom) + " : " + currentTemp);
          // CALL YOUR SPECIFIC CODE TO DO EACH THING IN EACH CASE
          break;
        }
        case 50: { // ASCII char 2 - start data write
          // #### Allow Data Write start/stop to be done via BT
          // turns on logging of temp data (to SD card)
          // turn on data writing and LED
          // CALL YOUR SPECIFIC CODE TO DO EACH THING IN EACH CASE
    ...

Of course, each time through the loop you should set your `command` variable back to 0 (I use 0 as the no-command).  Otherwise you'll keep processing on the same command value.

body:
Your problem is that you are using two blocking routines that can't operate together. Both the SoftwareSerial and the NeoPixel objects take time to perform operations stopping anything else from happening.

* SoftwareSerial blocks inside an ISR while receiving a byte
* NeoPixel blocks with interrupts disabled while outputting the LED status

That means that while NeoPixel is being updated SoftwareSerial is incapable of receiving any data.  It was fine when you only had a few LEDs, since NeoPixel only took a very short time to update, but now that you have more LEDs it takes too long to update and SoftwareSerial can no longer work reliably.

In order to get around the problem you will have to use a hardware UART port. The Uno only has one - pins 0/1 and the `Serial` object. If you're not using that for communication with your computer you can connect your Bluetooth module there instead and use `Serial` instead of `SoftwareSerial` - however you will most probably need to disconnect your Bluetooth module every time you want to upload fresh code to your Arduino.

body:
IMHO, after reading Majenko and raddevus reply,
you may do something to "reduce missing data"

1. reduce baud rate (may be 9600), give more time for bluetooth data transfer.

2. add a checksum byte for your data.

Rererence :

https://lucidar.me/en/serialib/most-used-baud-rates-table/


body:
Here's my code:
```
#include <LiquidCrystal.h>
int rs = 11;
int rw = 10;
int en = 9;
int d0 = 1;
int d1 = 2;
int d2 = 3;
int d3 = 4;
int d4 = 5;
int d5 = 6;
int d6 = 7;
int d7 = 8;
LiquidCrystal lcd(rs, rw, en, d0, d1, d2, d3, d4, d5, d6, d7);

void setup() {
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  Serial.begin(4800);
  lcd.setCursor(0,0);
  lcd.print("Loading...");
  delay(3000);
  lcd.setCursor(1,1);
  lcd.print("waht");
}

void loop() {

}
```
And here's the output:
[![enter image description here][1]][1]

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

Also note the first line of text starts in the second column. I've tried with a different LCD and the same issue occurs. It seems to go one character further in ascii (ex: the '**.**'s become '**/**') if that's any clue to what's going on. In a separate program (exact same setup) I can print "Hello World" on the first line no problem. Anyone know why it's doing this and how to fix it? Thanks

title: LCD randomly goes one character further in the ascii table

Answers: 1

body:
Your Least Significant Bit is always 1 (Check the [ASCII table][1] to see this).
You might have a problem with your wiring, double check the pin you use and that the continuity is good.

Also, as [KIIV][2] said in comment, depending on the board you use, you might have a conflict with the serial port (Which pull the line high when not transmitting, explaining the result you get). Try moving pin 1 to another one.

  [1]: https://en.wikipedia.org/wiki/ASCII
  [2]: https://arduino.stackexchange.com/users/23841/kiiv


body:
I want to map the value range 0-63 like this:
```
x       y
0-15  = 0
16-31 = 1
32-47 = 2
48-63 = 3
```

However, using map function `y = map(x, 0, 63, 0, 3);` returns:

```
x       y
0-15  = 0
16-31 = 0
32-47 = 1
48-63 = 2
```

Is this due to truncating fractions, or something else?

Is there a better alternative?

title: How do i make this map() application work as intended?

Answers: 2

body:
`map()` doesn't *quite* work as you'd expect.  The formula is:
```
(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
```

And all those values are `long`, which is a "long" integer. So all operations are done as integers, and that means that you lose an awful lot of precision in the calculation, since all decimal components are completely ignored.

It means that you only get the maximum output when you put in the maximum input.

As Michael Keijzers notes your expected output is `x/16` (or `x>>4` in bitwise notation), and that can be achieved with `map()` if you set the maximum input to be 48, not 63.

However a simple right shift 4 bits (or divide by 16 if the compiler is clever enough to implement it as a right shift) is a more efficient solution by far, since the processing involved is almost negligible, whereas multiplying and dividing is a relatively expensive set of operations.

body:
You could try:

```c++
y = map(x, 0, 64, 0, 4);
```

Majenko showed you the formula used by `map()`. You can check that the
formula works nicely if you think in terms of half-open intervals:

[0, 64) → [0, 4)

But this is still way less efficient than a bit shift.


body:
I'm an Arduino beginner. I've got 2 x 12V DC water pumps

https://www.ebay.co.uk/itm/224461221015

plus 12V, 2A AC/DC adapter to feed them.

I would like to regulate the speed (flow) of the pumps programmatically by Arduino. My first idea was to use 2 channel Relay, however, it only supports two states - on/off. Then I discovered this DC Stepper Motor Driver:

https://www.ebay.co.uk/itm/274521887403

That seems to be a good fit in terms of specifications, but I'm not sure whether it will work with the pumps? It makes me think of whether the DC Stepper Motor Driver may work with only specific motors?

Thanks for any advice!

title: Regulate Water Pumps flow by DC Stepper Motor Driver

Answers: 2

body:
Yes, it will work.

You can control the speed of the water pumps with a PWM signal by using:

    analogWrite(PWM_pin, value)

Or you can use a cheap transistor like a P2N2222A; here is a [full tutorial][1].

  [1]: https://www.instructables.com/How-to-drive-a-DC-Motor-with-Transistor-Arduino-Tu/

body: Unfortunately after trying it does not work as expected. It has been mentioned that it must be a **BRUSHED** motor and most of these pumps on eBay are **Brushless**.


body:
The [ATmega328P data sheet][1] in table 29-11 on page 324 notes that the internal 1.1V reference (VBG) may vary between 1.0V and 1.2V. In [this answer][2] this is called "not stable or accurate".

Question: Is this "unstable" or "inaccurate" or even both if I define it as

   * "unstable" if it varies over the day, say with temperature or VCC or or some such.
   * "inaccurate" if it is a rather stable voltage for a specific Nano-board I have in hand, just not the typical 1.1V.

In the latter case I could measure the value accurately and scale my analog measurements with the measured value instead of the 1.1V.

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

title: Nature of the voltage reference instability of internal 1.1V reference of ATmega328P (Nano)

Answers: 1

body:
I would say it was "stable but not accurate". The internal reference uses a [bandgap voltage reference](https://en.wikipedia.org/wiki/Bandgap_voltage_reference), which is pretty stable over the operating temperature range of the IC.

The output of the bandgap reference *is* fed through an amplifier to buffer it, which may introduce some instability with temperature, but this is not documented so cannot even be estimated.

The inaccuracy comes from minor differences in the manufacturing process. These don't change over time, so once calibrated for a precise value of voltage reference you should not see much in the way of variance in that value for different temperatures or power supply fluctuations.


body:
I've tried to create a receiver code for receiving my data (really only want the ac/gy values and nothing else) and use the following main code for sending via C programming: https://github.com/YifanJiangPolyU/MPU6050/blob/master/main.c

the sending receiving code in Arduino this far is the following (that doesn't work):

    void do_send(osjob_t* j){
        // Check if there is not a current TX/RX job running
        if (LMIC.opmode & OP_TXRXPEND) {
            Serial.println(F("OP_TXRXPEND, not sending"));
        } else {
            // Prepare upstream data transmission at the next possible time.

    byte strArray[30];
        int i = 0;
        if(Serial1.available()>0) {
           while (Serial1.available()>0){
              strArray[i] = Serial1.read();
              i++;
           }
                // send the 6 bytes payload to LoRaWAN port 7 --> now port 1
                LMIC_setTxData2(1, strArray, sizeof(strArray), 1); //might need to be converted to type data, not char.

                digitalWrite(LED_BUILTIN, HIGH);    // turn the LED on by making the voltage HIGH                      //optional: for confirmation
        }
            }
        }
        // Next TX is scheduled after TX_COMPLETE event.
        //delay(60000);

I've noticed that I cannot send char arrays with LMIC function for the feather m0, so I tried receiving it as a byte array which works to send. Any help/suggestions/snippets of code etc. would be greatly appreciated.

title: Receiving code between atmega328P (C) and Feather m0 (Arduino)

Answers: 0


body:
I'm trying to send the temperature value from the DHT sensor to a raspberry pi through I2C.
Which is the best way to do it?. The temp value is a float, and I think I have to convert it to byte and send that with Wire.write() to the raspberry, is that right?.
Right now I'm sending bytes from the raspberry (with Python) to the Arduino (C++):
Python:

    from smbus import SMBus
    import time

    address = 0x8
    bus = SMBus(1)

    While True:
      bus.write_byte(address, 4)
      time.sleep(1)
      print(bus.ready_byte(address))

Arduino code:

    #include <Wire.h>
    #include <DHT.h>
    ...

    void setup() {
      dht.begin();
      Wire.begin(0x8);
      Wire.onReceive(receiveEvent);
    }

    void receiveEvent () {
      float temp = dht1.readTemperature();
      delay(1000);
      byte tempByte[4] = {temp, 0, 0, 0};
      Wire.write(tempByte[0]);
    }

So the raspberry is printing 0.

Thanks for any help.

title: Convert float to byte, from Arduino to Raspberry Pi i2c

Answers: 1

body:
First of all, if you want the Arduino to send data as a slave, it should
do so `onRequest()`, not `onReceive()`. Thus:

```c++
void setup() {
    Wire.begin(0x08);
    Wire.onRequest(handleRequest);
}
```

Next, as pointed out by chrisl in a comment, you should not delay within
the `onRequest` handler. I would go further and say that you should not
even call `dht1.readTemperature()`, as that could take too much time to
be done in interrupt context. Instead, have the main loop query the
sensor periodically, and have the latest reading always available:

```c++
volatile float temperature;  // latest valid reading

void loop() {
    float new_temperature = dht1.readTemperature();
    noInterrupts();
    temperature = new_temperature;
    interrupts();
    // ...
}
```

Note that the latest value is updated with interrupts disabled. This is
to avoid a data race that could happen if the Arduino receives a request
while it is in the middle of updating the value. Notice also that
interrupts are disabled during a very short time: just the time needed
to update the variable.

Lastly, to send the data, you can use the version of `Wire.write()` that
accepts a buffer of arbitrary length:

```c++
void handleRequest() {
    Wire.write((uint8_t *) &temperature, sizeof temperature);
}
```

The temperature will be sent LSB-first, as a float, formatted as per
IEEE 754. The Raspberry Pi should be able to digest it in this very same
format.


body:
I am using the Espressif ESP32_DevKitC_V4 with platformio, and i cannot flash the board. I read about the various "button dance" procedures, and [the ES32-WROVER and the ESP32-WROVER-B seem to behave differently as well][1].

From the 80 tries of doing the "button dance" i got it one time to work. Are there any other options on how to flash the board with platformio without attaching a 100nF capacitor from EN to GND?

Here is the output when trying to flash

    Auto-detected: /dev/ttyUSB0
    Uploading .pio/build/ESP32/firmware.bin
    esptool.py v3.0
    Serial port /dev/ttyUSB0
    Connecting........_
    Chip is ESP32-D0WD (revision 1)
    Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
    Crystal is 40MHz
    MAC: 4c:11:ae:6c:c8:b4
    Uploading stub...

    A fatal error occurred: Invalid head of packet (0x65)
    *** [upload] Error 2  ==========

    [FAILED] Took 9.83 seconds ==========================
        The terminal process "platformio 'run', '--target', 'upload'" terminated with exit code: 1.

These are the settings in the platformio.ini file:

    [env:ESP32]
    platform = espressif32
    framework = espidf
    board = esp32dev
    board_build.flash_mode = dio

Thanks everyone for the help!

  [1]: https://github.com/espressif/esptool/issues/226

title: ESP32 Espressif ESP32_DevKitC_V4 in platformio: flash issues

Answers: 0


body:
I am working on building a serial command receiver. The idea is came from the boot loader. However, I got a very strange problem that I have no idea what could cause it.

As the first screenshot show, the print isn't finished because "===a=" is stuck, like this.
[![enter image description here][1]][1]

 In the code, it should print out and the others.

    char* receiveCmd(Stream &_serial, char &cmd_ptr, int &l_ptr) {
      Stream* serial = &_serial;

      if (serial->available() && (uint8_t)serialRead(_serial) == CMD_START) {
        int buf_count = 0; //start at data
        cmd_ptr = serialRead(_serial); //cmd_byte

        char low_byte = serialRead(_serial);
        char high_byte = serialRead(_serial);

        uint16_t length = low_byte; //data_length
        length = length | (high_byte << 8);

        Serial.println("\n\n===a===");
        Serial.println(length);
        Serial.println("===b===");

        l_ptr = (int)length;

        char* _buf = (char*)malloc(length * sizeof(char));

        while (buf_count != length) {
          if (serial->available()) {
            _buf[buf_count] = serial->read();
            buf_count++;
          }
        }

        char checksum = serialRead(_serial); //checksum, don't bother it yett
        char stop_byte = serialRead(_serial);

        if (stop_byte != CMD_EOF) {
          free(_buf);
          return NULL; //error
        }

        return _buf;
      }

      return NULL;
    }

Anyway, the problem is fixed when I print out other variables first, then the length var..

    char* receiveCmd(Stream &_serial, char &cmd_ptr, int &l_ptr) {
      Stream* serial = &_serial;

      if (serial->available() && (uint8_t)serialRead(_serial) == CMD_START) {
        int buf_count = 0; //start at data
        cmd_ptr = serialRead(_serial); //cmd_byte

        char low_byte = serialRead(_serial);
        char high_byte = serialRead(_serial);

        uint16_t length = low_byte; //data_length
        length = length | (high_byte << 8);

        Serial.println("\n\n===a===");
        Serial.println(low_byte, HEX);
        Serial.println(high_byte, HEX);
        Serial.println(length);
        Serial.println("===b===");

        l_ptr = (int)length;

        char* _buf = (char*)malloc(length * sizeof(char));

        while (buf_count != length) {
          if (serial->available()) {
            _buf[buf_count] = serial->read();
            buf_count++;
          }
        }

        char checksum = serialRead(_serial); //checksum, don't bother it yett
        char stop_byte = serialRead(_serial);

        if (stop_byte != CMD_EOF) {
          free(_buf);
          return NULL; //error
        }

        return _buf;
      }

      return NULL;
    }

Other code is exactly the same. Does anyone know what may cause it? I can't print out those thing during production because it is only for debugging. If I remove those print, the code is also stuck(because of the length variable again).

For additional information, the serial signal is generated from other Arduino and AltSerial Library. The structure is like this.

    void sendCmd(Stream &_serial, char cmd, char* payload, int length) {
      Stream* serial = &_serial;
      char buf[6 + length]; //start, data_length, data, checksum, stop

      buf[0] = CMD_START; //start_byte
      buf[1] = cmd; //cmd_byte
      buf[2] = length & 0xff; //data_length - low byte
      buf[3] = (length >> 8) & 0xff; //data_length - high byte
      buf[4 + length] = (char)calcCRC(payload); //checksum
      buf[5 + length] = CMD_EOF; //stop_byte

      for (int i = 0; i < length; i++) //load buf
        buf[4 + i] = payload[i];

      for (int i = 0; i < sizeof(buf); i++)
        serial->print(buf[i]);
    }

 I have used `Serial.print(altSerial.read(), HEX)` to check whether the byte is received correctly. They are all correct. That's why it is confusing me.QAQ

===== UPDATED INFORMATION =====

I have narrowed the problem. It seems like the below code is the main cause regard the issue. But no solution for this still.

    uint16_t length = low_byte; //data_length
    length = length | (high_byte << 8);

Thank you.

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

title: Need HELP!! Serial communication has a very "Strange Problem"

Answers: 1

body:
Why it does not work? You already got the answer in comments:

- You are reading more bytes from the serial stream than what you know
  are available. Then, your `length` variable can contain garbage, which
  makes `malloc()` fail even if you have plenty of available memory.

- You write into the memory buffer even if the allocation failed, which
  makes your program corrupt its memory. From this point, anything can
  happen.

You may notice that the behavior of your program depends on the timing.
Adding more instructions, or delays, may make it work. This is simply
because you give your peer more time to send its data packet. Of course,
relying on the timings is not a good approach: you instead have to make
sure you never `read()` more than what is actually `available()`.

Here is an (untested) attempt to do this correctly and in a non-blocking
fashion. It is based on a [finite state machine][fsm]. What is original
about this state machine is that it is implemented as a `switch`/`case`
where _every single case_ falls through:

```c++
/*
 * Packet format:
 *   CMD_START cmd_byte length_L length_H [payload] checksum CMD_EOF
 */
char *receiveCmd(Stream &serial, char &cmd_ref, int &l_ref) {

    // The current state is defined by what parts of the packet
    // we have already received.
    static enum {
        GOT_NONE, GOT_START, GOT_HEADER, GOT_PAYLOAD
    } state = GOT_NONE;

    // Variables only valid in the states GOT_HEADER and GOT_PAYLOAD.
    static char cmd_byte;
    static uint16_t length;
    static char *buffer;
    static size_t buffer_pos;

    switch (state) {
        case GOT_NONE:
            if (serial.available() < 1 || serial.read() != CMD_START)
                break;
            state = GOT_START;
            // fallthrough
        case GOT_START:
            if (serial.available() < 3)
                break;
            cmd_byte = serial.read();
            length = serial.read();
            length |= (uint16_t) serial.read() << 8;
            buffer = (char *) malloc(length);
            if (!buffer) {
                Serial.print(F("ERROR: Failed to allocate "));
                Serial.print(length);
                Serial.println(F(" bytes."));
                state = GOT_NONE;
                break;
            }
            buffer_pos = 0;
            state = GOT_HEADER;
            // fallthrough
        case GOT_HEADER:
            while (buffer_pos < length && serial.available())
                buffer[buffer_pos++] = serial.read();
            if (buffer_pos < length)
                break;
            state = GOT_PAYLOAD;
            // fallthrough
        case GOT_PAYLOAD:
            if (serial.available() < 2)
                break;
            serial.read();  // consume checksum
            if (serial.read() != CMD_EOF) {
                Serial.println(F("ERROR: Expected CMD_EOF."));
                free(buffer);
                state = GOT_NONE;
                break;
            }
            cmd_ref = cmd_byte;
            l_ref = length;
            state = GOT_NONE;
            return buffer;
    }
    return NULL;
}
```

You can think of this `switch`/`case` as a set of actions to perform
sequentially in order to process the whole packet. However, if the
function gets stuck for lack of incoming data, it just bails out. On the
next call, the `switch` puts it back where it left.

[fsm]: https://majenko.co.uk/blog/finite-state-machine


body:
I have thermal printer from adafruit and when printing images I have problems getting a proper black.

I tried playing with the dot print time and the dot feed time using the `setTimes` function, but this seem to have no effect.

```cpp
  unsigned long dotPrintTime = 3000*30L;
  unsigned long dotFeedTime = 2100*30L;
  printer.setTimes(dotPrintTime, dotFeedTime);
```

Also the `setHeatConfig` seems to have no effect. I tried different values.

```cpp
  uint8_t dots = 11;
  uint8_t _time = 120;
  uint8_t interval = 40;
  printer.setHeatConfig(dots, _time, interval);
```
Here an image of the result:

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

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

Is it possible to print fully black the whole width of the paper?

title: Adafruit Thermal Printer unwanted gradient

Answers: 1

body:
Thermal printers generate quick pulses of heat to change thermal paper from white to a darker color.  This may require more than the expected amount of current most Arduino project need.

Consider checking the maximum current rating of your power source.  From the [Adafruit printer web page][1] regarding using [this Mini Thermal Receipt Printer][2]:

> This printer in particular requires 5 to 9 Volts, 1.5 Amps current!
> That means you will need a fairly beefy supply and you cannot run it
> off of USB power. An external adapter is required!

Also consider trying different thermal paper manufactures and colors.

Lastly, consider how you might avoid [BPA from thermal paper][3].

  [1]: https://learn.adafruit.com/mini-thermal-receipt-printer/power
  [2]: https://www.adafruit.com/product/597
  [3]: https://www.sciencedaily.com/releases/2014/10/141022143628.htm


body:
I am developing smart curtain system with voice control using Arduino Uno and bluetooth sensor
Almost of codes is already written. but I have to fix error with delay function.
I am using timer0_millis for time control.
But the one thing I want to fix is that because of delay in timer1 function,
I cannot change the value of a. but it need to be changed when voice is coming.
can anybody help me to fix this?

```c++
extern volatile unsigned long timer0_millis;

#include <SoftwareSerial.h>
#include <Stepper.h>
#include <dht.h>
#include <SimpleTimer.h>

SoftwareSerial BT(2, 3);
const int stepsPerRevolution = 64;
Stepper myStepper(stepsPerRevolution, 11, 9, 10, 8);
dht DHT;

#define DHT11_PIN A1

SimpleTimer timer;
char a = BT.read();

void setup() {
    Serial.begin(9600); // Sets the data rate in bits per second (baud) for serial data transmission
    pinMode(7, OUTPUT);
    myStepper.setSpeed(300);
    BT.begin(9600); // Sets digital pin 13 as output pin
}

void loop() {
    if (BT.available()) {
        char a = BT.read();
        if (a == '1') {
            digitalWrite(7, HIGH);
            myStepper.step(2048);
            delay(500);
            Serial.print('1');
        }
        if (a == '2') {
            automode();
        }
        if (a == '3') {
            digitalWrite(7, LOW);
            myStepper.step(-2048);
            Serial.print('2');
            delay(500);
        } if (a == '4') {
            digitalWrite(7, LOW);
            myStepper.step(-2048);
            Serial.print('2');
            delay(500);
        }
    }
}

void automode() {
    int chk = DHT.read11(DHT11_PIN);
    int AnalogValue;
    AnalogValue = analogRead(A0);
    if (DHT.temperature > 30 && AnalogValue > 600) {
        myStepper.step(-2048);
        timer1();
    } else if (DHT.temperature > 30 && AnalogValue < 600) {
        myStepper.step(2048);
        timer1();
    } else if (DHT.temperature < 30 && AnalogValue > 600) {
        myStepper.step(2048);
        timer1();
    } else if (DHT.temperature < 30 && AnalogValue < 600) {
        myStepper.step(-2048);
        timer1();
    }
    return;
}

void timer1() {
    timer0_millis;
    if (timer0_millis >= 100000) {
        timer0_millis = 0;
    }
    do {
        delay(5);
    } while (timer0_millis < 100000);
    return;
}
```

title: Having preblem in developing smart curtain

Answers: 0


body:
I have an autonomous wall-following robot based on a Mega2560, that is just about maxed out in terms of memory usage and speed.  I'm starting to have weird intermittent failures with previously working code; a function will work fine in isolation (same hardware, but only the minimum required code to run just that one function), but not when used with the full program running, and other issues.

I ran across [this article][1] about the ShieldBuddy TC275, which purports to be pin-compatible with the Due (which I believe is pin-compatible with the Mega 2560, but I can't use the Due due to 5V compatibility issues), and MUCH faster, even if only Core0 is used.

I realize it is quite costly relative to other Arduino projects, but that's not a factor here.  Anyone have experience with this board as a replacement for a Mega2560?

TIA,

Frank

  [1]: https://www.rs-online.com/designspark/bringing-multicore-to-the-arduino-world-with-shieldbuddy-tc275

title: ShieldBuddy TC275 as a drop-in replacement for MEGA 2560?

Answers: 0