model two-link robot manipulator; simulate dynamics. in javascript

index.tsx
// Model Parameters
const m1 = 1; // mass of link 1
const m2 = 0.5; // mass of link 2
const l1 = 1; // length of link 1
const l2 = 0.5; // length of link 2
const g = 9.81; // gravity

// Simulation Parameters
const dt = 0.01; // time step
const totalTime = 10; // total simulation time

// Initial Conditions
let q1 = Math.PI / 4; // initial angle of link 1
let q2 = Math.PI / 6; // initial angle of link 2
let q1_dot = 0; // initial angular velocity of link 1
let q2_dot = 0; // initial angular velocity of link 2

// Simulation
for (let t = 0; t < totalTime; t += dt) {
    // Compute accelerations
    const q1_ddot = (m2 * l1 * q2_dot ** 2 * Math.sin(q2) + m2 * g * Math.cos(q2) * Math.sin(q2) - m2 * l2 * q2_dot ** 2 * Math.sin(q2) - (m1 + m2) * g * Math.sin(q1)) / (l1 * (m1 + m2 * (1 - Math.cos(q2) ** 2)));
    const q2_ddot = ((m1 + m2) * (l1 * q1_dot ** 2 * Math.sin(q2) - g * Math.sin(q1) + g * Math.sin(q2) * Math.cos(q1)) + q2_ddot * m2 * l2 * Math.cos(q2) * Math.sin(q2)) / (l2 * (m1 + m2 * (1 - Math.cos(q2) ** 2)));

    // Update velocities and positions
    q1_dot += q1_ddot * dt;
    q2_dot += q2_ddot * dt;
    q1 += q1_dot * dt;
    q2 += q2_dot * dt;

    // Display or store the results
    console.log(`t: ${t}, q1: ${q1}, q2: ${q2}`);
}
1263 chars
33 lines

gistlibby LogSnag