text:
Undefined reference to Class::function()
I have three files:

main.cpp
RotaryEncoder.h
RotaryEncoder.cpp

Note that the RotaryEncoder class acts as a wrapper to the Encoder library. I am getting the following build report and I haven't been able to find the bug for the past couple days:
Build output from PlatformIO on VS Code
Processing uno (platform: atmelavr; board: uno; framework: arduino)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/uno.html
PLATFORM: Atmel AVR 1.15.0 > Arduino Uno
HARDWARE: ATMEGA328P 16MHz, 2KB RAM, 31.50KB Flash
PACKAGES: toolchain-atmelavr 1.50400.190710 (5.4.0), framework-arduinoavr 4.1.2
LDF: Library Dependency Finder
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 7 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <Encoder>
Building in release mode
Compiling .pio/build/uno/src/main.cpp.o
Linking .pio/build/uno/firmware.elf
/var/folders/t1/fyh283nd1m7dxbrjlkjtf_kc0000gn/T//ccZN56Tq.ltrans0.ltrans.o: In function `main':
<artificial>:(.text.startup+0x2dc): undefined reference to `RotaryEncoder::getCount()'
collect2: error: ld returned 1 exit status
*** [.pio/build/uno/firmware.elf] Error 1

Explicit Error

In function 'main':
  :(.text.startup+0x2dc): undefined reference to 'RotaryEncoder::getCount()'.

main.cpp
#include <Arduino.h>
#include "RotaryEncoder.h"

#define cartEncoderPhaseA 3
#define cartEncoderPhaseB 4
#define pendulumEncoderPhaseA 2
#define pendulumEncoderPhaseB 5

// Initialize encoders
const double ENCODER_PPR = 2400.0;
RotaryEncoder cartEncoder(cartEncoderPhaseA, cartEncoderPhaseB, ENCODER_PPR);
RotaryEncoder pendulumEncoder(pendulumEncoderPhaseA, pendulumEncoderPhaseB, ENCODER_PPR);

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

void loop()
{
  long cartCount = cartEncoder.getCount();
}

RotaryEncoder.h
#pragma once

#include <Encoder.h>

class RotaryEncoder
{
private:
    Encoder encoder;
    double encoderPPR;
    double angleLowerBound;
    double angleUpperBound;

    double convertEncoderCountToRadians(long encoderCount);
    double normalizeAngle(double angle);

public:
    RotaryEncoder(int phaseA, int phaseB, double encoderPPR);
    long getCount();
    double getRadiansAndOffsetBy(double angleOffset);
    void setAngleLowerAndUpperBounds(double lowerBound, double upperBound);
};

RotaryEncoder.cpp
#include "RotaryEncoder.h"

RotaryEncoder::RotaryEncoder(int phaseA, int phaseB, double encoderPPR)
: encoder(phaseA, phaseB), encoderPPR(encoderPPR)
{}

inline long RotaryEncoder::getCount()
{
    return encoder.read();
}

inline double RotaryEncoder::getRadiansAndOffsetBy(double angleOffset)
{
    long encoderCount = getCount();
    double angleInRadians = angleOffset + convertEncoderCountToRadians(encoderCount);
    angleInRadians = normalizeAngle(angleInRadians);

    return angleInRadians;
}

inline double RotaryEncoder::convertEncoderCountToRadians(long encoderCount)
{
    return ((double)encoderCount / (encoderPPR)) * (2.0 * PI);
}

inline double RotaryEncoder::normalizeAngle(double angle)
{
    // Constrain an angle between [-pi, pi). Output is in radians
    // see: https://stackoverflow.com/questions/11498169/dealing-with-angle-wrap-in-c-code

    angle = fmod(angle + PI, 2 * PI);

    if (angle < 0)
        angle += 2 * PI;

    return angle - PI;
}

inline void RotaryEncoder::setAngleLowerAndUpperBounds(double lowerBound, double upperBound)
{
    angleLowerBound = lowerBound;
    angleUpperBound = upperBound;
}

Have you tried it without inlines? It's kinda pointless to have inline modifier in cpp file as it's compiled into RotaryEncoder.o and everything else is compiled separately and won't see any inline...

@KIIV Thank you so much, that worked. I didn't even think of that being the issue. If you want to post as an answer I will accept it

The inline modifier doesn't make a sense for methods definitions in separate cpp file. And obviously it makes the code compilable but methods aren't recognized as methods definitions and also it's not recognized as error (that's kinda weird).
Anyway, if you wan't inline methods, do it directly inside of class definition.


text:
Infinite loop if Serial.println() is not used
I'm trying to reset my program from software using the third method described here: Reset an Arduino Uno in code
The function is basically showing some data on an OLED display and afterwards should reset the processor
void setup() {
  MCUSR = 0;
}

void showCharacter(int char_number) {

  // [...]

  display.println(character_buffer);
  display.display();

  for (int j = 0; j < 3; j++) {
    enableLED(x, y);
    publishLEDs();
    delay(500);
    clearLEDs();
    publishLEDs();
    delay(500);
    Serial.println(j);
  }

  keyscan.sleep();

  // Reset system
  wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
  for (;;) {}
}

For whatever reason it makes a difference if the Serial.println() line is there. If the line is there, the code behaves as expected. The LED blinks three times, afterwards the Arduino is reset.
If I remove that line however, the LED continues to blink infinitely and the code does not reset. I really have no idea why that line has such a big difference, I wouldn't expect any difference to be honest. Anybody has an idea what's going on?
Edit:
I got a hint from a friend of mine that using the volatile keyword in the for loop could fix the problem. He vaguely remembered having a similar problem somehow related to compiler optimisation. And indeed, the following code works as expected:
for (volatile int j = 0; j < 3; j++) {
  enableLED(x, y);
  publishLEDs();
  delay(500);
  clearLEDs();
  publishLEDs();
  delay(500);
}

So let me rephrase my question a little bit - what is happening here, why is the volatile keyword needed?

Is that Serial initialized? I'm not sure we can answer this question, as there are no details about it. Why do you even need the restart?

replace the Serial.println()  with an equivalent delay

How do you know, that the code does not reset? A continuos blink is not possible with this for loop. When we have a question like "it works with serial print, but not without", it is often just, that it could not be seen, if it works, since there is no serial print. Please show us a complete minimal example, that shows your problem. The code above is not complete.

@KIIV, yes it is initialised and works.
jsotola, there is a 500ms delay just before the Serial.println(), why should that make a difference?
chrisi: after reset and init, the LED does not blink and also the OLED is reset. If the serial command is there, the devices resets, LED stops blinking and OLED shows correct content. If the command is not there, nothing of that happens and the LED keeps blinking (OLED content remains). I'll try to post more code tomorrow, but its somehow complex

I like the resetFunc style better.  Looping and waiting for watchdog just seems clunky to me.

a Serial.println() command takes a certain amount of time to execute

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Sim900a AT+HTTPREAD does not get fully answer
changed the firmware on SIM900B
try to send get request http://dummy.restapiexample.com/api/v1/employee/1
AT+HTTPACTION=0returned +HTTPACTION:0,200,98
but, when I try to read (AT+HTTPREAD or AT+HTTPREAD=0,98)the response data
I got broken response
expected result:
+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999","employee_age":"0","profile_image":""}

and actual results:
+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999","empe_"0"olme"

+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999","empe_"0"fea"}

+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999""pea:,piig"

+HTTPREAD:98
{"id":"1","employee_name":"Shibani","employee_salary":"999",moeg""reae}

my Arduino code looks like that
void setup() {
  Serial.begin(9600);
  mySerial.begin(57600);
  delay(5000);
  mySerial.println("AT");
  Serial.println("End of the setup");
}

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

Edit the question : post your arduino code.  Looks like a string overflow might be happening.

Maybe you're doing that silly "wait 5 seconds and assume there's a reply" thing I see all over the place. Or maybe you're using SoftwareSerial at 115200 baud...  No one can know - unless you share your code...

@Majenko, thanks, I've changed the baud to 9600 and it started work fine

@Majenko After doing
mySerial.println("AT+HTTPACTION=0");
mySerial.println("AT+HTTPREAD");
delay(1000);  //how do i get response without waiting a specific time.

Apparently you were running software serial at too high of a baud rate (57600) and bringing it down to 9600 fixed the issue.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What Arduino and shield components are worth recycling?
I'm building up a nice collection of smoked or otherwise bricked Arduino boards. I would like to save bits that might be useful later. I've desoldered a barrel plug to use when I want to separate the power supply to a motor shield. Is there something I could do with the ATmega328 processor, and how would I verify that it is still functional? Any other bits that you rescue?

This isn't a great place for this type of question.  But I suggest you start buying DIP package Arduino board and learn how to replace the Atmel processor and program the boot loader into the brand new processor.  If you burn out the power regulator (a bit harder to do) you can brush up on your soldering and try replacing them.

Basically you can re-use any part that you salvaged.

You can reuse everything what is not damaged, but it can be tricky to properly desolder multi-pin SMD parts.
It's hard to verify if a processor is still working, but it propably is not anymore if you applied a too high voltage on one of the input pins or drew to much current.
Parts like regulators are always handy. I would skip capacitors and resistors.
But you can try to desolder everything, it will teach you how to use e.g. solder wick properly. This will come handy in the future, if you need to replace parts properly! :)

Good, complete answer. As you say, the processor itself is the thing that is most likely to be damaged/destroyed due to putting too much voltage into one of the pins or drawing too much current out of it.


text:
Two Reed switch in two way directions
Hi im a student having problem in coding
I  want to set two reed switch in two direction.
Example : 1. Reed switch 1 detect then reed switch 2 detect - led turns to yellow
2.If reed switch 2 detect first then reed switch 1 detect - led turns to red
 It should play in sequentially form. Can help me in coding?
So far i have done this..
const int REED_PIN1 = 2; // Pin connected to reed switch const int REED_PIN2 = 3; // Pin connected to reed switch

const int RED = 9; // LED pin - active-high const int GREEN = 10; // LED pin - active-high const int YELLOW = 11; // LED pin - active-high

int up = 0; int down = 0;

void setup() { Serial.begin(9600); // Since the other end of the reed switch is connected to ground, we need // to pull-up the reed switch pin internally. pinMode(REED_PIN1, INPUT_PULLUP); pinMode(REED_PIN2, INPUT_PULLUP);

pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(YELLOW, OUTPUT);

digitalWrite(RED, LOW);
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, LOW);
}

void loop() { int proximity1 = digitalRead(REED_PIN1); // Read the state of the switch int proximity2 = digitalRead(REED_PIN2); // Read the state of the switch while (proximity1 == LOW) // If the pin reads low, the switch is closed. {

up  = up  + 1;
Serial.print(up);
Serial.print("        ");
Serial.println(down);

if(down < 1){
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}

else {
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
} while (proximity2 == LOW) // If the pin reads low, the switch is closed. { up = up - 1; Serial.print(up); Serial.print(" "); Serial.println(down); if(up < 1 && down < 1){ digitalWrite(RED, LOW); digitalWrite(GREEN, LOW); digitalWrite(YELLOW, HIGH);

delay(3000);      }
else{
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
} while (proximity2 == LOW) // If the pin reads low, the switch is closed. { down = down + 1; Serial.print(up); Serial.print(" "); Serial.println(down);

if(up > 1){
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, HIGH);

delay(1000);
}

else {
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
delay(1000);
}
while (proximity1 == LOW) ;// If the pin reads low, the switch is closed. { down = down - 1; Serial.print(up); Serial.print(" "); Serial.println(down); if(up < 1 && down > 1){ digitalWrite(RED, HIGH); digitalWrite(GREEN, LOW); digitalWrite(YELLOW, LOW);

delay(5000);      }
else{
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);
delay(5000);} } }

your code is really badly formatted ... do yourself a favor and format your code so that it is readable ... it will help you immensely with program creation and with debugging

Your code is a mess. Not only is it badly formatted, but because it's badly formatted you've lost all track of your brackets, and now it's all over the place. Half the code isn't even in a function any more.

I think, you don't understand, how while loops are written in C/C++. You can google that, to correct that part of the code. I'm pretty sure, that your current code would throw compilation errors. You can use these to fix the most urgent problems with the code. I started with the pattern "Code something, compile it, correct the errors, compile again, repeat until no errors occur".

Sorry, but your code is complete nonsense. The following code gives you an example. I have no access to a compiler at the moment, so there might be syntax errors and it is completely untested. Also, you gave no complete description of the things you want to do. e.g when to switch on the green LED or what the up and down variables are for.
And there might also be timing problems. In order not to miss a reed state change,
you should avoid adding delays and slow serial print outs.
I'm pretty sure, I did your homework. So my advice is to learn programming and try to understand. Homework was not ( only ;-) ) invented to enjoy the teacher, they help you through tests. ;-)
Your problem is similar to the decoding of a rotary encoder, so information about this subject might help you also.
const int REED_PIN1 = 2;
const int REED_PIN2 = 3;

// LED pins - active-high
const int RED    =  9;
const int GREEN  = 10;
const int YELLOW = 11;

int fixedState1 = HIGH;
int fixedState2 = HIGH;

void setup()
{
   // If the pin reads low, the switch is closed.
   pinMode(REED_PIN1, INPUT_PULLUP);
   pinMode(REED_PIN2, INPUT_PULLUP);

   pinMode(RED, OUTPUT);
   pinMode(GREEN, OUTPUT);
   pinMode(YELLOW, OUTPUT);

   digitalWrite(RED, LOW);
   digitalWrite(GREEN, HIGH);
   digitalWrite(YELLOW, LOW);
}

void loop()
{
  // AS LONG AS BOTH SWITCHES ARE ON AT THE SAME TIME,
  // THE PROGRAM FLIPS OUT ;-)
  int reedState1 = digitalRead( REED_PIN1 );
  int reedState2 = digitalRead( REED_PIN2 );

  if ( readState1 == LOW && fixedState1 == HIGH )
  {
    if ( fixedState2 == LOW )
    {
      digitalWrite( RED,    HIGH );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  LOW  );

      fixedState2 = HIGH;
    }
    else
    {
      // setting the green LED is just a guess
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  HIGH );

      fixedState1 = LOW;
    }
  }

  if ( readState2 == LOW && fixedState2 == HIGH )
  {
    if ( fixedState1 == LOW )
    {
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, HIGH );
      digitalWrite( GREEN,  LOW  );

      fixedState1 = HIGH;
    }
    else
    {
      // setting the green LED is just a guess
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  HIGH );

      fixedState2 = LOW;
    }
  }
}

Your code is so badly formatted it makes it very difficult to follow.
A couple of things that jump out at me:
You never set REED_PIN1 or REED_PIN2 to INPUT_PULLUP mode. You should do that in setup.
You have the code that deals with REED_PIN2 commented out so that can't possibly work.
I took a first crack at improved code formatting. There result is below:
const int REED_PIN1 = 2; // Pin connected to reed switch const
int REED_PIN2 = 3; // Pin connected to reed switch

const int RED = 9; // LED pin - active-high
const int GREEN = 10; // LED pin - active-high
const int YELLOW = 11; // LED pin - active-high

int up = 0; int down = 0;

void setup() {
    Serial.begin(9600);
    // Since the other end of the reed switch is connected to ground, we need
    // to pull-up the reed switch pin internally.
    pinMode(REED_PIN1, INPUT_PULLUP);
    pinMode(REED_PIN2, INPUT_PULLUP);

    pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(YELLOW, OUTPUT);

    digitalWrite(RED, LOW);
    digitalWrite(GREEN, HIGH);
    digitalWrite(YELLOW, LOW);
}

void loop() {
    int proximity1 = digitalRead(REED_PIN1); // Read the state of the switch
    int proximity2 = digitalRead(REED_PIN2); // Read the state of the switch while (proximity1 == LOW) // If the pin reads low, the switch is closed.

    up  = up  + 1;
    Serial.print(up);
    Serial.print("        ");
    Serial.println(down);

    if(down < 1) {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);

        delay(1000);
    }

    else {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);

        delay(1000);
    }
} while (proximity2 == LOW) { // If the pin reads low, the switch is closed.
    up = up - 1;
    Serial.print(up);
    Serial.print(" ");
    Serial.println(down);
    if (up < 1 && down < 1) {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, HIGH);

        delay(3000);
    }
    else {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);

        delay(1000);
    }
} while (proximity2 == LOW) { // If the pin reads low, the switch is closed.
    down = down + 1;
    Serial.print(up);
    Serial.print(" ");
    Serial.println(down);

    if(up > 1) {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, HIGH);

        delay(1000);
    }

    else {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);

        delay(1000);
    }
    delay(1000);
}
while (proximity1 == LOW) { // If the pin reads low, the switch is closed.
    down = down - 1;
    Serial.print(up);
    Serial.print(" ");
    Serial.println(down);
    if (up < 1 && down > 1) {
        digitalWrite(RED, HIGH);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);
        delay(5000);      }
    else{
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);
        delay(5000);

    }
}

EDIT:
After a first pass at code formatting I found the lines that are supposed to set up your REED_PIN1 and REED_PIN2 as inputs. That code got swallowed into a comment, so I didn't see it.
(Everything after a // until the end of the line is a comment. You can't put the opening curly brace for a while or an if statement after a comment.)
Don't put statements on the same line as an opening brace. Don't put multiple statements on a line. Every time you enter a new level of scope (inside another set of curly braces) increase your indentation level)
These are pretty firm conventions for code formatting. There's some debate on the margins for things like where to put your braces and how many blank lines to use, but your code violates the basics of readability all over the place.

I have tried the coding and readjust it but i dont get the output

I need the output like this Example : 1. Reed switch 1 detect then reed switch 2 detect - led turns to yellow 2.If reed switch 2 detect first then reed switch 1 detect - led turns to red It should play in sequentially form

Is like car goes in one way road and what happend if the car enter in the one way from opposite site

I can't make much sense of your twisted syntax.


text:
How Can I convert my arduino code to C/C++ embedded code
For example I have an code for arduino but I want to change it to embedded C to create more professional project with different hardware. is there any tutorial? I know the logic and the most of the codes are the same. I just wanna know about libraries or pin definitions for LCD and buttons.

Arduino code is already C, you can even use C++ constructs (some at least). Most libraries use already C++ classes for example. You are quite vague about 'different hardware'.

By different hardware I meant non arduino micro controller and customized LCD

non-arduino is sill very vague. Some MCUs don't offer a C compiler at all. Some offer a somewhat C compiler with weird syntax (PMS150C - I'm looking at you). You will have to be more specific that that. Tell us what hardware platform you are targeting and someone here will be able to give you an answer.

ATMega328P this is my MC target

Arduinos use a standard C++ compiler. The supposed "Arduino Language" doesn't exist; it is C++. Except that the Arduino IDE will permit you some shortcuts that the compiler doesn't. The two biggies are:

The IDE will notice that your are trying to use libraries (ones it recognizes, anyway) and insert the necessary #include <SOMELIBRARY.H>, if you didn't do it.
The IDE will notice when you make forward reference to a function not yet defined nor declared, and provide the necessary forward declaration.

But if you manage these for yourself, as you would have to in any other C++ environment, your code structure will be portable.
The remaining source of incompatibility is hardware dependence. Writing embedded systems software is almost always hardware dependent. It has to be dependent on the external hardware, and quite likely is dependent on specifics of the MCU. The latter dependencies can usually be written around. Function calls or direct references to the processor's I/O registers, for example, which, on another processor, will map differently, maybe even to memory addresses instead of to registers at all.
Another processor will very likely have an entirely different set of pins with different characteristics and capabilities from the original one. Libraries to drive external hardware will likely have been designed for a given processor or processor-family and may not map gracefully to another.
If processor independence is a design-goal of the project, then you'd probably define a hypothetical set of features that you'd expect all processors to share, and hand code for anything outside of that basic set. If you wanted to take advantage of certain features if they were available on a given processors, then, in addition to the hand-coded features you wish to have, you'd also provide conditionally compiled, optimized-for-the-processor code that you could enable when you compile for that processor, and disable for all others.

exactly I want to know what shortcuts Arduino gives me that other compilers don't

It's actually done by the IDE. The underlying compiler is a pretty plain vanilla C++ compiler. FWIW, I do what you're contemplating - write standard and complete C/C++. I don't actually port it much of anywhere; my primary purpose is to be able to use either the Arduino IDE or Eclipse/Sloeber, at will, and portable code is very effective to enable me to do that.

If you would to write more professional code, you could try to use a different editor instead the basic arduino editor.
Possible choices are, for example:

Visual Studio Core with platformio plugin.
Eclipse With Sloeber plugin.

Since arduino already use C/C++ Languange,  the only difference is the way you write and organize the code.

Amen! I am wondering if Arduino IDE 2.x will be based on something like VS Code with features that go beyond plain syntax highlighting.

In my opinion Arduino IDE should be very simple. If you need more that write a simple scatch, you can use other IDE already compatible with arduino.

The only thing that keeps me installing Arduino IDE is the board and library manager. As Arduino CLI doesn't seem to gain tracktion, this is unfortunately the easiest way to get startet with those. I wonder when Arduino-CLI will be stable and promoted on their page.


text:
cast from 'char*' to 'char' loses precision
Bit of a noob here. Im trying to use the sensor number (float) in my mqtt topic, but cant seem to get this right. Any help would be appreciated. Keep getting this error (cast from 'char*' to 'char' loses precision)
      char buffer2[5];

       dtostrf(sensor.sensor_no, 4, 2, buffer2);
     char* buffer4 = mqtt_topic + char(buffer2);

  dtostrf(sensor.dht22_t,0, 0, buffer);
     client.publish(buffer4, buffer); //Topic name

You can't add strings like that in C. Create a new empty buffer then use strcpy() and strcat() to fill it with data.

By adding strings together you are actually adding together the addresses in memory where those strings are.
Instead you need to create a new empty buffer and fill it with the contents of the other strings.
char buffer4[32]; // <-- Enough room for both strings and a NULL character

strcpy(buffer4, mqtt_topic);  // Copy in the first string
strcat(buffer4, buffer2); // concatenate the second string

Aaa. Thank you very much


text:
How can I use Methods in digitalWrite(): digitalWrite(int, "methodHere")?
When creating a piece of code to operate a 7-segment display, I ran into a problem:
The seven segment display on TinkerCad (I was using this at the time) requires you to pull down the inputs to turn a segment on, while the one that I have turns on when I pull up the inputs.
Instead of completely rewriting the code for the display that I had, I wanted to make my code more universal for if I need to use it in the future.
I cannot find a way to make the method digitalWrite(int pin, int val) work with a method that returns and int in the place of "int val"
This is the code that will not work:
int F = 11;
int G = 10;
int E = 9;
int D = 8;
int C = 7;
int DP = 6;
int B = 5;
int A = 4;
int type = 1;

 int highLow(int highOrLow)
{

  int digOutput;

  if(type = 1)
  {

    if(highOrLow = 1)
    {

      digOutput = 1;

    }
    if( highOrLow = 0)
    {

      digOutput = 0;

    }

  }
  if(type = 0)
  {

    if(highOrLow = 0)
    {

       digOutput = 0;

    }
    if( highOrLow = 2)
    {

      digOutput = 1;

    }

  }
  return digOutput;
}

void zero()
{
  digitalWrite(F, highLow(0));
  digitalWrite(G, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(D, LOW);
  digitalWrite(C, LOW);
  digitalWrite(DP, HIGH);
  digitalWrite(B, LOW);
  digitalWrite(A, LOW);
}

setup
{
pinMode(F, OUTPUT);
pinMode(G, OUTPUT);
pinMode(E, OUTPUT);
pinMode(D, OUTPUT);
pinMode(C, OUTPUT);
pinMode(DP, OUTPUT);
pinMode(B, OUTPUT);
pinMode(A, OUTPUT);
zero();
}

Note : I am just using pin f to test.
Also, my etiquette is not very well defined or tested, so please keep it rather simple if you can.
If it matters, I am going to be using to using an Arduino Mega2560 produced by Elegoo.
Thanks for any help!!

In this situation it is far more efficient to use #define and conditional compilation.
// Uncomment this for tinkercad
// #define INVERTED

#ifdef INVERTED
#  define ON HIGH
#  define OFF LOW
#else
#  define ON LOW
#  define OFF HIGH
#endif

Then just use ON or OFF in place of HIGH and LOW.
digitalWrite(3, ON);

But the reason you have a problem is not because you are trying to use a function as the value to digtalWrite() - the problem is actually in your basic C syntax.
You are using the assignment operator (=) when you should be using the comparison operator (==). For example here:
if(highOrLow = 0)

you should have:
if(highOrLow == 0)

Thanks a ton! Will try this when i can get access to a computer again!


text:
Decoding serial packets, please check my work!
I have a Innovate LC-2 wideband and Megasquirt ECU. The Innovate wideband has RS232 serial output I would like to use instead of the default 0-5V analog output.
So I designed and built a board using a MAX3232, MCP2515/MCP2561 CANbus, and ATMEGA328PB. I also have a MAX31856 for EGT, LIS3DH for accel, and BMP280 for barometer. I also mucked about on forums and threads until I understood enough to decode the format. What I have now works, but I would like someone more experienced to check it for errors!
The serial format is described here...
https://www.innovatemotorsports.com/support/downloads/Seriallog-2.pdf
My code looks a bit like this, it is part of a main loop reading data from other sensors as data is ready, so the loop is non-blocking. The main loop also transmits data over canbus at set intervals.
This does work, but is there anything I can do to make it more resilient?
Thank you in advance!
    if (Serial.available() > 0) {
      EGO_rx_byte=Serial.read();                                            // pull data from serial
      if ( (EGO_rx_byte & 0xA2) == 0xA2 ) {                                 // synchronization byte - bits 15-8 1x1xxx1x
         EGO_packet[0] = EGO_rx_byte;                                       // Store buffer data to Packet
         EGO_packet_index = 0 ;                                             // This is the start of the header packet, bits 15-8
      }
      else if ((EGO_packet_index == 0) && ((EGO_rx_byte & 0x80) == 0x80)) { // If index = 0 & bit 7 = 1 = 2nd syncro byte
         EGO_packet_index=1;                                                // this is second half of header packet, bits 7-0
         EGO_packet[1]=EGO_rx_byte;                                         // store buffer data to packet
      }
      else if ((EGO_packet_index == 1) && ((EGO_rx_byte & 0x42) == 0x42)) { // If index = 1 & 0x42 is set on next packet likely valid LC2 packet...
         EGO_packet_index=2;                                                // This was the third packet in six - Zero indexed
         EGO_packet[2]=EGO_rx_byte;                                         // Store buffer data to packet
      }
      else {
        EGO_packet_index++;                                                 // all else are data packets, increment the packet counter by one
        EGO_packet[EGO_packet_index]=EGO_rx_byte;                           // Store buffer data to packet in series
      }
      if (EGO_packet_index == 5) {                                          // Done recieving packets, ready to construct data... 2 words per EGO, 1 header packet
         EGO_status = (EGO_packet[2] & B00011100) >> 2;                     // status bits are in word 1 bits 12-10
         EGO_data = (EGO_packet[2] & B00000001) << 7;                       // AFR Multiplier - think this is programmed with lmprogrammer - bits 8, 6-0
         EGO_data += EGO_packet[3] & B01111111;                             // these are the 6-0 bits
         EGO_lambda = EGO_packet[4] & B00111111;                            // 13 bit lambda value, data depends on status bits
         EGO_lambda = EGO_lambda << 7;                                      // shift bits from first half of data packet
         EGO_lambda += (EGO_packet[5] & B01111111);                         // add bits from second half of packet
         switch (EGO_status) {                                              // Output data depends on Status
         case 0: Lambda = EGO_lambda; EGO_conn = 13;                        // EGO Output is valid - Lambda in 10 bit scale
         if (Lambda > 1023){Lambda = 1023;}break;                           // Megasquirt expects 0-1023 input value
         case 1:Lambda = 1023;EGO_conn = 13;break;                          // EGO Output is valid - reporting O2% in 1/10%
         case 2:EGO_conn = 10;Lambda =  500;break;                          // Free air calibration
         case 3:EGO_conn = 11;Lambda =  500;break;                          // Need Calibration
         case 4:EGO_conn = 12;Lambda =  500;break;                          // Warmup
         case 5:EGO_conn = 10;Lambda =  500;break;                          // Heater Calibration
         case 6:EGO_conn = EGO_lambda;Lambda =  500;break;                  // Error code 1-9
         case 7:EGO_conn = 0;Lambda =  500;break;                           // Reserved
         default:Lambda =  507;EGO_conn = 0;break;                          // Something else is happening, output 14.7 and error
         }
    }
}

That looks pretty robust to me as it is. You might like to make use if the length attribute of the header though to receive the right number of bytes for the payload though.

Thank you for the reply!
Oh, you mean pulling the header length from the first packet to determine the number of following packets? I have some very poorly written code that does so, but I lack the hardware to test more than one LC-2 on the serial bus at the time!


text:
How to connect 2 Fingerprint Sensor to Arduino Mega? Please help
My project was to open the door from inside and outside the room using fingerprint sensors, currently I used separate arduino on 2 different fingerprint sensor. Please help, my arduino detected only 1 fingerprint sensor when I try to connect them both on 1 arduino. ps: I connected the fingerprint sensor to digital pins (2,3) and (10,11) of the arduino mega. Thank you in advance...
//Here is my code

//for Relay

int in1 = 8; //pin for opening door

int in2 = 9; //pin for buzzer

 #include (<)Adafruit_Fingerprint.h>

//it (<) i use only to post the code

//Arduino Mega

SoftwareSerial mySerial1(2, 3); //for fingeprint sensor outside

SoftwareSerial mySerial2(10, 11);//for fingeprint sensor inside

Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);

Adafruit_Fingerprint finger2 = Adafruit_Fingerprint(&mySerial2);

void setup()
{

Serial.begin(115200);

pinMode(in1, OUTPUT);

 pinMode(in2, OUTPUT);

 digitalWrite(in1, HIGH);

 digitalWrite(in2, HIGH);

  while (!Serial);

delay(100);

  finger1.begin(57600);

finger2.begin(57600);

  if (finger1.verifyPassword() and finger2.verifyPassword()) { //To verify if 2

fingerprint sensor is working

 Serial.println("Found fingerprint sensors!");

} else {

 Serial.println("Did not find any fingerprint sensor!");

while (1) { delay(1); }

 }

  finger1.getTemplateCount(); //To show the numbers of enrolled fingerprint in sensor

 finger2.getTemplateCount();

  Serial.print("Fingerprint Sensor1 contains ");

Serial.print(finger1.templateCount); Serial.println(" templates");

 Serial.print("Fingerprint Sensor2 contains ");

Serial.print(finger2.templateCount); Serial.println(" templates");

Serial.println("Waiting for valid finger...");

}

void loop()
{

 //for fingeprint sensor outside the door
  getFingerprintID1();
  delay(50);

//for fingeprint sensor inside the door
  getFingerprintID2();
  delay(50);
}

uint8_t getFingerprintID1() {

uint8_t p = finger1.getImage();

switch (p) {

 case FINGERPRINT_OK:

//Serial.println("Image taken");

 break;

case FINGERPRINT_NOFINGER:

// Serial.println("No finger detected");

  return p;

 case FINGERPRINT_PACKETRECIEVEERR:

 //  Serial.println("Communication error");

  return p;

 case FINGERPRINT_IMAGEFAIL:

 //Serial.println("Imaging error");

return p;

 default:

 //Serial.println("Unknown error");

  return p;

 }

// OK success!

  p = finger1.image2Tz();

switch (p) {

case FINGERPRINT_OK:

 //Serial.println("Image converted");

  break;

case FINGERPRINT_IMAGEMESS:

 //Serial.println("Image too messy");

 return p;

case FINGERPRINT_PACKETRECIEVEERR:

 // Serial.println("Communication error");

 return p;

case FINGERPRINT_FEATUREFAIL:

// Serial.println("Could not find fingerprint features");

 return p;

case FINGERPRINT_INVALIDIMAGE:

 // Serial.println("Could not find fingerprint features");

  return p;

default:

 //Serial.println("Unknown error");

  return p;

}

  // OK converted!
  p = finger1.fingerFastSearch();

if (p == FINGERPRINT_OK) {

 Serial.println("Found a print match!");

digitalWrite(in1, LOW);  //Door will open for 5 seconds

 delay(5000);

 digitalWrite(in1, HIGH);

 delay(1000);

 Serial.print(finger1.fingerID);

 } else if (p == FINGERPRINT_PACKETRECIEVEERR) {

  //Serial.println("Communication error");

  return p;

} else if (p == FINGERPRINT_NOTFOUND) {

 Serial.println("Did not find a match");

 digitalWrite(in2,LOW); //if the fingerprint did not recognize buzzer will be ON

delay(1000);

 digitalWrite(in2,HIGH);

return p;

 } else {

//Serial.println("Unknown error");

 return p;

 }

return finger1.fingerID;

}

uint8_t getFingerprintID2() {

uint8_t p = finger2.getImage();

switch (p) {

case FINGERPRINT_OK:

 //Serial.println("Image taken");

  break;

 case FINGERPRINT_NOFINGER:

// Serial.println("No finger detected");

   return p;

case FINGERPRINT_PACKETRECIEVEERR:

//  Serial.println("Communication error");

  return p;

 case FINGERPRINT_IMAGEFAIL:

 //Serial.println("Imaging error");

  return p;

 default:

 //Serial.println("Unknown error");

   return p;

 }

  // OK success!
  p = finger2.image2Tz();

 switch (p) {

 case FINGERPRINT_OK:

  //Serial.println("Image converted");

  break;

case FINGERPRINT_IMAGEMESS:

 //Serial.println("Image too messy");

  return p;

 case FINGERPRINT_PACKETRECIEVEERR:

// Serial.println("Communication error");

  return p;

case FINGERPRINT_FEATUREFAIL:

 // Serial.println("Could not find fingerprint features");

 return p;

case FINGERPRINT_INVALIDIMAGE:

 // Serial.println("Could not find fingerprint features");

  return p;

default:

  //Serial.println("Unknown error");

 return p;

}

  // OK converted!

 p = finger2.fingerFastSearch();

if (p == FINGERPRINT_OK) {

 Serial.println("Found a print match!");

digitalWrite(in1, LOW);

 delay(3000);

digitalWrite(in1, HIGH);

 delay(1000);

 Serial.print(finger2.fingerID);

} else if (p == FINGERPRINT_PACKETRECIEVEERR) {

 //Serial.println("Communication error");

  return p;

  } else if (p == FINGERPRINT_NOTFOUND) {

 Serial.println("Did not find a match");

 digitalWrite(in2,LOW);

 delay(1000);

 digitalWrite(in2,HIGH);

 return p;

 } else {

 //Serial.println("Unknown error");

  return p;

 }

 return finger2.fingerID;

}

Don't ask your question again. You can edit your first question. Also please format the code correctly by selecting it in the question editor and clicking the {} button or pressing Control+K.

Why are you using software serial, when the Mega has 4 hardware serial interfaces?

sorry sir, I am a beginner thanks for the concerns

@chrisl im using adafruit library thats why i use 2 software serials, how can I use hardware serial properly? please help

I guess your problem is, that you are using SoftwareSerial. Doing Serial in software means, that you can only listen at one interface at a time, thus only one of the fingerprint sensors work at a time.
But you are using the Arduino Mega, which has 4 hardware Serial interfaces. They are named Serial and SerialX (with X being 1,2 or 3). You can give a reference to these Serial interfaces to the Adafruit library just like you are doing it with the SoftwareSerial interfaces. You are doing:
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&mySerial1);

Instead you could do:
Adafruit_Fingerprint finger1 = Adafruit_Fingerprint(&Serial1);

That will give a reference of the second hardware serial interface (first whould be Serial) to the Adafruit library, which will then use it to communicate with the sensor. Hardware and Software Serial implement the same interface, they just work differently under the hood, so you can easily exchange them at this level.

For Hardware Serial you cannot define your own pins. You have to use the pins corresponding to the used interface. For Serial1 this is pin 19 (RX) and pin 18 (TX)

Thank you!!! now I know how to use hardware serial on arduino mega :)))

I use this link as reference thank you


text:
I get the following error while using esp32

rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0,
  SPIWP:0xee
  clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
  mode:DIO, clock div:1 load:0x3fff0018,len:4 load:0x3fff001c,len:1044
  load:0x40078000,len:8896 load:0x40080400,len:5816 entry 0x400806ac
[E][camera.c:1049] camera_probe(): Detected camera not supported.
  [E][camera.c:1249] esp_camera_init(): Camera probe failed with error
  0x20004

I tried all the troubleshooting methods found in other forums

have you tried reading the error printout to determine what the problem is?

Welcome to StackExchange!
I guess you flashed esp32-cam firmware to off-branded ESP32-CAM with different pinout assignments.
To fix this, maybe you should try around with different settings.
Your code should have something similar to this:
// Select camera model
//#define CAMERA_MODEL_WROVER_KIT
#define CAMERA_MODEL_ESP_EYE
//#define CAMERA_MODEL_M5STACK_PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE
//#define CAMERA_MODEL_AI_THINKER

Now try to comment out the third line, and uncomment the last one. Probably it would help.

Whatever code you have on the ESP32 is looking for a camera. That camera can't be found - is it attached? Did you install the code? Did it come with the code pre-installed? If you installed the code, what code is it? If you didn't install the code yourself, maybe you want to write some new code to get the ESP32 to do what you want it to do.


text:
line following IR sensor not giving readings at 3m wire length?
I am using line following IR sensor with arduino mega. I need the sensor 2-3m away from arduino since the length of rover is 2m (sensor front & motor back). However, I cannot get accurate analog reading due to voltage drop so that is giving me a problem.
What I tried:-
1) I tried to supply 5.4V to the sensor but had no effect and it might damage the sensor so avoided it.
2) tried to keep the controller close to Arduino and let the wire between controller and BLDC motor be long but didnt work
More info about the project:-
-> Using 2 BLDC motor at the back and caster wheels in front with sensor
-> car length is 2m
What could be the best way to solve this problem?
Note:- if the short wire is the only way then is keeping the motor in front with sensor and caster wheels at back a good idea?

I would use Nano or Mini at sensors location and communicate with the Mega over RS485 or CAN.

I do not think that the voltage drop is a big problem. As the Arduino's Analog Pins have a very high resistance there is very low current on the signal wire. So the drop is minimal using normal wire diameters. It also seems that there is a  OpAmp on the sensor board and a potentiometer where you can regulate the voltage. You can make reference measurements with the mega for white and black obstacles.  Why do you think there are voltage drops, and are they so big that you can not decide between black and white anymore?

yes, when I take sensor reading closer (30cm) to arduino then it works perfectly but at 3m length there is negligible detection. I am not sure about voltage drop since volatge was almost same when Imeasured in both cases. Plus I am using wires of jumper wire thickness.

Those sensors are digital, not analog, as far as I know. The potentiometer on the sensor sets the amount of reflectivity (of the surface) needed to set its output HIGH (or LOW).

It has both digital and analog options in my sensor. Sorry I put wrong sensor in the above link which I updated just now.


text:
Do i must have capacitors when using L7805CV voltage regulator?
I am creating a small waterpump (5v) controled by arduino.
And i want to reduce voltage from 9v to 5v.
Do i must use capacitors when using L7805CV voltage regulator?

I fear this is not the right place to ask an electronics question. I suggest to ask on  https://electronics.stackexchange.com/ [electronics engineering]. As far as I know the capacitors are necessary to prevent  the 7805  from getting unstable.

@PeterPaulKiefer: I'm new here, but since this question involves details that are peculiar to Arduino (ref this answer), it seems to me that this is the right place.

@Seamus The question does not contain any reference to an Arduino in the title not in the text. There is a picture schematic and a UNO tag. But in the comments to the answer you cited the OP states that he/she uses an ESP32.  The question is about electronics; "should I use capacitors on a L7805CV?". I did not vote to close it, I just advised the OP to ask in a forum where the probability of getting a good answer is higher. But that's obsolete now, as there is a usable answer.

Look at the datasheet:
https://datasheet.octopart.com/L7805CV-STMicroelectronics-datasheet-7264666.pdf
It's not necessary but I advise to use capacitors on the inputs aswell as on the outputs. It will improve stability.
Another thing: the regulator could get quite warm, depending on how much current the motor consumes.
Why don't you use a 5V power supply? You could power the Arduino with it aswell.
At your schematic you are feeding 9V into the Vin pin of the Arduino, this might be a bad idea (I'm not 100% sure), but I think it bypasses the regulator on the Arduino -> it will kill your Arduino.

The Vin pin is connected to the voltage regulator on the Arduino Uno. It is meant to be provided by a higher voltage, so 9V is ok (as long as the OP doesn't draw too much current through the Arduino). But you are right: Using directly a 5V power supply would save you the voltage regulators.

Alright. I  was not sure if the Vin bypasses the onboard regulator or not.

VIN only bypasses the diode that is in series with the barrel jack.

I think @chrisl 's parenthetical note is the key point here. If the power to drive the motor is the 5V supply regulated on the Arduino, then this is most likely a bad idea. The motor should be powered directly from a regulated supply, and not through the Arduino.

@Seamus The motor is not powered through the Arduino but through extra regulator. Thats ok as long as the regulator can provide the needed current. But as both Arduino and motor run on 5V, the OP could simply use directly a 5V power supply.

That would be the easiest solution.

im using esp32 and by this documentation https://docs.zerynth.com/latest/official/board.zerynth.esp32_devkitc/docs/index.html ...it says the Input Voltage is: 7-12V


text:
Measure Natural Gas Pressure with arduino?
I am looking to measure Gas pressure in order to turn off Gas Heater when there is low gas. As in Pakistan alot of deaths occur when flame turns off because of low pressure of gas and then gas comes back. People suffocate into CO2. So to measure that gas what kind of sensor should i use with arduino?
Thanks

I'd probably point a light sensor toward the pilot-light (if it has one). Then sound an alarm if the light goes out. Messing with gas-lines (valves and pressure sensors) might make the whole situation more dangerous instead of safer.

Yes that also a good idea ,,

It sounds like death would be caused by gas poisoning, not CO2 (carbon dioxide) or CO (carbon monoxide) poisoning. If the flame goes out and then gas pressure is restored, un-burnt gas would be vented into the room. Unless gas is burning no CO or CO2 would be released. Further, our bodies detect excess CO2 and it causes us to feel short of breath and seek fresh air. CO on the other hand binds to the hemoglobin in our blood and prevents our blood from carrying oxygen, so we suffocate without knowing anything is wrong.
Natural gas is both poisonous and can cause explosions if it is lit with a spark. In most countries there is a scent added to the gas in the lines so we can smell it and know something is wrong. The scent is not enough to wake you up however.
The usual way to handle gas heater safety is with a pilot light and a thermocouple powered valve. The pilot light uses a tiny amount of gas to keep a small flame lit. That flame heats a thermocouple, which generates enough current to keep an electrically controlled gas valve open. If the pilot light goes out, the heat source to the thermocouple is removed, and the valve closes.
If the gas pressure drops enough, the pilot light goes out, the valve closes, and the heater turns off. If the gas pressure is restored, the user has to hold a button down to manually open the valve while re-lighting the pilot light.
In the U.S. gas heaters are required to have safety systems like I describe above. It sounds like the heaters in your country don't have safety systems like this.
Measuring gas pressure would be harder, as others have said in their answers. You'd need a sensor that is approved for use in gas appliances, as well as the fittings to attach it. The same goes for the valve that you would use to turn off the flow of gas when the pressure drops too low.
You'll need a pressure sensor approved for use with the type of gas you are dealing with, and that measures the pressure ranges in your gas lines. We can't know those things from the outside. You could probably find them out from the gas company that provides gas service.
In most countries working on gas lines and gas appliances requires special training and permits, since doing it wrong can cause explosions, fires, and gas poisoning.

Thanks man. Now i see thermocouple is used in our gas geezers and it is very effective. You are right. You gave a brilliant idea. Thanks man :)

"gas geezers"? What are gas geezers?

Gas water geezers, that are used to heat the water in cold weathers

"Water geezers" is not an idiom I've ever heard. Here in the US we just call them water heaters.

This is a fantastic idea, but you should be a bit more informed before you start the project.
I do not think the people suffocate into CO2 because CO2 is not inflammable under normal conditions so it is not used to feed the heaters. It's produced by the heater while it burns. Most probably the heater uses methane (CH4), ethane (C2H6) or propane (C3H8).
To measure the pressure, you have to insert the sensor within the gas pipe. If this is done incorrect, there is much more danger. So you have to find a fool proved method to add the sensor.
The selection of the sensor depends also on the pressure that can be considered as normal. Another value you have to find out is: how much decreases the pressure if the burner (or more burners) are switched on. i.e at which pressure do you assume the burner's flame to go out. This value must be well known.
When you know the max and min pressure values, you can look for a sensor that can safely measure this values. It should also be included in an enclosing that can be attached to the gas pipeline.
Attention: If the pressure drops just for a small moment, the flame might go off and the sensors might not be aware of that event.
Do you know, there are alternatives to measure the pressure?
A Gas Sensor in the room checks, if there is methane, ethane or propane in the air in the room. ( this is the most secure method ) There are cheap gas sensors from china, (e.g. MQ-02), but I do not know much about them. You can also combine them with a CO2 and/or CO sensors to sense whether the chimney is clogged.
A high temperature sensor near the flame recognizes if the flame is out. But this is difficult to accomplish, because you have to build the sensor into the heater.
EDIT
I want to point you to the comment of @Gerben. Checking the light of the pilot flame or the flame might also be interesting.
Having thought about this a bit,  I still find that measuring the air with gas sensors and starting a acoustic signal is the best way of doing it. If you want to close a valve in case you detect gas, the Arduino can start a siren and control the valve.
Attention: Again, working with gas installations is nothing a beginner should do. You want to save life ...


text:
How to Control 2-wire Rotary-Gear Linear Actuator
Any ideas how to control a 2-wire DC 5V 10mm Stroke Mini Linear Actuator based Rotary Gear Motor? Most linear actuators (aside from solenoids) are controlled via 3-4 wires. Do I need a separate motor controller for the actuator to control it via an Arduino Uno?

Second the H-bridge suggestion.

I suspect that's little more than a geared brushed DC motor with a fancy "nut" on it. So yes, you will need any standard motor driver rated for the correct voltage / current (an H-bridge).


text:
ATMega32u4 SLEEP instruction
I was reading the ATMega34u2 datasheet and trying to figure out Sleep Mode. I know most people recommend using avr/sleep.h library. But I wanted to try out using the registers. I am fairly new to all this so sorry if this an easy question but I can't seem to really find anybody doing it like this.
When checking which registers to adjust it says this:

The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer’s purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up.

Now I understand setting the bit but what exactly is the sleep instruction? How do I call it in my arduino program?

google ATMega34u2 sleep mode assembly language

SLEEP is an assembly instruction.  You can execute assembly with GCC's Inline Assembly facility.
In short:
asm volatile("SLEEP");

will do what you want.
The avr/sleep.h file has sleep_cpu() defined as:
#define sleep_cpu()                              \
do {                                             \
  __asm__ __volatile__ ( "sleep" "\n\t" :: );    \
} while(0)

Which is essentially the same thing - just wrapped in a block to isolate it from the rest of your code somewhat.


text:
24V LED Lights with Arduino
I need help on determining how I can control 24VDC Auer Stack lights with an Arduino. I intend to activate these lights with a RF control and monitor them via IoT; the latter is just something else, not my main concern right now. However, I don´t know if I need to use normal relays, solid state relays or MOSFETs such as an IRF520.
The lights are 24V, consume around 22mA-33mA, they are pre-wired and only have the 4 wires (from the amount of lights I intend to use) and a common wire.
Thanks in advance!

Thank you for your quick response! I can see the IRF520 might be too much. What about the IRF520 arduino module, it has lower current and voltage rates, do you think it might work?

All that differs between those LEDs and 12V LEDs is the voltage. You do exactly the same as you would do with 12V LEDs - you just make sure the components you use are rated for at least 24V.
The IRF520 is overkill for this application. It's rated for 100V and 9A - far more than you need. But that's not to say it won't work - it'll work just fine. But you don't need one as big or beefy.

Thank you for your quick response! I can see the IRF520 might be too much. What about the IRF520 arduino module, it has lower current and voltage rates, do you think it might work?

As long as the voltage rating is at least 24V, sure. It's probably the connectors and copper clearances on the board that dictate the voltage rating more than the MOSFET.

An IRF520 Arduino module is just a IRF520 on a PC board, with screw terminals, a connector, and an indicator LED. It doesn't add any real value over using a "bare" IRF520, and has the same restrictions.

I don't think the IRF520 is a logic level MOSFET. You need one that can be driven to satuation with 5V. I've used this one from Adafruit for several projects: https://www.adafruit.com/product/355
It worked fine. It's also overkill, but so what?
(It looks like that same part number, IRLB8721, is available from several other manufacturers for cheaper than the Adadfruit part.)
It's dirt simple to use. You can drive the gate directly from an Arduino digital pin. It will handle plenty of current and up to 60V, so it should meet your needs.

At the currents involved the R_DSON even for a non-logic-level MOSFET like this doesn't really figure that much. It could be 100Ω@5V and you really wouldn't notice.  Personally I use STD19N3LLH6AG for my more powerful driving requirements - but then I can't remember the last time I used a through-hole component...

Pardon my ignorance (I am not an electronics expert). I thought the IRF520 Arduino Module was logic level (by the fact that it is driven by an Arduino). What do you mean by "driven to situation with 5V"..

Sorry, that was a typo. (Must have been auto-correct.) The phrase I intended to type is "driven to saturation" That means fully turned on. I don't know if the Arduino module boosts the gate voltage somehow. Getting an Arduino "module" is a little silly, given that all you need is a logic-level MOSFET, which costs less than a dollar US. There's no need for a PC board or other stuff.


text:
How to Use Arduino Wifi Shield To Receive/Send Info
I am doing an engineering project where I am using an Arduino Uno to try to open a window with a motor when the device is activated. I want to activate it by using a phone to somehow send it a command to “turn on.” I have tried to use the ESP8266 but couldn’t get it working and now have an Arduino Wifi Shield but am very confused on how to use it to do this task. I am new to understanding Arduino so any help would be appreciated.
I found a tutorial on how to connect the wifi shield to internet on the arduino website but am not sure what I would do after this.
Thanks!

it would be almost the same as using the ESP8266 .... what problems did you have with the ESP8266?

ESP8266 is not easy for beginner,  Arduino Wifi Shield is retired.
If you use either ESP8266 or  Arduino Wifi, You can control via Web. There are a lot of examples about control via web on Internet.
However, there is a very simple way to control Arduino via Web, use PHPoC WiFi shield. This shield is pretty easy to use (plug and play), It has built in web apps (can be customized). See this example

use Blynk service or similar


text:
What is the correct folder structure for including local headers in my Arduino project?
I am designing a "project" with 5 Arduino's (each with separate codes), communicating with each other using NRF24. All the 5 codes are different except they share a common header "MyHeader.h". The Arduino IDE forces the .ino filename to be same as the folder-name it is in. I currently have the following structure:
[parentfolder]
    MyHeader.h
    [arduino1]
          arduino1.ino
    [arduino2]
          arduino2.ino
    [arduino3]
          arduino3.ino
    [arduino4]
          arduino4.ino
    [arduino5]
          arduino5.ino

Now, if I use the following, I get an error that the IDE cannot find the header file:
#include "../MyHeader.h"

I am forced to use the above structure due to the IDE folder naming restrictions, whereas I would definitely like to have a structure like the following:
[parentfolder]
    MyHeader.h
    arduino1.ino
    arduino2.ino
    arduino3.ino
    arduino4.ino
    arduino5.ino

How should I organize my project so that I can include my header (without obviously duplicating the file inside every folder)? Thanks.

check out https://uecide.org

put MyHeader.h in Documents/Arduino/libraries/MyHeader folder

Does your filesystem support symlinks?

The reason why you can't reference the parent folder of your sketch when compiling is because the Arduino IDE doesn't compile your sketch in that folder. Instead it writes out the files from the IDE itself into temporary files in a "build" folder and compiles them in there - so the parent folder then does not contain your header file because the IDE has no clue about that.
So you need to put your header file somewhere that the IDE does know about - and the simplest place is where the libraries are.
A library is nothing more than a header file in a folder (both named the same) with optional source and other header files.  If you place your header in a folder in your libraries folder the IDE will see it as a library and you can include it into any sketch.
So you would have:
Documents/
    Arduino/
        libraries/
            MyHeader/
                MyHeader.h
    MyFancyProject/
        NodeOne/
            NodeOne.ino
        NodeTwo/
            NodeTwo.ino
        NodeThree/
            NodeThree.ino


text:
Arduino nano with 128x64px OLED freezing
I have an arduino nano, MCP3424 i2C ADC and a 128x64px i2C OLED display. The function is quite basic; the arduino receives information from the ADC and prints it to the screen as described in the code below.
#include <Fonts/FreeSerif9pt7b.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

#define MCP 0x6E //7bit MCP3424 address
#define CH1 0x8C //PGA = 1, SPS = 3.75, One-Shot mode, channel 1, initiate new conversion.
#define CH2 0xAC //channel 2
#define CH3 0xCC //channel 3
#define CH4 0xEC //channel 4

void setup() {
  Serial.begin(9600);//Initiate Connection to computer
  Wire.begin();//Initiate Wire library
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    //Serial.println("SSD1306 allocation failed");
    for(;;);
  };
  delay(2000);
}

  int count = 0;
void loop() {

 RunProgram();
 count++;
 Serial.println(count);

}

int RunProgram(){
  int pins[] = {CH1, CH2, CH3, CH4};
  long results[] = {0, 0, 0, 0};
  //int count = 0;
  for (int i = 0; i < 4 ; i++) {
    Serial.println(F("Reading from MCP..."));
    results[i] = ReadMCP(pins[i]);
    Serial.print(F("Read from MCP channel: "));
    Serial.println(i);
    //delay(500);
  }
 Serial.println(F("Printing results..."));
 PrintResults(results[0], results[1], results[2], results[3]);
 //count++;
 //Serial.print(count);
 Serial.print(F(" Results printed: "));
}

int PrintResults(long res1, long res2, long res3, long res4) {

  //PrintResults(); takes 4 long ints, divides the oled display into 4 segments and prints the results on screen

  display.clearDisplay();
  Serial.println(F("Display cleared"));
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(2, 3);
  display.print(F("Ambient"));
  display.setCursor(66, 3);
  display.print(F("Probe 1"));
  display.setCursor(66, 35);
  display.print(F("Probe 3"));
  display.setCursor(2, 35);
  display.print(F("Probe 2"));
  Serial.println(F("text printed"));
  display.setCursor(3, 15);
  display.print(res1);
  display.setCursor(3, 47);
  display.print(res3);
  display.setCursor(66, 15);
  display.print(res2);
  display.setCursor(66, 47);
  display.print(res4);
  Serial.println(F("results printed"));
  /*display.setTextSize(2);
  display.setCursor(3, 15);
  if (x >= 1000) {
    display.println(x, 0);
  } else if (x >= 100) {
    display.println(x, 1);
  } else {
    display.println(x, 2);
  }*/
  display.drawRect(0, 0, 128, 64, WHITE);
  display.drawLine(0, 32, 128, 32, WHITE);
  display.drawLine(64, 0, 64, 64, WHITE);
  Serial.println(F("Borders printed"));
  display.display();
  Serial.println(F("Display updated"));
  delay(50);
  return 0;
  Serial.println(F("Return printed"));
}

long ReadMCP(int channel){
  //conversion takes the channel from which the reading is to be taken from and returns a number between 0 and 131071
  int x, y, z;
  long result = 0;

  Wire.beginTransmission(MCP);//begin transmission with ADC in Write mode
  Wire.write(channel);//Write the settings and channel for the ADC to the wire buffer
  Wire.endTransmission();//Send information in the buffer to the ADC
  delay(300);//wait for the ADC to take reading ( only 3.75 samples per second, roughly takes 266 milliseconds per reading)
  Wire.requestFrom(MCP, 3);//request 3 Bytes of information from MCP3424
  x = Wire.read();//read bytes
  y = Wire.read();
  z = Wire.read();

  //conversion of the three binary bytes to decimal
  if (x>1) {
    if (x%2){
      result += (1 * 65536L);//x * 65536 = x * 2^16
      result += (y * 256L);//y * 256 = y * 2^8
      result += z;
      result = -131072 + result;
    }else{
      result += (y * 256L);//y * 256 = y * 2^8
      result += z;
      result = -131072 + result;
    }

  } else {
    result += (x * 65536L);//x * 65536 = x * 2^16
    result += (y * 256L);//y * 256 = y * 2^8
    result += z;
  }
  return result;
}

The issue is, after a period of time (which so far has varied between 622 to 6 full loops of the program) the arduino freezes. I have found online that other people have experienced a similar problem. For example this page and this page this page seem to have others who are having the same issue. The fix offered on these pages, and others like it, were issues with memory. So I looked around for ways to reduce memory usage and came across this page. So I followed the advice and put all my strings in the F() function (or whatever it is, I'm not sure what it is or does) and segmented all my code into functions outside of the main loop. So I removed the majority of functions and variables from the main loop() function(before, all the functions in RunProgram() were in the main loop). However I am still encountering freezing issues. Can someone suggest reasons my arduino would freeze and ways to fix it?

Chances are it's the I2C communication that's locking up. I2C is not intended to be used over wires, and the internal pullup resistors in the MCU that are often used are far too high a value for proper I2C communication.  Add 1kΩ resistors between each of SCL and SDA and the 5V pin of your Arduino.

Thanks for the suggestion @Majenko. For clarification all three parts of the circuit are soldered on to perforated board and the longest wire run is a few centimeters at most. I tried your suggestion, I had 10k pullups added to my circuit and changed them to and tested 4.6k, 2k, 560 and 220 ohm pullups all which had no effect on the locking up. I then also tried with the 2k ohm resistors changing the Wire clock speed to 50,000, half the speed. Still same issue.

When the code is blocking, is at least one of the I2C lines (most probably the clock line) at low level? That would proof, that it is an I2C problem (since a released I2C bus has both lines at high level). If so, it is a difficult to debug problem. You can try to use another Arduino and try to mock one of the devices with it (so it sends the same data format, behaves about the same). Then check, if the problem goes away, if not try with the other device, then maybe with both devices replaced by Arduinos. Otherwise you would need an oszilloscope to analyse the data transmission.

@chrisl I removed the screen from the circuit and wired it in with just an arduino on a breadboard.  after the arduino and screen froze while cycling through a very simple display program I measured both the SCA and SCL lines which were both high while frozen. I don't have an oscilloscope, though I have ordered another OLED to see If I just got a bad screen.

@chrisl the screen by itself on the breadboard however is far more stable than on the circuit I made is there a way to find a difference between my circuit and the circuit on the breadboard

I just experienced the same problem. A simple Arduino Nano sketch printing "Hello World" lines to one of those small 128x64 OLED I2C monitors trough SSD1306AsciiWire class provided by SSD1306Ascii library would freeze randomly (freezing the whole sketch, not just ceasing to display). Class SSD1306AsciiWire communicates through Wire. And it appears that in my case I2C through Wire was getting stuck forever. In my case replacing the OLED monitor helped: after the replacement the whole thing started working fine (I'm still testing it though).

However, there's one peculiar thing: if I used SSD1306AsciiAvdI2c class from the same library instead of SSD1306AsciiWire, the first allegedly "defective" monitor would run the same sketch perfectly and flawlessly. No freezes or glitches of any kind. Class SSD1306AsciiAvdI2c uses it own implementation of I2C maser interface instead of relying on the native TwoWire Wire. So, it appears that there's some sort of sensitive moment in TwoWire implementation that makes it act up with some of these OLED monitors.

@AnT Interesting, for my specific case I just purchased another more expensive and obviously higher quality display and that solved the problem for me.

@Asyu7: You know, it is quite embarrassing, but I found the problem in my case: I simply forgot to call Wire.begin() before starting to communicate over Wire. Once I added a Wire.begin() call at startup, everything started to work perfectly. This is basically the difference between TwoWire and AvrI2c classes: AvrI2c apparently manages to self-initialize properly, while for the standard TwoWire making a call to begin() is the user's responsibility. Without Wire.begin() the Wire "kinda works" more-or-less... it might work with some devices and freeze with others.


text:
Need Help to Select Microcontroller ?? Help
i am doing a project which has to run in side a garage to control water levels in sump pit as well as in overhead tank . also schedule running of  pumps.
i have to run 5 pumps  (two for ground water to sump pit , three for sump pit to  over head tank) check two levels also need to check when pump goes on the water is flowing or not if not try another pump
the micro controller should last at least two years .
the temperature inside garage where micro controller board will be kept will go to 47 centigrade in summer to 15 centigrade in winter .
i see many options :
1.arduino uno
2.arduino uno from sparfu and adafruit
3.Sparkfun Arduino Fio
4.SparkFun Arduino Pro Mini 328
5.Adafruit Metro Mini 328
6.Adafruit METRO 328
7.Particle Photon
what whould i use ?

That greatly depends on your exact requirements. As you seem to only control 1 pump and 2 inputs (for water level), you don't have big requirements. How should the Arduino be powered? (Though I think the Particle Photon is a big overkill for this)

i have to run 5 pumps check two levels also need to check when pump goes on the water is flowing or not if not try another pump.  arduino will be powered by a smps 5 v. supply.i am concern about the durability of the controller at this temp. range for two year.

That temperature range is no problem. What is the humidity though?

can go to 96%.....

Particle Photon is not Arduino. all the other options are almost identical

i know...........

We cannot say, what single board you need to use. There are many boards, that are fitting to your requirements. You yourself have to choose.
Most of your listed boards use the same microcontroller (as Juraj wrote in his comment):
The Arduino Uno (doesn't matter where you buy it, it's the same) and all the boards with a 328 at the end use the Atmega238P. The Sparkfun Arduino Fio uses an Atmega32U4, which is different from the 328P, but not a very big jump (though it implements native USB support). These are all AVR based microcontrollers. The Particle Photon is not an Arduino. It uses an ARM processor and has wifi.
To choose from the big amount of boards on the market, you should look into your requirements:
- How many outputs do I need? Only simple digital outputs or also PWM? If the latter, how many individual PWM pins do I need?
- How many inputs do I need? Only digital or also analog?
- What extra devices do I need? Relays for motors/high loads? Special boards? And how do they need to be connected (what interfaces they use)?
- What interfaces do I need to the outside world? LCD Display + Buttons? Bluetooth? Wifi? Or nothing?
- How computationtime- and memory-consuming are the calculation tasks, that I need to perform (resources)?
- What environment will the project be in?
Based on the answers, you can choose a board, that fit's all the requirements and still leaves a bit headroom for further development. To help you I will write some examples for your project, that might be fitting for you.

Outputs: I guess your pumps are using mains power or similar (Be VERY carefully with mains power. It can easily kill you!). You need a relay to control these. It would be easiest to use a complete relay board, that includes all the needed extra circuitry. Then you just need to use one digital output pin per controlled pump, which results in 5 pins needed.
Inputs: This depends on what level sensors you have. If they have a digital signal (like a simple switch, that triggers, when it is covered by water), you just need to tie one digital input pin to each level sensor. With 2 level sensors per tank and 2 tanks we need 4 digital input pins for level sensing.
If the level sensors work with an analog voltage, you need to use 4 analog input pins. Their usage is a bit different, since their voltage has to be converted to a number value by the ADC (Analog Digital Converter) inside the microcontroller.
Interfaces: This is mostly up to you, since you didn't specify anything. You can just build the device with any outside interfaces, if you don't need them. Then you also can use a board without wifi. If you think, that adding wifi in the future would be a great idea, you can use a wifi capable board and just disabling wifi, until you need it. (Thinking a bit in the future, what future development might get interesting for this project)
Resources: Controlling motors (pumps are only motors for the microcontroller) based on some simple inputs is somewhat the standard task for a simple microcontroller. It doesn't need much computation power, neither much memory.
Environment: The temperature is not a problem for you. Basically all microcontrollers can operate in temperatures up to 80°C und down to -35°C (the exact values can be found in the datasheet of the corresponding microcontroller). The humidity is more of a problem. You need to build a water resistant casing for the electronics of your project, so that no water can get on the electronic parts. Also - to be sure - you should put one or two of these little silica bags into the casing, which sometimes come with electronic devices or such. The silica bags will bind the water in the air inside the casing and will keep the electronics even more dry.

So you need a simple microcontroller with 5 digital outputs and 4 inputs (digital or analog depending on your sensors), so in total 9 free fitting pins. An Uno or some of it's variants are fitting for this. If you want it smaller, that the Uno, you might want to use the Nano, which is the same as the Uno, just smaller. If you want wifi capabilities, you can go with an ESP variant like the NodeMCU.
This is just an example. There are many ways to build such a project, so there is no definitive answer. Any microcontroller, that fit's your requirements, is ok for the job.


text:
Sparkfun Pro-Micro stuck on uploading
I have read multiple posts on how to reset the sparkfun pro-micro when it gets stuck during upload, and this seems to work to get it back to a state where I can upload new code again - However, I am here to ask if it is possible that it is something in my code that is causing this issue?
The reason I suspect it is my code is because I have tried:

Different pro micro
Different USB cable
Downloaded latest IDE
Downloaded latest AVR boards package
Tried reverting back to an older AVR boards package as suggested in a different post

Not sure if this is a coincidence, but when I upload a simple blink sketch I don't have any trouble, but as soon as I upload my code (below), it gets stuck on uploading...
I can get it to eventually upload after many attempts using the reset during upload trick, but it seems to be unstable. I say unstable because sometimes it will print out the values requested, and other times it will print nothing...
int clampVal = 0;

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

void ClampReading()
{
    const int numRead = 400; //amount of calibration values we will average
    double vals[numRead];      // the readings from the analog input
    int readIndex2 = 0;                 // the index of the current reading
    double total2 = 0;                  // the running total
    int calibration2 = 0;               // calibration incrementer

    for (int thisReading2 = 0; thisReading2 < numRead; thisReading2++) {
    vals[thisReading2] = 0;
    }
    while(calibration2<numRead)
    {
      int rawClamp = analogRead(A0);
      total2 = total2 - vals[readIndex2];
      vals[readIndex2] = rawClamp;
      total2 = total2 + vals[readIndex2];
      readIndex2 = readIndex2 + 1;
      if (readIndex2 >= numRead) {
        readIndex2 = 0;
     }
      clampVal = total2 / numRead;
      calibration2++;
    }

}

void loop() {
 ClampReading();
 Serial.println(clampVal);
}

EDIT:
Once I reset and upload an EMPTY sketch, I can upload the empty sketch with no problems. I did it 5 times in a row with no issues. Then tried to upload the code above once, and it worked..but then tried to upload second time, and stuck in uploading again... it has to be the code, but I can't narrow down what it is.

Uno's Mega's and so on have a separate MCU (u3) that contains the boot loader and is responsible for the USB connection and for driving the virtual serial port. Micros ( and also Leonardos and Esploras ) have built in USB support in the main MCU (u4). So if your program does something that breaks the USB part of the MCU the communication breaks also. This  happens for instance if you disable the interrupts.
The only thing you use in your program that might cause a problem is the Serial connection. The blink example has no serial output.
If you add a Serial.begin(115200) and a Serial.println("Hello") to the blink example, I guess the problem occurs also.
The IDE establishes the programming connection by connection to the selected com port at 1200 Baud. The boot loader recognizes that, performs an auto reset and opens a second (programming port) from then the IDE has access to this port and uses it to communicate with the boot loader. On a UNO this is handled by the separate MCU and on the Micro the main CPU is responsible for that.
Perhaps it helps if you add a time delay, before the Serial.begin(). Then you will have more time to start the programmer.
There is also a trick to enlarge the time you can start the programming after a reset to 8 seconds. https://forum.arduino.cc/index.php?topic=224416.msg1643210#msg1643210
And one additional hint:
Your code is unnecessarily complicated. If you want, you can try the program below. I think it does the same as yours. I have no compiler and no micro at the moment so it's complete untested.
You used a calibration variable. I guessed that it is for skip the first calibration values. If you need the values you can store them in a separate array.
My prog. has a lower memory footprint because I store the integer values from the analog input into an integer array. You used a double array.
You also did a lot of unnecessary computations after you read an analog value. This can slow down the readings. Perhaps therefore you missed some values you expected to see.
//amount of calibration values we will average
const int valueCount = 400;
const int calibCount =   0;

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

void loop()
{
  // the readings from the analog input
  int vals[ valueCount ];

  for (int idx = 0; idx < valueCount + calibCount; idx++)
  {
    int rawValue = analogRead( A0 );
    if ( idx >= calibCount )
    {
      vals[ idx - calibCount ] = rawValue;
    }
  }

  double total = (double) 0.0;

  for (int idx = 0; idx < valueCount; idx++)
  {
    total += (double) vals[ idx ];
  }

  Serial.println( total / valueCount );
}

Thanks @peter Paul Kiefer for the very thorough explanation! When I get back in front of my micro later I will try your suggestions and code, fingers crossed it works!

That seems to have done the trick. I put in a delay of 500ms between serial prints and now it uploads repeatably. Thanks for the help!


text:
What kind of antenna should i use for my esp8266 module?
I have an esp8266 module and i want to increase its range by adding an antenna to it. What kind of antena should i use. Can i use an antenna from a RC car remote?

You need a 2.4GHz antenna. 2) There is no antenna connection on that module, so you will have to bodge it: https://www.instructables.com/id/External-Antenna-for-ESP8266/

An antenna from a RC car remote won't work? Can you send me a link of the antenna that you are talking about?

A 2,4GHz antenna is a 2.4GHz antenna. Antennae have to be a specific length and tuned to a specific frequency or they are next to useless (or worse, can reduce your range). If you can't be bothered to look for one in a shop using that simple search term, then rip one off an old dead WiFi router.

@Majenko im gonna rip off my old router's antenna. Thanks for the help

You must use a WiFi (2.4 GHz) antenna. From the picture in your post, you have one of the esp8266 modules with a "built-in" antenna implemented via traces on the PCB. You cannot add an external antenna without removing the old one first, and even that will be very dodgy - you'll likely render your esp8266 useless for any purpose.
Instead, you could get an esp8266 that is made for connecting an external WiFi antenna. See the Wikipedia article for details. It specifically mentions model # ESP-WROOM-02U as having a connector for an external antenna.


text:
Using Serial.begin() twice
I'm training kids programming Arduino. We're gonna use Serial for debugging purposes, so we started with a simple HelloWorld program. I let them try various stuff, including changing the speed.
Now, one of the outcomes was as simple as
void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.begin(9600);
  Serial.println("world");
}

My expectation was, that the Arduino does exactly as written, but the serial monitor of the Arduino IDE will become a bit consufed. When the monitor is set to 115200 baud, I expected to see
Hello
world
_#&%$"    < some garbage
world
_#&%$"    < garbage again
...

However, the real output is only one line
H⸮⸮⸮⸮C

Why is that? Is it impossible to change the baud rate in between?
The official documentation does not say we can use Serial.begin() only once.
I'm using Arduino Uno and Arduino IDE 1.8.9

This is because the output of the serial is buffered. It's still sending the first bit of data while you change the baud rate - and from then on it's just a complete mess.
You need to force it to finish sending before you can change the baud rate by using Serial.flush():
void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
  Serial.flush();
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.flush();
  Serial.begin(9600);
  Serial.println("world");
  Serial.flush();
}

That will wait after each print until all the data is sent out "onto the wire" before changing the baud rate for the next print.

Wouldn't it be better to use Serial.end() to reset the buffer pointer too?

Why? It's a circular buffer - there's no beginning or end to reset it to.

Sorry, I meant the read buffer. The OP is obviously a teacher. As he has to explain it to other people, he should be aware of what is also possible and what is the difference. Using end() will not only flush the write buffer, this also resets the read buffer. This can be important as the speed switch make only sense, if it is negotiated with the communication partner.  If this happens asynchronously, there might be unwanted data in the read buffer. On the other hand, there might be situations when the read buffer should be preserved, so using end()  can be a problem too.

BTW a circular buffer has head and tail pointers. Resetting the pointers in that case means set the head to the tail pointer to clear the buffer data.

You are assuming that is the case everywhere. That functionality is undocumented. Yes, the Arduino core does it, but there are no guarantees that every core does it. Or even every version of the Arduino core does it (for example flush changed from clearing the read buffer to blocking on the write buffer...). Plus disabling and re-enabling the serial port may cause unintended side effects (floating pins) which could cause problems.

The functionality is documented https://www.arduino.cc/reference/en/language/functions/communication/serial/end/ . Your last sentence makes me think. You are right, switching the pins back to common usage can cause problems too. This must be considered in the negotiation process. I think our conversation is very informative. ;-)  At least I have some new aspects to think about.

No the functionality "clear the rx buffer" is not documented.  The function is documented, with barely any information, but nowhere does it say anything about any buffers being cleared, or even flush() being performed.

I guess I would have implemented Serial.begin() in a way that flush() is built-in. But ok, ... I think the official documentation is not perfect yet.

@PeterPaulKiefer: the good thing about teaching is: I always learn something new. Personally, I would never have written such a program, because it was clear to me that the output will be nonsense. But these kids (9 to 12 years) are not limited by their experience yet. They do funny random stuff, sometimes with unexpected outcome like this. And I hope there'll be more questions to be asked :-) I guess I can't explain it to them yet, because the concept of a "buffer" is way beyond their understanding.

I added a change request for the official documentation: https://github.com/arduino/reference-en/issues/711

@ThomasWeller I wish there were more like you. The documentation really needs a lot of work...

@ThomasWeller You are right, younger kids and artists are an unbelievable good source of inspiration. They don't fear about failures. They try things even if they think they wouldn't work.  I believe that is the difference between humans and computers and why computer can be creative. They are intended not to make errors. BTW: if the kids are really interested in MCU programming (for me it seems so) they learn with light speed. And questions about buffers can arise quicker than you think ;-)

Majenko I fully agree with you, that the documentation is in a worse state. I often have to look into the source code to find the information I am looking for. And the documentation is a nightmare for beginners. I often thought about contribute to the documentation after my investigations. But I fear my bad English is not understandable, especially for beginners. Because the documentation is not complete, I do not use it as a reference for my answers here.  "The code is the truth!"  Changes can happen in the code and also in the docs, so it doesn't matter where I based my answers on.


text:
FIXING BUG when Using Wire library to obtain compass heading
I am using the HMC-5983 magnetometer module to obtain the compass heading of a autonomous car I am building using the arduino platform.I'musing the
Z axis and X axis to obtain the heading.
However when the headingFiltered variable is at 359 and the car turns to Zero,the headingFiltered becomes to 0 via all the values between 0 and 360 rather than just becoming 0.This causes my car be constantly steering side to side when heading in this relevant direction.
Also if there is anyway that this function could be improved,I'm open to suggestions.
The function I'm using  is as follows.
void chead() {

  //---- X-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mX1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mX0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mX0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mX1 = Wire.read();
  }

  //---- Y-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mY1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mY0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mY0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mY1 = Wire.read();
  }

  //---- Z-Axis
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mZ1);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mZ0 = Wire.read();
  }
  Wire.beginTransmission(Magnetometer); // transmit to device
  Wire.write(Magnetometer_mZ0);
  Wire.endTransmission();
  Wire.requestFrom(Magnetometer,1);
  if(Wire.available()<=1)
  {
    mZ1 = Wire.read();
  }

  //---- X-Axis
  mX1=mX1<<8;
  mX_out =mX0+mX1; // Raw data
  // From the datasheet: 0.92 mG/digit
  Xm = mX_out*0.00092; // Gauss unit
  //* Earth magnetic field ranges from 0.25 to 0.65 Gauss, so these are the values that we need to get approximately.

  //---- Y-Axis
  mY1=mY1<<8;
  mY_out =mY0+mY1;
  Ym = mY_out*0.00092;

  //---- Z-Axis
  mZ1=mZ1<<8;
  mZ_out =mZ0+mZ1;
  Zm = mZ_out*0.00092;
  // ==============================
  //Calculating Heading
  heading = atan2(Zm, Xm);// arc tangent of z/x

  // Correcting the heading with the declination angle depending on your location
  declination = 0.03717551307 ;
  heading += declination;

  // Correcting when signs are reveresed
  if(heading <0) heading += 2*PI;
  // Correcting due to the addition of the declination angle
  if(heading > 2*PI)heading -= 2*PI;
  headingDegrees = heading * 180/PI; // The heading in Degrees unit
  // Smoothing the output angle / Low pass filter
  headingFiltered = headingFiltered*0.85 + headingDegrees*0.15;
  //Sending the heading value through the Serial Port to Processing IDE

  //this was done to fix an error.which was when the compass was made to turn by 180° the reading obtained did not change by 180°.
  if(headingFiltered >= 0 && headingFiltered <= 89){
    c_head=map(headingFiltered,0,90,270,359);
  }
  if(headingFiltered > 89 && headingFiltered <= 204){
    c_head=map(headingFiltered,90,204,0,90);
  }
  if(headingFiltered > 204 && headingFiltered <= 290){
    c_head=map(headingFiltered,205,290,91,180);
  }
  if(headingFiltered > 290){
    c_head=map(headingFiltered,291,359,181,269);
  }

  //Further calibration
  if(c_head>=0 && c_head<8){
    c_head=352+c_head;
  }
  if(c_head>=8){
    c_head=c_head-8;
  }

  // Serial.print("Degrees - ");
  // Serial.println(c_head);

  float teta1 = radians(clatval);
  float teta2 = radians(dlatval);
  float delta1 = radians(dlatval-clatval);
  float delta2 = radians(dlongval-clongval); //==================Heading Formula Calculation================//

  float y = sin(delta2) * cos(teta2);
  float x = cos(teta1)*sin(teta2) - sin(teta1)*cos(teta2)*cos(delta2);
  float brng = atan2(y,x);
  degris = degrees(brng);// radians to degrees
  degris = ( ((int)degris + 360) % 360 );

  dif_h=c_head - degris;
  abs_dif_h=abs(dif_h);
}

The problem comes from the low-pass filter you are using:
// Smoothing the output angle / Low pass filter
headingFiltered = headingFiltered*0.85 + headingDegrees*0.15;

This filter is designed to smooth out rapid variations of the measured
heading. If the heading suddenly jumps from 359° to 0°, the filter will
replace that jump by a continuous change that goes through the
intermediate values.
I can think of three different options for solving this problem.
Option 1: filter the Cartesian coordinates
Unlike the heading, the in-plane components of the magnetic field vary
smoothly as the vehicle rotates. You can filter these components before
computing the heading as follows:
const float filter_constant = 0.15;

float filtered_angle(float y, float x)
{
    static float x_f, y_f;  // filtered components
    x_f += filter_constant * (x - x_f);
    y_f += filter_constant * (y - y_f);
    return atan2(y, x);
}

Then you would replace
heading = atan2(Zm, Xm);

by
heading = filtered_angle(Zm, Xm);

Option 2: filter the unwrapped heading
Another possible approach is to unwrap the heading before
filtering it. This is similar to phase unwrapping: instead of
requiring the heading to be limited to the interval [−π, π] (or
[0, 360°) if you work with degrees), you let it take arbitrary
values. Each time your vehicle does a full turn, the unwrapped heading
varies by ±360°. Here is a simple unwrapping filter:
// Unwrap an angle in radians.
float unwrap(float angle)
{
    static int revolutions;
    static float previous_angle;
    float delta = angle - previous_angle;
    previous_angle = angle;
    if (delta >= M_PI)
        revolutions--;
    else if (delta < -M_PI)
        revolutions++;
    return 2*M_PI*revolutions + angle;
}

The unwrapped heading is continuous, and can be safely low-pass filtered
without creating the kind of issue you have now. After the low-pass
filter, you can wrap it again with fmod() if you wish.
Option 3: wrap the heading differences within the filter
The previous idea can be applied backwards: instead of unwrapping the
heading, you can wrap the heading differences within the low-pass
filter, in order to keep them within [−π, +π) (i.e.
[−180°, +180°)). Then, if the filtered heading is 359° and you get
a new raw heading of 0°, the difference is −359°, but you wrap
it to +1°. This will cause the filtered output to just slightly increase
to 359.15°, given your chosen filter constant of 0.15.
Here is a low-pass filter based on this idea, that is aware of how
angles are supposed to wrap:
const float filter_constant = 0.15;

// Wrap an angle to [-pi, pi).
float wrap(float angle)
{
    while (angle < -M_PI) angle += 2*M_PI;
    while (angle >= M_PI) angle -= 2*M_PI;
    return angle;
}

// Low-pass filter an angle.
float filter_angle(float angle)
{
    static float filtered_angle;
    filtered_angle += filter_constant * wrap(angle - filtered_angle);
    filtered_angle = wrap(filtered_angle);
    return filtered_angle;
}

I think I like this option better that the other two because it does its
arithmetics in a way that is consistent with how angles are supposed to
wrap, and also because it
keeps less state (only one static variable). Also, you have
implemented something very similar to the wrap() function above, in
order to wrap the heading to [0, 2π). You could instead reuse
wrap() as:
// Wrap to [0, 2 pi).
heading = wrap(heading - M_PI) + M_PI;

Edit: There is a recently published Arduino library that implements
this third option. It “provides a class, runningAngle, that computes
an exponentially weighted running average of a series of angles, such as
compass readings. It is aware of how angles wrap modulo 360°.” The
library is called runningAngle and is available through the library
manager of the Arduino IDE.