body:
Am working on a small project in which I can control the speed a 24V DC Motor using a Variable resistance to A/D then generate the right PWM to an optocoupler while displaying the speed in 4 7-segments, the problem is the PWM (PORTD Pin 5) pin 5 on the Uno is not working when I Initialize any pin of PORTB (7-segment port)

    int main(void)
    {
      uint8 duty_cycle = 0, digit_t = 0, digit_h = 0, digit_ten = 0, digit = 0, read_index = 0, duty_old = 0;
      uint16 old_reading = 0, motor_rpm, read_average = 0;
      uint32 adc_readings = 0;
      /* Declare the 4 7-segments in the system */
      // BCD_Segment seg_1, seg_2, seg_3, seg_4;

      // /* Initialize the 7-segments */
      // Segment_Init(&seg_1, B, pin0, pin1, pin2, pin3, D, pin0);
      // Segment_Init(&seg_2, B, pin0, pin1, pin2, pin3, D, pin1);
      // Segment_Init(&seg_3, B, pin0, pin1, pin2, pin3, D, pin2);
      // Segment_Init(&seg_4, B, pin0, pin1, pin2, pin3, D, pin3);
      // //
      // ///* Turn off segments */
      // //Segment_OFF(&seg_1);
      // //Segment_OFF(&seg_2);
      // //Segment_OFF(&seg_3);
      // //Segment_OFF(&seg_4);
      /* segment pins */
      //SET_BIT(DDRB, 0);
      //SET_BIT(DDRB, 1);
      //SET_BIT(DDRB, 2);
      //SET_BIT(DDRB, 3);

     /* Enable pins */
    SET_BIT(DDRD, 0);
    SET_BIT(DDRD, 1);
    SET_BIT(DDRD, 2);
    SET_BIT(DDRD, 3);

      /* display 0*/
      //CLEAR_BIT(PORTB, 0);
      //CLEAR_BIT(PORTB, 1);
      //CLEAR_BIT(PORTB, 2);
      //CLEAR_BIT(PORTB, 3);

      /* segments off */
      CLEAR_BIT(PORTD, 0);
      CLEAR_BIT(PORTD, 1);
      CLEAR_BIT(PORTD, 2);
      CLEAR_BIT(PORTD, 3);

      uint16 adc_reading = 0;
      Boolean adc_flag = False;
      /* Declare the 4 7-segments in the system */

      /* Initialize the adc and the pwm timer */
      ADC_init();
      PWM_Init();

      while (1)
        {
          ADC_StartConversion();
          adc_flag = ADC_WaitForFlag();

          /* calculate the ADC voltage */
          adc_reading = ADC_GetValue();

          if((adc_reading <= 256) && (adc_reading >= 0))
     {
       PWM_DutyCycle(0);
     }
          else if((adc_reading > 256) && (adc_reading <= 512))
     {
       PWM_DutyCycle(50);
     }
          else if((adc_reading < 768) && (adc_reading > 512))
     {
       PWM_DutyCycle(75);
     }
          else if(adc_reading >= 768)
     {
       PWM_DutyCycle(100);
     }

          /* Clear the ADC flag */
          ADC_ClearFlag();

          /* update the pwm */
          //PWM_DutyCycle(duty_cycle);
        }
    }

[![PWM working good at some ADC level][1]][1]

and here the code for the bad PWM

        int main(void)
        {
          uint8 duty_cycle = 0, digit_t = 0, digit_h = 0, digit_ten = 0, digit = 0, read_index = 0, duty_old = 0;
           uint16 old_reading = 0, motor_rpm, read_average = 0;
      uint32 adc_readings = 0;
      /* Declare the 4 7-segments in the system */
      // BCD_Segment seg_1, seg_2, seg_3, seg_4;

      // /* Initialize the 7-segments */
      // Segment_Init(&seg_1, B, pin0, pin1, pin2, pin3, D, pin0);
      // Segment_Init(&seg_2, B, pin0, pin1, pin2, pin3, D, pin1);
      // Segment_Init(&seg_3, B, pin0, pin1, pin2, pin3, D, pin2);
      // Segment_Init(&seg_4, B, pin0, pin1, pin2, pin3, D, pin3);
      // //
      // ///* Turn off segments */
      // //Segment_OFF(&seg_1);
      // //Segment_OFF(&seg_2);
      // //Segment_OFF(&seg_3);
      // //Segment_OFF(&seg_4);

      /* segment pins */
      /* just enabling one pin or all fails the PWM on PORTD PIN 5*/
      SET_BIT(DDRB, 0);
      //SET_BIT(DDRB, 1);
      //SET_BIT(DDRB, 2);
      //SET_BIT(DDRB, 3);

     /* Enable pins */
    SET_BIT(DDRD, 0);
    SET_BIT(DDRD, 1);
    SET_BIT(DDRD, 2);
    SET_BIT(DDRD, 3);

      /* display 0*/
      //CLEAR_BIT(PORTB, 0);
      //CLEAR_BIT(PORTB, 1);
      //CLEAR_BIT(PORTB, 2);
      //CLEAR_BIT(PORTB, 3);

      /* segments off */
      CLEAR_BIT(PORTD, 0);
      CLEAR_BIT(PORTD, 1);
      CLEAR_BIT(PORTD, 2);
      CLEAR_BIT(PORTD, 3);

      uint16 adc_reading = 0;
      Boolean adc_flag = False;
      /* Declare the 4 7-segments in the system */

      /* Initialize the adc and the pwm timer */
      ADC_init();
      PWM_Init();

      while (1)
        {
          ADC_StartConversion();
          adc_flag = ADC_WaitForFlag();

          /* calculate the ADC voltage */
          adc_reading = ADC_GetValue();

          if((adc_reading <= 256) && (adc_reading >= 0))
     {
       PWM_DutyCycle(0);
     }
          else if((adc_reading > 256) && (adc_reading <= 512))
     {
       PWM_DutyCycle(50);
     }
          else if((adc_reading < 768) && (adc_reading > 512))
     {
       PWM_DutyCycle(75);
     }
          else if(adc_reading >= 768)
     {
       PWM_DutyCycle(100);
     }

          /* Clear the ADC flag */
          ADC_ClearFlag();

          /* update the pwm */
          //PWM_DutyCycle(duty_cycle);
        }
    }

and the output is like this
[![PWM went Rogue][2]][2]

  [1]: https://i.stack.imgur.com/z8RjD.png
  [2]: https://i.stack.imgur.com/ufAFa.png

Here's the code for PWM_Init
```````````````````````````````
void PWM_Init(void)
{
  /* Making the pwm pin output */
  pinMode(pin5, D, Output);

  /* fast pwm mode */
  SET_BIT(TCCR0A, WGM00);
  SET_BIT(TCCR0A, WGM01);
  CLEAR_BIT(TCCR0A, WGM02);

  /* Inverting */
  SET_BIT(TCCR0A, COM0B1);
  SET_BIT(TCCR0A, COM0B0);

  /* prescaler 1024 */
  SET_BIT(TCCR0B, CS00);
  CLEAR_BIT(TCCR0B, CS01);
  SET_BIT(TCCR0B, CS02);
}

void PWM_DutyCycle(uint8_t duty)
{
  OCR0B = (duty * 255) / 100;
}
`````````````````````````````````````

title: Uno PWM freq conflicts with other PORTs

Answers: 0


body:
[![enter image description here][1]][1]Any help is greatly appreciated! Trying to build a small door lock that is controlled by a finger print sensor, (I know it will not be very practical). My issue is with putting the hardware together, I have the sensor connected to the Arduno uno with the green and yellow to pins 2 and 3 respectively, then the red and black to the ground and 5V rail. My issue is not knowing how to go about connecting the adafruit chip to the breadboard as I am going to try to use wifi for this project. Secondly I noticed most people use the adafruit Fingerprint sensor which has the module and mine is just a cheap sensor from amazon and was wondering if it will still be able to work the same? Sorry for all the questions I am very new to this and I apologize for sounding so lost haha, anything helps.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/WAgFP.jpg
  [2]: https://i.stack.imgur.com/1OzI1.jpg

title: Finger print scanner using Arduino

Answers: 0


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

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

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

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

Answers: 1

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

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

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

----

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


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

Tnx a lot

title: Understanding analog pins in pinMode

Answers: 1

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

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


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

    int button

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

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

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

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

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

Answers: 1

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

 ``` c
    //int button;

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

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


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

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

I checked the relays and they do not overheat.

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

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

Answers: 1

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


body: I am building a device using an Arduino Nano, an OLED display and infrared thermometer sensor. I want to make it rechargeable so I am using a 1 cell lipo battery and a tp4056 circuit protection board, which cuts power at 4.2 V and 2.5 V. The OLED runs in the 5.0 V port and the sensor runs in the 3.3 V port in the Arduino. Of course the system does not work since the battery only delivers 3.7 V and when I measure the voltage in the Nano, it is actually seeing around 2.6 volts in each port (I'm assuming this drop is due to internal resistance of the cables and the protection circuit). Having said that I was thinking about using a boost converter but everything I find online says that the input voltage for the boost converter should be at least 3.5 V for it to deliver a constant 5.0 V output. This would not work since as I mentioned, the protection circuit will cut the power at 2.5 V which is well below the 3.5 V mark. Is there another practical solution I could use for this system to work with 1 cell lipo battery. I don't want to use 2 cell battery pack since it would make it more expensive and bigger in size. Also, I ran the project with a 9.0 V battery and it worked perfectly fine.

title: need at least 5 volts but 3.7 lithium polymer battery does not supply enough Voltage

Answers: 2

body:
This is exactly why the typical [LiPO battery shield](https://www.instructables.com/id/Arduino-Battery-Shield/) includes a boost converter.

I'm not sure where you saw the unusually high (3.5V) low-voltage limit, but that isn't typical of most converters.

body:
I would recommend using a display that does not require 5v to run.  Using a lower voltage display like an led based one will simplify the system.  My favorite thing to use is the adafruit feather huzzah8266 with the charlieplex display board on top.  They fit together via header pins and it has a built in lipo charging circuit and battery connector.  You can then wire your sensor in and voila.
https://www.adafruit.com/product/2821
https://www.adafruit.com/product/3134


body:
I have three files:

1. `main.cpp`
2. `RotaryEncoder.h`
3. `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**

```sh
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':
<artificial>:(.text.startup+0x2dc): undefined reference to 'RotaryEncoder::getCount()'.

<hr>

**main.cpp**

```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**

```cpp
#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**

```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;
}
```

title: Undefined reference to Class::function()

Answers: 1

body:
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.


body:
I'm trying to reset my program from software using the third method described here: https://arduino.stackexchange.com/questions/1477/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?

title: Infinite loop if Serial.println() is not used

Answers: 0


body:
changed the firmware on SIM900B

try to send get request http://dummy.restapiexample.com/api/v1/employee/1
`AT+HTTPACTION=0`returned `+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());
    }

title: Sim900a AT+HTTPREAD does not get fully answer

Answers: 1

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


body: 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?

title: What Arduino and shield components are worth recycling?

Answers: 1

body:
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! :)


body:
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);} } }

title: Two Reed switch in two way directions

Answers: 2

body:
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 `delay`s 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;
        }
      }
    }

body:
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.


body: 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.

title: How Can I convert my arduino code to C/C++ embedded code

Answers: 2

body:
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:

 1. 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.

 2. 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.

body:
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.


body:
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 buffer[10];
      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

Answers: 1

body:
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


body:
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!!

title: How can I use Methods in digitalWrite(): digitalWrite(int, "methodHere")?

Answers: 1

body:
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)


body:
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
             }
        }
    }

title: Decoding serial packets, please check my work!

Answers: 0


body:
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;

    }

title: How to connect 2 Fingerprint Sensor to Arduino Mega? Please help

Answers: 1

body:
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.


body:
> 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

title: I get the following error while using esp32

Answers: 2

body: 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.

body:
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.


body:
I am using [line following IR sensor][1] 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?

  [1]: https://www.google.com/imgres?imgurl=https://potentiallabs.com/cart/image/cache/catalog/New%20Components-17/line%20following%20sensor-800x800.jpg&imgrefurl=https://potentiallabs.com/cart/buy-ir-line-following-sensor-arduino-online-india-hyderabad&docid=j4GQ_w8gG_AKrM&tbnid=KlGvLGQ41-83qM:&vet=10ahUKEwigwYbe3onmAhXJT8AKHZ9tAKsQMwhcKAIwAg..i&w=800&h=800&safe=strict&bih=937&biw=1920&q=line following] sensor&ved=0ahUKEwigwYbe3onmAhXJT8AKHZ9tAKsQMwhcKAIwAg&iact=mrc&uact=8

title: line following IR sensor not giving readings at 3m wire length?

Answers: 0


body:
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?![enter image description here](https://i.stack.imgur.com/XIuly.png)

title: Do i must have capacitors when using L7805CV voltage regulator?

Answers: 1

body:
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.


body:
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

title: Measure Natural Gas Pressure with arduino?

Answers: 2

body:
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 ...

body:
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.


body:
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?

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

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

title: How to Control 2-wire Rotary-Gear Linear Actuator

Answers: 1

body: 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).


body:
I was reading the [ATMega34u2 datasheet][1] 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?

  [1]: http://ww1.microchip.com/downloads/en/devicedoc/atmel-7766-8-bit-avr-atmega16u4-32u4_datasheet.pdf

title: ATMega32u4 SLEEP instruction

Answers: 1

body:
`SLEEP` is an assembly instruction.  You can execute assembly with [GCC's Inline Assembly](https://gcc.gnu.org/onlinedocs/gcc/Using-Assembly-Language-with-C.html) 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.


body:
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?

title: 24V LED Lights with Arduino

Answers: 2

body:
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.

body:
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.


body:
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!

title: How to Use Arduino Wifi Shield To Receive/Send Info

Answers: 0


body:
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.

title: What is the correct folder structure for including local headers in my Arduino project?

Answers: 1

body:
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


body:
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][1] and this page [this page][3] 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][2]. 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?

  [1]: https://forum.arduino.cc/index.php?topic=615973.0
  [2]: https://learn.adafruit.com/memories-of-an-arduino/optimizing-sram
  [3]: https://arduino.stackexchange.com/questions/39193/arduino-freezing-with-oled-display

title: Arduino nano with 128x64px OLED freezing

Answers: 0


body:
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 ?

title: Need Help to Select Microcontroller ?? Help

Answers: 1

body:
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.


body:
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.

title: Sparkfun Pro-Micro stuck on uploading

Answers: 1

body:
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 );
    }


body:
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?[![enter image description here][1]][1]

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

title: What kind of antenna should i use for my esp8266 module?

Answers: 1

body:
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](https://en.wikipedia.org/wiki/ESP8266) for details. It specifically mentions model # ESP-WROOM-02U as having a connector for an external antenna.


body:
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](https://www.arduino.cc/en/Serial.Begin) does not say we can use `Serial.begin()` only once.

I'm using Arduino Uno and Arduino IDE 1.8.9

title: Using Serial.begin() twice

Answers: 1

body:
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.


body:
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.

```c++
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);
}
```

title: FIXING BUG when Using Wire library to obtain compass heading

Answers: 1

body:
The problem comes from the low-pass filter you are using:

```c++
// 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:

```c++
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

```c++
heading = atan2(Zm, Xm);
```

by

```c++
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:

```c++
// 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.

[phase unwrapping]: https://ccrma.stanford.edu/~jos/filters/Phase_Unwrapping.html

## 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:

```c++
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:

```c++
// 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.

[runningAngle]: https://github.com/RobTillaart/runningAngle


body:
I have a functional sketch that I run on an Arduino Uno, the output controlling a fan module; I need another timer to run a 2nd fan and I would like to use another output on the Uno to do that rather than using another unit.

What my sketch does is as follows:

- counts 15 minutes (interval_1)
- starts the fan for 1 minute (interval_2)
- starts another cycle.

What I need to do is to add another function that will start fan#2 for 15 sec (interval_3) when the cycle starts, using another output (relayPin_1), then stop.

So the flow will be:

- counts 15 minutes (interval_1)
- starts fan#1 for 60 sec (interval_2)
- starts fan#2 for 15 sec (interval_3)
- resets and starts another cycle.

Unfortunately, can't figure out how to insert the 2nd timer.

Sketch is below, if you have any ideas that would be much appreciated.

Thanks

    const byte relayPin = 4;                           // fan#1 control on pin 4,
    const byte relayPin_1 = 7;                         // humidifier fan#2 control on pin 7,
    const unsigned long interval_1 = 1000UL * 60,      // RUN timer, msec
                        interval_2 = 1000UL * 60 * 15, // OFF timer, msec
                        interval_3 = 1000UL * 15;      // Humidifier timer
    unsigned long currentMillis, previousMillis = 0;

    void setup() {
        // put your setup code here, to run once:
        pinMode(relayPin, OUTPUT);   // Output#1
        pinMode(relayPin_1, OUTPUT); //Output#2
        // relayPin_1 controls the humidifier's fan#2
        pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
        // at startup, fan is ON for interval_1 duration
        currentMillis = millis() - previousMillis;
        if (currentMillis <= interval_1) {
            digitalWrite(relayPin, HIGH);    // fan ON
            digitalWrite(LED_BUILTIN, HIGH); // LED ON (blinking)
            delay(333 / 2);
            digitalWrite(LED_BUILTIN, LOW);   // LED Off
            delay(999);
        }

        // when interval_1 is reached, turn fan OFF for the duration of interval_2
        else if (currentMillis <= (interval_1 + interval_2)) {
            digitalWrite(relayPin, LOW);    // fan OFF
            digitalWrite(LED_BUILTIN, LOW); // led OFF
        }
        else {
            // reset the timer
            previousMillis = millis();
        }

    }

*******************************
Okay... I had time to play with it today; what it does:
it starts both fan#1 and fan#2, then stops fan#2 at (interval_1 + interval_2), but fan#1 continues running until the cycle ends.
Therefore: fan#1 runs for 35 sec, fan#2 runs for 15 sec, as it should; and the cycle is stopped for 30 sec as it should.
However, I can't make fan#1 to run for only 20 sec. as it is defined.

```

const byte relayPin = 4;   // recyrculation fan#1 control on pin 4,
const byte relayPin_1 = 7; // humidifier fan#2 control on pin 7,
const unsigned long interval_1 = 1000UL * 20,    // RUN timer fan#1, msec
                    interval_2 = 1000UL * 15,    // RUN timer fan#2, msec
                    interval_3 = 1000UL * 30;    // OFF timer
unsigned long currentMillis, previousMillis = 0;

void setup() {
   // put your setup code here, to run once:
   pinMode(relayPin, OUTPUT); // Output#1
    pinMode(relayPin_1, OUTPUT); //Output#2
     pinMode(LED_BUILTIN, OUTPUT); }

void loop() {
// at startup, fan#1 & fan#2 are ON
 currentMillis = millis() - previousMillis;
  if (currentMillis < interval_1) {
    digitalWrite(relayPin, HIGH);   // fan#1 ON
    digitalWrite(relayPin_1, HIGH); // fan#2 ON
     digitalWrite(LED_BUILTIN, HIGH); // builtin LED ON

 } else if (currentMillis < (interval_1 + interval_2)) {
    digitalWrite(relayPin_1, LOW); // fan#2 OFF

   // when (interval_1 + interval_2) is reached, turn fans OFF for the duration of interval_3
 } else if (currentMillis < (interval_1 + interval_2 + interval_3)) {
   digitalWrite(relayPin, LOW);      // fan#1 OFF
    digitalWrite(LED_BUILTIN, LOW); // led OFF

 } else {
   // reset the timer
     previousMillis = millis(); }
 }
```

title: How to add another time counter to my functioning sketch?

Answers: 1

body:
Assuming you get your logic straightened out, you should be able to add as many cases to your if statement as you want:

      if (currentMillis <= interval_1) {
          // Before end of interval 1, fan off.
      } else if (currentMillis <= (interval_1 + interval_2)) {
          // In interval 2, fan on
      } else if (currentMillis <= (interval_1 + interval_2 + interval_3 )) {
          // In interval 3, fan2 on
      } else {
          // Turn everything off
          // reset the timer
      }


body:
I would like to build an automatic watering system. So my research brought me to the following items:

 - Breadboard Solderless Prototype PCB Board – ALLDE BB-007 (3pcs) 400 Pin with 4 power Rails and Double Sided Tape
 - Capacitive Soil Moisture Sensor (Operating voltage: 3.3 ~ 5.5 VDC, Output voltage: 0 ~ 3.0 VDC, Interface: PH2.54-3P)
 - 1 Channel 5V Relay Module (VCC: Connect 5V Positive Pole Power Supply, GND: Connect 5V Negative Pole Power Supply)
 - Mini Water Pump (DC Voltage: 3-5 V)
 - Arduino UNO REV3 [A000066]

I am beginner in electronics so I have some very basic questions. Given the above specifications, and assuming I would like to power this system with battery and not to a power outlet, what battery do I need to power up the Arduino? I would like to have this system running for at most 30 days. The system will be running constantly until the moisture sensor indicates that watering is needed, in which case will run the mini water pump for some time (I don't know how long this will be running).

Could a battery power up this system? I am not sure if I can link products, but this system is based on [this][1] system if I forgot to include some critical information about the system.

So to summarize, is is possible to power up this system with a battery pack, if so which battery should I use?

  [1]: https://www.amazon.com/WayinTop-Automatic-Irrigation-Watering-Capacitive/dp/B07TLRYGT1

title: Items needed to build an automatic watering system

Answers: 2

body:
I'd suggest feeding the system with a 12V lead-acid battery and a buck DC/DC converter with 5V output. (Those are more efficient than the regulators in Arduinos.) You could feed the regulated 5V directly into the USB port on your Arduino. You'll probably need a filtering capacitor on the Arduino 5V input to reduce fluctuations in power as the pump turns on and off however.

You'll need to do some back-of-the-envelope calculations on the power consumption of the Arduino, the on current of the water pump, the expected max duty cycle of the pump, and the efficiency of the DC/DC converter. That will let you estimate the power consumption of the whole system in mW/hr. You can then get a battery big enough to power it for your desired run-time. If you add a solar powered charging system you could increase your run-time or even make it run purely on solar power (with a big enough panel and enough bright sunshine.)

body:
For start, I would be seriously supprised if 5 volt pump does much good and vould start from 12VDC (car or campa-van stuff...) I would be supprised if you do not have 12DC supply around (from old router, chinese gimic sliming devices, christmas light box, cable setup-box...)

Don't panic, You may be able to get relay capable of switching higher Voltages.

Second: Newer connect anything that has solenoid directly to arduino. (not even relay). Most IC's or MCU's are only able to handle opening mosfet or a transistor, only some can handle one LED. Although in the moment relay switches off, it (its induced current) will take Arduino with it. if instead you use some common cheap NPN transistor and a diode across(in opposite direction).
I recommend soldering. relays and the things you power from them.
last get an IP55 box from nearest electric shop.

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

And lastly I would have replaced UNO for NANO here. Its much more compacr and fits easily into IP55 box
 For battery you van use car battery...
I Find since Yuasa started destroying (buying ) competition, the lead-acids lifespan gone far down (on alarms often insufficient in a year)