text:
Code test the duration press of the button
I wrote code that tracks the duration of a button click. It has bounce protection and frequent clicks. (Freeze)
My code:
bool freeze_time, btn_read, debounce;
unsigned int freeze_timer, btn_timer;

#define BTN 6

void setup() {
  Serial.begin(9600);
  pinMode(BTN, INPUT);
}

void loop() {
  /* Freeze Timer Protection */
  if(freeze_time) {
    if((millis() - freeze_timer) >= 2500) {
      freeze_time = false;
      btn_read = false;
    }
  }
  /* Read Button State */
  if(digitalRead(BTN) == HIGH) {
    if(!btn_read) {
      btn_timer = millis();
      debounce = true;
      btn_read = true;
    }
  }
  /* BTN Read Process */
  if(btn_read) {
    /* Debounce Protection */
    if(debounce) {
      if((millis() - btn_timer) >= 1000) {
        if(digitalRead(BTN) == HIGH) {
          Serial.println("Debounce ok.");
          btn_timer = millis();
          debounce = false;
        } else {
          Serial.println("Debounce fail.");
          freeze_time = true;
          debounce = false;
        }
      }
    }
    /* BTN Read Process */
    else if(!freeze_time) {
      if((millis() - btn_timer) >= 1500) {
        if(digitalRead(BTN) == HIGH) {
          Serial.println("Ok. Button Pressed > 1500ms");
          freeze_timer = millis();
          freeze_time = true;
        } else {
          Serial.println("Ok. Button Pressed < 1500ms");
          freeze_timer = millis();
          freeze_time = true;
        }
      }
    }
  }
}

I checked it on real Arduino UNO and Tinkercad simulator. Initially, everything works well, but if I press the button indefinitely, the system will fail (every time you press the serial port, messages appear as if all flags were lost and the timers did not work. I filmed the behavior:
1) Initially: http://recordit.co/lVlR1z1CUq
2) System is broken: http://recordit.co/lhvzM100DI
What could be the problem and how to make it fault tolerant?

(millis() - btn_timer) >= 1000 Switch bounce doesn't last for a full second. You could however press the button, and release it within one second. Try changing it to a more sensible value like 10. The rest of the code doesn't really make sense to me. Could you explain what it is you want to achieve, as it looks like the code it way to complicated to just measure if a button was press for more or for less that 1500ms.

upvote for posting  correctly formatted code

you can reduce the number of lines of code by putting repeated command lines outside of if-else blocks .....  for  example, in the last if-else block, keep the  serial.println() lines inside the block, but move the freeze_timer = millis(); and freeze_time = true; to outside of the block, either before or after the block (it makes no difference logically in this instance) ........... same with the debounce = false;  in the previous if-else block

Use a more concise and reliable model for debounce (https://arduino.stackexchange.com/a/33577/42061)

Why did the timers stop working?
The main issue seems to be that freeze_timer and btn_timer are of type unsigned int, while millis, as stated in its documentation, returns an unsigned long.
As you may know, unsigned int is normally be able to hold a much smaller range of values than unsigned long. In the case of whatever compiler Tinkercad uses for the Arduino Uno, I checked and unsigned int can hold values from 0 to 65535, while unsigned long can hold values from 0 to 4294967295. Whenever you save an unsigned long into an unsigned int, it will be reduced modulo 65536.
This means that once you pass 65.536 seconds checks such as the (millis() - freeze_timer) >= 2500 will always be true (at least until millis wraps back around after 4294967.296 seconds - around 50 days).
If you would like to learn a bit more about integer conversions, I think this Stack Overflow question covers it.
The simplest solution is, of course, to declare freeze_timer and btn_timer to be of the appropriate type, unsigned long.
Use simpler code
All of the above being said, like Gerben said, the code seems overly complex.
There also seem to be other issues. For instance, I would expect the debounce behavior should not ignore presses that last less than 1 second. Like Gerben said, 10 ms should be enough to discard any bounces.
Furthermore, I think it would be more appropriate to not even discard presses that last less than 10 ms. I would say the debouncer should trigger "press" regardless of whether the press lasted less than 10 ms. It's role should just be to ignore multiple presses within that 10 ms window (although to be fair, ignoring short presses is not a terribly big issue).
Although one could make some guesses, to really help you with this, we would need a description of your intended behavior. What is the purpose of freezing? Is it intended to allow multiple presses to be triggered when you never release the button (or maybe you should wait until release before triggering one again)?

Works! Thank you!!!


text:
Ethernet shield reconnection problem after power cut
I am using arduino mega and this ethernet shield. Everyting is okey and connection is good. however, the device does not connect to the internet again after a power cut. if I press the reset manually it works again. Also arduino mega is plug-in with uninterruptible power supply but modem is not connected uninterruptible power supply, modem turns off if power cut. I am starting this method each time when sending data from docs. I think it is enought to reconnect to internet and getting IP. what should I do for reconnect internet after power cut

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, myDns);
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);

  ThingSpeak.begin(client);  // Initialize ThingSpeak

try to use static IP address or 'reserve' the DHCP assigned IP address on router

other problem could be that your sketch gets next connection if the one doesn't connect and all 8 connections are then in waiting state.

Interesting, I have the same problem. Never bothered to solve it because it's a rare occurence and I figured it had to do with interaction between the Arduino and the PowerlineEthernet device I'm using.

@Juraj I don't believe static ip will solve my problem. because each time I am checking internet connection and getting IP.

add #define PRINT_DEBUG_MESSAGES before #include "ThingSpeak.h" to see if it connects

source: Stack Exchange

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

sort: votes


text:
How to use Serial.setTimeout()
I am just playing with the UART interface of my board to learn about how it works. Since I have only one board, I send data out just to receive them by my own board, which is working so far.
Now I wanted to find out what Serial.setTimeout() is for. As per description on the Arduino homepage, it sets the maximum time for to wait for data. The description says, upon others Serial.find() will use it.
So I set Serial.setTimeout() to 100ms, and between sending and trying to receive data, I put a delay of 500ms. Therefore my expectation would be, Serial.find() will not detect a message, since there is more than 100ms no traffic on the bus. But I am still recieving data, it seems that the Serial.setTimeout() has no effect.
What is wrong in my understanding/usage of Serial.setTimeout()?
Here is my example sketch:
#include <M5Stack.h> // needed for my board M5Stack

HardwareSerial Serial2(2); // R2: Recieve Serial2, 17: Transmit Serial2  --> connnect pin R2 and 17

unsigned char buf_recive[1];
unsigned char buf_transmit[2] = {0x42, 0x00};

void setup()
{
  M5.begin();
  Serial.begin(9600);    // setting baud rate for COM3
  Serial2.begin(9600);   // setting baud rate for M5Stack2M5Stack communication
  Serial2.setTimeout(100);    //set the Timeout to 100ms
}

void loop()
{
  delay(500);
  // send buf_transmit
  Serial2.write(buf_transmit, 2);
  delay(500);
  // detect first byte of recieve message
  if (Serial2.find(0x42))
  { //start to read when detect 0x42
    Serial2.readBytes(buf_recive, 1);
    Serial.println(buf_recive[0]);
  }
  buf_transmit[1] = buf_transmit[1] + 0x01; // just to see that something's going on
}

And here some prove, that I am still receiving data:

The bytes are received to rx buffer with interrupt in the core. The find() function finds them there after the 500 millis delay. Timeout is to wait for the next byte if the rx buffer is empty.
The timeout is good if you know that the other side sends a collection of characters or bytes. Like for example a line sent from Serial Monitor or a Http request on networking client. The transmition has small gaps between bytes, but you want to receive it at once. So a function waiting a little for the next byte is useful.
Serial, networking Client classes and other Arduino stream classes inherit reading functions from the Stream class. This class has all the read and parse functions. There are 3 non blocking functions available, read and peek. All other read and parse functions use the timeout and wait for the next byte if the rx buffer is empty.
try this sketch with Serial Monitor
void setup() {
  Serial.begin(115200);
  Serial.setTimeout(10000);
}

void loop() {
  if (Serial.available()) {
    String s = Serial.readString();
    s.trim();
    Serial.println(s);
  }
}

send a line from Serial Monitor. a couple of characters. then send fast another line and then wait longer then 10 secs and send one more.

I tried this by changing Serial2.write(buf_transmit, 2); to Serial2.write(buf_transmit[0]); delay(200);    Serial2.write(buf_transmit[1]);, which should simulate the gap between the bytes, but I am still receiving, obviously I have still not understood. Do you have a hint what I am doing wrong?

gap yes, but you read the rx buffer after both writes were received to rx buffer. you can't simulate it with one MCU

you can test it with Serial Monitor.

ok, doing it on one device seems stupid. Any idea how I could set a timeout on the Serial Monitor?

I added a test to answer

Thanks, that test helped a lot in understanding. Now I also got why it is not working with one MCO.

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


text:
How to communicate between a webcam and an Arduino UNO and get the live feed on mobile using ESP8266?
I am working on a project of making a Smart Robot Car using Arduino UNO, L298N Motor Driver Module, ESP8266 Esp-01 WiFi module and RemoteXY app for controlling via smartphone over WiFi.
My question is: If I want to get the live feed of the view that my robot is seeing, using a webcam (say Logitech HD Webcam C270) using a USB to serial converter module or whatsoever, how can I make it possible?
Please let me know if there is any special shield or any processing board needed. Help with coding and the conversion of Video data into the transmittable Data for Arduino and help in making that kind of data which can be read by the Device (e.g. Smartphone) is also needed and will be appreciable.
It may be mentioned here that I am a beginner and I am currently learning through YouTube and Blog Tutorials. I am totally dependent on StackExchange like forums for the help in my projects either whenever I am making a mistake or when I want to try and learn something new or both. Please Help me while keeping these things in your mind also.
Please suggest me some good books on this branch of the subject that could make me able to do these kinds of things on my own.
Thank You So Much in advance!
(P.S.: If you feel this question should be downvoted then, please firstly let me know in the comments section why do you feel like this before downvoting, I may delete my question earlier, cause I am concerned about my reputation here.)

I've seen some products that working similarly, on Banggood. For example see this one . In this product, a Camera is attached to the robot, which gives the live feed to the user or controller on his smart device. I am also willing to make something similar but I don't know how to communicate between Arduino and a WebCam Live. Thanks in advance!

The UNO can't handle that kind of bandwidth. Unless you are okay with 1 frame per 10 seconds. USB would also be problematic. I think you'd be better of with something like a Raspberry Pi for the USB Webcam. Or the ESP with some specific camera module . Only use the UNO to drive the motors.

@Gerben have you gone through the link I had commented? If yes then, could you please tell me how is it working? If No, then please check it once and then make me understand that phenomenon. Thanks!

The link shows a robot with an independent wifi enabled webcam. There is no interaction with the Arduino there, other that the cam sits on the robot

@chrisl please go to this link and see how is he connecting his computer only from one wireless network and running both (the camera and the robot) together. Then, explain me what's going on there. Thanks in advance!

In the description of the robot used it mentions the raspberry pi 3B. On the website there are similar robots sold without the webcam and with just an Arduino with a Bluetooth controller. My guess is that they interface the raspberry pi with WiFi and the webcam and an Arduino that does the motor driving. This would require custom software on both the pi, Arduino and host computer. Potentially it is all done with a Pi but the listing also mentions an Arduino.

@C.W.G         So is it completely impossible to do such things with an Arduino Uno?

Yes, directly anyway. I'd recommend either using a raspberry pi for the project or using a WiFi enabled webcam that can connect directly to your computer

The Uno is a very limited platform, perhaps surprisingly, given its wide range of abilities and built-in hardware features. The two most glaring limitations for you application are its 16MHz clock speed (relative to modern desktop processors) and thus its bandwidth, and it's non-expandable 2KBytes of RAM.
Image processing would be right out the window, and even merely transmitting a raw image would be pushing its bandwidth limits, for any reasonable frame-size with even a very modest frame-rate.
Example: For a 100x100 8-bit frame at 15 frames/sec, a 16MHz processor (16M instructions per sec) would have (16000000 / (100x100x15)) = ~107 clocks (instructions) available to process each byte. You'd need some of those to either poll for next-byte-ready or to enter and exit an Interrupt Service Routine to process the byte. You're probably up to around 20 clocks (at a wild guess), to do nothing more than a bit of wire can do! Maybe you could do some trivial manipulation of each byte on the way through (say, brightness manipulation) with a few more clocks and you're already using a significant fraction of the processor just for that. And there isn't enough memory to be able to process a region of the image. And if you could, you run out of processor time before you could do much .... The problem just cascades as you approach the limits of speed and memory-space.

As rightly pointed out by others and @JRobert, its very difficult or nearly impossible to live stream a video/audio through Arduino Uno which uses Atmega328 micro-controller which is mostly used for simple embedded processing such as sensor reading, serial tr/rx, i2c like operations.
But there are some workarounds which can make it possible by using some SPI camera and some Bluetooth shield or ESP8266 together.
Take a look at this project which can be helpful to you.
https://github.com/ArduCAM/Arduino
But remember, don't expect a very good quality or higher frame-rate video stream. Also it might only send video, i.e. picture frames and not audio.
Second solutions is:
If you just want your robot to get equipped with a camera which need to be live streamed back to your android/ios phone with good quality AV then the best way to do this is by a standard method used by most RC toys, UAV or robots.
What you need is:
1) 5.8Ghz AV transmitter

A Mini FPV Camera NTSC/PAL with inbuilt transmitter or
FPV camera and a 5.8G 600mW Wireless Audio/Video Transmitter for FPV

with above options you can get a possible range of 1 Km to 5Km or more.
2) second thing you need is receiver section

OTG 5.8G 150CH Full Channel FPV Receiver For Android and iOS is best for this.
This above module will help you to receive AV from FPV camera/module to your android.

I'll not give you direct link to the products as that wont be a good idea here on SE. instead you can search for them on google and choose as per your requirement. most of these modules will be less than 2000 INR or 30$


text:
Operating AD5780 EVAL Board Via MicroController
OK, so thanks in advance because I am new here. I am reading the AD57XX drivers here  https://wiki.analog.com/resources/tools-software/uc-drivers/renesas/ad5780 and am struggling to understand how to get the device working and understanding it properly.
I am using code here https://github.com/maxgerhardt/arduino-ad57xx-driver/blob/master/src/main.cpp in order to test the DAC. I have several questions about the drivers and operation in general. I will itemize them if that is ok

Where in the drivers am I performing Slave Select and where am I determining Clock Speed? I have looked through the C in the drivers library, and it seems that each command, whether reading or writing selects the Slave/Master each time? I see no reference to which pins on my microcontroller it is reference though so I do not know if any of this is right.
Why do I need to be reading in the Control Register or anything from the DAC at all? Why does this matter? All I want is to output a voltage
How do I perform the right conversion to a voltage that I want? The command " AD57XX_SetDacValue() " takes a long, but I do not understand how that relates to a float value of voltage. Say I want 2.35 Volts, or a Sine Function from -2 to 2 Volts, how do I do this conversion?
I don't know how to debug the system in general. When I run the example code, which is supposed to output a triangle wave function, I get a sin function, which seems to just be noise.

In my experience analog devices eval board software is crap, I've had a few that I couldn't even get working with their software. I eventually layed out my own board with microprocessor.

@laptop2d Do you have any suggestions / alternatives of how to get the DAC running? I can't find proper githubs of this running and I'm a little pannicked

Note for readers interested in this topic: The same question has been asked at the Analog Devices "EngineerZone" here. Therefore answers / new information / etc. may appear there.

I use the AD5780, but with a STM32 on my own board. What I would do is write my own code for the eval board if you can find a way to program it.

@laptop2d Do you have documented code you use for the STM32? I understand there will be differences, but any reference for me is useful? I'm not competent enough to really write my own drivers

Where in the drivers am I performing Slave Select and where am I determining Clock Speed? I have looked through the C in the drivers library, and it seems that each command, whether reading or writing selects the Slave/Master each time? I see no reference to which pins on my microcontroller it is reference though so I do not know if any of this is right.

The slave select is controlled within the SPI_Write() function.  It uses the PinMgt_PinWrite() function to do the slave select control, which in turn selects a pin from the pinMapping[] lookup table.
The clock speed is set in AD5780_Init().

Why do I need to be reading in the Control Register or anything from the DAC at all? Why does this matter? All I want is to output a voltage

You don't. The code is just for demonstration purposes. It shows you how you could query those registers. If you don't need to, then don't.

How do I perform the right conversion to a voltage that I want? The command " AD57XX_SetDacValue() " takes a long, but I do not understand how that relates to a float value of voltage. Say I want 2.35 Volts, or a Sine Function from -2 to 2 Volts, how do I do this conversion?

That value is the raw value to set the DAC to. You refer to the DAC datasheet to know what that value equates to.  In this case the range is from \$V_{REFN}\$ to \$V_{REFP}\$.  Divide that range by 218 and you have the voltage per bit.

I don't know how to debug the system in general. When I run the example code, which is supposed to output a triangle wave function, I get a sin function, which seems to just be noise.

You need some debugging tools. Things like a logic analyser to be able to acually see what the IO pins of your MCU are doing.  An oscilloscope can be used to see if a signal is present, but to see all the SPI signals together you really want a logic analyser.

Thank you for responding. I understand the equation for the raw value. I understand if I send 0x3FFFF (18 1's, I would get the maximum value). What I dont understand is that the command AD57XX_SetRegisterValue and AD57XX_SetDacValue both use "unsigned longs" but then the code just stores binary inside these longs instead? When I adapt that code to just send  AD57XX_SetDacValue(0x3FFFF) I don't get 10 Volts coming out

I have read the datasheet over and over again, I don't mean to appear lazy, but it doesn't seem to be helping me

but then the code just stores binary inside these longs instead? -- What is that supposed to mean?

Also in the pinMapping[] doesn't have MOSI, MISO, or SCK, how is this supposed to work?

MOSI, MISO and SCK are the SPI hardware pins. You have no control over them. The SPI hardware controls them.

Isn't a long a integer value? Why is it sending in 0x3FFFF ? I know I should be sending in 18 bits, but I don't understand why the command asks for a long

A long is a 4-byte area of memory for storing information in.  We choose to use base 10 to represent the value that is stored in that memory. You could just as well use (as you do there) base 16. It's all just base 2 (binary) in memory anyway.

Could I be following some tutorial or other github repo or something for this? Without any formal EE experience I'm pretty lost and don't know how to do anything really.


text:
Issues with CO2 sensor SEN0159
I followed the sketch example for the SEN0159 CO2 sensor as precised in the data sheet  https://www.dfrobot.com/wiki/index.php/CO2_Sensor_SKU:SEN0159. It's powered by a 9V/2A DC power supply more than 48h and it still reads 2.81V on the analog ouput pin even if i exhaust on the sensor during long time, nothing happen, giving - 1ppm CO2 value.
Can you explain me why i cannot observe CO2 variations ? Is there troubles with the board ?
Thanks!

why do you power it with 9V?! the tutorial states a operating voltage of 5V and the datasheet (https://media.digikey.com/pdf/Data%20Sheets/DFRobot%20PDFs/SEN0159_Web.pdf) specifies that the maximum input voltage is 6V. Maybe you broke it...

From datasheet link: "External power supply (7~12V) is necessary to supply the microcontroller board when you using this CO2 sensor module."

Yes, i made a mistake... The arduino board should be powered by a 7-12V power supply to support high current from 5V pinout in order to power the sensor card... I'm very lucky, my sensor is not broken. I have powered it with 5V and it works fine!!! Thanks


text:
LCD displaying weird text
I am doing a project that requires input from a keypad to be displayed on the LCD display.
lcd.print() displays in proper form, but when the I press characters on the keypad, they are overwritten as weird symbols.
Any help would be appreciated.
Here's the code:
void setup()
{
  Serial.begin(9600);
  Serial.println("LCD test with PWM contrast adjustment");
  pinMode(13,OUTPUT);
  analogWrite(6,Contrast);

  lcd.begin(16,2);

  pinMode(buzzer, OUTPUT);
  lcd.print(" Electronic ");
  Serial.print(" Electronic ");
  lcd.setCursor(0,1);
  lcd.print(" Keypad Lock ");
  Serial.print(" Keypad Lock ");
  delay(2000);
  lcd.clear();
  lcd.print("Enter Ur Passkey:");
  Serial.println("Enter Ur Passkey:");
  lcd.setCursor(1,0);
  for(int j=0;j<4;j++)
    EEPROM.write(j, j+49);
  for(int j=0;j<4;j++)
    pass[j]=EEPROM.read(j);
}

So, where in your code are you working with a keypad? I don't see a single line that would have anything to do with a keypad.

stick to one type of variable, to prevent mix-up
So if you stick to a byte (uint8_t) type for keypad:
uint8_t keys[4][3] = {
  {1,2,3},
  {4,5,6},
  {7,8,9},
  {0xF,0xA,0xB}                 // F-*  B-#
}

then you can save it to your EEPROM as a byte and read it as a byte.it will prevent mix-up.
your code which you are not displaying (everybody here can write one of those faster then to download it from here)already translate numbers to numbers and then you are growing them to symbols with higher value

I think you should use 48 instead of 49.
48 is the ASCII symbol of 0. If you add a number from 0-9 to it, than you get the ASCII symbols of '0' to '9'.
(and a small sidenote: Enter Ur Passkey: is more than 16 characters; also it is more 'professional not to make slang texts to try to fit it, why not using Enter Passkey: instead?


text:
I'm getting NaN for readings on my DHT22 sensor when using 3v3 pin, but not 5v pin
I have a DHT22 temperature sensor and DS1302 RTC module connected to the 3v3 pins on an Arduino Nano. Both the sensor and the RTC module are rated to work on either 3.3V or 5V, but the recommendation is 3.3V.  For some reason though, when I connect the sensor and RTC to 3.3V power on the Nano, the sensor just returns NaN even though the RTC module works.  When I change the sensor to use 5V and leave the RTC on 3.3V, I get a proper temp and humidity value on the DHT22.  What is wrong?
Turns out the solder joint for the 3v3 pin on the nano was not properly done. I figured this out after I swapped out the nano for another nano and it worked. Resoldering the 3v3 pin fixed the problem.

Sometimes the problem is simply that you didn't properly solder the headers onto the Arduino. You should check to make sure that your solder joints are all good.


text:
Not sure which Arduino to pick
Is the Arduino Uno the best one to purchase for a complete beginner?
I eventually want to get into building Nodebots since I already have experience writing Nodejs web-based applications.
Or should I go directly to purchasing an Arduino Starter Kit? SparkFun Inventors Kit? Adafruit ARDX Experimentation Kit for Arduino? Seeed Studio ARDX starter kit? or Freetronics Experimenter’s Kit for Arduino?
I don't know the difference between these and based off what I have shared about my situation so far, which one should I start with to A. Learn the Basics, B. Evolve into developing Nodebots.

Start simple, buy a cheap arduino uno clone from aliexpress: https://www.aliexpress.com/item/Free-shipping-high-quality-UNO-R3-MEGA328P-CH340G-for-Arduino-Compatible-NO-USB-CABLE/32231525607.html Learn how to use the arduino ide with the arduino board, and while you do that, you can investigate where to go next. It can be circuitpython, or esp32 with wifi, or a arduino mkr board or the nodebots. A arduino fan does not have just one arduino board, but a box full of things to tinker with. You need an extra driver for those cheap clones: http://www.wch.cn/downloads/CH341SER_EXE.html

NodeBots does external control of Arduino with Java Script. The controlling computer is a PC or a SOC like Raspberry PI. (Eventually Raspberry can run NodeBots without Arduino.)
For NodeBots, Arduino board runs a firmware called Firmata which executes the commands sent by the Johnny-Five Java Script firmata master library.
I would recommend you to learn C++ and Arduino functions and libraries and code the Arduino directly without Firmata and a controlling computer.


text:
Why LCD 16x2 cannot display "water leaking" when rain sensor detects water?
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
SoftwareSerial mySerial(0, 1);

int gas_sensor = A5;
int water_sensor = 8;
int buzzer = 9;
int fan = 13;
int sms_count = 0;

void setup() {
  pinMode(gas_sensor, INPUT);
  pinMode(water_sensor, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(fan, OUTPUT);
  mySerial.begin(9600);
  Serial.begin(9600);
  lcd.begin(16, 2);
  delay(500);
}

void loop() {
  if (digitalRead(water_sensor) == LOW && analogRead(gas_sensor)) {
    CheckWater_and_Gas();
  }
  else if (digitalRead(water_sensor) == LOW) {
    CheckWater();
  }
  else if (analogRead(gas_sensor)) {
    CheckGas();
  }
  else {
  }
}

void CheckWater_and_Gas() {
  int sensorValue = analogRead(gas_sensor);
  Serial.println(sensorValue);
  delay(1000);
  if ( digitalRead(water_sensor) == LOW && sensorValue > 150 ) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(fan, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(" Water and ");
    lcd.setCursor(0, 1);
    lcd.print(" Gas Leaking ! ");
    SetAlertWater_and_Gas();
  }
  else {
    digitalWrite(buzzer, LOW);
    digitalWrite(fan, LOW);
    lcd.clear();
  }
}

void CheckWater() {
  if ( digitalRead(water_sensor) == LOW ) {
    digitalWrite(buzzer, HIGH);
    lcd.clear();
    lcd.setCursor(0, 1);
    lcd.print(" Water Leaking ! ");
    SetAlertWater();
  }
  else {
    digitalWrite(buzzer, LOW);
    lcd.clear();
  }
}

void CheckGas() {
  int sensorValue = analogRead(gas_sensor);
  Serial.println(sensorValue);
  delay(1000);
  if (sensorValue > 150) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(fan, HIGH);
    lcd.clear();
    lcd.setCursor(0, 1);
    lcd.print("Gas Leaking !");
    SetAlertGas();
  }
  else {
    digitalWrite(buzzer, LOW);
    digitalWrite(fan, LOW);
    lcd.clear();
  }
}

how do you know that the rain sensor is detecting water?

i check it from online

actually i can detect water using this sensor but lcd cannot display 'water leaking' if i use the code

please format your code ..... select all of the code and click {} button

leave everything connected and load an LCD "Hello World" sketch ..... does it work?

i think lcd should be no problem because lcd can display gas leaking when mq6 gas sensor detects lpg gas. lcd can display water and gas leaking also when mq6 gas sensor and rain sensor detect lpg gas and water simultaneously. but i don't know why it cannot display water leaking when rain sensor detect water.

I guess analogRead(gas_sensor) is never zero so the first if is activated if digitalRead(water_sensor) is LOW

yep, it always has value

and is it the problem? that it shows "Water and Gas Leaking"?

You schould start searching the root cause for your error: code, display, sensor, … step by step.
Check if your display is working by 1.) reducing your loop() to
void loop() {
    CheckWater();
}

and 2.) change
void CheckWater() {
  if ( digitalRead(water_sensor) == LOW ) {
    digitalWrite(buzzer, HIGH);
    ...

to
void CheckWater() {
  if ( true ) {
    digitalWrite(buzzer, HIGH);
   ...

This allows you to check if your LCD is working properly. If not, start looking for the fault in wiring or maybe you are using a different LCD which has to be setup in a different mode as the sketch from online.
If this works, search for the rootcause in the sensor. Go back to the orignial code and put the input of the rain sensor to low. If your display shows: Water Leaking! something with your water sensor or it's Connection to your board seems to be wrong.

i will try it, thanks for answering me.

fine. if you gone through this, please edit your question adding the results and refining the question


text:
RS485 Serial Communication not working with Arduino
I am trying to control 2 devices with my arduino using RS485 communication.
Basically switch on device 1 for 5 seconds when I send 'g' to the master. And switch on device 2 for e3 seconds when I send 'h' to the master.
I have a similar setup working with delays in the code I cannot use delays in the final version.
Here is the code I am using -
Master -
#include<SoftwareSerial.h>

#define NL 10
#define CR 13

SoftwareSerial Serial1(10,11); //RX, TX

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
char prevChar = (char) 0;
char inChar = (char) 0;

void setup() {
  // put your setup code here, to run once:
  Serial1.begin(9600);
  Serial.begin(9600);
  pinMode(8, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  char getdata = 'm';
  digitalWrite(8, LOW);

  if (stringComplete) {
    Serial.println(inputString);
    inputString.trim();
    //Serial.println("abc");
    if (inputString.length() == 1 && inputString.charAt(0) == 'g')  {
      Serial.println("Starting laser 1.");
      digitalWrite(8, HIGH);
      Serial1.print('1');
      //Serial1.print('h');
      Serial1.print(CR);
      Serial1.print(NL);
      Serial1.flush();
      digitalWrite(8, LOW);
    }
    else if (inputString.length() == 1 && inputString.charAt(0) == 'h')  {
      Serial.println("Starting laser 2.");
      digitalWrite(8, HIGH);
      Serial1.print('2');
      //Serial1.print('h');
      Serial1.print(CR);
      Serial1.print(NL);
      Serial1.flush();
      digitalWrite(8, LOW);
    }
    inputString = "";
    stringComplete = false;
  }

  if (Serial1.available()) {
    while(Serial1.available() && getdata != '\n') {
      getdata = Serial1.read();
      Serial.print(getdata);
    }
    Serial.println("");
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    prevChar = inChar;
    inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    //Serial.println(inputString);
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n' && prevChar == '\r') {
      stringComplete = true;
    }
  }
}

Slave -
#include <TimerOne.h>

bool isLightOn = false;
int counter = 0;

int address = 2;

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
char prevChar = (char) 0;
char inChar = (char) 0;

void timerISR() {
  if (isLightOn) {
    counter = counter+1;
    if (counter >= 20) {
      counter = 0;
      isLightOn = false;
      digitalWrite(5, LOW);
      digitalWrite(13, LOW);
    }
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  Timer1.initialize(100000);
  Timer1.attachInterrupt(timerISR);

  pinMode(5, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  //digitalWrite(13, LOW);
  digitalWrite(8, LOW);
  if (stringComplete) {
    inputString.trim();
    //if (inputString.length() == 1 && inputString.toInt() == address) {
      isLightOn = true;
      digitalWrite(5, HIGH);
      digitalWrite(13, HIGH);
    //}
  }

  while (Serial.available()) {
    // get the new byte:
    prevChar = inChar;
    inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n' && prevChar == '\r') {
      stringComplete = true;
    }
  }
}
/*
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    prevChar = inChar;
    inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n' && prevChar == '\r') {
      stringComplete = true;
    }
  }
}
*/

My connections are something like this -

Master - Uno,
Slave 1 - Uno,
Slave 2 - Nano

Serial1.println("1"); sends "1\r\n". no need to print the characters separately. inputString = Serial.readStringUnil('\n'); reads all the input from Serial Monitor. but if you send only one character, why do you read into String?


text:
TMRpcm interferes with Wire.h
I'm using TMRpcm library for playing .wav files from my SD card. Everything works fine, but if I include Wire.h library the files aren't playing at all (there's no sound). I have only added this line of code above my program:
#include <Wire.h>
//code after

I suppose that this is because of the timer and interruption because TMRpcm documentation mentions that:

May interfere with other libraries that rely on interrupts. The isPlaying() disable() or noInterrupts()
   functions can be used to prevent parallel code execution.

I've tried to use those functions but maybe I do something wrong. Can somebody help me? How can I use those libraries at once?
UPDATE:
Here's my before code:
tmrpcm.play("neMode.wav");
delay(2000);

and after:
noInterrupts();
tmrpcm.play("neMode.wav");
delay(2000);
interrupts();

It doesn't change anything. I hear no sound at all.

How did you use disable() and noInterrupts()? Please show the code for a complete minimal example, that shows your problem.

@chrisl I updated my post with that information. Concerning disable() function I don't really know how to use it. I would appreciate if you could help me

It will not play something, when turning off interrupts. Please show a complete (!) example, that shows your problem.

Also posted at Arduino Forum. If you are doing this, you have to link to it, so that we don't spend time on searching for information, that you only gave on one site.

I cannot see an obvious reason, why it stops working, when including Wire.h. Have you tested, if the Arduino is stuck in some function? You can add simple LED blinks or Serial prints to slowly hunt the problematic code down.

Well, it stops working exactly after I add a line:
#include <Wire.h>
I'm a beginner in Arduino, that's why I may have some dummy questions. But I can't find a solution of how can I use isPlaying() disable() or noInterrupts() to prevent TMRcpm library from being interrupted. Could you show me please how is it used correctly?

Besides, the problem may be in timer that these libraries use. I have tried to change TMRpcm library to work with Timer2 in Config.h. But then I just hear noise&beep instead of my file that should be played.


text:
7 LED Number Display
I need to write a string of number such as 1234567 on a 7 LED display. For example 1 will be lit up on display for 0.5 seconds, it will turn off then 2 will light up and so on. In the end I need to display "-" for 2 seconds. I also added the image of the given task.
The following is the code I wrote.
I would like to ask if it is the correct, and are there any flaws.
  const int LEDa=13;
  const int LEDb=12;
  const int LEDc=11;
  const int LEDd=10;
  const int LEDe=9;
  const int LEDf=8;
  const int LEDg=7;

  int i;
  int a;

  void setup() {

    pinMode(LEDa, OUTPUT);
    pinMode(LEDb, OUTPUT);
    pinMode(LEDc, OUTPUT);
    pinMode(LEDd, OUTPUT);
    pinMode(LEDe, OUTPUT);
    pinMode(LEDf, OUTPUT);
    pinMode(LEDg, OUTPUT);

  }

  void loop() {
    int array[7]= {1,8,0,5,1,0,0};
    for(i=0;i<8;i++){
      a= array[i];
      }
        switch(a){
          case 1:
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          delay(500);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          break;
          case 2:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDe,HIGH);
          digitalWrite(LEDd,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDe,LOW);
          digitalWrite(LEDd,LOW);
          break;
          case 3:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDd,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDd,LOW);
          break;
          case 4:
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          delay(500);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          break;
          case 5:
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDd,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDa,HIGH);
          delay(500);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDd,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDa,LOW);
          break;
          case 6:
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDe,HIGH);
          digitalWrite(LEDd,HIGH);
          delay(500);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDe,LOW);
          digitalWrite(LEDd,LOW);
          break;
          case 7:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          break;
          case 8:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDd,HIGH);
          digitalWrite(LEDe,HIGH);
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDd,LOW);
          digitalWrite(LEDe,LOW);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          break;
          case 9:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDd,HIGH);
          digitalWrite(LEDf,HIGH);
          digitalWrite(LEDg,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDd,LOW);
          digitalWrite(LEDf,LOW);
          digitalWrite(LEDg,LOW);
          break;
          case 0:
          digitalWrite(LEDa,HIGH);
          digitalWrite(LEDb,HIGH);
          digitalWrite(LEDc,HIGH);
          digitalWrite(LEDd,HIGH);
          digitalWrite(LEDe,HIGH);
          delay(500);
          digitalWrite(LEDa,LOW);
          digitalWrite(LEDb,LOW);
          digitalWrite(LEDc,LOW);
          digitalWrite(LEDd,LOW);
          digitalWrite(LEDe,LOW);
          digitalWrite(LEDf,LOW);
          break;
          }
          if(i=8){
            digitalWrite(LEDg,HIGH);
            delay(2000);
            digitalWrite(LEDg,LOW);
            }
          }

So did you actually try to see if the code worked?  You are asking people simply to check the code for errors.

the switch is outside for

I have not yet constructed a circuit. This was an educational type of code that I needed to write. Besides asking fo error check I was wondering how can I make it more concise without the need of using cases, which in this case I got the answer for it.

You might be interested in my implementation. I’m using a shift register instead of a bunch of the Arduino’s pins, but it might give you some ideas. Check out the tests to see how it’s used. https://github.com/rubberduck203/digital-thermometer/blob/master/src/SevenSegment.cpp

my comment is kind of picky, but this is programming after all ...... following instructions exactly is important  ....... your description of the problem and the description in the picture differ ...... you  said it will turn off .... there is no such directive in the picture ...... perhaps, going from 1 to 2 means leave segment "b" on, turn off segment "c" and turn on segments "a","g" and "d"

I see 3 errors:

You define the array to have 7 elements, but in the for loop, you count 8 elements, by using i<8 (Array indizes start at 0, so 0 will be the first and 6 will be the last element). Currently you try to access an array element, that does not exist.
The if statement is also not useful here. In your current code you check for i being equal to 8, but it will never be 8 inside of the for loop, because you used the condition i<8. To display the last - after the number, you should put the code after the for loop.
In the same if statement you write i=8, but a single equality sign means assignment. The value 8 will be assigned to the variable i and this assignment is true everytime. If you want to test equality use == (double equality signs)

Tip: You can make your code smaller by defining functions for codes parts, that get repeated often (for example the code to turn off all LEDs).
Tip2: If you want the code to be very efficient, you can change the pins to use one single port. Then you can change all the pins of the port at once, by assigning a single byte to it. You can save these bytes in an array. This will make your code way shorter, but you also need a deeper understanding about port manipulations. You can choose, what you want to do.

It looks like it is mostly correct, although that is a very long-winded way to set 7 segments to multiple values. I would be more inclined to set up an array of bytes where 7 bits of each byte contain ones/zeros to control the LEDs. Then you could skip the massive switch statement and simply loop through the array of bytes.
One mistake: if(i=8) should be if (i == 8). (= is an assignment. You want the == comparison operator.) Your code won't work correctly until you fix that.


text:
Short Occuring Between Digital IO Pins on Arduino ZERO
I have a couple custom SAMD21 boards (similar to Arduino Zero) connected to a screen from which I am trying to read PWM screen touch signals.
The two boards are identical - same components and same setup. The PWM lines are run from the MCU to a connector and then to the screen. There are no components on the PWM line (there can be an optional ESD suppresor but I have unmounted it for now).
On one board, I do not experience any problems - the screen works, touch signals are received and processed accordingly.
On the other board, the PWM does not work at all, in fact, the digital pins used to control it do not work at all. The PWM lines are hooked up at PA04 (Digital Pin 17) and PB09 (Digital Pin 15). When I try to write a value (high or low) to one of these registers, the code freezes. When I remove the screen, the problem goes away.
I set up an example, which just involves writing a HIGH signal to one pin and a LOW signal to the other.
So I took the two PWM pins (15 and 17) and connected them with a 220ohm resistor. On the functioning board, everything works, the code completes, and I read about 1.3V between the two.
But on the bad board, using the same setup with the 220ohm resistor, the board freezes in the same way as with the screen. Removing the connection (including the resistor) clears the error.
Is there a way inside the firmware to correct this? The operation is so simple and it freezes even when I try to write directly to the register - meaning I can't check the rdy bit for completeness while the pointer operation is not complete. Should hardware components be added the digital IO lines? I am unclear on how to proceed given that one identical setup works and the other does not.
Thank you very much for any help!
void setup() {

  uint8_t _yp = 18; //PB08
  uint8_t _ym = 16; //PA05
  uint8_t _xp = 17; //PA04
  uint8_t _xm = 15; //PB09

  SerialUSB.begin(115200);
  while (!SerialUSB);
  SerialUSB.println("Serial initialized...");

  pinMode(_yp, INPUT);
  pinMode(_ym, INPUT);
  pinMode(_xp, OUTPUT);
  pinMode(_xm, OUTPUT);

  SerialUSB.println("pinMode set successful");

  SerialUSB.println("Write xp high");
  digitalWrite(_xp, HIGH);
  SerialUSB.println("Write xm low");
  digitalWrite(_xm, LOW);

  SerialUSB.println("Finished");
}

void loop() {
}

consider the possibility that the failing board is actually the good one and the board that works is actually defective ..... i have seen an instance when a defect prevented the board from failing ...... maybe you have two pins shorted on  the screen  ...... one of the pins is blown on the board that works

I certainly hope not. I've made about 350 of these so far. I've checked the screen for shorts, and even removed one of the components I suspected of causing a short. Today I also swapped the two MCUs - the error carried itself along with the chip to the other board..


text:
How to stop motor after a desired time?
I am trying to stop a dc motor after a desired amount of time !! And the motor starts upon settling on a condition !! From that very moment i want my motor to just run for 5 seconds and stop!! Below is the pseudocode:
 #define max 150
 #define min -150
 #define pin1 3
 void setup()
    {
        Serial.begin(9600);
         mpu.initialise();
     }
   void loop()
     {
        x= some_accelerometer_values;
         If (x>250)
            {
                analogWrite(pin1,255);
                delay(5000);
                exit(0);
             }
      }

I tried using millis() but it starts time with execution of program and i can't get to implement it just before the motor starts running!

Don't use exit(0) on a microcontroller. There is no OS to take charge after the end of the program. Better use an infinite loop, if you want to end the program and do nothing more

Have you understood the BlinkWithoutDelay example, that comes with the Arduino IDE? I explains the use of millis() rather good. You take a timestamp (value of millis()), when the start condition arises, and then you calculate the difference between the current millis() value and the timestamp and compare it to the 5s (5000ms).

Thumbs up for the exit(0); information !! I didin't knew that, nor it was working with it !! But the millis(); is troublesome !! Its counting time since the program started !! And not since the motor started !!

@HrithikBaishakhiya You can use a variable to save the time when the motor started. Then always check the difference between now, and when the motor has started. And if the difference is >= then 5 seconds, it turns off

But the millis(); is troublesome !! Its counting time since the program started !! And not since the motor started !! ..... how do you boil  an egg for 3 minutes by using a clock, without using a timer?

Assuming you turn your motor on with analogWrite(pin1, 255); just write analogWrite(pin1, 0); after the delay(5000);.
And using exit(0); isn't as bad as people will most likely say. Using exit(0) is the same as cli(); + while(1). So it disables interrupts and stucks your code in a while loop till your reset the arduino.

But if x remains greater than 250 for a while then it will run until x < 250!!

@HrithikBaishakhiya since you used exit(0); you want your code to only run once. And if you write analogWrite(pin1, 0); before the exit(0) your motor will turn off. Then the program will stop and not ask about whether x is greater than 250 or not.

@HrithikBaishakhiya if() is triggered by a condition, and will only be executed once per loop()

I respect your effort !! But its not recommended to use exit(0); as written in some contexts and suggest by chrisl above!! I am little confused here !!

@HrithikBaishakhiya as of I know, exit(0); disables interrupts and throws the arduino into a while(1) loop. I just tried it on my arduino-uno. It's pretty much a loop() but with disabling interrupts.


text:
Basic Arduino Airplane Control
I have a task where I need to control the airplanes thrust and altitude direction(Up-Down). For the thrust I thought of using a DC Motor and a Servo for the other. Control of servo will be from the buttons and the thrust value will be given from the serial port. (This is not a project of a real vehicle, only thing I need to do is the code, rest is imaginary.)

I have wrote the following code. I would like to ask is there any flaws and how can I further improve it? Thanks in advance.
With my regards...
#include <Servo.h>
  Servo servo1;
  int pos = 0;
  const int buttonSUP = 2;
  const int buttonSDOWN = 3;

  int buttonStateUP = 0;
  int buttonStateDOWN = 0;

  int motorPin = 4;

  void setup() {

  servo1.attach(9);
  pinMode( buttonSUP, INPUT);
  pinMode( buttonSDOWN, INPUT);

  pinMode(motorPin, OUTPUT);
    Serial.begin(9600);
    while (! Serial);
    Serial.println("Speed 0 to 255");

  }

  void loop() {
   buttonStateUP =digitalRead(buttonSUP);
   if(buttonStateUP=HIGH){
      servo1.write(90);
      Serial.println("UP");
    }
    if(buttonStateDOWN=HIGH){
      servo1.write(0);
     Serial.println("DOWN");
      }
    else{
        servo1.write(45);
        Serial.println("STABLE");
        }

    if (Serial.available())
    {
      int speed = Serial.parseInt();
      if (speed >= 0 && speed <= 255)
      {
        analogWrite(motorPin, speed);
        Serial.println(speed);
      }
    }

    }

Your formatting is off, but also, it's always either DOWN or STABLE?

I thought as the servo being 45 degrees shifted just as  this "<". There fore with a 90 degree move, I can shift from up to down or vice versa .

while (! Serial);  Is not needed if you have a board with USB-> Serial bridge Chip (arduino uno for example)
if(buttonStateDOWN=HIGH){
}

In every condition you used = instead of ==. Your "condition" actually assigns HIGH to buttonStateDOWN. If you want to compare integers, use ==.
And according to the question, I think you have misunderstood the speed buttons (or maybe I have). I think, they want you to code it so while the button is pressed or every time the button is pressed, the speed changes by +1 or -1.
Assuming the rest works fine, there could be a problem with your serial output, since you just spam messages.
Read about the millis();, it can help you so you only send something every x amount of seconds, without using delay(); Here


text:
MPU-6050 with Arduino - postmortem
I'm working with MPU-6050 with Arduino Uno.
I copied the code below from Arduino Playground - MPU6050.
Code :
  // MPU-6050 Short Example Sketch
  // By Arduino User JohnChi
  // August 17, 2014
  // Public Domain
  #include<Wire.h>
  const int MPU_addr = 0x68; // I2C address of the MPU-6050
  int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
  void setup() {
    Wire.begin();
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    Serial.begin(9600);
  }
  void loop() {
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
    AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
    GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    Serial.print("AcX = "); Serial.print(AcX);
    Serial.print(" | AcY = "); Serial.print(AcY);
    Serial.print(" | AcZ = "); Serial.print(AcZ);
    Serial.print(" | Tmp = "); Serial.print(Tmp / 340.00 + 36.53); //equation for temperature in degrees C from datasheet
    Serial.print(" | GyX = "); Serial.print(GyX);
    Serial.print(" | GyY = "); Serial.print(GyY);
    Serial.print(" | GyZ = "); Serial.println(GyZ);
    delay(333);
  }

Firstly, I want to know every details about this code, AcX, AcY, AcZ, GyX, GyY, GyZ what all these mean ?
It will be nice with some visual representation.
Secondly, If I change the delay to 500 from 333, will it cause a problem ?
This type of stupid question because, I can't find any relatable figure with 333 except 1000/3

Ac{XYZ} refers to the acceleration reported by the sensor in x, y, and z direction. Gy{XYZ} refers to the rotation (per second) reported by the sensor along the x, y, and z axis.

The 333ms delay is just a number, you can make it 2 or 20000 or whatever.

I can't find any relatable figure with 333 .... think about it a little bit ..... what is the purpose of loop()? .....  what happens if you put a 333ms delay in loop()?

thanks everyone ...

How to filter value in real time ? Can anyone tell me ?

AcX = Accelerometer data in X axis in floating point.
AcY = Accelerometer data in Y axis in floating point.
AcZ = Accelerometer data in Z axis in floating point.
GyX = Gyroscope data in X axis in floating point.
GyY = Gyroscope data in X axis in floating point.
GyZ = Gyroscope data in X axis in floating point

.
Secondly study regarding I2C communication and MPU 6050 datasheet.
Third you have any value for delay as it is how fast you want to fetch data from all axis from IMU.

Thanks, I was trying to move and rotate an object in Unity using Arduino as input . Now I have this , rotation is perfect but, position isn't . Maybe you can help me with that.

I think that  AcX, AcY, AcZ, GyX, GyY, GyZ are raw acceleration and gyroscopic values recieved from mpu6050 in the corresponding directions. in order to recieve them a procedure is followed.
 Wire.read();

means two registers are read and stored in the same variable
   accelerometer_x = Wire.read()<<8 | Wire.read();

reads registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L) that is ,
it deals with bitwise operation to shift the values 8 bits left (multiplying it by 256).
This enables addition ("|" or "ored") of two datas in order to continuously output the accelerometer data !! Without this you would not be able to see the increasing and decreasing sloping values .
Further, the print just displays the instantaneous values on screen.
If you want to go in deapth of the code, you can visit this site for line to line description !!
https://www.mschoeffler.de/2017/12/09/example-application-gy-521-module-mpu-6050-breakout-board-and-arduino-uno/
 delay(500);

Totally depends on your project, i don't see any forecoming issues if you will make 333 go 500 !! It will just stablize the output on screen there for a bit longer (for .5 seconds)

How to process these raw value to actual value ?

@MaifeeUlAsad You can always use the mpu6050 library by jeffrowberg !! He has done an excellent job in reverse engineering the mpu6050 aspects and put them in perspective. You can use mpu6050_dmp6 sketch to get real processed values.

you can also include the library and use some functions like mpu.getmotion6(&ax, &ay,&az,&gx,&gy,&gz,) to get these precise values.

Thanks, I was trying to move and rotate an object in Unity using Arduino as input . Now I have this , rotation is perfect but, position isn't . Maybe you can help me with that.


text:
How to Simulate and Tune a PID
I've been trying to simulate a PID using Brett Beauregard's PID library in order to understand it better. Here is my code.
#include <PID_v1.h>

const unsigned int numReadings = 500;
double analogVals[numReadings];
unsigned int i = 0;
int angle = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
void setup()

{
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  Serial.begin(115200);
  Setpoint = 300;
  myPID.SetOutputLimits(-2,2);
  myPID.SetSampleTime(100);
  Input = random(292, 302) ;
}

void loop()
{
  if (i % 2 == 0) {
  Input += random(-2,3);
  }
  angle += 1 % 360;
  Input += sin(angle*355/(113*180));
  myPID.Compute();
  Input += Output;
    analogVals[i] = Input;
    i++;
    if (i>= numReadings)
    {
      for (int j = 0; j < i; j++) {
      Serial.println(analogVals[j]);
      }

      i = 0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
    }
}

Even if I restrict the output of the PID to a very small value, I get huge nonsense results of this code. It oscillates like -1000 to 1000. I've read this https://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops
and tried to adjust my parameters, but they're just shots in the dark really, I can't even damp these massive oscillations. How would I tune a PID to cancel out a sin error ?
Thanks in advance

please post the link to the PID library?

I do not have your PID_v1.h, but I made a simple experiment trying to control your example with a simple P-Controller instead of the PID lib. I made the following changes to your code:
...
double K_P = 1;
...
//myPID.Compute();
  Output = K_P*(Setpoint - Input);
  Input += Output;

This is working for very small amounts of K_P, but as soon as K_P gets higher than 2.0 it gets instable very fast. I guess this is what you are observing. The reason for me is, that you have implemented a ideal control path. In real control tasks you will always have some transfer behavior
Therefore I added a simple PT1 element (first-order lag element) to your code, now your system is much more stable and you can experiment with the K, I and D factors. Here it works with K_P even higher than 400:
// #include <PID_v1.h>

const unsigned int numReadings = 500;
double analogVals[numReadings];
unsigned int i = 0;
int angle = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
double Input_PT1;
double K_P = 20;
//Specify the links and initial tuning parameters
//PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
void setup()

{
  //turn the PID on
  // myPID.SetMode(AUTOMATIC);
  Serial.begin(115200);
  Setpoint = 300;
  // myPID.SetOutputLimits(-2,2);
  //myPID.SetSampleTime(100);
  Input = random(292, 302) ;
}

void loop()
{
  if (i % 2 == 0) {
    Input += random(-2, 3);
  }
  angle += 1 % 360;
  Input += sin(angle * 355 / (113 * 180));
  //myPID.Compute();
  Output = K_P * (Setpoint - Input_PT1);
  Input += Output;
  // start PT1
  Input_PT1 -= Input_PT1 / 25;
  Input_PT1 += Input / 25;
  // end PT1
  analogVals[i] = Input_PT1;
  i++;
  if (i >= numReadings)
  {
    for (int j = 0; j < i; j++) {
      Serial.println(analogVals[j]);
    }

    i = 0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
  }
}

Some hint:

The sketch above does not initialize Input_PT1, so it takes some secondes until you reach a steady value of 300, if you do not want to wait, just initialize Input_PT1 with 300. But this is exactly where you can start increasing first I, then D factors to try to increase speed for reaching a steady value of 300 and experiencing what influence I and D part will have.
Input_PT1 is not a good naming, since this is the output of the PT1 element, but since you are using it as the PID Input, I did not change.

Here a drawing of what I implemented in contrast to your sketch (at least I hope so ;-))


text:
Reading inside critical sections from ISR
Is it necessary to protect reads of volatile variables in critical sections when using interrupts? Or are critical sections only required when concurrently writing variables?
Here is an example of a variable written within an ISR which is protected with a critical section:
void loop() {
    portENTER_CRITICAL(&mux);
    uint other = variable_written_from_isr + 1;
    portEXIT_CRITICAL(&mux);
}

What will happen if an interrupt changes variable_written_from_isr while it is being read? Would anything worse that inconsistencies happen?
Here is an opposite example where a variable is written from an interrupt and read from the loop (or a task):
void IRAM_ATTR handleInterrupt() {
    portENTER_CRITICAL_ISR(&mux);
    uint other = variable_written_from_loop + 1;
    portEXIT_CRITICAL_ISR(&mux);
}

Please note that I aware of stdatomic. I am mainly interested in understanding the behavior of concurrent access in the context of interrupts.

What will happen if an interrupt changes variable_written_from_isr while it is being read? ..... there will be no interrupt because  portENTER_CRITICAL(&mux); disables interrupts

Thank you for pointing it out. I was expecting the interrupt execution to be delayed until the critical section is exited.

You should use critical sections around any operations that could potentially be affected by the execution of an ISR (or which could affect an ISR) that aren't atomic.
Simply put, an atomic instruction is one which can be represented by a single assembly language instruction. You can't interrupt during the execution of an assembly instruction, so anything that only takes one instruction can't be interrupted until it's complete.
Examples would be moving a value from one 8-bit variable (assuming an 8-bit architecture) into a register, storing an 8-bit value into memory, etc.
What instructions are likely to be atomic very much depends on the architecture that you are working on.  The only real way to be sure is to compile the code into assembly language and examine what is produced. Of course, that means learning the assembly language of your chosen architecture.
However: if in doubt, use a critical section. Better to be safe than sorry. But keep those critical sections as short as possible to not disturb the interrupts more than is needed.
For example, instead of starting a critical section, reading some volatile value, doing some calculations with it, and writing it elsewhere, you should use the critical section just to read the volatile value into a temporary variable. After the critical section, you can then do your calculations and things with it, while the interrupt is then free to be called again.

A non-atomic read in your main code of a 2-or-more-byte variable that can be written in an interrupt routine does need to be protected. In this case, the variable itself can't be corrupted, but the value read from it by your main code might be - in the case where the main code is reading the shared variable one byte at a time, and gets interrupted between two of those byte-reads.


text:
connection of led with dht and code combination
Hi again? I saw my last question did not come out well, so let me rephrase it.
Ideally, my project is composed of 3 sensors: 2 dht-22 sensors and an mq-7 sensor.
For the dht22 sensors, I am using data pin connections 9 and 10 PWM on the Arduino mega 2560 board with their respective 10 kilo-ohm resistors, with 5v supply and ground connections.
The issue is that I want to set limits for both temperature and humidity for both sensors to be:  (16

#include "DHT.h"

#define DHT1PIN 9     // what pin we're connected to
#define DHT2PIN 10

#define DHT1TYPE DHT22
#define DHT2TYPE DHT22

// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht1(DHT1PIN, DHT1TYPE);
DHT dht2(DHT2PIN, DHT2TYPE);

void setup() {
  Serial.begin(115200);
  Serial.println("DHTxx test!");

  dht1.begin();
  dht2.begin();
}

void loop() {
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h1 = dht1.readHumidity();
  float t1 = dht1.readTemperature();
  float h2 = dht2.readHumidity();
  float t2 = dht2.readTemperature();

  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (isnan(t1) || isnan(h1)) {
    Serial.println("Failed to read from DHT #1");
  } else {
    Serial.print("Humidity 1: ");
    Serial.print(h1);
    Serial.print(" %\t");
    Serial.print("Temperature 1: ");
    Serial.print(t1);
    Serial.println(" *C");
  }
  if (isnan(t2) || isnan(h2)) {
    Serial.println("Failed to read from DHT #2");
  } else {
    Serial.print("Humidity 2: ");
    Serial.print(h2);
    Serial.print(" %\t");
    Serial.print("Temperature 2: ");
    Serial.print(t2);
    Serial.println(" *C");
  }
  Serial.println();
}

Ps: LEDs used are 10mm.
For the MQ-7 sensor, this is it's code.
/* MQ-7 Carbon Monoxide Sensor Circuit with Arduino */

 const int AOUTpin=0;//the AOUT pin of the CO sensor goes into analog pin A0 of the arduino
 const int DOUTpin=8;//the DOUT pin of the CO sensor goes into digital pin D8 of the arduino
 const int ledPin=13;//the anode of the LED connects to digital pin D13 of the arduino

 int limit;
 int value;

 void setup() {
 Serial.begin(115200);//sets the baud rate
 pinMode(DOUTpin, INPUT);//sets the pin as an input to the arduino
 pinMode(ledPin, OUTPUT);//sets the pin as an output of the arduino
 }

 void loop()
 {
 value= analogRead(AOUTpin);//reads the analaog value from the CO sensor's AOUT pin
 limit= digitalRead(DOUTpin);//reads the digital value from the CO sensor's DOUT pin
 Serial.print("CO value: ");
 Serial.println(value);//prints the CO value
 Serial.print("Limit: ");
 Serial.print(limit);//prints the limit reached as either LOW or HIGH (above or underneath)
 delay(100);
 if (limit == HIGH){
 digitalWrite(ledPin, HIGH);//if limit has been reached, LED turns on as status indicator
 }
 else{
 digitalWrite(ledPin, LOW);//if threshold not reached, LED remains off
 }
 }

I am yet to buy a relay circuit to be able to connect it with the circuit using a , but for now I would appreciate it the scenarios highlighted for the sensors could be addressed and also, how the two codes could be combined to be one single code.
If there is any question, feel free to ask.
The project is for silo monitoring and control.

Only thing that gives people problems when combining two simple sketches are "delay" commands. There is just one "delay" so it's perfect.

Create new sketch
Paste everything that's not in a method from the two sketches.
Combine setup methods together by pasting first one and second one below.
Remove duplicated commands like Serial.begin(115200); from the method
Combine loop methods together by pasting first one and second one below.
Move code in loop to make the code visually pleasing (it's called the "smell" of code)

This should not be a big problem with those two particular sketches.
Please ask more precise questions as soon as you will have problems.


text:
Prevent function inlining
I'm trying to shrink the compiled code size, and I have noticed that the compiler inlines functions a lot, even the ones I have not marked "inline", but I can't manage to turn that off.
It looks like the compiler uses the -Os flag by default (optimize for low program size), because when I add it, the resulting program size is the same.
I tried adding "__attribute__((noinline))" to the functions but it makes no difference. Any idea how to prevent function inlining?
I'm using Visualmicro on Visual Studio Community 2017. Arduino 1.8.8. Arduino Uno board.

Did you try  __declspec(noinline)? https://docs.microsoft.com/pl-pl/cpp/cpp/noinline?view=vs-2017

@FilipFranik That is only for Microsoft's compiler. Arduino uses GCC, which doesn't use Microsoft's custom cr@p.

@BjörnMorén How have you determined that it's inlining the functions?

See over on SO https://stackoverflow.com/questions/7244363/how-to-prevent-gcc-to-inline

Do you assume that not inlining a function shrinks the compiled code size? That might not be correct. The gcc compiler follows the -Os flag. Forcing to make a function call might increase the code size. You could show us your code, and we can shrink it. For an arduino uno, you could also move data from code to eeprom.

Thanks for the replies!
I created a class with a function with no arguments containing dummy code. Then I tried calling this function from the main() section, first one time and noted the size, then two times in a row and watched how it increased the compiled code size by 60 bytes. Then I applied the noinline attribute, and it made no difference. However, now when I do the same thing, the compiler behaves like it should. So my apologies for wasting your time with this.

But there is definitely something fishy going on with this compiler. Another test I did was to make all private variables public. Compiled code size shrunk, which is to be expected, since some optimizations could be made. Then I made them private again. Compiled size stayed at the shrunk size. It is as if the compiler needs a few tries to really optimize the code.

It is also weird how using the -Os flag still inlines functions even though they are not marked "inline". -Os means optimize for size. I can clearly tell it does this, because when I apply the noinline attribute to the functions, it makes my compiled code size smaller. I wish there was a compiler flag that meant "no inlining, except when the inline keyword is used".

What you call weird is in fact the extremely optimized code that the gcc compiler makes. The gcc can (almost) do whatever it wants. The "lto" optimization globally optimizes things, and the result is hard to predict. Sometimes variables are only temporary in registers and never occupy a memory location. There are options to control inlining: http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html You can add them to a sketch with the #pragma. I took one of my larger sketches and tried a few inline options, but the code size never got smaller. Can you give a small sketch that becomes smaller?

As I wrote in the comments, I can't recreate this problem again. So I apologize for wasting everyone's time. But I still find it weird how the -Os flag works. I assumed it meant smallest possible size. But I now think it means "fairly small, but also make it run fast". Look at the code below, and how using the noinline attribute makes the code smaller. I added the -Os compiler flag to be sure, but I think it is already on by default.
class InlineClass
{
public:
    void __attribute__((noinline)) testFunc(int arg1)       // 570 bytes
    //void testFunc(int arg1)               // 602 bytes
    //inline void testFunc(int arg1)        // 602 bytes
    {
        _var1 = arg1 + 1;
        _var2 = arg1 + 2;
        _var3 = arg1 + 3;
        _var4 = arg1 + 4;
        _var5 = arg1 + 5;
    }

private:
    volatile int _var1 = 0;
    volatile int _var2 = 0;
    volatile int _var3 = 0;
    volatile int _var4 = 0;
    volatile int _var5 = 0;
};

void setup()
{
    InlineClass ic;
    ic.testFunc(1);
    ic.testFunc(2);
    ic.testFunc(3);
    ic.testFunc(4);
    ic.testFunc(5);
}

Did you check all the inline options in that link? https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html The -Os turns on some them and the compiler uses heuristic to decide what to do. For example with the -finline-small-functions option. I get the 570 and 602 size for an arduino uno, that means you have found a miscalculation of the heuristic. That is an impressive achievement! I tried to turn the inline options off to be able to control it with a compiler option, but that did not work. When testFunc is made larger, the sizes are the same.

@Jot Thanks for the reply. I played around with the compiler flags relating to inline functions in the document you linked, but could not get it to work well. This is all a mystery to me, because when I selectively apply "attribute((noinline))" to certain functions in my sketch, I can shrink it by 578 bytes, from 32492 to 31914 bytes, which is a lot when you are close to the limit. Could it be that the compiler isn't properly tailored for the AVR processor? I assume that making it work for a certain instruction set requires a lot of tuning, that might have been done poorly?

@Jot I also posted this question to the people at Arduino.cc, lets see what they have to say. Maybe it is a GCC issue, or maybe an Arduino specific issue. https://forum.arduino.cc/index.php?topic=607719.0

In my "local.h" file - macros & other definitions I tend to use a lot, just such as one you're asking about - I keep this one:
// Don't compile this function inline
//   '__NOINLINE void foo(void){ ... }'
#ifdef __GNUC__
#define __NOINLINE  __attribute__ ((noinline))
#else
#define NOINLINE error 'NOINLINE' not defined for this compiler
#endif

which both gives me a fairly simple way to invoke no-inlining, and a warning if I try to use it with a compiler for which I haven't defined its use. You don't really need the macro; you could use the gcc-dependent syntax - I just favor a simpler (and portable) symbol that could be defined for any compiler's no-inline syntax.

Great idea. I was thinking of doing the same to avoid the ugly noinline attribute string.

Would the drive-by down-voter care edify the rest of us with his/her reasons why this answer fails to address "Any idea how to prevent function inlining?"


text:
Changing Baud Rate not working
I have copied this code from Github :
 #include <Wire.h>
 #include <MPU6050.h>

MPU6050 mpu;

// Timers
unsigned long timer = 0;
float timeStep = 0.01;

// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;

void setup()
{
    Serial.begin(115200);
    //Serial.begin(9600);

    // Initialize MPU6050
    while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
    {
         //Serial.println("Could not find a valid MPU6050 sensor, check
               wiring!");
     }

     // Calibrate gyroscope. The calibration must be at rest.
     // If you don't want calibrate, comment this line.
    //mpu.calibrateGyro();

     // Set threshold sensivty. Default 3.
     // If you don't want use threshold, comment this line or set 0.
      mpu.setThreshold(1);
   }

   void loop()
      {
       timer = millis();

      // Read normalized values
     Vector norm = mpu.readNormalizeGyro();

     // Calculate Pitch, Roll and Yaw
      pitch = pitch + norm.YAxis * timeStep;
       roll = roll + norm.XAxis * timeStep;
       yaw = yaw + norm.ZAxis * timeStep;

         // Output raw
      //Serial.print(" Pitch = ");
         Serial.print(pitch);
           Serial.print(":");
        //Serial.print(" Roll = ");
     Serial.print(roll);
        Serial.print(":");
       //Serial.print(" Yaw = ");
        Serial.println(yaw);

           // Wait to full timeStep period
      delay((timeStep*1000) - (millis() - timer));
     }

Now the question is, whenever I try to change the baud rate Serial Monitor becomes empty.
How can this be resolved?
Some screen-shots :

Stuck!!!

where do you change the baud rate?

I changed, but nothing happened so I commented that line

please see there is a line //Serial.begin(9600);

And did you also change the baud rate in the serial monitor?

Yes, I have added screenshots ...

You are not very much clear but these are the possible reasons for your problem.

You are using a while loop in your setup() function in your code. Your code might get stuck in there that's why you are not able to see pitch and roll. Try removing comment from the Serial.begin function over there.
After Changing baudrate in your code please make sure you are changing it on your serial monitor as well.

I have changed the  baud rate both in code & serial monitor. After printing 6/7 values it gets stuck. I have no idea whats going on   :'(

I also added a Serial.println("ok") at the last line of Setup that worked.

can you provide screenshot of your serial monitor.

I have added screenshots, please see

last thing that i understand that can make issue is that delay function in the end, try setting some default value in that like 5 or 10 then check if window still stucks

I tried that too, but didn't working with 115200 baud rate

maybe it's because of the library

i think so as i tried your code with mpu part commented and code works well. Try this library example

Thanks, I was trying to move and rotate an object in Unity using Arduino as input . Now I have this , rotation is perfect but, position isn't . Maybe you can help me with that.


text:
UART ESP and MEGA2560
Could someone help me with some suggestions please?
Using ESP8266 and MEGA2560 on UART interface i want to display the message received on the mega serial to the LCD connected to it on i2c. The problem is that the LCD shows some strange unknown character and the serial monitor corresponding to mega shows this :
LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on

when it should display this:
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF

the code for ESP is this:
int pinLed = 16;
void setup()
{

 Serial.begin(115200);
 Serial.begin(115200);
 pinMode(16,OUTPUT);
 delay(500);
}

void loop()
{

digitalWrite(16,HIGH);
Serial.print("LED on\n");
delay(5000);

digitalWrite(16,LOW);
Serial.print("LED OFF\n");
delay(5000);

}

the code for mega is this:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include<SoftwareSerial.h>
LiquidCrystal_I2C lcd(0x3F,20,4);

void setup()
{

  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  while (!Serial)
  {

    Serial.print("Attempting to connect! ");
    Serial.print("Trying again...");
  }
}

  void loop()
{

  if (Serial.available()>0)

  {
    char c = Serial.write(Serial.read());
    Serial.print(c);
    lcd.print(c);
  }
}

Solution to your problems.

Use println instead of print.
Change char c = Serial.write(Serial.read()); to char c = Serial.read();

Use:
println *emphasized text*

instead of
print *emphasized text*

use println instead print

why should they use println?


text:
Cannot write pin LOW
All the other examples I've seen have had coding errors where they set a pin LOW in a loop with no delay so that it goes high again right away - but this problem is different, and probably something obvious.
I set up a breadboard memory (EEPROM or similarly-pinned flash) programmer (ala BenEater and many similar sources) using two 74**595s for the first 15 address bits as well as the OE# bit in the MSB spot, and the nano digital outputs for the 8 data bits as well as the WE# (write-enable) bit.  The data, address, and OE# pins set correctly every time.  The WE# pin, however, stays HIGH forever once it goes HIGH.
I have tried every digital pin for WE#, I have tried every analog pin with an analogWrite.  I have tried now three different memory chips and three Arduino Nanos that I've used successfully elsewhere, but still no success.
The only thing I can assume is that the WE# pin on the memory ICs somehow is keeping the line high, but I can't for the life of me figure out how that's possible.
Code and logic analyzer example:
/*
 EEPROM Programmer
 In this case, programming a SST39SF010A
 55ns read access, 22us write time
 Software Data Protection to write:
 (0x5555, 0xAA)
 (0x2AAA, 0x55)
 (0x5555, 0xA0)
 */

#define SHIFT_DATA  13
#define SHIFT_CLK   12
#define SHIFT_LATCH 11
#define ROM_D0      2
#define ROM_D1      3
#define ROM_D2      4
#define ROM_D3      5
#define ROM_D4      6
#define ROM_D5      7
#define ROM_D6      8
#define ROM_D7      9
#define WRITE_EN    10

void setAddress(int address, bool outputEnable) {
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, ((address >> 8) | (outputEnable ? 0x00 : 0x80))); // High bits
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address); // Low bits
  digitalWrite(SHIFT_LATCH, LOW);
  digitalWrite(SHIFT_LATCH, HIGH);
  digitalWrite(SHIFT_LATCH, LOW);
}

byte readROM(int address) {
  for (int pin = ROM_D0; pin <= ROM_D7; pin++) {
    pinMode(pin, INPUT);
  }
  byte data = 0;
  setAddress(address, /* outputEnable */ true);
  // Read each pin
  for (int pin = ROM_D7; pin >= ROM_D0; pin--) {
    data = (data << 1) + digitalRead(pin);
  }
  return data;
}

void printContents() {
  for (int base = 0; base < 256; base += 16) {
    byte data[16];
    char buf[80];
    for (int offset = 0; offset < 16; offset++) {
      data[offset] = readROM(base + offset);
    }
    // buffer (string) to hold the formatted data
    sprintf(buf, "%03x:  %02x %02x %02x %02x %02x %02x %02x %02x  %02x %02x %02x %02x %02x %02x %02x %02x",
      base, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
      data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]);
    Serial.println(buf);
  }
}

void writeROM(int address, byte data) {
  for (int pin = ROM_D0; pin <= ROM_D7; pin++) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
  }
  setAddress(address, /* outputEnable */ false);
  for (int pin = ROM_D0; pin <= ROM_D7; pin++) {
    digitalWrite(pin, (data & 0x01));
    data = (data >> 1);
  }
  digitalWrite(10, LOW);
  delayMicroseconds(10);
  digitalWrite(10, HIGH);
  delay(1);
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(56700);
  Serial.flush();

  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);

  // Set pull-up resistor
  digitalWrite(WRITE_EN, HIGH);
  pinMode(WRITE_EN, OUTPUT);

  Serial.println();

  writeROM(0x5555, 0xAA);
  writeROM(0x2AAA, 0x55);
  writeROM(0x5555, 0xA0);
  for (int i = 0; i < 256; i++)
  {
    writeROM(i, i % 13);
  }
  printContents();
}

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

http://forum.arduino.cc/index.php?topic=68753.0

@MichaelT I am not seeing how that link is equivalent.  The pin in my project is not left floating.  It is connected and does not respond to commands to set to LOW.

Does the pin go low when disconnected from the memory chip?

@MaximilianGerhardt Good question - when it isn't connected, it stays low.

@MaximilianGerhardt Well, sometimes it just takes one rational question, thank you.  Somehow it works on my Arduino Uno but none of my Nanos...  I will just keep going from here and try to trouble shoot the nanos later

Are you sure you don't have a case of both chips trying driving the OE line (in opposite directions), destroying the output driver? What is the voltage of WE# on the memchip without the pin being disconnected? Is floating? Can you manually ground the pin and see a 0V on the multimeter? Maybe also see https://electronics.stackexchange.com/a/107190/158783

@MaximilianGerhardt Ding ding.  Not sure how, but somehow OE and WE are shorted on my breadboard.  It was the common factor, the memory have the same pinouts so I just swapped them.  Everything was driving the same channels high, thus no way to bring it low.  Also I think it killed my Uno D10 pin... :-(  But thanks for the help - I wasn't even thinking of that and I have no idea how two channels so far apart on a breadboard are shorted together, but my DMM reads 0.01 Ohms between them.  Now it's time to break apart a breadboard...


text:
Strange behaviour with WS2812B RGB LED Strip
I tried to use a RGB LED strip, following a guide.
I connected the voltage pin to the Arduino UNO 5v pin, the ground pin to the GRN pin and I used the pin 5 for DIN.
I used this image as reference:

I tried two different libraries, with the first one, the FAST LED, I used this code:
#include <FastLED.h>

#define LED_PIN     5
#define NUM_LEDS    15
#define BRIGHTNESS  64
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];

#define UPDATES_PER_SECOND 100

CRGBPalette16 currentPalette;
TBlendType    currentBlending;

extern CRGBPalette16 myRedWhiteBluePalette;
extern const TProgmemPalette16 myRedWhiteBluePalette_p PROGMEM;

void setup() {
    delay( 3000 ); // power-up safety delay
    FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
    FastLED.setBrightness(  BRIGHTNESS );

    currentPalette = RainbowColors_p;
    currentBlending = LINEARBLEND;
}

void loop()
{
    ChangePalettePeriodically();

    static uint8_t startIndex = 0;
    startIndex = startIndex + 1; /* motion speed */

    FillLEDsFromPaletteColors( startIndex);

    FastLED.show();
    FastLED.delay(1000 / UPDATES_PER_SECOND);
}

void FillLEDsFromPaletteColors( uint8_t colorIndex)
{
    uint8_t brightness = 255;

    for( int i = 0; i < NUM_LEDS; i++) {
        leds[i] = ColorFromPalette( currentPalette, colorIndex, brightness, currentBlending);
        colorIndex += 3;
    }
}

void ChangePalettePeriodically()
{
    uint8_t secondHand = (millis() / 1000) % 60;
    static uint8_t lastSecond = 99;

    if( lastSecond != secondHand) {
        lastSecond = secondHand;
        if( secondHand ==  0)  { currentPalette = RainbowColors_p;         currentBlending = LINEARBLEND; }
        if( secondHand == 10)  { currentPalette = RainbowStripeColors_p;   currentBlending = NOBLEND;  }
        if( secondHand == 15)  { currentPalette = RainbowStripeColors_p;   currentBlending = LINEARBLEND; }
        if( secondHand == 20)  { SetupPurpleAndGreenPalette();             currentBlending = LINEARBLEND; }
        if( secondHand == 25)  { SetupTotallyRandomPalette();              currentBlending = LINEARBLEND; }
        if( secondHand == 30)  { SetupBlackAndWhiteStripedPalette();       currentBlending = NOBLEND; }
        if( secondHand == 35)  { SetupBlackAndWhiteStripedPalette();       currentBlending = LINEARBLEND; }
        if( secondHand == 40)  { currentPalette = CloudColors_p;           currentBlending = LINEARBLEND; }
        if( secondHand == 45)  { currentPalette = PartyColors_p;           currentBlending = LINEARBLEND; }
        if( secondHand == 50)  { currentPalette = myRedWhiteBluePalette_p; currentBlending = NOBLEND;  }
        if( secondHand == 55)  { currentPalette = myRedWhiteBluePalette_p; currentBlending = LINEARBLEND; }
    }
}

void SetupTotallyRandomPalette()
{
    for( int i = 0; i < 16; i++) {
        currentPalette[i] = CHSV( random8(), 255, random8());
    }
}

void SetupBlackAndWhiteStripedPalette()
{
    fill_solid( currentPalette, 16, CRGB::Black);
    currentPalette[0] = CRGB::White;
    currentPalette[4] = CRGB::White;
    currentPalette[8] = CRGB::White;
    currentPalette[12] = CRGB::White;

}

// This function sets up a palette of purple and green stripes.
void SetupPurpleAndGreenPalette()
{
    CRGB purple = CHSV( HUE_PURPLE, 255, 255);
    CRGB green  = CHSV( HUE_GREEN, 255, 255);
    CRGB black  = CRGB::Black;

    currentPalette = CRGBPalette16(
                                   green,  green,  black,  black,
                                   purple, purple, black,  black,
                                   green,  green,  black,  black,
                                   purple, purple, black,  black );
}

const TProgmemPalette16 myRedWhiteBluePalette_p PROGMEM =
{
    CRGB::Red,
    CRGB::Gray,
    CRGB::Blue,
    CRGB::Black,

    CRGB::Red,
    CRGB::Gray,
    CRGB::Blue,
    CRGB::Black,

    CRGB::Red,
    CRGB::Red,
    CRGB::Gray,
    CRGB::Gray,
    CRGB::Blue,
    CRGB::Blue,
    CRGB::Black,
    CRGB::Black
};

and with the second library, Adafruit_Neopixel
#include <Adafruit_NeoPixel.h>
#define PIN 5
#define NUM_LEDS 15
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

// *** REPLACE FROM HERE ***
void loop() {
  RGBLoop();
}

void RGBLoop(){
  for(int j = 0; j < 3; j++ ) {
    // Fade IN
    for(int k = 0; k < 256; k++) {
      switch(j) {
        case 0: setAll(k,0,0); break;
        case 1: setAll(0,k,0); break;
        case 2: setAll(0,0,k); break;
      }
      showStrip();
      delay(3);
    }
    // Fade OUT
    for(int k = 255; k >= 0; k--) {
      switch(j) {
        case 0: setAll(k,0,0); break;
        case 1: setAll(0,k,0); break;
        case 2: setAll(0,0,k); break;
      }
      showStrip();
      delay(3);
    }
  }
}
// *** REPLACE TO HERE ***

void showStrip() {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.show();
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   FastLED.show();
 #endif
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.setPixelColor(Pixel, strip.Color(red, green, blue));
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   leds[Pixel].r = red;
   leds[Pixel].g = green;
   leds[Pixel].b = blue;
 #endif
}

void setAll(byte red, byte green, byte blue) {
  for(int i = 0; i < NUM_LEDS; i++ ) {
    setPixel(i, red, green, blue);
  }
  showStrip();
}

I don't know why, but only some of the leds in the strips make lights and only blue lights. How can I fix this problem?
I also tried to change the Din pin using 4, 5 and 6, but nothing changed.
EDIT
I found that all my led were broken... I bought a new strip and now I have a prototype perfectly working using any of the code above. Thanks for helping me

How long is the strip? How many LEDs? Did you calculate how much current it can draw? How are you powering your Arduino?

@EdgarBonet the strip has 15 leds and I defined the number in the global variables.I'm powering Arduino using USB cable. Thanks for your reply

15 LEDs, all on full bright, need 15 x 3 x 20mA =  900mA.  USB can only supply 500mA. Try putting a Serial.print in setup() and see if the Arduino is resetting.

Is Serial.print without params in input?

Serial.begin(9600);   Serial.println ("reset");

@CrossRoadsI tried but nothing changed.. Do you have any other suggestions?

In the first sketch you use
#define LED_TYPE    WS2811

While you have WS2812
Each led strip type has different timings, so it can occur that some LEDs will flash, or are on or off while they should not be, if the wrong model is selected.
Probably the first LEDs work better than later ones.

WS2811 data sheet https://cdn-shop.adafruit.com/datasheets/WS2811.pdf vs WS2812 datasheet https://cdn-shop.adafruit.com/datasheets/WS2812.pdf  WS2812 has built in LEDs and can run at a slightly faster speed.

I tried what you proposed but nothing changed..

What makes you sure replacing the LED strip was the solution? I suggest running the LED strip from the Arduino +5V is a likely problem (too much current drawn) and using a different LED strip you've just been lucky that it works now.
Try with a separate power supply for the LEDs but connect grounds together. If you don't have another 5V power supply which can supply at least 1 Amp, try limiting the brightness and/or number of LEDs in software to see if it works and if so, then try with the original strip.

"What makes you sure replacing the LED strip was the solution?" I bought exactly the same model, the same RGB led strip and now it works perfectly. I also tried with a 5V battery and with the old strip the result was the same, only four led worked.


text:
Fading led with push button
I need to make for school a project. That when i hold a button it fades. But when you let go the button it needs to stop immediately. But when i you hold the button again it needs to start again with fading but the brightness needs to start from 0. I have a program but when i press again it just starts from the previous brightness. Pls help. This is my code:
int led = 9;
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
    pinMode(led, OUTPUT);
}
void loop() {
  int val = digitalRead(2);
  Serial.println(val);
if (val==HIGH){
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount; }
  delay(100);
}
else{

  digitalWrite(9, LOW);
}
}

The main problem is you have to reset brightness to 0 when the switch is LOW. Btw, I did not test the sketch, only compiled it.
int led = 9;
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
    pinMode(led, OUTPUT);
}
void loop() {
  int val = digitalRead(2);
  Serial.println(val);
if (val==HIGH){
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount; }
  delay(100);
}
else{

  digitalWrite(9, LOW);
  brightness = 0;    // Restart with brightness 0
}
}

Some other improvements result in:
#define LED_PIN      9
#define DELAY_TIME 100
int brightness = 5;
int fadeAmount = 5;

void setup() {
   Serial.begin(9600);
   pinMode(LED_PIN, OUTPUT);
}

void loop() {
  int switchButton = digitalRead(2);
  Serial.println(switchButton);

  if (switchButton == HIGH) {
    analogWrite(LED_PIN, brightness);
    brightness += fadeAmount;
    if ((brightness <= 0) || (brightness >= 255)) {
      fadeAmount = -fadeAmount;
    }
    delay(DELAY_TIME );
  }
  else {
    digitalWrite(LED_PIN, LOW);
    brightness = 0;    // Restart with brightness 0
  }
}

Explanation

Always indent your code (so that { and } are clear, notice each new { increases the indentation by two spaces, each } decreases the indentation by two spaces.
For values that do not change use a #define. This prevents (in this case) a few bytes not be stored in valuable memory space. Especially if you would use arrays this is important.
You used 9 in digitalWrite(9, LOW); which was probably a mistake, always use defines wherever possible. I also would use #define DELAY_TIME 100 instead of the hardcoded 100 value.
I addes some spaces before/after values (like switchButton == HIGH). It doesn't matter if you do or not, but be consequent.
Use good variable names (switchButton is more clear than val.
Use brightness += fadeAmount; instead of brightness = brightness + fadeAmount;; this is the normal way of increasing (or decreasing/multiplying/whatever) the value of a variable.
Use ( and ) in non trivial if statements like if ((brightness <= 0) || (brightness >= 255)), this could save you hours of searching in case you ever make a mistake (in this case there is no functional change).

Good luck with your project.

oh yeah thank you very much. i will test it soon.

Wow, a bounty of good coding advice! (Voted)