text:
esp8266 not responding to the AT commands
I am integrating Arduino Uno with the WiFi module ESP8266.  I have already made the connections between the ESP8266 and the Arduino Uno which are :
txd uno -> rxd esp8266
rxd uno -> txd esp8266
gnd uno -> gnd esp8266

The VCC and chid pind of ESP8266 are connected to an external supply of voltage 3.3V and 160mA current. The code is getting uploaded onto the Arduino and the ESP8266 is also getting powered on.But i am facing a problem while i send the AT commands on the serial monitor. It is not responding even though the red led is on constantly and when i press enter after sending the command , the blue led blinks for a few seconds.
Do i have to update the firmware of the ESP8266?

possible duplicate of esp 8266 not getting programmed

It is not a duplicate of the above question.In that the led lights are not glowing but here the esp8266 is not responding to the AT commands.

It is a duplicate since you have made the same basic error in your wiring and are trying to incorrectly communicate in the same way.

Could you explain to me what is the basic error which i am making?

You cannot use the TX/RX pins both for communication with the PC AND communication with an external module at the same time. You've effectively got the ESP wired backwards for communication with the serial monitor, but if you turn it around it would be wired backwards for communication with the Arduino. If you want to communicate through the serial terminal you will have to connect the ESP through different pins and pass the data through using SoftwareSerial.

I don't think you should connect the TX of the arduino directly to the RX of the ESP, as the ESP only accepts 3.3v signals, while the Uno uses 5v signals.

160mA is barely enough to power the ESP.  That chip can draw up to 1A under the right conditions if i remember correctly.

Please save this chip from a horrible death!  Get your voltages down to 3.3v on the signal pins, or you will kill it!

I have brought down the voltages to 3.3V by using a voltage divider.It is still having the same problem.

I am facing the same problem. I used Arduino due for communicating with esp8266. I have used serial1 for communicating with esp. after booting , whatever I transmit to esp , the same characters are returned to me. The esp itself looks fine as its SSID appears and I manage to connect it through wifi. can any one help in this regard.

I had same problem. It helped to connect GNDs of both power supplies namely the one powering the arduino and the 3.3V one powering the ESP8266.

Okay, I'll just summarize the stuff I've seen in the comments and answers. It's quite a basic issue? You'll find a lot resources on it on the web.
Current (draw of chip too high?):
Wireless communication can take a lot of current. You should have a good power supply. Arduino usually can't supply enough current. Check the datasheet of the chip to see it max current draw.
Rx/Tx (Wiring):
Be sure you send through the Tx pin, into the Receive (Rx) pin of the other device.
Also, you can't use the same Tx pins for USB communication AND to connect to the ESP, that basically won't work.
Voltage (3.3V vs 5V):
The arduino runs on 5V, but, the ESP on 3.3V you shouldn't want to mix these up.
It'll do in some cases. Putting 3.3V (Tx of ESP) on the Rx of arduino (5V) won't damage it. But the other way around is strongly discouraged. Use a logic level shifter or voltage divider between it.
Chip might be broken
If the chip isn't doing anything at all, you should take in consideration that it's possible the chip is broken... I've spent too many hours on debugging my code while the chip simply wasn't working. Also after having applied 5V to the ESP8266, this becomes quite likely.

I have taken into consideration all your solutions and done these things : 1. i am using a battery pack as a power supply and not the arduino. 2. i am using different pins for communicating between the usb and for communicating with the ESP. 3.i have connected a voltage divider circuit and brought down the voltage to 3.3V while connecting the tx of arduino to rx of esp. But i am still not able to receive anything from the ESP.

If you used 5V logic on the ESP you might've killed it. Are you sure the chip works?

We had a similar issue and landed up spending a lot of time figuring out what was going wrong, the following certainly helped us resolve the issue:

We set the Baud rate of the Serial communication to 1200. This started showing the responses from ESP correctly with no / minimal junk
We set the baud rate of communication with ESP to 115200. This ensured that the ESP received correct commands.
We ensured that each command we send is terminated by a CR for e.g. ESP8266.println(espCmd + "\r"); // where ESP8266 is SoftwareSerial ESP8266 (rxPin, txPin);
Also, powering the ESP module with 5V gave no responses from ESP. When we powered it with 3.3V only then it started to provide any response - initially response looked like junk due to mismatched baud settings.

Hope this helps.
(Sometime you may need to use both \r\n....)
Regards

But surely supplying the correct voltage to the board (3.3v) and level shifting the rx and tx lines so the ESP gets 3.3v and the Arduino gets 5v would work much better.

Even I faced a similar problem , I was Abel to communicate using AT until I uploaded another program on to the board ,that is initially all esp boards come with the AT response firmware Once you upload ur code or program if I'm not wrong I guess it replaces it so you won't get any response
That was my personal experience using all sorts of esp8266 boards (01, nodeMCU ) etc
As I'm still learning plz correct me if I have projected it in the wrong way
Thanks

Seems like you didnt used any type of voltage divider or level shifter between the Arduino Tx -> ESP8266 RX Line. The ESP8266 isnt really 5V friendly. Too Bad the Arduino outputs 5V on all of it Pins.
You could still try it With a Voltage Divider using 2 Resistors or a level Shifter in hope it works. Elsewise With a 3.3V USB-> UART Module or get a New ESP8266

I was thinking that we only need a supply of 3.3v.Dint know that there has to be a voltage divider between the pins also.Do we need the voltage divider only between the arduino tx-> esp 8266 rx pins and not between the arduino rx -> esp 8266 tx?

Nope. The TX pin sends data out. That means the voltage is given by the Microcontroller. That means the Arduino Transmit Pin is 5V, which is Bad for the ESP, while the Transmit Pin of the ESP is 3.3V, With which the Arduino has no Problem to work With. You also need to remember these things when you work With screens vor Sensors. Always read the dataheet and search for the maximum voltage in the io ( 90% of the time you can search for Vio)

I have taken into consideration your solutions and done these things : 1. i am using a battery pack as a power supply and not the arduino. 2. i am using different pins for communicating between the usb and for communicating with the ESP. 3.i have connected a voltage divider circuit and brought down the voltage to 3.3V while connecting the tx of arduino to rx of esp. But i am still not able to receive anything from the ESP.

You missed something bro!
Arduino          ESP8266
Rxd       ->     Txd
Txd       ->     Rxd
3.3 V     ->     VCC
GND       ->     GND
3.3 V     ->     CH_PD

All above is right! Few days back, it was working. Suddenly, it stopped working but red led on it still lights.


text:
Control Speed of DC FAN Using Arduino PID Library
I want to make a circuit that control speed of DC fan Using Arduino PID Library to get thing at specific temperature.

The circuit looks like this but can be changed, The dc fan motor connected to PWM 3 and thermistor connected with pin A0.
The thermistor check the temperature of a device that heated by nearby heater so fan cools the device to get the specific temperature.
Case 1
When Heater not running, the thermistor value in Serial monitor 0-1023, When fan not running it gives 1023 and when fan runs at full speed it gives about 0.
Case 2
But when heater is running the values of thermistor has been changed and when fan not running it gives 1023 and when fan runs at full speed it gives about 500.
I want to set a point 650 from thermistor value(INPUT Value), and fan speed have to adjust using pid so temperature adjusted and the thermistor gives 650 value.
Sample PID code
 #include <PID_v1.h>
//Define Variables we'll be connecting to double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp=4, aggKi=0.2, aggKd=1;
double consKp=1, consKi=0.05, consKd=0.25;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);
void setup()
{
  Serial.begin(115200);
  //initialize the variables we're linked to
  Input = map(analogRead(0), 0, 1023, 255, 0);
  Setpoint = 650;
  myPID.SetOutputLimits(0, 255);
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}
void loop()
{
  int sensorValue = analogRead(0);
  Input = map(analogRead(0), 0, 1023, 255, 0);
    double gap = abs(Setpoint-Input); //distance away from setpoint
  if(gap<10)
  {  //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
     //we're far from setpoint, use aggressive tuning parameters
     myPID.SetTunings(aggKp, aggKi, aggKd);
  }
  myPID.Compute();
  analogWrite(3,Output);
  Serial.println(sensorValue);
}

What changes have to done in code so we can set point from input values?
And
Please help me so this code works for me.

You can't connect a motor directly to an output pin (unless it's a really small motor). You also need to a flyback diode to the motor. My guess is that the motor is generating a lot of "noise" on the power rail, leading to weird analogRead values.

Two thing that may be helpful.
First make sure you have a common ground. For instance for you transistor you are using separate power from the arduino and 12 volt source. Connecting the two ground of the arduino and the power supply may resolve this for you.
The other thing is it is often times helpful to put a capacitor across the DC motor to help with voltage fluctuations.

But the grounds are connected in the diagram...

First try using external power source to power the motor, as only  very small motors can be connected to an Arduino's power source.(Basically, the Motor is using most of the power, leaving too little power for the Arduino to operate properly)
If that fails, change the code(I will give sample code by tomorrow, if you cannot find one yourself)-maybe use a PWM signal instead of trying PID, as it is much simpler and give very little room for error.
And also, don't forget the fly back diode mentioned by Gerben.

you do not read full question , i know the output of dc motor is always a PWM Signal for speed Controlling. i want to use PID Library to detect error between Set Point and current temperature value and change speed of motor according to that value.

I knew that you obviously knew that output to a DC motor is always a PWM signal, I meant to tell you to leave the PID library and write your own code so that it acts like PID.

I have tried that and it works easily enough.

link

There are some issues with your map command.
For example, you are reading the thermistor value using analogRead(A0), which has a return range from 0 to 1023. After that you attempt to use map() to change this value to 0 - 255 but use the wrong syntax. The correct syntax for this command is Input = map(analogRead(0), 0, 1023, 0, 255);. However, I can't see the reason for that because you are reading values 0-1023, change it to 0-255, but set point is 650. So you never get setpoint because maximum is 255.
Try use as input just analogread(0). There is no reason to change input into PWM range and output is for PID library in PWM range as a default so you can send output direct to motor pin. Of course use some H-bridge or something like that.

//Now it will work
//  https://arduino.stackexchange.com/questions/9731/control-speed-of-dc-fan-using-arduino-pid-library

#include <PID_v1.h>
double Setpoint, Input, Output;  //not there in original sketch
//Define Variables we'll be connecting to double Setpoint, Input, Output;
//Define the aggressive and conservative Tuning Parameters
double aggKp = 4, aggKi = 0.2, aggKd = 1;
double consKp = 1, consKi = 0.05, consKd = 0.25;
//double consKp=2, consKi=5, consKd=1;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, REVERSE);
void setup()
{
  Serial.begin(9600);
  //initialize the variables we're linked to
  // Input = map(analogRead(0), 0, 1023, 255, 0);

  //int val = analogRead(0);
  //val = map(val, 0, 1023, 0, 255);
  // analogWrite(9, val);

  Setpoint = 100;
  myPID.SetOutputLimits(0, 255); //MIN,MAX
  //turn the PID on
  myPID.SetMode(AUTOMATIC);  // MANUAL
  myPID.SetControllerDirection(REVERSE);  // DIRECT
}
void loop()
{
  int sensorValue = analogRead(0);
  Input = map(sensorValue, 0, 1023, 0, 255);

  double gap = abs(Setpoint - Input); //distance away from setpoint
  if (gap < 10)
  { //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
    //we're far from setpoint, use aggressive tuning parameters
    myPID.SetTunings(aggKp, aggKi, aggKd);
  }

  myPID.Compute();
  analogWrite(3, Output);
  Serial.print(" PWM = ");
  Serial.print(Output,0);
  Serial.print("       sensor value =  ");
  Serial.print(sensorValue);
  Serial.print("       Input =");
  Serial.println(Input,0);
}

It may be better to not use map(), as it will give trouble between float and int variable usage - do it manually in the code.

This is both a comment rather than an answer, and also erroneous.  Arduino's map() in an integer function.  It is perfectly legitimate to initialize a floating point variable with an integer value.

source: Stack Exchange

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

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

sort: votes


text:
How to calculate voltage?
I want to check each cell voltage using arduino.
and how to calculate dc current using CT Sensor using Arduino?

Is it a Mini or a Leonardo?

You have two problems here:

How to take 24 readings on an Arduino with only 6 analog inputs.
How to get the voltage in the range of 0 to 5 volts.

To take 24 readings you can use an analog multiplexer or two. For example the 74HC4051 (8 channels) or the 74HC4067 (16 channels). With both of those you could handle 24 channels.

To read the voltages you could successively read each cell, relative to ground (eg. the first one should be 2 V, the second should be 4 V, and so on up to 48 V).
Cells 1 and 2 are fine, they are lower than 5 V. Cells 3 to 24 are not. You need to set up a voltage divider to divide down the voltage into the range 0 to 5.
The formula for a voltage divider is:
Vout = Vin * R2/(R1+R2)

Let's make R1 to be 10k ohms, and solve for R2 (given that we want Vout to be 5).
R2 = Vout * R1/(Vin - Vout)
R2 = 5 * 10000 / (Vin - 5)

Plugging that into a spreadsheet we get:
Vin    R
6  50000
8  16667
10 10000
12  7143
14  5556
16  4545
18  3846
20  3333
22  2941
24  2632
26  2381
28  2174
30  2000
32  1852
34  1724
36  1613
38  1515
40  1429
42  1351
44  1282
46  1220
48  1163

These aren't particularly easy resistor values to work with, so we'll use standard values and calculate what the output voltage should be (with the spreadsheet):
Vin   R   volts   Scale
2
4
6   47000 4.9474  1.2128    <--- R2 is 47 k
8   16000 4.9231  1.6250    <--- R4 is 16 k
10  10000 5.0000  2.0000
12   6800 4.8571  2.4706
14   5100 4.7285  2.9608
16   4300 4.8112  3.3256
18   3600 4.7647  3.7778
20   3300 4.9624  4.0303
22   2700 4.6772  4.7037
24   2400 4.6452  5.1667
26   2200 4.6885  5.5455
28   2000 4.6667  6.0000
30   2000 5.0000  6.0000
32   1800 4.8814  6.5556
34   1600 4.6897  7.2500
36   1600 4.9655  7.2500
38   1500 4.9565  7.6667
40   1300 4.6018  8.6923
42   1300 4.8319  8.6923
44   1200 4.7143  9.3333
46   1200 4.9286  9.3333
48   1100 4.7568 10.0909

The "Scale" column will be explained in a moment.

Now we are ready to make up a circuit along these lines:

I haven't shown all the battery cells here - I don't have that much energy! But the principle is the same.

The 2V and 4V inputs we can read directly. From 6V upwards we need to apply the scaling factor from the voltage divider network.
That is shown in the "Scale" column above.
The formula for the voltage on the pin is:
float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

So assuming Vref is 5V, and you have a reading of 512, then you apply it like this:
 ( 512  + 0.5 ) / 1024.0 * 5 = 2.502 volts

Now you multiply by the scale factor above, so if this was the 34 V input, the scale factor would be 7.25, and the voltage from the battery would be:
2.502 * 7.25 = 18.14  volts

The stage is now set to work out each voltage:

Use the multiplexer "select" pins to choose one of the battery inputs
Take an analog reading
Scale it by the appropriate amount from the table
Work out what the charge in the cell is (by comparing it to the previous one)

For example, if the first cell read 1.9V and the second cell read 3.85V then you know that the difference is 3.85 - 1.9 which is 1.95 volts.

Thanks Nick for your great answer...!! :) Can you help me to calculate dc current using CT Sensor using Arduino?

I don't know much about CT sensors, but does a page like CT sensors - Interfacing with an Arduino not help?

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


text:
Control Android Camera using Arduino over Bluetooth
I want to Control Android Mobile Camera shutter using Arduino over Bluetooth. So i can click photos using arduino.
I have HC-05 Bluetooth Module and Arduino Nano/Arduino leonardo.

The Connection as shown in figure.
The Android mobile successfully connected to Bluetooth Module but i am not found any code to control camera or any button on android mobile.

You'll need an Android APP to interface with the bluetooth and receive instructions to control the camera. Maybe the play store has something. If not, you'll have to learn Android programming.

Is there any code available which can control android mobile volume buttons from arduino??

What have volume buttons got to do with anything?

Volume buttons can also use for camera shutter, so if arduino can control volume buttons then it also use as camera shutter.

I think you don't understand how things work. An app may read the buttons and use them to do things like activate the shutter, but you cannot "control" a button from inside software. A button is an external physical thing.

Did you look on the play store for anything suitable? If you didn't find anything then chances are there is nothing. So you will have to learn Android programming. I am sure there are plenty of bluetooth examples, and plenty of camera examples. Your task will be to work out how to combine the two into a custom app. And this isn't the place for that, since it has nothing to do with Arduino.

Yes i already search on play store and there are nothing related to this. That's why i am asking here, Because i am not a android programmer.

I think those cheap BT shutter buttons act like a keyboard, and send the spacebar keycode (if I remember correctly)

I am trying out Camera Pro. It allows shutter control on Android over Bluetooth. I just got an Uno R3 and and HC-05 so I have not wired it up to try it.
There are example sketch and detailed docs here.

Welcome to Stack Exchange. Link-only answers are generally considered not good because the link may disappear. Add some relevant info from the link to your question, please. Thank you and enjoy our site!


text:
How to add Ultrasonic Sensor to the board?
I am making an RC car , have combined the Arduino UNO R3 with the AR 293d, and pluged in the HC-SR04 sensor to the SRO4 hole at the left top corner in the below graph. However, besides one sensor  I would like to add three more HC-SR04 sensor.
Reference:
http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

The problems are
1) is the board sufficient to plug three more sensor ?
2) or what extra board I need if not sufficient and how to combine those board
2) also, can I plug in other hole?
Thanks for helping
Update: breadboard connection
So I have to get a stuff like this?
http://www.tandyonline.co.uk/small-solderless-breadboard.html
and one more question, sorry for begin newbie, there are many holes on breadboard, which hole I should connect those three sensor on it, and the hold I should connect the breadboard with the AR-293D board?
And for programming, is there any way to get the pin at the breadboard as I have read some program before, the pin is assign with a number?
Thanks again for helping.

If you are in doubt on how to use breadboards and perfboards check out this video with collin: https://www.youtube.com/watch?v=w0c3t0fJhXU I would recomend watching everything he made - he is fairly entertaining and going in a steady pace where everyone can follow.

1) Not really. You have so little space and you have to selder them. Try using wires
2) If you want it to be flexible use a sandard solderless breadoard on the center of the car and then with male-female jumperwires try connecting them.
3) The board has traces. That means some holes have a very specific purpose.
Updated:
On every breadboard the holes are connected verticaly. For example, in the image from your breadboard you posted 1A, 1B, 1C, 1D and 1E are connected together.
If you would like to have all of the 3 sensors better use wires and then atach them on to your breadboard.
Here is a picture:
https://www.dropbox.com/s/3ij4w6eytio8p08/Screen%2016-25-31.png?dl=0

Thanks a lot, then I go for a breadboard, please have a look at update question.


text:
Arduino Due upload firmware issue
I have Arduino Due on SAM3x8e. I'm on Ubuntu 14.04. Before today I uploaded firmware via terminal using those commands:
$ stty -F /dev/ttyACM0 speed 1200 cs8 -cstopb -parenb
$ /home/q/apps/devel/arduino/arduino-1.5.7/hardware/tools/bossac --port=ttyACM0 -U false -e -w -v -b /home/q/work/gk/j-v2/embedded/smib/Release/smib.bin -R

It was good, but now it stopped working. Bossac just hangs up '-d' displays nothing. That is all.
I downloaded arduino IDE 1.6.5, but this doesn't matter. In ide's console I get
Sketch uses 11,000 bytes (2%) of program storage space. Maximum is 524,288 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyACM0
/home/q/.arduino15/packages/arduino/tools/bossac/1.3a-arduino/bossac -i -d --port=ttyACM0 -U false -e -w -v -b /tmp/build238086227206829290.tmp/AnalogReadSerial.cpp.bin -R

It sticks, no leds blinking on Arduino board. It seems it actually hangs up, due to it loads 99% of CPU... May be Ubuntu update caused this issue...?
dmesg
[ 5168.658692] usb 3-3: new full-speed USB device number 7 using xhci_hcd
[ 5168.676969] usb 3-3: New USB device found, idVendor=2341, idProduct=003d
[ 5168.676979] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[ 5168.676985] usb 3-3: Product: Arduino Due Prog. Port
[ 5168.676989] usb 3-3: Manufacturer: Arduino (www.arduino.cc)
[ 5168.676994] usb 3-3: SerialNumber: 75438313633351A07051
[ 5168.677225] usb 3-3: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[ 5168.677652] cdc_acm 3-3:1.0: ttyACM0: USB ACM device

syslog
Oct  4 21:49:01 4xybook kernel: [ 5356.553290] usb 3-3: new full-speed USB device number 8 using xhci_hcd
Oct  4 21:49:01 4xybook kernel: [ 5356.571623] usb 3-3: New USB device found, idVendor=2341, idProduct=003d
Oct  4 21:49:01 4xybook kernel: [ 5356.571635] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
Oct  4 21:49:01 4xybook kernel: [ 5356.571643] usb 3-3: Product: Arduino Due Prog. Port
Oct  4 21:49:01 4xybook kernel: [ 5356.571649] usb 3-3: Manufacturer: Arduino (www.arduino.cc)
Oct  4 21:49:01 4xybook kernel: [ 5356.571655] usb 3-3: SerialNumber: 75438313633351A07051
Oct  4 21:49:01 4xybook kernel: [ 5356.571923] usb 3-3: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
Oct  4 21:49:01 4xybook kernel: [ 5356.572506] cdc_acm 3-3:1.0: ttyACM0: USB ACM device
Oct  4 21:49:01 4xybook mtp-probe: checking bus 3, device 8: "/sys/devices/pci0000:00/0000:00:14.0/usb3/3-3"
Oct  4 21:49:01 4xybook mtp-probe: bus: 3, device: 8 was not an MTP device

lsusb
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 8087:07da Intel Corp.
Bus 001 Device 003: ID 064e:c336 Suyin Corp.
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 002: ID 152d:0567 JMicron Technology Corp. / JMicron USA Technology Corp.
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 008: ID 2341:003d Arduino SA
Bus 003 Device 002: ID 1a2c:0e24 China Resource Semico Co., Ltd
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Any help would be really appreciated.
Update
strace gives this.
execve("/home/q/apps/devel/arduino/arduino-1.5.7/hardware/tools/bossac", ["/home/q/apps/devel/arduino/ardui"..., "--port=ttyACM0", "-U", "false", "-e", "-w", "-v", "-b", "-d", "/home/q/work/gamekeeper/jackpot-"..., "-R"], [/* 78 vars */]) = 0
brk(0)                                  = 0x22a5000
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e385000
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=169535, ...}) = 0
mmap(NULL, 169535, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7f468e35b000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/usr/lib/x86_64-linux-gnu/libstdc++.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0 \266\5\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=979056, ...}) = 0
mmap(NULL, 3159040, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f468de61000
mprotect(0x7f468df47000, 2093056, PROT_NONE) = 0
mmap(0x7f468e146000, 40960, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0xe5000) = 0x7f468e146000
mmap(0x7f468e150000, 82944, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f468e150000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libgcc_s.so.1", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260*\0\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=90080, ...}) = 0
mmap(NULL, 2185952, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f468dc4b000
mprotect(0x7f468dc61000, 2093056, PROT_NONE) = 0
mmap(0x7f468de60000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x15000) = 0x7f468de60000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\320\37\2\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0755, st_size=1840928, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e35a000
mmap(NULL, 3949248, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f468d886000
mprotect(0x7f468da41000, 2093056, PROT_NONE) = 0
mmap(0x7f468dc40000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ba000) = 0x7f468dc40000
mmap(0x7f468dc46000, 17088, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7f468dc46000
close(3)                                = 0
access("/etc/ld.so.nohwcap", F_OK)      = -1 ENOENT (No such file or directory)
open("/lib/x86_64-linux-gnu/libm.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\20V\0\0\0\0\0\0"..., 832) = 832
fstat(3, {st_mode=S_IFREG|0644, st_size=1071552, ...}) = 0
mmap(NULL, 3166568, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f468d580000
mprotect(0x7f468d685000, 2093056, PROT_NONE) = 0
mmap(0x7f468d884000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x104000) = 0x7f468d884000
close(3)                                = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e359000
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e357000
arch_prctl(ARCH_SET_FS, 0x7f468e357780) = 0
mprotect(0x7f468dc40000, 16384, PROT_READ) = 0
mprotect(0x7f468d884000, 4096, PROT_READ) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f468e356000
mprotect(0x7f468e146000, 32768, PROT_READ) = 0
mprotect(0x7f468e387000, 4096, PROT_READ) = 0
munmap(0x7f468e35b000, 169535)          = 0
brk(0)                                  = 0x22a5000
brk(0x22c6000)                          = 0x22c6000
openat(AT_FDCWD, "/dev", O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC) = 3
open("/dev/ttyACM0", O_RDWR|O_NOCTTY|O_NONBLOCK) = 4
ioctl(4, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, {B9600 opost isig icanon echo ...}) = 0
ioctl(4, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, {B9600 opost isig icanon echo ...}) = 0
ioctl(4, SNDCTL_TMR_START or SNDRV_TIMER_IOCTL_TREAD or TCSETS, {B115200 -opost -isig -icanon -echo ...}) = 0
ioctl(4, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, {B115200 -opost -isig -icanon -echo ...}) = 0
nanosleep({0, 500000000}, NULL)         = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99992})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99994})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99996})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99997})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99997})
read(4, "", 1024)                       = 0
select(5, [4], NULL, NULL, {0, 100000}) = 1 (in [4], left {0, 99997})
read(4, "", 1024)                       = 0

It indefinitely polls the descriptor. select = 1 means there is a data, but read returns 0. It seems like something on lower level is broken... may be because of system update (

You could run bossac under strace and possibly see what it is doing when it hangs, but be prepared for a flood of data.  Are you able to either try that board on another computer, or try another similar board on this computer?

Which port are you using - the programming port or the native port?

@Chris Stratton I tried another board with the same result (

@Majenko Same result on both ports.

Have you tried erasing the board?

How exactly? if bossac -e, yes

From the man page for select() readfds will be watched to see if characters  become  available  for
reading  (more  precisely, to see if a read will not block; in particu‐
lar, a file descriptor is also ready on end-of-file) - probably the case since after the first call it starts returning effectively immediately with the timeout unused.  You might see if anything is odd in the serial port settings, or use lsof to see if anything else has the port open.  Trying on another machine (or live USB boot?) would be good too.

@Majenko I havn't seen 'erase' button before), I tried, unfortunately, it doesn't help

Hi Chris, I updated strace log, now it's from begining. lsof shows only bossac as port user. Under Ubuntu Live USB bossac returns "No device found". On another windows machine it works

Kernel update resolves the issue.
http://askubuntu.com/questions/681555/ubuntu-14-04-arduino-due-upload-firmware-issue


text:
Adrudio Due: How do MCU components USARTx & UART relate to board pins TXn/RXn?
I'm making USART support for SAM3x8e based Arduino Due board.
I looked into arduino source code, exactly
arduino-1.5.7/hardware/arduino/sam/variants/arduino_due_x/variant.cpp

and see that for Serial0 UART component is used, for Serial1 USART0 is used, for Serial2 - USART1 and for Serail3 - USART3. The USART2 is not even mentioned.

Why is this done that way?
I would like to realize what those comonents (USARTx & UART) are? Is UART is the subset of one of USARTs?
What is relation between USARTn & UART components and arduino board's TXn/RXn pins? Exactly, what pins are those component mapped to?

Thanx.


text:
Wifi strength Automation . Help. Noobie here

#include <ESP8266WiFi.h>
const char *SSID = "mr_lazy_boei";
const char *pass  = "usalusal";

WiFiClient client;

// Relay pin number
int ignition=2;
int self=0;

//   Return RSSI(Received Signal Strength Indicator) or 0 if target SSID not found
int32_t getRSSI(const char* target_ssid) {
 byte available_networks = WiFi.scanNetworks();

 for (int network = 0; network < available_networks; network++) {
   if (WiFi.SSID(network).compareTo(target_ssid) == 0) {     //stringOne.compareTo(stringTwo) < 0
     return WiFi.RSSI(network);
   }

 }
 return 0;
}

void setup() {
 Serial.begin(115200);
 delay(10);

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

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

pinMode(ignition,OUTPUT);
pinMode(self,OUTPUT);
}

void loop(){

int32_t rssi = getRSSI(SSID);

 // For debugging purpose only
 Serial.print("Signal strength: ");
 Serial.print(rssi);
 Serial.println("dBm");

 if (rssi > (-55) && rssi != 0) // if rssi is greater then -55 dbm or it's 0 dbm, then the light will turn
 {
   digitalWrite(ignition, LOW);
   Serial.println("ON");
}
else

{
 digitalWrite(ignition,HIGH);
 Serial.println("OFF");
}
if (rssi > (-55) &&rssi !=0)
{
 digitalWrite(self,LOW);
 delay(750);
 digitalWrite(self,HIGH);
 Serial.println("SELF OFF");

}

}

Above is my code written. As you can see, I have two variables: ignition and self. ignition works the way I want, but the self variable turns on and and then off. That is correct. But it again turns on because of void loop().
Let me explain further:
If wifi signal is strong the ignition should turn on and the self should turn on for less than a second and then turn off. It should not turn on again. When the signal goes weak the ignition turns off. Again, when signal gets strong the ignition turns on and I need self to turn on for not even a second and turn off.
I tried my best getting that. I tried moving it to void setup(), but that just works when I power up the device. After that it doesn't turn on or off. Please kindly help me. I know here I am having very talented brothers who would help me out on this issue.

If wifi signal is strong the ignition should turn on and the self should turn on for less than a second and turn off . It should not turn on again .... very confusing ... what is it in the second sentence?

@jstola i am sorry . Just imagine a car... First its ignition should turn on and remain on . Whereas the self motor should turn on for less than a second and turn back off .

In my program . The self turns on and off again and again.... It should only turn on and off once only . Thats it . It should not repeat again and again .

@jstola Sorry for messing things up .

I think for "self" you mean "starter motor"...?

yes you are right . @Majenko

So basically you want it so that when you walk up to your car the ignition turns on and the engine starts. When you walk away it all shuts off. When you walk back to the car it starts again? You need to implement a Finite State Machine to manage the different states the system can be in.

the translation from another language sure can mess things up ... lol

Yes you are right . I have managed to program it for ignition and it works perfectly . But i am getting issue in the self thing . It repeats again and again . I dont jave any good knowledge about finite state machine . Ill check it @Majenko

try to use description without redundant facts ... for example, in turn on for less than a second and turn off, the and turn off is redundant .... turn on, run for a second, then turn off is actually better because it is close to how the program would do it ... power on, pause, power off

Oops . I am sorry... Maybe i am not that good at explaining things up . But thanks to you for sparing time for me and understanding my issue . Now the one and only option is finite state machine or anything else can also be done ?

Can anyone use finite state machine in my program  for me ?

so, if you are driving down the highway at 120 km/h and your phone runs out of battery, then the engine should just shut down?

No . Its just for learning purpose .  I dont give permission to anyone to drive without the key plugged in  . And maybe as time passes i would ensure a lot of safety in it .

Now can you help me in my program ?  Wish i would have given more importance to programing earlier .. i would never end up lyk this

you could start by presenting properly formatted code ... have you actually looked at how your post looks?

You need to design your program using a Finite State Machine.
First start off by defining each state that your program can be in, and what is allowed to happen in each of those states.
For example:

IDLE

The only thing that is allowed to happen here is detecting the RSSI and deciding whether or not to start the engine.

IGNITION

The RSSI has got strong enough and you want to start the car. The only thing you want to do is turn on the ignition and wait a moment. Nothing more.

CRANK

Once you've waited a moment you can crank the engine. That means turning on the starter motor and waiting a moment.

RUNNING

Now the engine has started you can release the starter motor and leave the engine to idle. It's now that you want to start watching the RSSI gain.

STOP

The RSSI has dropped below your threshold, so now you can stop the engine.

IDLE

Now the engine's stopped you can go back to the start and idle looking for the RSSI to get high enough again.
These are all the states of a Finite State Machine. You move from state to state depending on different inputs or triggers.  One input is your RSSI value - or more strictly your RSSI value being above or below a threshold.  Another input is (less obviously) time. Waiting for some time to pass.
So you start in state 1. In that state all your program is doing is watching the RSSI. When that rises you move to state 2. At that point it performs whatever actions are needed (turn on the ignition) and record the time. When enough time has elapsed you move on to state 3, and do the same.
It could actually be simplified by compressing states 2 and 3 together:

Turn on ignition
Delay
Turn on starter motor
Delay
Turn off starter motor
Delay
Move to next state

You could then increase the complexity again a little (while increasing the safety) by adding extra steps when you're watching the RSSI. You can then check to see if the RSSI has been above (or below) the threshold for a certain amount of time before moving on to the next step:

IDLE - watching RSSI

If RSSI rises above threshold go to state 2.
Else stay in state 1

Record the time and keep watching the RSSI

If RSSI drops below threshold: Go back to 1.
If Enough time has passed: Go to state 3.
Else stay in state 2

Start the engine.

Go to state 4

RUNNING - watching RSSI

If RSSI falls below threshold go to state 5.

Record the time and keep watching the RSSI

If the RSSI rises above threshold: Go back to 4
If enough time has passed: go to state 6.
Else stay in state 5.

Stop the engine.

Go to state 1.

... etc ...

Thank youuuuuu!!! Ill try doing finite state machine right away ...

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


text:
Is an Ultrasonic Sensor or Infrared Sensor better for measuring distance (to/from a human body)?
I'm trying to make a sensor to detect that a person is within 50cm to trigger a function. But when I use the HR-SR04 sensor, it works accurately on flat surfaces (e.g. walls, books) with a margin of error around 5cm, but not on uneven surfaces (e.g. humans) where the value randomly jumps between 0cm to 1000cm.
I was thinking whether using an IR distance sensor would be better.

That depends on your requirements. An IR distance sensor will work better with different materials, since IR light is mostly reflected in very broad angles (expect for very reflective materials, like mirrors), so that uneven surfaces are also detected. But you will get a significantly worse error margin in your 50cm range. Normal IR distance sensors are just an LED and an IR photo transistor, sometime with some extra components. So the LED is lighting up and the photo transistor is measuring, how much of the IR light is coming back. The IR sensor depends also on the reflectiveness of the materials and the level of surounding IR light.
But as you don't really need to measure the distance, but just want to know, if there is an object in the range, an IR sensor might be enough. You would need to change the threshold of your IR sensor according to your needs (by experimenting with it).
All in all I think, yes, an IR sensor can give you better results for your application, though not for really measuring the distance, but only for the presence in a range with rather big error margin.

I've upvoted your answer (even though I like mine better) because you provide good information and a good, alternative perspective.

I have found IR accuracy to be poor resolution (+/- a few centimeters), as it's highly dependent on the refectivity of the surface. It also frequently has very poor range (a few cm to tens of cm), depending on the emitting power of the illumination source.
I have found ultrasonics, however, even the cheap $0.99 ones you mention, to have much better resolution (+/- mm), and much better range (about 2m), depending on the code driving them. I have yet to see good non-blocking code in any library for one of these, but when I write my own non-blocking code with interrupts and basic digital signal processing, such as a median filter, I get excellent results.
So, I recommend you use ultrasonics, but it requires advanced knowledge to do it well and do it right, such as using interrupts and taking the median of every 3 to 5 samples to remove spurious results.
On very flat surfaces, such as walls, at angles 45 deg or larger, ultrasonics also do poorly, since they end up measuring the distance including the extra reflections off the walls, but contrary to what you experienced, on odd shaped or softer objects, such as humans, I find them to do much better. I have used ultrasonics as the means of detecting humans several times before with good results. The real secret/challenge is your code. And again, I have yet to find a library worth using, and good code on these cheap things makes a HUGE difference in results and reliability and accuracy!

would you have any link to recommend to showcase such code (interrupts, median measurements)?


text:
Sending minimal data between two Arduinos far away from each other
Problem: I need to send small integer numbers (single-digit numbers suffices) between two arduinos located approximately 50-60m away from each other.
The connection must be made through cables. I have read that the mentioned distance is too long for using serial communication. I do not care if the method is not fast, delays up to one or two seconds are ok for this. If it helps: the devices (Arduino UNO or similar) will run not  yet written codes for a simple alarm system (with no cameras/images).

Question: What is a good way to this?

My efforts: I thought a couple of alternatives to solve this problem. Both involve the use of PWM signals sent from a device A to another B.

One of them requires some DAC in A  and read the analog input in B. The values read are then mapped to the small integer lists. I found some disadvantages with this approach:

Increment of hardware complexity and cost. Although I have read that the digital to analog conversion can be made with cheap capacitors I would have many problems to acquire them because of the lock-down of my country.
Probably I will need to  do many test to set up the mapping procedure  due to voltage drop.

The second is just read the digital input in B many times during a fixed period (e.g. 0.1 or 1 second) and average the values that were read in that period. My bet is that the devices are not synchronized and then the average (times 1023) in such longs periods would be close to the value sent by analogWrite(somepin, value). Finally, the accepted value would be the closest value in alist of acceptable values.
Example: For passing one of the numbers 0,1,2 or 3 the A device will output 0, 341, 682 or 1023, respectively. Eg. for passing "1" A will do analogWrite(somepinA, 341). B will read int lecture = digitalRead(somepinB) and get the time average of lecture for some time period. After multiplication by 1023 it could return something like "312". Then, it must find the value in [0, 341, 682,1023] closest to 280 (341) and map to 1.

Even if they were synchronized some way, I think that I could send 0 or 1 using random numbers or digitalWrite(somepinA) (Is it possible? Advantages? Disadvantages?)

I'm a novice in this field so I do not known if there is something wrong with my approach. I would also appreciate if a better alternative is proposed.
Thanks in advance.

RS485 RS485 RS485

you can use 10 levels of current, which unlike voltage, is the same on both ends.

@dandavis, I am not sure what you mean, sorry.

look into "4-20ma" reading for example. it's used over very long distances. in a loop, current is the same everywhere, so if the sensor provides a current instead of a voltage, you can read that current far away. the simplest is to read the drop over a known resistor. Even the on-board ADC should be able to distinguish 10 stable voltage levels. Then you need to turn sensor voltage to current, using a ready-made driver, or a simple opamp circuit.

one of the answers at  https://diy.stackexchange.com/questions/197992/re-writing-a-router-into-the-main-control-panel gave me an idea to use a modem ...   google arduino fsk modem module

also, check out https://www.pjon.org/SoftwareBitBang.php

RS-485 is best (you can buy some modules for this from Adafruit, Amazon, eBay, etc), but you can use the built-in hardware RS-232 serial UARTs from each on pins 0 and 1 so long as the baud rate is really really low. The lower the baud rate, the longer the range can be because lower baud rates reject noise better (and the longer the cable, the worse the noise, since the longer the cable the more it acts like an antenna and an inductor and a capacitor). Here are some rough estimates of how far you can transfer regular-logic-level unbalanced RS-232 signals:

Source:
https://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html
If this trend continues, you should be able to get like 120m at 1200 bps (baud), 240m at 600 bps, 480m at 300 bps, etc. maybe even up to > 1000m at 50 bps. I don't think the trend will continue like that, and we are using 5V TTL logic (signal voltage) levels here instead of RS-232's +/- 12V or so, so our logic levels are much worse and will have less range, so just use 50 baud and give it a shot:
// do on each Arduino
Serial.begin(50); // 50 baud = 10 bytes/sec throughput rate; see below

Note that for 8-N-1 serial communication baud rate, which is the default on Arduino, there are 10 bits per byte sent over the wire. This is because there is "one start bit, the eight data bits, and the one stop bit" for every 8-bit byte sent. That's an effective throughput data rate of 80%. This means a baud rate of 50 bps (bits per second) only can transmit 50/10 = 5 bytes per second. That's it! That's suuuuuper slow, but if it's fast enough for your application, it's fast enough!
I hypothesize 5V TTL twisted quad RS-232 communication between two Arduinos would have a maximum range at 50 baud of about 1000m/(24V span for regular RS-232 / 5V span for 5V TTL logic RS-232) = 208m. Just a crude guestimate. Please report back any findings you get from your experiments. I'd like to hear about it.
Assuming that this all does work, it would also be useful to start increasing the baud rate on each device until the data starts getting corrupted. Back off on the baud rate a little, and that's your maximum baud rate. Take that maximum baud rate and divide by 2 or 3, and that's your maximum "safe" baud rate perhaps. If you need throughput that is as high as possible, then that's what I'd do. Ex: maybe in your case 50 baud works just fine, so you increase it. At 1000 baud you start seeing corrupted data, so you back off to 800. At that point you no longer see corrupted data. So, divide that by 2 or 3 and you get a maximum "safe" baud for your setup of perhaps 800/3 = 267 to 800/2 = 400.
Try using a twisted quad cable (wires are twisted together in groups of 4) to reduce noise and increase range, and set the baud rates on each Arduino to like 50. You will need 3 wires connected between the Arduinos:

GND to GND
Tx to Rx
Rx to Tx

Power them each separately with ungrounded power supplies.
Communicate via Serial.write() and Serial.read() (so long as Serial.available() shows some data is available in the read buffer).
More on balanced vs unbalanced lines, and why I recommend "twisted quad" wire:
Normally, RS-232 is considered to be an unbalanced line transimission system. This means the impedance in the transmission wire is not equal to the impedance in the return wire, which would be a common ground between the sender and receiver, in conjunction with (in parallel with) an Earth ground through the building wiring and/or actually through the Earth...literally, the dirt you walk on. By powering each Arduino with an ungrounded power supply, such as a 2-prong power supply, however, which is common, there is no Earth ground connected to the Arduino. Furthermore, by only having a single transmission line active at any moment between two Arduinos, you have just balanced the transmission between them. Now, the out path is a single Tx signal from one Arduino to the other, and the return path has matching impedance, as it is your single, common GND wire between the two Arduinos. You now have balanced line RS-232 TTL logic level transmission between the two Arduinos. Balanced line transmission can have improved noise rejection and range by using a twisted pair between the two lines. In this case, however, there are 3 lines: Tx --> Rx, Rx --> Tx, and Gnd --> Gnd. So, you should use twisted quad wire, which means 4 wires at once are twisted together. Connect all 3 lines to the same twisted quad bundle. Again, remember, this assumes only one Arduino is transmitting at a time on one single wire in one single direction at a time (so as to not negate your return current through the GND line when transmitting on two lines, one in each direction, or double your return current through the GND line when transmitting on two lines each in the same direction [assuming you had multiple UARTS on each device]), thereby this usage creates a balanced line system since they also aren't truly grounded through a 3-prong grounded power supply. If these 2 requirements are met (1 Arduino transmits at a time, and at least one of them is not grounded to the building wiring), use twisted quad wire, as the system is balanced line communication. If it is not the case, because you are transmitting from each Arduino to the other at exactly the same time, or because both (not one) Arduinos are grounded to the building, thereby offering an alternative return path through the building ground wiring, then twisted quad cable will not benefit you, and you should use regular untwisted wiring.
Having said all that, experimentation is the real boss here. Try it out. if I didn't have twisted quad wire I'd try twisted pair, and if I didn't have twisted pair, I'd try untwisted wire.
Regarding your approach about using PWM to produce an analog output to be read by the receiving end:
Using PWM to produce an analog voltage to be read by the receiving end is an interesting approach. Without filtering, I think what you'd be doing is producing tremendous noise, however, literally producing electromagnetic radiation (think like low frequency radio or TV waves or something), where this huge 60m wire is your broadcasting antenna. If you put a 20k~50k resistor right at the sending end, however, and a 1uF capacitor right at the receiving end, however, to filter this PWM into an analog output immediately at the sending end, I think it would then eliminate your antenna effect where you are broadcasting something, and work much better, but still be highly susceptible to external noise influencing it. Give it a shot, but I suspect a simple set of digital pins to set HIGH or LOW on different pins to match different states would be much much much better than any analog signal at those lengths, with a 50 baud serial signal being the next best for signal-to-noise thereafter.
So, in order of best to worst signal-to-noise ratio (SNR):

differential pair (referenced to each other) digital HIGH/LOW values to represent states, which you update very slowly
RS-485 differential pair serial transmission
Note: for all of the following really low-speed digital signal sending scenarios, you might try it with the low-pass filter shown in the schematic below too, as it may help reject noise.
single-ended (referenced to GND) digital HIGH/LOW values to represent states, which you update very slowly
super low-speed SPI (including bit-banging it); ie: declare any digital pin a CLOCK_PIN, and any other digital pin a DATA_PIN. Set a clock pin LOW, set a data pin HIGH, set the clock pin HIGH. The clock transition tells the receiver (you have to code this up) to read the data pin, so you just read a 1 bit. Set the data pin LOW, set the clock pin LOW. The clock transition tells the receiver to read the data pin, so you just read a 0 bit. Leave the data pin low, set the clock pin HIGH again. You just sent another 0 bit, etc etc. Send data like this really slowly. It will work at great lengths--even better than asynchronous serial since it's synchronous.
asynchronous serial (+/- 12V true RS-232) at 100 baud
asynchronous serial (+/- 12V true RS-232) at 50 baud
asynchronous serial (5V TTL RS-232) at 50 baud
asynchronous serial (3V TTL RS-232) at 50 baud
analog value filtered with resistor and capacitor low-pass RC filter; update: I'd try this filtering layout for sending analog values via PWM (see schematic below, but use the higher resistor value I describe in my bullets underneath the schematic, rather than the lower value I show in the schematic); the filter may also be beneficial to help filter noise when doing low-speed digital communication too, so give it a shot in your 50-baud rate serial setup above too:

Send with analogWrite() (PWM); receive with analogRead().
Report back on this too please. I'm very curious if it would work.

unfiltered PWM---square wave antenna broadcasting who knows what--could result in an interesting broadcasting system for you. Add a transistor and you could really amp up the power and broadcast some interesting signals out! Get some good high power going here (1W~10W+) and maybe even get the government to find out who's jamming GPS and cellular? I don't know: could be interesting!

Schematic of low-pass RC filter to reduce noise between the two Arduinos when sending really low-speed digital signals (better), or slowly-changing analog signals (worse) between the two sides:

simulate this circuit – Schematic created using CircuitLab

For filtering the digital signals (ex: 5V TTL pseudo-RS232 serial at 50 to 100 baud):

Use 470 Ohms for each resistor, as shown above.
This results in a cutoff freq of 847 Hz, so stay below ~169 baud (cutoff_freq/5 = 847Hz/5 = 169 or so) for digital signal sending through this filter.

For filtering analog signals sent via analogWrite():

Since most Arduino pins have a PWM Frequency of 490 Hz, we need a cutoff frequency of ~490Hz/10 = 49Hz or lower to cleanly filter out the PWM frequency and result in a true analog output.
Using the calculator linked-to below, that means you should use R values of at least 10k each, which results in a cutoff freq. of 40 Hz. You can use 20k resistors each too, for a cutoff freq. of about 20 Hz.

To increase cutoff frequency to allow higher baud rates, decrease either R or C or both.
For a cutoff frequency calculator, see: https://electronicbase.net/low-pass-filter-calculator/#rc-low-pass-calculator --> "RC Low Pass Filter Calculator" --> enter, for example, 940 Ohms (470 x 2) as the resistor value and 0.2uF (0.1uF x 2) as the capacitor value to see that the resulting cutoff frequency for this low-pass filter is 846.57 Hz.

I'm no filter expert, but this is what I'd try. If someone sees some glaring errors in this filter or ways to improve it, please comment below the answer.
Extras:
Here's the Bode plot for the above series filter I show except with a 1k resistor and 0.1uF (100nF) capacitor followed by the same thing again. The purple line is the voltage we care about. Source: godfreyl, here.

The cutoff frequency here is 398Hz, which is where the -3db drop occurs, which corresponds to the half power and 70.7% voltage attenuation point. (sqrt(0.50) = 0.707, so 0.707^2 = 0.5)). You can read more about cutoff frequency here.

Additional reading:

https://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html
Google search for "is rs232 balanced?"
https://www.idc-online.com/technical_references/pdfs/data_communications/tutorial_2.pdf
http://www.iec-usa.com/Browse05/DTBALUN.html
https://en.wikipedia.org/wiki/Signal-to-noise_ratio

twisted pair for TTL?

Well, no: I misspoke. I should have said "twisted quad" wire. I've updated my answer and provided detailed justification for that recommendation.

Just a point of terminology: “5V TTL” and “RS-232” are incompatible terms; a link can be either but not both at the same time. The built-in hardware UART is 5V TTL, therefore not RS-232.

I'm trying to convey the information that it is asynchronous serial, following the exact bit patterns and protocol described in RS-232, except only the logic levels are different. "5V TTL" says nothing about the protocol, it means only "5V logic levels." You can have "5V TTL SPI", "5V TTL I2C", "5V TTL Dalls One-Wire", "3V TTL SPI", "5V or 3V TTL you-name-it", but "5V TTL RS-232", though technically inaccurate as you state, is the most accurate and informative representation of the setup in my opinion, because it describes the voltage, hardware, and protocol in 3 words.

I've had a problem with these terms for years, because of these discrepancies, so I'm choosing to say it in the most informative (and as accurate as is possible while being informative) way. "5V TTL" overrides the logic level portion of the RS-232 specification. In your experience, is there a better way to say it, while still conveying the exact protocol and bit information, just at a different logic level?

I tend to use “asynchronous serial”, or just “UART”, although the latter refers to the hardware port. For example: “you can use the built-in hardware UART”, “I hypothesize 5V TTL twisted quad serial communication [...]” (at this point it is already clear it's from the UART), “5V span for 5V TTL asynchronous serial”. Then it could be that some people don't know what those terms mean...

Asynchronous serial isn't a bad way to say it, but it's still more ambiguous than the way I said it. There are many forms of asynchronous serial, and RS-232 protocol is only one of them. Any communication protocol that runs without a shared clock or auto-clocking from the data rate is asynchronous. Again, in my wording, saying "RS-232" narrows this down to just one form of asynchronous serial protocol, and I "override" the default voltage levels for it by explicitly stating "5V TTL", where again, just "TTL" isn't enough either. Anyway, "asynchronous serial" is fine too, just less specific.

+1 Thank you for your very enlightening explanation! I read it carefully and also I read the linked contents. The approach I will follow depend heavily on the local product availability and prices. I could not find the twisted quad wire in my country (at least in "our eBay"). I think I will go for the RS-485 but  I'll also do some tests with RS-232, just to play around. I am curious about your opinion about if the method I suggested could work (even if it's not the best choice) or if it has any major misconceptions.

I addressed your PWM question just now in the bottom of my answer. Report back please if you try my recommended approach. I'm very curious about it now. Just remember, sending square waves down a long line is...a wireless broadcasting antenna. The lower the frequency, the longer the antenna needs to be to broadcast properly. Has to do with matching the frequency and the wavelength to the speed of light and the antenna length or something like that to get a good wireless signal broadcasted. So, you'd need to filter it to try NOT to broadcast wireless signals that way.

I just expanded my signal-to-noise ratio list from 3 to 10 items. This answer just keeps growing.

@user1420303, a UTP cable used for networks has 4 twisted pairs. I am sure you can buy RS485 adapters for Arduino. don't waste time attempting to make the UART work on long cable.

It appears the easiest would be to use a simple CAN transceiver on each end, one set to transmit and the other to receive. You did not mention bidirectional communications although both Physical layers suggested below will support that quite easily. The electrical characteristics of the CAN bus cable restrict the cable length according to the selected bit rate. You can use cabling up to 250 meters with the baud rate of 250 kbit/s. The maximum bus length with a bit rate of 10 kbit/s is 1 km, and the shortest with 1 Mbit/s is 40 meters.
Another approach would be to used RS485. RS485 is popular for inexpensive local networks, multidrop communication links and long haul data transfer over distances of up to 4,000 feet. The use of a balanced line means RS485 has excellent noise rejection and is ideal for industrial and commercial applications. Note these typically are driven with Async signals from a uart or similar device. Software serial would work great and leave the onboard serial port for debugging. the Async communications does the syncing automatically, nothing for you to do, just keep the baud rates the same.

The CAN protocol seems significantly more complex than the typical UART (async serial) over RS-485, and the Arduino has no hardware support for it. Or are you suggesting to do UART over the physical layer of CAN?

Great you have it. Use the physical layer but what you send on it is up to you. I believe in your case it will be a simple 1 way transmission to a slave. The baud rate you use is whatever you like and is convenient. I generally run software serial at 9600 baud and my terminal at 115200 that way the terminal can get whatever is sent without flooding. Have fun and let us know how it works out.


text:
PID control doesn't work. After computing the values, the values just become equal to 0
So, I have a working code of the stabilizer project using 2 servo motors, mpu6050, Arduino Uno. However, I want to add PID part for tuning the servo motors movement. I followed the example PID library and just changed the input as data received from the mpu6050 sensor, and output as the data that we send to servo motor. The problem is after adding the PID part project stopped working properly. Servo motors did not react to the accelerometer movement anymore. I tried printing out the values computed by the PID and all of them turned out to be 0 and they don't change even if I rotate the sensor. Can anyone spot the mistake in the code with PID part? I am pretty sure that the rest works perfectly.
/*
                        DIY Gimbal - MPU6050 Arduino Tutorial
                        by Dejan, www.HowToMechatronics.com
                        Code based on the MPU6050_DMP6 example from the i2cdevlib library by Jeff Rowberg:
                        https://github.com/jrowberg/i2cdevlib
*/
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file
#include "PID_v1.h"

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
#include <Servo.h>
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

double Setpointx, Setpointy, Inputx, Inputy, Outputx, Outputy, pidX, pidY;
double Kp = 2, Ki = 5, Kd = 1;
PID myPID0 (&Inputx, &Outputx, &Setpointx, Kp, Ki, Kd, DIRECT) ;
PID myPID1 (&Inputy, &Outputy, &Setpointy, Kp, Ki, Kd, DIRECT) ;
// Define the 3 servo motors
Servo servo0;
Servo servo1;
Servo servo2;
float correct;
int j = 0;

#define OUTPUT_READABLE_YAWPITCHROLL

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
  mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  Setpointx = 10;
  Setpointy = 10;

  myPID0. SetMode (AUTOMATIC);
  myPID1. SetMode (AUTOMATIC);

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  Wire.begin();
  Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  Fastwire::setup(400, true);
#endif

  // initialize serial communication
  // (115200 chosen because it is required for Teapot Demo output, but it's
  // really up to you depending on your project)
  Serial.begin(115200);
  while (!Serial); // wait for Leonardo enumeration, others continue immediately

  // initialize device
  //Serial.println(F("Initializing I2C devices..."));
  mpu.initialize();
  pinMode(INTERRUPT_PIN, INPUT);
  devStatus = mpu.dmpInitialize();
  // supply your own gyro offsets here, scaled for min sensitivity
  mpu.setXGyroOffset(17);
  mpu.setYGyroOffset(-69);
  mpu.setZGyroOffset(27);
  mpu.setZAccelOffset(1551); // 1688 factory default for my test chip

  // make sure it worked (returns 0 if so)
  if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    // Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    //Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
  } else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    // Serial.print(F("DMP Initialization failed (code "));
    //Serial.print(devStatus);
    //Serial.println(F(")"));
  }

  // Define the pins to which the 3 servo motors are connected
  servo0.attach(10); //Z Axis
  servo1.attach(9); //Y Axis
  servo2.attach(8); //X Axis
  servo1.write(90);
  servo2.write(90);
}
// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
  // if programming failed, don't try to do anything
  if (!dmpReady) return;

  // wait for MPU interrupt or extra packet(s) available
  while (!mpuInterrupt && fifoCount < packetSize) {
    if (mpuInterrupt && fifoCount < packetSize) {
      // try to get out of the infinite loop
      fifoCount = mpu.getFIFOCount();
    }
  }

  // reset interrupt flag and get INT_STATUS byte
  mpuInterrupt = false;
  mpuIntStatus = mpu.getIntStatus();

  // get current FIFO count
  fifoCount = mpu.getFIFOCount();

  // check for overflow (this should never happen unless our code is too inefficient)
  if ((mpuIntStatus & _BV(MPU6050_INTERRUPT_FIFO_OFLOW_BIT)) || fifoCount >= 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    fifoCount = mpu.getFIFOCount();
    Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
  } else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);

    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

    // Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    // Yaw, Pitch, Roll values - Radians to degrees
    Inputx = ypr[2];
    myPID0.Compute();
    Outputx = pidX;
    Inputy = ypr[1];
    myPID1.Compute();
    Outputy = pidY;
    Serial.print("\nX: ");
    Serial.print(pidX);
    Serial.print("\nY: ");
    Serial.print(pidY);
    ypr[0] = ypr[0] * 180 / M_PI;
    pidX = pidX * 180 / M_PI;
    pidY = pidY * 180 / M_PI;
    // Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(pidY, -90, 90, 0, 180);
      int servo2Value = map(pidX, -90, 90, 180, 0);
      // Control the servos according to the MPU6050 orientation
      servo0.write(90);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif
  }
}

Why are you doing Outputx = pidX;? Outputx is the output variable of the PID object. You are not supposed to write to it. You need to read it and then use it as a servo angle. And you should only compute the PID when you are actually using the value. You don't need it for the callibration cycle

@chrisl How should I use the outputx then after it is being computed by myPID.compute()? I mean I have to make the values that I send to the servo in degrees and map them from 0 to 180. I doubt that if I put outputx directly to servo2.write(outputx) it would be in degrees instead of radians and with no mapping. And the last question where the pid output should be computed then? Isn't it supposed to be computed inside the void loop()?

Your code is not using Outputx after it is being computed by myPID0.Compute();, you are immediately overwriting what is computed with the following Outputx = pidX; line.  Per https://playground.arduino.cc/Code/PIDLibrarySetOutputLimits/ use myPID0.SetOutputLimits(0,180); & servo1.write(Outputx), etc.  and drop the rest of the conversion and mapping stuff.   The Kp, Ki, and Kd constants all convert units of setpoint-input error into units of controlled output.  (Or at least change Outputx = pidX;intopidX = Outputx;)

pidX and pidY are initialized to zeros in the declaration, and then are only updated by the pidX = pidX * 180 / M_PI;     pidY = pidY * 180 / M_PI; which resets them to zero.  You need to change the Outputx = pidX; into pidX = Outputx;, and also for Y.

You seem to have some misconceptions about PID. For explaining I will use a different use case of a PID control, which is easier to understand (and also mentioned in the documentation of the PID library):
A PID control can be used in any feedback loop system with consistent feedback. When you drive your car you want it to reach a specific speed. For that you press the gas pedal, changing its angle until you reach the target speed. In this scenario you are doing the PID control. The setpoint is the target speed, the input is the actual current speed and the output is the angle of the gas pedal.
You see: Output and input/setpoint don't have the same unit. They are completely different measurements of different things. They are only connected via the feedback loop in the system, meaning that increasing the gas pedal angle will increase the speed of the car. The PID control is then just a formula which involves the actual speed, the desired speed and some scaling variables (Kp, Ki, Kd)(to tune the behavior of the control). And the output of the formula is then the needed gas pedal angle at that time.
So what does this mean for you?

You don't need to convert the output value into an angle. The unit of the output is not important, since the PID will control itself to get to the setpoint. It is more important to tune the PID through Kp, Ki and Kd to get the PID to behave correctly in your system.

The workflow looks like this:

Set the setpoint variable Setpointx to the wanted input value.
Read the input from the MPU and save it to Inputx
Call myPID0.Compute(); to compute the output from setpoint and input.
Read the value from Outputx and write it to your servo. The servo movement will then cause a change in the read input in the next loop.
repeat from step 2

As I currently don't really understand your feedback loop system: Make sure, that the feedback loop is working correctly. An increase in the output should lead to an increase in the input. Make sure it is consistent. Your input value should not have too much noise (or the PID will react to that noise). For testing you might want to tune Kp, Ki and Kd down so that the PID works slower. Then you can see the behavior better. Make sure, that both PID controls aren't influencing each other. They need to be independent.

Use myPID0.Compute(); every time you write a new value to your servo and only then. Calling it in between will be just a waste. So it makes sense to use that line somewhere directly before writing to the servo.

If it still not works, then you should have a detailed look at the read values and how they relate to the servo angle. Are the requirements above met? Are they stable enough. Is the feedback loop as expected? What does changing Kp, Kd and Ki change in the outcome?

The PID input and output don't have to be in matching units, but they could be. The Servo.write() input range is 0 to 180 for minimum to maximum, and is intended to map to degrees https://www.arduino.cc/reference/en/libraries/servo/write/  -- Internally Servo.write() maps the 0-180 back to microseconds: https://github.com/arduino-libraries/Servo/blob/master/src/avr/Servo.cpp#L264  In this case, input and setpoint need to be in the same units, but output could be in degrees constrained to 0-180 or 1000-2000 microseconds. kP converts input units of error to output units.

This chunk of code is feeding radians into the PID algorithm, and then discarding/overwriting the output with the initialized-to-zero pidX and pidY values.
...
Inputx = ypr[2];
myPID0.Compute();
Outputx = pidX;
Inputy = ypr[1];
myPID1.Compute();
Outputy = pidY;
...

I'd set the output limits to match the device under control:
void setup() {
   // join I2C bus (I2Cdev library doesn't do this automatically)
   Setpointx = 10;  // MPU degrees
   Setpointy = 10;  // MPU degrees

   myPID0. SetMode (AUTOMATIC);
   myPID1. SetMode (AUTOMATIC);
   myPID0.SetOutputLimits(0,180); // servo degrees
   myPID1.SetOutputLimits(0,180); // servo degrees
   ...

...and then convert the inputs to match the setpoints, and feed the constrained PID outputs directly to the controls:
Inputx = ypr[2]*180.0/M_PI;
myPID0.Compute();
pid_X = Outputx;
Inputy = ypr[1]*180/M_PI;
myPID1.Compute();
pidY = Outputy;
...
servo1.write(Outputx);
servo2.write(Outputy);
...

It is important to use the PID.SetOutputLimits(min,max) so that the PID routine can internally ensure that the outputs don't wander deep into infeasible control regimes.  If you don't call SetOutputLimits(), the default output constraints are 0-255, which would not make sense for a 0-180 servo.
One way to think of your PID constants Kp = 2, Ki = 5, Kd = 1; is how big an output unit change (degrees of servo setting) you want to make for a unit of input (MPU radians or degrees?) error, integrated error (error*seconds/5 per https://playground.arduino.cc/Code/PIDLibrarySetSampleTime/), or delta error.  They might need adjusting if the system isn't responding as you like.


text:
Why is my CNC shield smoking? Is it safe to keep on for long periods of time?
I am working on a project that involves moving stepper motors, and the device will have to be on for upwards of hours. I am moving the bipolar NEMA17 stepper motors using a Protoneer CNC shield V3 on top of an Arduino UNO and DRV8825 stepper drivers. Though I haven't left the motors on for too long, whenever I do for longer periods, maybe 5 minutes or more, smoke starts being emitted around the 4 pins I connect my motors with. My question is that, if anyone has had a similar issue before, if they could explain why this occurs. I would also like to know if the stepper drivers are actually being protected by the heatsinks, because they can get ridiculously hot even after a few minutes and I'm worried that they wouldn't be able to last more than 15 minutes before exploding. Hopefully there's enough information here for someone to understand what's going on, but I'd glad to give more if that helps get a better idea of what's going on here. Thank you!

sounds like the connectors are not providing a solid electrical connection and may even be inadequate for the job ... your post does not really provide any useful info about the actual problem ... you could have asked the same thing in about 10 words ... my NEMA17 stepper motor connector is smoking.  how do i correct this?

too much heat is a problem of too much current and too much resistance; reduce both.

How would I reduce the resistance? Just lower the current? Are you sure that the problem isn't that there's not enough resistance?

Smoking is definitely a bad sign and not OK to run under these conditions. Take a photo of your setup. Maybe your wires are too small? Maybe your code is wrong, or your wiring is wrong and you are periodically shorting the motors, causing really high currents.

How do you attach wires to that shield? Little jumper wires to the pin headers?

Here are some pictures. It's not a complicated setup really. https://imgur.com/a/Ldex9bb
I think all I can do for now is lower the current on my drivers and hope for the best

Please paste images directly into your question. I'll do it for you this time.

I edited your question and inserted your 3 images. It requires review and approval. Perhaps even you can approve the edits? Not sure. Next time, please just drag and drop or copy and paste images right into your question while editing it.

Pin headers have a typical maximum current of 3A - and that is assuming you are connecting a plug with good connections. That is seldom the case.

The pins themselves can only handle 3A of current? Seems like that could definitely be the issue. By the way, how come everyone is commenting instead of writing up answers?

Because none of the comments resolve your question, so aren't really answers... With regard to the OP, smoke is never a good sign... The pins can probably take more than 3A since they are just solid pins, it's the connector/quality of the connection that can't. I suspect the black plastic shrouds are a bit melted if that's whats been getting hot! Plus, the drivers (if they are the A4988 ones) are only 2A rated, so if they are being pushed harder, overcurrent and thermal protection will be hard at work.

Those NEMAs are big ones - i suspect too big for the little A4988 chips - which can only provide 2A when actively cooled and generally only for short periods. I wouldn't try to push more than 1.7ish Amps for any length of time.
You will also need to set the vREF correctly for the motors you are using - if this is not set you will either provide too little current or too much current.
Look up the specifications for the NEMAs you have - and upgrade the Stepper controller to something more like a TB6600 that can handle greater current.
Also when the Steppers are not being used - disable (if you dont need them to hold) this will turn off the drivers and let them cool between runs/moves.

How can I disable a stepper motor?

On that particular CNC shield pin 8 is the enable pin - LOW=enabled, HIGH=disabled.


text:
Help in personal alarm clock project, cant write time on seven segment display

I'm trying to make a type of Arduino alarm clock, which when the time I inputed is equals to the current time, a servo will turn on my lights. It basically consists of a Keypad, an RTC DS1307 and a TM1637 seven segment display. The basic idea is that the RTC module would print time to the display until I decide to write something on the keypad, which would clear the time on the display to let me write the alarm. My problem is that the display manages to both show time on the display and write to the display but this only works on separate code, not together.
The keypad has a '*' and '#' character, when i decide to write the time i want the lights to turn on, after writing it i press the '*' character to save that time and then the idea would be to compare the time written and the present time, if i press '#', then all would be canceled and the RTC module would continue to show the time on the display. (i have not manage to advance that much due to my error on not being able to clear the display when i want to write on the keypad)
#include "Arduino.h"

// KEYPAD
#include "Keypad.h"

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

//define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};

char customKey;

byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

// DISPLAY
#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"

const byte PIN_CLK = 4;   // define CLK pin (any digital pin)
const byte PIN_DIO = 5;   // define DIO pin (any digital pin)
SevenSegmentExtended      display(PIN_CLK, PIN_DIO);

// RTC

#include <Wire.h>
#include <TimeLib.h>
#include <DS1307RTC.h>

void setup(){
    Serial.begin(9600);         // initializes the Serial connection @ 9600 baud
    display.init();
    display.setBacklight(100);  // set the brightness to 10 %
    display.print("ON");      // display INIT on the display
    delay(1000);                // wait 1000 ms
    display.clear();
}

// OTROS

#define digit 4

byte data_count = 0;
char Data[digit];

void loop(){

    tmElements_t tm; // CLOCK

    display.setColonOn(true);
    customKey = customKeypad.getKey();

    if (RTC.read(tm)) {
        display.printTime(tm.Hour, tm.Minute, true);
    }

    if (customKey) { // ACTIVATE KEYPAD

        display.clear();

        if (customKey == '*') { // IF *
            display.blink();

            if (Data[data_count] < 3) {
                error();
            }

        } else if (customKey == '#') { // IF #
            display.blink();
            display.setColonOn(false);
            display.clear();
            clearData();
        } else { // WRITE ON DISPLAY

            Data[data_count] = customKey;
            display.setCursor(0,data_count);
            display.print(Data[data_count]);

            if (data_count < 4) {
                data_count++;
            } else {
                error();
            }
        } // END DISPLAY WRITE

    } // END KEYPAD IF

} // END LOOP

void error() { // DISPLAY ERROR AND DELETE DATA
    display.clear();
    display.setColonOn(false);
    display.print("ERR");
    delay(1000);
    display.clear();
    clearData();
}

void clearData() { // CLEAR DATA
    while (data_count != 0) {
        Data[data_count--] = 0;
    }
}

This are the libraries i'm using if it helps:
https://github.com/bremme/arduino-tm1637,
https://github.com/PaulStoffregen/DS1307RTC and the
Keypad library from Arduino library manager
Hope I made myself clear with my problem, english is not my first language, if you want more clarification then let me know!
That is basically what i've got, i'm sorry if the post is too long, i have been struggling with this problem for two days and i don't know how to proceed. Hope you all can help. Thanks!

I think your problem is here:

if (RTC.read(tm)) {
    display.printTime(tm.Hour, tm.Minute, true);
}

This code displays the current time, and it runs on every single loop
iteration. This is visibly not what you want. Your project should have
at least two distinct operational modes: “display the current time” and
“allow the user to input data”. You need a variable to remember which is
the current mode, e.g.
enum { MODE_DISPLAY_TIME, MODE_DATA_INPUT } mode;

You need to precisely define the events that make your program switch
modes, and code specific behaviors for each mode. For example:
if (mode == MODE_DISPLAY_TIME) {
    if (RTC.read(tm)) {
        display.printTime(tm.Hour, tm.Minute, true);
    }
} else if (mode == MODE_DATA_INPUT) {
    // Handle user input.
}

This general approach is called a “finite state machine”. You can read
more about it in this blog article by Majenko.


text:
Terminal read-only serial monitor without blocking serial port for sketch upload
I would like to have all serial output from Arduino (nano) dumped to the terminal in Linux, without blocking the serial port for uploading new sketch version (for quick debugging loop), when using Arduino-Makefile:
[Errno 16] could not open port /dev/ttyUSB0: [Errno 16] Device or resource busy: '/dev/ttyUSB0'

Is there something made for that already? I did read about 10 related questions here and elsewhere (using screen, socat and others) but none of them deals with the question how to not block the port.
I might eventually code something in Python, which will disconnect when  signalled and reconnect again after a few seconds (I use custom Makefile for the upload) and I imagine Arduino's IDE serial monitor does something similar.
Other pointers on how to solve the issue are appreciated!

(using screen, socat and others) but none of them deals with the question how to not block the port.

Other pointers on how to solve the issue are appreciated!

I say:

Virtually all hardware problems can be solved with software. But, sometimes, the $50000 software problem can be solved with the $2 hardware solution.

This is one of those cases. Buy a CP2102 6-pin serial UART USB adapter for < $2 on Ebay, or for < $10 on Amazon, to provide a second serial interface to the same Arduino (both connected to the same hardware UART built in to the Arduino's ATmega328 mcu). Let the main USB serial interface handle code uploads to the Arduino. Let this 2nd, external UART handle READ-ONLY from the Arduino!
Plug it in:
Arduino     CP2102 USB 6-pin UART
-------     ---------------------
Tx          Rx
GND         GND

Done. Do NOT plug in the CP2102 Tx to anything.
Now, use picocom (one of my favorites), screen, or my crude datalogging Python serial terminal I wrote here (eRCaGuy_PyTerm), or a 2nd instance of the Arduino IDE with the Serial Monitor, or any other serial terminal for that matter, to read from the CP2102 while the Arduino's built-in USB adapter does code uploading.
Two serial interfaces to the same pins on the Arduino: one does Tx/Rx to/from the Arduino, while the other does only Rx to read from the Arduino.
I use a 2nd UART like this all the time as a trick to allow me to read the data from the Arduino into one Serial Monitor in one instance of the Arduino IDE so I can see the numbers, and I use the external CP2101 USB adapter to read the same exact data from the Arduino into the Serial Plotter of another instance of the Arduino IDE so I can see the live, plotted graphs!
It's amazing how well this works. Quick hack. Easy solution.

Note: to you use my eRCaGuy_PyTerm Python serial terminal, first set all your serial parameters inside the user_config.py file, then run python3 serial_terminal.py to run the program. It is a 2-way serial terminal, with datalogging. It works quite well. I really should improve its readme and post some examples someday.

Cool!! In fact I have a few of those adapters around, it will be a $0 solution :)

You can write your own python script that prints received serial output. By using try/except in a loop you can "pause" your serial monitor while uploading is in progress.
I did the same a while ago using pyserial on linux. I'd like to share it, but at the moment I have no access to my other machine. I can post it later if you want.

Please post it, that would be awesome! I did not try yet but reconnecting while upload is in progress will make it fail; can you handle that or is there simply a fixed time to wait after failure?

@eudoxos k, I'll look for the code. You can't access the port with two processes at the same time, but you can catch the exception