test

a4960.cpp

Committer:
tanabe2000
Date:
2018-03-01
Revision:
0:56b10b0c7db4

File content as of revision 0:56b10b0c7db4:

#include "a4960.h"

a4960::a4960() : spi(PB_15,PB_14,PB_13), _cs_pin(PB_1), _blink_pin(LED1), _PWM_pin(PA_11)
{
    PWM_freq = 20000.0;
    PWM_duty = 0.5;
    motor_started = true;

    _config[0] = 0b0000000000000000; // 50 us comm blank time, 2.4 us blank time, 200 ns deadtime
    _config[1] = 0b0010000000000000; // Vri = 100% Vref, Vdsth = 800mV
    _config[2] =  0b0100000000000000; // 35.6 us current control time
    _config[3] = 0b0110000000000000; // current limited, 50% current for hold, 18ms hold time
    _config[4] =   0b1000000000000000; // 0.8ms min comm time, 24 ms start comm time
    _config[5] =  0b1010000000000000; // 16.875deg phase adv, 100% ramp current, 0.4ms ramp rate
    _config[6] =  0b1100000000000000; // fault detection all on
    _config[7] = 0b1110000000000100;
    // auto BEMF hyst, 3.2us zx det window, no stop on fail, DIAG pin = fault, restart on loss of sync, brake off, forward, coast
    
    SPI_init();
}

void a4960::SPI_init()
{
    // initialize pins
    _cs_pin = 1;
    _blink_pin = 1;
    _PWM_pin.period(1/PWM_freq);
    _PWM_pin.write(PWM_duty);
    spi.format(16,3);
    spi.frequency(1000000);
    // initialize SPI connection
    //SPI.begin(P0_8, P0_9, P0_11);//SCK, MOSI, MOSI
    // set registers to default config
    for (int i = 0; i < 8; i++) {
        write_to_a4960(_config[i]);
    }
    // turn off pin to indicate initialization complete
    _blink_pin = 0;
}
void a4960::write_to_a4960(uint16_t msg)
{
    // split 16-bit message to a4960 into two 8-bit messages
    uint8_t ms_half;
    uint8_t ls_half;

    // ---- 1st message (bits 15 - 8)
    // 3 bit address
    // 12 bit message
    // shift message to get rid of 8 LSB on the end and OR
    // the write bit and the
    // 4 remaining bits into the first-half msg
    ms_half = 1 << 4 | (uint8_t)(msg>>8);
    // ---- 2nd message (bits 7 - 0)
    ls_half = (uint8_t)(msg);

    // pull to active low
    _cs_pin = 0;
    wait_us(200);

    // transfer the to messages halves, MSB first
    printf("test %d :%d\n\r",spi.write(ms_half<<8 | ls_half),(ms_half<<8 | ls_half));
    printf("test2 :%d",spi.write(0));

    // wait and pull CS line back to inactive high
    wait_us(200);
    _cs_pin = 1;
}

void a4960::write_run(void)
{
    write_to_a4960(_config[7] | 1);
}

void a4960::write_brake(void)
{
    write_to_a4960(_config[7]);
}

int a4960::read()
{   _cs_pin = 0;
    uint8_t h;
    wait_us(200);
    h = spi.write(0b1110000000000000);
    //h = spi.write(0);
    wait_us(200);
    _cs_pin = 1;
    return h;
}