text:
Counting the number of pulses in a second
For my speedometer application, I want to count the number of pulses occurring every second and convert it to speed. So for that, I need to count the number of pulses occurring at a given input pin for one second. This count is used to convert to speed. The count should go to zero and start over after every second. But I don't get how to set a limit of one second and start over every second. So far I have come up to this:
int count = 0;
float lasttime = 0;
float currenttime = 0;
const int speedpin = 52;

void setup()
{
    Serial.begin(115200);
    pinMode(speedpin, INPUT);
}

void loop()
{
    currenttime = millis();
    if (currenttime - lasttime <= 1000)
    {
        if (digitalRead(speedpin == HIGH))
        {
            count = count + 1;
        }
        else
        {
            count = count;
        }
    }
    else
    {
        count = 0;
    }
    Serial.println(count);
}

You may want to have a look at attachInterrupt(), which is often used for these things, because with this you will not miss a pulse. Then you should also read more about interrupts, so that you understand, what you are coding with it.

@chrisl It starts missing pulses much faster than using external clock source to the counter. Depends on how many mcu cycles takes to handle whole ISR.

@KIIV: if  the pulses do not bounce (as mechanical switches do), attachInterrupt() is rather convenient and the counting itself is very fast. If there are less than 256 pulses/sec to expect, handling of this byte counter in the main loop is super easy as well.

How are you planning to display the output from your speedometer application? Will you use the serial monitor, a 7 segment display module, or maybe a 16 x 2 LCD?

Right now am seeing in the serial monitor. But in the application, I will display it in an LCD screen

What type of vehicle will you be using the speedometer app on?

Actually, this is for a project on electric bikes

As already explained in Michel Keijzers' answer, instead of counting how
many times you find the input HIGH, you should count the LOW →
HIGH transitions. This requires saving the previous input state and
counting a transition only when the input is HIGH while it was LOW
last time you saw it:
static int last_pin_state = LOW;
int pin_state = digitalRead(SPEED_PIN);
if (pin_state == HIGH && last_pin_state == LOW) {  // rising edge
    count++;
}
last_pin_state = pin_state;

For displaying the count every second, use the technique explained in
the Blink without delay Arduino tutorial:
static uint32_t last_time = 0;
if (millis() - last_time >= PERIOD) {
    Serial.println(count);
    count = 0;
    last_time += PERIOD;
}

Note that you have to reset the count every time you print it.
VE7JRO suggests using interrupts. Interrupts save you the pain of
writing the edge detection. On the other hand, they also make things
slightly more complicated, because you now have to worry about
atomicity, race conditions, volatile variables and such. There is no
need to use interrupts unless the pulses are so fast (or your loop()
is so slow) that you may miss a pulse. If your loop() gets bigger and
slower, and you risk missing pulses, then interrupts can really help.
But the proper way to use them is to count the pulses in the ISR. If you
use the ISR only to rise a flag, you loose the speed advantage of the
interrupts, which is the whole point of this approach.
The interrupt service routine would then be like this:
volatile unsigned int count;

void count_pulse()
{
    count++;
}

Then, the loop only has to print and reset the count:
void loop()
{
    // Periodically print and reset the count.
    static uint32_t last_time = 0;
    if (millis() - last_time >= PERIOD) {
        noInterrupts();
        unsigned int count_copy = count;
        count = 0;
        interrupts();
        Serial.println(count_copy);
        last_time += PERIOD;
    }
}

Note that the variable count is shared between the ISR and the main
loop. That's why it has to be declared volatile. Also, its access
within loop() has to be protected within a critical section delimited
by a noInterrupts()/interrupts() pair, otherwise you would have a
race condition. Also note that, in order to keep the critical section as
short as possible, the value of count is only copied within the
critical section, and the actual printing is deferred to after the
critical section is finished.

If 'count' comes from a counter or device register, or is kept by an interrupt service routine, you don't ever want to zero the count. If a pulse arrives between the time you read the variable and the time you clear it, you will have failed to count that pulse.
Instead, make sure 'count' is of a suitable length to contain the largest number of pulses you could ever receive in one interval. Then, at each interval, save count to a temporary, say, 'tempCount'. Subtract the current 'tempCount' from the previous count, 'prevCount', in which you stored 'count' the previous time through. The difference will be the number of pulses counted in this interval. Use it or save it or whatever you need to do with it. Then store 'tempCount' into 'prevCount', and you're done.
No missed pulses, no overflow errors.

If count comes from an ISR, you can safely read it and clear it in the same critical section. Unless it's only 8 bits, you need that critical section just to read it anyway. If count comes from a hardware counter, then you are right, it should never be cleared.

Yes, if done in a critical section. But if background (ISR) code is collecting pulses and foreground code is calculating the counts, there would still be an opportunity for errors. Using a continuous counter (and it's only 1 byte wide), you could avoid the need to turn off interrupts again.

First align your code:
int count = 0;
float lasttime = 0;
float currenttime = 0;
const int speedpin = 52;

void setup()
{
  Serial.begin(115200);
  // put your setup code here, to run once:
  pinMode(speedpin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  currenttime = millis();
  if(currenttime - lasttime <= 1000)
  {
    if (digitalRead(speedpin == HIGH))
    {
      count = count + 1;
    }
    else
    {
      count=count;
    }
  }
  else
  {
    count=0;
  }
  Serial.println(count);
}

Than the statement count = count assigns a variable to itself which is not needed, and for increment you can use count++, so you get:
int count = 0;
float lasttime = 0;
float currenttime = 0;
const int speedpin = 52;

void setup()
{
  Serial.begin(115200);
  // put your setup code here, to run once:
  pinMode(speedpin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  currenttime = millis();
  if(currenttime - lasttime <= 1000)
  {
    if (digitalRead(speedpin == HIGH))
    {
      count++;
    }
  }
  else
  {
    count = 0;
  }
  Serial.println(count);
}

In the loop, you do not count pulses, but only the measurements where a pin is HIGH and when the pin is LOW anywhere within the second, it is set to 0.
What you instead want to do is (assuming you want to count the LOW -> HIGH transients: Make a global variable called e.g. previousState. Now, if the previousState == LOW and the current state of the GPIO is HIGH, only than increase count with one. Also, within the loop, each time update the previousState with the current state.
I leave the implementation to yourself.

But for one second I have to count the pulse. And after that one second is over count should go to zero and start counting again. Thus I need the number of pulses for each second.

Than you store after one second the number of measured pulses (count) in a separate variable to be processed in the next second (while count already measures the new pulses for that second).


text:
Is it possible to send 2 or more o/p signal at the same time?
I wanted run two motors using Cytron MDD10A Dual Channel motor driver. So my concern is based on execution of code that is done line by line, in that case when I'm driving two motors will this delay in output signal at the PWM pins make a difference in nature of performance i.e. for example a car wheel, in case there is such delay it'll cause one wheel to rotate prior to another which is not desired. If yes, how do I rectify the same.
I also wanted to know when I use the delay function does it cause the delay in execution of the previous line or reads the upcoming line upon some 'x' seconds of delay?
Thank you for your help.
edit: code sample:
void FWD() {       // to move forward
    digitalWrite(m1, HIGH);  // motor 1 ON
    digitalWrite(m2, HIGH);  // motor 2 ON
    analogWrite(tm1, 225);   // tm1 assigned to a PWM pin
    analogWrite(tm2, 225);   // tm2 assigned to another PWM pin
}

in the above function I wish to run both analogWrite at the same time as I'm not sure how will it affect the output? I wish for the motors to start at the same time.

What is an O/P signal?

sorry, output signal. I wish to send two PWM signal at the same time to two different PWM pins.

you would have to post your code so we can fully understand what your talking about. But in general PWM signal are generated via timers and underlying hardware, so you can have multiple running at the same time.  A delay call will pause on its line. It will have already completed the previous line.

code sample:
void FWD(){
//to move forward
digitalWrite(m1, HIGH);//motor 1 ON
digitalWrite(m2,HIGH);//motor 2 ON
analogWrite(tm1,225);// tm1 assigned to a PWM pin
analogWrite(tm2,225;)//tm2 assigned to another PWM pin
}
in the above function I wish to run both analogWrite at the same time as I'm not sure how will it affect the output? I wish for the motors to start at the same time.

Arduino's(and any other device with a  single core processor) can only do one thing at a time. But you will not be able to tell which motor starts. The analog write function does not wait for the motor to do anything, it simply sets timers and interrupts to handle this. You should study the "Blink without Delay" example to understand how to do multiple things "at the same time".  Both motors will start at the same time.

Thank you @ChadG :)

@ChadG: No interrupts are involved in analogWrite().

@EdgarBonet not directly, but timers used by PWM are interrupt driven.

@ChadG: No, they are not. TIMER0_OVF is used for internal timekeeping, but this is unrelated to the PWM. The Arduino core does not enable any other timer interrupt, unless you use Tone, Servo, or another timer-dependent library.

how much delay do you think there is between the motor startups with the code you posted? ... also, do you think that two motors actually start up at the same time if connected together?

Technically, it is possible to start two PWM outputs at the exact same
time on an Uno or Nano. If they are both controlled by the same timer,
you just have to update the corresponding control register once with
the relevant bits set to enable both channels. For example, you could
start outputs 5 and 6 simultaneously, as both are on Timer 0:
OCR0A   = value;  // set the duty cycle on OC0A = digital 6
OCR0B   = value;  // set the duty cycle on OC0B = digital 5
TCCR0A |= _BV(COM0A1) | _BV(COM0B1);  // enable both outputs

If the outputs are on different timers, it is a bit more tricky. Timers
0 and 1 can be synchronized by clearing their shared prescaler with the
Timer/Counter Synchronization mode active. I do not think there is a
simple way to synchronize Timer 2 with any of the others.
All this is highly hardware-dependent, and not supported at all by the
Arduino core library. Thus, if you want to apply any of this, you will
have to study the datasheet, and poke directly into the I/O
registers of the microcontroller.
But then, as Delta_G clearly points out in his answer, all this is
irrelevant to motor control. Motors are mechanical devices that have
significant inertia. They take time to speed up and slow down. Just to
give you a sense of scale, PWM outputs 3, 9, 10 and 11 deliver a square
wave with a period of 2.04 ms. Yes, those are milliseconds, and
this is too short for the motors to significantly change their speed
within one period. Contrast this with the handful of microseconds,
that the call to analogWrite() will take.

I don’t think your fear is founded.  Yes technically one motor starts after the other but the amount of time would be a few microseconds at most.   For perspective it takes you about 200,000 microseconds to blink your eye.  You will not be able to tell.  They will appear to start at exactly the same time.  You would need some very sophisticated high speed cameras to see the difference in timing.  It wouldn’t affect how your car moves.

source: Stack Exchange

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

sort: votes


text:
Doing several things at the same time with functions, objects or interrupts?
First of all, thank you for taking the time to read this. I am a newbie, so apologies (done examples on arduino website, basic C++).
I'm trying to get an idea of what the best way to structure a sketch is, which needs to do several things at the same time. For example, reading an IMU sensor and using it to control the mouse, reading a button for on/off and let's say flashing an LED. I have repetitive injury so this is the project I'm trying to complete, but the principle should be scalable for more complex projects.
I've come across some great resources and my understanding is you can use:

functions (e.g. blink without delay)

objects (cooperative multitasking)

interrupts

something like a RTOS

Where my limits lie is understanding the benefits/limitations of these options and picking which one to focus on for my project. For example, if using functions is sufficient, why do people bother with interrupts and installing a RTOS?
I would appreciate any guidance for what an effective approach should look like.
Thanks again.

Functions and objects have nothing to do with “doing several things at the same time”, they are just ways to encapsulate some logic. In both cases you are doing non-blocking programming. The most useful programming paradigm for non-blocking programming is the finite state machine.

Please read up about the concept of "real time". This does not mean that something is fast, it just means it is fast enough (based on whatever standards you apply). For instance, if your blinking led has a skew of a few milliseconds, you won't notice - it is irrelevant.

Thanks for the link, I'm going through it today.

as long as you follow the examples, and non of your code uses delay(), it should naturally do many things at once, CPU time and memory allowing. For what you describe, it's hard to imagine even an UNO not being up to task.

Thank you Davis for the comment

An RTOS may be a good option for running a complex application on a
quite powerful Arduino. Many Arduinos (the AVR-based ones), however, are
too limited to run complex applications, and the overhead of an RTOS is
quite significant for them. In this case you end up with two options:

non-blocking programming
interrupts

Whichever is best depends on the specific tasks you are managing.
Non-blocking programming
This is best exemplified by the Blink Without Delay Arduino
tutorial. The general principle is to break down you code into small
non-blocking tasks, and perform each one only when it is the right time
to do so. Breaking down the program logic into a set of non-blocking
tasks is not always completely trivial, but you can use a Finite state
machine, which is a very powerful and general concept for doing so
in a systematic way.
Once all task are non-blocking, the main program loop then looks like
this pseudo-code:
void loop() {
    if (task_1_should_be_performed_now()) {
        perform_task_1();
    }
    if (task_2_should_be_performed_now()) {
        perform_task_2();
    }
    // etc...
}

Most of the time, all conditions are false, and the program swifts
through the tests completing the loop in a very short time.
Occasionally, it performs one of the tasks, which makes the loop longer
but, since the tasks never block, not very long anyway. Typical loop
time is highly dependent on the specifics of your code, but I would
expect it to be no more than one millisecond most of the time.
This is probably the most common pattern for multitasking on the
Arduino. You can encapsulate this logic in functions, objects,
libraries, etc. This is the approach I would recommend provided none of
your tasks is so urgent that it cannot wait for one loop iteration.
Interrupts
Occasionally, you may have a task that is so urgent that it cannot wait
for the next loop iteration. It has to be performed right now. Or maybe
the loop takes a very long time because of a blocking call in a library
you have no control over. In those situations, an interrupt may be the
best option.
Interrupts come with some tricky programming issues, which require some
precautions on the part of the programmer:

they block other interrupts, increasing their latency → interrupt
service routines should be as short as possible

they can cause problems with non-reentrant library functions → those
functions should be avoided in interrupt context

they can interact badly with the optimizer → variables used in both
interrupt context and normal context should be qualified as
volatile

they can cause synchronization issues with the data shared with the
main code → access to that data in normal context should be protected
in critical sections.

For all these reasons, it is best to use interrupts only when needed,
i.e. only when a task cannot wait for the next iteration of loop().

Hi Edgar, I really appreciate you taking the time and effort to respond in such a helpful way. I'll follow the link and take the rest of the day to absorb the content. Thank you very much. Just to confirm a couple of quick points. You're implying that from a multitasking perspective it makes no difference whether I encapsulate the code in functions or objects? What would be an example of a task which cannot wait for a loop iteration? Would a press of a button to perform an action such as switching analog sensor read on/off qualify?

if i may; streaming audio, some wifi interactions, capturing hi-rate ADC samples, etc. Look into interrupts, which are basically events that can cut in line for real-time handling of stuff like button presses. Your analog sensor doesn't mind waiting a ms to take another sample.

@ZhelyazkoGrudov: 1. An object is just a convenient way to encapsulate functions (called methods) together with data. The right level of encapsulation can help make your code cleaner and easier to maintain, but it has no relevance vs. the multitasking approach. 2. For detecting a button press, you may need to use interrupts if the button is going to be operated by Quicksilver. If the operator is a regular human, a millisecond or two of latency makes no difference.

Such a good answer! Maybe I am designing a project for the avengers, you never know... In all seriousness, thanks for the explanation.

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


text:
Interfacing MAX6675 with Arduino Mega 2560
I'm trying to use a thermocouple k type and a MAX6675 IC.  I bought the MAX6675 chip and made the circuit (just a 1 nf capacitor on +5 V and GND near the IC) with the help of the datasheet
I used the library from adafruit and for the sake of avoiding errors, I used the Example from the same library (serialThermocouple) with 52 as CLK, pin 50 as SDO and pin 53 as CS.
The program is producing numbers and the sensor appears to stabilize around 104.0C and 105.0C, but why? that is not the real temp or even close to it? Is there any other conversion to get the real degree around me?
oh !! and Another question..
Why is the 8 bit shift here?

  v = spiread();
  v <<= 8;
  v |= spiread();

I saw it in many code. Also this one
digitalWrite(_ssPin, LOW);
tcData = SPI.transfer(0x00)<<8;
tcData |= SPI.transfer(0x00);
digitalWrite(_ssPin, HIGH);
temp = (tcData>>3)/4.0;

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


text:
ESP8266 GET method error
I am working on ESP8266 and I want to send a GET request with AT command to my localhost but I failed every time. Can you help me solve this problem please? Thank you for interest!
I attached my terminal code and my code:

#define ag_ismi "SUPERONLINE_WiFi_8022"
#define ag_sifresi "rC5YGNYebuCf"
#define IP "192.168.1.9"

void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  Serial.println("AT");
  delay(3000);
  if(Serial.find("OK")){
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String baglantiKomutu=String("AT+CWJAP=\"")+ag_ismi+"\",\""+ag_sifresi+"\"";
    Serial.println(baglantiKomutu);
    delay(5000);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(60000);
  Serial.println("AT+CIPMUX=1");
  Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.9\",8000");
  delay(1000);
  String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1";
  //model+="Host: 192.168.1.9:8000\r\n\r\n";
  model+="r\n\r\n";
  Serial.println("AT+CIPSEND=" + String(model.length()));
  Serial.println("\r\n\r\n");
  delay(1000);
  Serial.println(model);
  Serial.println("\r\n\r\n");
  delay(1000);
  Serial.println("");
}

problem is, that you connected the esp8266 to Serial. now your Serial debug prints go to esp8266 and disturb it. use SoftwareSerial

It should be
String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1\r\n";
model+="Host: 192.168.1.9\r\n\r\n";

remove Serial.println("\r\n\r\n"); before Serial.println(model); it is send before GET line
Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.9\",8000");
String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1\r\n";
model+= "Host: 192.168.1.9\r\n\r\n";
Serial.print("AT+CIPSEND=");
Serial.println(model.length());
delay(1000);
Serial.print(model);
delay(1000);

EDIT:
Remove debug prints to Serial or use SoftwareSerial to connect the esp8266 to Uno. Now the debug prints are sent to esp8266 mixed with AT commands and data. For SoftwareSerial change the default baud rate of the AT firmware.

I tried this code but its also not working. when I run GET /kanbanDB/arduino?model=1 HTTP/1.1 code, if I send first time wifi module waiting 30 second and send requets but second time I run this code it failed. that failure is about power supply ?

how do you power it?

I used arduino with USB power


text:
lightshow project

Hello guys. I'm working on a little lightshow that has 3 extra feature's when i press the button. depending on the variable counter the lights should do something and it should message you that you found a feature. But my project does'nt work. it compiles fine on the tinkercad site but not everything works. The lights itself work but the button feature's dont. I don't know if my code is wrong or the wiring since its able to compile.
I expected that if i press the countbutton it counts up and when it reaches 6 it does the code in the if statement. However when i press the count up and or count down button according to the variable it needs to reach it doesn't do anything.
the code:
int time = 250;
int ledpins[] = {3, 6, 7, 4, 2, 5};
int amount = 6;
int countup = 11;
int countdown = 12;
int counter;
int timepressed = 4000;
float timerpressed = 0;

void setup()
{
  for (int pin = 0; pin < aantal; pin++)
    {pinMode(ledpins[pin], OUTPUT);}
   //alle leds worden door middel van de loop gedefinieerd als output
   //pin is eerst 0 dat is element 3 in de array. de counter heeft einde
   //nog niet en gaat verder tot de conditie bereikt is
   pinMode(countdown, INPUT_PULLUP);
  pinMode(countup, INPUT);
   Serial.begin(9600);
}

void loop()
{
  bool plus = digitalRead(countup);
  bool minus = digitalRead(countdown);
  delay(20);

  if (plus == LOW){
    counter++;
   if (counter > 10) counter = 0;
  }

  if (minus == LOW){
    counter--;
  }

//Easter egg nummer 1. 2 lights on.
if (counter == -2){
    digitalWrite(ledpins[1], HIGH);
    digitalWrite(ledpins[4], HIGH);
    Serial.print("Gefeliciteerd je hebt (1/3) easter egg gevonden!");
}
//Easter egg nummer 2. all lights off.
else if (counter == 6){
  digitalWrite(ledpins[0], LOW);
  digitalWrite(ledpins[1], LOW);
  digitalWrite(ledpins[2], LOW);
  digitalWrite(ledpins[3], LOW);
  digitalWrite(ledpins[4], LOW);
  digitalWrite(ledpins[5], LOW);
  Serial.print("Gefeliciteerd je hebt (2/3) easter egg gevonden!");
}
//Easter egg nummer 3. blink alternately after keeping the button pressed for 4 seconds.
else if (timerpressed >= timepressed){
  digitalWrite(ledpins[0], HIGH);
  digitalWrite(ledpins[1], HIGH);
  digitalWrite(ledpins[4], HIGH);
  digitalWrite(ledpins[5], HIGH);
  Serial.print("Gefeliciteerd je hebt (3/3) easter egg gevonden!");
 }

Okay an update on this post is a was able to make a couple of fixes. My code was keep getting stuck in the array loop for the leds. I've made it that it now only goes trough it once. Another thing i fixed was the wiring of the buttons since this wasnt correct. The only feature that isnt working right now is the keep the button pressed feature.

int tijd = 250;
int ledpins[] = {3, 6, 7, 4, 2, 5};
int aantal = 6;
int knopplus = 11;
int knopmin = 12;
int teller;
int indruktijd = 4000;
float timerdruktijd = 0;
int pin = 0;
int pin1 = 0;

void setup()
{
  for (int pin = 0; pin < aantal; pin++)
    {pinMode(ledpins[pin], OUTPUT);}
   //alle leds worden door middel van de loop gedefinieerd als output
   //pin is eerst 0 dat is element 3 in de array. de counter heeft einde
   //nog niet en gaat verder tot de conditie bereikt is
   pinMode(knopmin, INPUT_PULLUP);
  pinMode(knopplus, INPUT);
   Serial.begin(9600);
}

void loop()
{
  bool plus = digitalRead(knopplus);
  bool minus = digitalRead(knopmin);
  delay(20);

  if (plus == LOW){
    teller++;
   if (teller > 10) teller = 0;
  }

  if (minus == LOW){
    teller--;
  }

//Easter egg nummer 1. twee lichten aan.
if (teller == -2){
    digitalWrite(ledpins[1], HIGH);
    digitalWrite(ledpins[4], HIGH);
    Serial.print("Gefeliciteerd je hebt (1/3) easter egg gevonden!");
}
//Easter egg nummer 2. alle lichten uit.
else if (teller == 6){
  digitalWrite(ledpins[0], LOW);
  digitalWrite(ledpins[1], LOW);
  digitalWrite(ledpins[2], LOW);
  digitalWrite(ledpins[3], LOW);
  digitalWrite(ledpins[4], LOW);
  digitalWrite(ledpins[5], LOW);
  Serial.print("Gefeliciteerd je hebt (2/3) easter egg gevonden!");
}
//Easter egg nummer 3. knipper om en om na 4 seconden lang de -knop ingedrukt te houden
else if (timerdruktijd >= indruktijd){
  digitalWrite(ledpins[0], HIGH);
  digitalWrite(ledpins[1], HIGH);
  digitalWrite(ledpins[4], HIGH);
  digitalWrite(ledpins[5], HIGH);
  Serial.print("Gefeliciteerd je hebt (3/3) easter egg gevonden!");
 }

  for (pin; pin < 6; pin++)
  {digitalWrite(ledpins[pin], HIGH);
   delay(tijd);
   digitalWrite(ledpins[pin], LOW);}
  //loop voor volgorde heen.

  for (pin1; pin1 < 6; pin1++)
  {digitalWrite(ledpins[pin], HIGH);
   delay(tijd);
   digitalWrite(ledpins[pin], LOW);}
  //loop zelfde volgorde terug
}

"It doesn't work" is a poor problem description. We have to search your code for the possible problem and that get's way easier, when you give us a good description of the problem. So please answer the questions: What is actually happening depending on your actions? What did you expect to happen instead?

I agree with chrisl; however one problem I see is that you need to debounce the buttons, see https://www.arduino.cc/en/Tutorial/Debounce   … also try to write your comments and variable names in English, not Dutch (I understand since I'm Dutch too, but most people will not).

thank you guys for the comments. I changed it according to you guys feedback.

Can you also give us a sample of the Serial output (if there is any)?

Why do you have one button with internal pullup but the other not?

I have no serial output :/, and i have one button with the pullup because i was searching for a sketch to make a pressed button function. I tested the sketch itself and it was working so i tought merging it together with this project then it should work aswell.

One button has no connection to ground. Check that purple wire second from the right on the top half of the breadboard...

At which point in the program do you update timerdruktijd if the button you mean is pressed (which of the buttons should even be pressed to activate this)?


text:
Compile code error: 'Serial' does not name a type

int LDR_deger = 0;

int Ledpin1 = 12;
int Ledpin2 = 11;
int Ledpin3 = 10;
int Ledpin4 = 9;
int Ledpin5 = 8;

int LDR_pin = 0;

void setup()
{

  Serial.begin(9600);
  pinMode(Ledpin1, OUTPUT);
  pinMode(Ledpin2, OUTPUT);
  pinMode(Ledpin3, OUTPUT);
  pinMode(Ledpin4, OUTPUT);
  pinMode(Ledpin5, OUTPUT);
}
void loop()

{
  LDR_deger = analogRead(LDR_pin);
digitalWrite(Ledpin1,HIGH);
digitalWrite(Ledpin2,HIGH);
digitalWrite(Ledpin3,HIGH);
digitalWrite(Ledpin4,HIGH);
digitalWrite(Ledpin5,HIGH);

if (LDR_deger <= 80 && LDR_deger> 30) {
  digitalWrite(Ledpin1, LOW);
} else{
  digitalWrite(Ledpin1, HIGH);
  if (LDR_deger<= 150 && LDR_deger > 80){
  digitalWrite(Ledpin2, LOW);
  digitalWrite(Ledpin1, LOW);
  }else{
    digitalWrite(Ledpin1, HIGH);
    digitalWrite(Ledpin2, HIGH);
    if (LDR_deger  <= 200 && LDR_deger> 150){
      digitalWrite(Ledpin2, LOW);
      digitalWrite(Ledpin1, LOW);
      digitalWrite(Ledpin3, LOW);
     }else{
      digitalWrite(Ledpin1, HIGH);
      digitalWrite(Ledpin2, HIGH);
      digitalWrite(Ledpin3, HIGH);
      if (LDR_deger <= 1000 && LDR_deger> 300){
      digitalWrite(Ledpin2, LOW);
      digitalWrite(Ledpin1, LOW);
      digitalWrite(Ledpin3, LOW);
      digitalWrite(Ledpin4, LOW);
      digitalWrite(Ledpin5, LOW);
     }else{
      digitalWrite(Ledpin1, HIGH);
      digitalWrite(Ledpin2, HIGH);
      digitalWrite(Ledpin3, HIGH);
      digitalWrite(Ledpin4, HIGH);
      digitalWrite(Ledpin5, HIGH);
     }
       }
     }
   }
  }
Serial.print("LDR Deger: ");
Serial.print(LDR_deger);
Serial.println(" ");
delay(500);
}

Don't simply post code and expect us to guess what is the problem.  Also give some explanation of what you have tried

One reason you are receiving the compile error, is due to the code outside of a function. When you write nice, neat, properly formatted code, these errors are easy to spot. The Arduino IDE has a built in feature that will "highlight" a matching curly bracket (or curly brace?).

Maybe the Auto Format (CTRL+T) feature should be mentioned too. It gets so obvious after using it.

VE7JRO already has answered your question. Below is not an answer to the question but a better way to program something like you have.
In your case, you need to set 5 pins according. I assume the following lines are just for initialization (and not needed when you set them afterwards to FALSE), as I do not see any delay.
digitalWrite(Ledpin1,HIGH);
digitalWrite(Ledpin2,HIGH);
digitalWrite(Ledpin3,HIGH);
digitalWrite(Ledpin4,HIGH);
digitalWrite(Ledpin5,HIGH);

It is much easier for each pin to set the conditions direction; this will reduce all the if statements and make it very clear for each pin what the value should be.
First we make some variables to prevent duplication. Actually I normally like using bool but it is not a predefined type. Also I like to have the low range on the left and the high range on the right, and using parenthesis. I added the range 200-300, and lower/upper range:
int LDR_deger_min_inf_30 =  (LDR_deger <= 30);
int LDR_deger_30_80      = ((LDR_deger >  30) && (LDR_deger <=   80));
int LDR_deger_80_150     = ((LDR_deger >  80) && (LDR_deger <=  150));
int LDR_deger_150_200    = ((LDR_deger > 150) && (LDR_deger <=  200));
int LDR_deger_200_300    = ((LDR_deger > 200) && (LDR_deger <=  300));
int LDR_deger_300_1000   = ((LDR_deger > 300) && (LDR_deger <= 1000));
int LDR_deger_1000_inf   =  (LDR_deger > 1000);

Now you can create a table for each pin (which makes great documentation and a clear overview); I would add it in a comment (if you have no other documentation way):
// pin min_inf_30 30_80 80_150 150_200 200_300 300_1000 1000_inf
//  1     HIGH     LOW    LOW     LOW   HIGH      LOW     HIGH
//  2     .. (fill in yourself)
//  3     .. (fill in yourself)
//  4     .. (fill in yourself)
//  5     .. (fill in yourself)

Now you can write the pins one by one (I only did the first as example):
digitalWrite(Ledpin1, LDR_deger_min_inf || LDR_deger_200_300 || LDR_deger_1000_inf ? HIGH : LOW);
digitalWrite(Ledpin2, …);


text:
Trying to understand how to make a program do three things with a button press
I am trying to write some code, which I barely grasp - but it's coming along! But I think I've hit a wall that I could using some help getting  over...
I'm not asking for you to fix my code - I know that's not how I am going to learn, maybe explain why my code isn't doing what I want it to, and/or some resources I can using to learn about it.
I think it has something to do with me trying to use the same pins in the initialization part since the error is about a conflicting declaration..
Here's my breadboard layout if this helps too:

//ABOUT - This programs goal is to make a button cycle through three    different 'modes'
//Mode 1 - make a RGB LED cycle through its colors
//Mode 2 - make the same RGB LED fade-cycle through its colors
//Mode 3 - make the same RGB LED blink on-off all three colors at once
//Additional modes may follow but this is the beginning.

//currently all my initialization code is from three different programs and I think that's why parts are not working.. I think
//I can share the mode initialization code for each mode....?  But the face code uses the uint8_t vs just int so maybe not?

//Button Cycle - this is the first part of my code, designed to teacah me how to make a button cycle through to different parts of the code

int counter = 0;
int switchPin = 13;
int LEDB = 11;
int LEDG = 10;
int LEDR = 9;

//RGB LED Cycle Circuit - mode 1
const int redLED=3; //red LED connects to digital pin 8
const int blueLED=5; //blue LED connected to digital pin 7
const int greenLED=6; //green LED connected to dogotal pin 6

//RGB LED Fade Circuit - mode 2
const uint8_t redLED = 3;  // pin connected to the red LED - I don't understand why this code says const uint8_t  -
const uint8_t blueLED = 5;  // pin connected to the green LED
const uint8_t greenLED = 6; // pin connected to the yellow LED

void setup()
{
  Serial.begin(9600); //I added this to help learn what the counter was doing
  pinMode(switchPin, INPUT);
  pinMode(LEDR, OUTPUT);
  pinMode(LEDG, OUTPUT);
  pinMode(LEDB, OUTPUT);
}

void loop() {
  //Handle input
  int switchVal = digitalRead(switchPin);
  if(switchVal == LOW) //changed from HIGH which was making the modes appear to change randomly - may come in useful later but not what I want initially
  {
    delay(500);
    counter ++;
    Serial.println(counter); //prints value of counter to serial monitor so I can see why it appeared to be random
    //I learned that when the switchVal == HIGH was in place the counter would cycle continuously. Making each button
    //press appear random. Changing this to LOW made the counter wait for a LOW event before counting. Increasing the
    //delay to half a sec gives time to release the button before the counter continues.

    //Reset count if over max mode number
    if(counter > 3)
    {
      counter = 1; //in serial monitor you will see that the counter goes to 4 but this code tells the program that 4 = 1 so it runs the right mode
    }
  }
  else
    //Change mode 1
    switch (counter) {
    case 1:
      analogWrite(LEDB, 000);
      analogWrite(LEDG, 000);
      analogWrite(LEDR, 255);

      //start LED Cycle - this is simply pasted in from the LED cycle program - seems to work fine

      digitalWrite(redLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(redLED,LOW);//turns the LED off
      digitalWrite(greenLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(greenLED,LOW);//turns the LED off
      digitalWrite(blueLED,HIGH);//turns the LED on
      delay(100);//waits 3 seconds
      digitalWrite(blueLED,LOW);//turns the LED off
      break;

    //mode 2 code
    case 2:
      analogWrite(LEDR, 000);
      analogWrite(LEDB, 000);
      analogWrite(LEDG, 255);

      //LED Fade Cycle
      // Fade an analog pin up and down.
      void fade(uint8_t pin);
      {
        for (int i = 1; i <= 255; i=i+5) {
          delay(10);
        }
        for (int i = 254; i >= 0; i=i-5) {
          delay(10);
        }
      }
      //void loop(); - think I can only have one void loop so I'm commenting this out for now..
      {
        //Serial.println(F("Fading GREEN."));
        fade(redLED);
        //Serial.println(F("Fading BLUE."));
        fade(blueLED);
        //Serial.println(F("Fading YELLOW."));
        fade(greenLED);
      }
      break;

    //mode 3 not coded yet - waiting to make mode 2 work
    case 3:
      analogWrite(LEDG, 000);
      analogWrite(LEDR, 000);
      analogWrite(LEDB, 255);
      break;
    }
}

Change the title to a more specific question.  What exactly about the code do you not understand?

There are two immediate things I can see wrong:

You have two sets of the same pin definitions. You only want one set. Both sets are identical - once it's defined its defined - you can't define it again as the same thing.
You seem to have a function defined in the middle of your loop() function.  That can't work - functions have to be separate things. (also you don't want a ; in your function definition...)

I think what you are missing is a pulldown resistor for the button. Simply put, a pulldown resistor is a resistor pulls down the input reading to 0 when the button is not pressed. Without the pulldown resistor, the value read in the digitalRead will float around giving inaccurate results.

Above is a circuit showing how the pulldown resistor should be wired with a button.
If you would like to learn more about pulldown resistors, please refer to this page describing buttons in the Arduino Website.
This is just a hardware issue I noticed; hopefully, this will help you out in addition to the other recommendations given.
As a side note, a pull-up resistor can also be used, and in this case, the value will be 1 when the button is not pressed.

You've used the blue lower rail for Ground but used the red lower rail (usually used for +5v) as a simple connection point. It's not wrong but it's unusual enough to be confusing to readers. The choice of red  button-signal wire on the red rail also strongly suggest a connection to +5v even though that is not the case here.
The buttons, "tact" switches, are confusing by design (see picture below). Each pair of pins curved toward each other (I marked one with a red arrow) are the physically same pin and always connected to each other. The pairs are connected to each other only when the button is pressed. It's really easy to miss that and insert the button 90deg either way from what you intended. Fritzing's button icon doesn't show the orientation either. Yours may well be correct - it's just a pitfall to be aware of.

void fade(uint8_t pin); doesn't define a function - it declares that one exists somewhere else. I think you meant void fade(uint8_t pin){ ... } (note no semi-colon), which would define the function, if that were a proper location to do so. But in C and C++, functions may not be defined within other functions (loop(), in this case). Fix the definition of 'fade' and move it to above 'setup()'. That will properly define it and make it usable from within the loop() function.
The braces, {}, where you tried to define a second loop function are unnecessary (and, you're correct, you can't define more than one function with the same name and signature (parameter count & types, and return type). But you don't need another loop(); the code contained in the {} - three calls to the fade function - remain part of case 2:.


text:
Invoke a method in the main sketch from within a library
I need to use a specific library that issues error messages in the form of String texts. The library uses the Serial.println() function to send the messages to the Arduino IDE's serial monitor.
The problem is that I have the Serial lines from the Arduino linked to another device, therefore I can't use the Serial Monitor to see the messages. I have a method in the Main Arduino sketch that sends any String text msg generated to another device using Udp commands (wireless). This device is connected to a serial monitor unit.
My question is: How can I invoke the Udp method inside the main sketch of the Arduino program from within the aforementioned library? This would help me to convert the Serial.print() text messages from the library directly into Udp messages to be able to visualize them.
The Udp method I'm using is declared as void UdpSend(String msg) in the Arduino sketch. I'd like to use something similar inside the library to wrap the text msg and send it over to the method on the main program.
Any example or link to get this information will help.
EDIT1:
@Majenko,

On the target library, added:  void libUdpSend(const char *libMsg);
On the sketch, I added this method (Udp comm handler):
 void libUdpSend(const char *libMsg)
 {
   Udp.begin(localPort);
   Udp.beginPacket(Udp.remoteIP(), localPort);
   Udp.write(libMsg);
   Udp.endPacket();
   delay(40);
 }

Added this line on the library (right after the declaration on 1.) to test through the remote serial interface:
libUdpSend("String wrapper has been implemented SUCCESSFULLY!");

When trying to compile linking the library, the following exception occurrs:

error: expected constructor, destructor, or type conversion before '(' token
  libUdpSend("String wrapper has been implemented SUCCESSFULLY!");

I then switched to String as this is the type I want to wrap, Same steps:

On the target library, added:  void libUdpSend(String *libMsg);
On the sketch:
void libUdpSend(String *libMsg)
{
  Udp.begin(localPort);
  Udp.beginPacket(Udp.remoteIP(), localPort);
  Udp.write(libMsg.c_str());
  Udp.endPacket();
  delay(40);
}

Now the error message says:

request for member 'c_str' in 'libMsg', which is of pointer type 'String*' (maybe you meant to use '->' ?)

I am not an expert on pointers so I'd need some help on how to assign the pointer as argument on the UdpWrite function using the '->' command proposed by the compliler?
Let me know your thoughts on this.

I have a simple library for debug messages over Telnet https://github.com/jandrassy/TelnetStream . it creates an instance which can be used instead of Serial in any source file which includes TelnetStream.h

send a bug report to the lib creators and say that hardcoding serial for debug output is the wrong thing to do.

The connection between a sketch and a library is not one-way as many suppose.  Things can go quite happily in both directions.
What you are proposing is something I do quite often when developing a library and I need to get some debugging information out of the library. Yes, it's possible to directly use Serial in the library, but that's something I don't like, and often isn't appropriate anyway, as in your situation.
However, doing it the way you propose (and I use) is actually very simple.
You just make your function in your sketch and tell the library to use it.
For example, in your sketch:
void debug(const char *msg) {
    Serial3.println(msg);
}

And in the library add the line:
void debug(const char *msg);

Then at any point in the same file (or translation unit) you can use
debug("I am here");

That is assuming that the file that you are using it in is a C++ file (.cpp).  If it's a C file (.c) then you have to treat things very slightly differently.  You see, C++ makes a mess of the function names (even vanilla functions like that) which means they can't be seen by C files.  So you have to tell the compiler "I'd like this to be usable in a C file, please".
Which you do with a special "extern" wrapper around your function:
extern "C" {
    void debug(const char *msg) {
        Serial3.println(msg);
    }
}

And then debug() is usable in a C file in the same way as above.
However now it won't work in a C++ file...  (round and round we go...)
Simple to fix: add the extern "C" to the prototype in the C++ file:
extern "C" {
    void debug(const char *msg);
}

If you want to include your "extern" in a header file that could be included into either C or C++ files it's very common to use a construct such as:
#if defined(__cplusplus)
extern "C" {
#endif

void debug(const char *msg);

#if defined(__cplusplus)
}
#endif

That will add the extern "C" wrapper for C++ files (identified by the presence of the macro __cplusplus) but omit it for C files.
I have used "const char *" as the parameter for this example, but you can choose whatever parameters are appropriate for your usage.

@ Majenko - thx for your answer. I implemented the solution as you proposed it but the compiler is throwing an error generated on the modified library.
error: expected constructor, destructor, or type conversion before '(' token

 libUdpSend("String wrapper has been implemented SUCCESSFULLY!");

I tried to put the code here but the comment section has very limited size. I might send you a bit more of the info via email perhaps?.  Any ideas on something in the code I might be missing?  The target library is .cpp btw, so no extern C structure needed.
Thanks -EZ

Just edit your question and add it there.

See "EDIT 1" in the original question. Thanks!


text:
Arduino DC motor with 2 buttons
I have a problem with my Arduino project and I tried everything to fix it but nothing helps.
I am trying to rotate my DC motor with two buttons:

one button is to stop/start rotating on left side, and;
the second one is for stop/start rotating on the right side.

I can't switch the states and if the motor is rotating I can't stop it. The speed is controlled by the potentiometer and works fine, just the buttons are the problem. I hope somebody can help me.
int enablePin = 11;
int in1Pin = 10;
int in2Pin = 9;
int switchPin = 7;
int switchPin1 = 6;
int potPin = 0;
int statusPin= 13;
boolean status;

void setup()
{
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(enablePin, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
  pinMode(switchPin1, INPUT_PULLUP);

  pinMode(statusPin,OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(13,HIGH);

  int speed = analogRead(potPin) / 4;

  boolean reverse = digitalRead(switchPin);
  boolean reverse1 = digitalRead(switchPin1);

  if(reverse == false){
    status = true;
  }
  if(reverse1 == false){
    status == false;
  }

  setMotor(speed, status);
}

void setMotor(int speed, boolean reverse)
{
  analogWrite(enablePin, speed);

  digitalWrite(in1Pin, ! reverse);
  digitalWrite(in2Pin, reverse);
}

I just added the second button with paint, so don't get confused.

Did you try a simple sketch that rotates right and an other one that rotates left to make sure that at least that was working ?

Also format and comment your code it will be a lot easier to read.

In your code the buttons only control the direction, but are not turning the motor on or off. This is only be done with the potentiometer, which can be set to zero speed.
To really enable the motor with the buttons, you have add some logic for the enable pin. For example change the setMotor() function and give it also a boolean as parameter, which indicates the enabling of the motor:
void setMotor(int speed, boolean enabled, boolean reverse)
{
    if(enabled) analogWrite(enablePin, speed);
    else        analogWrite(enablePin, 0);
    digitalWrite(in1Pin, ! reverse);
    digitalWrite(in2Pin, reverse);
}

You can set a corresponding boolean variable in the loop() function like you did with the status variable. Set this new variable to true in both if-statement of the buttons. Alternatively you can do this inline with the setMotor() call by writing:
setMotor(speed, reverse || reverse1, status);

The || is a logical OR operation. It returns true if any of both operands are true. In a similar way you can ditch the other if-statement with the status variable:
setMotor(speed, reverse || reverse1, !reverse && reverse1);

! negates the value of reverse and && does a logical AND. You can decide yourself, if you want to use if-statements (which are a bit easier to read or these logical statements (which are more compact).

Also you should use better variable names. reverse and reverse1 are not really good to distinguish. Better would be reverse and forward.


text:
Function only taking the first 4 elements of a character array
I'm writing a function for my arduino program that takes a character array of any size and will mark all the characters that aren't in the alphabet by changing their value to '1'.
I have a switch variable (foundSym) that will turn to 0 if the character IS part of the alphabet. At the end of my first for loop if the switch never changed, that means the character was NOT a letter and will be marked. Note I also don't want to mark space characters (' ').
The issue I have is every array I pass into the function will only have a length of 4, no matter the size.
I've checked the length of each array before it enters the function and when it is in the function, everytime the size gets shortened to 4 elements!
Here is my function...what am I doing wrong??
void markSymbols(char str[]){
  for(int i = 0; i<sizeof(str); i++){
    int foundSym = 1;
    for (int j = 0; j<26; j++){
      if (str[i] == alphabet[j]) {
        foundSym = 0;
        break;
        }
    }
    if (str[i] == ' ') foundSym = 0;
    if (foundSym == 1) str[i] = '1';
  }

}

Daft question but why not use the isAlpha function?

Or isAlpha doesn't give the correct set of characters check the ascii value e.g. if ((str[i] >='a') && (str[i] <= 'z')) foundSym=0; and then repeat for uppercase.  Or if you want to get fancy  char tmp = str[i] | 0x20; if ((tmp  >='a') && (tmp <= 'z')) foundSym=0; would check both upper and lower case.

You are passing a pointer (char str[]) and the sizeof operator is giving you the size of that pointer (4 bytes it appears in your case - on some Arduinos it would be 2 bytes).
The length of a character array is found by using strlen - assuming the string is terminated by a null (0x00).

I think this will do the same as your code.  I understand it doesn't directly answer the question, but I hope it shows you an alternative way of doing it using the library functions.  But they are very difficult to find unless you know about them already.
void markSymbols(char* str)
{
  for(int i = 0; i < strlen(str); i++)
  {
    if (! ((isAlpha(str[i]) || (str[i] == ' ')))
    {  // If the character is not an letter of the alphabet (upper and lower case) and it is not a space (char 32).
        str[i] = '1';
     }
  }
}

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


text:
ESP8266EX along with Arduino Due rev3 to check wifi status
Hi i am using ESP8266EX along with Arduino Due rev3 to check wifi status. when i compile my following sketch compiler give me error
User\Awais\Document\Arduino\liberaries\espsoftserialmaster\softserial.cpp:27:18: fatal error: gpio.h: no file or directory found
any one help me solve this problem
    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial (15,14); //RX|TX

     void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  ESPserial.begin(115200);
  Serial.println("NL & CR");
}

  void loop() {
 // put your main code here, to run repeatedly:

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

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

And where did you get that SoftwareSerial library? SoftwareSerial libraries are architecture dependent. You can't use AVR ore esp8266 SoftwareSerial library with ARM.
Due has no need for SoftwareSerial, it has 4 Serial ports configured.


text:
My Arduino Fingerprint Sensor FPM10A is not working with an Arduino Nano with Atmega168 processor
I recently bought this Arduino Fingerprint Sensor FPM10A from Aliexpress. So, when I connected it with my Arduino Nano and uploaded the 'enroll' example and opened the serial monitor. The fingerprint print sensor got detected but when I enter #1 to enroll the fingerprint no output is given on the serial monitor. I think my Arduino Nano just freezes.But other examples such as 'Empty database, it works with no problems. Is this caused by the less powerful Atmega168 microprocessor? If I get a Arduino Uno or an Arduino Nano with an Atmega328P microprocessor will this problem be solved? And I do not think the fingerprint module is defective as other examples worked like a charm.
Please see the attached photo above.

There appears more then one type of FPM10A.  Some with more connections than others.  It would be helpful if you could provide a link to your FPM10A and a data sheet.
Also, an Arduino Nano should use an ATmega328 processor.  If you have a nonstandard Arduino Nano perhaps it would also help to provide links and data sheets to the Arduino Nano you are using.
When using nonstandard Arduinos, it may be best to check for additional processor and / or board support.  And to use (load) them into your IDE when available.

There is no data sheet available

118 bytes for the stack and local variables is not enough. The problem is indeed the Atmega168. The Atmega328P has twice the ram.

Did you buy the arduino board Nano Atmega168 on Aliexpress? Sometimes the cheapest arduino compatible boards are okay, but sometimes they are stripped of decoupling capacitors or the polyfuse is missing (on a uno board). Sometimes they put a Atmega168 on the board, it is a few cents cheaper.
If you buy the cheapest nano compatible board, look at the photo if the quality is reasonable. The newer arduino boards have a ARM Cortex processors. The Atmega328p is still okay for small projects. I suggest to use the Atmega328p as the minimum.
A Arduino nano Atmega328p clone at Aliexpress costs about 2 dollars, so there is no reason to buy an Atmega168.
When the compiler tells you that "Low memory available, stability problems may occur" for the ram, then you can almost be sure that it will not work.
I try to keep about 300 bytes ram available for local variables, stack and the heap. It depends how much memory the libraries require. I also don't use the String objects for the Arduino uno or nano.
For a beginner, you can try to keep at least 500 bytes ram available.


text:
Write data on the computer with Arduino
I wonder if in Arduino you can modify the computer eg create a text file inside the computer using Arduino. Is there any way you can do this or something like that?
Because you can use the library #include <stdio.h>, which is a C++ language library to handle file on the computer.
In Arduino maybe you can create files on the computer using pointers or a library? Because using the library "Keyboard.h" you can handle the computer. The Keyboard library can interact with the computer by typing on the computer
I'm in doubt, I need your knowledge.

You can do it with a Serial.print if there is a program on the computer ready to accept the input from the serial port.

But to be clear, that requires writing a program on the computer to listen for the signal from the Arduino and actually do the work.  The Arduino cannot command the computer by itself.  All it could do would be to send a signal to let the computer know it was time to do it.

The arduino can't directly modify the contents of the PC hard drive, the ability for a peripheral device to do this would be considered a massive security flaw in the PC operating system.
Having said that there are a few ways to do it:
To save a text file without anything special on the PC:
Have the Arduino act as a keyboard. Send (windows key + R) (pause) notepad < enter > (pause) [ The text you wish to save to the PC ] (alt-f) s < file name > < enter>
This does require the PC to be unlocked (or you send the unlock key sequence first) and setting the directory to save to or overwriting a file could get tricky but should be possible if you work out the correct key sequence. The (windows key + r) combination is very powerful and also very dangerous. It makes it trivial to wipe the entire computer so use it with care.
To save a binary file to the PC:
Set up the arduino to act as a serial port. Start the terminal program of your choice and set it to log to a file. Send the data from the arduino. On the PC wait until the transfer is complete and then save the log file.
To read/save/modify any file without user interaction:
Set up the arduino to act as a serial port. Write a desktop PC application that takes the data from the Arduino. Define a protocol that allows the arduino to to specify the filename and what to do with it. The arduino doesn't directly access any files, instead it sends the commands to an application running on the PC, that application then performs the required file operations.
Alternative way to read/save/modify any file without user interaction:
Connect the arduino to the PC using USB. Exploit a flaw in the PC operating system to install a virus on the PC that gives you full control over the computer.

There are a number of serial-terminal programs that run on your PC (and pretty much any OS) that will copy the data they receive to a file. I use CoolTerm on MacOS. I think Windows HyperTerminal offers that capability as well on Windows. You have to start the terminal program on the PC, set it to capture, and open the capture file yourself - the Arduino can't cause the PC to do that - but once you've done it, the terminal program will copy all output from the Arduino to the capture-file. You might also have to set the PC to not sleep, if you need it to capture data without you being present.

The keyboard library just sends key presses to the computer like a keyboard.  From the PCs point of view it's no different from you banging on the keyboard in front of it.  The Arduino can't control anything on the computer and it can't run any code on the computer.  Now if you can do what you want completely from the keyboard then arduino could send those same keypresses.  But the Arduino has no access to the PCs operating system or file system.

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


text:
How to create a library from scratch?
Good morning. I have a problem that I hope you understand. I'm trying to create a library from scratch. I've read and watched most videos and documentation that are on the internet. I can not understand and I'm not able to make one.
I hope someone can help me create a library that only shows a message that says "Hello World" in the serial port and give me the code if they are so kind. Also, it would be good if they could explain it to me.
I insist I know of many programming languages and realize this has made me a problem. I just need the code of the 3 parts so I can analyze it and understand it. I wait for your help.

A library is just c and c++ source files that contain code. What part of that do you not understand?

It complicates me to create the files with the code

I know C ++ but in Arduino there are very few clear references to help that can create a library

Is it possible to change some colored words?

A simple example...
Create a folder named My_Library, and place it in the Arduino/libraries folder
Create a sketch named My_Library.h and add the following:
#ifndef __My_Library_H__
#define __My_Library_H__
#include "Arduino.h"

//example 1
#define myhello1() ( { \
   Serial.println(F("Hello World"); \
Serial.println(F("Hello World again"); \
} )

//example2
void myhello2() {
 Serial.println(F("another Hello World");
Serial.println(F("another Hello World again");
}

#endif

Place the the sketch in the "My_Library" folder
In the beginning of your sketch, add
#include <My_Library.h>

Then, wherever you want, add the following:
//example 1
myhello1();

//example2
myhello2();

I have not tested the above, but it should work fine.  Regardless, this gives you a reasonable starting point.
For your last question concerning word colour, research "Arduino Libraries" regarding the "keywords.txt" file.


text:
Power supply to L293D motor driver
I am new to Arduino. I'm making a line-following bot. I need to power my L293D module. I know that I can supply 9/12V directly with a battery but I am not sure whether I can supply 5V directly from the 5V pin of the Arduino or I have to use something like an IC 7805.
I am confused because I read that the L293D can cause currents up to 600 mA but the max current for an Arduino Uno pin is only 50mA. This question might seem too novice but it would be of great help if someone could explain me about this or the concept in general.
Thanks in advance.

You should probably not be using an L293 in a new design at all - it has high internal losses and has been obsolete for at least a decade.  Whatever you use, the motor power must not be routed through the Arduino board at all.  Do not use a small 9v battery for motors; likely you should use between 5 and 8 AA cells.

Where do people get this 50mA number from?

"Do not use a small 9v battery for motors; likely you should use between 5 and 8 AA cells. " Can you please tell the reason behind this ??

@Majenko sorry it was a mistake that was for 3.3V pin.i confused it with 5V pin

9V PP3 batteries have only about 150mAh. AA have nearer 2000mAh.

Ohh so more power capacity ...Right .thankyou

Check the L293x datasheet.
The L293D IC has two power supply pins. Pin 16, VCC1, is to power the IC itself, ei., its internal logic. Pin 8, VCC2, is to power the motors.
The maximum logic current (ICC1 MAX) drawn by the driver IC at pin 16 is 60mA. Thus, provided you do not have other things connected to the Arduino that can take the current draw above the limit, it is safe to connect VCC1 of the driver IC directly to the Arduino's 5V pin.
The maximum current you can draw from the 5V pin is around 400 mA, or 900 mA, when the Arduino is powered by an external power adapter.
The maximum current sourced or sinked by each driver input pin (xA) is 100 μA, and by enable pins (EN), it is 10μA, which is well within the limit of the Arduino digital pins, 40mA (not 50 mA!). So you can also safely connect Ax and EN directly to the Arduino.
Coming to the last point, the maximum power current supply by driver outputs (xY) is 600 mA. You cannot source or sink more than 600 mA from the 1Y, 2Y, 3Y and 4Y pins. All of this current will be drawn from pin 8 (VCC2), which is connected to the power supply for the motors, which can be a 9V battery. Note that ICC2 MAX is 1.2 mA. Thus, if the supply voltage of the motors is 5V, you must use another voltage source, like 7805 and not the 5V pin of the Arduino to provide VCC2.
To summarize,

You can connect pin 16 of L293D to Arduino's 5V pin.
You can connect pins 1, 2, 7, 9, 10, 15 of L293D to Arduino's digital pins.
You cannot connect pin 8 of L293D to Arduino's 5V pin.

Thankyou for your answer made a lot of doubts and misconceptions clear. Just to clear things out icc2 max is current from pin 8 of L293D and it's max value is 1.2A instead of 1.2mA right? Or am I making a mistake here ?

900mA if you don't mind cooking the 5v regulator...


text:
Finding ESP8266 in a network
I am connecting an ESP8266 to my home network (WiFi). After successful connection, an IP is assigned to it. I am sending commands to the ESP8266 from an Android app.
What can I do to find the ESP8266 on any network where my Android app is also connected? I ask this because whenever I change the network, a new IP is assigned to the ESP8266 and I have to manually change the IP in the Android app.
I just need to find the ESP8266 on the network, get its IP address and send commands to it.
Thanks in advance.

This question may have an answer that helps: https://arduino.stackexchange.com/questions/38092/how-do-i-know-ip-of-assigned-ip-address-to-esp8266

That's what mDNS is for. The ESP866 API has examples that show you how to use it.

@Majenko : Usefull thing mDNS is, but i am having a lot of issues , to use it in my product. I will give a try to post a new issue regarding that.
Btw thanks for the response, i really appreciate the help each time u contribute.

i am using socket to communicate with the esp8266. hence needed the ip address.

@Majenko : i have tried using mDNS but it doesn't work when the esp is in STA mode.

Did you found any solution to this ?

The best way to do this if you are doing it for product is using SSDP protocol.
It's Simple service discovery protocol which allows you to search for device in a network. It's implemented in many smart devices now a days with dlna or upnp.
Implement a SSDP server on esp8266 and
Implement a SSDP client on Android device.
You can find many devices with this approach, using simple filter to result with your specific information you want from SSDP packet can allow you to only get desired devices from network.
All the documentation about SSDP is given on Arduino esp8266 GitHub page.
You can broadcast your IP in your SSDP packet and then use it in your app, But still your most imp problem of dynamic IP remains unsolved as your IP will always be changing and using IP for accessing a hardware like home automation is not proper way.
You can either use.
1) Static IP for this if you want offline access or
2) Use cloud based solutions, such as mqtt to access device anywhere without the worries of NAT, IP or anything.
But second option is more of commercial kind, you need multiple resources to implement it.

@KarmaCoding If you think I have answered your question then upvoting or marking it as accepted answer is good idea. I can add more info to it if you want.

Some solutions that have worked for me:

Reserved IP - use the router's DHCP reservation to give the same ESP the same IP each time.
Static IP - Set the ESP to use the same IP each time, bypassing the DHCP feature altogether. This also boots the ESP slightly faster. WiFi.config(ip, gateway, subnet);
Dump the IP address to Serial on boot, so that you can at least see what's assigned: Serial.println(WiFi.localIP());
Give the STA a unique name that you can find in the router's DCHP clients page: WiFi.hostname("look_here");
use mDNS to assign a domain-like local URL to the device: MDNS.begin("esp8266");// default to "http://esp8266.local/"

useful answer too. but i am finding something to implement on a product level with different custom working protocols for multiple devices to search them in a network , where only my devices will get listed, also it must be the fastest way. i am using socket to communicate with the esp8266. hence needed the ip address.


text:
My gimbal program does not compile
my code:
// Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    // Yaw, Pitch, Roll values - Radians to degrees
    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    // Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      // Control the servos according to the MPU6050 orientation
      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif

// Yaw, Pitch, Roll values - Radians to degrees
    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

// Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }

// After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      // Control the servos according to the MPU6050 orientation
      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }

it says ypr does not name a type
/*
   Arduino and MPU6050 Accelerometer and Gyroscope Sensor Tutorial
   by Dejan, https://howtomechatronics.com
*/
#include <Wire.h>
const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll, pitch, yaw;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;
void setup() {
  Serial.begin(19200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        //end the transmission
  /*
  // Configure Accelerometer Sensitivity - Full Scale Range (default +/- 2g)
  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  delay(20);
  */
  // Call this function if you need to get the IMU error values for your module
  calculate_IMU_error();
  delay(20);
}

void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
  // Calculating Roll and Pitch from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)
  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  // Correct the outputs with the calculated error values
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)
  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;
  // Complementary filter - combine acceleromter and gyro angle values
  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

  // Print the values on the serial monitor
  Serial.print(roll);
  Serial.print("/");
  Serial.print(pitch);
  Serial.print("/");
  Serial.println(yaw);
}

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  */

  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value

  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)

  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)
  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;

  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

We simply print the values on the serial monitor and once we know them, we can implement them in the code as shown earlier, for both the roll and pitch calculation, as well as for the 3 gyroscope outputs.
MPU6050 Pitch Roll and Yaw outputs
Finally, using the Serial.print function we can print the Roll, Pitch and Yaw values on the serial monitor and see whether the sensor works properly.
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    if (j <= 300) {
      correct = ypr[0];
      j++;
    }
    else {
      ypr[0] = ypr[0] - correct;
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif

    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    if (j <= 300) {
      correct = ypr[0];
      j++;
    }
    else {
      ypr[0] = ypr[0] - correct;
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }

Please show us your full code. Did you define ypr beforehand?

as well as any error messages from the debug console

I know this is more of a comment but I can't do that yet.
This is for the code with wire.h at the top of the code.
I loaded your code into my arduino IDE and my line numbers reference those

You have lines 22-32 commented out.
The // at the end of line 40 may cause you problems.
If lines 41-43 the same that you have in
void setup ()
the same then you have the program doing something over and over again, that has already been set up.
line 145 you have a lone */ that the compiler should have found.
Lines 136 to 178 are not inside {} are not being run.  They also look very similar to what is inside your void loop()
Line 180 has the same void calculate_IMU_error() { as on line 80, which one is being ran?


text:
How do I make a character array scanner properly?
I start with this:
char delay_chars[10];

then I have a stream of incoming characters that I need to assign like this:
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e']

I can do that, but then more characters come in so I need it like this:
[' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e', ' ']
['l', 'o', 'v', 'e', ' ', 'p', 'i', 'e', ' ', 'a']
['o', 'v', 'e', ' ', 'p', 'i', 'e', ' ', 'a', 'n']
['v', 'e', ' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd']
['e', ' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd', ' ']
[' ', 'p', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'c']
['p', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'c', 'a']
['i', 'e', ' ', 'a', 'n', 'd', ' ', 'c', 'a', 'k']
['e', ' ', 'a', 'n', 'd', ' ', 'c', 'a', 'k', 'e']

You get the idea. I don't know how I can remove the first character of a char array (like I do with a String, remove(0, 1)) and I don't know how to add a new element at the end.
If I had to guess, I'd make a loop that will reassign the index of each character one step back or something like that but I'm not sure if that's how I should do it.

You can do it this way, but there's a better way that's faster and a lot less work.  You want something called a circular buffer.  Look that up and see if it doesn't do what you want differently but better.

If I had to guess, I'd make a loop that will reasign the index of each character one step back or something like that but I'm not sure if that's how I should do it.

Yep, that's pretty much it...
Here's how I do it:
char data[10];

if (Serial.available()) {
    char inch = Serial.read();
    for (int i = 0; i < 9; i++) {
        data[i] = data[i+1];
    }
    data[9] = inch;
}

Every incoming character gets added to the end of the array after everything else has been shuffled down one place.

It's pretty frustrating that in C you have to do all array stuff yourself

There are functions that can do it for you, but it's not really worth using them for such a simple operation. The for loop could be done with memmove(data, data+1, 9);

@NovaliumCompany By the way, I just corrected a typo.

Ok. I now have another annoying problem... my Arduino Uno seems to start to spit jibberish when I do some stuff... Do you mind helping me? (in a chatroom)

@NovaliumCompany Jibberish usually means you're overrunning a buffer. Maybe you're printing an array with no terminating NULL character?

Here's what I'm doing https://textuploader.com/168i3 The Serial.write starts normal and then turns into Jibberish. Here's more info about the problem: https://justpaste.it/3wobv

You can use SerialTransfer.h to automatically packetize and parse your data for inter-Arduino communication without the headace. The library is installable through the Arduino IDE and includes many examples.
Here are the library's features:

This library:

can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
works with "software-serial" libraries
is non blocking
uses packet delimiters
uses consistent overhead byte stuffing
uses CRC-8 (Polynomial 0x9B with lookup table)
allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 255 bytes)
can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:
#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  myTransfer.txBuff[0] = 'h';
  myTransfer.txBuff[1] = 'i';
  myTransfer.txBuff[2] = '\n';

  myTransfer.sendData(3);
  delay(100);
}

Example RX Arduino Sketch:
#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    Serial.println("New Data");
    for(byte i = 0; i < myTransfer.bytesRead; i++)
      Serial.write(myTransfer.rxBuff[i]);
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");
    Serial.println(myTransfer.status);
  }
}

You can easily edit the above example code to transfer ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'p', 'i', 'e'] instead of ['h', 'i', '\n'].


text:
Arduino doesnt seem to be reading my pin states
I seem to have an unbelievable thing. My code was working perfectly on one arduino, when i upload the same sketch to another one, it is behaving strangely, it seems like it is not reading any of my pin states:
The code is ment to drive a simple stepper motor with driver. depending on the state of several pins in which direction it moves or moves at all.
What is happening now is when i upload the sketch the motor starts to turn, nomatter what pinstate any of the input pins have, the motor just turns on uploading and even if i apply 5v to any of the pins, it just keeps turning the same direction.
Following the code. I hope someone could tell me what i am doing wrong, i am a newbie to programming:
int PUL=7; //define Pulse pin
int DIR=8; //define Direction pin
//int ENA=5; //define Enable Pin
int up = 2;
int down = 3;
int limitpin=1;
int limitpinup=4;
int i=0;

int buttonupstate = 0;
int buttondownstate = 0;
int limitstate=0;
int limitstateup=0;

void setup() {
  pinMode(PUL, OUTPUT);
  pinMode(DIR, OUTPUT);
  pinMode(up, INPUT);
  pinMode(down, INPUT);
  pinMode(limitpin, INPUT);
  pinMode(limitpinup, INPUT);
}

void loop() {
  buttonupstate = digitalRead(up);
  buttondownstate = digitalRead(down);
  limitstate = digitalRead(limitpin);
  limitstateup = digitalRead(limitpinup);
  i = 0;
  switch (limitstateup){
  case LOW:
    switch (limitstate){
    case LOW:
      if (buttondownstate==HIGH){
        do
        {
          digitalWrite(DIR,LOW);
          // digitalWrite(ENA,HIGH);
          digitalWrite(PUL,HIGH);
          delayMicroseconds(20);
          digitalWrite(PUL,LOW);
          delayMicroseconds(20);

          buttondownstate = 0;
          buttondownstate = digitalRead(down);
          limitstate == 0;
          limitstate = digitalRead(limitpin);
          limitstateup == 0;
          limitstateup = digitalRead(limitpinup);
        } while (buttondownstate == HIGH && limitstate == 0 && limitstateup == 0);
      }
      if (buttonupstate == HIGH){
        do
        {
          digitalWrite(DIR,HIGH);
          // digitalWrite(ENA,HIGH);
          digitalWrite(PUL,HIGH);
          delayMicroseconds(20);
          digitalWrite(PUL,LOW);
          delayMicroseconds(20);

          buttonupstate = 0;
          buttonupstate = digitalRead(up);
          limitstate == 0;
          limitstate = digitalRead(limitpin);
          limitstateup == 0;
          limitstateup = digitalRead(limitpinup);
        } while (buttonupstate == HIGH && limitstate == 0 && limitstateup == 0);
      }
      break;
    case HIGH:
      do{
        digitalWrite(DIR,HIGH);
        digitalWrite(PUL,HIGH);
        delayMicroseconds(20);
        digitalWrite(PUL,LOW);
        delayMicroseconds(20);
        limitstate = 0;
        limitstate = digitalRead(limitpin);
      }while (limitstate == HIGH );
      break;
    }
    break;
  case HIGH:
    do{
      digitalWrite(DIR,LOW);
      digitalWrite(PUL,HIGH);
      delayMicroseconds(20);
      digitalWrite(PUL,LOW);
      delayMicroseconds(20);
      limitstateup = 0;
      limitstateup = digitalRead(limitpinup);
    }while (limitstateup == HIGH );
    break;
  }
}

Do you have pull-up or pull-down resistors on the inputs?  If they’re floating when the button isn’t pressed then they are free to read presses whenever they pick up noise.

Well to be honest nothing is connected to the input pins for the moment. If they are in low state they shouldn't do anything right?  When I uploaded to an original Arduino and connected the pins to the rest of the wiring it worked perfectly. When I upload it now to an Arduino clone it starts turning without stop.

Wenn nothing is connected to an input pin, it is not in a low state. It is floating. Google arduino floating pin. You need to connect either a pullup or a pulldown resistor. The Arduino has an internal pullup resistor, that you can activate

Actually, I just looked at the schematics of my relay board. All input pins are with pull down resistors . When connected to that the motor also just started spinning. Without stopping. It's +5v to relay to resistor to ground. So I guess that is the correct way to work for a pull down. When relay is activated it should get a high state. Correct?

We aren’t talking about your relays.  You need pull-up or pull-down on the input pin for the buttons and switches.  When nothing is connected to a pin it is in a random state sometimes reads high and sometimes low.  You need something to keep it in a defined state while the button isn’t pressed.  Google “Arduino floating input” and you should get lots of information on the topic.

Thanks all of you,
Indeed there is nothing wrong with my code. The problem is indeed in the pull-down resistors, I rebuild the connection on a breadboard and works perfectly. I will have to check my PCB that contains all relays and resistors, the problem has to be on that board, bad connection or something like that.
However I would like to state that on the Osoyoo Uno board, the whole thing worked perfectly, so there has to be something different between Osoyoo Uno board and another Arduino board.

Here is the schematic to my PCB board. I checked it again, but i think all the digital pins have actually pull-down resistors active.

No, there doesn’t have to be anything different.  The code appeared to work on the other board.  But at any random time one of those inputs could have read a spurious press if it picked up the right noise.  The only difference was luck.  Floating input pins are almost never a good idea.

Post a wiring schematic.   It kind of sounds like you might not be completely understanding what we’re talking about here.  And if it seems to work now that’s no sign that it’s fixed.  If I puts are still floating then you’ve still got a problem.

By the way, the arduino has internal pull-ups.  The more normal way to arrange things is to have the button wired to read LOW when pressed and then you can use the internal pull-ups and don’t need external resistors.

I see pull downs on the relays.  But I don’t see any for the inputs to the arduino.  It’s hard to tell because the arduino isn’t in the picture but I think I see where the lines go back to the input pins and there aren’t pull-downs in those.

Or are the relays the inputs?  Usually a relay is on an output.  I’m more confused by your drawing than I was before.  How does all of this connect to arduino?

I am sorry. This was made with circuitmaker to create my own PCB for it. Actually pin number 10 on every relay leads to an input on the Arduino. You can see that in The exact middle of the schematic there are 4 terminals each lead to a digital input and are connected to a resistor and to pin 10 of every relay.

The resistors connect to pin 10 of the relay and what ground?  Is it connected to Arduino ground?

Yes all go to Arduino ground. They are grouped all together. (Also the ground from my stepper driver. Dir- and PUL-) so there is one cable for ground going from this PCB to the Arduino ground


text:
DS1302 RTC module running too fast
I am using a DS1302 RTC module with an Arduino Mega 2560 Rev 3. I follow steps on this website since I have no experience with RTC module before. Here are the outputs I am getting.
17:15:21.835 -> Current Date / Time: 26/2/2023 17:15:44
17:15:26.830 -> Current Date / Time: 26/2/2023 17:16:13
17:15:31.856 -> Current Date / Time: 26/2/2023 17:16:42
17:15:36.853 -> Current Date / Time: 26/2/2023 17:17:11

As you can see from the above output, the DS1302 is running five times faster than the real time (output past 30 seconds as real word past 5 seconds). Same thing happened if use different codes with different libraries.
Does this mean the RTC module itself is broken, or I can modify RTC module's speed with code?
//This code is to use with DS1302 RTC module, it permits you to setup the actual time and date
//And you can visualize them on the serial monitor
//This code is a modified version of the code provided in virtuabotixRTC library
//Refer to https://Surtrtech.com for more information

#include <virtuabotixRTC.h> //Library used

//Wiring SCLK -> 6, I/O -> 7, CE -> 8
//Or CLK -> 6 , DAT -> 7, Reset -> 8

virtuabotixRTC myRTC(6, 7, 8); //If you change the wiring change the pins here also

void setup() {
  Serial.begin(9600);
  // Set the current date, and time in the following format:
  // seconds, minutes, hours, day of the week, day of the month, month, year
  myRTC.setDS1302Time(15, 15, 17, 7, 26, 2, 2023); //Here you write your actual time/date as shown above
  //but remember to "comment/remove" this function once you're done
  //The setup is done only one time and the module will continue counting it automatically
}

void loop() {
  // This allows for the update of variables for time or accessing the individual elements.
  myRTC.updateTime();

  // Start printing elements as individuals
  Serial.print("Current Date / Time: ");
  Serial.print(myRTC.dayofmonth); //You can switch between day and month if you're using American system
  Serial.print("/");
  Serial.print(myRTC.month);
  Serial.print("/");
  Serial.print(myRTC.year);
  Serial.print(" ");
  Serial.print(myRTC.hours);
  Serial.print(":");
  Serial.print(myRTC.minutes);
  Serial.print(":");
  Serial.println(myRTC.seconds);

  // Delay so the program doesn't print non-stop
  delay(5000);
}

There is a crystal (a metallic cylinder) on the RTC clock module. Can you please report what is written on it?

Is the backup battery installed?

The crystal is 32.768kHz and I think it has a specific load capacitance of 6 pF. The backup battery was installed and it was also connected to the 5V rail from the Arduino.

If I change delay(5000); to delay(1000);, it is still running 5 times faster.

This electrical stack exchange answer covers the problems, theory of design & testing of such crystal oscillators.  It's likely more then you want to know.  These things are cheap. Less than $10 from reputable suppliers and only a few from questionable sources.  If you bought it from the likes of Adafruit, they might replace it. If I buy it from a questionable source I usually buy a few just in case one doesn't work.

I stumbled over the exact same issue today (using Arduino Uno/atmega328) and a module/board like this:
https://surtrtech.com/2018/01/27/how-to-simply-use-ds1302-rtc-module-with-arduino-board-and-lcd-screen/
When reading out time after setting it, it runs 5-6 times too fast.
I found some hint here regarding precision:
https://forum.arduino.cc/t/ds1302-drift/327796/7
However, they were talking about a 2 minutes of drift every 24 hours which for sure is a totally different thing.
One comment there was to pay special attention to the ground as noise there might be interpreted as additional clock signals and speed up the clock. So I played with the grounds on the board and disconnected everything else connected so far to pins of the Arduino board, but that did not change anything, still 5-6 times faster.
I also played with and without CR2032 battery and 5V and 3.3V input to the clock board's VCC input pin and ...suddenly... it worked ok.
I think with 3.3V input on VCC and no battery, it initially had the "normal" precision but now I can again connect it to 5V input and it still runs normal...
I also kept it a while disconnected from external power source (only running on battery), then connecting it back to the Laptop and reading out date/time values and still it worked ok.
It is totally weird.
Regards, Dan

While this is a good answer in the sense that it shows a way how to get out the issue, would you mind to investigate this effect systematically? One thought model could be that the crystal oscillator starts in some overtone frequency when powered the wrong way. If you do, please share the results by [edit]ing your answer.