message:
How to safely remove arduino nano from breadboard?

I did some prototyping with arduino nano in breadboard. And then after i done with the design, I was gonna implement it in a printed pcb so i need to remove the nano from breadboard. And this is when the disaster happened.

The board is kinda hard to pull by hand, so i use a long-thin screwdriver in the gutter to pull the nano up (just like i did many times to dip ICs with no problem). And successfully detached the nano from breadboard and also broke the tantalum under the nano in the process. So the question is:

1. How do you usually remove the nano board from breadboard safely? And
2. The tantalum i broke is 4.7uF smd. I can't find any 4.7uF tantalum in nearby shops, but i have electrolyte caps rated 4.7uF 16v. Can i use it for replacement?

body: I also had the same problem but what I had done was, I pressed the breadboard with my leg and used my all fingers to grip the nano and pulled it with my full force and then it is done. And no parts were damaged and id you lost any part you can search on https://octopart.com/ .


sender: user

sender: assistant

body:
> How do you usually remove the nano board from breadboard safely? And

If you can't remove it by hand (grip it lengthwise and ease up each end with your finger / thumb levering against the breadboard) then you need a lever. The best is a plastic spudger, such as this:

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

The plastic will flex rather than damage the Arduino. Using a screwdriver can, as you have noticed, damage the Arduino.

> The tantalum i broke is 4.7uF smd. I can't find any 4.7uF tantalum in nearby shops, but i have electrolyte caps rated 4.7uF 16v. Can i use it for replacement?

Sure. All that is, is a reservoir capacitor on the USB input. The value isn't super-critical, as long as the voltage is above 5V. It's not, strictly speaking, even needed. You can just remove it completely and clean up the pads to ensure there's no shorts. The board should still work fine.

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


message:
Adafruit RGB LCD w/ Shield kit connection to arduino uno?

I have a [adafruit rbg 16x2 lcd with shield kit][1] and am trying to connect it to an arduino uno. The only thing is the assembly instructions have the lcd basically using every pin on the arduino, even tho it says its not for connections. Since we are using many of the pins already on the board, can I wire it to the board without soldering it to every pin, essentially only wiring to the few necessary pins?

Sorry, I am very new at this. Thank you for the help.

EDIT: Was essentially looking for the follwing diagram. Thanks to all!
[![enter image description here][2]][2]

  [1]: https://learn.adafruit.com/rgb-lcd-shield
  [2]: https://i.stack.imgur.com/b2vgu.png

body:
The idea of shields is that they (in theory) can be stackable.
(In practice they are usually not)
This means that technically you can do this:

[![stack of shields][1]][1]

That's why by design every shield connects to every Arduino pin but uses only some of them. That way shield is mechanically well attached to the Arduino, and can pass "unused" pins to the shield above it.

Your shield is designed to be always "on top" so I think it only connects to some pins just for mechanical support. Technically the LDC screen needs only 6 pins and 1 pin per button.

EDIT:
I read now that the shield you got uses only 2 pins and communicates using I2C bus (which is perfect) so I'm 100% sure that it's designed to be on top of the stack and work together with other shields and uses extra pins for mechanical support.

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


message:
Replicate output of pwm pin on another output pin?

Ardiuno Mega 2560

I have a legacy PCB that connects PORTA, pins = {22, 23, 24, 25, 26, 27, 28, 29} to the PWM input of a set of actuators. The accompanying code made use of an interupt service routine to generate PWM signals. This in turn caused all sorts of other problems for the system.

So, I would like to leverage the Mega's internal counters & use the PWM available on pins = {2, 3, 4, 5, 6, 7, 8, 9} & use the `analogWrite()` function. At present there is nothing else connected to these pins but access is limited.

Before I go down the route of redesigning the PCB I was wondering if it was possible to replicate the outputs of pins {2, 3, 4, 5, 6, 7, 8, 9} to pins {22, 23, 24, 25, 26, 27, 28, 29}?

body:
As Jot wrote, you cannot simply route a signal from pin to pin inside the chip/Arduino. So - unless you redesign the PCP, which would be the cleanest way, or use jumper wires, which is not so clean - you are down to using software PWM. There are also libraries for this, if you don't want to write this yourself, for example the [SoftPWM library][1]. These libraries have their own limits, especially in frequency. Be sure to check, if they fit your needs.

  [1]: https://github.com/bhagman/SoftPWM


message:
Powering an Arduino directly from a motor driver (DRV8825) or external power source?

Hello people from StackExchange,

I'm new to Arduino and driving stepper motors in general; please excuse me for my limited knowledge on the subject. I've been doing research for a few hours already, looking into powering stepper motors and the Arduino, though I've gotten conflicting information regarding my problem.

My problem, or well question if you will, is as follows:
The circuit I need, simplified, contains an Arduino, a stepper motor driver (DRV8825), a NEMA17 5kg.cm stepper motor and a 12V battery pack (yet to be decided what kind of pack, though it will be 12V). Do I need another, lower voltage, battery pack?

After looking into how to power stepper motors using the Arduino online, I found several sites instructing me how to do so. All of the sites had the same circuit I would use, only the motor was different. Here is one of the circuits:

[![Circuit from LastMinuteEngineers, note it only has a single power supply][1]][1]

As you can see, it only has a single power supply (with capacitor to catch voltage peaks). I understand most of the circuit, though one question remains: why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver? (You can see the pin descriptions in the second image below) Or do they simply not show the (5v) power supply for the Arduino?

The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not? And if not, would connecting the Arduino to the power supply via the VIN pin work? That would be nice, as it would offer a simple way of fixing the problem instead of getting a separate power source. Connecting the Arduino through USB wouldn't work for my project, as it can't have any wires coming from it. It needs to be completely mobile.

For comparison, here is a circuit that does show the Arduino with an external power source:

[![Circuit that does have an external power source][2]][2]

I'm a first years mechanical engineering student, hence my little knowledge on Arduino's and stepper motors.

Thanks in advance.

  [1]: https://i.stack.imgur.com/s6R4B.png
  [2]: https://i.stack.imgur.com/laViw.jpg

body:
> why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver?

No. It is assumed that you will provide the power to the Arduino yourself - either through the USB connection to the computer, or through the barrel jack.

> The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not?

No. The Arduino requires power to be provided.

> And if not, would connecting the Arduino to the power supply via the VIN pin work?

Yes, but it's not ideal.  At 12V the power wasted by the on-board linear voltage regulator will be proportionally high.  As long as all that is being powered is the Arduino itself that shouldn't be too bad, but if you try to draw any significant current either out of the 5V pin or through multiple IO pins (for example to drive lots of LEDs) then it will overheat and potentially shut down.

A more ideal arrangement would be to connect a 5V switching regulator to the 12V battery and use that to power the Arduino either through the 5V pin or the USB connector. Personally, I use cheap UBEC modules from RC model suppliers. They are small, low-cost, and very easy to wire up.


message:
Getting weird characters from Arduino

My arduino is connected to ultrasonic sensor and I am trying to read the value from it. When I tried running "tail -f > /dev/ttyACM0" my arduino is sending some weird characters that I am not able to decode[![enter image description here][1]][1]

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

body:
It would seem you failed to configure the port on the Linux side. By
default, it is configured to who-knows-what baud rate, and to a “cooked”
mode where the data is preprocessed by the kernel driver. You want
instead to set it to the correct baud rate and to “raw” mode. The `stty`
(meaning, “set terminal”) command does this:

    stty -F /dev/ttyACM0 raw 9600

Replace 9600 with whatever baud rate your Arduino is using.

If you Arduino program attempts to read the serial port, it will see the
echo of the characters it sends. In that case you probably want to
disable this echo also:

    stty -F /dev/ttyACM0 raw -echo 9600


body:
Most likely this is incorrect baud rate. You can try with a program dedicated to serial ports, my personal choice is picocom but it can by minicom or any other:

    $ picocom -b 9600 /dev/ttyACM0

The `-b` parameter is used for specifying the baud rate, depending on the sketch it can be something else than 9600, the most common ones are: 9600, 14400, 19200, 28800, 38400, 57600

Another solution is to configure the `/dev/ttyACM0` with correct baud rate using `stty`:

    stty -F /dev/ttyACM0 9600 cs8 -cstopb -parenb

This will configure the serial port to 9600 bps, 8 bits, 1 stop bit, no parity, and allow the `tail` command to read it correctly, if the communication parameters match what the arduino is sending


message:
Can the 'Adafruit Non-Latching Mini Relay FeatherWing' be used with an Arduino microcontroller such as an Arduino Mega 2560?

Can this relay found here:

https://www.adafruit.com/product/2895

Be used with an Arduino Mega? The description given seems to specify that you should hook it up to their dedicated 'Featherwing Board' but it's the only relay available on their site. Looking at the pins it has it seems it should hook up to an Arduino with no problems. Has anyone here had the chance to use this relay with an Arduino microcontroller? I asked them about this on their forum but I haven't received a reply yet.

PS: I want to use it to connect a 'Strobe Siren 12VDC' and the relay I was looking to get is out of stock at my local shop.

https://store.nerokas.co.ke/index.php?route=product/product&product_id=1398
https://store.nerokas.co.ke/index.php?route=product/product&product_id=1679

body:
Yes.

There's not a lot more to be said really.

It's a relay, and they provide a MOSFET and associated circuitry to drive it cleanly.

Just connect power and ground to the Arduino, along with the "Signal" pin to the GPIO pin of your choice, and away you go.

Note that the relay is a 3.3V relay, so you must power it by the 3.3V pin, not the 5V pin.


body:
That is a 3.3V device. you'll need to give it a separate 3.3V power input, and it needs much higher current at 3.3V than the Arduino can supply.

 I don't know if you can feed it a 5V logic signal or not. (If it needs 3.3 V control signals as well, and it's current needs are modest you could step down the voltage from an Arduino 5V digital output to 3.3 with a simple voltage divider circuit.)

You'd be better off getting a 5V relay. If you do a Google search on "Arduino Relay" you'll find tons of them. You can get 1 relay, 2 relay, 4 relay, and more on a board. Many have optical isolation to make sure the relay coils don't add noise to the logic lines.

In general it's a good idea to use a separate power supply for the relay, or at least use a power supply with plenty of current to spare, and add filtering capacitors between the 5V rail and ground right next to both the relay and the Arduino. These capacitors serve to filter out variations in voltage as the relay coils are powered on and off.

(Even "digital" relays draw a large amount of current from their power source when they first turn on, and abruptly *stop* drawing current when they turn off, which introduces a lot of noise on the power line. "Naked" relays need "flyback diodes" to avoid reverse currents that will destroy transistors, but the "digital ready" relays I'm talking about have those built in.)

Here is one such relay I found from Googling "Arduino relay".

https://vetco.net/products/single-relay-module-for-arduino?gclid=EAIaIQobChMI8Ye70K-e4QIVBkSGCh2EBgEiEAQYAyABEgIxpvD_BwE


message:
Control 2 ESC with a potentiometer with arduino

I have 2 ESC (electronic speed controller) which control these brushless motors: [Hobbyking Donkey ST3511 Brushless Motor][1]

I would like to make them work with a poentiometer, under arduino.

I have a program but it only works with one engine. Here is the program :

    #include <Servo.h>//Using servo library to control ESC

    Servo esc;
    Servo esc2;
    //Creating a servo class with name as esc

    void setup()

    {

    esc.attach(9); //Specify the esc signal pin,Here as D8

    esc.writeMicroseconds(1000); //initialize the signal to 1000

    Serial.begin(9600);

    esc2.attach(9); //Specify the esc signal pin,Here as D8

    esc2.writeMicroseconds(1000); //initialize the signal to 1000

    Serial.begin(9600);

    }

    void loop()

    {

    int val; //Creating a variable val

    val= analogRead(A0); //Read input from analog pin a0 and store in val

    val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(Change if needed)

    esc.writeMicroseconds(val); //using val as the signal to esc
    esc2.writeMicroseconds(val);
    }

I did not find help on the internet, thank you in advance.

  [1]: https://hobbyking.com/en_us/hobbyking-donkey-st3511-810kv-brushless-power-system-combo.html?gclid=CjwKCAjwm-fkBRBBEiwA966fZNUs_Lq5O0I9nkySMYFtYdEYreK2LXFlR0XGbOV2MIj9oXWXFvWRkxoCAhEQAvD_BwE&gclsrc=aw.ds&___store=en_us

body:
If you want one potentiometer to handle BOTH ESCs' speed, you could use this code:

    //Using servo library to control ESC
    #include <Servo.h>

    //Starting the servos
    Servo esc1;
    Servo esc2;

    void setup() {
        esc1.attach(9); // Use a PWM pin to the Servo, in this case 9
        esc1.writeMicroseconds(1000); //initialize the signal to 1000
        esc2.attach(10); // Pick another PWM to the other, in this case 10
        esc2.writeMicroseconds(1000); //initialize the signal to 1000

        Serial.begin(9600);
    }

    void loop() {
        int val; //Creating a variable val
        val= analogRead(A0); //Read input from analog pin a0 and store in val
        val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(analogRead's goes from 0-1023 and analogWrite's goes from 0-255, check your servo's specs)
        esc1.writeMicroseconds(val); // write to the first ESC
        esc2.writeMicroseconds(val); // write to the second ESC
        delay(100); // We usually set a small delay to avoid excessive readings or over-heating, but thats optional...
    }

If you need to use two potentiometers, one for each ESC, then you would have to start another variable to read the 2nd pot value and use it to write on the 2nd ESC, simple as that! :)


message:
Is Ticker.h really safe to use?

I have this code

    #include <Ticker.h>  //Ticker Library
    Ticker blinker;
    /* ... */

    //blinker.attach(1, []() { digitalWrite(LED,!digitalRead(LED)); }
    while(!client.connect(laptop,port)) {
       Serial.println("Connecting...");
       delay(1000);
    }

Which works fine, tries connecting, then eventually connects.

If I uncomment the line attaching to this 'blinker' Ticker, then I get a crash right after the first 'Connecting...' print. When I look at the stack trace, it mentions that the crash happens during the delay(1000) in my while loop (which is presumably the moment when the program yields and the blinker can do some work)

Is there anything I can do to make this timer work better?

body:
**Update**: the original question mentioned timers, so this answer is for a hardware timer interrupt handler. It doesn't apply to `Ticker`, which is what the question is now about.

The callback that you attach to `blinker` will be called as an interrupt handler, so it's important to make sure it's already loaded into executable instruction memory (iRAM) on the ESP8266. When you pass anonymous function inline to `blinker.attach()` it won't tagged to be stored in iRAM.

Try this instead:

    void ICACHE_RAM_ATTR blinker_handler(){
        digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
    }

    ...

    blinker.attach(1, blinker_handler);

`ICACHE_RAM_ATTR` tells the system to keep the code in the instruction RAM. There's not a lot of iRAM (32Kbytes) so you don't want to do this too often, but it's important for interrupt handlers (another reason to keep them short and sweet).


message:
Powering Uno with 9v battery makes it "freak out"

I encountered an odd problem with my Uno, it works completely fine through USB on the PC or when powered by a power bank, but as soon as I connect it on a 9v battery it just freaks out. I have a relay connected to it that is connected to a switch, works fine, but on the battery it keeps turning on and off super fast, like so fast that the relay doesn't even show it's doing it, I noticed because of the noise it makes. I even tried to slow it down with a delay but nothing changed.

Anyone have any idea why the battery would make this happen?

body: Not enough current available from the battery, relays take quite a lot. As soon as the relay tries to switch the voltage drops and the Uno resets due to brownout (low voltage)


body: It's actually not just the relay that takes up a lot of current. The 9V-port on your arduino uno is actually not meant for a 9V block, because the arduino uno needs a higher current than your 9V block can deliver. You can put 6 1.5V battery cells (AA batteries) in series, they will deliver the current you'll need.


message:
Cannot upload to Robotdyn Mega 2560 PRO MINI?

I get this error trying to upload `avrdude: stk500v2_ReceiveMessage(): timeout`

It is Robotdyn Mega 2560 PRO MINI and a Robotdyn CH340 which I have connected like this: [![enter image description here][1]][1]

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

I installed the CH340 drivers from here https://sparks.gogo.co.nz/ch340.html and I can see it in the device manager.
Connecting the Mega 2560 Pro Mini lights up the `L` and `On` LED but when pressing upload (testing with simple examples as Blink) I get the error and neither RX or TX lights up.

I have tried everything I can think of. What am I doing wrong?

I have confirmed that it is connected to the correct COM-port and I use these settings:

    Board: Arduino/Genuino Mega or Mega 2560
    Processor: ATMega2560 (Mega 2560)

I have also tried many different USB-cables, short and long, and USB 2.0 and USB 3.0 ports. I use Windows 10 64-bit.

body:
Try placing a 100nf capacitor on RST. That is usually required on an FTDI programmer.

See Edgar's post - https://arduino.stackexchange.com/users/47431/edgar


message:
Parsing array of an object in a library constructor

I am trying to develop an Arduino library that consists out of two classes. I want 'WayPointStack' to store an array of 'WPCommand', but I can't get it to work.

WayPointStack.h

    #ifndef WayPointStack_h
    #define WayPointStack_h

    #include "Arduino.h"
    #include "WPCommand.h"

    class WayPointStack
    {
      public:
     WayPointStack();
     WayPointStack(WPCommand* wp);
        WPCommand GetNextWP();
     WPCommand GetWP(int i);
     void AddWP(int target, int time);
     int SetWPPointer(int i);
     int GetLength();
      private:
     WPCommand* _wp;
     int pointer;
     int length;
    };
    #endif

WPCommand.h

    #ifndef WPCommand_h
    #define WPCommand_h

    #include "Arduino.h"

    class WPCommand
    {
      public:
     WPCommand(int target, int time );
        WPCommand();
     int GetTarget();
     int GetTime();
     int LEFT;
     int RIGHT;
     int FORWARD;
     int BACKWARD;
     int STOP;
     int END;
      private:
        int _target;
     int _time;
    };

    #endif

Parts of WaypointStack.cpp

    #include "Arduino.h"
    #include "WayPointStack.h"
    #include "WPCommand.h"

    #define arrSize 100

    WayPointStack::WayPointStack()
    {
      _wp = new WPCommand[arrSize]; // should be enough, heap blabla
      length = 0;
      pointer = 0;
    }

    WayPointStack::WayPointStack(WPCommand[] wp)
    {
     _wp = new WPCommand[arrSize]; // should be enough, heap blabla
     for (int i = 0; i < sizeof(wp), i++){
      _wp[i] = wp[i];
     }
     length = sizeof(wp);
     pointer = 0;
    }

I'm pretty sure I'm doing something wrong with the pointers, but I don't know how to fix it. The first two errors are

    WayPointStack.cpp:24:42: error: expected ',' or '...' before 'wp'
    WayPointStack::WayPointStack(WPCommand[] wp)

and

    WayPointStack.cpp:27:29: error: 'wp' was not declared in this scope
    for (int i = 0; i < sizeof(wp), i++){

I obviously have to use a pointer. This is all I know, so far.
Has someone an idea?

body:
This is a C++, not Arduino question and should be asked on Stack Overflow.

In C/C++ the [] must be on variable name, not on type. `WPCommand wp[]` (it is the same as `WPCommand* wp`).

`sizeof` return size in bytes, not element count. send `length` as parameter

Dynamic memory allocation in MCU is not a good thing. You can have in `WayPointStack`

    WPCommand _wp[arrSize]


message:
switching two relays without delay using millis

I have an Arduino-uno and two relays. Each relay has two switch on for two seconds at regular intervals.
total loop time relay 1 and relay2 is 1800 seconds.
relay 1 - 2 on,360 off,2 on,600 off,2 on,430 off,2on,402 off.
relay 2 - 12 off, 2 on, 358 off, 2 on, 606 off, 2 on, 478 off, 2 on, 338 off.
Can somebody help me on a code for this please.

body:
this is a typical application for [Blink Without Delay][1]

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


message:
Arduino nano power 5V or 12V and LED strip 2812B 5V

I would like to know a little more about Arduino inputs and outputs.

I'm doing a small project which is composed of 1 LED strip with 40 LED's.

Can't find any definitely information about Arduino +  LED strip.

At the moment all of this doesn't work correctly and I guess the reason is bad power connection .

The main power is from USB. So all of this in a car. I have ~12v (+2 or -2 Volts ) and then Voltage regulator to 5V with USB output and then cable connecting 5V through USB Arduino . Then I took wires from VIN ( pin number 30 ) to LED strip +5V ( which is basically main fuse on the strip ) and then GND to ground of led strip and of course DIN to DIN like it should be.

Conclusion is - the led strip won't work normally and colors are not proper .

How should I do connect ?

If I will take off the voltage regulator then main fuse from the car ~12V connect to the VIN (it will be a main arduino power) . GND - GND pin obviously.  - and then again from same point ~12V of car will connect to voltage regulator 12V to 5V and that 5V must be with LED strip FUSE +5V ?

Is it will be correct way ?
And one more question, shall I put between "*main fuse from the car ~12V connect to the VIN (it will be a main arduino power)*" - Voltage regulator 12V to 5V ? is it necessary ?

Thanks for you answers guys, hope you will help me with this.

I'm going to read same questions and answer with this any way. Will wait your answers too :)

body:
> The main power is from USB. So all of this in a car. I have ~12v (+2 or -2 Volts ) and then Voltage regulator to 5V with USB output and then cable connecting 5V through USB Arduino .

Good. That is the best way of powering an Arduino in a car. Use a phone charger is best.

> Then I took wires from VIN ( pin number 30 ) to LED strip +5V

There's no such thing as a "pin number 30" on an Arduino Uno. However, powering *anything* from VIN when you are supplying power into the Arduino through USB is *very* bad.

Basically, the current has to flow *backwards* through the onboard regulator to get to the VIN pin - and the regulator *really* doesn't like that.

Instead, you should be connecting your LED strip to the 5V pin of the Arduino so it is connected direct to the 5V USB power.

Note, however, that the USB power has a limit of 500mA.  This is not a limit of the supply - it is a limit imposed by a 500mA PTC fuse on the Arduino that will shut off the current if more than 500mA is drawn.  It would be far better if you could cut the USB cable and take the 5V and GND wires and directly connect them to both the Arduino's 5V and GND pins, and the LED strip's 5V and GND connections.  That will then mean that the LEDs are taking their power directly from the power supply, not from the Arduino.


body:
40 LEDs can draw up to 60mA x 40 = 2.4A (2400mA). Make sure you have a large enough current source if you are planning on using full white on all LEDs.

Arduino regulators are not selected to support 2.4A. 600-700 mA tops, and then only if the voltage to the barrel jack is 7.5V max. With 12V, much less current is supported as the regulator gets hot dissipating (12V - 5V) x current draw as excess heat.

And 500mA for USB as noted due to PTC fuse.


message:
1st LED turn ON when 1st button is pressed and other LEDs remaining OFF

I have 2 LEDs and 2 buttons. What I want to code is when first button pressed the 1st LED turn on (stay on for 5 seconds) and 2nd LED remain off, and same if 2nd button pressed the 2nd LED turn on and 1st LED remain off. I want the processing reset after 5 seconds.
Here is my work, what it does now is 1st LED turn on when I press 1st button, but the 2nd button and 2nd LED still can press and light up right after. I want the 2nd button deactivate when 1st button pressed for 5 seconds.
Please give me basic program because I am new to this.

    int pinButton_1 = 8; //the pin where we connect the button
    int pinButton_2 = 9;
    int LED_1 = 1; //the pin we connect the LED
    int LED_2 = 2;
    void setup() {
      pinMode(pinButton_1, INPUT); //set the button pin as INPUT
      pinMode(pinButton_2, INPUT);
      pinMode(LED_1, OUTPUT); //set the LED pin as OUTPUT
      pinMode(LED_2, OUTPUT);
    }

    void loop() {
      int stateButton_1 = digitalRead(pinButton_1); //read the state of the button
      int stateButton_2 = digitalRead(pinButton_2); //read the state of the button
      if(stateButton_1 == 1) { //if is pressed
         digitalWrite(LED_1, HIGH); //LED_1 on
         digitalWrite(LED_2, LOW); //LED_2 off
         delay(50);
      }
         if (stateButton_2 == 1) {
          digitalWrite(LED_1, LOW);
          digitalWrite(LED_2, HIGH);
          delay(50);
         }
      }

body:
First of all you have not implemented a stay on time of 5seconds `delay(5000);` but only 50ms `delay(50);`.

Second, you are not really switching of your LED's if no further button is pressed.

Change your `loop()` to the following, I guess this will help you to start your next steps into getting familiar with your code:

        void loop() {
          int stateButton_1 = digitalRead(pinButton_1); //read the state of the Button_1
          if(stateButton_1 == 1) {      //if Button_1 is pressed
             digitalWrite(LED_1, HIGH); //LED_1 on
             digitalWrite(LED_2, LOW);  //LED_2 off
             delay(5000);
          }
          digitalWrite(LED_1, LOW); //Switch off LED_1

          int stateButton_2 = digitalRead(pinButton_2); //read the state of the button 2
          if (stateButton_2 == 1) {
             digitalWrite(LED_1, LOW);
             digitalWrite(LED_2, HIGH);
             delay(5000);
          }
          digitalWrite(LED_2, LOW); //Switch off LED_2
        }

**Hint:** Using `delay()` is often not a good construct, better to do it with `millis()`, but this means some more changes. For the start in your case `delay()` will do, but check out what here in different Questions/answers is already written about `delay()` vs. `millis()`


message:
what is the difference between array of uint16_t data versus an array of uint16_t variables?

I've been struggling with weird behavior, crashes and general problems when trying to use an array of four uint16_t groups of data. When I create four separate variables and load that into an array, it works OK and is smaller.

This is for use with the irlib2 SendBase and HashRaw components.

What's going on here?

The code utterly fails with crashes, unresponsive hardware when I use the following variable assignment with an arduino micro. Additionally this version uses about 400 bytes more of memory than the second example

**failed variable assignemnt**
```
uint16_t sources[4][RAW_DATA_LEN] = {
  {8550, 4306, 530, 1606, 530, 566, 502, 1610, //POWER ON/OFF
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000},

  {8546, 4310, 558, 1578, 562, 538, 498, 1638, //sourceCD
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000},

  {8550, 4306, 530, 1606, 534, 566, 502, 1606,  //sourceCDR
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000},

  {8550, 4310, 526, 1634, 506, 566, 502, 1634,  //sourceAUX
  506, 566, 502, 574, 506, 1626, 510, 566,
  506, 1630, 506, 566, 502, 1634, 506, 566,
  502, 1634, 506, 1606, 530, 566, 506, 1630,
  506, 566, 502, 1634, 506, 1630, 506, 1630,
  510, 1602, 526, 570, 510, 566, 502, 1634,
  502, 570, 502, 570, 510, 566, 502, 570,
  510, 562, 506, 1630, 506, 1630, 510, 562,
  506, 1630, 510, 1000}
} ;
```

When I instead assign each grouping to a variable and then create an array of those variables, the code is significantly smaller (about 400 bytes) and appears to run as expected without crashes.
**Successful variable assignment**
```
#define RAW_DATA_LEN 68
uint16_t powerOnOff[RAW_DATA_LEN] = {
  8550, 4306, 530, 1606, 530, 566, 502, 1610,
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000
};

uint16_t sourceCD[RAW_DATA_LEN] = {
  8546, 4310, 558, 1578, 562, 538, 498, 1638,
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000
};

uint16_t sourceAUX[RAW_DATA_LEN] = {
  8550, 4310, 526, 1634, 506, 566, 502, 1634,
  506, 566, 502, 574, 506, 1626, 510, 566,
  506, 1630, 506, 566, 502, 1634, 506, 566,
  502, 1634, 506, 1606, 530, 566, 506, 1630,
  506, 566, 502, 1634, 506, 1630, 506, 1630,
  510, 1602, 526, 570, 510, 566, 502, 1634,
  502, 570, 502, 570, 510, 566, 502, 570,
  510, 562, 506, 1630, 506, 1630, 510, 562,
  506, 1630, 510, 1000
};

uint16_t sourceCDR[RAW_DATA_LEN] = {
  8550, 4306, 530, 1606, 534, 566, 502, 1606,
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000
};

//Set up array of codes
uint16_t sources[4] = {powerOnOff, sourceCD, sourceCDR, sourceAUX};
```

This is the code as it stands in an unfinished state. In an effort to trace back the crashes and odd behavior I systematically removed most of the code to the point where the last if statement is sending the IR codes.

**Entire Code**
```
#include <movingAvg.h>    // moving average library
#include <IRLibSendBase.h>    //We need the base code
#include <IRLib_HashRaw.h>    //Only use raw sender
#include <elapsedMillis.h>    //measure elapsed time

// ====REMOTE CODES====
//define the IR Sender
IRsendRaw mySender;
#define RAW_DATA_LEN 68
uint16_t powerOnOff[RAW_DATA_LEN] = {
  8550, 4306, 530, 1606, 530, 566, 502, 1610,
  530, 566, 502, 574, 506, 1630, 506, 566,
  506, 1630, 506, 566, 502, 1610, 530, 566,
  502, 1634, 506, 1606, 530, 570, 498, 1634,
  506, 570, 510, 562, 506, 566, 502, 1634,
  506, 1606, 530, 1610, 530, 562, 538, 538,
  530, 542, 538, 1598, 538, 1570, 558, 542,
  538, 538, 530, 542, 538, 1598, 530, 1578,
  558, 1578, 562, 1000
};

uint16_t sourceCD[RAW_DATA_LEN] = {
  8546, 4310, 558, 1578, 562, 538, 498, 1638,
  530, 542, 506, 570, 502, 1634, 502, 570,
  498, 1638, 534, 538, 498, 1638, 530, 542,
  506, 1606, 554, 1582, 558, 538, 510, 1602,
  554, 546, 506, 566, 502, 570, 510, 1602,
  554, 1582, 558, 538, 510, 566, 502, 1606,
  554, 546, 502, 1610, 558, 1574, 554, 546,
  502, 570, 510, 1602, 526, 1610, 526, 574,
  506, 1602, 526, 1000
};

//uint16_t sourceAUX[RAW_DATA_LEN] = {
//  8550, 4310, 526, 1634, 506, 566, 502, 1634,
//  506, 566, 502, 574, 506, 1626, 510, 566,
//  506, 1630, 506, 566, 502, 1634, 506, 566,
//  502, 1634, 506, 1606, 530, 566, 506, 1630,
//  506, 566, 502, 1634, 506, 1630, 506, 1630,
//  510, 1602, 526, 570, 510, 566, 502, 1634,
//  502, 570, 502, 570, 510, 566, 502, 570,
//  510, 562, 506, 1630, 506, 1630, 510, 562,
//  506, 1630, 510, 1000
//};

uint16_t sourceCDR[RAW_DATA_LEN] = {
  8550, 4306, 530, 1606, 534, 566, 502, 1606,
  534, 566, 502, 570, 510, 1602, 526, 570,
  510, 1602, 534, 566, 502, 1606, 534, 566,
  506, 1602, 530, 1606, 534, 566, 502, 1610,
  530, 570, 498, 574, 506, 566, 502, 570,
  510, 1602, 526, 570, 510, 566, 502, 570,
  510, 1602, 526, 1610, 526, 1606, 534, 1602,
  534, 566, 502, 1610, 530, 1602, 534, 1602,
  526, 574, 506, 1000
};

//Set up array of codes
uint16_t *sources[3] = {powerOnOff, sourceCD, sourceCDR};//, sourceAUX};

//This causes some sort of horrible crash - maybe an overflow of the uint16 data type?
//#define RAW_DATA_LEN 68
//uint16_t sources[4][RAW_DATA_LEN] = {
//  {8550, 4306, 530, 1606, 530, 566, 502, 1610, //POWER ON/OFF
//  530, 566, 502, 574, 506, 1630, 506, 566,
//  506, 1630, 506, 566, 502, 1610, 530, 566,
//  502, 1634, 506, 1606, 530, 570, 498, 1634,
//  506, 570, 510, 562, 506, 566, 502, 1634,
//  506, 1606, 530, 1610, 530, 562, 538, 538,
//  530, 542, 538, 1598, 538, 1570, 558, 542,
//  538, 538, 530, 542, 538, 1598, 530, 1578,
//  558, 1578, 562, 1000},
//
//  {8546, 4310, 558, 1578, 562, 538, 498, 1638, //sourceCD
//  530, 542, 506, 570, 502, 1634, 502, 570,
//  498, 1638, 534, 538, 498, 1638, 530, 542,
//  506, 1606, 554, 1582, 558, 538, 510, 1602,
//  554, 546, 506, 566, 502, 570, 510, 1602,
//  554, 1582, 558, 538, 510, 566, 502, 1606,
//  554, 546, 502, 1610, 558, 1574, 554, 546,
//  502, 570, 510, 1602, 526, 1610, 526, 574,
//  506, 1602, 526, 1000},
//
//
//  {8550, 4306, 530, 1606, 534, 566, 502, 1606,  //sourceCDR
//  534, 566, 502, 570, 510, 1602, 526, 570,
//  510, 1602, 534, 566, 502, 1606, 534, 566,
//  506, 1602, 530, 1606, 534, 566, 502, 1610,
//  530, 570, 498, 574, 506, 566, 502, 570,
//  510, 1602, 526, 570, 510, 566, 502, 570,
//  510, 1602, 526, 1610, 526, 1606, 534, 1602,
//  534, 566, 502, 1610, 530, 1602, 534, 1602,
//  526, 574, 506, 1000},
//
//  {8550, 4310, 526, 1634, 506, 566, 502, 1634,  //sourceAUX
//  506, 566, 502, 574, 506, 1626, 510, 566,
//  506, 1630, 506, 566, 502, 1634, 506, 566,
//  502, 1634, 506, 1606, 530, 566, 506, 1630,
//  506, 566, 502, 1634, 506, 1630, 506, 1630,
//  510, 1602, 526, 570, 510, 566, 502, 1634,
//  502, 570, 502, 570, 510, 566, 502, 570,
//  510, 562, 506, 1630, 506, 1630, 510, 562,
//  506, 1630, 510, 1000}
//} ;

// ====PIN ASSIGNMENTS====
const int audioPin1 = A1;     //Channel 1
const int audioPin2 = A2;
const int debugPin = A3;     //when low, run in debug mode
const int statusLight = 10;   //active channel indicator light

//  ====CHANNEL MEASUREMENTS====
# define CHANNELS 3     //number of channels to sample from
int audioChannels[CHANNELS] = {audioPin1, audioPin1, audioPin2};      //element 0 will be ignored
int channelValues[CHANNELS] = {0, 0, 0};
const int SAMPLES = 300;
movingAvg audioAverages[CHANNELS] = {movingAvg(SAMPLES), movingAvg(SAMPLES), movingAvg(SAMPLES)};

//  ====CHANNEL VARIABLES====
int currentChannel = 0;     //channel that is currently active (0 is off)
int previousChannel = 0;    //channel that was active before change (0 is off)
const int audioThreshold = 15;      //minimum value for an "active" channel

//  ====TIMERS===
int counter = 0;
const int heartBeat = 500;
int channelReleaseTimeOut = 5000;      //time to wait before releasing an inactive timer
int powerTimeOut = 10000;       //time to wait before turnning off
int powerOnDelay = 7000;
elapsedMillis channelReleaseTimer = 0;
elapsedMillis powerTimer = 0;

// ====CONTROL VARIABLES====
bool debugMode = true;

void sendCode(int myChannel=0) {
//  debug("sending code", -1);
  for (int i=0; i < 20; i++) {
//  INCLUDING THE FOLLOWING LINE BREAKS THE DEBUG FUNCTION AND CAUSES OTHER STRANGE BEHAVIOR
//    mySender.send(sources[myChannel], RAW_DATA_LEN, 36);
    Serial.println("send code here");
    delay(2);
  }
} //END sendCode()

int findActiveChannel() {   //returns first active channel in the array or 0 if none are active
  int myChannel = 0;
  for (int i = 0; i < CHANNELS; i++) {
    if (channelValues[i] >= audioThreshold) {
      myChannel = i;
      break;
    }
  }
  return myChannel;
} //END findActiveChannel()

void debug(String message, int val) {

  if (debugMode) {
    Serial.print(message);
    Serial.println(val);
  }
} //END debug()

void setup() {
  delay(1000); //delay in case of runaway loop - allow programmer time to interrupt
  //  ====PIN SETUP====
  pinMode(statusLight, OUTPUT);
  pinMode(debugPin, INPUT);
  pinMode(audioPin1, INPUT);
  pinMode(audioPin2, INPUT);

  if (debugMode) {
    Serial.begin(9600);
    delay(2000);
    debug("starting up ", -1);
  }

  // ====INIT VARIABLES====
  for (int i = 0; i < CHANNELS; i++) { //init and reset the moving averages
    audioAverages[i].begin();
    audioAverages[i].reset();
  }
}

void loop() {
  int activeChannel = 0;
  for (int i=0; i < CHANNELS; i++) {      //sample channels
    int audioValue = 0;
    if (i > 0) {      //only sample channels > 0
      audioValue = analogRead(audioChannels[i]) - 512;      //voltage divider on amp circuit shifts all values +512 (2.5V)
      audioValue = abs(audioValue);     //abs() funciton is actually a macro; needs to be on own line
      channelValues[i] = audioAverages[i].reading(audioValue);    //update and store the moving average for each channel
    }

//    if (counter >= heartBeat) {
//      debug("channel: ", i);
//      debug("    audioValue: ", audioValue);
//      debug("           avg: ", channelValues[i]);
//    }
  }     //end sample channels

//  if (counter >= heartBeat) {
//    debug("======================", -1);
//  }

  if (channelValues[currentChannel] >= audioThreshold) {      //reset the channel release timer if the current channel is active
    channelReleaseTimer = 0;
    powerTimer = 0;
  } else {
    activeChannel = findActiveChannel();

    //DEBUGGING - show countdown to channel release
    if(channelReleaseTimer < channelReleaseTimeOut and counter >= 500) {
      debug("Channel became inactive: ", currentChannel);
      debug("     releasing in: ", channelReleaseTimeOut - channelReleaseTimer);
    }
    //END DEBUGGING

    if (activeChannel != currentChannel and channelReleaseTimer >=channelReleaseTimeOut) {      //change channel
      debug("Changing channel from: ", currentChannel);
      debug("Changing channel to: ", activeChannel);
      currentChannel = activeChannel;
      powerTimer = 0;
    }
  }
  //END else find active channel

  if (currentChannel > 0) {     //reset the power timeout if there is an active channel
    powerTimer = 0;
  }

  if (previousChannel != currentChannel) {      //check for a channel change and send appropriate codes
    if (previousChannel == 0) {     //state change from off to on
      digitalWrite(statusLight, true);
      debug("power state change -> ON ", -1);
      sendCode(0);
      debug("     delaying for reciver to power up: ", powerOnDelay);
      delay(powerOnDelay);
      previousChannel = currentChannel;
    }

    if (currentChannel < 1 and powerTimer >= powerTimeOut) {
      digitalWrite(statusLight, false);
      debug("power state change -> OFF ", -1);
      sendCode(0);
      previousChannel = currentChannel;
    }

    if (currentChannel > 0) {
      sendCode(currentChannel);
      previousChannel = currentChannel;
    }

  }

  if (counter >= heartBeat) {
    debug("\nheartBeat ", -1);
    counter = 0;
  }

  counter++;
  delay(2);

}
```

Including the line `mySender.send(sources[myChannel], RAW_DATA_LEN, 36);` in the `sendCode()` function causes the `debug()` function to behave erratically and the arduino to get stuck in a variety of states that require a hard reset, sometimes disconnecting the power.

This is the expected output from the serial console:
```
20:18:20.188 -> Channel became inactive: 2
20:18:20.188 ->      releasing in: 4666
20:18:20.188 ->
20:18:20.188 -> heartBeat -1
20:18:21.377 -> Channel became inactive: 2
20:18:21.377 ->      releasing in: 3492
20:18:21.377 ->
20:18:21.377 -> heartBeat -1
20:18:22.528 -> Channel became inactive: 2
20:18:22.528 ->      releasing in: 2317
20:18:22.528 ->
20:18:22.528 -> heartBeat -1
20:18:23.713 -> Channel became inactive: 2
20:18:23.713 ->      releasing in: 1144
20:18:23.713 ->
20:18:23.713 -> heartBeat -1
20:18:24.864 -> Changing channel from: 2
20:18:24.864 -> Changing channel to: 1
20:18:24.864 -> send code here
```

When including the mysender line indicated above, the serial output becomes as follows for a similar situation:
```
0:21:14.965 -> 1
20:21:14.965 -> 4984
20:21:14.965 -> -1
20:21:16.121 -> 1
20:21:16.121 -> 4986
20:21:16.121 -> -1
20:21:17.299 -> 1
20:21:17.299 -> 3814
20:21:17.299 -> -1
20:21:18.463 -> 1
20:21:18.463 -> 2640
20:21:18.463 -> -1
20:21:19.650 -> 1
20:21:19.650 -> 1468
20:21:19.650 -> -1
20:21:20.804 -> 1
20:21:20.804 -> 294
20:21:20.804 -> -1
20:21:21.116 -> 1
20:21:21.116 -> 0
20:21:21.998 -> -1
```

body:
I have no solution for you, but I would argue that your problem has
nothing to do the choice between an array of arrays and an array of
pointers. You will have to search somewhere else.

I tried a minimal test by removing everything that is not central to the
question. Assuming you are using [this library][irlib2], the prototype of
`IRsendRaw::send()` is

<!-- language-all: lang-c++ -->

    void IRsendRaw::send(uint16_t *buf, uint8_t len, uint8_t khz)

I thus wrote this dummy test class to replace the library:

    class IRsendRaw {
    public:
        void send(uint16_t *buf, uint8_t len, uint8_t khz) {
            Serial.print(F("Sending at "));
            Serial.print(khz);
            Serial.println(F(" kHz"));
            for (int i = 0; i < len; i++) {
                Serial.print(" ");
                Serial.print(buf[i]);
            }
            Serial.println();
        }
    };

and used it in the following test program:

    // Comment this line out to use an array of arrays instead:
    #define ARRAY_OF_POINTERS

    // ====REMOTE CODES====
    //define the IR Sender
    IRsendRaw mySender;

    #define RAW_DATA_LEN 68

    #ifdef ARRAY_OF_POINTERS

    uint16_t powerOnOff[RAW_DATA_LEN] = {
      // ...
    };

    // And so on sourceCD[], sourceCDR[]...

    //Set up array of codes
    uint16_t *sources[3] = {powerOnOff, sourceCD, sourceCDR};//, sourceAUX};

    #else

    //This causes some sort of horrible crash
    //- maybe an overflow of the uint16 data type?
    uint16_t sources[4][RAW_DATA_LEN] = {
      {8550, 4306, 530, 1606, 530, 566, 502, 1610, //POWER ON/OFF
      // ...
      506, 1630, 510, 1000}
    };

    #endif

    void setup()
    {
        Serial.begin(9600);
    #ifdef ARRAY_OF_POINTERS
        Serial.println(F("== Using an array of pointers =="));
    #else
        Serial.println(F("== Using an array of arrays =="));
    #endif
        for (int myChannel = 0; myChannel < 3; myChannel++) {
            Serial.print(F("\nChannel "));
            Serial.println(myChannel);
            mySender.send(sources[myChannel], RAW_DATA_LEN, 36);
        }
    }

    void loop(){}

The parts with ellipses (“...”) are just copied from your question. Now,
this test program works as expected, both in “array of pointers” and in
“array of arrays” mode.

It would then seem your problem comes from somewhere else. How full is
the memory of your Arduino? Quite often memory problems lead to strange
behaviors, where a crash can be triggered by a piece of code that is
perfectly legitimate and has nothing to do with the root cause of the
crash.

[irlib2]: https://github.com/cyborg5/IRLib2


message:
Trying to measure change in light levels over time

I have two LDR's attached to my Arduino Uno and an RGB LED as an output component. The two LDR's are at different offboard heights in order to see the change in light between them. I want to code on Arduino so that if the difference in light between the two LDR's does not change by a large amount over a 1 hour period (i.e stays similar), it will make the RGB  LED flash. I know that I have to use an if and else statement to do this, but does anyone know how I can code it so that I can achieve the above statement?

Thanks

body:
Break this into pieces. Solve the pieces one at a time.

Write code that reads the 2 photocells and calculates the difference between them. Log that difference to the console.

Then add a global variable to remember the old difference, and a max difference. Each time you take a new set of readings and calculate the difference, compare it to the old difference. If the new difference is greater than the old difference, update the max difference. Then update the "old difference" with the new reading.

Figure out how to use millis() to record a starting time, and monitor the reading difference until an hour has passed. If the reading difference is below your "large amount" threshold, start the light blinking.

Then you need to decide what to do about times greater than an hour. Do you track the max difference over the most recent 60 minutes and flash the light if it is below your threshold? Maybe save a difference reading every 5 minutes into a ring buffer with 12 entries (an hour's worth of entries) and keep checking the ring buffer for a difference value greater than your threshold? (You should be able to Google search "C ring buffer" for sample ring buffer code. It's actually quite simple to implement.

You might also want to calculate a moving average difference reading, and compare each reading to that. I recommend using an Exponential Moving Average (EMA).

I have code in my project that uses EMA to calculate a single brightness value rather than a difference, but the idea is the same. Here is an excerpt from my code:

Define a global:

    float   photocellAverage =      0;

    #define sampleCountToAverage 100  //The larger the number of samples, the more slowly the average will change with each new reading.

Then

    int photocellValue = analogRead(photocellPin);
    photocellAverage -= photocellAverage / sampleCountToAverage;
    photocellAverage += float(photocellValue)/sampleCountToAverage;

For you, you'd be calculating a difference reading and an EMA of that difference reading:

    float   photocellDifferenceAverage =      0;

    int photocell1Value = analogRead(photocell1Pin);
    int photocell2Value = analogRead(photocell2Pin);
    int photocellDifference = photocell1Value - photocell2Value;
    photocellDifferenceAverage -= photocellDifferenceAverage / sampleCountToAverage;
    photocellDifferenceAverage += float(photocellDifference)/sampleCountToAverage;


message:
Is it possible to send data from device (e.g. MPU6050) to Arduino through cut/hacked USB cable?

So I understand the USB cable consists of VCC, GND and Data+, Data-.

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

Is it possible to connect an MPU-6050 gyro to these 4 pins, especially data+/-, and still receive them normally through the SCL/SDA pins on the Arduino?

The goal is to make an input piece modular by having an USB out at it while having an USB in at the Arduino.

Here is a basic visualization:

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

  [1]: https://i.stack.imgur.com/2p274.jpg
  [2]: https://i.stack.imgur.com/PksvD.png

body:
Execellent non-Arduino question about I2C cable so the answer is also non-Arduino. I recommend the following Hackaday blog. https://hackaday.com/2017/02/08/taking-the-leap-off-board-an-introduction-to-i2c-over-long-wires/. You can find a more theoretical model in https://www.analog.com/media/en/technical-documentation/technical-articles/I2C-Cabling.pdf

Basically yes you can use cables. Different cables have different level of capacitance per meter. This will reduce the maximum frequency and may also require adjustment of the pull-up resistors.

Cheers!

BW: "nihil novi sub sole": This question has been asked before, https://forum.arduino.cc/index.php?topic=143337.0


message:
Reading Digital Pins and Outputing on entire Ports

I'm very new to coding so please don't grill me.

I'm working on a scientific project where I am using a NI-DAQ to digitally trigger mosfets to trigger 300us - 3ms pulses on two high powered LED arrays. My intention is to use the Arduino UNO to basically relay one digital output into many. It remains important to use the NI-DAQ as the pulses are dependent on video cues and other outputs, otherwise the pulses would be purely produced by the Arduino.

I have decided to the port Port reg output to accomplish this as it would appear to have the greatest temporal precision but I’m having a very difficult time getting a single pin to trigger a port. I would greatly appreciate some help.

My code currently looks as such:
```
int inpin = 2; //input specified as pin 2
int x = 0; // variable to store the read value

void setup() {
pinMode(inpin, INPUT); //sets digital pin 13 as input
DDRD=B11111111; //pin 8-13 is in output mode
DDRC=B11111111; //pin A0-5 designated output
}

void loop() {
x = digitalRead(inpin); //read the input pin
if (inpin = HIGH) PORTB=B11111111; // if digital input is high, all Bport high
if (inpin = HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
if (inpin != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
if (inpin != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low

}
```

At the moment it seems the board it reading the input but is not relaying the outputs correctly with the PORTB continuously off and PORTC continuously on. Any help would be great!

body:
You have some coding errors.  You likely meant to write something like:

    void loop() {
      x = digitalRead(inpin); //read the input pin
      if (x == HIGH) PORTB=B11111111; // if digital input is high, all Bport high
      if (x == HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
      if (x != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
      if (x != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low
    }

Which could be simplified to:

    void loop() {
    if (digitalRead(inpin) == HIGH)
    {
      PORTB=B11111111; // if digital input is high, all Bport high
      PORTC=B11111111; // if digital input is high, all Cport is high
    }
    else
    {
      PORTB=B00000000; // if digital input is low, all Bport is low
      PORTC=B00000000; // if digital input is low, all Cport is low
    }
    }


body:
If you are doing this sort of low-level port manipulation, I suggest you
ditch the Arduino core and go the avr-libc way:

<!-- language: lang-c -->

    #include <avr/io.h>

    int main(void)
    {
        DDRB = 0xff;  // all port B as output
        DDRC = 0xff;  // all port C as output
        DDRD = 0;     // all port D as input
        for (;;) {
            if (bit_is_set(PIND, PD2)) {  // if PD2 reads HIGH
                PORTB = 0xff;  // all port B goes HIGH
                PORTC = 0xff;  // same for port C
            } else {
                PORTB = 0;     // all port B gos LOW
                PORTC = 0;     // same for port C
            }
        }
    }

This compiles to very efficient code that takes at most 7 CPU
cycles per loop iteration. In contrast, a call to `digitalRead()` can
take hundreds of cycles, greatly increasing the program latency.

Obviously a buffer would still be way better in terms of latency, as
pointed out by ratchet freak in a comment.


message:
Serial.parseInt() takes longer time than desired

**My whole code for master. Please head to void read() where I've used parseInt()**

    #include <nRF24L01.h>
    #include <printf.h>
    #include <RF24.h>
    #include <RF24_config.h>
    #include <SPI.h>

    RF24 radio(7, 8); //Set up nRF24L01 on CE pin and CSN pin respectively

    const uint64_t pipe = 0x0ABCDEF; //Address for communication between master and slave
    uint16_t data[7];
    const uint16_t buffer_size = sizeof(data); //Size of the payload for the RF
    int i, flag;
    int tx_counter = 0;

    void read();
    void setup() {

      Serial.begin(115200);

      radio.begin();
      radio.setChannel(2);
      radio.setDataRate(RF24_1MBPS);
      radio.setPALevel(RF24_PA_MIN);
      //radio.powerUp();
      radio.openWritingPipe(pipe);
      //radio.setPayloadSize(7);
      radio.stopListening();

      //Default values range from 100 to 700
      for (i = 0; i < 7; i++) {
        data[i] = 100 + (100 * i);
      }
      flag = 0;
      Serial.println("Enter 7 values");
    }

    void loop() {

      read();

      if (flag) {
        bool tx_ok = radio.write(data, buffer_size);
        tx_counter++;
        Serial.print("Transmission count:\t");
        Serial.println(tx_counter);
        print();
        if (tx_ok) {
          Serial.println("Transmitted Successfully");
          Serial.println("\nEnter Next set of 7 numbers");
        }
        else Serial.println("Transmission failed");

      }
    }

    void print() {
      for (i = 0; i < 7; i++) {
        Serial.println(data[i]);
      }
      flag = 0;
    }

    void read() {
      while (Serial.available()) {
        for (i = 0; i < 7; i++) {
          data[i] = Serial.parseInt();
        }
        flag = 1;
      }
    }

My problem is that Serial.parseInt() takes some time. The code prints out the values to the serial monitor after sometime. I have timed it and it appears to be around 7 seconds. The arduino page on the function says default timeout is 1 sec. So I think 7 elements in the array takes 1 sec each. If I use `Serial.setTimeout(2000)`, the same thing takes 14 seconds.

This has got to have a simpler way. I want it to behave like when we use `Serial.read`. Please help me on this.

body:
this is what you want:

    void read() {
      for (i = 0; i < 7; i++) {
        while (!Serial.available()); // wait forever for some input
        data[i] = Serial.parseInt();
      }
      flag = 1;
    }


message:
Varible Ramp up speed for motors controlled by joytstick

I trying to create a piece of code which will ramp up the motors speed to a changing value controlled by a joystick. For example joystick requests 120 speed to motors so instead of going 0 to 120 it goes 0, 10, 20 …. 120. But the maximum value will constantly change between 0-130 so it needs to ramp up each time.
This is a snippet of my code to run the motors in the forwards direction.

    {
      motorControl = analogRead(joystick);
      motorControl = motorControl / 4;
      if(motorControl > 129)

    {

        digitalWrite(pwm2, 0);
        digitalWrite(pwm3, 0);
        speedI = (motorControl - 130);
        speedFadeI =
        Serial.println(speedFadeI-130);
        analogWrite(pwm1, (speedFadeI - 130));
        analogWrite(pwm4, (speedFadeI - 130));

thank you for anyone who has a idea

body:
I assume from the `0, 10, 20 …. 120` series, that you want to have a linear ramp to the desired speed. This can be done really easily, if your requirements are not to high.

First we define the interval, in which we want to update the speed, and a constant acceleration, that you can choose. The current speed will be saved in a global variable.

    #define INTERVAL        100
    #define ACCELERATION    51
    int current_speed = 0;

I chose an interval of 100ms and the acceleration value, so that it will ramp from 0 to 255 (full speed) in 5s (which results in 51 PWM values per second). Now, in the `void loop()` function, we use an if-statement with the `millis()` function to trigger an speed update at the regular interval. For this to work, we need a (here global) variable, that holds a timestamp. (If you don't know this technique, you can see it in the `BlinkWithoutDelay` example, that comes with the Arduino IDE, and there are many tutorials about this on the web)

Inside the if-statement, we write a second if-statement. It checks, if the current speed is above or below the set point, that comes from the joystick. If it's above, we will substract one speed step (calculated by acceration and interval and divided by 1000, because we used milliseconds and not seconds for the interval), if it's below we will add one speed step.

    unsigned long timestamp = 0;

    void loop(){
        int setpoint = analogRead(joystick)/4;
        if(millis() - timestamp > INTERVAL){
            if(current_speed > setpoint){
                current_speed -= ACCELERATION*INTERVAL/1000;
            } else {
                current_speed += ACCELERATION*INTERVAL/1000;
            }
            if(current_speed > 255) current_speed = 255;
            else if(current_speed < 0) current_speed = 0;
            analogWrite(pwm1, current_speed);
            timestamp += INTERVAL;
        }

I also added if-statements to cap the current speed between 0 and 255. Otherwise the value would overflow, when written to the corresponding 8-bit timer register by the `analogWrite()` function.

Of course, this method also has drawbacks. You will have to find a good value combination of `ACCELERATION` and `INTERVAL`, because when the current speed reaches the setpoint, it will oscillate around this value. The best way is to set the `ACCELERATION`, that you need, and choose a good interval based on that.

There are other ways to program this, but I like this way for being really simple.


message:
Serial communication stops when powered with batteries?

Circuit explanation-

1. Arduino Uno connected to multiple sensors and to 16 x 2 LCD.
2. Uno's TX pin to ESP-01 RX pin.
3. Uno has been programmed to read values from sensors and display them on LCD along with printing them on Serial Monitor.
4. ESP-01 has been programmed to receive values from Serial Monitor and transmit it to ADAFRUIT MQTT server.

Problem -
However when i am using USB to power the Uno it is successfully displaying data on LCD as well as to Serial Monitor and values are succesfully being send on the MQTT server after being read from Uno's serial.
**But when Uno is battery powered, serial communication stops.**

I have tried adding 2 decoupling capacitors of 100uF to 12V battery supply. Battery are rechargeable cells.

What could be the issue?

body:
I will put the solution from the comments into an answer.

All devices, that should interact through electrical wires with each other, must have a common ground. Ground is the point, from which the voltage is measured, and the devices need a reference, that is not only valid for themselves, but also valid for the communication partner.

You can think of the following analogy: Image that you and a friend have each one ball, that you are throwing into the sky (a positive height/voltage) and catching it again (zero height/voltage --> ground). While you stand on the parking lot, your friend is standing on a high building. As long as you both only play this with yourself, it is easy for you to throw and catch the ball, because you can easily measure the height of the ball and it will always behave the same. But know imagine, that you want to play together. The height/voltage, that your ball reaches is still positive for you. But from the perspective of your friend it will look, like a large negative height/voltage. How should your friend interpet that and how should he now play with you?

---

In some electrical circumstances you don't want to connect the grounds of two devices together (maybe because of noise on the ground line). Then you have to achieve galvanic isolation, so no electrical connection between those two. An optocoupler is a device, that can achieve this. Basically it's just an LED and a phototransistor in one casing. From one device you power the LED. Due to the LEDs light, the phototransistor (which is connected to the other device) will become conductive. In combination with a pullup/pulldown resistor on the phototransistor you can have communication without common grounds.


message:
Unable to store data in variable from Serial.read()

I have a relay and bluetooth module connected to Arduino Uno. I send data such as digit 1 to the bluetooth module and I view it in the Serial Monitor. If I send 1 from serial monitor I get 4910 printed.

I would like to turn on the relay and have it stay on until I send a different digit. However, in my code below it doesnt work, the relay doesnt stay on.

Only, if I put the digital.write under **while(Serial.available())** it works.

    const int ledPin =  11;
    int relayOn;

    void setup() {

      //initialize serial port for logs
      Serial.begin(9600);

      pinMode(ledPin, OUTPUT);

    }

    void loop() {

      while (Serial.available()) {

          Serial.println("Data: ");

          Serial.println(Serial.read());

          if(Serial.read())
          {
            relayOn = Serial.parseInt();
          }

          while (relayOn > 1)
          {
            digitalWrite(ledPin, HIGH);

          }

        }

    }

body:
Your input is "5\n" with '\n' as line ending setting in Serial Monitor.

In the code you have first `Serial.println(Serial.read());`. It will read and print the '5'. Then you have `if(Serial.read())`. It will read the '\n'. It is not 0 so the next line is `relayOn = Serial.parseInt()`. It will find no input and times out returning 0.

if you want to use parseInt():

    void loop() {
      if (Serial.available()) {
        Serial.print("Data: ");
        relayOn = Serial.parseInt();
        Serial.println(relayOn);
        if (relayOn > 1) {
          digitalWrite(ledPin, HIGH);
        }
      }
    }


body:
Try using serial interrupt in arduino

    void loop() {
    }

    void serialEvent()
    {
      while (Serial.available())
        {
           char inChar = (char)Serial.read();
          Serial.print("Data: ");
          Serial.println(inChar);
           if (inChar == '1')
            {
                  digitalWrite(ledPin,HIGH);
                  break;
            }
           else
            {
                  digitalWrite(ledPin,LOW);
                  break;
            }
         }
    }


body:
You could try something like (not tested):

    void loop() {
     if(Serial.available()){
       input = Serial.parseInt();
       Serial.print("Data: ");
       Serial.println(input);
       if(input == 1){
          digitalWrite(RELAY, HIGH);
          digitalWrite(LED, HIGH);
       }
       else if(input == 2{
          digitalWrite(RELAY, LOW);
          digitalWrite(LED, LOW);
       }
     }
    }

don't forget to declare input variable, use 1 to turn on, 2 off :)


message:
Enable and disable individual interrupts

I am working on timer interrupts and external interrupts.
for external interrupts I understood the functions like attachInterrupt. detachinterrupt for individual interrupts ,noInterrupts() and  interrupts() can be used to enable and disable all interrupts at a time.

But How to enable and disable timer interrupts??

I am writing a code for alarm clock and snooze button. So what I want is
1) whenever alarm time is equal to watch time, start a timer for 5 minutes and a buzzer buzzes.
2) whenever I press the snooze button,  another timer starts and after 30 seconds a buzzer beeps. again I press snooze and again the timer starts and after 30 seconds buzzer beeps.
3) But after 5 minutes of the first timer, both timer interrupts gets disabled as now I dont want any buzzer.

I know how to initialize the timer in setup function, and I am getting the buzzes every 30 seconds. I also know that interrupts will come according to the timer value and I need to call the function after a fix number of counts or 30 seconds or 5 minutes.

But I dont know how to disable and enable timer interrupts wherever I want in code.

body:
* Step 1: Read the datasheet for the chip.
* Step 2: Find the registers that control the timers and their interrupts.
* Step 3: Set or clear the relevant bits in those registers.

For example, the [ATMega328P](http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf) has the `TIMSK1` register for Timer 1, which has three bits related to interrupts:

> * **Bit 2 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable**
>
> When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1
output compare B match interrupt is enabled. The corresponding interrupt vector (see Section 11. “Interrupts” on page 49) is
executed when the OCF1B flag, located in TIFR1, is set.
>
> * **Bit 1 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable**
>
> When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1
output compare A match interrupt is enabled. The corresponding interrupt vector (see Section 11. “Interrupts” on page 49) is
executed when the OCF1A flag, located in TIFR1, is set.
>
> * **Bit 0 – TOIE1: Timer/Counter1, Overflow Interrupt Enable**
>
> When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1
overflow interrupt is enabled. The corresponding interrupt vector (see Section 11. “Interrupts” on page 49) is executed when
the TOV1 flag, located in TIFR1, is set.

So to turn off the Compare B Match interrupt you can use:

    TIMSK1 &= ~(1 << 2);

And to turn it on again:

    TIMSK1 |= (1 << 2);

Both Timer 0 and Timer2 have a `TIMSKx` register which works in the same way.


message:
need to get values from a function with structure pointer argument and print on serial terminal

I am developing a code in which I need to print value of structure pointer on serial terminal.
Below is my code snippet:

    typedef struct
    {
      uint8_t AB;     ///< Address byte (Start byte)
      uint8_t CB;     ///< Command (index) "ASCII-byte"
      uint8_t SI;     ///< Action (sub index) "ASCII-byte"
      uint8_t PH_1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
      uint8_t PH_2;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
      uint8_t PL_1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
      uint8_t PL_2;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
      uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
      uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
    } rs485_message_t;

    int proto485ComposeMsg(rs485_message_t* msg, uint8_t address, uint8_t command, uint8_t action, uint16_t value){
      msg->AB = address;
      msg->CB = command;
      msg->SI = action;
      msg->PH_1 = (int)((value & 0xF000) >> 12) ;
      msg->PH_2 = (int)((value & 0x0F00) >> 8);
      msg->PL_1 = (int)((value & 0x00F0) >> 4) ;
      msg->PL_2 = (int)(value & 0x000F);
      int checksumRaw = (msg->CB) + (msg->SI) + (msg->PH_1) + (msg->PH_2) + (msg->PL_1) + (msg->PL_2);
      setCheckSum(msg);
    }

    uint8_t proto485Write(uint8_t address, uint8_t command, uint8_t action, uint16_t value)
    {
      int i = 0;
      int stringOne[9] = {int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00)}; ;
      rs485_message_t rs485Msg;
      proto485ComposeMsg(&rs485Msg, address, command, action, value); // value is passed in "raw" format
      Serial.write(rs485Msg);       // getting error on this line
    }

Please help... Thank you

body:
You can't just print a structure. After all, how is the program supposed to know how it is supposed to be displayed?

Do you want just the raw data, or do you want it formatted in a human readable form?

For just the raw data you need to cast the pointer to a type that can be printed as an array. For example:

    Serial.write((uint8_t *)&rs485Msg, sizeof(struct rs485_message_t));

To print it in a human readable form you will need to take each value that you want to see and print it separately with any data manipulation that you may want.  For example:

    Serial.print("Checksum 0: ");
    Serial.println(rs485Msg.CS0, HEX);

Another thing you can do is to change your structure into a class and inherit the `Printable` class.  You can then implement the `size_t printTo(Print &p);` member function which sends the data to the `p` object for printing in the format you want.  Then you can just print it directly as you are trying to do in your code.


message:
Program to run two motors with Motor driver

I'm trying to make a program that would run two motors clockwise and then anticlockwise. But my program is causing my motors to only run clockwise everytime . It doesn't run anticlockwise at all. Can anyone help me find the bug?

Main code:

    void loop()
    {
      // turn on motor A
      digitalWrite(In1, HIGH);
      digitalWrite(In2, LOW);
      // set speed to 150 out 255
      analogWrite(EnA, 150);
      // turn on motor B
      digitalWrite(In3, HIGH);
      digitalWrite(In4, LOW);
      // set speed to 150 out 255
      analogWrite(EnB, 150);
      delay(2000);
       digitalWrite(In1, LOW);
      digitalWrite(In2, HIGH);
       digitalWrite(In3,LOW);
      digitalWrite(In4, HIGH);
      // now turn off motors
      digitalWrite(In1, LOW);
      digitalWrite(In2, LOW);
      digitalWrite(In3, LOW);
      digitalWrite(In4, LOW);
      delay(2000);
    }

body:
check this one

    void loop()
    {
      // turn on motor A
      digitalWrite(In1, HIGH);
      digitalWrite(In2, LOW);
      // set speed to 150 out 255
      analogWrite(EnA, 150);
      // turn on motor B
      digitalWrite(In3, HIGH);
      digitalWrite(In4, LOW);
      // set speed to 150 out 255
      analogWrite(EnB, 150);
      delay(2000);
       digitalWrite(In1, LOW);
      digitalWrite(In2, HIGH);
       digitalWrite(In3,LOW);
      digitalWrite(In4, HIGH);
      // now turn off motors
      delay(5000);
      digitalWrite(In1, LOW);
      digitalWrite(In2, LOW);
      digitalWrite(In3, LOW);
      digitalWrite(In4, LOW);
      delay(2000);
    }


message:
Can I power an NodeMCU trough VIN providing 5v

I have a spb 8266 board, an ESP-12E NodeMCU.
I broke my micro USB.

There's [this][1] piece of information but my case is unclear:

Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

(The board only has 3.3V and **no** 5V)

  [1]: http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/

body:
> Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

Yes. That is the pin's purpose.  You can use any voltage from about 4.5V up to 20V, although higher voltages will cause more heat from the on-board 3.3V regulator.

VIN just connects to the 5V of the USB.


body: If you are working with the "v3" (Lolin) pcb, USB v5 pin is not directly connected to Vin, but to VU. Vin has a S4 SMD diode (aka Schottky 40V1A 1N5819) between it and the USB v5 pin.


message:
Pass structure pointer as an argument to a function in c

I am developing a code in which I need to pass a structure pointer value to a function as a parameter. I am calling function "proto485Compare()" in "RS485TaskSlave()". "rs485Msg" contains my data for which I need to verify for checksum, I am checking it in "RS485TaskSlave()" using "if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message)))" but it is showing error on this line.

Please help me to get the values of "rs485Msg" & check for checksum on this line

Below is my code snippet:

     typedef struct
        {
          uint8_t AB;     ///< Address byte (Start byte)
          uint8_t CB;     ///< Command (index) "ASCII-byte"
          uint8_t SI;     ///< Action (sub index) "ASCII-byte"
          uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
          uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
          uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
          uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
          uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
          uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
        } rs485_message_t;

        uint8_t proto485ValidCheckSum(rs485_message_t message)
        {
          uint8_t rawChecksum = (message.CB - OFFSET_ASCII) + (message.SI - OFFSET_ASCII) +
            (message.PH1 - OFFSET_ASCII) + (message.PH0 - OFFSET_ASCII) +
              (message.PL1 - OFFSET_ASCII) + (message.PL0 - OFFSET_ASCII);

          uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message.CS1 &&
            ((rawChecksum & 0x0F) + OFFSET_ASCII) == message.CS0;

          return res;
        }

        void RS485TaskSlave(void *p_arg) //b - RS485 communication Task
        {
            uint8_t res;
            rs485_message_t rs485Msg;
            uint8_t command, action, value;

            (void)p_arg;
            while(1)
            {
              res = driver485Read((uint8_t *)&rs485Msg, RS485_MSG_LENGTH);
              if(RS485_MSG_LENGTH == 9)
             {
                res =  proto485Compare((uint8_t *)&rs485Msg, command, action, value);
             }
            }
        }

        int16_t proto485Compare(uint8_t* message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev)
        { int j = 0;
          rs485_message_t rs485Msg;
          char res;
          uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
          uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

         if(proto485ValidCheckSum(rs485_message_t ((uint8_t*)message))) //
    /*GETTING ERRORVON THIS LINE please help how to pass message value to verify checksum at this line*/
          {
          printf("compare command..........");

            for (j=0; j<9; j++)
            {
              arduinodata[j] = message[j];
              printf("%d ",arduinodata[j]);
            }
            printf("\n");

            if(compareArray(FWmsg,arduinodata,7)==0)
            {
              uint8_t add, fwc, fwa;
              uint16_t fwv;
              res = GetABFWversion(&add, &fwc, &fwa, &fwv);
              res = proto485OnlyWrite(add,fwc, fwa, fwv);
            }
          }
          else
          {
            printf("Arrays have different elements.\n");
          }
          return res;
        }

body:
Remove your casting, and change your `message` parameter to be `rs485_message_t *`:

    int16_t proto485Compare(rs485_message_t * message, uint8_t* comparec, uint8_t* comparea, uint8_t* comaprev) {
        int j = 0;
        rs485_message_t rs485Msg;
        char res;
        uint8_t FWmsg[9] = {0x09,0x31,0x30,0x30,0x30,0x30,0x33,0x30,0x34};
        uint8_t arduinodata[9] = {0x09,0x30,0x30,0x30,0x30,0x30,0x30,0x30,0x30};

        if(proto485ValidCheckSum(message))) { ...

And when you call it, simply:

    res =  proto485Compare(&rs485Msg, command, action, value);

To get at the individual bytes you can then cast a new variable:

    uint8_t *messageAsBytes = (uint8_t *)message;

Then you can use:

    messageAsBytes[i]

etc.

However another cleaner way is to create a `union` in your structure:

    struct rs485_message_t {
        union {
            uint8_t bytes[9];
            struct {
                uint8_t AB;     ///< Address byte (Start byte)
                uint8_t CB;     ///< Command (index) "ASCII-byte"
                uint8_t SI;     ///< Action (sub index) "ASCII-byte"
                uint8_t PH1;    ///< Payload "ASCII-byte" of the high nibble of the high byte of the raw payload
                uint8_t PH0;    ///< Payload "ASCII-byte" of the low nibble of the high byte of the raw payload
                uint8_t PL1;    ///< Payload "ASCII-byte" of the high nibble of the low byte of the raw payload
                uint8_t PL0;    ///< Payload "ASCII-byte" of the low nibble of the low byte of the raw payload
                uint8_t CS1;    ///< Checksum "ASCII-byte" of the high nibble of the raw checksum
                uint8_t CS0;    ///< Checksum "ASCII-byte" of the low nibble of the raw checksum
            };
        };
    };

So you can now access `message->CS0`, etc, as well as `message->bytes[3]`.

You should also pass a pointer when you call `proto485ValidCheckSum` - purely to save memory.

    uint8_t proto485ValidCheckSum(rs485_message_t *message)
    {
      uint8_t rawChecksum = (message->CB - OFFSET_ASCII) + (message->SI - OFFSET_ASCII) +
        (message->PH1 - OFFSET_ASCII) + (message->PH0 - OFFSET_ASCII) +
          (message->PL1 - OFFSET_ASCII) + (message->PL0 - OFFSET_ASCII);

      uint8_t res = (((rawChecksum & 0xF0) >> 4) + OFFSET_ASCII) == message->CS1 &&
        ((rawChecksum & 0x0F) + OFFSET_ASCII) == message->CS0;

      return res;
    }

And again call it with a pointer, which the first block of code does anyway.

In general, it's better to pass a single pointer to a struct around from function to function instead of cloning it each time.

You can also use "pass by reference" if you like, but I find it's better to stick to pointers when passing something around alot like this.


message:
Powering arduino with battery

I haven't tried so don't know if it works or not. So I got a 6v battery AA, is it possible to run my arduino uno which already got a code in it if I plug + pin to vin and - to GND? Without its USB?

body:
The UNO recommends at least 7 Volts on the Vin. 6 Volt is the absolute minimum. As the AA batteries drain, the voltage will be below this 6 Volts very quickly.

I tend to use a 3xAA battery holder, giving around 4.5Volt, and connect that straight to the Vcc pin (bypassing the voltage regulator). This works just fine in most cases.


body:
Get a 5 battery holder and put 5 alkaline batteries into it. (5 battery holders are sometimes used to provide 6 volts from ni-cat or NiMh batteries, which provide ≈1.2V.

5 alkaline AA batteries would give you ≈7.5V, which gives you more "wiggle room" for the voltage regulator.

## EDIT:

As Gerben pointed out in their comment, 5 AA batteries will drop below the minium voltage input to the Arduino's voltage regulator well before they are depleted. A 6 battery holder would let you use more of the total battery capacity. (At the cost of wasting the excess voltage as heat.)


body:
Go and buy some 9v Duracell battery and use it . Put the plus in Vin and the negative in gnd  .
Also i noticed that you are a newbie to arduino  so  be aware.
5v pin in arduino it's an output voltage.
3.3 v also output voltage.
Vin is the vcc is An electronics designation that refers to voltage from a power supply connected to the "collector" terminal of a bipolar transistor. In an NPN bipolar (BJT) transistor, it would be +Vcc, while in a PNP transistor, it would be -Vcc.
Gnd mean ground .
Read this please.
https://www.pcmag.com/encyclopedia/term/53705/vcc


message:
Data Logging without Interfacing SD Card module

I want to log data to a text document without connecting the SD card module. I don't want to print the data on Serial Monitor I want to store it in a file. Is it possible? Can someone help me with it?
I am using a Arduino Nano on a Windows 10 system, and I want to know if there is an Arduino library to write logs to a file.

body:
The simplest answer is to install a program that handles serial connection and can write everything into a logfile. On Linux, CuteCom is a program like that. On Windows, putty can handle serial (as well as SSH and telnet), and has logging.

The more advanced soulution is to write a program (or a simple script) that can do that. You could make it to do some other stuff as well (like configuring the Arduino side), and you can run it in the background without user interaction.


message:
How to control DC motor speed with L298N and Node MCU?

I want to control an RC car with a joystick in mobile. Currently, I can only make the motor move forward and backward but not able to control the speed. Node mcu is used as a processor to receive the message.

Here is the code below:-
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #include <PubNub.h>
    #define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
    #include <L298N.h>

    const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
    const char *pass =  "786110786";

    const char * pubkey = "";
    const char * subkey = "";

    const char * subchannel = "base";

    #define ENB D6
    #define IN1 D3
    #define IN2 D4

    L298N motorL(ENB, IN1, IN2);

    #define ENA D5
    #define IN3 D1
    #define IN4 D7

    L298N motorR(ENA, IN3, IN4);

    void setup() {
        /* For debugging, set to speed of your choice */
        Serial.begin(115200);

           Serial.println("Connecting to ");
           Serial.println(ssid);

           WiFi.begin(ssid, pass);
           while (WiFi.status() != WL_CONNECTED)
              {
                delay(500);
                Serial.print(".");
              }
          Serial.println("");
          Serial.println("WiFi connected");

        /* Start the Pubnub library by giving it a publish and subscribe
           keys */
        PubNub.begin(pubkey, subkey);

    }

    void loop() {

      int tim = millis();

        PubSubClient *sclient = PubNub.subscribe(subchannel);
        if (!sclient) return; // error
        String msg;
        SubscribeCracker ritz(sclient);
        if (!ritz.finished()) {
            ritz.get(msg);
            if (msg.length() > 0) {
                Serial.print("Received: "); Serial.println(msg);

                String X = getStringPartByNr(msg, ':', 0);
                String Y = getStringPartByNr(msg, ':', 1);

                X.remove(0,1);

                int Xcord = X.toInt();
                int Ycord = Y.toInt();

                Serial.print("X: "); Serial.println(Xcord);
                Serial.print("Y: "); Serial.println(Ycord);

                int angle;
                int throttle = (Xcord + Ycord)/2;

                if ((Xcord > 100) && (Ycord > 100)) {
                  angle = round(atan2(Ycord-100,Xcord-100)*(180/3.14));
                  motorR.forward();
                  motorL.forward();
                  motorR.setSpeed(abs(int(throttle*sin(angle))));
                  motorL.setSpeed(throttle);
                  Serial.print("R speed: "); Serial.println(abs(int(throttle*sin(angle))));
                  Serial.print("L speed: "); Serial.println(throttle);
                  //motorR.forward();
                  //motorL.forward();
                }
                else if ((Xcord < 100) && (Ycord > 100)) {
                  angle = 180 - round(atan2(Ycord-100,100-Xcord)*(180/3.14));

                  motorR.setSpeed(throttle);
                  motorL.setSpeed(abs(int(throttle*sin(angle))));
                  Serial.print("R speed: "); Serial.println(throttle);
                  Serial.print("L speed: "); Serial.println(abs(int(throttle*sin(angle))));
                  motorR.forward();
                  motorL.forward();
                }
                else if ((Xcord < 100) && (Ycord < 100)) {
                  angle = 180 + round(atan2(100-Ycord,100-Xcord)*(180/3.14));

                  motorR.setSpeed(200-throttle);
                  motorL.setSpeed(abs(int((200-throttle)*sin(angle)*(-1))));
                  Serial.print("R speed: "); Serial.println(200-throttle);
                  Serial.print("L speed: "); Serial.println(abs(int((200-throttle)*sin(angle)*(-1))));
                  motorR.backward();
                  motorL.backward();
                }
                else if ((Xcord > 100) && (Ycord < 100)) {
                  angle = 270 + round(atan2(Xcord-100,100-Ycord)*(180/3.14));
                  motorR.setSpeed(abs(int((200-throttle)*sin(angle)*(-1))));
                  motorL.setSpeed(200-throttle);
                  Serial.print("R speed: "); Serial.println(abs(int((200-throttle)*sin(angle)*(-1))));
                  Serial.print("L speed: "); Serial.println(200-throttle);
                  motorR.backward();
                  motorL.backward();
                }

                Serial.print("Angle: "); Serial.println(angle);
                //Serial.print("time: "); Serial.println(tim);

            }
        }

        sclient->stop();

    }

    String getStringPartByNr(String data, char separator, int index)
    {
        // splitting a string and return the part nr index
        // split by separator

        int stringData = 0;        //variable to count data part nr
        String dataPart = "";      //variable to hole the return text

        for(int i = 0; i<data.length()-1; i++) {    //Walk through the text one letter at a time

          if(data[i]==separator) {
            //Count the number of times separator character appears in the text
            stringData++;

          }else if(stringData==index) {
            //get the text when separator is the rignt one
            dataPart.concat(data[i]);

          }else if(stringData>index) {
            //return text and stop if the next separator appears - to save CPU-time
            return dataPart;
            break;

          }

        }
        //return text if this is the last part
        return dataPart;
    }

Port Reading:-
[![enter image description here][1]][1]

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

What can the problem be?

body:
That's  because the l298n library are used for the arduino or other microcontroller that have hardware PWM in their systems. The library using hardware pwm by generating pulses and make variations of the cyclic rapport aka "alpha" .
Esp8266 have no pwm in their systems
So try to use software pwm library for the esp8266

> this is the link. https://www.arduinolibraries.info/libraries/soft-pwm

Also don't include that library and try to make it work using easy lines of codes.


message:
Arduino help adding a second mpu 6050 sensor my working code

Background information: I currently have this arduino code that uses one mpu 6050 sensor to get angles in the x, y, and z directions and then display them to the user nicely. Code can be found here [basic MPU 6050 code][1]

The problem: **I would like to add a second mpu 6050** to my project and average the values from the two mpu 6050s.

I know how to physically wire the second sensor into the project but don't know how to do the coding side of things. The code I have is below. Any help is greatly appreciated. This is a very fun tool.

    #include<Wire.h>
    const int MPU_addr=0x68;
    int16_t axis_X,axis_Y,axis_Z;
    int minVal=265;
    int maxVal=402;
    double x;
    double y;
    double z;

    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);
      Wire.write(0);
      Wire.endTransmission(true);
      Serial.begin(9600);
    }
    void loop(){
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);
      axis_X=Wire.read()<<8|Wire.read();
      axis_Y=Wire.read()<<8|Wire.read();
      axis_Z=Wire.read()<<8|Wire.read();
        int xAng = map(axis_X,minVal,maxVal,-90,90);
        int yAng = map(axis_Y,minVal,maxVal,-90,90);
        int zAng = map(axis_Z,minVal,maxVal,-90,90);
           x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
           y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
           z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);
         Serial.print("Angle of inclination in X axis = ");
         Serial.print(x);
         Serial.println((char)176);
         Serial.print("Angle of inclination in Y axis= ");
         Serial.print(y);
         Serial.println((char)176);
         Serial.print("Angle of inclination in Z axis= ");
         Serial.print(z);
         Serial.println((char)176);
         Serial.println("-------------------------------------------");
         delay(1000);
    }

  [1]: http://myecworks.blogspot.com/2016/09/measuring-inclination-angle.html

body:
Ok first did YOU wiring theme correctly? Because the mpu use i2c BUS .
Second this code from gitlab it may help you .
https://gitlab.com/shuvashish/batikkrom.com/blob/master/MuttipleMPU/MuttipleMPU.ino
Check it . And use it


message:
Distance Sensor. Calculating running median and Average

I'm trying to smooth out values for my IR distance sensor through running median filtering and a running average. I've tried to do the averaging, but my values don't seem correct and I am confused about how I would do the median filtering. I am also using timer interrupts and I don't want to use libraries when calculating the average and median. I've attached the code where I attempted to calculate the average.

    int analogpin=5;
    int sum=0;
    int index=0;
    int averead=0;
    const int numreadings=9;
    int i;
    int timer1_counter;
    int adc_val;
    int int_flag;
    int int_array[9];
    float V;

    void setup() {

    int_flag=0;

    Serial.begin(9600);
    pinMode(analogpin,OUTPUT);
    for(i=0; i<=8; i++){
      int_array[i]=0;
    }

    noInterrupts();           //

      TCCR1A = 0;
      TCCR1B = 0;

    timer1_counter = 59286;

      TCNT1 = timer1_counter;
      TCCR1B |= (1 << CS12);
      TIMSK1 |= (1 << TOIE1);
      interrupts();
    }

    ISR(TIMER1_OVF_vect)
    {
      TCNT1 = timer1_counter;
      int_flag=1;
        }

    void loop() {

      if (int_flag==1){
        adc_val=analogRead(A2);
        V=5.0*adc_val/1023.0;
        analogWrite(analogpin,adc_val/4);
        }
        sum=sum-int_array[i];
        int_array[i]=analogRead(A2);
        sum=sum+int_array[i];
        index=index++;
        if(i==9){
          i=0;
        }
        averead=sum/numreadings;
        Serial.print("\n"); Serial.print("Average Filter Reading: ");
    Serial.println(averead);
        delay(1);
        }

body:
`analogRead()` returns an integer and therefore your calculation `V=adc_val*(5.0/1023.0)` will be casted as int as well. I suggest changing it to `V=5.0*adc_val/1023.0`.

In general a running mean can be calculated like this:

    #define buffer_size 9
    #define analog_pin 5

    int ring_buffer[buffer_size];
    uint8_t index=0;
    float running_mean() {
      ring_buffer[index]=analogRead(analog_pin);
      float mean=0;
      for (uint8_t i=0;i<buffer_size;i++) {
        mean+=ring_buffer[i];
      }
      if (++index>=buffer_size) index=0;
      return mean/buffer_size;
    }

You should flush the buffer during initialization, otherwise you don't get proper readings before the 9th iteration.


body:
Here is a simple alternative suggestion: Assuming you already know the average distance _d_ and a new reading _v_ comes in. The difference _v-d_ can be used to update the average. But since you want you want to smooth this out over several readings, you only update _d_ by a fraction of the difference: _d += 0.8*(v-d)_. The factor controls the smoothing.

To get this started, you estimate that the first value you read is the average. This does not require an array to keep past readings around.


body:
There are two main problems with your program. The first is noted in
Gerben's comment: you (attempt to) increment `index` (with a bad
syntax), while you should be incrementing `i` instead. The second
problem is these lines:

<!-- language-all: lang-c++ -->

    for (i = 0; i <= 8; i++) {
        int_array[i] = 0;
    }

Fix the `index` vs. `i` confusion, remove the lines above, and your
program should work.

**Explanation**: The first point should be obvious, I hope. I am
discussing here the second issue. At the end of the loop above, the
index `i` has the value 9. Later, in `loop()`, and assuming you fixed
the first issue, the program does

    i++;
    if (i == 9) {
        i = 0;
    }

and `i` has the value 10. From there `i` will continue incrementing, and
you are always writing outside of the array.

The root of the problem is that you used the same variable `i` for two
different purposes. There are several solutions to this:

* use different variable names for different purposes
* use local variables whenever applicable (here: in `setup()`)
* be defensive in your tests: instead of `if (i == 9)` write
 `if (i >= 9)`, but note that this alleviates but does not completely
 solve the problem
* remove the initialization of the array altogether.

I suggest removing the initialization because the array is a global
variable and, per the C++ standard, if not explicitly initialized it is
implicitly initialized to zero, so your initialization is redundant.


message:
Maintaining time in Arduino

I am working on development of alarm clock using Arduino.

No doubt RTC will be the best but it increases the Price of the project. Also I opened a digital clock (which I purchased online) and I see that there is only one IC (obviously it is covered with something black wax). But there was that one patch only.
So it seems it used only a controller or RTC. But with only RTC its not possible to control LCD. So it must be only a microcontroller

Now I have three options for maintaining time

1. I use RTC like DS3231
2. I use millis() function
3. I use timer and timer interrupts of micro controller for free running timer.

Can I get accurate time using micro controller.

body:
I see from eBay that you can get the DS1307 for around 10 cents. Is that really too much to pay? You also need a crystal and a backup battery (eg. CR2032). Without a battery the device cannot possibly remember the time if it is powered off.

If your device is battery powered then you could conceivably just use millis(), however you would need to have a way of setting the time. The resonator used on a Uno is not as accurate as a crystal, however that might be good enough depending on your project.

If you are trying to save money I wouldn't use a Uno or Micro, but the bare chip, with a few extra components (eg. decoupling capacitors, a couple of resistors, and a crystal).