问:
Read Multiple Channels of RX-TX with arduino
I have a 9 channel RF RX/TX and want to connect 3 motors to it.  I am able to connect channel 1 with motor 1 but unable to connect channel 2 with motor 2 simultaneously with arduino.

Here is the code I am currently using:

```<code>int motor1Left = 7;// defines pin 5 as connected to the motor
int motor1Right= 9;// defines pin 6 as connected to the motor
int motor2Left = 22;// defines pin 7 as connected to the motor
int motor2Right = 26;// defines pin 8 as connected to the motor
int enable = 5;
int enable2 = 10;
int channel1 = 2; // defines the channels that are connected
int channel2 = 3;// to pins 9 and 10 of arduino respectively

int Channel1 ; // Used later to
int Channel2 ; // store values

void  setup ()
{
  pinMode (motor1Left, OUTPUT);// initialises the motor pins
  pinMode (motor1Right, OUTPUT);
  pinMode (motor2Left, OUTPUT);
  pinMode (motor2Right, OUTPUT);// as outputs
  pinMode (channel1, INPUT);// initialises the channels
  pinMode (channel2, INPUT);// as inputs

  Serial.begin (9600); // Sets the baud rate to 9600 bps
}

void  loop ()
{
  Channel1 = (pulseIn (channel1, HIGH)); // Checks the value of channel1
  Serial.println (Channel1); //Prints the channels value on the serial monitor
  delay(1000);

  Channel2 = (pulseIn (channel2, HIGH)); // Checks the value of channel1
  Serial.println (Channel2); //Prints the channels value value on the serial monitor
  delay(1000);

  if (Channel1 > 1470 && Channel1 < 1500) /*These are the values that I got from my transmitter, which you may customize according to your transmitter values */
  {
    digitalWrite (motor1Left, LOW); // Sets both the
    digitalWrite (motor1Right, LOW);// motors to low
    analogWrite(enable, 100);
  }

  if (Channel1 < 1460) // Checks if Channel1 is lesser than 1300
  {
    digitalWrite (motor1Left, HIGH);// Turns the left
    digitalWrite (motor1Right, LOW); // motor forward
    analogWrite(enable, 100);
  }

  if (Channel1 > 1510) // Checks if Channel1 is greater than 1500
  {
    digitalWrite (motor1Left, LOW);// Turns the right

    digitalWrite (motor1Right, HIGH);// motor forward
    analogWrite(enable, 70);
  }

  if (Channel2 > 1480 && Channel1 < 1500 )
  {
    digitalWrite (motor2Left, LOW);// Sets both the
    digitalWrite (motor2Right, LOW);// motors to low
    analogWrite (enable2, 100);
  }

  if (Channel2 < 1300) // Checks if Channel2 is lesser than 1300
  {
    digitalWrite (motor2Left, LOW);// Turns the left
    digitalWrite (motor2Right, HIGH);// motor backward
    analogWrite (enable2, 100);
  }

  if (Channel2 > 1500) // Checks if Channel2 is greater than 1500
  {
    digitalWrite (motor2Left, HIGH);// Turns the right
    digitalWrite (motor2Right, LOW);// motor backward
    analogWrite (enable2, 100);
  }
}
</code>```

答:
I'm assuming you have a standard 9-channel hobby RC transmitter (with the little joysticks you move with your fingers) and a corresponding 9-channel hobby RC receiver intended to go into a RC car or airplane with standard servo 3-pin headers (9 of them).
And you have your Arduino, and a few motors you want to control with it.

Your program has better-than-average comments, but some are still mystifying, such as:

```<code>int motor1Left = 7;// defines pin 5 as connected to the motor
</code>```

Really?

I would break this problem into (at least) two parts, try to get each part working independently, and then try to get everything working together.

One way to break it up into parts is to have an array something like

```<code>int pulseWidth[9];
</code>```

I might write one program that only reads pulse widths from the RC receiver and prints them out the serial port.
Then I might extend that program to store those pulse widths into that array,
and then print out the values in that array.
Then I might write a completely separate program that sets each value in that array to a different constant,
and then uses the values in that array to control the motors.
Only after I got both programs working would I combine them into one program.

Reading the pulse widths is definitely the trickiest part,
but I hear that several people have gotten that to work adequately for them.

The two basic approaches to reading pulse widths that I've seen are:

(a) Get all the signals on one wire, sometimes called "the PPM stream" (i.e., if it uses a 4017 IC for splitting, attach the wire to the "CLK" pin 14; if it uses a 4015 IC for splitting, attach the wire to the "CLK" pin 9), and feed that one wire into a single Arduino input. Or,

(b) Feed each output pin that you care about to separate input pins on the Arduino. (It may help if you use an O'scope to figure out which order the "RC receiver" pulses those pins.)

Have you tried maybe running program listed at
"RC Hobby Controllers and Arduino"
without any changes at all?
Does that much work on your hardware?

Other people connecting a hobby RC receiver to an Arduino include (in no particular order):

"reading 6-channel RC receiver PWM signal"

"Arduino, Vex receiver and signal splitter"

"Arduino: Read PWM Signal from a RC-Receiver"

"Arduiono: 3 axis auto stabilized platform"

"Arduino and Tx/Rx system"

"Arduino Receiver"

"RCArduino: How To Read Multiple RC Channels"

"How To Read RC Receiver PPM Stream"

"Arduino: Read PPM signals from RC receiver or Control"

"Arduino: Read Receiver"

"How to hack the PPM signal from any receiver (Futaba) with Arduino"

"PPMMixer: Arduino Radio R/C PPM Mixer Programmable"

"Arduino ppm signal reader and generator"

"Arduino PPM signal reader/decoder Library"

P.S.: often you get better answers to problems like this if you write all three parts: (1) what you want to happen, (2) the complete program listing, and (3) what actually happens when you run the program — "Motor 2 never moves, no matter how I move the control stick", or "Motor 2 always moves exactly like motor 1 moves", or whatever it is you actually observe.

You did great with part (2), but without (1) and (3) it's difficult for anyone to help you.

Body:
I'm assuming you have a standard 9-channel hobby RC transmitter (with the little joysticks you move with your fingers) and a corresponding 9-channel hobby RC receiver intended to go into a RC car or airplane with standard servo 3-pin headers (9 of them).
And you have your Arduino, and a few motors you want to control with it.

Your program has better-than-average comments, but some are still mystifying, such as:

int motor1Left = 7;// defines pin 5 as connected to the motor

Really?

I would break this problem into (at least) two parts, try to get each part working independently, and then try to get everything working together.

One way to break it up into parts is to have an array something like

int pulseWidth[9];

I might write one program that only reads pulse widths from the RC receiver and prints them out the serial port.
Then I might extend that program to store those pulse widths into that array,
and then print out the values in that array.
Then I might write a completely separate program that sets each value in that array to a different constant,
and then uses the values in that array to control the motors.
Only after I got both programs working would I combine them into one program.

Reading the pulse widths is definitely the trickiest part,
but I hear that several people have gotten that to work adequately for them.

The two basic approaches to reading pulse widths that I've seen are:

(a) Get all the signals on one wire, sometimes called "the PPM stream" (i.e., if it uses a 4017 IC for splitting, attach the wire to the "CLK" pin 14; if it uses a 4015 IC for splitting, attach the wire to the "CLK" pin 9), and feed that one wire into a single Arduino input. Or,

(b) Feed each output pin that you care about to separate input pins on the Arduino. (It may help if you use an O'scope to figure out which order the "RC receiver" pulses those pins.)

Have you tried maybe running program listed at
"RC Hobby Controllers and Arduino"
without any changes at all?
Does that much work on your hardware?

Other people connecting a hobby RC receiver to an Arduino include (in no particular order):

"reading 6-channel RC receiver PWM signal"

"Arduino, Vex receiver and signal splitter"

"Arduino: Read PWM Signal from a RC-Receiver"

"Arduiono: 3 axis auto stabilized platform"

"Arduino and Tx/Rx system"

"Arduino Receiver"

"RCArduino: How To Read Multiple RC Channels"

"How To Read RC Receiver PPM Stream"

"Arduino: Read PPM signals from RC receiver or Control"

"Arduino: Read Receiver"

"How to hack the PPM signal from any receiver (Futaba) with Arduino"

"PPMMixer: Arduino Radio R/C PPM Mixer Programmable"

"Arduino ppm signal reader and generator"

"Arduino PPM signal reader/decoder Library"

P.S.: often you get better answers to problems like this if you write all three parts: (1) what you want to happen, (2) the complete program listing, and (3) what actually happens when you run the program — "Motor 2 never moves, no matter how I move the control stick", or "Motor 2 always moves exactly like motor 1 moves", or whatever it is you actually observe.

You did great with part (2), but without (1) and (3) it's difficult for anyone to help you.


问:
Find the robot pose from three beacon measurement
At every timestep my robot gets sensor measurements from a scanner that finds three beacons with known poses $B_1 = (B_{1x}, B_{1y})^T, B_2 = (B_{2x}^T, B_{2y}) , B_3 = (B_{3x}, B_{3y})^T$ these measurements include the distance and angle to the beacon, the measuremnt for $B_1$ would be $m_{1t} = (d_{it}, \omega_{1t})^T$. and equivalently for the other beacons.

From these measurements i want to calculate the robots pose containing its position and orientaion $x_t = (p_{xt}, p_{yt}, \Theta_{xt})^T$.

Calculating the position can be done by trilateration, but I can't seem to find a way to get the orientation of the robot from these measurements. Is there possible a model to calculate both in a single calculation?   If not a solution for finding the orientation of the robot would be great.

答:
You cannot directly find the direction (heading) of your robot. You only can derive the triangulated x, y positions.

However, if you have some constraints in motion dynamics (for example if your robot only moves in its body-x direction when steering is zero) you may have a time-derivative of the position and find the velocity vector.

And if you filter the velocity and position data to an estimation algorithm (I.e. Kalman filter) you may get an accurate position and velocity in time. Naturally, it does not give a solution when the robot is stationary.

ContentLicense: CC BY-SA 3.0


答:
I'm not sure where you're having the trouble with this. As you mention:

Step 1 - Find the position of the robot by trilateration with the three beacon distances.

Step 2 - Find the heading of a straight line between the location you are at and any of the three beacons

Step 3 - Find your heading by subtracting your local heading from the result of Step 2

Step 4 - Put bounds on your heading (0-360 degrees, for example).

So, for instance, say you have beacons at (x,y) positions of (1,0), (1,1), and (0,1). You trilaterate your own location to be (0,0), because the distance reading from each beacon was 1.

Great.

Now, you have to define what "heading" means to you. Is this an "engineering" heading, where 0 is the +x-axis and the angle goes positive counter-clockwise? Or is this a navigation heading where 0 is "up" (North) and the angle goes positive clockwise?

Whatever the case, let's chose to look at the beacon located at (1,0). There is a heading from your location to that beacon. If you're using navigation coordinates, it's 90 degrees (East).

Now, what is the angle of that beacon as it appears to your robot?

If you are measuring it with an angle of zero, then that means that you are pointed directly at it, which means that your heading is the same as the heading between your point and that beacon, which means that your (navigation) heading is also 90 degrees.

Say you measure it as being at -90 degrees relative to your robot (again, on a navigation setup). If the beacon is -90 degrees relative to you, then you are +90 degrees relative to the beacon. This means that your heading is whatever the heading is to the beacon, plus 90 degrees. That is, your robot's heading is 180 degrees (South).

You should be able to do this with any of the beacons and get the same answer.

Title: Find the robot pose from three beacon measurement

Body:
At every timestep my robot gets sensor measurements from a scanner that finds three beacons with known poses $B_1 = (B_{1x}, B_{1y})^T, B_2 = (B_{2x}^T, B_{2y}) , B_3 = (B_{3x}, B_{3y})^T$ these measurements include the distance and angle to the beacon, the measuremnt for $B_1$ would be $m_{1t} = (d_{it}, \omega_{1t})^T$. and equivalently for the other beacons.

From these measurements i want to calculate the robots pose containing its position and orientaion $x_t = (p_{xt}, p_{yt}, \Theta_{xt})^T$.

Calculating the position can be done by trilateration, but I can't seem to find a way to get the orientation of the robot from these measurements. Is there possible a model to calculate both in a single calculation?   If not a solution for finding the orientation of the robot would be great.


问:
PI with poor sampling rate
I have a 1-DOF electromechanical application whereby I am controlling the contact-force at the tip of the end-effector.

The force sensor on the end-effector unfortunately gives me force data and an incredibly low sampling rate at 20 Hz, and I cannot do anything about it.

I generated a linear model for my plant and determined I will probably need a sampling rate of at least 320 Hz to follow the rule of thumb (Ts is 1/10th of your time constant). With the current setup, I of course have poor disturbance rejection (i.e., when the surface moves into the end-effector) with a PI controller .

Fortunately, the wall motion is periodic and fairly predictable. I implemented a modified Smith predictor that can reject periodic disturbances. This works fairly well but I am interested in exploring other options. Is there anything else I can take a look into that may help with this situation? For instance, I was considering taking a look into implementing a Kalman filter, since I can use it to predict the next sample in the loop, which may improve performance - I am not sure if that is right.

Regards,

答:
You're really, really vague about your application, setup, hardware, etc., so I don't know that it's possible to really give any meaningful advice. Regarding the Kalman filter, you are correct in that part of the filter predicts the next sample, but that's just the linearized model that you said you already have. You could propagate that model to generate filler samples, but again that would just be using your system model.

I don't know what kind of a force sensor you would be using that would only output that low of a force, or what your system is, but maybe you could get (noisier) higher-frequency samples via other means, like strain gauges, shunt resistors (to measure current), etc.

The biggest suggestion I think I could give you would be that, if you have a system model, you switch from a PI controller to a state feedback controller. That uses a built-in linearized model of your plant to provide better control. If you have the linearized model already, then it should be pretty straightforward to generate the controller. This of course won't fix your sampling rate, but you might get better performance with a more robust controller.

Title: PI with poor sampling rate


问:
Calibrating a laser scanner to a line camera
We have a high-resolution Riegl laser scanner and mounted atop it a Resonon Pika L, which is a hyperspectral camera which records one spatial column at a time, using the second dimension of the sensor for the wavelength spectrum from 400 to 1000 nanometers.

Now we would like to label each scan point with hyperspectral data. For this, we

record a fixed angular window with the laser scanner

stitch together the individual spatial columns from the hyperspectral camera rotating with the scanner

Identify chessboard corners in the point cloud

also find them in the stitched hyperspectral panorama (reduced to rgb).

Using OpenCV's calibrateCamera we try to get a camera matrix, which I assume will only be valid for this particular panorama size (if at all)

and then we could in theory obtain rotation and translation between scanner and panorama coordinates using solvePnP.

Is this a valid way to go about solving this problem? There doesn't seem to be much prior art in this regard.

答:
I converted my comments to an actual answer:

If I understand your setup correctly, you're saying you have a line scan camera mounted to the top of the rotating head of a laser scanner, and all you're looking for is the one-time transform matrix between the scanner and camera coordinate frames. Is this correct? If so, why not just perform the test in a controlled environment where the features are easy to discern?

[The spectral camera doesn't really have] a 1d image if you have the encoder feedback from the Riegl. But yes, if you could generate a shape (easily detectable by the laser scanner) that also had some interesting spectral content (easily detectable by the hyperspectral camera), then you could compare encoder counts where the same feature were located in both systems.

As your spectral camera appears to cover the visible spectrum, you could use an exterior door (presumably the wall is one color, and outside is "noisy" colors), or a table, or an open window, or a or a monitor or any colored, physical object.

I don't know if you're trying to mass produce something, but probably the easiest way to do this is just to manually align the two outputs until you have good coherence. I don't know if this is the point of what you're trying to do or not, but again you have visible spectrum data from your line camera. You could segment out the RGB information from that data, use it to texture your point cloud, and then tweak the transform values until your texture overlay "fits" with the depth information you've got from the laser scanner.

Of course if you're mass producing the thing and/or you plan on constantly re-aligning the data, then you would probably want some way to automate this, but automation is not always the answer.

It would be really neat if it could align itself, but please please consider the time cost of just doing the alignment manually versus the time cost of writing a custom alignment algorithm for scratch. If you have a rigid coupling between the two sensors (your project doesn't seem to be hurting for money!!) then you shouldn't need to do the alignment more than once.


问:
Guessing the K matrix gain for the Optimal Control LQR?
I'm are going to create a LQR to control a system. The problem is to choose the Q and R weighting matrices for the cost function. The Q and R matrices are going to minimize the cost function so the system are going to be optimal.

I'm using Scilab and Scilab have a good library for optimal control. Scilab have a built function named lqr() to compute the gain matrix K, which is the LQ regulator.

But the problem is still to choose those weighting matrices. I don't know here to start. I just might start with the identity matrix as Q and just a constant as R. But the gain matrix K does not make my model go smooth. No one can say that this is the real Q and R weighting matrices for the system. As a developer, I choose the weighting matrices. But why should I do that when I can choose the K gain matrix directly?

So I just made up my own numbers for the gain matrix K and now my model is very smooth. All I did just do was to guess some numbers for the gain matrix K and simulate and look at the result. Was it still bad, I might change the first element for the gain matrix to increase the position, or change the second element in the gain matrix K, to speed up the velocity for the position.

This works great for me! Guessing and simulate and look at the results.
I choosing the LQ-technique for two main reasons: It gives multivariable action and can reduce noise by using a kalman filter. A PID cannot do that.

But here is my question:

Will this method give me an optimal control just by guessing the gain matrix K and changing the values depending how the simulation results looks like?

I'm I happy with the results, I might quit there and accept the gain matrix K as the optimal LQR for the system.

答:
If you want to avoid having to deal with the non-uniqueness of a state space model representations of LTI systems and want to have some more control of the impact that changing $Q$ has on the resulting controller, then you could define the cost you want to minimize as

$$
J(u) = \int_0^\infty\left(y^\top\!(t)\, \hat{Q}\, y(t) + u^\top\!(t)\, \hat{R}\, u(t) + 2\,y^\top\!(t)\, \hat{N}\, u(t)\right) dt.
$$

If your state space model is of the form

$$
\left\{\begin{array}{l}
\dot{x} = A\, x + B\, u \\
y = C\, x + D\, u
\end{array}\right.
$$

then you can rewrite the cost function into a form which can be solved with LQR as follows

$$
J(u) = \int_0^\infty\left(x^\top\!(t)\, Q\, x(t) + u^\top\!(t)\, R\, u(t) + 2\,x^\top\!(t)\, N\, u(t)\right) dt,
$$

with

$$
Q = C^\top \hat{Q}\, C,
$$

$$
R = \hat{R} + D^\top \hat{Q}\, D + D^\top \hat{N} + \hat{N}^\top D,
$$

$$
N = C^\top \hat{N} + C^\top \hat{Q}\, D.
$$

Now you could start with $\hat{R}$ equal identity, $\hat{N}$ equal zero and $\hat{Q}$ diagonal (with only positive numbers on the diagonal), for example identity. Now by doing a simulation of your closed-loop system using the obtained LQR controller you can see if you have desired performance. If for example the $k$th output decays too slowly, you could increase the value of the $k$th diagonal element of $\hat{Q}$.

If you would also like to guarantee internal stability of the system you could also add an identity matrix multiplied by a small positive number to the expression for $Q$. In order to get some estimate of the size of this small number you could maybe use a couple of orders of magnitude smaller (say $10^{-6}$) than the largest eigenvalue of the initially obtained $Q$.

So using this transformation of $(\hat{Q},\hat{R},\hat{N})\to(Q,R,N)$ should give you some more intuitive tuning nobs when designing a LQR controller. This method should also not be affected by the state space realization you are using of the LTI system.


问:
What is are digitally-mated pairs
I am considering competing in the robogames, but the rules require that R/C bots have  digitally-mated pairs. I am not sure what these pairs are. For reference here are the rules for robot sumo and combots.

Robot Sumo Rules

Combot Rules

答:
This means that you have to make sure that your remote talks only to your own robot and you doesn't interfere with the commands of other robots. This could be an encryption so that no other robot understands your commands.

From Combat Robot Rules:

All robots (including insect classes) MUST use a radio system with digitally coded, mated pairs between transmitter and receiver. This means that no other transmitter, operating on the same frequency, can communicate with your receiver, and your transmitter cannot send signals to any receiver other than your own. Examples of such systems are Spektrum, IFI, and XPS XtremeLink - these are just examples and should not be taken as a comprehensive list or an endorsement.

Title: What is are digitally-mated pairs


问:
Why the bldc motor not able to move my water boat?
I have a 1100kv brushless motor from dys with a propeller as shown.

I have attached this motor to two pvc pipes joined together as shown and packed the electronics inside polyform to protect from water.

When I did the test run of this model the boat didn't move. The motor was just creating the turbulence in the water.
So I your help of where I am going wrong
 1. Is it wrong to place brushless motor in water(although have seen videos of
people placing their motors in water) ?
 2. Is the propeller design/size is wrong (maybe its a simple fan propeller not made for water, really no idea)?
 3. Or the motor rating is not enough (thought lower kv rating would generate more torque and therefore more thrust) ?
I used a 11.2V 2200 mah 25C lipo battery.

答:
It sounds to me like you've got cavitation. Basically, the blades are turning so fast that the water around the blades boils. Boiling can happen at normal pressure and high temperature, like on a stove, or at normal temperature and low pressure, as in your case.

The blades boil the water, then the prop is surrounded by vapor instead of water and there isn't anything to push.

Here's a hobby thread on cavitation, where the OP complains,

I was driving my boat on saturday and I noticed sometimes my motor would spin very fast and the boat would go no where as if it were not spinning the prop.

and another poster replies, in part,

Cavitation is caused by the prop spinning too fast... You get something simular if the prop is 'too far' out of the water at some point. Lots of 'splashing', not much water moving.

(Emphasis added). That post goes on to say that it's not exactly cavitation, but it 100% is cavitation.

You need to slow the prop down. You basically have three options to slow the prop down:

Write smaller values to the ESC to request a lower speed (easiest), or

Use a gearbox to change motor speed to prop speed (most efficient), or

Get a larger and/or more aggressive prop such that the torque required to turn the prop naturally lowers the motor speed (least efficient).

The problem with option 1 is that there is some "maximum throttle" at which you'll start cavitating, and then you're limited to the power and speed output of the motor from 0% to whatever that maximum throttle is. Even a low kV BLDC motor like you have still naturally spins very fast. You may have controller issues running a BLDC motor under relatively high torque at such a low speed.

Option 2 is the most expensive because it requires you to purchase a gearbox, but that's the way it's done on commercial and military ships - run the (steam or gas) turbines at high speed, where they operate most efficiently, then gear that down to a low speed, where the prop operates most efficiently.

Option 3 is probably not going to get you very far, because you'll probably find it hard to get a suitable prop installed in the correct location.

Of course, there's an option 4 also: replace the motor. You would want to go for the lowest speed motor you could find; something like a 100rpm motor would probably be perfect.


问:
Extended Kalman Filter for IMU
I am trying to use a multilayer perceptron to make a flight controller for a ROV. I have a MPU-9250 IMU and I need to remove the noise from the sensor before I can train my MLP. The IMU has a accelerometer, gyro and a magnetometer. I know my state vector is supposed to be

```<code>[acc_x, Acc_y, Acc_z, gyro_x, gyro_y, gyro_z, mag_x, magy, mag_z]
</code>```

I am not sure about the rest. Since I want the clean Acc, gyro and mag's x, y and z values can I just use an identity matrix for everything in EKF?

I want to pass the IMU data to the MLP after cleaning it and try to predict the control signal for all my thrusters. For my dataset I recoded the IMU information from a ROV2 and I also recorded the pwm signals for each thruster. If it does work I won't be able to control things like PID values of the thrusters but for now I don't really care about it.

答:
When I was writing my own flight for quad-copter, this article helped me a lot and I think it could help:
Arduino code for IMU Guide algorithm. Using a 5DOF IMU (accelerometer and gyroscope combo):

This article introduces an  implementation of a simplified filtering algorithm that was inspired by Kalman filter. The Arduino code is tested using a 5DOF IMU unit from GadgetGangster – Acc_Gyro. The theory behind this algorithm was first introduced in my Imu Guide article.

Title: Extended Kalman Filter for IMU


问:
What is the easiest way to install ROS on OSX Mountain Lion?
The latest OSX documentation I found on the website is from 2011, and the latest build is from over a year ago. I'm a complete n00b to all things ROS and wanted to start playing with it. What is the easiest way?

Edit: this version of the installation instructions is more recent (April 2013), but it says that

OSX is not officially supported by ROS and the installation might fail for several reasons. This page does not (yet) contain instructions for most higher level ROS packages, only for the base system. This includes the middleware and command line tools but not much more.

"Does not contain instructions" also means it doesn't work? What do OSX users who work on ROS usually do? Run it on an Ubuntu VM? Install it just fine on their own on OSX, even though there aren't detailed instructions on the website?

答:
Installing ROS is one thing, but the question you should really be asking is about maintaining  ROS.

It's certainly possible to install ROS on any *nix system if you satisfy all the dependencies, but since those dependencies are constantly being updated to new versions the maintenance quickly becomes a nightmare.  The OSX install tips on their wiki (Homebrew or MacPorts -- noting the lack of instruction for higher-level libraries) give some hints of this.

Virtualbox is (unfortunately) the easiest method -- "unfortunately", because technically you're installing ROS on the guest OS, not OSX.  But on the upside, it's the supported way to go.


问:
6DOF Robot Dynamics from Newton-Euler Iterative Algorithm
I don't know if someone can help me with this but I'm calculating the dynamics of a 6DOF robot using the Newton-Euler iterative dynamics algorithm. I'm following the recursive method (inwards and outwards) explained in the book Introduction to Robotics Mechanics and Control (Pages 175-176). After putting down on MATLAB the calculations, I started to check if the gravity compensation, g term, made sense. I had calculated the gravity term from the Lagrange approach before so I knew the set of torques had to be the same for a specific pose. Although the values are almost similar (one actuator has some considerable deviation, still unknown to me as to why). Now, here's the thing: the robot is the Kinova JACO v2 arm, and if one assumes that only the gravity effect is taking place,  no torque is assumed for the first actuator (its associated link is at the base). Indeed this is visually clear, and the Lagrangian approach based on the potential energy corroborates that, giving me a torque vector with no torque being sent to the first actuator.

My problem is just that... The Newton-Euler iterative algorithm is based on the balance of the forces between the links. And since the contributions of the forces are summed up (when performing the outwards calculations) the torque sent for the actuator 1 is not zero and has actually the value that would be sent to the actuator 2. Basically a "shift" was made, and the torque for actuator 1 should've been for actuator 2, and so on.

I don't know if you can get any insight from this... But I've tried to recheck my calculations and I can't seem to find any problem with them... Please if you have any suggestions I'll be grateful.

Thanks.

答:
Since you include no equations, all we can say is that yes, the Newton-Euler algorithm works and the fact that you are not getting the expected results means that you implemented the algorithm incorrectly.

Sounds like either a labeling/indexing problem. Perhaps you are extracting the actuator torque incorrectly from wrong set of resultant forces.

Try writing the equations and free-body diagram for a 1dof robot and compare that to what your algorithm does.


问:
Electronic speed controllers and total current draw
Do we have to take Electronic Speed Controllers (ESC) into account when calculating the total current draw of the system?

As far as I can understand, the motor and ESC are connected in series, so we take the component that draws the most current, which is the motor in this case. Then, all combinations of a motor and ESC are connected in parallel, thus the currents add up. Am I thinking right? Or am I missing something here?

答: You are correct. There will be a small amount of current used for the ESC electronics that are not in series with the motor, but that should be negligible. </p>


问:
Grid based SLAM using BeagleBone Green Wireless and RPLIDAR
I've written a grid based DFS algorithm with a PID-based steering system to maneuver a 30cm2 square-grid maze all in Python. The robot is a 4 wheel drive with an approximate size of 20 cm. The robot has a BeagleBone Green Wireless controller which is connected by USB to the RPLIDAR A1.

At this current moment, the robot is underutilizing the LIDAR and I want to begin to learn SLAM. However, the environment is highly predictable which I think makes a full SLAM counterintuitive. I would also like the code to be low CPU strain.

I've seen people converting a conventional SLAM into a grid based but only after the calculations are complete. I was wondering if there is a way to do a Grid Based SLAM right from the start (assume its position and map with a grid).

Accuracy isn't hugely important here as long as it understands a tile and the robot is able to avoid walls.

Any advice, tips or suggestion is appreciated. How would you store the map? How would you locate the position of the robot? How would you map the LIDAR's values?

答:
I have little experience with SLAM but I have played with Bitmaps in python and they sound like they could be used as a means of storing the map. A bitmap is fundamentally a 2D array in which you can change the "pixels" to show walls and other objects in your maze. If you do a scale of 30:1 to store the grid map.

There are two methods of storing the slam data in bitmaps.

A 2D array of "tiles" (bitmaps) sized 10 x 10 bits that can be formatted to show "walls"

A huge single bitmap

You can learn more about bitmaps in Python here, How do I create a BMP file with pure Python?. If you need an example of a bitmap this image will help What a Bitmap Looks Like.


问:
Would the quad fly better with a 3S or 4S based on the weights of the batteries?
So the questions from the title is a bit hard to explain, so here is a better explanation of my question.

I want to get into the FPV quad flying hobby, so I decided to pick up a very starter quad, it's the Eachine Wizard X220. From the specs of the quad its lift off weight is 535 grams and the quad itself (without the battery but with all electronics) weights in at 364 grams. So I just need to pickup a battery everything else is accounted for. I want to get a 4S battery 1500 mAh which is 160 grams but that brings the total weight to 524.

So, my question is would the quad not be as efficient with this weight. Or should I just stick a 3S 1300 mAh and have a total weight of 484 grams?

答:
Adding more weight to a quadcopter will inevitably make the handling worse and reduce the flight time per Mah. However, we are talking about a 40-gram difference between these two batteries. It all depends on what matters the most to you when it comes to flight time and speed tradeoff.

A bigger battery is the better idea if you want the longest flight time possible. The trade off for more weight is less speed especially if the overall thrust of the engines is only 780g. Aircraft specs from here. That being said, you would most likely only gain 1-3 minutes at the cost of speed.

I would suggest the smaller battery as its an FPV drone and more speed makes the whole experience more enjoyable. What I have learned over my many years of using quadcopters including both the DJI Mavik Pro and countless custom drones is that it doesn't necessarily matter if the battery on the drone is small. The thing that does matter is that you have spare batteries to swap out when the battery on the drone dies.


答: From experience, I suggest you only install ROS on Ubuntu (the only supported platform at the moment). As previously mentioned, Virtualbox or, in my case, VMware Fusion, is how you'd get it to run as a guest in OSX. I'd suggest you dual-boot to Ubuntu for running ROS, though, mainly due to the computational requirements of some packages and workflows.</p>

Title: What is the easiest way to install ROS on OSX Mountain Lion?

Body:
The latest OSX documentation I found on the website is from 2011, and the latest build is from over a year ago. I'm a complete n00b to all things ROS and wanted to start playing with it. What is the easiest way?

Edit: this version of the installation instructions is more recent (April 2013), but it says that

OSX is not officially supported by ROS and the installation might fail for several reasons. This page does not (yet) contain instructions for most higher level ROS packages, only for the base system. This includes the middleware and command line tools but not much more.

"Does not contain instructions" also means it doesn't work? What do OSX users who work on ROS usually do? Run it on an Ubuntu VM? Install it just fine on their own on OSX, even though there aren't detailed instructions on the website?


答:
3S makes more sense on lighter quads but a 4S may give you more flight time, if you're running a mid range weight quad.

I have raised this question on many occasions when building custom quads for friends.

Title: Would the quad fly better with a 3S or 4S based on the weights of the batteries?

Body:
So the questions from the title is a bit hard to explain, so here is a better explanation of my question.

I want to get into the FPV quad flying hobby, so I decided to pick up a very starter quad, it's the Eachine Wizard X220. From the specs of the quad its lift off weight is 535 grams and the quad itself (without the battery but with all electronics) weights in at 364 grams. So I just need to pickup a battery everything else is accounted for. I want to get a 4S battery 1500 mAh which is 160 grams but that brings the total weight to 524.

So, my question is would the quad not be as efficient with this weight. Or should I just stick a 3S 1300 mAh and have a total weight of 484 grams?


问:
Can we specify the working zone for the robot using SLAM approach for navigation?
I am using SLAM for the autonomous vehicle navigation.

I want to the specify the working zone for the vehicle before the start of navigation, or can we restrict the working zone of the vehicle using SLAM approach for navigation.

答:
In theory that is possible. A SLAM (Simultaneous localization and mapping) algorithm, as the name suggests, will build a map of the environment and infer the vehicles position in that environment. Based on that information it should be possible to limit a vehicles navigation to a certain "working zone".

In practice the properties of the operational environment in combination with what vehicles, sensors and SLAM algorithms are used will determine if and what kind of "working zones" can be enforced. But without further information it is impossible to make a statement about any more concrete practical implications.


问:
Communication between Intel Edison and Open Mv7
I'm trying to do a simple communication between an Intel Edison and Open Mv 7 Camera through UART (Tx/Rx). I assumed this would be a simple task but both sides receive "�". Both are using python, the Intel Edison using  Pyserial to communicate while OpenMv7 is using PYB library.

Open Mv7.

```<code>import time
from pyb import UART

uart = UART(3, 9600)

while(True):
    if(uart.any() > 0):
        print(uart.read())
</code>```

Intel Edison

```<code>import serial
import time

ser = serial.Serial(port = "/dev/ttyO1", baudrate=9600)
ser.close()
ser.open()

print("Online")

ser.write("Hello World!")
</code>```

答:
Seems like the code should work. I can suggest 3 things that might be of assistance.

Make sure you have a prominent Common Ground Sometimes your PC isn't enough

Increase the BraudRate on both devices.

Most important make sure both devices are running at the same voltage. The Intel Edison is 1.8V without the Arduino Expander and the Arduino expander has a jumper that allows it to work at both 3.3V and 5V. You might need to switch it to 5V.


问:
What's wrong in controlling Roll+Roll rate in a quad-copter instead of using 2 separate loops for each?
I am curious to know why we can't apply control algorithm like PID on the weighted signal of Roll and Roll rate in a quad-copter instead of using two loops to control them independently. Fundamentally PID will make the input signal to approach $0$. In the case of (Roll + Roll-Rate), which would be $ w_1\theta + w_2\dot\theta$, the sum becomes $0$ when individually both tend to $0$; since we have an exponentially decaying curve.

So why do people generally use sequential loops to control each of them separately? (Roll is just for example)

答: That only works when the desire roll angle is 0. What happens if you are trying to turn and have a desired roll angle of 1deg? Even changing your sum to match the angle error, $w_1 (\theta - \theta_d) + w_2 \dot{\theta}$ you are still not guaranteed to reach $\theta=\theta_d$; you're only driving towards $w_1 (\theta - \theta_d) = -w_2 \dot{\theta}$. For most situations this will not be a stable equilibrium so then you'll oscillate back the other direction.</p>


问:
What does Simultaneous Localization And Mapping (SLAM) software do?
I took a course to have a better understanding of drones and their design. At the end of the course there was a test question that I got wrong and I would like to understand why.

I was supposed to select the choices that best describe SLAM.

and the possible answers were:

Estimates the location of features in the environment?

Controls the robot's flight through the environment?

Causes the robot to avoid obstacles in the environment?

Navigate in a cluttered environment?

Estimates the position and orientation of the robot with respect to
    the environment?

At first I knew that at least 3 and 4 were right because I watched a drone doing these things. I also thought that the last answer was linked to these two so I said yes to it too. Finally, I thought that the only thing that was still controlled by the user would be the flight...

Yet I failed again... Therefore what does Simultaneous Localization And Mapping (SLAM) software do?

答: My bet is 1 & 5. The agent or robot quickly orients itself to its environmental position. 1 satisfies this question. 5 satisfies the agent requirement.</p>


问:
Visualizing raw accelerometer and gyro data
I have an arduino wired to an MPU6050 breakout board. The arduino continuously collects accelerometer and gyroscope data from the MPU6050 and calculates angle and velocity.

Simply plotting the vector components (x,y,z) of this data does not allow one to reason about the motion of the sensor or robot. It's possible, though not easy, to do sanity checks (Is the sensor oriented as expected? Is gravity working?). But it's very difficult to look at a x,y,z plot of accelerometer log data and imagine what the robot did for instance.

I was wondering if there is some sort of tool or Python library to visualise accelerometer and gyro, or IMU data? (I'm looking for something like this- https://youtu.be/6ijArKE8vKU)

答:
I'm sure you've tried this, but if you follow the links in that YouTube video, you'll see that its author has posted the source code.  See:

Gait tracking with x-IMU, and;

Github: xioTechnologies/Gait-Tracking-With-x-IMU

Yes, it's written in MATLAB, but "for anything MATLAB can do, there's a corresponding Python library".  :)   In particular, you might want to investigate the quaternion package(s) in NumPy -- that's where the magic happens.

That should get you started.


问:
What reward function results in optimal learning?
Let's think of the following situations:

You are teaching a robot to play ping pong

You are teaching a program to calculate square root

You are teaching math to a kid in school

These situations (i.e. supervised learning), and many others have one thing (among others) in common: the learner gets a reward based on its performance.

My question is, what should the reward function look like? Is there a "best" answer, or does it depend on the situation? If it depends on the situation, how does one determine which reward function to pick?

For example, take the following three reward functions:

Function A says:

below a certain point, bad or worse are the same: you get nothing

there is a clear difference between almost good and perfect

Function B says:

you get reward linearly proportional to your performance

Function C says:

if your performance is bad, it's ok, you did your best: you still get some reward

there is not much difference between perfect and almost good

Intuitively, I'd think A would make the robot very focused and learn the exact pattern, but become stupid when dealing with similar patterns, while C would make it more adaptable to change at the cost of losing perfection.

One might also think of more complex functions, just to show but few:

So, how does one know which function to pick? Is it known which behavior would emerge from (at least) the basic A, B and C functions?

A side question is would this be fundamentally different for robots and human kids?

答:
These issues are addressed, to some extent, by the study of utility functions in economics.  A utility function expresses effective or perceived values of one thing in terms of another.  (While the curves shown in the question are reward functions and express how much reward will be tendered for various performance levels, similar-looking utility functions could express how much performance results from various reward levels.)

What reward function will work best depends on equilibria between the payer and the performer.  The wikipedia contract curve article illustrates with Edgeworth boxes how to find Pareto efficient allocations.  The Von Neumann–Morgenstern utility theorem delineates conditions that ensure that an agent is VNM-rational and can be characterized as having a utility function.  The  “Behavioral predictions resulting from HARA utility” section of the Hyperbolic absolute risk aversion article in wikipedia describes behavioral consequences of certain utility functions.

Summary: These topics have been the subject of tremendous amounts of study in economics and microeconomics.  Unfortunately, extracting a brief and useful summary that answers your question might also call for a tremendous amount of work, or the attention of someone rather more expert than me.


问:
Facing problems in Mask vector in Robotics toolbox
I am working on a 7 DOF serial manipulator and was trying to use ikine to get the joint coordinates for simple 2 DOF robot.

Even though I am using the masking vector as [ 1 1 0 0 0 0 ], I am getting error stating:

Number of robot DOF must be >= the same number of 1s in the mask matrix

This is my 2 DOF robot

```<code>L1 = Link('d', 0, 'a', 1, 'alpha', 0);
L1.m=50;
L1.r=[0.5,0,0];
L1.I=[0,0,0;0,0,0;0,0,10];
L1.G=1;
L1.Jm=0;

L2=Link(L1);

r2=SerialLink([L1,L2]);

r2.name='POLIrobot';
r2.gravity=[0;9.81;0];

q0=r2.ikine([eye(3),[0.2;0;0];[0,0,0,1]],[0,0],[1 1 0 0 0 0]);
</code>```

Can anyone please help and explain why is it happening?

答:
What are the options you're passing to the r2.ikine function? I believe that, at a minimum, you need to identify them. Try something like the following:

q0 = r2.ikine([eye(3),[0.2;0;0];[0,0,0,1]],'mask',[1 1 0 0 0 0]);

I can't tell what your [0,0] is (and neither can the function!), so I don't know what to suggest for that.


问:
Can I write the seperation principle for LQG controllers in this state space form?
Look at this picture. This is the seperation principle diagram.

It is an LQG controller which going to control the real life process. What I want to do, is to create a state space model for this seperation principle system, including the real life process. A LQG controller is a LQR controller together with the Kalmanfilter. Kalmanfilter is also called an observer.

The LQR controler is a feedback gain matrix L and the kalmanfilter is just a mathematical description of the real life system with a gain matrix K.

r(t) is the reference signal vector which describe how the system's states should hold e.g. temperature or pressure.
y(t) is the output from the real life process.
$\hat{y}$ is the estimated output from the kalmanfilter.
d(t) is the disturbance vector for the input. That's a bad thing, but the Kalman filter are going to reduce the disturbance and noise.
u(t) is the in signal vector to the real life system and the kalmanfilter.
n(t) is the noise vector from the measurement tools.
x(t) is the state vector for the system.
$\dot{x}$ is the state vector derivative for the system.
$\hat{x}$ is the estimated state vector for the system.
$\dot{\hat{x}}$ is the estimated state vector derivative for the system.

A is the system matrix. B is the in signal matrix. C is the output matrix. L is the LQR controler gain matrix. K is the kalmanfilter gain matrix.

So....a lot of people create the state space system as this: $$ $$
For the real life system:
$$ \dot{x} = Ax + Bu + d$$
For the kalmanfilter:
$$\dot{\hat{x}} = A\hat{x} + Bu + Ke$$
But $u(t)$ is:

$$u = r - L\hat{x}$$

And $e(t)$ is:
$$e = y + n - \hat{y} = Cx + n - C\hat{x} $$

And then...for some reason, people says that the state space model should be model by the state estimation error:

$$\dot{\tilde{x}} = \dot{x} - \dot{\hat{x}}  = (Ax + Bu + d) - (A\hat{x} + Bu + Ke)
$$
$$ \dot{\tilde{x}}  = (Ax + Bu + d) - (A\hat{x} + Bu + K(Cx + n - C\hat{x})$$
$$ \dot{\tilde{x}} = Ax - A\hat{x} + d - KCx - Kn + KC\hat{x} $$
And we can say that:
$$\tilde{x} = x - \hat{x} $$
Beacuse:
$$\dot{\tilde{x}} = \dot{x} - \dot{\hat{x}}$$
The kalmanfilter will be:
$$ \dot{\tilde{x}} = (A - KC)\tilde{x} + Kn$$

The real life process will be:
$$ \dot{x} = Ax + Bu + d = Ax + B(r - L\hat{x}) + d = Ax + Br - BL\hat{x} + d$$

But:
$$\tilde{x} = x - \hat{x} \Leftrightarrow  \hat{x} = x - \tilde{x}$$

So this will result for the real life process:
$$ \dot{x} =  Ax + Br - BL(x - \tilde{x}) + d = Ax + Br - BLx + BL\tilde{x} + d$$

So the whole state space model will then be:

$$
\ \begin{bmatrix} \dot{x} \\ \\\dot{\tilde{x}} \end{bmatrix} =\begin{bmatrix} A - BL& BL \\ 0 & A-KC \end{bmatrix} \begin{bmatrix} x\\ \tilde{x} \end{bmatrix}+\begin{bmatrix} B & I & 0\\ 0 & 0 & K \end{bmatrix}\begin{bmatrix} r\\ d\\ n \end{bmatrix}\
$$

Youtube example:
https://youtu.be/H4_hFazBGxU?t=2m13s

$I$ is the identity matrix. But doesn't need to be only ones on digonal form.
$0$ is the zero matrix.

The Question: $$ $$
If I write the systems on this forms:
$$ \dot{x} = Ax + Bu + d = Ax + B(r - L\hat{x}) + d$$
For the kalmanfilter:
$$\dot{\hat{x}} = A\hat{x} + Bu + Ke = A\hat{x} + B(r - L\hat{x}) + K(y + n - \hat{y})$$
Beacuse $u(t)$ and $e(t)$ is:
$$u = r - L\hat{x}$$
$$e = y + n - \hat{y} = Cx + n - C\hat{x} $$

I get this:
$$\dot{x} = Ax + Br - BL\hat{x} + d$$
$$\dot{\hat{x}} = A\hat{x} + Br - BL\hat{x} + KCx + Kn - KC\hat{x}$$
Why not this state space form:
$$
 \begin{bmatrix} \dot{x} \\ \\\dot{\hat{x}} \end{bmatrix} =\begin{bmatrix} A & -BL \\ KC & [A-BL-KC] \end{bmatrix} \begin{bmatrix} x\\ \hat{x} \end{bmatrix}+\begin{bmatrix} B & I & 0\\ B & 0 & K \end{bmatrix}\begin{bmatrix} r\\ d\\ n \end{bmatrix}\
$$
Youtube example:
https://youtu.be/t_0RmeSnXxY?t=1m44s

Who is best? Does them both works as the LQG diagram shows? Which should I use?

答:
This is really a lot to look at, but the most glaring issue I noticed off the bat is your definition of the control signal $u(t)$.

What is the input to your controller? What should be the input to your controller? What is the output of the controller?

State feedback controllers (and LQR controllers) attempt to drive the system states to zero. The control law for these controllers is:

$$
u = -Lx \\
$$

or, in the case of a state estimator (Kalman filter, EKF, etc.), is:

$$
u = -L\hat{x} \\
$$

You are attempting to implement reference tracking by passing an input $r(t)$ to the controller. With a state feedback controller, this is generally done with integral control by adding a state to the state matrix such that:

$$
\dot{e_I} = r(t) - x(n) \\
$$

where $x(n)$ is the state you're trying to control. Consider, for instance, an oscillating system (spring/mass/damper, etc.) where you're trying to control position. The states would all be the same (position/speed/acceleration), so how would your controller "know" that you're attempting to control position and not speed if you're using a control signal of $u(t) = r(t) - Kx$?

So again, for an oscillator, your system might look like:

$$
\left[\begin{array}{c}
\dot{x} \\
\ddot{x} \\
\end{array}\right] = \left[\begin{array}{cc}
0 & 1 \\
-\omega_n^2 & 0 \\
\end{array}\right]\left[\begin{array}{c}
x \\
\dot{x} \\
\end{array}\right]
$$

Your integral controller then appends a state. Now, if you're trying to control position, you get:
$$
\left[\begin{array}{c}
\dot{x} \\
\ddot{x} \\
\dot{e_I} \\
\end{array}\right] = \left[\begin{array}{ccc}
0 & 1 & 0 \\
-\omega_n^2 & 0 & 0\\
-1 & 0 & 0 \\
\end{array}\right]\left[\begin{array}{c}
x \\
\dot{x} \\
e_I \\
\end{array}\right]
$$

Note the $\dot{e_I}$ state - the derivative of an integral error is just the control error. The integral error term $e_I$ doesn't impact either the $x$ or $\dot{x}$ states, but it gives you a new state for control purposes, $u(t) = -Kx$. Now you get a third gain to tune (third pole to place).

Again, this is all specific for state feedback controllers, but the method works the same for integral control of an LQR system - this is referred to as linear-quadratic-integral control.

Now you can also clearly change which states you're trying to control by altering how the $\dot{e_I}$ term is defined. You can "pick" the position state with $[1,0]$, or the speed state with $[0,1]$, or the acceleration state by recognizing the definition from the state space form: $\ddot{x} = [-w_n^2,0][_{\dot{x}}^{x}]$.

In re-reading your question, it looks like there may be some confusion too on observer setup/design. Observer design is commonly referred to as the "dual" of the controller design because they take similar forms and you can generally do the same steps to get the answer.

A state feedback controller attempts to drive the states to zero. With an observer, you commented:

And then...for some reason, people says that the state space model should be model by the state estimation error

Correct. The observer "states" are the errors between the modeled states and the actual system states. This is where duality comes in. A state feedback controller and an observer BOTH attempt to drive their states to zero.

In a controller, the states are the actual system states.

In an observer, the states are the differences between actual and modeled system states. When the observer has done its job, the modeled states should be exactly equal to the actual system states. In order for the observer to have a meaningful use for the controller, the observer should converge faster than the controller such that the controller has the actual system states (or very close to) by the time the controller begins to respond.

This is the basis for the thumb rule that the observer poles should be "faster" than the control poles (I've read and generally use 5-10 times faster). The observer will cause the modeled states to fluctuate while it converges (hunts) to the correct state measurement, so it's important for that fluctuation to happen faster than the system is able to respond so it doesn't ripple through the controller output.

SO, that's the reasoning for observer design - it's basically a second controller that exists to drive state error to zero.

:EDIT: - I removed the previous last section here because I mis-read $\tilde{x}$ in the first set of equations as $\hat{x}$ and then confused myself comparing the two. That said, I think the second form is still a little incorrect (assuming the first form is correct) because of how the exogenous inputs are incorporated. Working entirely from the first form, it starts as:

$$
\ \begin{bmatrix} \dot{x} \\ \\\dot{\tilde{x}} \end{bmatrix} =\begin{bmatrix} A - BL& BL \\ 0 & A-KC \end{bmatrix} \begin{bmatrix} x\\ \tilde{x} \end{bmatrix}+\begin{bmatrix} B & I & 0\\ 0 & 0 & K \end{bmatrix}\begin{bmatrix} r\\ d\\ n \end{bmatrix}\
$$

First, recognize that the state error $\tilde{x} = x-\hat{x}$, and then look just at the first row:

$$
\dot{x} = \left[A-BL\right]x + \left[BL\right]\tilde{x} + Br + Id \\
$$

For the purposes of the rest of this, I'm just going to refer to $Id$ as $d$. So, substitute in the definition of $\tilde{x}$:

$$
\dot{x} = \left[A-BL\right]x + \left[BL\right]\left(x-\hat{x}\right) + Br + d \\
$$
$$
\dot{x} = \left[A-BL\right]x + \left[BL\right]\left(x\right) + \left[BL\right]\left(-\hat{x}\right) + Br + d \\
$$
$$
\dot{x} = \left[A-BL+BL\right]x + \left[-BL\right]\hat{x} + Br + d \\
$$

$$
\boxed{\dot{x} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d} \\
$$

Great! This is the same first row as the second form. Now, to the second row of the first form:

$$
\dot{\tilde{x}} = [A-KC]\tilde{x} + Kn \\
$$

Again, make the substitutions of $\tilde{x} = x-\hat{x}$ and now also $\dot{\tilde{x}} = \dot{x} - \dot{\hat{x}}$:

$$
\dot{x} - \dot{\hat{x}}= [A-KC]\left(x-\hat{x}\right) + Kn \\
$$

Expand the $x-\hat{x}$ term:

$$
\dot{x} - \dot{\hat{x}}= [A-KC]x - [A-KC]\hat{x} + Kn \\
$$

To get rid of the $\dot{x}$ on the left hand side, just use the definition of $\dot{x}$ from the result of the first row!

$$
\dot{x} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d
$$

$$
\left[A\right]x + \left[-BL\right]\hat{x} + Br + d - \dot{\hat{x}}= [A-KC]x - [A-KC]\hat{x} + Kn \\
$$

Rearrange:
$$
\left[A\right]x + \left[-BL\right]\hat{x} + Br + d - \left([A-KC]x - [A-KC]\hat{x} + Kn\right) = \dot{\hat{x}}\\
$$

$$
\dot{\hat{x}} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d - \left([A-KC]x - [A-KC]\hat{x} + Kn\right)\\
$$

Distribute the negative:
$$
\dot{\hat{x}} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d + \left(-[A-KC]x + [A-KC]\hat{x} - Kn\right)\\
$$

$$
\dot{\hat{x}} = \left[A\right]x + \left[-BL\right]\hat{x} + Br + d - [A-KC]x + [A-KC]\hat{x} - Kn\\
$$

Rearrange again:

$$
\dot{\hat{x}} = \left[A\right]x - [A-KC]x + [A-KC]\hat{x} + \left[-BL\right]\hat{x} + Br + d - Kn\\
$$

Simplify one last time:

$$
\boxed{\dot{\hat{x}} = [KC]x + [A-BL-KC]\hat{x} + Br + d - Kn}\\
$$

This is almost, but not quite what is given as the second row of the second form. This equation has the term $d$ (really $Id$) included and also has $-Kn$ instead of $Kn$.


问:
Control a robotic gripper
I have created a robotic gripper. However, I need help in the control circuit:

There are two buttons, the upper and lower one (connected to the timer):

the upper one is two states timer either up or down (will be replaced with an active low pin in PCB design).

the lower one is a push button that must be pushed and  let back to its initial position to give a pulse to the monostable timer to make the servo rotate long enough to just close the gripper (calculate with the RC circuit).

My problem: I want to replace the down button with some component so as to give a quick pulse when the upper button change state.

For example, the button was 0 and went 1 -> Component -> a small pulse to drive the timer (not a pulse that will last until the state changes):

Where,

Green: is button state

Red: trigger pulse needed.

答:
This can be easily done with a 555 timer, or even a flip flop and a counter.   Are you looking for design concepts or a detailed design?

EDIT

Check out this site for a simple edge-triggered one-shot that uses two nor gates and an R-C (scroll down to the NOR Gate Monostable section).   I can't draw the circuit on here using my phone so I apologize about just providing a link.

Title: Control a robotic gripper


答:
Both state space representations are equivalent. For example the eigenvalues of the two closed-loop system matrices should be the same. However when implementing LQG you only have access to the outputs and the variables you introduced yourself, so either $\hat{x}$ or $\tilde{x}$. But you are still limited by the given dynamics of the states of the system you want to control

$$
\dot{x} = A\,x+B\,u,
$$

where only $u$ can be chosen freely. As stated before, the true state $x$ is not known. This together implies that the matrix entry of the closed-loop system matrix at the first row and first column should remain $A$, as in your last state space form with $\hat{x}$.

However your first state space with $\tilde{x}$ is often used to proof stability. Namely the eigenvalues of the closed-loop system matrix are equal to the combination of the eigenvalues of $A-B\,L$ and $A-K\,C$, which should both be Hurwitz.

As also stated in the answer of Chuck, your incorporation of the reference signal $r$ in the feedback law will in general not give good (steady state) tracking. Namely LQR is only good at controlling the state space to zero. If you do want good reference tracking you should look at Linear Quadratic Integral, or add feed forward.

Title: Can I write the seperation principle for LQG controllers in this state space form?

Body:
Look at this picture. This is the seperation principle diagram.

It is an LQG controller which going to control the real life process. What I want to do, is to create a state space model for this seperation principle system, including the real life process. A LQG controller is a LQR controller together with the Kalmanfilter. Kalmanfilter is also called an observer.

The LQR controler is a feedback gain matrix L and the kalmanfilter is just a mathematical description of the real life system with a gain matrix K.

r(t) is the reference signal vector which describe how the system's states should hold e.g. temperature or pressure.
y(t) is the output from the real life process.
$\hat{y}$ is the estimated output from the kalmanfilter.
d(t) is the disturbance vector for the input. That's a bad thing, but the Kalman filter are going to reduce the disturbance and noise.
u(t) is the in signal vector to the real life system and the kalmanfilter.
n(t) is the noise vector from the measurement tools.
x(t) is the state vector for the system.
$\dot{x}$ is the state vector derivative for the system.
$\hat{x}$ is the estimated state vector for the system.
$\dot{\hat{x}}$ is the estimated state vector derivative for the system.

A is the system matrix. B is the in signal matrix. C is the output matrix. L is the LQR controler gain matrix. K is the kalmanfilter gain matrix.

So....a lot of people create the state space system as this: $$ $$
For the real life system:
$$ \dot{x} = Ax + Bu + d$$
For the kalmanfilter:
$$\dot{\hat{x}} = A\hat{x} + Bu + Ke$$
But $u(t)$ is:

$$u = r - L\hat{x}$$

And $e(t)$ is:
$$e = y + n - \hat{y} = Cx + n - C\hat{x} $$

And then...for some reason, people says that the state space model should be model by the state estimation error:

$$\dot{\tilde{x}} = \dot{x} - \dot{\hat{x}}  = (Ax + Bu + d) - (A\hat{x} + Bu + Ke)
$$
$$ \dot{\tilde{x}}  = (Ax + Bu + d) - (A\hat{x} + Bu + K(Cx + n - C\hat{x})$$
$$ \dot{\tilde{x}} = Ax - A\hat{x} + d - KCx - Kn + KC\hat{x} $$
And we can say that:
$$\tilde{x} = x - \hat{x} $$
Beacuse:
$$\dot{\tilde{x}} = \dot{x} - \dot{\hat{x}}$$
The kalmanfilter will be:
$$ \dot{\tilde{x}} = (A - KC)\tilde{x} + Kn$$

The real life process will be:
$$ \dot{x} = Ax + Bu + d = Ax + B(r - L\hat{x}) + d = Ax + Br - BL\hat{x} + d$$

But:
$$\tilde{x} = x - \hat{x} \Leftrightarrow  \hat{x} = x - \tilde{x}$$

So this will result for the real life process:
$$ \dot{x} =  Ax + Br - BL(x - \tilde{x}) + d = Ax + Br - BLx + BL\tilde{x} + d$$

So the whole state space model will then be:

$$
\ \begin{bmatrix} \dot{x} \\ \\\dot{\tilde{x}} \end{bmatrix} =\begin{bmatrix} A - BL& BL \\ 0 & A-KC \end{bmatrix} \begin{bmatrix} x\\ \tilde{x} \end{bmatrix}+\begin{bmatrix} B & I & 0\\ 0 & 0 & K \end{bmatrix}\begin{bmatrix} r\\ d\\ n \end{bmatrix}\
$$

Youtube example:
https://youtu.be/H4_hFazBGxU?t=2m13s

$I$ is the identity matrix. But doesn't need to be only ones on digonal form.
$0$ is the zero matrix.

The Question: $$ $$
If I write the systems on this forms:
$$ \dot{x} = Ax + Bu + d = Ax + B(r - L\hat{x}) + d$$
For the kalmanfilter:
$$\dot{\hat{x}} = A\hat{x} + Bu + Ke = A\hat{x} + B(r - L\hat{x}) + K(y + n - \hat{y})$$
Beacuse $u(t)$ and $e(t)$ is:
$$u = r - L\hat{x}$$
$$e = y + n - \hat{y} = Cx + n - C\hat{x} $$

I get this:
$$\dot{x} = Ax + Br - BL\hat{x} + d$$
$$\dot{\hat{x}} = A\hat{x} + Br - BL\hat{x} + KCx + Kn - KC\hat{x}$$
Why not this state space form:
$$
 \begin{bmatrix} \dot{x} \\ \\\dot{\hat{x}} \end{bmatrix} =\begin{bmatrix} A & -BL \\ KC & [A-BL-KC] \end{bmatrix} \begin{bmatrix} x\\ \hat{x} \end{bmatrix}+\begin{bmatrix} B & I & 0\\ B & 0 & K \end{bmatrix}\begin{bmatrix} r\\ d\\ n \end{bmatrix}\
$$
Youtube example:
https://youtu.be/t_0RmeSnXxY?t=1m44s

Who is best? Does them both works as the LQG diagram shows? Which should I use?


答:
Any form of supervised learning is a directed search in policy space. You try to find the policy -- so which action to take -- which provides the maximum reward expectation. In your question you give reward as a function of performance. As long as this function is monotonic any method which converges will ultimately end up giving you maximum performance (too stay with your terminology).

How fast the method converges is another matter, and may well depend on the curve. But I think this will differ from method to method.

An entirely different problem is that for more complex scenarios performance is not a simple scalar, and defining it can be pretty difficult. What's the reward function for being good at math?

Title: What reward function results in optimal learning?

Body:
Let's think of the following situations:

You are teaching a robot to play ping pong

You are teaching a program to calculate square root

You are teaching math to a kid in school

These situations (i.e. supervised learning), and many others have one thing (among others) in common: the learner gets a reward based on its performance.

My question is, what should the reward function look like? Is there a "best" answer, or does it depend on the situation? If it depends on the situation, how does one determine which reward function to pick?

For example, take the following three reward functions:

Function A says:

below a certain point, bad or worse are the same: you get nothing

there is a clear difference between almost good and perfect

Function B says:

you get reward linearly proportional to your performance

Function C says:

if your performance is bad, it's ok, you did your best: you still get some reward

there is not much difference between perfect and almost good

Intuitively, I'd think A would make the robot very focused and learn the exact pattern, but become stupid when dealing with similar patterns, while C would make it more adaptable to change at the cost of losing perfection.

One might also think of more complex functions, just to show but few:

So, how does one know which function to pick? Is it known which behavior would emerge from (at least) the basic A, B and C functions?

A side question is would this be fundamentally different for robots and human kids?


问:
Motor Controller Power Supply
I have an Orange Pi which I would like to use as the computer for a robotic project. It supplies around 15 mAh power directly from the board, barely enough for a single LED so I will have to use a motor controller and an external power supply.

My question is, is there a limit to how big of a motor I use with this small orange Pi zero? As long as I have the appropriate power supply and controller for the motor I feel it shouldn't be an issue.

What are some things to keep in mind?

答:
Dependings on what type of motor driver you use...

If you drive transistors directly from an orange PI output, you need to make sure that the PI can supply enough current to saturate the transistors (this is mainly true for BJT type transistors, less problematic for FET or IGBTs, which you most probably drive with a transistor driver).

If the transistor gates are not driven directly (e.g. are optically isolated or you have a transistor driver IC) by the PI you only need to make sure that the voltage levels of the PI and the IC driving the transistors match.

If the motor driver is driven by an analog signal (e.g. 4-20mA signal or 0-10V signal) driving it directly from the PI will probably be problematic since max current for the first case or max voltage for the second case probably cannot be achieved.

If there is a communication protocol between the transistor driver and the motor driver unit, maximum current will definitely not be an issue. In this case you need to match the communication protocol pins (e.g. i2c or SPI)

Title: Motor Controller Power Supply


问:
Compensation for IMU mounting misalignment
I have an MPU6050 IMU and I would like to mount it on an FSAE car and use it to measure the yaw, pitch, roll, and angular velocities as it drives. As it's impossible to mount it perfectly flat and align the IMU axes with the axes of the car, I am looking for a way to calibrate and compensate for the rotational offset of the car's frame and the IMU's frame.

From the IMU I can get quaternions, Euler angles, raw acceleration and angular velocity data, or yaw, pitch, and roll values. I imagine the solution will involve matrix and trig calculations, but I didn't pay nearly enough attention in multivariable calc to figure this out.

答:
You need the transformation from the car to the IMU.

You can get this by recording the IMU published attitude with the car in known orientations.

You should be able to construct the IMU to car transformation by grabbing the IMU orientation while the car is flat, pitched up a bit (30 deg would should enough), and rolled (again, 30 deg should be enough).

Using the three known car attitudes and the three measured IMU attitudes you should be able to construct the car IMU transformation.


答:
"Optimal learning" is a very vague term, and it is completely dependent on the specific problem you're working on.  The term you're looking for is "overfitting":

(The green line is the error in predicting the result on the training data, the purple line the quality of the model, and the red line is the error of the learned model being used "in production")

In other words: when it comes to adapting your learned behavior to similar problmes, how you rewarded your system is less important than how many times you rewarded it -- you want to reduce errors in the training data, but not keep it in training so long that it loses the ability to work on similar models.

One method of addressing this problem is to cut your training data in half: use one half to learn on and the other half to to validate the training.  It helps you identify when you begin to over-fit.

Non-linear reward functions

Most supervised learning algorithms expect that application of the reward function will produce a convex output.  In other words, having local minima in that curve will prevent your system from converging to the proper behavior.  This video shows a bit of the math behind cost/reward functions.


问:
Can RC servo motors continually rotate?
I know that RC servo motors are designed for precise movement, rather than a D.C. motor's continual rotation. Are most RC servo motors limited to movement within one rotation or can they actually be made to continually rotate? That is to say, is their movement limited to a specific arc? Or does it depend on the type of RC servo motor?

I have seen videos of industrial size steppers rotating constantly, but, more specifically, I was wondering whether a MG995 can.

I don't own any RC servo motors yet, so I can't actually test it myself. I just want to make sure before I make a purchase. I keep seeing conflicting information, for example the instructable, How to modify a RC servo motor for continuous rotation (One motor walker robot), implies that a RC servo motor will not continually rotate, else otherwise, why would there be a need to modify it?

Addendum

I have just realised, after further digging about on google, and as HighVoltage points out in their answer, that I have confused steppers and servos.

In addition, I found out how to hack the TowerPro MG995 Servo for continuous rotation.

答:
Regarding the first statement in your question:
"I know that RC servo motors are designed for precise movement, rather than a D.C. motors' continual rotation. Are most RC servo motors limited to movement within one rotation or can they actually be made to continually rotate?"

A Continuous Rotation RC Servo is NOT a Servo

Here is why

What is a Servo

A Servo (Servomotor) is a motor with a position sensor and a closed-loop controller that adjusts the motor power to assure the motor is accurately held at the commanded position.

What is an RC Servo

An RC Servo is a small DC motor geared down to a drive shaft that has a potentiometer (rotary resistor) for its position sensor and is controlled by a pulse train.  The width of the pulse (PW) determines the drive shaft position. The controller compares the PW to the potentiometer position and the motor is driven to compensate for the error.  In a typical RC Servo, a 1.5 ms pulse is center position.  For an example, in this case, the pulse is compared to the center resistance value of potentiometer.  If the potentiometer is at its center value, no power is applied to the motor.  If, however, the servo is clockwise (CW) of center then the potentiometer value will be lower and the servo controller will apply power to turn the motor counter-clockwise (CCW) to bring it back to center. The bigger the error, the more power will be applied to the motor.  If the error is in the opposite direction, the motor will be driven CW.

The advantage of this design is that you can produce a very light weight servo out of small inexpensive components.  The limitation of this design is that the travel of the drive shaft is limited by the rotational travel of the potentiometer.  For RC that is not generally an issue as RC servos are usually used to drive control services that have very limited travel.

Why a "Continuous Rotation" RC Servo is not a Servo

As @Greenonline mentioned, you can modify an RC Servo for continuous rotation.

Note is the video what they guy does

He removes the end stop that protects the potentiometer

He cuts the wires from the controller to the potentiometer and connects a fixed resistor

So, going back to my description of an RC Servo, what does that result in?

Since the position sensor (potentiometer) is gone, there is no longer a control loop so it is no longer a Servo.

If you were to send in a PW of 1.5 ms, the controller would see the resistance at center point and would not apply power to the motor.

If you were to send in a PW of <1.5 ms (commanding a position CCW of center), the controller would see the resistance at center point and drive the motor CCW to get there (which it never will) and hence it will rotate continuously CCW.

Because there is no feedback control you will not be able to rely on the speed or accuracy of the motor; but, you will have a small DC motor that you can command using a RC Servo controller (or a using a PW)

Title: Can RC servo motors continually rotate?


问:
What is the function of inductors in series between the terminals and the brushes of a DC motor?
I'm repairing (hopefully) a 12 V DC motor (Johnson Electric HC971(2)LG-101).

The motor has a coil in the motor cap between each terminal and the corresponding brush - two coils (inductors) one on each side of the armature electrically speaking. It also has what I think is a resistor on one side and what I think is a (broken) capacitor between the two terminals.

What is the function of the two inductors in series between the terminals and brushes?

I'm sure this info it's out there somewhere but I haven't found it online after several days of searching.

答:
Likely the series induction prevent higher frequencies from making it back from the motor to the power supply. The inductors looks like an open circuit to higher frequencies.

A parallel capacitor can also help as it shorts the higher frequencies preventing them from getting back to the power supply.

ContentLicense: CC BY-SA 4.0


问:
Mounting on servo horn
I'm trying to mount a rod on a micro servo's horn. The horn has several 1mm wide through holes. Does anyone know what sort of (tapping?) screws should be used for tapping 1mm plastic holes? Are M1.2 too small since the threads will be just 0.1mm deep?

Are there canonical approaches to choosing the appropriate self-tapping screw size given hole diameter?

答:
With plastic holes especially on Servo Horns, the best solution is to use screws that are slightly bigger than the hole. Depending on the strength needed for this connection there are two methods which would work.

Add screws to every hole

Buy Metal Servo Horn with tapped holes

Title: Mounting on servo horn


问:
Should the kalmanfilter have disturbance as input?
This is a kalmanfilter

As you can see, the process noise(disturbance) is not going to the kalmanfilter. But the state space model for the state feedback system is written as this: https://youtu.be/H4_hFazBGxU?t=5m43s

So what is right and what is wrong? Should a kalmanfilter have disturbance as input too?

Like this. With disturbance as input:

$$
\ \begin{bmatrix} \dot{x} \\ \\\dot{\tilde{x}} \end{bmatrix} =\begin{bmatrix} A - BL& BL \\ 0 & A-KC \end{bmatrix} \begin{bmatrix} x\\ \tilde{x} \end{bmatrix}+\begin{bmatrix} I & 0\\ I & K \end{bmatrix}\begin{bmatrix} d\\ n \end{bmatrix}\
$$

Or this. Without disturbance as input:

$$
\ \begin{bmatrix} \dot{x} \\ \\\dot{\tilde{x}} \end{bmatrix} =\begin{bmatrix} A - BL& BL \\ 0 & A-KC \end{bmatrix} \begin{bmatrix} x\\ \tilde{x} \end{bmatrix}+\begin{bmatrix} I & 0\\ 0 & K \end{bmatrix}\begin{bmatrix} d\\ n \end{bmatrix}\
$$

答:
I don't like the format you're using, with $\tilde{x}$, because it masks the fact that it is actually $x-\hat{x}$. In generally, you don't actually care about the state error; what you really should care about are the states themselves. The state error drives your state estimates to be equal to the actual states (eventually), but beyond that they shouldn't really be providing any useful information.

I say this because, as written, it looks like the actual system states $x$ aren't a part of your state error calculations because there's a big fat zero in the bottom-left of the system matrix. In reality though, again, you've masked the fact that you're actually using the system states twice - once directly as $x$ and then again as $x - \hat{x}$. There's a zero in the bottom-left of the system matrix because it's redundant.

All this is a preface to two points:

Your input disturbances $d$ will propagate to the Kalman filter naturally because they affect the system states, which in turn are measured and used as part of the input to the Kalman filter, AND

You can't include input disturbances in a Kalman filter in real life because you can't measure them, in the same way you can't "know" what the measurement noise is.

Use the first form.


问:
Can I implement continuous time feedback regulator in an Arduino microcontroller?
Arduino is a digital mikrocontroller. But I wonder if it's possible to implement an continuous time feedback regulator in an Arduino microprocessor?

Continuous time feedback regulators such as PID:

$$
K = P(e(t)-D\frac{\mathrm{d} }{\mathrm{d} x}e(t) + I\int_{0}^{\infty} e(t) dt)
$$

Or LQG regulator (this is a LQR with kalmanfilter only, not the model):
$$
\dot{\hat{x}} = (A - KC)\hat{x} + Bu + Ky + Kn - KC\hat{x}
$$

$$
u = r - K\hat{x} $$

Or do it need to be a digital feedback regulator?  I mean....those feedback regulators works exellent by using operational amplifiers.

I know that operational amplifier works in real time. But an Arduino working in 16 Mhz speed, and that's very fast too.

答:
continuous time feedback regulator in an Arduino microprocessor.

You can get at most a very accurate approximation of the continuous time system using Arduino by converting the continuous time model of your system into a discrete-time version: once you have the transfer function of you continuous time control system (filter or controller) you can operate a discretization through some well-known method such as the
Bilinear transform and then obtaining the digital (dicrete-time) version to implement.

PS: do not confuse the real-time with the continuous time.

EDIT: Every time you deal with the "digital world" (memories, sample&hold processing) you need a discrete-time version of your continuous time model. You cannot directly implement it as it is (beside using an automatic code generator, but even in that case an automatic conversion continuous-to-discrete is also needed).
Just to have an example, if you have a simple low-pass filter, easy to build with analog electronic components (resistor and capacitor) as:
$$W(s) = \frac{1}{1+sRC}$$

to implement it into a discrete-time system (such as microcontroller) you need its discrete time version which will have comparable performance under certain conditions:

$$W(z) = {\frac  {1+z^{{-1}}}{(1+2RC/T)+(1-2RC/T)z^{{-1}}}}$$

The most important thing to observe when a model of a system is converted is Nyqvist-Shannon sampling theorem.


问:
What is the difference between 4-point and 8-point connectivity in graph based planning?
In graph-based planning (say, A*), states are connected to their neighbors.  How should one decide whether to connect to the 4 neighbors or the 8 neighbors?  What are the pros and cons of each approach?</p>

答:
I believe it simply boils down to what your robot can do.

If you are for some reason restricted to moving only in 4 directions, then you connect each grid cell to 4.

If you can go in 8 directions, you connect each grid cell to 8.

If you can go in 6 directions, you use a honeycomb grid and connect each grid cell to 6.

There is no generic answer. If you plan to go diagonally with a robot that can't perform the action, that's bad planning. If you plan to only go horizontally and vertically while your robot can take shortcuts, that's also bad planning.


问:
Multicopter: What are Euler angles used for?
I hope you can help me and this is the right forum to ask.

In the process of building and programming my own Quadcopter, I encountered the term Euler angles. I took some time to understand them and then wondered why they are used in multicopter systems.

In my understanding Euler angles are used to rotate a point or vector in a coordinate system/ to express that rotation. I now wonder why i should use Euler angles to compute the orientation of the quadcopter as I could easily(at least i think so) compute the angles by themself, like
$$
\theta = arctan(y/z)
$$
$$
\phi = arctan(x/z)
$$
(just using accelerometer, where $x, y, z$ are axis accelerations and $\theta, \phi$ are pitch and roll, respectively. In the actual implementation I do not only use the accelerometer, this is just simplified to make the point clear).

Where exactly are Euler angles used?
Are they only used to convert desired trajectory in the earth frame to desired trajectory in the Body frame?

I would be very glad if anyone could point this out and explain the concept/ why and where they are used further.

To clarify: I do know that Euler angles encounter gimbal lock, that they are three rotations about $x, y, z$ axis and
how they generally work(I think). @Christo gave a very good explanation.

My question now is, why are they used? Isn't it counterproductive to apply the yaw rotation, then pitch, and then roll?

```<code>-Earth frame X,Y,Z
rotation about Z(psi)
->Frame 1 x', y', z'
rotation about y'(theta)
->Frame 2 x'', y'', z''
rotation about x''(phi)
->Body frame x, y, z
</code>```

and vice versa.

Why? I would just have said:

```<code>pitch = angles between X and x
roll = angle between Y and y
yaw = angle between x-y-projection of the magnetic field-vector and the starting vector(yaw is kinda different).
</code>```

(Notice the difference between uppercase and lowercase, look at the Earth-to-Body-Frame for notation).
Tied with this i wonder why the correct formula for pitch($\theta)$ should be $$\theta = \tan^{-1}\left(-f_x/\sqrt{f_y^2+f_z^2}\right)$$
I would have thought $$\theta = \tan^{-1}\left(-f_x/f_z\right)$$ suffices.
Maybe I have some flaw in my knowledge or a piece of the puzzle is still missing.

I hope this is understandable, if not feel free to ask. If this gets too crowded, I can always ask another question, just make me aware of it.

If anyone could explain how to use quaternions to express orientation I would be very thankful, but I can also just ask another time. I get the concept of Quaternions, just not how to use them to express orientation not rotation.

答:
Your own equations make a lot of assumptions about the problem you are trying to solve. They are sufficient to solve your problem, but will not work for certain conditions (z = 0 for instance).

Euler angles are similar. A way describe orientation (we typically use orientation to mean all angles, not just pitch and roll as you are using here). Euler angles have limitations similar to your equations and won't work for a lot of situations (Search: gimbal lock).

In my own career, I have never used euler angles. I find them confusing since there are so many permutations of them.

Direction cosines (3x3 rotation matrices) are much easier to visualize for me and I use them when doing things by hand. Since they are also the primary way to do transforms, it's also the way that most use to do calculations.

Quaternions work great for calculation. Convert your orientation to a quaternion using the typical equations, do your slerp or whatever, and convert them back to an orientation when you need to transform coordinates or vectors.

My recommendation would be to learn to use rotation matrices and quaternions when working with orientations, and leave representations that use angles to the primary school kids.


问:
High Res Rotary Encoders
As part of a project I need an encoder to determine the angle that this, Continuous Rotation Servo - FeeTech FS5103R, has rotated through. The resolution needs to be fairly high as I will be using it to automate a process and so I want to make sure it's accurate.

The shaft it will be mounted to will be custom built so I'm just looking for standalone encoders right now. What are the pros and cons of different styles of rotary encoders?

答:
RC Servos are servos that use a potentiometer as their position sensor.
To make a continuous rotation RC servo, the potentiometer is replaced with a fixed resistor so the servo loop is lost and thus the accuracy and position information as well.
See A Continuous Rotation RC Servo is NOT a Servo for more details.

BUT... if you do the modification yourself (like is the guy in this video did) then the potentiometer is still there and it should provide a really inexpensive and pretty accurate way to know the motor's position.  To use it, route the wires out and use an Analog Input on your processor to measure the absolute position of the motor.

OK, here it where I divert into something I believe will work but haven't tested.  I believe if you alter the procedure to ONLY cut the center wire to the potentiometer and still do the rest of the modification then route that center wire out, the wire will have a voltage that represents the location of the motor shaft.  This is because the outer wires are just to provide power and powering both resistor stacks should not be a problem and the voltage on the wire will be a voltage between the servo supply voltage and ground.

Another option is to use an actual optical encoder.  Note that this is a significantly more expensive and complicated solution because:

Optical encoders can be expensive

You will need to figure a way to directly couple the encoder to the shaft.

If you get a standard quadrature encoder, you will need to add a home sensor since the encoder (unlike the potentiometer) has no concept of absolute position

You will have to know how to decode and use quadrature signals to count position.  This is really easy to mess up for cases like an encoder vibrating on an edge.

You will also need to make sure your design is fast enough that you can catch all the transitions when running at full speed (interrupt based or custom hardware).  For a 1024 count encoder and a 55rpm motor then your are going to need to sample the encoder at least every 500us or faster.

.... shall I continue

I would recommend you use the potentiometer in the servo.

Title: High Res Rotary Encoders


答:
Euler angle can be used to describe the orientation of the quadcopter relative to the local level surface and relative to a azimuth reference (typically true north). The roll ($\phi$) and pitch ($\theta$) angles describe the tilt of the quadrotor relative to the local vertical; i.e., relative to the gravity vector.  The yaw angle ($\psi$) describes the amount of rotation around the local vertical direction.

Typically, the roll and pitch angles are used to control the direction of the quadcopter's total thrust vector.  If they are zero, the thrust vector will point directly upwards, opposite to the direction of the gravity vector. Non-zero values of roll and pitch can be used to tilt the thrust vector so that the resultant horizontal component of the thrust vector can be used for translational motion.

It is generally not a good idea to use accelerometer measurements to calculate roll and pitch angles:

Accelerometers measure the specific force vector in body axes.  Three accelerometers aligned along the body axes will measure
\begin{eqnarray}
f_x &=& a_x-g\sin\theta \\
f_y &=& a_y+g\cos\theta\sin\phi \\
f_z &=& a_z+g\cos\theta\cos\phi
\end{eqnarray}
where $a_x$, $a_y$, and $a_z$ are components of the kinematic acceleration in body axes, and $g$ is the acceleration due to gravity.  If your Quadcopter is not accelerating, such as when it is stationary, the $a_x$, $a_y$, and $a_z$ components become zero. And only then can you use the accelerometer measurements to calculate the roll and pitch angles:
\begin{eqnarray}
\phi &=& \tan^{-1}\left(f_y/f_z\right) \\
\theta &=& \tan^{-1}\left(-f_x/\sqrt{f_y^2+f_z^2}\right)
\end{eqnarray}
This is a common method used to initialize the roll and pitch angles in a stationary IMU.  In flight, the accelerometers will also measure the components of its kinematic acceleration and the equations given above cannot be used to measure the roll and pitch angles.

Euler angles is one of three methods commonly used to describe the orientation of the quadcopter relative to the earth.  The other two are quaternions, and  direction cosines.  Each of these methods have advantages and disadvantages, and we can easily convert from one representation to another.  But, this a probably a topic for a next question.

Edit: Description of Conventional Euler Angles

First, we need to define two Cartesian frames with their origins located at the centre of mass of the quadrotor.  The body frame is fixed to the vehicle, with its $x$-axis parallel to the plane of the rotors pointing "forward", its $y$-axis is parallel to the plane of the rotors and perpendicular to the $x$-axis pointing to the right, and its $z$-axis perpendicular to the $xy$-plane pointing down. The origin of the local-level local north (LLLN) frame translates with the body frame, but always remain level with its $N$-axis pointing north, its $E$-axis pointing east, and its $D$-axis pointing down. The orientation of the quadrotor relative to the Earth is then described by the orientation of the body frame relative to the LLLN frame.  Euler angles are a set of three rotations taken about a single axis at a time in a specified order to generate the orientation of the body frame relative to the LLLN frame.  The so-called "conventional" Euler angles used in the aerospace industry are yaw ($\psi$), pitch ($\theta$), and roll ($\phi$) obtained from a particular sequence of rotations.

With the body frame initially aligned with the LLLN frame so that the $x,y,z$ axes are aligned with the $N,E,D$ axes and $\psi=\theta=\phi=0$, or stated differently, that the plane of the rotors is horizontal and the quadrotor's nose is pointing north, perform the following three rotations:

First, the body frame is rotated through the yaw angle in a positive sense around its $z$-axis.

Then the displaced body frame is rotated through the pitch angle in a positive sense around the displaced $y$-axis.

Finally, the displaced body frame is rotated through the roll angle in a positive sense around the displaced $x$-axis to obtain its final arbitrary orientation relative to the LLLN frame.

(Use a little model to visualize these three rotations.)

Note that these three rotations are not commutative (angle are not vectors) so that a different sequence of rotations will result in a different final orientation.

Title: Multicopter: What are Euler angles used for?

Body:
I hope you can help me and this is the right forum to ask.

In the process of building and programming my own Quadcopter, I encountered the term Euler angles. I took some time to understand them and then wondered why they are used in multicopter systems.

In my understanding Euler angles are used to rotate a point or vector in a coordinate system/ to express that rotation. I now wonder why i should use Euler angles to compute the orientation of the quadcopter as I could easily(at least i think so) compute the angles by themself, like
$$
\theta = arctan(y/z)
$$
$$
\phi = arctan(x/z)
$$
(just using accelerometer, where $x, y, z$ are axis accelerations and $\theta, \phi$ are pitch and roll, respectively. In the actual implementation I do not only use the accelerometer, this is just simplified to make the point clear).

Where exactly are Euler angles used?
Are they only used to convert desired trajectory in the earth frame to desired trajectory in the Body frame?

I would be very glad if anyone could point this out and explain the concept/ why and where they are used further.

To clarify: I do know that Euler angles encounter gimbal lock, that they are three rotations about $x, y, z$ axis and
how they generally work(I think). @Christo gave a very good explanation.

My question now is, why are they used? Isn't it counterproductive to apply the yaw rotation, then pitch, and then roll?

```<code>-Earth frame X,Y,Z
rotation about Z(psi)
->Frame 1 x', y', z'
rotation about y'(theta)
->Frame 2 x'', y'', z''
rotation about x''(phi)
->Body frame x, y, z
</code>```

and vice versa.

Why? I would just have said:

```<code>pitch = angles between X and x
roll = angle between Y and y
yaw = angle between x-y-projection of the magnetic field-vector and the starting vector(yaw is kinda different).
</code>```

(Notice the difference between uppercase and lowercase, look at the Earth-to-Body-Frame for notation).
Tied with this i wonder why the correct formula for pitch($\theta)$ should be $$\theta = \tan^{-1}\left(-f_x/\sqrt{f_y^2+f_z^2}\right)$$
I would have thought $$\theta = \tan^{-1}\left(-f_x/f_z\right)$$ suffices.
Maybe I have some flaw in my knowledge or a piece of the puzzle is still missing.

I hope this is understandable, if not feel free to ask. If this gets too crowded, I can always ask another question, just make me aware of it.

If anyone could explain how to use quaternions to express orientation I would be very thankful, but I can also just ask another time. I get the concept of Quaternions, just not how to use them to express orientation not rotation.


问:
How to detect when a stepper motor has stalled?
How can I detect when a stepper motor has stalled?

A google search led me to some people who say that
when the stepper motor stalls, the current spikes up,
which is easily detectable with a Hall sensor.
(Or, I suppose, by any of the other current sensors mentioned at
"How can I sense the motor's current?"
).

However, I measured the current through (one of the 4 wires of) my stepper motor,
and it's always within a few percent of 0.5 A, whether my stepper driver is holding one position, moving it normally (which in my application is very slowly), or the stepper driver thinks it is telling the stepper to move normally, but the motor has pegged out against the hard limit.
Measuring the current in the +12V power supply going to the stepper motor driver, also seemed to give a fairly constant current.
This may be because I turned down the current limit to that amount on my "chopper" stepper motor driver.

Am I missing some key detail in the "measure the current" approach?

A google search led me to some other people that measure the back-EMF (BEMF) in one coil of the stepper during the time the stepper driver is only driving the other coil.
But that only seems to distinguish between "a motor moving quickly" vs "a motor stopped", and doesn't seem to distinguish between my case of "a motor moving slowly" vs "a motor stopped".

Is there some way to apply the BEMF approach even in a system where I always drive the stepper slowly, and never spin it quickly?

I'm currently using a stepper driver board with the TI DRV8825 chip on it, and I hoped the "fault" pin would tell me when the stepper motor has stalled against my hard stop.
But it doesn't seem to be doing anything -- is it supposed to tell me about a stall, but I just have it wired up wrong?

Is there some other chip or drive technique that detects when the stepper has stalled out against the hard stop?

Is there some other technique for detecting a hard stall that I can "add on" to a system using an off-the-shelf stepper motor driver?

(Is there some other StackExchange site that is more appropriate for questions about motors and motor drivers?)

答:
One option is a stepper motor driver which uses sensorless stall system, such as the STMicroelectronics L6470 dSPIN: Fully integrated microstepping motor driver with motion engine and SPI.

Once calibrated it can detect a stall condition and raise the FLAG pin high to alert to the uC of the problem.