text:
MPU6050 Sending Bad values for Angular Velocity
The mpu gives me perfectly fine values for the yaw, pitch, and roll position of the chip, but when I use mpu.getRotation(&gx, &gy, &gz) to obtain the current angular velocity of the chip, the values returned are awful. I wrote a program in Processing to graph the data from my Arduino, and this is what it looks like:

I suggest you click on the picture and zoom in a bit because it's difficult to see. The green line represents zero (0), the Pink line represents the angular position of the mpu6050 chip, obtained from mpu.getYawPitchRoll..., and the Blue line represents the angular velocity on the same rotational axis.
A few extra things to note:

The scale between the Pink and the Blue lines is slightly off, but that shouldn't matter for this purpose.
The time-frame for this graph is about 16s.
Before being graphed, the raw gx value is divided by the gyro's sensitivity scale factor, 131, and then converted from radians to degrees.
In addition to this, it is also put through a complementary filter, so the whole formula looks like this: rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI));

As you can see, the measurements for angular velocity (Blue) make almost no sense when graphed next to the angular position (Pink).
My question is this: What can I do to clean-up/filter these angular velocities and get rid of all the errors? I need these values to be accurate enough to be used in something like a drone PID.
Things I have tried:

Complementary filters of various proportions.
Adjusting the MPU's built in low-pass filter.

Thanks for any suggestions.

At last! I have discovered the solution.
Quick Solution for those who don't like reading: Amend the previous rollRate formula to rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);. Or, if you don't want the filter, rollRate = -1 * gx / 16.4;
The problem starts with the function mpu.getRotation(&gx, &gy, &gz) which accepts int16_t types for gx, gy, and gz. Since int16_t is a 16 bit integer, it has a maximum range of -32,768...+32767. The reason this integer type is used is because the output range for the gyro is -32750...+32750, which fits nicely into the 16-bit integer's range.
The problem was that when I converted these values to a readable angular velocity (and complementarily filtered) using  rollRate = (0.7*rollRate) + (0.3*(-180 * gx / 131 / M_PI)); , the gx value was multiplied by -180 in part of the calculation. This means that if gx was high enough initially, it would have rolled over to -32786 and ruined the whole calculation, causing the horrible spikes in the graph.
At the same time I discovered this problem, I also realized that converting from radians to degrees was unnecessary, as the gyro output was already in units of degrees (just scaled by a sensitivity factor). After that big face-palm, I revised my rate formula to the following: rollRate = (0.7 * rollRate) + (-0.3 * gx / 16.4);. You will notice the scale factor has changed from 131 to 16.4. That is because the gyro range is actually +/-2000 deg/s by default, not 250 deg/s. I tried to change it back to +/-250 with mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_250);, but after examining the graph, it appeares that mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); does not account for this setting change, and resulted in the ypr overshooting and then leveling out to its correct value after a delay. I decided not to mess around with the quaternion container, q, and just accepted the lower sensitivity.

Like the previous image, I suggest zooming in.


text:
2 Motor Robot Control with RC Radio
I am making a robot for a local robotics competition.  One main function I need to do is move it forward, backward, right, left.  Just like an RC car.  I have programmed it to do that but it seems like the motors are not going the same speed as each other.  When I move the stick just a little bit only one motor starts moving then when I go a bit further the only starts as well. I use an L293D and an Arduino UNO to control the 2 12v motors. I use a 6 channel receiver and transmitter for radio control.  I think it might be something with the motor, but I might be missing something.  Hopefully, someone can help me out. Thanks!
int motor1_in1 = 3; //H bridge direction pins
int motor1_in2 = 2; //H bridge direction pins
int motor2_in3 = 7; //H bridge direction pins
int motor2_in4 = 6; //H bridge direction pins

//the following are all ~PWM capable ports
int motor1_enable1 = 4; //H bridge motor 1 PWM PIN
int motor2_enable1 = 5; //H bridge motor 2 PWM PIN
int rc_channel2 = 10;
int rc_channel4 = 8;

void setup() {
  pinMode(rc_channel2, INPUT);
  pinMode(rc_channel4, INPUT);
  pinMode(motor1_in1, OUTPUT);
  pinMode(motor1_in2, OUTPUT);
  pinMode(motor1_enable1, OUTPUT);

  pinMode(motor2_in3, OUTPUT);
  pinMode(motor2_in4, OUTPUT);
  pinMode(motor2_enable1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  motorMoveForward();
  motorMoveSide();
  // delay(100);
}

void motorMoveForward()  {
  int pwm = 0;
  int rc2 = pulseIn(rc_channel2, HIGH, 25000);

  if (rc2 == 0) {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);
  }
  else if (rc2 > 1520) { //Backwards
    pwm = map(rc2, 1520, 1910, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, HIGH);
    digitalWrite(motor2_in3, HIGH);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, pwm);
    analogWrite(motor2_enable1, pwm);

    Serial.print(" DOWN    : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);

  }
  else if (rc2 < 1480) { //Forwards
    pwm = map(rc2, 1480, 1090, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, HIGH);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, HIGH);

    analogWrite(motor1_enable1, pwm);
    analogWrite(motor2_enable1, pwm);

    Serial.print(" UP     : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);
  }
  else {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);

    Serial.print(" CENTER  : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);
  }

}

void motorMoveSide()  {
  int pwm1 = 0;
  int rc4 = pulseIn(rc_channel4, HIGH, 25000);

  if (rc4 > 1520) { //RIGHT
    pwm1 = map(rc4, 1520, 1905, 0, 255); //map our speed to 0-255 range
    //digitalWrite(motor1_in1, LOW);
    // digitalWrite(motor1_in2, HIGH);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, HIGH);

    analogWrite(motor1_enable1, pwm1);
    analogWrite(motor2_enable1, pwm1);

    Serial.print(" RIGHT   : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);

  }
  else if (rc4 < 1480) { //LEFT
    pwm1 = map(rc4, 1480, 1090, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, HIGH);
    digitalWrite(motor1_in2, LOW);
    //digitalWrite(motor2_in3, HIGH);
    //digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, pwm1);
    analogWrite(motor2_enable1, pwm1);

    Serial.print(" LEFT    : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);
  }
  else {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);

    Serial.print(" CENTER  : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);
  }

}

See the many answers which explain how horrible the L293 is.  Fundamentally this doesn't seem to be a job for an Arduino - what you probably want is a pair of small hobby ESCs.

pulseIn() is an exceptionally bad, blocking way to read in RC signals, and performs very poorly, while also slowing your loop speed down a lot. Reading in RC signals properly is a very advanced task. Here's one example I made to show how to do it properly on a single RC channel: https://github.com/ElectricRCAircraftGuy/eRCaGuy_TimerCounter/blob/master/examples/read_PWM_pulses_on_ANY_pin_via_pin_change_interrupt/read_PWM_pulses_on_ANY_pin_via_pin_change_interrupt.ino. Doing it for many channels is far more complicated still, as jitter and interrupt time must be minimized.

From your code I would say, the problem lies within your loop function. The functions motorMoveForward() and motorMoveSide() are both over very quickly. But to actually move your motors need some time, before you change directions. Currently the motors rapidly change between driving forward and sidewards. Since in your motorMoveSide() function you only change direction for one of the motors, this one will rapidly being told to move forward and backwards. That results in the motor to move slowly or to not move at all. You simply cannot move forward and sidewards at the same time.
If you just want to controll the movement of your robot via RC, it may be better to use one channel just for speed value (for example 0 --> stop, 255 --> full power) and one for the direction (for example 0 --> full power left, 127 --> just forward, 255 --> full power right). A normal RC car works the same way. Or you can take one channel for one motor (and mapping speed and direction of the specific motor like you did with both motors). Which way to go depends also on your remote (e.g. what is best for controlling it with the remote).

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:
What is wrong with this code?
So I am writing code to control a servo with an RC radio. I am using an Arduino Mega.  I get this error whenever I compile.  I am not that experienced with Arduino so I am probably not doing something right. Thanks for the help!

Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Mega or Mega
  2560, ATmega2560 (Mega 2560)"
C:\Users\ethan\Desktop\Periferals_control\Periferals_control.ino: In
  function 'void loop()':
Periferals_control:46: error: expected ';' before '{' token
{
^
exit status 1 expected ';' before '{' token
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

#include <Servo.h>
Servo servo1;
Servo servo2;
//the following are all ~PWM capable ports
int servoElevator_PwmIn = 6; //Elevator Servo
int servoGrabber_PwmIn = 7; //Grabber Servo

//Channels on AT9
int leftStickVertical = 2; //Channel 3
int rightStickVertical = 3; //Channel 7

int elevatorServoStop = 50;

void setup() {

  //pinMode(servoGrabber_PwmIn, OUTPUT);
  //pinMode(servoElevator_PwmIn, OUTPUT);
  pinMode(leftStickVertical, INPUT);
  pinMode(rightStickVertical, INPUT);
  Serial.begin(9600);

  servo1.attach(6);
  servo2.attach(servoGrabber_PwmIn);
}

void loop() {

  int leftStickVerticalPwm = pulseIn(leftStickVertical, HIGH, 25000);
  int rightStickVerticalPwm = pulseIn(rightStickVertical, HIGH, 25000);
  Serial.print(leftStickVerticalPwm);
  Serial.print("\t");
  Serial.print(rightStickVerticalPwm);
  Serial.print("\n");

  if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }
}

  if (rightStickVerticalPwm == 0)
  {
    servo1.write(elevatorServoStop);
  }
  else if (rightStickVerticalPwm > 1500)
  {
    servo1.write(100);
  }
  else (rightStickVerticalPwm < 1400)
  {
    servo1.write(30);
  }

You cannot have another comparison in an else statement. You might have meant else if in the last clause.
Clarification if you're not well familiar with C/C++: If you have an if statement, it can be followed by arbitrary many else if clauses and at maximum one else clause which will execute when all other conditions fail. For example:
 int a = 10;
 if( a == 9 ) {
       //Executed if a = 9
 } else if( a < 20 ) {
   //If above not executed, this will be executed if a < 20
 } else {
   //This is executed if none of the conditions above hold.
   //A pure "else" does not have a condition and only one may
   //exist in an `if` statement.
 }

you should not provide conditions for " else " statement because it focuses on what action should happen if all " if and else if " conditions are not fulfiiled.

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


text:
Carry out two consecutive tasks when a button is pressed
I'm building a project that has 2 motors. What I want to do is:
When button is pressed (hold down through RF controller) then:

Run motor A on pwm at 50 for 1 second
Run motor B on pwm at 255 for 1 second

After that first second

Run motor A on pwm at 255 until button is released
Stop motor B.

And when I hit the button again the whole thing repeats. Here is my rough code but it doesn't work that way. What it does is if I pressed the button in the first second since start up off the Arduino it does the first task. If I press it again it does the second task.
I have looked and tried through a lot of examples of blink without delay and multitasking. But I still can't get it working.
Here is my code:
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include <elapsedMillis.h>

// Motor 1
int dir1PinA = 4;
int dir2PinA = 5;
int speedPinA = 3; // Needs to be a PWM pin to be able to control motor speed

// Motor 2
int dir1PinB = 7;
int dir2PinB = 8;
int speedPinB = 6; // Needs to be a PWM pin to be able to control motor speed

int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;

unsigned long previousMillis = 0;
long OnTime1 = 500;
long OnTime2 = 10000;

void setup(){
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(1,pipe);
 radio.startListening();

 pinMode(dir1PinA,OUTPUT);
 pinMode(dir2PinA,OUTPUT);
 pinMode(speedPinA,OUTPUT);

 pinMode(dir1PinB,OUTPUT);
 pinMode(dir2PinB,OUTPUT);
 pinMode(speedPinB,OUTPUT);

 }
 void CandPush()
 {
          analogWrite(speedPinA, 50);//Sets speed variable via PWM
          digitalWrite(dir1PinA, HIGH);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinB, LOW);
          digitalWrite(dir2PinB, HIGH);

 }
 void CandStop()
 {
          analogWrite(speedPinA, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinA, HIGH);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 0);//Sets speed variable via PWM
          digitalWrite(dir1PinB, LOW);
          digitalWrite(dir2PinB, LOW);

 }
 void Home()
 {
          analogWrite(speedPinA, 0);//Sets speed variable via PWM
          digitalWrite(dir1PinA, LOW);
          digitalWrite(dir2PinA, LOW);
          analogWrite(speedPinB, 255);//Sets speed variable via PWM
          digitalWrite(dir1PinB, HIGH);
          digitalWrite(dir2PinB, LOW);

 }
 void loop(){

 if (radio.available()){
    bool done = false;
    while (!done){
    done = radio.read(msg, 1);
    Serial.println(msg[0]);
    if (msg[0] == 111)
    {
      unsigned long currentMillis = millis();
      CandPush();
      if(currentMillis - previousMillis >= OnTime1)
      {
        CandStop();
        previousMillis = currentMillis;
      }

    }
 }
 }

 else
 {
  Home();
  Serial.println("Nothing");
 }
 }


text:
How to properly link an Arduino and its sensors
To finalize a prototype, I would like to have a proper structure containing the arduino (uno here), its shields and its sensors. I would like the sensors to be soldered to the arduino+shields block, but the sensors were sold on a small separate PCB (example).
What is the recommended method to have a strong, clean link between the two ?

You could solder those modules to a prototype shield.  If you replace the header with a right-angle one (or even just bend the pins on the existing one) you could even mount it vertically to save space.

Prototype shield:

Right-angled headers:

This sounds right. I would be glad if you could illustrate with pictures so that it is perfectly clear, though. Thank you

I tried to find a picture online but couldn't. You may be the first to do it :)

A prototype shield has a matrix of holes like a breadboard - except you solder them. The breakout board has pins. The pins go in the holes, and you solder it. Then you solder wires between those soldered pins and the Arduino header pins. If you want more than one module and the pins are only on one side, then use right angled pins so the breakout board sticks up in the air.

In effect treat the breakout board like any other component. It's just a little larger than most.

You can create a pretty good quality DIY "prototype shield" (shields are expensive) like here https://startingelectronics.org/projects/arduino-projects/arduino-tiny-stripboard-shield/

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


text:
Arduino Nano and SIM800L on Battery Power
I'm very new to Arduino and everything related but I'm highly interested to learn more. However, I've run into a problem right in the beginning.
I want to build some sort of portable emergency/notification button. One pushes the button and an SMS is sent or an HTTP call made to a server. I want to base this project on the Arduino Nano as it's quite small and therefore easily transportable. To have GSM/GPRS connectivity I found the SIM800L which seems quite suitable to what I have in mind. Now to the big question, how to power the Arduino Nano as well as the SIM800L on an portable power source, preferrably only one power source.
From my understanding, the SIM800L requires a peak current of 2A when doing handshakes and sending signals. Is there any way I can power the SIM800L through the Arduino Nano, like Battery -> Arduino Nano -> SIM800L, or do I need to connect both the Arduino Nano and the SIM800L to the battery?
Regarding the lifespan, for now it would be sufficient if I could press the button a few times and afterwards it'd stop working.

Check out

Thin battery to power arduino micro with nRF8001?

Also, I found a 6v battery (A544) at Menards that is about the same diameter as a AA, but is considerably shorter. It has 178 mAh capacity.
I haven't taken the time to test it, but I would guess it wouldn't have as much of a temperature issue.
It's not as small as the CR2032 in the above mentioned link, nor is it flat, but it's an option.
You might consider an Arduino Beetle. They are really super incredibly tiny and still 16mHz. I can't get any more info from where I'm at, but I'd believe they would use even less power than a Nano/Micro.
I found an Instructable that shows how to use a Beetle, a rechargeable 3.7v LiPo battery, and an HC-06 Bluetooth module. Sounds like it's equivalent to what you're looking for.
http://www.instructables.com/id/Beetle-Minimize-Your-Arduino-Projects/

I did use a big electrolytic polarized capacitor in parallel with the sim800l power pins (like 470uF 16v) on an uno.
It will handle the power on peak :)

When you are using a Arduino nano for your project you wont be able get the 2A current draw form the board.You have to use a external power source like a battery.You have to find a better battery with a considerable Ahs.


text:
Arduino HTTP Post request
I have a Arduino Mega with Wiznet 5100 Ethernet shield. Am trying to post some data onto localhost for started later on which will be accepted by a website.
But when I try to post the data I get some error. When I try to send the same data via postman it gets accepted . But when it goes from arduino error occurs.
The arduino Code is as follows:
client.println("POST /api/trackers/5a28eddaf57a6e2060e85601/solars/5a3bb2adf57a6e1a71ca135b/arduino_data HTTP/1.0");

client.println("Host: 192.168.6.16");

client.println("Accept: application/vnd.mirasol.v1");
Serial.println("After Accept application vnd");

client.println("User-Agent: Arduino/1.0");
Serial.println("After User Agent Arduino");

client.println("Accept: application/json");
Serial.println("After Accept application json");

client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

client.println("Content-Type: application/json");
Serial.println("After content type application json");

client.println("Connection: close");
Serial.println("After connection close");

client.println();
Serial.println("After client println");

client.println(postdata);
Serial.println("After post data");
Serial.println(postdata);

The output in the serial monitor is as follows:
    connecting...
connected
After Accept application vnd
After User Agent Arduino
After Accept application json
After content length
After content type application json
After connection close
After client println
After post data
{"current":10.50, "voltage":10.50}
H
disconnecting.

And the error shown in localhost is as follows:
2017-12-27 15:21:57 +0530: HTTP parse error, malformed request (): #<Puma::HttpParserError: Invalid HTTP format, parsing fails.>

I have the application in Ruby on Rails with Mongoid as the DB.
FYI: New to coding..

Your problem most likely stems from this bit:
client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

You have an extraneous "ln" in there causing the post data length to be on a separate line from the Content-Length:
Content-Length:
23

You should change the first println to a print. Also the order could do with changing to keep things logically grouped:
client.print("Content-Length: ");
client.println(postdata.length());

Serial.println("After content length");

Which would result in:
Content-Length: 23

Well did that and the rails server responded... But now am getting Completed 204 No Content . I want to send the data from the body instead of the URL to keep the security good in a way.

I would suggest, for debugging, duplicate all client prints to the serial so you can see precisely what is being sent to the server.

That 204 was there since I had not given any view or response for when the request would come in... Just went into the function and added a json response to it and it worked like a charm ... Kudos to u for helping ...


text:
Why is my Arduino code for running a Bluetooth controlled robot with obstacle sensor not working as it should be?
I have created a Bluetooth based smartphone controlled robot (a 4 wheel car) earlier using Arduino and an obstacle avoidance robot.
Now, I wanted to combine both of them. So, I combined their functions and codes in such a manner that felt right to me. But, it kinda seems wrong to my robot.
My Bluetooth Controlled robot was running smoothly. My obstacle avoiding robot was running flawless. But, when I tried to join them, both of them started crying.
I tried to change orders of the functions, adding some functions twice or thrice removing them from some places that didn't feel right then. Nothing was worthy.
I need to upload whole code because I'm not sure where am I doing it wrong
#include <SoftwareSerial.h>

#include <RemoteXY.h>

// RemoteXY connection settings
#define REMOTEXY_SERIAL_RX A2
#define REMOTEXY_SERIAL_TX A3
#define REMOTEXY_SERIAL_SPEED 9600

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,8,0,54,0,176,0,8,228,4,
  5,48,44,26,30,30,0,31,8,1,
  6,0,-84,-142,20,20,0,2,26,129,
  0,6,37,23,8,0,64,78,97,118,
  101,100,0,131,3,51,1,20,5,1,
  2,31,82,111,98,111,116,32,67,97,
  114,0,131,0,62,5,19,5,2,2,
  31,67,111,110,116,114,111,108,108,101,
  114,0,129,0,10,45,13,7,0,16,
  84,72,69,0,129,0,5,52,25,8,
  0,136,83,104,101,105,107,104,0,1,
  0,-34,-111,12,12,1,2,31,88,0,
  1,4,79,44,12,12,0,37,151,240,
  159,147,162,0,65,4,87,9,7,7,
  0,65,1,87,17,7,7,0,65,2,
  87,25,7,7,0,67,5,3,3,25,
  14,0,94,24,51,2,0,86,1,11,
  5,0,135,26,31,31,79,78,0,79,
  70,70,0 };

// this structure defines all the variables of your control interface
struct {

    // input variable
  int8_t joystick_1_x; // =-100..100 x-coordinate joystick position
  int8_t joystick_1_y; // =-100..100 y-coordinate joystick position
  uint8_t rgb_1_r; // =0..255 Red color value
  uint8_t rgb_1_g; // =0..255 Green color value
  uint8_t rgb_1_b; // =0..255 Blue color value
  uint8_t button_1; // =1 if button pressed, else =0
  uint8_t button_2; // =1 if button pressed, else =0
  uint8_t switch_1; // =1 if switch ON and =0 if OFF

    // output variable
  uint8_t red_led_r; // =0..255 LED Red brightness
  uint8_t blue_led_b; // =0..255 LED Blue brightness
  uint8_t green_led_g; // =0..255 LED Green brightness
  char text_indicator[51];  // string UTF8 end zero

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

#define PIN_BUTTON_2 A4
#define PIN_SWITCH_1 A5

#include<AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 250
//#define MAX_SPEED 150 // sets speed of DC  motors
//#define MAX_SPEED_OFFSET 20

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor left_motor_A(1, MOTOR12_64KHZ);
AF_DCMotor left_motor_B(2, MOTOR12_64KHZ);
AF_DCMotor right_motor_A(3, MOTOR34_64KHZ);
AF_DCMotor right_motor_B(4, MOTOR34_64KHZ);
Servo myservo;

int distance = 100;

int right_motor_speed = 0;
int left_motor_speed = 0;
//define two arrays with a list of pins for each motor
AF_DCMotor RightMotor[2] = {right_motor_A, right_motor_B};
AF_DCMotor LeftMotor[2] = {left_motor_A, left_motor_B};

//speed control of motors
void Wheel (AF_DCMotor * motor, int v) // v = motor speed, motor = pointer to an array of pins
{
  if (v > 100) v=100;
  if (v < -100) v=-100;
  if (v > 0){

    motor[0].run(FORWARD);
    motor[1].run(FORWARD);
    motor[0].setSpeed(v * 1.75);
    motor[1].setSpeed(v * 1.75);
  }
  else if ( v<0 ){

    motor[0].run(BACKWARD);
    motor[1].run(BACKWARD);
    motor[0].setSpeed(v * 1.75);
    motor[1].setSpeed(v * 1.75);
/*    //digitalWrite (motor [1], FORWARD);
    analogWrite (motor [2], (v) * 0.75);
    //analogWrite (motor [2], (-v) * 0.75); */
  }
  else{
    motor[0].run(RELEASE);
    motor[1].run(RELEASE);
    motor[0].setSpeed(0);
    motor[1].setSpeed(0);
  }
}

 int lookRight()
 {
    RemoteXY.blue_led_b = 255;
    RemoteXY.red_led_r = 0;
    RemoteXY.green_led_g = 0;
    sprintf(RemoteXY.text_indicator, "CHECKING THE RIGHT SIDE.");
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
 }

 int lookLeft()
 {
    RemoteXY.blue_led_b = 255;
    RemoteXY.red_led_r = 0;
    RemoteXY.green_led_g = 0;
    sprintf(RemoteXY.text_indicator, "CHECKING THE LEFT SIDE.");
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
 }

 int readPing()
 {
  delay(100);
  int cm = sonar.ping_cm();
   if(cm==0)
  {
    cm = MAX_DISTANCE ;
  }
  return cm;
 }

 void moveStop()
 {
  left_motor_A.run(RELEASE);
  left_motor_B.run(RELEASE);
  right_motor_A.run(RELEASE);
  right_motor_B.run(RELEASE);

 }

void setup()
{
  RemoteXY_Init ();

  pinMode (PIN_BUTTON_2, OUTPUT);
  pinMode (PIN_SWITCH_1, OUTPUT);

  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);

}

void loop()
{
  RemoteXY_Handler ();

  digitalWrite(PIN_BUTTON_2, (RemoteXY.button_2==0)?LOW:HIGH);
  digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);

    int distanceR = 0;
    int distanceL =  0;
    delay(40);

    if(distance<=27)
    {
      moveStop();
      RemoteXY.blue_led_b = 0;
      RemoteXY.red_led_r = 255;
      RemoteXY.green_led_g = 0;
      sprintf(RemoteXY.text_indicator, "AN OBSTACLE HAS COME IN FRONT OF YOUR ROBOT!!!");
      digitalWrite(PIN_BUTTON_2, HIGH);
      delay(1500);
      distanceR = lookRight();
      delay(250);
      distanceL = lookLeft();
      delay(250);

      if(distanceR>=distanceL)
      {
        RemoteXY.blue_led_b = 255;
        RemoteXY.red_led_r = 0;
        RemoteXY.green_led_g = 0;

        sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE RIGHT SIDE.");
      }

      else
      {
        sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE LEFT SIDE.");
      }
    }
    else
    {
      RemoteXY.blue_led_b = 0;
      RemoteXY.red_led_r = 0;
      RemoteXY.green_led_g = 255;
      //manage the right motor
      Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
      Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);

    }
    distance = readPing();

    //manage the right motor
    //Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
    //Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);

  }

I want my Robot to work on my directions and when he senses something on its front end then he should stop there and tell me through a RemoteXY.text_string and then check for obstacles at the left and right side and tell me on which side it is available to go. After that, it should again take my orders via my mobile phone.
Firstly, it became impossible to connect the robot to the Smartphone using Bluetooth because the robot was very busy in doing some other stuffs (only he knows what was he doing). Then, I applied a "RemoteXY Button" on my code (that is not in the code that I'm posting here) with an "if" block; such that if this switch is pressed via the Smartphone, only then the robot will start moving. So, doing this thing helped me to connect my robot to my smartphone via Bluetooth but, when I was connection then the Servo Motor was regularly spinning (again, I don't know why) after secure connection, when I turned that switch on, then my robot took only my first order (which is usually moving forward) and it performed on my first order for almost first 3 to 5 seconds and then the Robot got his system hanged and my smartphone was automatically disconnected from the robot.
I am unable to figure out where is the filth in my code or my code is itself fully filthy. This is the matter, where I need you guys' help
Other information that you might need for better Support/help, I am using:
1). RemoteXY app for Android to Robot Communication
2). Arduino UNO as Microcontroller
3). Arduino IDE for Programming Arduino
4). One SG 90 Servo Motor.
5). Four Geared DC- Motors.
6). L293D Motor Driver Shield for driving Dc motors and the Servo
7). HC SR-04 ultrasonic sensor for obstacle sensing
8). A 12V battery
9). HC-05 Module for Bluetooth Communication
10). A buzzer for external indicator/horn. At pin A4
11). A filthy code for Arduino Programming .
Any help with the code will be appreciated.
Thank You So Much in advance. ❤

I guess you are using this library. You have some longer delays in there. Can it be, that the RemoteXY_Handler has to be called more often, so that the App won't disconnect bluetooth? Currently the app might think, that the connection is lost, because if the distance is low enough, the Arduino will not be able do send any data to the app. That would resemble the behavior of the yield function on ESP. Try with a code without long delays

@chrisl  Yeah it might be possible. I'll check it out and update you. Btw I tried reducing some delays but that helped robot to take only one order. So, I think it might help me.  One more thing: Is my robot's microcontroller getting hanged because of so many tasks? I mean he is checking for obstacle and stoping in front of it, meanwhile I'm giving it more orders from my smartphone. So, plenty of multitasking might be resulting in the freezing of processing of the robot?  What do you think? And if Yes so, then how could it be modified and improved?

That's not generally too much. But a microcontroller can only do one thing at a time. So to multitask you have to switch between the tasks very fast. To do this, you should use non-blocking code, like in the BlinkWithoutDelay example, that comes with the Arduino IDE. You should look into Finite State Machines (FSM). They are easy to program and a good way to structure your program.

@chrisl Could you please share a link with me about FSM(s), that may help me since I have no idea about Finite State Machines. I tried reading Wikipedia Article but I was unable to understand that.

@chrisl  This tutorial looks interesting. Will it be enough to help me out on this issue?  I'll try implementing it on my code. If it helps me out, I'll give you an update. If I get stuck in some problem, I'll need your help. I urge you to help me then.

My guess is, that the function RemoteXY_Handler() has to be called very regularly (without long pauses in between) to communicate with the app on your smartphone, or the app will think, that the communication is lost, and disconnect from the robot. This means, that you cannot use long delay() calls in your code, since that is just busy waiting. In your code in case of an obstacle in front of the robot, you wait 3.6s in total. That is too much. The robot is doing nothing in this time. Instead you should use a non-blocking coding style. That means, that the code will not block, waiting (and doing nothing) until an event happends (for example a specific amount of time passed), but instead will execute other functions, until the event occurs. That is a generally better way to program a microcontroller, since it enables you to add more functionalities easily without disturbing the program flow.
Here you try to do timed things with delay(). Instead you should use a coding style, like the one found in the BlinkWithoutDelay example, that comes with the Arduino IDE. It is explained various times throughout the internet and this site. Basically it is like regularily looking at your watch (the millis() function here) and only doing things, when the time has come. You should look at the example and maybe go through some of the tutorials about this, so that you really understand, what happens there. Then you can start to rewrite your code and eliminate all delay() calls. That will need some restructuring of the code.

The BlinkWithoutDelay example is an easy structure, since it contains only few logic. Your goal is a bit more complex. So I suggest, that you use a Finite State Machine (FSM). It is rather easy to implement and a powerful tool to structure your code. It's definitely worth learning for every programmer.
A FSM consists of multiple states, that are connected by transitions. In each state there can be code executed. Also there might be code, that is only executed on transitions. First you have to model your project into states. One state here could be REMOTE_CONTROLLED, which would just execute the commands coming from the app. Based on input from sensors and the app you can then transition between the states. If you see, that you might need a delay() inside a state, that might be a hint, that you can further divide the state into substates. For example I would make an extra state, which gives the servo the time to move. I would suggest, that you really draw a graph for your project with all your states (state name in a bubble). Then draw arrows as state transitions between them. This will give you a good overview of the structure to implement.
In code this is often implemented with a switch() case structure and a state variable:
int state=0;
int distance = 100;

void loop(){
    RemoteXY_Handler ();
    distance = readPing();

    switch(state){
        case 0:
            // Do whatever the remote demands here
            if(distance <= 27){
                // Execute code, that should happen once at transition here
                state = 1; // This makes the transition to the next state
            }
        case 1:
            // Code of the next state
    }
}

With this structure at every time only the code of the current state will be executed. The transitions are made simply by setting the state variable to the next desired state. To make the states more speaking in the code, you can use an enum, so that every state can be referenced with an enum name. The remote handler and the reading of the distance is done outside the FSM here, since you always need the input from those. Based on them, you can do state transitions.
To do timed things in an FSM, you can put the millis() code (like in the BlinkWithoutDelay example) into the corresponding state.

Note, that this is only one way to implement a FSM. The video, that you linked, does this a bit different by using functions pointers (the state() function pointer is the state variable here). The principle is the same, only the programming structure is different. You can decide yourself, what works better for you, and what you understand better (pointers can be a bit difficult to understand for beginners).

Thank You So Much @chrisl for guiding me to the right path. I am familiar with Pointers in C Language as I have done a crash course on C Language. But, I am not master of that. So, I'll better use the way that you told me here. I have read your whole answer and after perfectly understanding everything that you've told here, I'll try to implement it on my code and project. Then, I'll leave an update here that how it helped me or what is confusing me while implementing.  Thank You So Much again Sir


text:
Can I connect Multiple Devices to One 5V and one GND pin of my Arduino Uno R3
I have made a Bluetooth Controlled Robot Car. Using L298N Motor Driver, HC-05 Bluetooth Module and Arduino R3 I was able to run it by giving one "VIN" and one "GND" to L298N, one "5V" and one "GND" to HC-05 and I gave 12V input to the Arduino Board.
But now I want upgrade it to an upper level by adding IR transceiver as obstacle sensor and a buzzer (as a horn, such that it will sound whenever any obstacle is sensed OR I'll set a button in the GUI to play the horn)
Please Help me. I am a very beginner and assume it as my first project.
Any kind of help would be appreciated.
Thanks in advance.

Yes, you can connect multiple devices to GND and +5 V. You may find that you need to bring one wire from the PCB to an external connector or piece of stripboard so that you can make more reliable connections.
Watch that your total current does not exceed the rating for the voltage regulator or USB power supply.

You can also use a breadboard to “split” the 5V and GND.


text:
NFC PN532 SPI - Error: Timeout when waiting for ACK
I've been struggling to get the PN532 module working over SPI with an Arduino Uno.
I have the wires connected as follows:
SCK   -> 13
MISO  -> 12
MOSI  -> 11
SS    -> 10
VCC   -> 5V
GND   -> GND

And the board mode set for SPI as follows:

When I run the code below I get this output:
-------Peer to Peer HCE--------
write:  02
Time out when waiting for ACK
Didn't find PN53x board

Code:
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"

PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);

void setup() {
    Serial.begin(115200);
    Serial.println("-------Peer to Peer HCE--------");

    nfc.begin();

    uint32_t versiondata = nfc.getFirmwareVersion();
    if (! versiondata) {
      Serial.print("Didn't find PN53x board");
      while (1); // halt
    }

    // Got ok data, print it out!
    Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
    Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
    Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

    // configure board to read RFID tags
    nfc.SAMConfig();
}

void loop()
{
    // Truncated
}

I've been trying to edit the source files and find the problem but I cannot seem to find whats causing it. Some help is much appreciated :)

According to https://dangerousthings.com/wp-content/uploads/PN532_Manual_V3-1.pdf you are doing everything correctly, Uno pins and supply voltage is okay.. Can you invert the two switch positions for interface selection for fun? Can you try their example code from the PDF? Can you try the I2C interface?

@MaximilianGerhardt I cannot use anything else than SPI, because I probably broke the SDA and SCL soldering points when trying to resolder them... (Perhaps this explains the weird behavior and is the chip dead, but I am refusing to believe that for now). Concerning the code, this is the exact code from their GitHub.


text:
Reduce speed on DC motor
The Arduino starter kit came with a DC motor. I want to have it rotate at a slow speed so it can be on a reel and automatically dispense and wind wire, however, I don't know how I can slow it down.
Giving it an analog value of 1 is still way too fast.
Is there any way to control or reduce the speed. Like a 360 degree turn in a second rather than milliseconds?
Thanks

Remember if you are using a UNO or similar there is no Analog Output, the output is PWM (Look that up).
If its DC motor then it needs to work from a DC (constant voltage) and will spin at a fixed speed.
Motors usually have a RPM (speed) specification.
Speed can be reduced with gears and rotation detected with rotary encoders and or sensors like Infra Red Switches or Reed Switches.
You can also get Motor Controllers like...
https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
AC Motors can be speed controlled by changing drive frequency, this is usually called an inverter.
NOTE reducing DC voltage will result in less torque and higher current.
Hope this helps.


text:
Multiple esp32s running on batter power using ESP-NOW
I have a project where I'd like to have two esp32s communicate using ESP-NOW, but both running on battery. I'd like for both to be in deep sleep, wake up and communicate, and go back to sleep, repeat.
What's the best way to handle this? Would trying to coordinate waking and sleeping with the RTC be possible? Should I have the wake up more frequently and wait a bit for a message from the other? Other ideas?
In the absolute worst case scenario I could potentially have one running on an outlet which would make this easy, but it's highly preferable for both to run on battery power.
Thanks!

Perhaps ESPNow software features have changed since I had last done this. But IIRC, there is a receiver and many transmitters. The receiver always has to be listening. The transmitters can sleep. There was no guaranteed delivery. It was meant to be quick & fast. Unlike WIFI where there is a lot of negotiations going on before data is sent. Which takes more time and likely cuts your battery life considerably.

(I should just turn these comments into an answer.) Also, again, IIRC, the sleep timers were not accurate and were influenced by temperature. Likely to sleep both the transmitter and receiver, you would have to write clever code on the receiver to synchronizing it (calculate the receiver's next sleep timer value) with the transmitter's short messages.

how far apart are the two devices?  ... you could add another ESP32 that is powered from an outlet to act as a synchronizer

@st2000 Oh, that is is a lot of great info, thanks!! Sounds like my approach might not be the best route to go. I was trying to avoid wifi since from my research it looked like ESP-Now was more power efficient. But if I end up using wifi I guess I could use a web bucket as an intermediary, way it doesn't matter who's awake or asleep.

@jsotola About 30 ft. Oh interesting! That might be a viable solution. Thanks!

It is my understanding that ESPNow is using "WIFI frequencies" but the messages are really short. And, because the messages are very abbreviated, are ignored by "real WIFI" as bad data. ESPNow saves on battery life because the messages are really short. But there is no guaranteed delivery. ESPNow works best where data can be sent repeatedly. Such as remote temperature sensors or door open/close sensors.

I did something similar for two devices but using a different hardware base: https://forum.arduino.cc/t/synchronised-nrf24l01-transceiver-pair-for-low-power-operation-using-the-attiny1614/925264 . It is not simple because you have to have a strategy for recovering in the case of a lost transmission and have timing tolerance so the receiver is on just before the expected transmission.

@6v6gt Holy crap! This is pretty much exactly what I was looking for, thank you so much!
If you want to put this as an answer I can mark it. Thanks!


text:
Teensy 4.1 audio cuts out when motor moves
I have a Big Mouth Billy Bass project, using a Teensy 4.1, teensy audio shield connected to speaker through line out to an amp, and two MX1508 motor controllers to control the body and mouth motors.  Code is here https://github.com/ambrice/billybigmouth/blob/main/billybigmouth.ino
I'm starting the save with AudioPlaySdWav play() and that works, and while that's playing I can run MX1508 motorGo() on one of the motors and audio plays.  But if I move the head and then use motorGo() on the mouth motor, the audio stops playing for the time when the mouth is being moved.  It picks up later in the song after, so it's like it was on mute during that time.  I assume there's an issue with playing audio and driving two PWMs at the same time, how do I get all three working at the same time?

Welcome to SE/Arduino! Please take the [tour]to learn how this site works, and read "[ask]" and other pages of the [help]. Then come back and [edit] your question to provide details, like a minimal, complete(!), and reproducible example sketch. Since you suspect "interference" between audio and PWM, it is especially important to know the details.

There is a link to the complete code with all the details in the question

Please learn how this site works. Questions are supposed to be self-contained, that means include the [mre] directly. External resources tend to vanish, and this is not a forum.


text:
Using time function in arduino
how to get exact timestamp of a sensor reading and compare it with other sensor values in arduino?
Ex: Get the time of low reading of LDR and compare it

You see that word in the tag that you chose? That's the name of the function you want.

You should clarify 1) what do you mean by exact (you need to specify the resolution needed), 2) what kind of sensors you are using (particularly how long does it take them to make a measurement) and 3) if you have a target, the accuracy you need (accuracy != resolution)

Are you after a human readable timestamp (eg. 17:53:43) for logging etc. or are you after a machine timestamp (eg. 42750 ms after powerup)? If the machine timestamp is fine then use millis() as others have suggested.

@nuwankarunarathna Really more details are needed to answer this question.

i want to get two readings from two ldr sensors and need to have the exact time that ldrs are gone low.(low light condition). this has to be done over multiple times and i should have the capability to compare the values

As Majenko said you can use the millis() keyword.
Unless millis is not accurate enough. In that case you can use micros(), but this overflows every 70s if I'm correct, but you can offset it against millis().
If you need to compare two values, what you can do is:

get millis()
get micros()
read sensor data (optimize if needed)
get micros()

Average the difference of the micros, and add it to millis, and you have the average time for the sensor data readings.
Of course if it doesn't matter that all sensor data is read at approximately the same time, you can use millis() for each sensor data reading and work with those values.

Why should you take the aveage timestamp of the measure and not the beginning or the end? I think that the beginning is more consistent and more appropriate (usually you acquire and then elaborate, so the actual measurement is closer to the beginning rather than the end)

@frarugi87 I also would use the start, but if you need the one time stamp for multiple measurements, the 'average'  might be more applicable.

since arduino code is in a loop how can i exactly know the time

You first get the time with millis(). Than immediately afterwards you do the measurement. Assumign the measurement takes very little time, you can use the millis() value as 'timestamp'.


text:
Building an EEZYBOTARM MK1
My bot arm building is complete, I'm using it with Arduino and 2 joysticks with 4 servos ( mg90s), running with the 9v battery, but still, the servos could not lift the bot arm once it is going down and the servo keeps fluctuating. It is a 3d printed bot so it is not so heavy. please help?

A little wimpy PP3 battery?

Even if your device is not so heavy, a 9V battery has a maximum practical current draw in the 10s of milliamps. It's not a good choice for operating motors.
A better choice would be AA, C, D, or Lithium-Ion/Lithium-Polymer batteries, wired in series to produce the desired voltage.

how much volts AA batteries?

Nominally 1.5V per cell (each AA is one cell)

will 5, AA 1.5v each work fine?

I can't answer that for you. It depends on the specs of your servos, how long you want the device to operate on one set of batteries, etc. If you needed to get to 9V, then 5 AAs will not do it. The 1.5V per cell is the max, and as they discharge, the voltage will drop lower and lower.

The proper number of batteries depends on how your servos are powered.  You must not use the Arduino's regulator for this.  Run bare they want 4 or 5 AA's depending on their maximum voltage rating and the cell chemistry.  However 5 AA's is not reliably enough to feed an Arduino's regulator.


text:
How to use digital pin as ground?
I have recently brought an arduino nano. It has only two ground pins but I needed three for my project. Is there a way to use a digital or analog pin as ground pin? Please show me how to do it

ground is only one. connect every ground wire to one ground pin

Careful with using GPIOs as GND sinks.. An I/O pin can sink only so much current. For a GPIO bank, 100mA max, one pin recommended 20mA (https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations). I would connect directly to the main GND (from the power supply). Solder a few more wires if you have to.

If your project is on a breadboard, you can use one of the "rails", typically the blue longways row at either edge of the breadboard, to collect all of the necessary grounds, and wire that to one Ground pin on the Arduino.
If you're building a printed circuit board to connect to the Arduino, do the same thing - collect all of the PCB grounds together and wire that to one Arduino Ground pin.
If you're using a manufactured shield, you may have to get creative about collecting your grounds. A tiny breadboard is one way. Another is to solder a number of wires together in star-formation, insulate the solder joint with tape or shrink-tube, and connect one of the star's points to the Arduino ground.
If some of your devices needing grounds are low-current devices such as LEDs, you could set an unused pin to OUTPUT mode, and LOW, and use it as a ground, but the device must not be passing more current than an Arduino pin driver can sink. From Atmel's data sheet for the AtMega328p (used in the Uno):

Although each I/O port can sink more than the test conditions (20mA at
      VCC = 5V, 10mA at VCC = 3V) under steady state conditions
      (non-transient), the following must be observed:
ATmega48A/PA/88A/PA/168A/PA/328/P: 1] The sum of all IOL, for ports C0 - C5, ADC7, ADC6 should not exceed 100mA.
2]     The sum of all IOL, for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100mA.
3]     The sum of all IOL, for ports D0 - D4, RESET should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.

There is no need to separate grounds, you can connect all grounds together. In fact they are connected together on the board itself.

You can just try converting two digital pins as 5V VCC and ground.
This will be useful when we use multiple sensors.
#define VCC2  5 // define pin 5 or any other digial pin here as VCC2
#define GND2  2 // define pin 2 or any other digital pin as Ground 2

void setup() {
  pinMode(VCC2,OUTPUT);//define a digital pin as output
  digitalWrite(VCC2, HIGH);// set the above pin as HIGH so it acts as 5V

  pinMode(GND2,OUTPUT);//define a digital pin as output
  digitalWrite(GND2, LOW);// set the above pin as LOW so it acts as Ground
}

void loop() {
}

I'm not sure I'd recommend this, but if you're going to do it you should know that it will have very limited current available, which will depend heavily on the Arduino involved, or rather its MCU.  You might allowed up to 40mA, but also perhaps only 4mA. And that your new "VCC" will drift toward ground as you draw more current.  Likewise with "GND" raising toward VCC.  They may not start as near the board VCC and GND as you like, as they're not intended for this purpose but only to produce logic levels.

It can be useful if you need to turn on/off the sensor during operation, but as timemage said, it is not advised. Using a transistor controlled by the Arduino's pin is way better.


text:
bluetooth module and pic
I am currently working on a project that requires bluetooth module and pic. I need to get the ID or address of the connected device.Any idea how can i do it. I only know that this is done using AT commands.

Which bluetooth module are you using? Can you show us the sketch you used to try and get the address?

i am using HC-05 module.I am connecting this module with my phone and want to access my phone's ID or address.

Please edit your question and show us the sketch you are using.


text:
Arduino uno PWM CTC mode - strange behaviour on interrupt
i have this simple code that i use for generating a square wave signal of 125 KHz on pin 9 using Timer1 in the "Clear Timer on Compare Match (CTC) Mode".
I also use Timer1 Compare Match A interrupt for toggling pin 7 of PORTD.
void setup() {
pinMode(9, OUTPUT);
pinMode(7, OUTPUT);

TCNT1 = 0;
TCCR1A = 0;
TCCR1B = 0;

OCR1A = 7;
TIMSK1 = _BV(OCIE1A);
TCCR1A = _BV(COM1A0);
TCCR1B = _BV(CS11) | _BV(WGM12);
}

void loop() {
}

ISR(TIMER1_COMPA_vect)
{
  PORTD = PORTD ^ 128;
}

It happens that

The 125KHz waveform on pin 7 is delayed by 1us with respect to the waveform of pin 9. I think that is related to the time that the microcontroller takes to "entering" the interrupt function and toggling the PORTD pin (1us are 16 clock cycle of the 16MHz master clock).
Sometimes the waveform on pin 7 (the one generated inside the interrupt service routine) has some "gaps". For example, this is the waveform acquired with my scope:Why this strange behaviour happens?

Thank you

This isn't the only ISR in the Arduino, there is at least the one counting millis. Counter 0 overflow ISR is not as short as yours, so every 1024us it'll cause some jitter (or as in your case, skipping the edge and basically inverting the phase). It'd be also several clock cycles delayed (against HW generated signal). Pushing and poping the registers into the stack are the deterministic delays, but the latency between setting the ISR flag and calling the ISR routine depends on currently executed instruction (some of them takes 2cycles, and there are also longer ones).
There is not much time to do anything else either. Your ISR might take less than 20 cycles, but you only have 64 cycles (ISR is called at 250kHz rate so it generates 125kHz signal).
So if anything else prevents your ISR to be called (another ISR, disabled interrupts), you can miss them, as there is only one interrupt flag.
If you want the same waveform on pin 7, just use a wire and let the pin mode as INPUT.
BTW: You don't have to use PORTB = PORTB ^ _BV(PB7);, the PINB = _BV(PB7) toggles PB7 without read-modify-write access.

Thank you for the detailed explanation! Also setting TCCR0A and TCCR0B to zero solved the problems with the "gaps".

@Anacleto but be aware of using anything related to millis like delay. It's exactly the same problem as you can't use the delay in another ISR.


text:
Is my HC-SR04 sensor broken?
I am extremely new to Arduino and electrical engineering, and the project I am attempting involves a ultrasonic sensor.  I am using the HC-SR04 with the Elegoo Mega2560 Arduino board.  A few days ago I was able to print out the distance correctly with an Arduino library, but after adding a h-bridge, 2 motors, and 2 9-volt batteries, the sensor didn't seem to work properly.  I went back to a simple circuit with only the HC-SR04, and the distance readouts were all over the place.  No matter what, the distance stayed between 90 and 120, mainly staying in the 110s.  These numbers seemed to have no correlation with the actual distance.  I even tried to calculate the distance myself in case there was something wrong with the library.
I have the VCC pin on the HC-SR04 connected to the 5v on the Arduino, the GND pin connected to the GND pin on the Arduino, the Trigger pin connected to pin 50 on the Arduino, and the Echo pin on the Arduino connected to pin 52 on the Arduino.  The Arduino is connected to my computer through USB.
Here is my sketch for printing out the distance without a library:
const int triggerPIN = 50;  //these are digital pins on the Arduino board
const int echoPIN = 52;     //I'm sure these pins aren't broken because I never used them before now

long duration;
int distance;

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

    pinMode (triggerPIN, OUTPUT);
    pinMode (echoPIN, INPUT);

    delay(1000);
}

int getDistance () {
    digitalWrite (triggerPIN, LOW);
    delayMicroseconds (2);

    digitalWrite (triggerPIN, HIGH);
    delayMicroseconds (10);
    digitalWrite (triggerPIN, LOW);

    duration = pulseIn (echoPIN, HIGH);
    distance = duration * 0.034 / 2;

    Serial.println (distance);
}

void loop() {
    getDistance ();  //I tried putting the code directly in the loop function with the same result
}

I am afraid that I broke either a part of the Arduino board or the sensor when I was fiddling around with the two batteries.  Is it possible to break a HCSR04 sensor by connecting two much voltage to the VCC pin on the sensor?  If so, how should I prevent this in the future?  I know that the working voltage for a HCSR04 is 5V, does this mean it needs at least 5V or no more than 5V?  I wanted to know for sure that it was broken and not an error on my part before I bought a new one.    Thanks in advance!

Unfortunately, it seems the HC-SR04 has no proper datasheet with maximum values. The only documents you can find define the operating voltage of 5V. I personally tested it with less than 5V (IIRC I could make it work at 4V and a bit less).

The code that you have provided for the distance calculation is fine according to me. There is a high chance that you might have damaged your HC-SR04, Ultrasonic sensor.
As you have asked about how to prevent this from happening in the future, I would suggest that you should use a voltage regulator in the circuit, LM7805, it restricts the output voltage to 5V - just matching your ultrasonic sensor's operating voltage as it works perfectly at 5 Volts.

Thank you so much Manav.  I bought a few more ultrasonic sensors and the sketch works perfectly. I will definitely look into a voltage regulator.

Amazing! Glad to be of help.

No.  Don't use a discrete 7805.  The Arduino already has a better regulator which is wired up properly, while adding another one is easy to get wrong.  And should the ground connection not be there, even for an instant, the regulator will pass the full input voltage.

A major functional difference between the code in your question and the usual ping sensor example is that your code repetitively measures as fast as it or the output stream will allow.
In contrast, the normal example has a delay(100) after each measurement cycle.  This allows 1/10th of a second time for any longer room echoes to die out, and thus avoid confusing new measurements.
While that might not be your immediate or only problem, it is generally a good idea not to try to take sonar measurements so closely spaced in time that they could overlap.
Should your sketch also need to do other things, instead of a blocking delay() you can check the elapsed time and only take a new sonar measurement once a certain amount of time has passed; in the meantime your program can continue with any other critical operations.

I guess the main problem is a serial printing. It always bother the system mainly the analog reading. It's quiet good for check some sub result while you programing (what the return value from a method etc) but not good to test your project result. In this case the distance measurement. Try a different way, put some led into the circuit and if the distance over 10cm switch on first, if over 20 cm switch on the second and so on. Or write the result  on an lcd panel, or 8x8 led.

I will keep that in mind for future projects, an lcd panel seems like the way to go.

No, the problem is not serial printing.  But putting in a delay (or non-blocking timer check before taking a new measurement) to allow any old echoes to die out would not be a bad idea.


text:
Libraries/classes using other libraries/classes
This is, hopefully, a simple issue!
I'm trying to access my fully working libraries (fully compiles, and works with the hardware perfectly) from another library (Computer.h) to abstract it away from the Sketch.ino file.
LLRelay, and all my other libraries, work flawlessly when instanced/constructed/built/etc within the main Sketch.ino; however, when called within "Computer.h", there's issues.
I've been at this for most of the day trying different things, from instantiating the libraries in the header files, the *.cpp files, to within functions, to changing the scope and publicity/privacy of them - still no luck.  See the (2 * "HERE -") comments for the errors.
Any help is greatly appreciated!
This is what I have managed to reduce it down to for debugging:
Sketch.ino
// Sketch.ino
#include "Computer.h"

Computer pc1;

void setup(){};

void loop(){
    pc1.update();
};

Computer.h
// "../customLibs/Computer.h"
#ifndef Computer_lib
#define Computer_lib
#if(ARDUINO > 100)
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class Computer {
    public:
        Computer();
        void update();
    private:
        void fans();
};
#endif

Computer.cpp
// "../customLibs/Computer.cpp"
#include "Computer.h"
#include "src/relay/LLRelay.h" /* Potential culprit, I have tried many variations and locations for this to go, all with the same, or similar compilation errors */

/* HERE - "undefined reference to `LLRelay::LLRelay(unsigned char)'" */
LLRelay fan1(13); // fan1(uint8_t relayPin);

Computer::Computer(){
    Serial.begin(9600);
};

void Computer::update(){
    fans();
};

void Computer::fans(){

    /* HERE - "undefined reference to `LLRelay::On()'" */
    fan1.On();

};

LLRelay.h
// "../customLibs/src/relay/LLRelay.h"
#ifndef LLRelay_lib
#define LLRelay_lib
#if(ARDUINO > 100)
  #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class LLRelay {
  public:
    LLRelay(uint8_t relayPin);
    void On();
    void Off();
  private:
    uint8_t _relayPin;
};
#endif

LLRelay.cpp
// "../customLibs/src/relay/LLRelay.cpp"
#include "LLRelay.h"

LLRelay::LLRelay(uint8_t relayPin){
  _relayPin = relayPin;
  pinMode(_relayPin, OUTPUT);
  digitalWrite(_relayPin, LOW);
};

void LLRelay::On(){
  digitalWrite(_relayPin, HIGH);
};

void LLRelay::Off(){
  digitalWrite(_relayPin, LOW);
};

The Arduino IDE must detect the library to include it in the build process. It is done by matching a library to a header file by searching the libraries in configured library locations. Only the root folder and the src subfolder of a library are searched.
If your library is in the sketch folder's libraries subfolder and it is called customLibs, then only the customLibs folder and the customLibs/src subfolder are searched and the include file LLRelay.h in customLibs/src/relay folder is not found.
reference: Layout of library folders and files

The Arduino build process does not consider libraries used from other libraries. You will need to include src/relay/LLRelay.h in the main project file in order to make it compile.


text:
Can SPI and serial.begin be used at the same time?
I have two modules where I want to control them through a single Arduino UNO.
I guess Serial.begin(9600) uses serial port and UART. But Im not sure about SPI.
Can I use SPI library hence the SPI communication together with serial communication(serial.begin) at the same time to communicate with two different modules?

Yes. UART and SPI are completely different things.  One uses pins 0/1, the other uses pins 11/12/13, and they use separate hardware and control registers inside the chip.

Thanks is it possible to use some other pin than pin 11 for SPI? Im currently using 8 9 10 and 11 for another module.

No. 11/12/13 are SPI. That can not be changed. Ever. It's written in stone (well, silicon, which is what most stone is made of).  You could bit-bang SPI using shiftIn() and shiftOut() on other pins if you don't need any great speed or full duplex operation if you really want.

I see then I will try to change the other module's pins.

@atomant if you're using a "Software SPI" you can use as default wired of SPI on your module. else if you're using a "Hardware SPI" you can define another pinout as SPI wire!!


text:
Reading consecutive two pulse periods continuously
I'm controlling the DC motor/fan speed by PWM through varying analog input. Using Uno or Nano.
The loop is as follows:
void loop()
{
  val = analogRead(analogPin0);  // read the analog input pin
  analogWrite(pwmPin9, map(val, 0, 1024, 0 , 255));
}

Above analogPin0 value is varied by a poti.
But I also want to output the rpm on an LCD. To do that I need to measure the period between two consecutive pulses as shown below:

How could I measure continuously "period between two consecutive pulses"? Should I use interrupt? Does anybody have any experience with that?

About what time range are we speaking here for the period?

One pulse period from minimum 4ms up to 100ms

why do you need to measure the signal? ... you know exactly the value of the parameter that you are passing to the analogWrite() function

I dont know the exact rpm just the duty cycle

did you forget to tell us about a revolution sensor? ... it is unclear how you expect to determine the fan RPM from the pulse width of the power supply voltage

I see 2 ways to go here:

You could attach a simple interrupt for rising edge to the pin with attachInterrupt() and count the rising edges with a variable. If the third rising edge is sensed, you have 1 period. To measure the time you can save the starting time of the first rising edge to a variable with micros() (which gives you the time since startup in microseconds). At the third rising edge save the time difference between start and end to another variable (declared volatile): micros()-start_time. This variable can then be displayed in your loop() function. Be sure to only copy the variable to a local variable in this part and deactivate interrupts during this operation with noInterrupts() (reactivate interrupts after that with interrupts(). Also you should use an atomic flag variable (atomic meaning, that writing or reading this variable cannot be interrupted. For example if you use byte or any other 1byte variable) to show the loop() function, that there is new data to display. Only if that's the case, the code in the loop() function would process the data.
If you want to go fancy or if you want to measure higher speeds (lower periods), You can use the hardware of Timer1 as counter. You give the Timer1 your signal as clock input. On every edge the timer value get's incremented by 1. So when the timer value is 5, one period has passed. You can use the timer in compare match mode, so that it will generate an interrupt, if a special value (here 5) is in the timers value register. In that ISR (Interrupt Service Routine) you would record the current time with micros(). On compare match the timer will generate the interrupt, set the value to zero again (if configured right) and again start to count. So the period would be the time between 2 consecutive time measurements. Displaying in the loop() function can be handled similar to the principle above.

It might also be good to directly take a mean of the period (to filter out noise in the period) by counting, until multiple periods have gone by. In the first case you could count to 11 to get 5 periods. Then divide the time difference by 5 to get 1 period. For the second case you can set the Timer1 match register to 21 to get 5 periods. Here also divide the time by 5 to get 1 period.
Since you seem to be a beginner, I would suggest the first way: Using attachInterrupt(). The second way is more if you want to dig into the microcontrollers registers and the descriptions in the datasheet.
The first way could look something like this:
const int pin = 2;

volatile byte counter = 0;
volatile unsigned long start_time;
volatile unsigned long period;
volatile byte data_flag = 0;

void speed_ISR(){
    counter++;
    if(counter==3){
        unsigned long now = micros();
        period = now - start_time;
        data_flag = 1;
        start_time = now;
        counter = 1;
    }
}

void setup(){
    pinMode(pin, INPUT);
    attachInterrupt(digitalPinToInterrupt(pin), speed_ISR, RISING);
}

void loop(){
    if(data_flag){
        noInterrupts();
        unsigned long local_period = period;
        data_flag = 0;
        interrupts();
        // Now display the period on the LCD her
    } else {
        // Print zero to the LCD
    }
}

The code gives you the opportunity to write zero to the LCD, when there is no pulse input (hence no data --> data_flag has to be zero). This may be uncomfortable to read on low pulse frequencies, if the LCD doesn't need longer to display the results as the next pulse will be measured, as it might display zero and the next measurement in fast succession. You could either use millis() to set data_flag to zero after a specified time (instead of resetting it near the LCD code), or you can limit the display rate like the blinking is done in the BlinkWithoutDelay example, that comes with the Arduino IDE.
Note that this code is not tested.

I get an error as : expected primary expression before "==" token. this is at the line if(byte==3){

will byte be counter?

And also having "'NoInterrupts' was not declared in this scope "

Ok, typing errors. Yes, the if statement in the ISR should be with counter. Also it is noInterrupts(), not notInterrupts. Sorry, I have changed my answer

And there are missing 2 semicolons in the ISR. I hope now it is structually sound

Which pins instead of pin 2 I can use?

I changed the attachInterrupt call, to make it really correct as in the documentation. You can look [here][https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/] for a table, which pins can be used. The documentation says on the Uno you can use the pins 2 or 3.

micros() should be called only once within the ISR: unsigned long now = micros(); period = now - start_time; start_time = now; ... Note that only period and data_flag need to be volatile. counter and start_time can be static locals of speed_ISR().

About the volatile variables: Yes, you are right. About micros(): Why shouldn't micros() be called multiple times? The value will not change during the ISR, since this relies on interrupts

@chris Could you update your code? Will this part be outside of ISR unsigned long now = micros();
period = now - start_time;
start_time = now;
?

The call to micros() takes a non-trivial number of cycles. And its value will change during the ISR, as it relies on a timer.

My another issue I couldn't modify the program to output zero when there is no pulse input.

if(!data_flag) would do it I guess?

@atmnt I changed the code again, since Edgar is right about micros(). Unlike millis(), micros() will also change during an ISR, since it reads directly from the timer register. I also added the requested functionality, a description about the pitfalls and how to avoid them.

An interrupt off of one of the timers sounds like the easiest way to go. To get a measurement precision of, say 3% at 4ms means sampling every (4000us * .03) = 120us (8.333 KHz). If your code has little else to do, you might get away with clock-watching - micros() ticks every 4us - but you'll need to keep anything else you do between reads of micros() to under 120us, and half of that might be a good target figure.
In this answer I described a general non-blocking procedure for managing several tasks in a timely way. If you chose such a design, one task might manage the potentiometer and analog output, another one the RPM measurement, and another the LCD. The ISR would do nothing but set a flag.
The RPM & LCD tasks can run at a relatively low rate as they're intended for human consumption only. They may have to work piece-wise, though, to meet their time restrictions.


text:
wire up usb to pins rather than on board usb socket
I have an uno r3 clone in an enclosure and one of these usb ports on the enclosure.
It's pretty tight in there so I was wondering if there was a way to bypass the usb port on the board and plug it in directly to the pins.
So do something like plug the usb into the outer port on the enclosure and then cut off the usb end and plug the wires directly into the board rather than using the onboard arduino usb port.
The group of 4 just above the i2c seems promising but couldn't find much on it.
Thanks for your help.

Have you looked at alternative (smaller) arduinos such as the mini?

Solder the wires to the underside of the usb socket. Option two; place the uno ne’er the edge of the enclosure and have the original socket stick out (you may have to desoldering the power jack to get it close enough to the side of the enclosure. Option three; get an uno clone with a micro usb jack instead of a regular B.

I did consider the mini and nano but attatching it to an enclosure is a little tricky. I have some pcb risers for the uno which fix perfectly and it is very secure in the enclosure. I'll give the underside a go first, removing the whole pcb block on the uno will be difficult.

You will have to (optionally) desolder the existing USB socket and solder the wires to the pins where that socket was on the board. It connects directly to the pins of the CH340G surface mount chip (rectangular one by the USB socket) and soldering wires to those pins would be tricky.

Thanks for your help Majenko and Ratchet. I'll just desolder the usb port then.

The USB actually goes through the 16 pin chip that will translate the USB to serial to the RX and TX pins. None of the external sockets or plated through holes are connected to the data lines of the USB port.
You are better off soldering the wire to the pins on the connector itself. Or try and find a proper wire with the correct connectors.


text:
Ethernet Shield - Multiple simultaneous connections cause TCP reset
I have a very inconvenient problem with a web server I'm writing for a Arduino Mega 2560 with a W5100 Ethernet Shield (with the "official" Ethernet lib). I wrote the server code and it works like a charm, BUT there is a condition, when the server won't accept all the TCP handshakes and resets the TCP connections:
When I load a big webpage, the browser (Firefox and Chrome too) asks for the .htm first, then collects the links in the file and request them all simultaneously and that's when I got the problem:
The server gets multiple TCP connections but it only accepts the first, then dumps all the others (by TCP reset). After that the client sends them again and the problem starts again: the server accepts the first and drops the others. And so on, for example if the browser needs 3 files, it will take ~9 seconds, because of the retransmission delay. (3 + 6 seconds) Eventually the webpage will load, but a 10 second delay is not acceptable.
Is there any way to cache the requests on the Ethernet Shield or to tell the browser to wait a bit between requests or any other way, to wait a bit for the Arduino to finish the previous request?
Snippet for the server, Wireshark and Chrome network data: https://gist.github.com/anonymous/181f359b70d69e4470931204c4ec175c
Thanks for the help!
G.

I am also having this on a Portenta H7. However, the requests are not being retried. Some assets are just never loading. Did you ever find a solution?

I have received a request from the OP to move this to Network Engineering because it got no answers. I'm going to decline this for the moment because I doubt they will be familiar with the Arduino Ethernet shields.

The low-cost shields have a known limit on the number of connections they can handle simultaneously (no doubt limited by available RAM). From the page Arduino Ethernet Shield 2 we learn:

It supports up to eight simultaneous socket connections.

You don't seem to be getting that, which makes me wonder if it is a code issue. It might help to post your code. If you make code that "blocks" while handling the first connection you may not accept the other ones in a timely way, leading to a reset.
Please post a Minimal, Complete, and Verifiable example.
I did a post about a tiny web server for the Arduino which uses a state machine to handle incoming data without blocking.

You may also be able to help yourself by using the HTTP header that requests that the connection be kept open, eg.
Connection: keep-alive

That might stop the client opening new connections in quick succession.

Thank you for your answer, I'll write a working example of my server tomorrow, I'll leave a comment then.
Your web server solution might be applicable for my problem, but I'd have to modify it and my server code heavily to make it queue requests, so it's kind of a last resort solution.
The "keep-alive" header unfortunately did not solve the problem.

I asked for the move of my question because I was hoping I could get some networking (like TCP/IP or HTTP or client-side) tip to solve the problem without heavily modifying my server code and also because I had no answer, but that changed recently. :)

@NickGammon what do you mean you server is non-blocking? It only handles one client (one HTTP connection) at a time as far as I can tell from your code. I don't see how this solves the problem.

@Marcel In the main loop, it gets a character at a time from the client and passes that to the "state machine" in the server code. It doesn't block. Until a request reaches a reasonable processing point it just keeps accepting new characters. A reasonable point might be when a GET parameter has been received, upon which it calls processGetArgument. Now since it doesn't block, you could have multiple instances of the server object, and feed multiple HTTP connections to them (one to each one).

@NickGammon Oh I see. Thanks for clarifying. The implementation seems a little involved though. Any plans to add something like this to the library?


text:
Can I use GSM and Data Logger Shield at the same time on one Arduino?
Me and my classmates are trying to make an arduino base project where we will be using sensors, GSM, and Data logger shield. We want the arduino to store the data collected and at the same time send a message to the user if significant data are collected.My is question is above.

It depends, but high likely yes.
The sensors, GSM and Data Logger may use the I2C, SPI, analog pins or UART (last not likely).
For I2C, the Arduino can handle many of such devices, because it is part of the protocol.
For SPI it is similar, although some cheap SD card reader for Arduino are notorious not being compatible with other SPI devices. And the Arduino has only one SPI port (but can handle many SPI devices, as long as they all are capable to allow other SPI devices).
For analog pins, these are likely only used by sensors, the Arduino has 5. But there are some ways to use more sensors by polling, using multiplexers etc.


text:
Data type problem
I have a program I would like to ask:
  I use the Bluetooth control LED to light up.
In the picture, the serial port window shows r, but the LED does not light up. What went wrong? Ask everyone, thank you very much.

you read val from Serial but not send it from Serial. do val = BTSerial.read(); Serial.write(val);

it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。it work ！非常謝謝。

Please answer in English. This is an English speaking site.

@Majenko as of what I understood he just changed his code according to what the user has commented under the question post


text:
How to power my Arduino mini using wall socket?
I am trying to power my Arduino Mini (which is connected to IR receiver and a relay board). The idea is to hide the entire setup behind the electrical board including the power supply. I have hacked more than a few power adapters (ranging from Mobile chargers 5-7V to 12 V adapters)
This is what I understand from what I have read so far about Arduino Mini power supply.

I can power directly using Vcc pin if I supply 5V DC regulated. (not recommended)
I can power Raw pin by using 5-12V DC and the onboard regulator will take care of converting it. 12V is the maximum, I should not use 12V it can fry the regular if used for a long period as the on-board regulator is a linear one, so a lot of heat.

This is what I understand from what I have tried so far about Arduino Mini power supply:

Don't connect power supply EVER to Vcc, it will harm the board. ALWAYS use Raw.
12 V supply = puff. instantaneously. No more on-board regulator. Now that Arduino Mini only works if I connect it using Vcc. (the charger was rated 12V 500mA)
Connecting 5V DC (300mA) is heating the regulator alot.

I have connected the Relay and IR receiver directly to the Arduino mini. Pin 10-14 are used for the relays Ins and PWD 3 for IR output.
The mini works with these 5V mobile chargers but the amount it heats up scares me.  Any suggestions on what I should do?
Also how much current consumption would be needed. I have tried using a 5V 300mA charger and 5V 700mA charger. Both work almost the same. Why?
I am a computer engineer and very new to Arduino.
Linking a similar question: Most compact method of powering Arduino from wall socket

What? Just take a USB cable apart and solder the positive lead to raw/vin/vcc. You'll get a lower onboard voltage (~4.5V) but it works fine for both relay and IR (rx and tx). You can probably go as low as 3.78V onboard before it gets too weird. Got such a device running here, it's working perfectly. If you've got a clean 5V (+/- 5%) you can solder the positive lead to 5V pin.

Exactly what I have done as of now. The issue was the regular heating up. I have not measured the temperature, any good easy way of doing so?

I use an off-the-shelf laser IR thermometer with ~95% of temperature (so multiply by 1.05), it works well. The regulator heats up because you pull too much current, drive your loads with transistors. Only use 20mA per output pin, don't get greedy on 5V/3V3 pins, use 200mA, 100mA respectively (yes, they can handle more, I know)

I have connected the Relay and IR receiver directly to the Arduino
  mini. Pin 10-14 are used for the relays Ins and PWD 3 for IR output.

I hope you don't mean that you have connected the coils of the relays directly to the Arduino pins. If that's the case, the surprise won't be the regulator blowing up, but the MCU surviving. Please edit the post and add complete schematics and/or photos of your prototype.

The mini works with these 5V mobile chargers but the amount it heats
  up scares me. Any suggestions on what I should do.?

Use a small heatsink if you're concerned about the regulator heating up. But it really shouldn't be a problem unless you're driving too much current from it. Have you actually measured the temperature it reaches?
Also, don't feed the coil through the regulator, but directly from the 5V adapter (presuming your relays are 5V). This will save a lot of dissipation in the regulator. NOTE: don't do this if you use a higher (> 5) voltage adapter!!

Also how much current consumption would be needed. I have tried using
  a 5V 300mA charger and 5V 700mA charger. Both work almost the same.
  Why?

Those current ratings are maximum values, not constant values. So, if your circuit draws let's say 290 mA, both adapters will be able to do the job.
EDIT: additional information
To safely and properly use relays with arduino, you need some interfacing electronics like this:

Full article from the source, here. Flyback diode: 1N4148. You can use almost any "logic-level" N-channel MOSFET.
If you're using instead a relay module similar to the shown below, all the required interfacing electronics are already built into it and your digital pins won't suffer any overcurrent condition.

However, the regulator will (probably) still suffer from excessive current through it. In some of these relay modules you can optionally use a different power line (JD-VCC, see below) for the relay coil. If you own one of these, feed it directly from the 5V adapter, skipping the regulator.

If the relay module doesn't have a separate power line, it may still work when connected to the 5V adapter if the dropout in the regulator is not too big (i.e., the "high" level from the digital pins is not too far away from the adapter voltage).

Hi, thanks for answering one point after the other. When you say "connected the coils of the relay", you mean to say Vcc is connected from the boards 5V pin?  Well the answer would be yes in any case because all 6 pins connected to relay are from the board itself and I will change it. Just want to understand what you mean by coil. Also as suggested I will measure the temperature and update you, as of now I don't have a good way measuring the temperature. I will see and get a laser temperature thermometer.

You're welcome. I'm concerned about how you may be wiring the relay, so I will update the post will some additional info about it.

The coil is located between the input (control) terminals. The relay is activated by making a current flow through the coil, which is achieved by applying a voltage to it. Depending on the relay, this current can be as high as 100-120 mA per relay. The arduino pins can't neither source nor sink that much current. The arduino mini onboard regulator may also struggle if several relay are powered from it.

If you have a multimeter, check whether it can do temperature readings. If it can, then you just need a temperature probe (they're not expensive) for it.

The Arduino website says you should not power your Arduino Mini with more than 9 volts.

Warning: Don't power the Arduino mini with more than 9 volts, or plug
  the power in backwards: you'll probably kill it.

https://www.arduino.cc/en/Main/arduinoBoardMini
The 5 to 12 Volts (not more than 12V for long time periods) refers to the Arduino UNO and probably others.

You certainly can connect a 5v or 3.3v to the Vcc pin for most boards. Most regulators can take a reverse voltage. To be sure, check the data sheet or place a reverse diode on the regulator.
Again, depending on the particular regulator your board has. Most of them are good for 16 to 18v. But that can change drastly if more load current is involved.
Well, that's your answer then. Put a reverse diode across the regulator, Between the Vcc and raw pins.


text:
Arduino Voltage Divider
So am doing a project which involves the reading of voltage and current generated by Solar Panel. Now I learnt that Arduino cant Read Voltage directly above 5V. To read above that you need to add a voltage divider circuit in between. But that's the great solution for a solar panel around 20W.
Now what if i want to read voltages of n number of solar panels which are in a farm in which each solar panel generated around 300-400 W .
1)Will adding voltage divider help?
2) What is the limit of Arduino of Voltage Divider?
3) What registers i would have to use for such big voltage divider?

Are you a electrical engineer and familiar with high voltages and high currents? When you have to ask this question, you better not mess with the solar panels. The solar power inverter has probably a way to get those numbers via a website or a interface.

@Jot no am not an electrical engineer. I do not the how u work with high voltages and current.

1)Will adding voltage divider help?

You will need n voltage dividers, one for each solar panel.

2) What is the limit of Arduino of Voltage Divider?

There is a limit on the equivalent Thévenin resistance of the voltage
source connected to the Arduino analog inputs. It should be no larger
that 10 kΩ, otherwise you risk cross-talk between the channels.
If the solar panels have a low output resistance, then the equivalent
Thévenin resistance is the resistance resulting from setting the two
resistors of the divider in parallel. Setting the smallest resistance
to 10 kΩ will ensure you meet the condition while at the same time
keeping the consumed current quite low.
There is also a limit on the number of solar panels that you can
independently monitor: 16, which is the number of analog inputs on the
Mega.

[...] each solar panel generate[s] around 300-400 W

The power generated is irrelevant: only the voltage is a concern. Your
dividers must output no more than 5 V.

1) Will adding voltage divider help?

Yes.

2) What is the limit of Arduino of Voltage Divider?

The Arduino has no relevance here. You can build voltage dividers to convert thousands or millions of volts down to 5V if you need to.

3) What registers i would have to use for such big voltage divider?

I guess you mean "resistors" here, not "registers"...
Resistors that give no more than 5V out at the peak voltage of the solar panels, and have a high enough voltage tolerance for the maximum voltage across any one resistor.


text:
How can I write an integer to a Mifare RFID card using the RFID library?
I'm a beginner to C++ and I'm clearly missing some fundamental knowledge of data types. As such, I'm struggling to adapt the examples in the miguelbalboa/rfid library to my use case. I'm simply trying to write an integer to a 13.56Mhz RFID tag. Ideally I'd like to optimize the data so as to be quick to read (it seems fully reading these cards can take a while and I'd like to read the integer, an ID, as quickly as possible).
So on to my actual questions... what is the data type shown in this block of example code (shown below) and how can I turn an integer into the same data type? Finally, how should I read this saved value back into the familiar integer data type?
byte dataBlock[]    = {
    0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
    0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
    0x09, 0x0a, 0xff, 0x0b, //  9, 10, 255, 11,
    0x0c, 0x0d, 0x0e, 0x0f  // 12, 13, 14, 15
};

really important info that you failed to mention ... what is the model of the device that you are using?

The dataBlock[] variable is an array of bytes. One byte can represent an integer ranging from -128 to 127, or a positive integer ranging from 0 to 255. If your integer value will always be in one of those ranges, then you can just put your integer in the first element of the array and zero out the remaining.
byte dataBlock[]    = {
    0x01, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00
};

(That saves a value of 1 to the first element, and zeros to the rest. If you want to change the first element:
dataBlock[0] = yourValue;

If your integer is a 2-byte integer, as is typically found in Arduino with type int, you need to split your value into the high byte and low byte:
dataBlock[0] = (byte)(yourValue & 0xFF); // Low byte
dataBlock[1] = (byte)(yourValue >> 8);   // High byte

Then you write the data block as per the example. To get your 2-byte integer value back:
yourValue = ((int)dataBlock[1])<<8 | dataBlock[0];  // Shift high byte, OR with low byte.

Well, the example is using the MIFARE_Write and MIFARE_Read functions. These functions, as explained in the library, accept at least 16 bytes, so the 16-bytes buffer is the smallest you can read/write. Consequently I suggest you, if you don't have any additional data, to use 16-bytes IDs (you get a much wider code space).
If you strictly want to use 2 or 4-bytes integers, the first solution which comes to my mind is jose's one, so manually split the int in two (or the long in four) bytes and store them in the array. For instance
// Big endian format
dataBlock[idx]   = (byte)(intValue >> 8); // Byte 1
dataBlock[idx+1] = (byte)(intValue);      // Byte 0
// or
dataBlock[idx]   = (byte)(longValue >> 24); // Byte 3
dataBlock[idx+1] = (byte)(longValue >> 16); // Byte 2
dataBlock[idx+2] = (byte)(longValue >> 8);  // Byte 1
dataBlock[idx+3] = (byte)(longValue);       // Byte 0

// Little endian format
dataBlock[idx]   = (byte)(intValue);      // Byte 0
dataBlock[idx+1] = (byte)(intValue >> 8); // Byte 1
// or
dataBlock[idx]   = (byte)(longValue);       // Byte 0
dataBlock[idx+1] = (byte)(longValue >> 8);  // Byte 1
dataBlock[idx+2] = (byte)(longValue >> 16); // Byte 2
dataBlock[idx+3] = (byte)(longValue >> 24); // Byte 3

NOTE: idx can be any value; the easiest approach is to put the int at the beginning (so substitute idx with 0)
This is the safest way to handle this, since the endianness is explicit. You can, however, trust the compiler and use its implicit handling of multi-byte variables in this way:
*((int*)(&datablock[idx])) = intValue;
// or
*((long*)(&datablock[idx])) = longValue;

You take the cell where you want to put the beginning of the data, get its pointer, cast it to the pointer type you need, then write inside that pointer the value you want. Please note, however, that cells idx and idx+1 in the case of an int, or idx to idx+3 for long, will be written. If your array ends, you will pollute the memory in unpredictible ways (just like if you write dataBlock[18] = something when dataBlock has 16 cells).
Note you cannot control the endianness of the byte array, but if you always use the same device to read and write you should not worry. FYI, at present the compiler used by Arduino IDE is little endian.
Note also that, for idx = 0, (&datablock[idx]) can be simplified in (datablock).
To read back the data, you have the following ways
// Big endian format
intValue = (((int)dataBlock[idx]) << 8) | dataBlock[idx+1];
// or
longValue = (((long)dataBlock[idx]) << 24) | (((long)dataBlock[idx+1]) << 16) | (((long)dataBlock[idx+2]) << 8) | dataBlock[idx+3];

// Little endian format
intValue = (((int)dataBlock[idx+1]) << 8) | dataBlock[idx];
// or
longValue = (((long)dataBlock[idx+3]) << 24) | (((long)dataBlock[idx+2]) << 16) | (((long)dataBlock[idx+1]) << 8) | dataBlock[idx];

Or, in the last case,
intValue = *((int*)(&datablock[idx]));
// or
longValue = *((long*)(&datablock[idx]));


text:
Need to control 2 DC motors powered using arduino mini and l298n from about range of 100m
I need to control 2 DC motors which are arranged with arduino mini and L298N module from a distance of 100m wirelessly, what is the easiest and cheapest way of doing so?I checked RC controllers and xbee but they are way too expensive!
Any help will be appreciated!

Welcome to Arduino:SE. Please be aware that this is not a free design house or an on-demand online technical encyclopedia. You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

The cheapest way is probably using nRF24L01+, a 2.4 GHz transceiver. It should be possible to communicate over 100 m, using a slow speed and without any obstacles in between. If you need a better/faster communication, either use a version with an external antenna and/or use other frequences (using different transceivers, below 1 GHz). The last options are more expensive.


text:
RxCpp on Arduino?
I would like to make use of some sort of event bus on Arduino.
Lately I have been making use Reactive Extensions on a number of different platforms, Android, Angular, iOS, etc, and found them very useful.
I tried to install the library and compile something (just including the headers in the example) and I got the following error.
/home/john/Arduino/libraries/rxcpp/rx-trace.hpp:97:57: error: 'exception_ptr' in namespace 'std' does not name a type
     inline void on_error_enter(const Subscriber&, const std::exception_ptr&) {}
                                                     ^

Before I spend too much time trying to force something that will not work, does anyone know if this will work on Arduino, or of any other event bus library that works well on the platform?

Well, exceptions are disabled, basicaly all c++ libraries aren't available and so on....


text:
Arduino tone frequency isn't always precise
I'd like to play an asynch 'beep' sound (2.5kHz, pin 8) on an Arduino Mega with several other modules connected. I write them here, just for the record: SDCard reader and RFID reader through SPI bus, RTC through I2C, GSM module through hardware Serial 1. And I use PWM on two other pins (11,12) for controlling LEDs brightness.
It works well, however, sometimes (1 of 10) the beep frequency is about half-tone higher.
The code itself is good, because I use a constant in the tone() function call for specifying the frequency.
Does anybody have an idea what can influence the tone's PWM frequency such way, maybe on hardware level?

As far as I know, tone() implements pin toggling in software (using timer interrupt), so it's possible that the frequency is lower when there's a lot of activity and higher when the CPU is mostly idle.
Try calling your beeping code alone inside an otherwise empty sketch and with no external hardware, and check out whether the sound is higher than you expect.

Half-tone, that's a lot of change.  I would expect a lowering of frequency if anything from other resources being active.  An increase in frequency suggests perhaps something is changing the internal counter values that is used for the toggling.
2.5KHz is 400microseconds, toggling every 200us. You might consider using Arduino "blink without delay" to monitor the passing microseconds and toggling based on that. I've created up to 20KHz signal that way, but not with anything else running.


text:
using special symbols from the U8glib library
I enter font symbols into the u8g.setFont() and I get a string of sympols. How do I grab just one of those symbols, for example an arrow?