NYP

Dependencies:   LSM6DSL

Fork of NYP_humanoid by Junjie Wang

servo.cpp

Committer:
ha731548874
Date:
2018-04-30
Revision:
1:cde16b5e604d
Child:
2:7d574b1ab3cd

File content as of revision 1:cde16b5e604d:

#include "mbed.h"
#include "rtos.h"

DigitalOut l1(LED1);
DigitalOut l2(LED2);
DigitalOut l3(LED3);
DigitalOut l4(LED4);
RawSerial motor(PC_4,PC_5);
unsigned char tx_buffer[3];
unsigned char tx_buffer_ptr = 0;
unsigned char tx_buffer_full = false;
unsigned char rx_buffer[6];
unsigned char rx_buffer_ptr = 0;
unsigned char rx_buffer_full = false;
signed short int motorcp[] = {8500,8500};
unsigned short int Position;
int MotorID;
void Tx_interrupt();
void Rx_interrupt();

void motor_update(unsigned char Id, unsigned short int Position)
{
    unsigned char id,lo,hi;
    id=0x80|Id;
    hi=(Position>>7)&0x007F;
    lo=Position&0x007F;
    NVIC_DisableIRQ(USART3_IRQn);
    tx_buffer[0] = id;
    tx_buffer[1] = hi;
    tx_buffer[2] = lo;
    NVIC_EnableIRQ(USART3_IRQn);
}
void SERVO_init() 
{
    for(MotorID=0;MotorID<=1;MotorID++)
    {
        motor_update(MotorID,motorcp[MotorID]);
        wait_us(900);
    }
}
void SERVO_task() 
{
    motor.format(8,Serial::Even,1);
    motor.baud(115200);
    rx_buffer_ptr = 0;
    rx_buffer_full = false;
    motor.attach(&Rx_interrupt, Serial::RxIrq);
    motor.attach(&Tx_interrupt, Serial::TxIrq);
    NVIC_EnableIRQ(USART3_IRQn);
    while(1)
    {
        motorcp[0]=7500;
        motorcp[1]=7500;
        Thread::wait(1000);
        motorcp[0]=8500;
        motorcp[1]=8500;
        Thread::wait(1000);
    }
}

void Tx_interrupt() 
{
    while(motor.writeable())
    {    
        motor.putc(tx_buffer[tx_buffer_ptr]);
        tx_buffer_ptr++;
        if(tx_buffer_ptr==3)
              tx_buffer_ptr = 0;
    }
    return;
}
void Rx_interrupt()
{
    while(motor.readable())
    {
        rx_buffer[rx_buffer_ptr] = motor.getc();
        rx_buffer_ptr++;
        if(rx_buffer_ptr==6)
        {
            rx_buffer_full = true;
            rx_buffer_ptr=0;
        }
    }
}