1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#include <iostream> #include <cmath> #include <iomanip> const double PI = 3.141592653589793; const double DEG_TO_RAD = PI / 180.0; // Function to calculate the position of the end-effector void calculateEndEffectorPosition(double angle1, double angle2, double length1, double length2, double& x, double& y) { // Convert angles from degrees to radians double rad1 = angle1 * DEG_TO_RAD; double rad2 = angle2 * DEG_TO_RAD; // Calculate the position of the end-effector x = length1 * std::cos(rad1) + length2 * std::cos(rad1 + rad2); y = length1 * std::sin(rad1) + length2 * std::sin(rad1 + rad2); } int main() { // Arm segment lengths double length1 = 10.0; // Length of the first segment double length2 = 10.0; // Length of the second segment // Angles in degrees double angle1, angle2; std::cout << "Enter the angles for the robot arm (in degrees):\n"; std::cout << "Angle 1: "; std::cin >> angle1; std::cout << "Angle 2: "; std::cin >> angle2; double x, y; calculateEndEffectorPosition(angle1, angle2, length1, length2, x, y); std::cout << std::fixed << std::setprecision(2); std::cout << "End-Effector Position: (" << x << ", " << y << ")\n"; return 0; } |
Explanation
- Constants:
- PI: Mathematical constant π.
- DEG_TO_RAD: Conversion factor from degrees to radians.
- Function
calculateEndEffectorPosition(double angle1, double angle2, double length1, double length2, double& x, double& y)
:- Purpose: Calculates the position of the end-effector (tip) of the robot arm based on joint angles and segment lengths.
- Parameters:
angle1
,angle2
: Angles of the two joints in degrees.length1
,length2
: Lengths of the robot arm segments.x
,y
: Output parameters for the position of the end-effector.
- Implementation:
- Converts angles from degrees to radians.
- Computes the end-effector position using the forward kinematics equations for a 2-segment arm:
x = length1 * cos(angle1) + length2 * cos(angle1 + angle2)
y = length1 * sin(angle1) + length2 * sin(angle1 + angle2)
- Main Function:
- Segment Lengths: Defines lengths for the robot arm segments.
- Angle Input: Prompts the user to enter the angles for the two joints.
- Position Calculation: Calls
calculateEndEffectorPosition
to compute the end-effector position based on the input angles. - Result Display: Prints the position of the end-effector with two decimal places of precision.
Usage
- Robot Arm Simulation: Models the movement of a robot arm with two segments based on joint angles.
- Forward Kinematics: Demonstrates the calculation of the end-effector’s position using trigonometric functions.