text:
Getting stable measurements with the BNO055 IMU
I bought the BNO055 "smart" IMU from Adafruit, thinking it would be a simple way to get orientation data for a small mobile robot project, but I've found the thing to be very difficult to use and nearly worthless.
It's advertised as being able to auto-calibrate, and although it does attempt to do this, I've found that the calibration doesn't hold. It continuously re-calibrates itself, and either gets stuck in an error state or find a successful calibration...but then loses it after a few seconds.
Is there anything I can do to improve its stability? Does it need to be mounted inside a special grounded housing? Is there a special incantation I should utter before powering it on?
I'm reading it from an Arduino Uno via I2C, and though the wiring and programming is relatively simple, getting it calibrated and staying calibrated I've found to be nearly impossible.
Even after the "system" flag says its fully calibrated, and I have the IMU just sitting on a table, not moving, after a minute, it loses its "system" calibration. The accelerometer, gryoscope, and magnetometer usually remain calibrated, but how can I trust them if the on-board fusion algorithm is reporting it's not ready?
If the BNO055 is a lost cause, is there anything better? I've tried several MPU-**** chips from InvenSense, but they're even worse.

did you follow the calibration procedure?

Try a permanent calibration. From the Adafruit forums:

You'd basically need to read and write data registers 55-6A. In both cases, you have to set the sensor in CONFIG_MODE. There's more information on page 48 of the datasheet.

The magnetometer is influenced by surrounding magnetic sources like motors. You might be able to tell the extent of the effect using the following method:

The System Calibration Status will start out at 0 and will go to 3
  when the sensor is calibrated. For example, the mag calibration status
  will go to 3 if you do some figure 8s. If you put a piece of metal
  near the sensor, the calibration status will drop to 0. But when the
  metal is moved away, it will go back to 3. You may be able to use this
  value as an indicator that calibration is lost. I have found that once
  it's calibrated, it seems to hold calibration well.

For getting solid readings out of the gyroscope, this might be helpful advice:

I don't worry about scaling the gyro output on a per-sample basis. I simply sum the output into a 32 bit (or larger) integer register. I do subtract-out a null value at each sample, which I will talk about later. But essentially, if you sample your gyro at 1kHz, and sum the output into an accumulator, you will see that the value of that accum at any time will be directly proportional the angle of rotation. If your rate is set for 250 deg/sec, then a rotation of 180 deg will result in approximately 23330000 in the accumulator. I call that the GYRO_CAL number. So, at any given time the angle, in degrees, is deg = accum / GYRO_CAL * 180.
Since the gyro output is linear, the accumulator is insensitive to
  whether the rotation is fast or slow (as long as the max deg/sec isn't
  exceeded).
Here is my basic routine for each gyro reading:

void read_FIFO(){
       sample = read_value_from_FIFO();   //read the latest z-axis sample. I use the fifo, but that isn't necessary
       accum += sample - null;           //add the sample to the sum and subtract the null
       if((accum > GYRO_CAL) -= GYRO_CAL*2;  //roll the accumulator at +180 deg.
       if((accum < -GYRO_CAL) += GYRO_CAL*2; // roll the accumulator at -180 deg.
       angle = accum/GYRO_CAL * 180;   // convert to degrees
}

I calculate the null at the beginning of each run. I sum 1000 readings
  and take the average. The gyro has to sit still for 3 or 4 seconds for
  this. The GYRO_CAL value can be calculated by summing the output while
  you rotate the gyro by 180 deg. Or you can sum over many turns, and
  divide by the number of 180 deg turns for a more accurate value.
You could probably use a 64-bit FP for the accumulator, but since
  arduino only supports 32 bit FP, I found it absolutely necessary to
  use a 32 bit integer to avoid roundoff and other errors.
If you follow that general outline, I promise you will get rock solid
  performance out of the gyro. There are a few other small optimizations
  that I make, which I can discuss later.

Unfortunately, there is no such feature as "permanent calibration" with the BNO055. Yes, once I obtain stable calibration parameters, I can save and later reload them. That's what that forum thread describes, and that's what I'm already doing. Unfortunately, the BNO055 continuously updates and re-calibrates itself, eventually losing these "good" values if the magnetometer encounters a little interference.


text:
is PIN To PIN matching mcu against Atmega328P-AU available?
I want to upgrade my product which is based on Atmega328p-AU, having the problem of programming memory. I don't want to change the PCB of the product. Is PIN To PIN matching MCU against Atmega328P-AU available?

Too little RAM, or too little Flash memory?

The only other AVR chip with more program memory in the 32/TQFP form factor is the ATMEGA4808 at 48 kB.
Unfortunately, the pinout is not the same compared to the ATMEGA328P-AU:
ATMEGAx8P family datasheet
ATMEGAx08 family datasheet

source: Stack Exchange

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

sort: votes


text:
Is Gsm antenna effect on microcontroller working?
in my embedded system I used patch antenna and Atmega 328 microcontroller,but somehow it causes the abrupt function of a microcontroller or reset. how can it be solved?

It's a common problem with GSM. A GSM can have a sudden current spike. The supply might not be able to deliver this and thus one or more devices will reset (power down and up). (http://www.tek.com/sites/tek.com/files/media/document/resources/2032%20Power%20Supply%20WP.pdf)

There are 3 possible causes that I can think of (it's difficult to say more without further details):

SW bug: this is hard to confirm without actually finding the bug, but it might cause a lock-up and trigger a watchdog reset (do you have a watchdog running?) or a pointer error cause a jump to some memory location along the boot path (not so likely, I suspect)
Too tight power envelope: when your system tries to transmit, it draws more power than the power supply/battery can provide. This cause a temporary voltage drop, to the point that the system kinda power cycles. You can try to use a power supply with higher maximum current.
Electromagnetic interference: somehow the transmission interferes with the AVR. You can try to direct the antenna further away from the AVR and to increase the distance in between.

But you should really add more information to your question.

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


text:
Is there a cheap relay that can control voltage from stuff like bulb lights with a 5 V control output?
I need to power a light bulb or something like 110 V or 220 V at normal amperage for TV or something at that range like a fan...
My micro-controller is an Arduino with 5 V out and 12 V max out trough transistor switch.
To my understanding a stepper motor drive could be a viable option to enable the relays... I can even control current, right?
Up to 8 channels
Could this work better?

Just remember SSRs are not good with fluorescent light bulbs as there is  a small current through the relay in closed state.

Which to use where
Ok, so I've narrow the 2 main choices that you have : either a MOSFET or a RELAY. For higher voltages, it is much safer to go with a relay but for higher current, you might as well use a power MOSFET.
Option 1 - Relays
They are mainly used to control already made stuff like a bulb using main's voltage. They are also used to control stuff like a fan (pre built), lamp, and many more. Relays are also simple to wire and don't quire much electronics skills. The main disadvantage of a relay is that they are not as good as MOSFETs when it comes to current handling.
Advantages: Light bulb, stuff bought from the sotre (TVs, fans, small heater), house automation, laundry, house heater, fridge
Opition 2 - MOSFETs
IMPORTANT NOTICE : YOU CANNOT USE A MOSFET WITH MAIN'S VOLTAGE
MOSFETs are great when it comes to kick some voltage in to your devices. I remember as a kid, I use to stock these in NERF guns. Motors will instantly start with MOSFETS!. For even higher current control. Try power mosfets, they are designed for high current. Also know that mosfets are bad in the way that they tend to warm up a lot (if the current is high).
Advantages: Neon light, motors, things that need to be responsive (drone motors), things that need to be precise (PWM)
In conclusion, relays master the world of high voltages and MOSFETs the world of high current!

MOSFETs have an intrinsic body diode between source and drain. You want this diode to be reverse-biased when the MOSFET is off. Hence MOSFETs are not good for switching AC, and mains is AC.

Well thats why I said that Relays are better for mains voltage. Shoud I modify anything?

Yes, make it crystal clear that a MOSFET is unsuitable for switching mains. It is absolutely not obvious from your answer as it stands now.

@EdgarBonet, I included the notice, aything else

It think it is clear enough.

More understandable but if you could give an example on AC relay handling and if an arduino is able to handle it without external modules I could accept this answer! Thanks

I know solid state relays are better but they are not cheap! I want to know if I can wire an 8 channel relay module to control 110v to 220v devices!! Like the one in the link provided

Quick link : https://www.youtube.com/watch?v=LLFQ8sBWc80. He uses a cheap 2-channel but a 8-channel should work. See how he does it and follow CAREFULLY. I can't insist on safety with relays!

So, yes you can use the one from the link that you provided.

You can use a 5V Solid-State Relay module to control light bulbs. They cost $4-6 from US-based suppliers and $1-3 from a Chinese supplier. Just hook up the supply to the center pin and the load to either the NO or NC pin. Supply 5V to the module and wire a digital pin to the module to control it.

Nice one and thanks but could you confirm if any of the ones I found on ebay works as well?? Check my edit

@DarkXDroid The seller did not include part numbers or manufacturer names so I couldn't lookup any datasheets. A relay with a max 250VAC and max 10A rating will be able to handle any standard light bulb. The main concern is how much current is required to trigger the relay. Arduino I/O pins can only supply (or source) ~20mA so if the relay draws more than that it will damage the board. The relays in the link might work but you can't know for sure without the datasheet. I know that Sainsmart relay modules are safe to use with Arduino digital pins.

I got ´´Omron 5V solid state relay 240V 2A, output with resistive fuse 240V 2A?´´
I think itś not enough so I´ll search for 250vac with an 10A, right?

Better Solution?
http://www.ebay.com/itm/ESP8266-2-Kanal-Channel-Relais-Modul-5V-10A-250VAC-10A-30VDC-Optokoppler-Arduino-/282185010711?hash=item41b3898e17:g:k~gAAOSw6n5Xuwl4

Another one? http://www.ebay.com/itm/8-channel-relay-module-optocoupler-isolated-relay-5V10A-opto-relay-board-SN513-2-/291140196745?hash=item43c94ed989:g:lTMAAMXQNo5TZwnw

Is there a way to use transistors as switches? Or are there any other better solution without frying pins or ic?

@DarkXDroid I was about to say transistors or better: mosfets. A mosfet is a good way to switch with Arduino because mosfets require voltage and not current to switch. Many mosfets are designed to trigger between 1~3 volts. You can then supply 5V from the Arduino 5V pin (which can give up to 1A current) and use that to switch the relay.

@Len I saw about mosfets but could understand if they were better options!! Thanks! Could you recommend me one of the option in my comments? I like to make sure If one of them is better than the other based on your exp

@Len This mosfet is a good option http://www.ebay.com/itm/Four-Channel-4-Route-MOSFET-Button-IRF540-V2-0-MOSFET-Switch-Module-Arduino-/200959373944?hash=item2eca1cb278:g:B1oAAOSwwo1Xdeup

You don't need a shield or something. Just get the single mosfet, make sure gate is pulled down and you're basically good to go.

Something like a IRF640 with TO-220 package should be good. Continuous drain can be as high as 18A, so no worries there. Just put 5V on the Gate and it turns on, if you don't put 5V on it, the pulldown resistor will ground Gate and that turns off the mosfet.

@Len can I simplify it by using a motor drive? Cos I have 2 in hands ... Check my edit... But I can change current on at least 4 pins per drive with the module I have without worry on frying the micro

@DarkXDroid I don't know about that. Never used a motor driver like that. I'd stick to mosfets.

The first one you have seems fine (in my opinion). Note though that relays are something not to be cheap with. They can cause dangerous accidents if you buy them from a cheap supplier (chinese). I'll always go for a local supplier (don't know where you live so I can't tell). Make sure to check Radioshack and stores like that.
Also make sure that you find one with a datasheet. No datasheet = no specs. No specs = you don't know the max of your relay which is BAD. The max of a relay should be known and respected or something bad can happen.

First or second option? I understand that low grade equip can cause a disaster but I already have a solution... besides this is prototyping and I want to understand the technology and limits. That why I put a range devices that I could control. But you got a valid point with security and end capacity

first option is the one that i prefer

I´m grateful for everything .... I´go with that at first

In my experience, the relays purchased from a local or US supplier are all made in China anyway.

My exp tells me the same lol the thing is that I should pay more to stay on the safe side

@ThatAintWorking, if you buy it from a US supplier and it fails, you can sue them for $ (only if the product is defective). Buy it from Chine, suffer the consequences...

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


text:
Arduino motor shield orange/white pin usage
I have an Arduino motor shield like this one plugged into my Mega board.

I would like to know some more information about the orange and white pin blocks on the board. The Arduino website has the following information, but it doesn't give any explanation of what is best to use them for or which pins are mapped to the data pins etc.

TinkerKit connectors for two Analog Inputs (in white), connected to A2 and A3.
TinkerKit connectors for two Aanlog Outputs (in orange in the middle), connected to PWM outputs on pins D5 and D6.
TinkerKit connectors for the TWI interface (in white with 4 pins), one for input and the other one for output.

What I want to do is connect a servo up to the board and was hoping I could use one of the orange OUT blocks. I haven't been successful in finding any examples of this which leaves me in doubt as to whether it is possible or not. I would just plug it in, but I'm afraid of frying the shield/mega/servo. Probably an irrational fear, but I can't afford another one of any at the moment!
I don't know which pins in the block are assigned to the data, vcc and out, so if anyone know I would be grateful for the answer.
Also, just because it is annoying not to understand, what are the TWI connectors for?
I hope this isn't too general a question as I could really use some answers!

The Arduino forum has some info you might find useful: http://forum.arduino.cc/index.php?topic=94474.0

Thanks @akellyirl, that is definitely helpful. Not what I was hoping for, but I'm not surprised... I'll just have to extend the 3-wire cable from the servo with individual connectors to go to separate pins on the Arduino as necessary. (I don't particularly want to splice the connector) Oh well!

For what it's worth, Adafruit do a Motor Shield that brings out pins for 2 servos: http://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/overview

TWI = Two Wire Interface (the other 2 pins are power and gnd). This is just a renaming of a possibly incomplete implementation of I²C bus, see: http://en.wikipedia.org/wiki/I%C2%B2C#Derivative_technologies

The 4-pin TWI headers have pitch 2.54 mm and are compatible with Molex crimp housing 22013047 each holding 4x crimp contacts 8500113. Molex also offers complete cable assemblies in three different lengths: 150 mm (2177971041), 300 mm (2177971042) and 600 mm (2177971043).

I don't know which pins in the block are assigned to the data, vcc and
  out, so if anyone know I would be grateful for the answer.

Following the example on TinkerKit's Custom Distance Sensor page, we see that:

If you look on the edge of the sensor, you can see the three pins,
  that are power (5V), ground and signal. The same as your TinkerKit!
  modules, just in a different order.
The only difference is that the signal and ground cable are inverted.

So the order in the connector is Vcc Signal Ground.
Another way, and what I would do to be 100% sure, is measure resistance with a multimeter. If your meter has a continuity test feature, that's even better because it'll beep.
Anyway, put one end of the probe on pin 1 of the connector and the other end on GND and see if the resistance is very close to 0 ohms. If it's reading OL (Over-Limit) then that pin is not GND.
Put the probe on Vcc instead and it should show 0 ohm or beep. So now you know that pin is Vcc.
Do the same for the other pins and find out which one is ground. The third pin is your PWM output. It's connected to D5 or D6, check the continuity on those pins to see which one.

...which pins are mapped to the data pins etc.

The shield page provides a schematic

I would like to know some more information about the orange and white pin blocks on the board

These have the reference printed on the board

TWI IN and TWI OUT
They are the same and are both connected to the same I2C pins of Arduino (SCL, SDA). They are intended to help in case you want to connect more than one device.

OUT 5, OUT 6
Connected to Arduino pins 5 and 6 (PWM outputs)

IN 2, IN 3
Connected to Analog in A2 and A3

The power outputs of L298 intended to drive the motor are the blue screw connectors.

@bladepanthera also remember when you see the tilde ~ on an Arduino board, they are reminding us these pins support PWM. Also, when using connectors, the concept of "in" and "out" are suggestions. I'd rather see A2, A3 to remind us it is capable of analog input.

Although the 'Orange' (Out) pins of the Deek-Robot Motor Shield can be used to drive a servo by swapping the '+5vdc' and 'Signal' wires at the servo harness plug it is best to not do as this.  This is because the current drive for the servo is drawn from the Arduino UNO.  Given that an individual servo can draw well in access of 125ma the current draw may/will exceed the current sink limitations of the associated Arduino UNO circuitry. It is best to use an external power source, properly filtered for electrical noise, as the current source for the servo(s).  This has been documented/recommended in multiple information sources.

You can use Thinkerkit pins(out ~5 and ~6) for controlling servos. Just need to do a bit of tweaking here. Hobby servo motors have got 3 pins orange(signal) , red(live+) in the middle, and brown(gnd-). But, the motor shield rev3 uses the middle pin for signal. To overcome this problem, swap the middle wire with the orange one on the servo plug.
There are three small latches that prevent wires coming out of the plug, use the tip of a needle and with little force slightly lift them up then pull out the wires from the servo plug, they should come off easily.
Remember to attach pin 5 or 6 in the arduino code. I used servo.h library.

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


text:
How to find how much data in the transmit buffer?
How do you find how many bytes are currently waiting in the transmit buffer?
I'm trying to diagnose a weird serial disconnection problem with an Arduino Uno and a rosserial node. It works fine for 10-20 minutes, and then mysteriously losing connection. At first, I thought the Arduino was running out of memory, but I'm able to use the MemoryFree library to log available memory, and it never drops below 9051 bytes.
I now want to make sure the problem isn't because the serial buffer is overflowing, from the Arduino trying to send too much data.

tx buffer doesn't overflow. the write function of HardwareSerial waits for space in the tx buffer

You mean the: https://www.arduino.cc/reference/en/language/functions/communication/serial/availableforwrite/ As @Juraj wrote, the tx buffer does not overflow, if you send too much data the Arduino is slowed down a lot (100 times or more) because it is waiting for space in the tx buffer.

If you really want to know (not that it would do you any good) you can use the Serial.availableForWrite() function (which returns how much space is left in the buffer) and subtract the returned value from the size of the buffer.
int used = 64 - Serial.availableForWrite(); // Assuming a 64 byte buffer

I haven't tested it, but you may be able to use SERIAL_TX_BUFFER_SIZE instead of the 64 to make it properly portable.
int used = SERIAL_TX_BUFFER_SIZE - Serial.availableForWrite(); // Possibly portable

I now want to make sure the problem isn't because the serial buffer is
  overflowing, from the Arduino trying to send too much data.

If you are using the software serial Arduino library there is a way to check for overflow.

that is for rx buffer


text:
how do I detect a data connection?
on an ardunio, is there a way to detect if a data connection (vs power only) is present? I want to have my arduino behave differently if connected to a pc, or on stand alone power.
specifically, I have a project that sends keystrokes to a midi piano program I wrote, but when a pc is not connected, I would like to have the arduino send the notes to a peizo buzzer attached to the circuit instead.
Im using a teensy, or a leonardo, or an Uno.

You could have the main code run when a signal is sent over the serial monitor...

Teensy and Leonardo, probably yes. Uno - no.

for sending keystrokes, no on the uno, but I still think it may be possible to get a status indication. useful for other projects. does the arduino look at the rx/tx pins of the usb?

Are you using the Keyboard class to send HID reports, or are you using Serial and then your program is interpreting it as key presses?

In this project I am using the keyboard class. I was thinking the arduino would have a data pin I could monitor.


text:
Unusualy high fail rate with Adafruit Circuit playgrounds
I am on my 4th failed Adafruit Circuit playground, I can usualy program them a few times, like less than 10, then they become unresponsive. no amount of reseting, rebooting, bootloader re-installations, etc seem to help.
I am using Arduino 1.8.1, on a linux platform, running on a Lenovo T510.
I have numerous other MCUs that have never failed... Im just curious why there is such a high failure rate with the circuit playgrounds I am getting.

Overvoltage somehow? 3.3v Modules with a 5V TTL adapter?


text:
How can I connect a Fona to an Adafruit feather?
I have this adafruit-feather-huzzah-esp8266:
https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/pinouts
and I want to connect a Fona board. But I am not certain which pins have the aforementioned software serial pins
necessary to make the required connections.
https://www.arduino.cc/en/Reference/SoftwareSerial
from the Fona tutorial:
https://learn.adafruit.com/adafruit-fona-3g-cellular-gps-breakout/arduino-wiring
which pins on the adafruit-feather-huzzah-esp8266 should I use for pin:
"TX connects to digital 3 (9 on Leo/Micro, 10 on Mega) "
where the feather doesn't have this a pin3.
similarly, which pins correspond to RST and RX?

you want RX-TX, TX to RX, reset to whatever you have free.

I'll try it, although in the tutorials it is not configured that way

if you need softwareserial, as opposed to hw, on the ESP pins 4+5 are going to be your best bet. if you don't need SPI, 13+15 will work as well.


text:
what pins are attached to ethernet shield SD card?
I have ARDUINO ETH SHIELD 06 - Rev 03. https://www.adafruit.com/product/201
what pins are attached to Ethernet shield SD card?

Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header). This is on digital pins 10, 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used to select the W5100 and pin 4 for the SD card.


text:
neopixel not blinking
I have some neopixels, and I have one hooked up to my teensy.
I want to have the color change, when the push button is pressed vs not pressed. The LED will change colour when I upload the code, if I have the button pressed, green, if the button is not pressed, red.
The serial monitor reports changing button press statuses, so I'm not sure why the neopixel isn't changing.
The adafruit website is confusing to me, they have wonderful and involved project examples, but they never have just a basic IO example.
I would appreciate it, if someone could point out where Im going wrong with this code:
#include <Adafruit_NeoPixel.h>

#define PIN            0

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      1

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
const int buttonPin = 2;
int buttonState = 0;

void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(0,OUTPUT);
  Serial.begin(9600);
  pixels.begin(); // This initializes the NeoPixel library.

}

void loop() {

buttonState = digitalRead(buttonPin);
Serial.println(buttonState);

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
      if (buttonState == LOW) {
          pixels.setPixelColor(PIN, pixels.Color(0,33,0)); // green
          pixels.show();

      }else{
          pixels.setPixelColor(PIN, pixels.Color(66,0,0)); // red
          pixels.show();
        }
        delay(500);
  }

this code compiles, without errors, and uploads just fine, but pressing the button won't change the LED color.

I'm not a Teensy Pro but the neopixel library requires a PWM pin. Pin 0 doesnt seem to be PWM on the Teensy. Try another pin.

NeoPixels most certainly don't require a PWM pin. Although they use PWM for signaling, they don't need a persistent PWM signal.

NeoPixels use assembly instructions to carefully time the signals. It's a weird kind of PWM, that can't be done with hardware PWM, since the width times for a 1 or 0 are different. It's like using PWM but setting the frequency for every bit, but this 1000's time per sec.

@IgnacioVazquez-Abrams . On Arduino, if you do not use a PWM pin with the Adafruit neopixel library, it doesn't work.

@canadiancyborg: Nothing in Adafruit_NeoPixel.cpp requires use of a PWM pin, at least not on AVR. It's all done with loops in assembly.

@IgnacioVazquez-Abrams . well thats just my personnal experience with it. Thanks tought for informing me that I do not to use PWM.

I had a wiring Problem, the device wasn't properly grounded, but still illuminating.
Its working now on pin0, but the idea to use PWM pins is valid. Duly noted.

It could be that if I were to string another neopixel in, it might not still work. I guess Ill have to test that.

No, the idea isn't valid. I've used them on non-PWM pins plenty of times.


text:
lilypad works with wrong baudrate
I wrote a simple code on lillypad with fdti module as below:
void setup(){
Serial.begin(57600);
}
void loop(){
 Serial.println("ddd");
 delay(500);
}

but it gives wrong characters at serial port window of arduino ide at 57600 baudrate. But I changed baudrate to 115200 at same window it gives right string as "ddd". Other baudrates do the same thing. What is the solution or where is the problem. I couldnt understand why baudrate shift occurs

The baud rate shift occurs because of a mismatch between the speed your program thinks the chip is running at and the speed the chip is actually running at.
You may also have noticed that delay(500) is too fast and actually lasts as long as delay(250) would.
By the numbers involved it looks like the board is running twice as fast (115200 / 57600 = 2) as your board definition says it is - maybe you're using an 8MHz definition for a 16MHz board, or a 1MHz definition for a 2MHz board, etc.
Make sure you have the right board definition selected in the IDE for your board.


text:
Is there any realy working setup for multicopter with codes
I'm searching pc controlled quadrotor code projects.  I tried to do strangedev's project but not works for me. Is any one test this project. PID commands works like relays. suddenley speeds up and down. I tried to tune PID constants with Ziegler nichols but no success. Is there any realy working code and setup. Can you share your experiences?

I've not used the (unmaintained) code you reference, but if a PID is responding much too fast in a new system, cut the parameters down significantly, first focusing on P and later I.  Turn off the D, and the I terms, then slow the P down until it is behaving reasonably.  Once Proportional control is working then try bringing I up in proportion to the change you did with P.
The https://github.com/strangedev/Arduino-Quadcopter/blob/master/quadcopter/quadcopter.ino#L62 code starts with (P,I,D) values of (0.5,0,1), so back off to (0.25,0,0) or (0.05,0,0) or lower to get the speed or response more as you expect, and then experiment.
Higher P will make it faster and saturate to the PID limit values quicker and make it more-relay like.  If your system is in a relay-like bang-bang mode, then Zeigler-Nichols tuning will be hard to do well. Reduce P until you get a non-relay-like response.    Show your code and add in some print/debugging to see what sort of pitch values give you what sort of outputs.  PID isn't magical, if you want a pitch measurement of -30 to cause a control output of +10, P=10/(-30)=0.3 might be a good starting point.
The way the unmaintained code looks, value of P=20 will saturate at your output limits of +/-20 with only a pitch measurement of +/-1 degrees.
Show your actual code and values in your question, slow down the PID, and add debugging output.

I did it with ziegler-nichols. But it behaves like relay. I tried pitch tuneup with increase of P slowly but each P constant from 0.1 to 20 gives suddenly  speed up. Also sample time change gives nothing.

Higher P will make it faster and saturate to the +/-100 values quicker and make it more-relay like.  If your system is in a relay-like bang-bang mode, then Zeigler-Nichols will be hard to do well. Reduce P until you get a non-relay-like response.    Show your code and add in some print/debugging to see what sort of pitch values give you what sort of outputs.  PID isn't magical, if you want a pitch measurement of -30 to cause a control output of +10, P=10/(-30)=0.3 might be a good starting point.


text:
Get image from Fingerprint module
I want to get the image from the fingerprint module (https://makeradvisor.com/tools/fingerprint-sensor-module/) as a result of scanning. It is enough to have a single frame image. it would be good if the computer can get image the output image from the serial port (as in linescan camera example: https://www.youtube.com/watch?v=welv4w8B88g https://www.tindie.com/products/ap_tech/tsl1401cl-linescan-camera/)
I am open to your suggestions if it can be done in another module.

Since all of these cheap fingerprint readers are similar you can find a compatible datasheet and just find the commands and descriptions there. However, I couldn't find a datasheet that would include a good description of the protocol. So the other option is to look at the protocot through the software SFGDemo which is apparently capable of getting an image of a fingerprint. Or to use this python package which apparently also can download the image.


text:
Single pin as input and output
Is there a way to set an Arduino pin as being both an input, and an output?
I was looking at tristates, I'm not sure if that is related, or if there is some other method.
Perhaps I can try switching states rapidly. on one pin. I'm just not familiar with how to do it, and I don't see anything about it on the Arduino site.
This is a function of other microcontrollers, such as PICs, but I'm not sure about AVRs and Arduino types.

A tri-state pin is not both an input and an output, rather each pin can be in 1 of 3 states (High, Low, High Impedance). These are typically used on a bus, where many similar devices are connected.
AFAIK the Arduino does not support tri-state, but it is possible to implement a bus. This was done by using open collector/drain devices with a resistor pull-up.
This was a common method of implementing computer busses (more than 40 years ago with RTL logic), but suffers from slow speed, and low fan-out, due to capacitance.
It is still used for low speed short busses such as I²C and 1-wire.
In practice all devices are set as Input. When a device wants to communicate it is configured as Output.

The three states are "High", "Low", and "High-Impedance"; a tri-state pin is always an output.

@IgnacioVazquez-Abrams True - brain fade on my part.

All the I/O pins of an AVR-based Arduino are four-state: not only do they support the three states you mention, they also have a fourth INPUT_PULLUP state, which is a weak pull to Vcc. You can connect a pin to an open-collector bus directly and then just switch between INPUT (i.e. HiZ, to either read or write 1) and OUTPUT LOW (to write 0).

The source code for the 1-Wire protocol is a great place to start when learning how to use a single pin for both input and output.
See also chap. 18. I/O-Ports in the ATmega328p datasheet.
Cheers!

Does it mater that the device isnt a 1-wire protocol item? Its NeoPixel Rings. such as https://www.adafruit.com/products/1643

@j0h: Why do you need to connect that as an input? The output from those is usually only useful for chaining them together.


text:
What boards have integrated USB charging?
I've been building wearables, using the adafruit trinket, which I love, its small size is easy to tuck away. But I hate having to unplug the battery to charge it every time. I wired in a SPDT switch, and a small USB charger, but it's kind of a cockamamie solution.
I've seen some devices with a battery adapter, and integrated USB charging,
but they are larger, and harder to tuck away.
I don't need more than 4 IO ports, I'm just looking for a tiny microcontroller platform with integrated USB charging. I just saw the mkr1000 today, which looks decent, but is still larger than I would like. If you know of a product that meets this description, please let me know.

https://www.adafruit.com/product/2124 maybe?

The Feather mainboards are fairly small and have integrated LiPo/Li-ion charging. They're not as small at the Trinket but if you don't need the space on the proto boards then you can examine the design files to see what can be cut away.

Im looking into that, but Im a newb when it comes to eagle cad

You can safely cut away the prototype area of the Feather 32U4. Though you'd also cut away the SPI, I2C, and UART pins. So unless your project isn't using any of those, this is not an option. (PS you could still get to SDA and SCL by soldering a wire to the vias)


text:
how to put whitespace in long Serial println() input
I have this long, Serial.println() that is in quotes, on multiple lines.
Arduino IDE warns: "Missing terminating character".
I am certain there is a way to break the lines up, while having the entire text enclosed in quotes, but I don't remember how.
Serial.println("
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
<svg
   xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
    xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:sodipodi=\"http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd\"
   id=\"svg8\" version=\"1.1\" viewBox=\"0 0 227.35277 156.29323\"
   height=\"6.1532764in\"
   width=\"8.9508963in\"
   sodipodi:docname=\"etchasketchborder.svg\">
    <defs
     id=\"defs2\" />
  <path
     style=\"fill:#ff0000;stroke:#ff0000;stroke-width:1.32300019;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
     d=\"m 12.000819,0.66145838 c -6.2819637,0 -11.33936062,5.05739692 -11.33936062,11.33936062 V 144.29249 c 0,6.28197 5.05739692,11.33936 11.33936062,11.33936 H 215.35224 c 6.28197,0 11.33885,-5.05739 11.33885,-11.33936 V 12.000819 c 0,-6.2819637 -5.05688,-11.33936062 -11.33885,-11.33936062 z M 18.932696,12.696383 H 205.5854 c 5.02557,0 9.07128,4.04571 9.07128,9.071282 v 77.03923 c 0,5.025575 -4.04571,9.071285 -9.07128,9.071285 H 18.932696 c -5.025572,0 -9.0712819,-4.04571 -9.0712819,-9.071285 v -77.03923 c 0,-5.025572 4.0457099,-9.071282 9.0712819,-9.071282 z\"
    />
  <ellipse
     style=\"fill:#ffffff;fill-opacity:1;stroke:#ff0000;stroke-width:1.32300007;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
     cx=\"21.16666\"
     cy=\"130.59085\"
     rx=\"10.583334\"
     ry=\"9.0714283\" />
  <ellipse
     style=\"fill:#ffffff;fill-opacity:1;stroke:#ff0000;stroke-width:1.32300007;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1\"
     cx=\"200.62982\"
     cy=\"131.57361\"
     rx=\"10.583334\"
     ry=\"9.0714283\" />
      </svg>
");

https://stackoverflow.com/questions/1135841/c-multiline-string-literal

Ah, I figured it out.
you cant do this:
Serial.println("foo
                                bar");

but you can do this:
Serial.println("Foo"
                "Bar");

So then in bash I write a little command, to take my svg files, and escape the quotes that exist in the file, then another line to add quotes at the start and end of every newline. then I can just copy paste my svg images into the println() function.
$ sed -i 's/"/\\"/g' input.svg

and
$ xargs -I{lin} echo \"{lin}\" <input.svg

respectively.

Note that "foo" "bar" (on separate lines) results in "foobar" not "foo\nbar" as the layout would suggest.

sure, I was just looking to break it up visually. I think the svg doesnt care about newlines, and if it does, ill just add a \n into my bash script.

SVG doesn't care (It's just XML after all) - but just something to keep at the back of your mind in case you use the same trick for something that does care (or for other users that read this answer and don't realise that little caveat).


text:
Arduino freezes if I do NOT do Serial.println() at least TWICE
Hii I have a big project, and found this when I tried to remove all the test code.
To summarize:

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

You can see the main.cpp file here. (you can check the entire repo here)
My setup:

Arduino Nano (Clone) Old bootloader
SSD1306 (Clone) Oled 128x32 with ss_oled library as controller
3 DIY Buttons
VS Code with platformio installed.

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

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

New things I've discovered:

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

I´ve created a pastebin showing these last 2 items more clearly.

what happens if you call Serial.println("test123") twice?

try delay(10); instead of the two prints

Is there a specific reason you have while (!Serial); at the start of your code? On a nano it should do nothing, but you never know...

Also note that the SSD1306 OLED display takes most of your RAM, leaving you very little to play with. There's a very high chance it's failing to allocate its internal buffer and crashing.

jsotola replaced the prints as you suggested, didn't work.
Juraj added delay(50) before the 2 jsotola prints, didn't work, removed the jsotola prints and left only the delay(50), also didn't work.
Majenko, I've added that while(!Serial) in a desperate moment to fix this problem. Also, I don't think that is, because it runs nice and smooth when the 2 prints with internalbuffer are ran.

then you have some error in your code, which causes 'undefined behavior'


text:
Fader OOP Problem
This code works and it can fade three LEDs without any problem, obviously you can even add more of them : )
// Pins Definition
const int button1 = 13;
const int button2 = 12;
const int button3 = 11;
const int redled = 2;
const int greenled = 3;
const int blueled = 4;

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

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

    // Pins
    int led;
    int buttonpin;

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

  public:

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

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

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

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

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

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

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

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

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

LED ledblue;
LED ledgreen;
LED ledred;

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

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

Comments are not for extended discussion; this conversation has been moved to chat.

I don't really know about the
// Pins
byte led;
byte buttonpin;

but maybe you can try
// Pins
int led;
int buttonpin;

I changed them to integers but there's no change in the speed of the program, but I saw that if I change the position of Now and ElaspedLoopTime in the main Loop it will get faster but it doesn't completely work

I don't agree that it isn't an answer. It looks like an answer. I just happens to not solve the problem.

@NickGammon I fixed everything right now so I changed the title to [Solved], this is my first time in a forum so I don't really know if i can close the question or not

@alessandromrc For example see https://meta.stackexchange.com/questions/116101/is-it-ok-to-add-solved-to-the-title-of-a-question

@DaveNewton Thanks!

I have a tutorial similar to this: https://www.instructables.com/How-to-Create-an-Arduino-Library/


text:
Physically passing through a pin to access another
I would like to know about physically passing through a pin in order to get to another. For instance, if I have a sensor on one side of an ATMEGA328P or ESP8266 (Wemos D1 Mini) yet need to connect to a pin on the other side, would I be able to simply go through an unused pin instead of worrying about going around or using a jumper wire? If so, would I need to set the unused pin in a certain way, for example as an input (with or without pull-up)?
PS: The diagram  of the first answer illustrates my question exactly and the answer has been accepted as the solution.

It is unclear to me, what exactly your problem is. Why would you need to "go through a pin" (whatever that means) to access another pin? The pins are all spaced out. Why are you not able to reach the pin, that you want to connect?

No.  If you want to connect to a certain pin then you need to connect to that pin.  The pins are physically connected to certain parts of the chip.  They're not re-routable.

Let me see if I understand what you are asking. You want to connect both the relevant pin and an unrelated one, like in this DIP footprint:

If this is the case, the answer is yes, provided that the pass-through pin is always held in a high-impedance (i.e. INPUT) state.

This is exactly the answer to the question at hand. Thank you.

Make sure that the unused pin isn't configured for any conflicting functions like SPI, I2C, or UART communication, as this could interfere with the signal you're routing.

Thanks. I thought as much that is why I referred to the pin as unused, but I guess I didn't clarify p0roperly.


text:
MKR1400-how do I troubleshoot a POST request?
I'm successfully sending a GET request (in the setup function, to load certificates,) but my POST request fails with a bunch of AT errors. I suspect this has to do with the way I'm formatting the POST. Any ideas would be appreciated.
Code follows:
// MKRGSM - Version: 1.5.0
#include <MKRGSM.h>
#include <ArduinoJson.h>
#include <Arduino_MKRGPS.h>

const char PINNUMBER[]     = "";
// APN data

const char GPRS_APN[]      = SECRET_GPRS_APN;

const char GPRS_LOGIN[]    = "";

const char GPRS_PASSWORD[] = "";

DynamicJsonDocument doc(1024);

// initialize the library instance

GSMSSLClient client;

GPRS gprs;

GSM gsmAccess(true);

// Specify IP address or hostname

char server[] = "webhook.site";
char path[] = "/ce480c43-95a8-4f1e-b996-bc02f6d1adaa";
int port = 443;

void setup() {

  // initialize serial communications and wait for port to open:

  Serial.begin(9600);

  while (!Serial) {

    ; // wait for serial port to connect. Needed for native USB port only

  }

  // If you are using the MKR GPS as shield, change the next line to pass

  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  delay(200);

  if (!GPS.begin()) {

    Serial.println("Failed to initialize GPS!");

    while (1);

  }
  Serial.println("Starting Arduino GSM ping.");
  // connection state
  bool connected = false;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while (!connected)
  {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY))
    {
      connected = true;
    }
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  // Use this to load Root Certs the first time
  if (client.connect(server, port))
  // Use this to not load Root Certs anymore as done last time and stored in modem's flash
//  if (client.connect(server, port, false))
  {
        Serial.println("connected");

    // Make a HTTP request:

    client.print("GET ");

    client.print(path);

    client.println(" HTTP/1.1");

    client.print("Host: ");

    client.println(server);

    client.println("Connection: close");

    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {

  ...GPS stuff happens here

  // print GPS values

  Serial.println();

  Serial.print("Location: ");

  Serial.print(latitude, 7);

  Serial.print(", ");

  Serial.println(longitude, 7);

  Serial.print("Altitude: ");

  Serial.print(altitude);

  Serial.println("m");

  Serial.print("Number of satellites: ");

  Serial.println(satellites);

  doc["latitude"] = latitude;
  doc["longitude"] = longitude;
  doc["altitude"] = altitude;

  String location;
  serializeJson(doc, location);
  Serial.print("Location string: ");
  Serial.println(location);

  Serial.println();

  Serial.println("Starting Arduino web client.");

  // connection state

  if (client.available()) {
    Serial.println("Sending location");
    client.print("POST ");
    client.print(path);
    client.println(" HTTP/1.1");
    delay(5);
    client.println("Content-Type: application/json;");
    delay(5);
    client.print("Content-Length: ");
    client.println(location.length());
    client.print("Host: ");
    client.println(server);
    delay(5);
    client.println("Connection: close");
    delay(5);
    client.println();
    delay(5);
    client.println(location);
    Serial.print("Successfully sent location");

    if (!client.available() && !client.connected()) {

      Serial.println();

      Serial.println("disconnecting.");

      client.stop();
    }
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }

}

Here's what the output looks like:

Location: 32.1208382, 35.2468376 Altitude: 640.40m Number of
satellites: 5 Location string:
{"latitude":32.12084,"longitude":35.24684,"altitude":640.4}
Starting Arduino web client. Sending location
AT+USOWR=0,13,"504F53542068747470733A2F2F"
ERROR
AT+USOWR=0,37,"2F63653438306334332D393561382D346631652D623939362D626330326636643161646161"
ERROR AT+USOWR=0,9,"20485454502F312E31"
ERROR AT+USOWR=0,2,"0D0A"
ERROR
AT+USOWR=0,31,"436F6E74656E742D547970653A206170706C69636174696F6E2F6A736F6E3B"
ERROR AT+USOWR=0,2,"0D0A"
ERROR AT+USOWR=0,16,"436F6E74656E742D4C656E6774683A20"
ERROR AT+USOWR=0,2,"3539"
ERROR AT+USOWR=0,2,"0D0A"
ERROR AT+USOWR=0,6,"486F73743A20"
ERROR AT+USOWR=0,12,"776562686F6F6B2E73697465"
ERROR AT+USOWR=0,2,"0D0A"
ERROR AT+USOWR=0,17,"436F6E6E656374696F6E3A20636C6F7365"
ERROR AT+USOWR=0,2,"0D0A"
ERROR AT+USOWR=0,2,"0D0A"
ERROR
AT+USOWR=0,59,"7B226C61746974756465223A33322E31323038342C226C6F6E676974756465223A33352E32343638342C22616C746974756465223A3634302E347D"
ERROR AT+USOWR=0,2,"0D0A"
ERROR

I could send the data as parameters in the GET query, but that's ugly.

see the GSMWebClient example

I saw that example, but it's a GET.

Your HTTP request is badly formatted.

reading the response is same. and the HTTP request line shouldn't have a complete URL for POST either

Your HTTP request is badly formatted.  You have:
POST https://webhook.site/ce480c43-95a8-4f1e-b996-bc02f6d1adaa HTTP/1.1
Content-Type: application/json

Instead the protocol is implied by the port you are connecting to, and the domain name does not go in the path on the server component - it has its own header.
Your request should look more like:
POST /ce480c43-95a8-4f1e-b996-bc02f6d1adaa HTTP/1.1
Host: webhook.site
Content-Type: application/json
Content-Length: [x]
Connection: close

[location]

Where [x] is location.length() and [location] is the content of the location string.

Thanks, I've updated the code as per your suggestions. Unfortunately, it's still failing. I'm not even seeing it go into the if (client.connect(server, port)) { block, which suggests that there is something wrong with the way I'm initializing the client.

@BorisK You need to add a second newline after Connection: close. In HTTP the headers and content are separated by two newlines. Your original question included this client.println();, but your updated code omitted this.

@gerben I'm not even seeing the "Sending location" output, which suggests the client is not connecting

@Gerben I have swapped SIMs and am now connecting on a GET but failing on a POST. I've updated the original question. If you could take a look, I would be grateful.

The problem was that GSM gsmAccess; needed to be GSM gsmAccess(true). Unfortunately, while that solves the immediate problem, which is that the client was not initializing, there are other issues which deserve a separate question.


text:
DFPlayer Mini does not boot reliably after being powered down
For a low power project, I need to power up the DFPlayer Mini module, let it say something, and power it down again using an Arduino Nano (w/o power regulator and LEDs). In the idle time, the Arduino will go to deep sleep. This is to be repeated regularly, e.g. on a daily basis. However, it seems I'm not able to power the module down in the right fashion. The module is connected to the Arduino via an n-channel logic-level MOSFET (IRLZ44N), such that the Player's VCC is permanently at ~5.3 V (4x1.3 V batteries), but no current can flow through the FET's drain to ground (source) if the MOSFET is not switched on via one of the Arduinos pins on its gate. I have a pull-down resistor on the gate to prevent a floating state and a 100uF capacitor from 5V to GND, otherwise turning on the MOSFET apparently causes a current spike which can reset the Arduino. The player's RX is protected by a 1k resistor as described in several tutorials. 5.3 V is not exactly within the specs of the player, but it doesn't seem to be the issue, as the following code works in the sense that the player does its job consistently fine in the first iteration of the loop but then fails every time afterwards.
#include <Arduino.h>
#include <LowPower.h>
#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>

// MP3 module is powered through logic-level MOSFET
// 100uF capacitor is connected across 5V - GND to smoothen current spikes
static const int MP3Power = 2;
static const int MP3Tx    = 3;
static const int MP3Rx    = 4;
static const int MP3Baud  = 9600; // Default hardware baud rate

uint32_t loop_count = 50000; // large loop_count: start into working loop after reset
//unsigned long loop_max;

uint32_t loop_max   = 1;     // 8 sec * 1 ~ 8 sec

DFRobotDFPlayerMini player;
SoftwareSerial MP3serial(MP3Rx, MP3Tx); // RX, TX

void speak(int filenumber, int volume=20);

void setup() {
  // Set all pins connected to MOSFET gates as low outputs.
  pinMode(MP3Power, OUTPUT); digitalWrite(MP3Power, LOW);
}

void loop() {
  if (loop_count < loop_max) {
    // increase loop counter, then go to deep sleep for 8 sec.
    loop_count++;
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  } else {
    // reset loop count, speak
    loop_count = 0;
    speak(1);
  }
}

void speak(int filenumber, int volume) {
  // turn on power for mp3 module
  digitalWrite(MP3Power, HIGH);
  // wait for the module to cope with being powered up
  // it does light up its LED when powered up and doesn't seem to like
  // to be talked to right away.
  delay(1500);

  // initialise mp3 serial communication
  MP3serial.begin(MP3Baud);
  // sometimes I added another delay here, but it didn't really change to much.

  if (!player.begin(MP3serial)) {
    // MP3 Player can't start -- shut down everything and return early (but gracefully?)
    /*
     * This is where I end up after the first time worked. I can confirm this e.g. by blinking an
     * LED in here or reading the player's state, which returns a timeout error, whatever this means.
     */
    MP3serial.flush();
    MP3serial.end();
    digitalWrite(MP3Power, LOW);
    delay(100);
    return ;
  }

  player.setTimeOut(1000);
  player.EQ(DFPLAYER_EQ_POP);
  player.outputDevice(DFPLAYER_DEVICE_SD);

  player.volume(volume);
  player.playMp3Folder(filenumber);

  // enter this loop until playing is finished
  while (true) {
    delay(250); // give the player a little time before querying
    int i = player.readState();
    delay(250); // give the player a little more time, just in case
    if (i != 1) {
      // 1 means playing, break out when finished
      break;
    }
  }

  // close mp3 module
  MP3serial.flush();
  MP3serial.end();
  // wait a bit?
  delay(100);
  // turn off power
  digitalWrite(MP3Power, LOW);
  // wait until everything is turned off for good
  delay(100);

  // I also tried this, but it didn't really change anything
  //pinMode(MP3Tx,OUTPUT); digitalWrite(MP3Tx, HIGH);
  //pinMode(MP3Rx,OUTPUT); digitalWrite(MP3Rx, HIGH);
}

I also managed to obtain some delay settings via trial and error such that sometimes it would play another track, but this was very unstable. As you can see, I have a lot of delays, which makes me unhappy. I suspect that the error lies somewhere within the part which powers down the DFPlayer mini module. Can someone give me a hint what I'm doing wrong?

please add a schematic diagram of the circuit

I added two diagrams, are these ok?

On the breadboard, the top blue rail doesn't have a connection to the bottom blue rail. In the schematic, the GND pin on the DFPLAYER MINI is not connected to anything.

Well, there's no direct connection between the top and bottom blue rails as the point of the MOSFET is to disconnect them if it is switched off. They are connected to the MOSFET on its drain and source terminals, respectively. So this is intended. The DFPlayer Mini's pin 10 (GND) isn't connected to anything, but the same GND (pin 7) is actually connected to the top blue rail. I could connect pin 7 and 10, but it doesn't make any difference, since they are already connected internally.

It would be better to have a high-side MOSFET switch to control the power to the DFPLAYER and connect both GNDs to ground.

Unfortunately, I only have two logic-level MOSFET types available: IRLZ44N (the one I used so far) and IRL540N, both are N-channel enhancement mode MOSFETs. As written in the question, the first run does work completely fine, so the power setup seems to work (power is off initially!). The problem arises only after I power down the DFPlayer and power it up again. It actually does power up again, but communication doesn't seem to work properly, as I get these timeout errors. Hence, I actually assume this is rather a software issue due to turning the serial communication off and on again.

Try using a mechanical switch or wire link in place of a high-side MOSFET switch to see if you can depower and repower the DFPLAYER and continue successfully with the programme.

Following your suggestion, I removed the MOSFET completely from the breadboard and instead bridged the top blue rail with the bottom one (so actually there's no switch involved anymore). I left the sketch as above. The same thing happens: The player works the first time after powering up / resetting the Arduino, then starting with the second iteration, the player fails to play the file each time.

More information: With the bridged rails, the setup does work, if I comment out the lines containing MP3serial.flush(); and MP3serial.end();. However, taking the  bridge away again and plugging the MOSFET back in, same issue: works in the first iteration then fails, but sometimes it starts the audio and then stops.

With the bridged rails and no MOSFET, what happens when you depower and repower the DFPLAYER via a high-side wire link during the 8 second sleep? Does it then work during the subsequent iteration?

I removed the MOSFET and added a bride, s.th. both the 5V and GND rails are connected via bridges. This works if I comment out the flush and end commands. Then, if I pull either the 5V or the GND bridge and plug it back in place, it works (It actually works regardless of whether I plug it back in time or not, which seriously confuses me). That being said, if I plug out the 5V bridge, the Arduino draws more than 3 mA in deep sleep (due to serial left on!?), but w/o the GND bridge it draws only ~0.1 mA. The latter is what I'm aiming for, as it shall run for a year on a 1900mAh battery.


text:
Arduino Nano skips statements after Interrupt
I am using an Arduino to control an AC Phase Control Circuit to control some lamps.
The problem is that the interrupts seem to break the code inside the loop().
This Code should just blink one lamp. But it doesnt!
What I found out so far:
The Led always has dim_level[22] so it seems like (at least the first) delay in the loop is skipped.
The strange thing:
When i add a statement that takes some time between the delays everything is working
For example
void loop() {
  CH[0] = dim_level[0];
  Serial.println("---------------------------------------------------------");
  delay(500);
  CH[0] = dim_level[22];
  Serial.println("---------------------------------------------------------");
  delay(500);
}

The not working code:
#include <TimerOne.h>

unsigned char channel_1 = 7;    // Output to Opto Triac pin, channel 1
unsigned char channel_2 = 6;    // Output to Opto Triac pin, channel 2
unsigned char channel_3 = 5;    // Output to Opto Triac pin, channel 3
unsigned char channel_4 = 4;    // Output to Opto Triac pin, channel 4
unsigned char CH1, CH2, CH3, CH4;
unsigned char i = 0;
unsigned char delay_time = 1;   // delay ms or flashing SPEED
unsigned char clock_tick;        // variable for Timer1
unsigned char CHANNEL_SELECT;    // variable for channel select

unsigned char CH[] = {CH1, CH2, CH3, CH4};

unsigned char dim_level[] = {5, 8, 10, 12, 15, 18, 20, 25, 30, 35, 45, 50, 55, 60, 65, 70, 75, 80, 82, 85, 88, 92, 95}; // don't use this massive for 60Hz
// create new massive for 60Hz
void setup() {
  Serial.begin(2000000);
  pinMode(channel_1, OUTPUT);// Set AC Load pin as output
  pinMode(channel_2, OUTPUT);// Set AC Load pin as output
  pinMode(channel_3, OUTPUT);// Set AC Load pin as output
  pinMode(channel_4, OUTPUT);// Set AC Load pin as output
  attachInterrupt(1, zero_crosss_int, RISING);
  Timer1.initialize(100); // set a timer of length 100 microseconds for 50Hz or 83 microseconds for 60Hz;
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here

}

void timerIsr()
{
  clock_tick++;
  if (CH[0] == clock_tick)
  {

    digitalWrite(channel_1, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_1, LOW);    // triac Off
  }

  if (CH[1] == clock_tick)
  {
    digitalWrite(channel_2, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_2, LOW);    // triac Off
  }

  if (CH[2] == clock_tick)
  {
    digitalWrite(channel_3, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_3, LOW);    // triac Off
  }

  if (CH[3] == clock_tick)
  {
    digitalWrite(channel_4, HIGH);   // triac firing
    delayMicroseconds(10);           // triac On propogation delay (for 60Hz use 8.33)
    digitalWrite(channel_4, LOW);    // triac Off
  }
}

void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  clock_tick = 0;
}

void loop() {
  CH[0] = dim_level[0];

  delay(500);
  CH[0] = dim_level[22];

  delay(500);
}

Im new to arduino maybeIi miss some concepts but I read that interupts should not break delays outside interrupt

volatile qualify CH.

I don't know whether or not it's appropriate to mark as as duplicate for this, but have a look at this question and the answer given there.  If that makes things work, then maybe it makes sense.

@timemage yes thats is - thank you. you want to post an answer?

Like timemage mentioned i had to qualify ch as volatile.
so:
volatile unsigned char CH[] = {CH1, CH2, CH3, CH4};

is the fix


text:
How to properly send bytes between RPI and Arduino over I2C while using ISR without IOerrors?
I have a I2C connection between an RPI 3B+ and Arduino Nano. I want to send a key and a corresponding value byte, and the arduino does something with that inside a timed ISR. Which works. But I get IOerrors at the RPI side, probably because the ISR is busy. So I did a little test. Every 10000 messages send:

245 IOerrors at 51,281 Hz ISR
104 IOerrors at 25,600 Hz ISR
28 IOerrors at 6,400 Hz ISR

Is there any way to have less or no IOerrors? I need about 25,600 kHz for my ISR.
RPI side:
bus.write_i2c_block_data(0x60, 0x00, [key, val])

Arduino side message handler called as Wire.onReceive(msg_handler);:
void msg_handler(int bitstream) {
     Wire.read();
     int pin = Wire.read();
     int val = Wire.read();
     Serial.println(pin);
     Wire.begin(0x60);

I do the wire begin every time because otherwise once it had a IOerror it stops printing on the serial.
My wiring is 18 AWG and about 20cm. The error:
[Errno 121] Remote I/O error

What i2c clock speed are you using?
Even at the faster "fairly standard" speed of 400kHz, that's 2.5us per bit. For a two byte transfer, that's 4us for the data alone, which is 25000 transfers per second. Add on the start and stop bits, plus processing time and you can see that your target data rate isn't possible.
i2c just isn't that fast as standard, though there are much faster "non standard" modes.


text:
Correct usage of SPI with ISR
My Arduino needs to do:

Run ISR as many times as possible/ as fast as possible.
Occasionally receive data over I2C.
Output data over SPI in ISR.

My question is regarding SPI and ISR.
The documentation about SPI I found, was quite poor.
SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0));
SPI.usingInterrupt(255);
SPI.begin();

void isr_function()
        SPI.transfer(data);
        pulse_latch();
};

Is this the correct use of SPI in my case?
Can it be faster?

The SPI library function; transfer is blocking. If you really need some additional cpu cycles, you can send the data between ISR calls instead. The SPI hardware can send the data while the CPU is doing something useful, instead of waiting for the SPI transfer to finish. You would then latch the data at the beginning of (the next) ISR.

PS You can't run SPI at 16Mhz on a Nano. The maximum speed is F_CPU/2, if I remember correctly, which would be 8MHz

If you need to push a lot of data quickly through SPI, it's a lot more convenient to use a micro with a SPI peripheral that supports DMA. Most likely the ARM-based arduinos will fit the bill.


text:
SIM800L and UNO can't request web page
I know this module is super old but the network I am on still uses GPRS so should work.
This is the module:

I am using the Adafruit example scipt FONAtest. I can connect to GPRS
    <--- SHUT OK
    ---> AT+CGATT=1
    <--- OK
    ---> AT+SAPBR=3,1,"CONTYPE","GPRS"
    <--- OK
    ---> AT+SAPBR=3,1,"APN","live.vodafone.com"
    <--- OK
    ---> AT+CSTT="live.vodafone.com","",""
    <--- OK
    ---> AT+SAPBR=3,1,"USER",""
    <--- OK
    ---> AT+SAPBR=3,1,"PWD",""
    <--- OK
    ---> AT+SAPBR=1,1
    <--- OK
    ---> AT+CIICR
    <--- OK
FONA>

There is credit on the SIM so it has data for sure, I can also send SMS.
There are several different approaches people seem to take (altering AT commands) to persuade this device to work, pretty sure I have tried all of them :) I always get a timeout when trying to read or GET a webpage.
I have tried several combinations via terminal and I seem to connect ok but get no further. It has worked once, but that was in a different part of town.
How do I check that the GPRS is actually connected? Any troubleshooting tips?
There is a dedicated 2A 5V connected to the unit, it isn't dropping out AFAIK. Do you have a rock-solid AT sequence that always works?
Also, there seem to be SAPBR commands that don't work at all, not sure why?

You should check whether the GPRS is attached with AT+CGATT?, after sending AT+CGATT=1, if it return +CGATT: 1, it means it is attached and you can proceed for the next step.

Don't know why, I had to manually set the DNS t0 8.8.8.8 using AT+CDNSCFG?
It had DNS entries in there but they didn't want to resolve for some reason.

It highly depends on the URL you are trying to fetch.
Those modules DO NOT understand secure HTTP/S. They only understand plain unsecure HTTP.
Most web pages nowdays don't offer unsecure HTTP access and always redirect the request to a HTTP/S server. So in my opinion the usefulness of those devices is very limited when it comes to internet access.
If you have full control over the web server you should disable the enforcement of a secure connection.
Beyond that. The sequence you posted is just for activating GPRS.
I also found the FONA sample for fetching a page not very reliable but I was able to request the page multiple time. Perheps you have your module in a place with low signal strenght. Does your module offer an u.fl connector for a better antenna?

It does have a u.fl connector and I have the bundled antenna attached. The RSSI is -89 which I think isn't great. The code I always get is 603

I do have control over the webserver and it is http


text:
3th time blown à Nano every
Like subject all ready telling you, I blew up my 3th Nano every.
I mounted them on a perf board, soldered with 99% tin 1.0mm and a Flux, cleaned with flux remover, etc... When I then power them up through USB I have a short on pin 29 and 30 (Vin Gnd). And the board is ready to go directly in the poubelle (the garbage thing).
Second and third time, after soldering I scratched the space between both pins to make sure there is no connection. But...
Yip again. Is this a common issue? Am I overseeing something?
Did my measurements with multimeter. No shorts.

which perfboard did you use? ... what is the picture supposed to show? ... you have provided zero information about what you did

have you tested all relevant pins for connections? I mean actually testing them (for example with a multimeter)

those are not answers ... you are still providing zero information ... i did not ask you where you bought the perf board ... please provide clear pictures of the two sides of the perf board before any work was done ... also provide clear pictures that show what you did

Thx for your answers. I use a Ali express perfboard. The picture show the Vin and Gnd pin at the left. I want to show you the gap between the two solderpoints. The only thing I did was soldered the Nano in place, powered over USB en floep. Spark between Vin en Gnd. I tested all the pin with a multimeter. Didn't got saw any issues. Could it be the perfboard?

where exactly did you see a spark? ... the only time you will see a spark with a 5 V supply, is when two condutors are very close together or the voltage is much higher than you think

Can you post a sketch or schematic showing how all of this is connected. Your picture shows 4 pins but what are they, I cannot see the other side of the board? How did you determine you have a short>

posted the pictures in the question, dont mind the cap, he's there but not connected. I see smoke, and hear crakling sounds between pin Vin en Gnd. I power the nano over usb, the first time I used a bench powersupply. I thought that was the issue. Then I used legit usb powersupply from one of my Rpi's, same issues. The third time I used the usb port from my pc and scratched between Vin and Gnd to make sure there is enough gap between the two pins, as seen on first picture, first pin on the left is Vin, Gnd is second pin.

I took the time to hang the nano on my bench power to show you what is happening. What you're seeing here are pins 29 and 30 Vin and ground. https://drive.google.com/file/d/183kBK4hXRMbkuoGcrJJOLEInRQ5zVFIP/view?usp=sharing

Use pin headers and check for the shorts before you'll insert board...

if gnd shorted to vin, the nano should be okay.

What solder are you using? What flux are you using? What flux cleaner are you using?

i looked at the video ... wow ... definitely looks like contamination ... are you using paste solder? ... solder two bare pins that are not connected to anything and measure the resistance between them

measure resistance between two adjacent, unused holes ... the board itself may have a conductive layer

have you removed the Nano and tested it? ... it may be undamaged .... afrer the short circuit in the video burns itself out, the Nano may be functional, but being held in a reset state by a short between reset and gnd

@jsotola on your advice, I prept a perfboard like this, two bare pins using only solder, two with solder and flux, two with solder flux and cleaner. And apparently its the solder that causes the problem, and maybe the fact I didn't cleaned the board enough afterward? But ok, I don't think this should happen... I'm using Welco solder. Flux is from Weller and the cleaner I use is Cramolin. I desoldered the nano, I get a USB corrupted notif. When compiling I get these messages bit.ly/2WIK0d3
bit.ly/2WFt0nB

I don't know "welco". Is it an electronics solder or a plumber's solder? The same for the flux: is it electronic flux or plumber's flux?

If i am not wrong you have soldered nano directly to the  perf board, which i don't recommend at all. You could try soldering a female strip pin on to the pref board and insert the nano board in the strip pin. This way you could easily remove/install the board easily as you wish.

Since whoever down-voted this didn't bother to say, I'll offer a guess as to the reason. They appear to still be developing the question.  And one of the comments suggests doing this exact thing, though, I think as a diagnostic measure rather than answer.


text:
Hardware implementation of trigonometric functions?
Is anybody aware as to whether there are any modern microcontrollers that have hardware implementations of trigonometric functions? According to my understanding, modern CPUs have basic maths functions such as square roots and the trigonometric functions implemented in hardware to increase the speed and/or throughput of these maths functions. Do any widely used microcontrollers you know of have similar hardware implementations?
The reason I am asking this is because I want to know if it is feasible to implement more efficient trigonometric functions for specific use cases. On modern CPUs with the right compiler settings, it is almost always faster to use or derive from the built in trigonometric functions, rather than rolling your own software implementation specific to your problem.

It does belong in the question doesn't it.. hehe. And no, I'm talking about whether software implementations can realistically be faster than the standard implementations provided by standard libraries. Be that specialised versions of the taylor series, or other non-standard approaches to implementing something like sine.

I'm actually beating around the bush to avoid embarrassing myself, I have a class to generate a continuous sine wave of a constant frequency/sampling rate, and it doesn't have a place in modern high performance code due to the aforementioned built in trigonometric functions present on modern CPUs. However I would like to know if it has a use in lower processing power devices such as microcontrollers and microprocessors. Should I delete this question and actually provide the code for criticism?

"are you not aware of the purpose of this site?" mate all I was asking was if microcontrollers had something like a single machine instruction to compute trigonometric functions. There doesn't seem to be a general "microcontroller" stack exchange site so I thought this place would be best. Apparently not.

Electronics Stack Exchange is more targeted at microcontrollers in general. For your question to be on-topic here you would need to be asking about an Arduino implementation. As Arduino is, generally speaking, targeted at beginners there would probably be no such thing.

For small / slow MCUs it is more common to use a LUT than to calculate these kind of numbers on the fly.

I do not know the answer to your main question, but I will try to answer
the underlying question:

I want to know if it is feasible to implement more efficient
trigonometric functions for specific use cases.

There are microcontrollers that do not have hardware implementations
of trig functions, and that is the main point. The AVRs powering many
Arduinos are among them: they don't even have hardware floating point.
The libc provides implementations of the trig functions that are both
quite accurate (about 24 bits of accuracy) and very slow (about
100 µs for a cos() on an Uno).
There are also situations where you do not need that level of accuracy.
So yes, custom trig functions that hit the right balance between speed
and accuracy can be helpful on Arduinos. Note that the right balance is
project specific, so there is no one-size-fits-all, and rolling your own
can make sense.
For reference, I once wrote a fixed-point cos() accurate to
9.53 × 10−5 that ran in 6.77 µs on average on
an Uno. I can provide a link if someone is interested. If you can do
better (faster at same accuracy, or more accurate at same speed) I
definitely would love to see that.

I wrote a class that generated a continuous sine wave using the spring equation (F = -kx, where x is the desired resting length of the spring), basically meaning that each sample of the sine wave (assuming a constant sampling rate and frequency) would only require two multiplications and two additions. The tradeoff for this solution is that it is continuous, you cannot call sin(1), then sin(5), then sin(3), you just sample from a sine wave of a set frequency. There are two other tradeoffs, memory for storage of the spring state, and the integration of floating point errors.

The integration of floating point errors does not have a large effect on the shape of the wave, it just means it tends to go in and out of sync with the sin function after multiple samplings. You can recalibrate the function by calling standard sine and cosine function once per recalibration. I don't not why I'm talking about this. I just wanted to talk about it. Because I'm very egotistical.

I wanted to test if this solution actually is faster than repeatedly calling something like sin(x) repeatedly to fill a buffer or something, but I appear to have misplaced the cable I need to actually program my Arduino.


text:
I have been having a lot of trouble adding a countdown to a piece of code
This is the code. The /// are where I added the countdown. Unfortunately the countdown only goes down 9 seconds. What I want it to do is go down the full 24 hours. I have been trying to fix this error for months with no luck.
int beeper_pin      = 2; //Naming buzzer pin
int resetGarden_pin = 3; //Naming the warning led pin
int pump_pin        = 6; //Naming the pump pin

#include <LiquidCrystal_I2C.h> // Driver Library for the LCD Module

LiquidCrystal_I2C lcd(0x27, A4, A5);

void clearLCDLine(int line)
{
  lcd.setCursor(0, line);
  for (int n = 0; n < 20; n++) // 20 indicates symbols in line. For 2x16 LCD write - 16
  {
    lcd.print(" ");
  }
}

void beepWarning() {            //Makes beeping a subroutine

  lcd.setCursor(0, 0);
  lcd.print("WARNING");
  delay(100);
  lcd.setCursor(0, 1);
  for (int x = 0; x < 3; x++) {

    lcd.setCursor(0, 1);
    lcd.print("WATER PUMP ACTIVE");
    delay(100);
    clearLCDLine(1);
    lcd.setCursor(0, 1);
    lcd.print("WATER PUMP ACTIVE.");
    delay(100);
    clearLCDLine(1);
    lcd.setCursor(0, 1);
    lcd.print("WATER PUMP ACTIVE..");
    delay(100);
    clearLCDLine(1);
    lcd.setCursor(0, 1);
    lcd.print("WATER PUMP ACTIVE...");
    delay(100);
    clearLCDLine(1);
  }

  lcd.setCursor(0, 1);
  lcd.print("WATER PUMP ACTIVE...");

  for (int x = 0; x < 3; x++) {   //Repeats 3 times

    digitalWrite(beeper_pin, HIGH); //Turn on buzzer
    delay(100);                     //Delay of 400 milliseconds
    digitalWrite(beeper_pin, LOW);  //Turns off buzzer
    delay(100);                     //Delay of 400 milliseconds

  }
}

void SOSWarning() {            //Makes SOS a subroutine

  clearLCDLine(1);
  lcd.setCursor(0, 0);
  lcd.print("WPA Reset Aerogarden");

  for (int x = 0; x < 3; x++) {   //Repeats 3 times

    for (int d = 0; d < 3; d++) {   //Repeats 3 times
      digitalWrite(beeper_pin, HIGH); //Turn on buzzer
      delay(200);                     //Delay of 400 milliseconds
      digitalWrite(beeper_pin, LOW);  //Turns off buzzer
      delay(200);                     //Delay of 400 milliseconds
    }

    for (int a = 0; a < 3; a++) {   //Repeats 3 times
      digitalWrite(beeper_pin, HIGH); //Turn on buzzer
      delay(400);                     //Delay of 400 milliseconds
      digitalWrite(beeper_pin, LOW);  //Turns off buzzer
      delay(400);                     //Delay of 400 milliseconds
    }

    for (int d = 0; d < 3; d++) {   //Repeats 3 times
      digitalWrite(beeper_pin, HIGH); //Turn on buzzer
      delay(200);                     //Delay of 400 milliseconds
      digitalWrite(beeper_pin, LOW);  //Turns off buzzer
      delay(200);                     //Delay of 400 milliseconds
    }

    delay(500);                     //Delay of 500 milliseconds
  }
}

void weekDelay() { //Makes waiting for a week a subroutine
  clearLCDLine(1);
  lcd.setCursor(0, 0);
  lcd.print("Waiting One Week");

long hour = 23, minute = 59, second = 59;//second //////////////////////////
long countdown_time = (hour * 3600) + (minute * 60) + second; ///////////////////////////////////////////////////////////////////////////

  long countdowntime_seconds = countdown_time - (millis() / 1000); /////////

  if (countdowntime_seconds >= 0) {   ///////////////////////////////////////////////
    long countdown_hour = countdowntime_seconds / 3600;
    long countdown_minute = ((countdowntime_seconds / 60) % 60);
    long countdown_sec = countdowntime_seconds % 60;
    lcd.setCursor(4, 1);
    if (countdown_hour < 10) {
      lcd.print("0");
    }
    lcd.print(countdown_hour);
    lcd.print(":");
    if (countdown_minute < 10) {
      lcd.print("0");
    }
    lcd.print(countdown_minute);
    lcd.print(":");
    if (countdown_sec < 10) {
      lcd.print("0");
    }
    lcd.print(countdown_sec);
  }
  delay(500);///////////////////////////////////////////////////////////////

  delay(500);

  delay(86400000);
  clearLCDLine(0);
  lcd.setCursor(0, 0);
  lcd.print("Waiting Six Days");
  delay(86400000);
  clearLCDLine(0);
  lcd.setCursor(0, 0);
  lcd.print("Waiting Five Days");
}

void pumpOn() {               //Makes turning on the pump a subroutine
  clearLCDLine(1);
  lcd.setCursor(0, 1);
  lcd.print("PUMPING");
  delay(100);
  digitalWrite(pump_pin, HIGH); //Turning on the pump
}

void pumpOff() {              //Makes turning off the pump a subroutine
  digitalWrite(pump_pin, LOW);  //Turning off the pump
  clearLCDLine(1);
  lcd.setCursor(0, 1);
  lcd.print("WATER PUMP OFF");
  delay(100);
}

void setup() {
  //run once:
  lcd.backlight();
  lcd.init();

  lcd.setCursor(4, 0);//////////////////////////////////////////////////////
  lcd.print("HH:MM:SS"); //////////////////////////////////////////////////

  lcd.clear(); // Clear the screen
  lcd.setCursor(0, 0);
  lcd.print("Aero_Pump V3");
  delay(1000);
  lcd.setCursor(0, 1);
  lcd.print("By Alex");
  delay(1000);
  pinMode (beeper_pin,      OUTPUT); //Setting outputs
  pinMode (resetGarden_pin, OUTPUT); //Setting outputs
  pinMode (pump_pin,       OUTPUT); //Setting outputs
  lcd.clear(); // Clear the screen

  digitalWrite(resetGarden_pin, LOW); //Turning off the reset garden light

  beepWarning(); //Beeps a warning
  pumpOn();      //Turns on the pump
  delay(3000);  //Adds a delay of 24000 milliseconds
  pumpOff();     //Turns off the pump
  weekDelay();   //Waits a week

  beepWarning(); //Beeps a warning
  pumpOn();      //Turns on the pump
  delay(135000);  //Adds a delay of 48000 milliseconds
  pumpOff();     //Turns off the pump
  weekDelay();   //Waits a week
}

void loop() {

  SOSWarning(); //Beeps an SOS warning
  pumpOn();      //Turns on the pump
  delay(48000);  //Adds a delay of 48000 milliseconds
  pumpOff();     //Turns off the pump

  for (int x = 0; x < 3024000; x++) {
    lcd.backlight(); // turn on backlight.
    delay(100);
    lcd.noBacklight(); // turn off backlight
    delay(100);
  }
  lcd.backlight(); // turn on backlight.
}

This is more specifically what needs to be fixed:
long hour = 23, minute = 59, second = 49;//second //////////////////////////
long countdown_time = (hour * 3600) + (minute * 60) + second; ///////////////////////////////////////////////////////////////////////////

  long countdowntime_seconds = countdown_time - (millis() / 1000); /////////

  if (countdowntime_seconds >= 0) {
    long countdown_hour = countdowntime_seconds / 3600;
    long countdown_minute = ((countdowntime_seconds / 60) % 60);
    long countdown_sec = countdowntime_seconds % 60;
    lcd.setCursor(4, 1);
    if (countdown_hour < 10) {
      lcd.print("0");
    }
    lcd.print(countdown_hour);
    lcd.print(":");
    if (countdown_minute < 10) {
      lcd.print("0");
    }
    lcd.print(countdown_minute);
    lcd.print(":");
    if (countdown_sec < 10) {
      lcd.print("0");
    }
    lcd.print(countdown_sec);
  }

This is some edited code that I have tried but might have made a mistake on because it does 0 days instead of 7 and (Hours/Min/Sec) 04:09:36.
void weekDelay() { //Makes waiting for a week a subroutine
  clearLCDLine(1);
  clearLCDLine(0);
  lcd.setCursor(0, 0);
  lcd.print("Waiting One Week");

  unsigned long start = millis();
  unsigned long week_secs = 7 * 24 * 3600;
  unsigned long countdowntime_seconds;

  while (countdowntime_seconds = week_secs - (millis() - start)/1000){
     char buff[80];
     unsigned long countdown_day = countdowntime_seconds / 3600 / 24;
     int countdown_hour = (countdowntime_seconds / 3600) % 24;
     int countdown_minute = ((countdowntime_seconds / 60) % 60);
     int countdown_sec = countdowntime_seconds % 60;
     sprintf(buff,"%1d days, %02d:%02d:%02d",
            (int) countdown_day,
            countdown_hour,
            countdown_minute,
            countdown_sec
            );
     Serial.print(buff);
     clearLCDLine(1);
     lcd.setCursor(2, 1);
     lcd.print(buff);
     delay(1000);
     }
}

You sure have a lot of delay()s in your code. Here's a simple millis based count down timer if you are interested. https://arduino.stackexchange.com/a/82217/37523

It seems like the countdown is just skipped for some reason.

I would be happy to help you. Before writing any code, it's better to write the user manual first. Can you give me a description of your project, what it does, when it does it, etc.?

Your code is in the middle of the weekDelay() function, which looks like it has several problems.  What do you expect weekDelay() to do?

The project is for an Aerogarden. It pumps water into the garden every week from information based on my collected data. It writes on the LCD information like if it is pumping, waiting (it should have the timer here), and it can show when it is going to pump with a beep warning. After beeping, pumping, and waiting for a few times I run out of information and do a loop and show a warning message, blinking the LCD and pumping a set amount.

WeekDelay() should be a delay for a week. It clears the LCD, Sets the cursor to 0,0 and prints "Waiting one week". It should then have a countdown of 24 hours on the screen and then just how many days it is waiting. It does that through clearing the LCD, Setting the cursor, printing days and waiting.

Is it supposed to wait a week? As is, weekDelay looks like it only does two day-long   delay(86400000); pauses.  You could replace lots of its code with char buff[80]; sprintf(buff,"%02d:%02d:%02d",countdowntime_hour,countdowntime_minute,countdowntime_secs); lcd.print(buff);
It also doesn't seem to have any countdown logic--From this code I see no loops in weekDelay() that could count down even 9 seconds, let alone the 604800 seconds in a week.

The answer is very good and seems to work. I do have a question though. How would I make it count down? Sorry for the extra time this will take you. I will give you the checkmark anyways for all the work you did.

I rolled back your edit because it changed the question too much.

I'd try something with a while(){} loop and a sprintf(), like:
void weekDelay() { //Makes waiting for a week a subroutine
  unsigned long start = millis();
  unsigned long week_secs = 7 * 24 * 3600;
  unsigned long countdowntime_seconds;

  while (countdowntime_seconds = week_secs - (millis() - start)/1000){
     char buff[80];
     unsigned long countdown_day = countdowntime_seconds / 3600 / 24;
     // or maybe
     //int  countdown_day = (int)(countdowntime_seconds / 3600UL / 24UL);

     int countdown_hour = (countdowntime_seconds / 3600) % 24;
     int countdown_minute = ((countdowntime_seconds / 60) % 60);
     int countdown_sec = countdowntime_seconds % 60;
     sprintf(buff,"%1d days, %02d:%02d:%02d",
            (int) countdown_day,
            countdown_hour,
            countdown_minute,
            countdown_sec
            );
     clearLCDLine(1);
     lcd.setCursor(0, 0);
     lcd.print(buff);
     delay(1000);
     }
}

Or make it more general and start it off like:
void coundownDelay(unsigned long seconds) { //Makes waiting for a week a subroutine
  unsigned long start = millis();
  unsigned long countdowntime_seconds;

  while (countdowntime_seconds = seconds - (millis() - start)/1000){

     ...

}

and call like:
  ...
  countdownDelay(7 * 24 * 3600);   //Waits a week
  ...

It is incredibly close and I thank you a lot for your contribution.

Sorry -- I had the sense of direction wrong.   I edited the math.  For debugging, you might want to try smaller delays so you can see if and where things go wrong in less than 9 hours.

Ah, it is the integer math interacting with the size of days.  04:09:36 = 43600+960+36 = 14976  which happens to be equal to  7243600 % 32768.     See https://www.gammon.com.au/forum/?id=12146 and https://wiki.sei.cmu.edu/confluence/display/c/INT35-C.+Use+correct+integer+precisions  for what's happening.   I added some casting and types to the day= line.  Alternately, one could define days as unsigned long days and then print it with sprintf(buff,"%1d days, %02lu:%02d:%02d",

I changed my code to int countdown_day =  countdowntime_seconds / 3600 / 24;   to have two divides instead of a multiply and divide.  I don't have an arduino available, so it is still untested there.  In C, the several versions worked.

That particular number, 04:09:36 is special, it is 14976 seconds, which is what a week work of seconds (7243600=604800) forced into a signed int that can only hold numbers in −32768, +32767.  This indicating problems doing the math with 16 bit ints.  Right now I can only test code bits with gcc on a Mac, where default math is done with 32 bit ints.  I added two options to the code, one doing the math with unsigned longs all the way through (and casting it to an int for the sprintf) an another attempting to keep the math in ULs and casting it into an int for storage.

I edited the code at the bottom. This had the same issue unfortunately. I firstly tried to just use the 24UL code and it said that the "countdown day" was not defined. It fixed the issue when I added both pieces of code but that might not have been what you meant when you made the code. Do you want me to define days? Also, I will check the code on a C emulator.

What emulator do you use? And what was the code you were using for it?


text:
Could I put an arduino in series with a battery charger?
recently in one of my projects I have wanted to make battery powered. I was wondering if I could connect the charger to the battery and the battery to the Arduino without blowing it. The battery is 12v 7.2 Ah and the charger is 12v 1 A.
(See attached)

Please explain in more detail what you have and what you want to do. You can also draw a schematic do be more clear.

I added the picture. Do I need something like a diode or just wire everything together like the image?

Just for clarity: your diagram shows the Arduino, the batteries, and the charger connected in parallel - which is correct for what you want to do. However, a 12v power supply (batteries, charger, or both) are at, or very close to the maximum input voltage spec the Uno. The Uno's voltage regulator has to waste - as heat - a good deal of power in reducing the voltage to 5v. And if the power supply provides any more than 12 volts, it will exceed regulator's spec.
Update:

how much do you think it would go over?

We can't know without knowing the specs on the particular batteries and charger. A battery charger has to apply a higher voltage than the present voltage of the battery it is trying to charge, in order to drive current into the battery against its (the battery's) voltage. You need to know more about the charger and the batteries.
Update 2:

The batteries are 12V 7.2 Ah and they are PK12V7.2 as the product name.

Those Lead/Acid cells. I didn't find a spec for the charger, but  in automotive use, Lead/Acids are charged at 14.2 volts. Your Uno's regulator won't like that. I'm guessing you measured your charger's output voltage with no load.
Try measuring it with the batteries attached and at low, medium, or almost fully charged. That should give you a better idea. We can only guess without the specs but it sounds like these components would be pushing your Uno's regulator pretty hard.
If these components and the Uno part of a system that requires 12v for some other components, I'd suggest using 2 power supplies, 12v for the components that need it, and 7 volts into Vin (or 5v, if well regulated, into the 5v pin) on your Uno. The lower voltage could be supplied by a buck converter powered off of the 12v, which would fairly efficient and require only one charger.

If it was 12v how much do you think it would go over? The Arduino should take 12v. Do you think there might be any other issues other than the one? The diagram is what I want with 2 batteries and the charger on for a day every two weeks.

The batteries are 12V 7.2 Ah and they are PK12V7.2 as the product name. The charger is the Motomaster 12V 1A lead acid battery charger.

The battery charger charges the batteries but is only 11-12 volts on my multimeter. Any other issues that can hurt the arduino like... something?

11-12V is much too low for charging a Lead Acid battery. This is bad for your battery and it will probably not hold a charge for long, if you do not charge it to 13.8V (at a minimum) to 14.2V or more soon. Reducing 12V down to the 5V the Arduino needs using the standard on-board linear regulator will waste most power going into the board in the form of heat. This is not only very inefficient but can also overheat the regulator. Use a (much more efficient) buck regulator to regulate the 12V down to 7V (Vin) or 5V.

Thank you. Seems like I need a regulator and a new battery charger because even with a load it stays at 12V.