Prototyp V2

Dependencies:   PM2_Libary

main.cpp

Committer:
lupomic
Date:
2022-04-27
Branch:
Lupo_2
Revision:
70:da5754e1514c
Parent:
55:8cb262e56efb
Child:
71:e740ef7c7813

File content as of revision 70:da5754e1514c:

#include "mbed.h"
#include "PM2_Libary.h"
#include <cmath>
#include <cstdint>
#include <cstdio>
#include "math.h"
//*******************************************************************************************************************************************************************
// Defined Variables in mm coming from Hardware-team. Need to be updated
const float wheel_diameter                = 30; // diameter of wheel with caterpillar to calculate mm per wheel turn (4)
const float arm_length                    = 118.5; // lenght of arm from pivotpoint to pivotpoint (3)
const float dist_arm_attach_distsensor    = 20; // distance between pivot point arm  on body to start distancesensor on top in horizontal (6)
const float dist_distsensors              = 200; // distance between the two distancesensors on top of Wall-E (9)
const float dist_arm_ground               = 51; // distance between pivotpoint arm and ground (5)
const float gripper_area_height           = 16 ; // Height of Grappler cutout to grapple Stair (8)
const float dist_grappleratt_grappler_uk  = 33; // distance between pivotpoint Grappler and bottom edge (?)

const float height_stairs                 = 100; // height to top of next stairstep in mm
//***********************************************************************************************************************************************************
// declaration of Input - Output pins

// user button on nucleo board
Timer user_button_timer;            // create Timer object which we use to check if user button was pressed for a certain time (robust against signal bouncing)
InterruptIn user_button(PC_13);     // create InterruptIn interface object to evaluate user button falling and rising edge (no blocking code in ISR)
void user_button_pressed_fcn();     // custom functions which gets executed when user button gets pressed and released, definition below
void user_button_released_fcn();

// Sharp GP2Y0A41SK0F, 4-40 cm IR Sensor
// define variable to store measurement from infrared distancesensor in mm
double ir_distance_mm_L = 0.0f;
double ir_distance_mm_R = 0.0f;  
double ir_distance_mm_Lookdown_B = 0.0f;
double ir_distance_mm_Lookdown_F = 0.0f; 

AnalogIn ir_analog_in_Distance_L(PC_2);  
AnalogIn ir_analog_in_Distance_R(PC_3);
AnalogIn ir_analog_in_Lookdown_B(PC_5);
AnalogIn ir_analog_in_Lookdown_F(PB_1);
// create AnalogIn object to read in infrared distance sensor, 0...3.3V are mapped to 0...1

// 78:1, 100:1, ... Metal Gearmotor 20Dx44L mm 12V CB
DigitalOut enable_motors(PB_15);    // create DigitalOut object to enable dc motors
float   pwm_period_s = 0.00005f;    // define pwm period time in seconds and create FastPWM objects to command dc motors

//motor pin declaration
FastPWM pwm_M_right (PB_13);    //motor pin decalaration for wheels right side         
FastPWM pwm_M_left  (PA_9);     //motor pin decalaration for wheels left side 
FastPWM pwm_M_arm   (PA_10);    //motor pin decalaration for arm 

//Encoder pin declaration
EncoderCounter  encoder_M_right (PA_6, PC_7); //encoder pin decalaration for wheels right side
EncoderCounter  encoder_M_left  (PB_6, PB_7); //encoder pin decalaration for wheels left side
EncoderCounter  encoder_M_arm   (PA_0, PA_1); //encoder pin decalaration for arm
//***********************************************************************************************************************************************************
// Hardware controll Setup and functions (motors and sensors)

// create SpeedController and PositionController objects, default parametrization is for 78.125:1 gear box
const float max_voltage               = 12.0f;     // define maximum voltage of battery packs, adjust this to 6.0f V if you only use one batterypack
const float counts_per_turn_wheels    = 20.0f * 78.125f;    // define counts per turn at gearbox end (counts/turn * gearratio) for wheels
const float counts_per_turn_arm       = 20.0f * 78.125f * 10.0f;    // define counts per turn at gearbox end (counts/turn * gearratio) for arm
const float kn                        = 180.0f / 12.0f;      // define motor constant in rpm per V
const float k_gear                    = 100.0f / 78.125f;   // define additional ratio in case you are using a dc motor with a different gear box, e.g. 100:1 (DC with 100:1 has 2'000 turns for 360°)
const float kp                        = 0.1f;     // define custom kp, this is the default speed controller gain for gear box 78.125:1

//motors for tracks
PositionController positionController_M_right(counts_per_turn_wheels * k_gear, kn / k_gear, kp * k_gear, max_voltage, pwm_M_right, encoder_M_right); // parameters adjusted to 100:1 gear, we need a different speed controller gain here
PositionController positionController_M_left(counts_per_turn_wheels * k_gear, kn / k_gear, kp * k_gear, max_voltage, pwm_M_left, encoder_M_left); // parameters adjusted to 100:1 gear, we need a different speed controller gain here
//Arm Motor
PositionController positionController_M_Arm(counts_per_turn_arm * k_gear, kn / k_gear, kp * k_gear, max_voltage, pwm_M_arm, encoder_M_arm); // parameters adjusted to 100:1 gear, we need a different speed controller gain here

// PositionController positionController_M3(counts_per_turn, kn, max_voltage, pwm_M3, encoder_M3); // default 78.125:1 gear with default contoller parameters
//PositionController positionController_M3(counts_per_turn * k_gear, kn / k_gear, kp * k_gear, max_voltage, pwm_M3, encoder_M3); // parameters adjusted to 100:1 gear, we need a different speed controller gain here
//***********************************************************************************************************************************************************
// logic functions for basic movement

//placeholder variables for prototype testing
const int   drive_stright_mm = 100; // placeholder for testing drives amount forward
const int   drive_back_mm = -100; // placeholder for testing drives amount backwards
int         ToNextFunction = 0;  // current state of the system (which function is beeing executed)
int         state=0;

// definition important variables
const float   pi = 2 * acos(0.0); // definiton of pi
const float   max_speed_rps_wheel = 0.6f;  // define maximum speed that the position controller is changig the speed for the wheels, has to be smaller or equal to kn * max_voltage
const float   max_speed_rps_arm = 0.3f; // define maximum speed that the position controller is changig the speed for the arm, has to be smaller or equal to kn * max_voltage
float         start_deg_arm = -asin((dist_arm_ground - dist_grappleratt_grappler_uk) / arm_length) * 180.0/pi ; //calculates the starting degree of the arm (gripper has to touch ground in frotn of Wall-E)
float         current_deg_arm = start_deg_arm; // saves the current degree the arm has.

// import functions from file mapping
extern double powerx(double base, double pow2);
extern double mapping (float adc_value_mV);

// calculates the deg which the arm has to take to reach a certain height (the input height has to be the height of OK Gripper area)
double calc_arm_deg_for_height(int height_mm)
{
    float deg_arm;
    if ((height_mm - dist_arm_ground - (dist_grappleratt_grappler_uk - gripper_area_height)) > arm_length) //check if height is reachable
    {
        printf("Error in calc_arm_deg_for_height: desired height is bigger than Wall-E arm lenght."); // error message when desired height is not reachable. 
    }
    else 
    {
        float height_arm = height_mm - dist_arm_ground - (dist_grappleratt_grappler_uk - gripper_area_height); // calculates the height which only the arm has to cover (- attachement height (arm to robot) etc.)
        deg_arm = asin(height_arm / arm_length) * 180.0/pi; // calculates the absolute degrees which the arm has to reach
    }
    return deg_arm;
}

//calculates the deg which the wheels have to turn in order to cover specified distance in mm
float wheel_dist_to_deg(int distance) // distance has to be in mm.
{
    float deg_wheel = distance * 360 /(wheel_diameter * pi);
    return deg_wheel;
}

// bring arm in starting position. Height of stairs.
int start_position()
{
    float diff;
    double deg_up_from_horizon = calc_arm_deg_for_height(height_stairs); //deg which arm motor has to turn to in order to grab stair. starting from horizontal position
    float deg = deg_up_from_horizon + start_deg_arm;
    if ((0.0 > deg) || (deg > 360.0))
    {
        printf("Error in start_position: degree is out of bound for Start Position."); // error when desired reaching point is out of reach.
        return 2;
    }
    positionController_M_Arm.setDesiredRotation(deg / 360.0, max_speed_rps_arm); // command to turn motor to desired deg.
    current_deg_arm = positionController_M_Arm.getRotation() * 360.0; //write new position to variable 
    diff = deg-current_deg_arm;
    if (diff<=0.3){
        return 1;
    }
    else {
        return NULL;}


}

//Drives forward into the next step 
//Prameter:distance in milimeter
int drive_straight(float distance)
{
    float diff_R;
    float diff_L;
    float deg_to_turn = wheel_dist_to_deg(distance);
    positionController_M_right.setDesiredRotation(deg_to_turn / 360.0, max_speed_rps_wheel);
    positionController_M_left.setDesiredRotation(deg_to_turn / 360.0, max_speed_rps_wheel);

 
    diff_R= deg_to_turn-(positionController_M_right.getRotation()*360);
    diff_L= deg_to_turn-(positionController_M_left.getRotation()*360);
    if (diff_R<=0.3&&diff_L<=0.3){
        return 1;
    }
    else {
    return 0;
    }
}

//only turns the arm until the robot is on the next step
int lift_up()
{
    float diff;
    float position_lift_end_deg = asin((-dist_arm_ground - (dist_grappleratt_grappler_uk-gripper_area_height)) / arm_length) - 90; // calculates the degree which has to be reached in order to get on top of next step
    
    positionController_M_Arm.setDesiredRotation(0, max_speed_rps_arm);
    return NULL;
}
//***********************************************************************************************************************************************************

int ground (float){
    return 1;
}
//simple check if there is an object in proximity
//returns 0 if there is NO object present
//returns 1 if there is an object present
//returns 2 if the distance isn't in the expected range

uint8_t StepDetection(double distance){
    double d_valueMM = distance;
    if(d_valueMM >= 4)  return 0;
    if(d_valueMM < 4)  return 1;
    if(d_valueMM < 0 || d_valueMM > 100 ) return 2;
    else    return 2;
}
//Function which checks if sensors and motors have been wired correctly and the expectet results will happen. otherwise Wall-E will show with armmovement.
int check_start()
{

    return NULL;
}

// while loop gets executed every main_task_period_ms milliseconds
int main_task_period_ms = 30;   // define main task period time in ms e.g. 30 ms -> main task runns ~33,33 times per second
Timer main_task_timer;          // create Timer object which we use to run the main task every main task period time in ms
//***********************************************************************************************************************************************************

int main(void)
{
    // attach button fall and rise functions to user button object
    user_button.fall(&user_button_pressed_fcn);



    while (true)
    {
        enable_motors = 1;

        
        switch (ToNextFunction) 
        {

            case 1: 
            start_position();
            printf("Case 1: Position ARM (rot): %3.3f\n",positionController_M_Arm.getRotation());
            if (state==1){
                    ToNextFunction += 1;
            }
            break;

            case 2:
            state=StepDetection(ir_analog_in_Distance_L);
            if (state==1){
                    ToNextFunction += 1;
            }

            case 3: 
            state=drive_straight(drive_stright_mm);
            printf("Case 2: Position Right(rot): %3.3f;    Position Left (rot): %3.3f\n",
            positionController_M_right.getRotation(),positionController_M_left.getRotation());
            if (state==1){
                    ToNextFunction += 1;
            }
            break;

            case 4: 
            state=lift_up();
            printf("Case 3: Position ARM (rot): %3.3f\n",positionController_M_Arm.getRotation());
            if (state==1){
                    ToNextFunction += 1;
            }
            break;

            case 5: 
            state=drive_straight(drive_back_mm);
            printf("Case 4: Position Right(rot): %3.3f;    Position Left (rot): %3.3f\n",
            positionController_M_right.getRotation(),positionController_M_left.getRotation());
            if (state==1){
                    ToNextFunction += 1;
            }
            break;

            case 6: 
            state=lift_up();
            printf("Case 5: Position ARM (rot): %3.3f\n",positionController_M_Arm.getRotation());
             if (state==1){
                    ToNextFunction = 1;
            }
            break;  

            default:  ;
        } 
    }
       // read timer and make the main thread sleep for the remaining time span (non blocking)
        int main_task_elapsed_time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(main_task_timer.elapsed_time()).count();
        thread_sleep_for(main_task_period_ms - main_task_elapsed_time_ms);
        return 0;
}


void user_button_pressed_fcn()
{
    user_button_timer.start();
    user_button_timer.reset();
}

void user_button_released_fcn() 
{
    // read timer and toggle do_execute_main_task if the button was pressed longer than the below specified time
    int user_button_elapsed_time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(user_button_timer.elapsed_time()).count();
    user_button_timer.stop();
    if (user_button_elapsed_time_ms > 200) 
    {
       ToNextFunction = 1;
    }
}