Rihito Ohata / Mbed 2 deprecated 1-CAN-th2mot-mbed2-01_02

Dependencies:   mbed

main.cpp

Committer:
efLPdib4455
Date:
2020-09-07
Revision:
1:f06777cfcc8d
Parent:
0:f25ac5f8c95e
Child:
2:d28f9138ca4b

File content as of revision 1:f06777cfcc8d:

// mbed-os rev.171(mbed_os=2, very old)  (r020904,sige)
// 1--CAN-th2mot-mbed2-01_01  
//    packs the position(0-36000) command to the data_segment and 
//    dispatches the std_data_frame to the HT02(=GI8008) motor thru CAN1.
//    returns the received data_seg from the motor.
//    (the actual HT02 motor would send back the response data frame?)
//
//  th2mot(double th, unsigned int id)    (th=theta_in, id=CANid_in) 
//


// Ticker ticker;
DigitalOut led1(LED1);
DigitalOut led2(LED2);

CAN can1(p30, p29);     // (RX,TX)pins in this order
CAN can2( p9, p10);

char c_sent=0, c_read=0;   // counters of sent and read
char dseg[8]={0xFF, 0x01, 0x00, 0x64, 0x00, 0x80, 0x00, 0x00};  //data_segment

//  bytewise RW by the union Hoge, where char MUST be unsigned.
//  short=(signed 2 bytes integer). 
union Hoge{ unsigned char c[2]; uint16_t ii; };



// data segment specific to the HT02 motor
// [0]=host_addr(0xff=this_MCU, 0x01=motor_#01),
// [1]=func_code(01=pos.cmd), [2]=[4]=reserved(?)
// [3]=acce=*256[rpm/s],    [5]=target velo.[rpm] (of motor axis wo the gear, maybe)
// [6]=pos.lower byte,      [7]=pos.higher byte (of output axis, maybe)[0-36000]


void th2mot(double th, unsigned int id)
{
    Hoge hoge;
    printf("+(th2mot).. \n\r");
    //  truncates th*100. to uint16_t, which is then packed to dseg[6][7].
    //  e.g. th=12.345[deg], then hoge.ii=1234 (=0x04d2) and dseg[6]=0xd2, dseg[7]=0x04
    hoge.ii=(uint16_t)(th*100.);         dseg[6]=hoge.c[1]; dseg[7]=hoge.c[0];

    if( can1.write(CANMessage(1, dseg, 8, CANData, CANStandard)) ) {
        c_sent++;
        printf(" ++sent thru can1. c_sent=%d dseg[6][7]=%02x%02X \n\r", c_sent, dseg[6],dseg[7]);  }
    else
        printf(" ++failed can1.write sent=%d dseg[7]=%02x\n\r", c_sent, dseg[7]);
 
    led1 = !led1;
}   //  endof th2mot

int main()
{
    printf("+entered (testmain of th2mot)... \n\n\n\r");
    can1.frequency(1000000);    can2.frequency(1000000);  // CANbus=1Mbps
    double th; unsigned int id;
    th=12.3456;  id=1;
    th2mot(th, id);
    CANMessage msg;      // remote msg? what determines the size(msg)?
    while(1){
        printf("+(main) in while loop...  \n\r");
        if (can1.read(msg)) {   // org=can2
            c_read++;
            printf(" ++can2 c_read=%d, d[0]_read=%d\n", c_read, msg.data[0]);
            led2 = !led2;
        }
        else
            printf(" ++failed can1.read...  sent=%d\n", c_sent);

        wait(0.2);
    }   //  endof infinite_while_loop
}       //  endof main