2017年6月16日 星期五

CC2540 software implement I2C (mpu6050 for example)

We all know that cc2540 doesn't have hardware I2C pin. In this article, I  :

1.use to GPIO pins to simulate I2C SDA and SCL.

2.read the electrics potential as I2C data.

3.print out the data by UART

*For how to use UART in CC254x,
please look for it on previous article here:
http://blog.csdn.net/feilusia/article/details/47431659

STEP 0. set MPU6050 on CC2541
I define
SCL = P1.5
SDA= P1.6



STEP 1 .
I made a project file "SimpleBLEPeripheral_uart_mpu6050_file".

add these files in :
..\BLE-CC254x-1.3.2\Projects\ble\SimpleBLEPeripheral_uart_mpu6050_file\Source
and add in IAR.

1. sw_iic.c
2. sw_iic.h
3. mpu6050.c
4. mpu6050.h





































and here is the source code:

sw_iic.h
#ifndef _SW_IIC_H_
#define _SW_IIC_H_

/*power by Agatha Kuan 
2017.06.09*/

#define uchar unsigned char   
#define uint unsigned int     


#define SCL P1_5
#define SDA P1_6

#define HIGH                (1)
#define LOW                 (0)


extern void SDA_OUT(void);
extern void SDA_OUT(void);
extern void SDA_IN(void);
extern void SDA_HIGH(void);
extern void SDA_LOW(void);
extern void SCL_HIGH(void);
extern void SCL_LOW(void);

extern uint SDA_READ(void);

extern void IIC_DELAY(void);
extern void delay_1ms(void);

extern void IIC_Init(void);
extern void Signal_Start(void);
extern void Signal_Stop(void);
extern void Write_Byte(uchar wdata);
extern uchar Read_Byte();
extern void Write_Add(uchar add,uchar wdata,uchar comd);
extern uchar Read_Add(uchar add,uchar comd);

#endif


sw_iic.c
/*power by Agatha Kuan 
2017.06.09*/

#include "IIC.h"
#include "sw_iic.h"
#include <iocc2540.h>

#define  uchar unsigned  char 
#define  uint  unsigned  int


void SDA_OUT(void)
{
 P1SEL &= ~(1 << 6);
 P1DIR |= (1 << 6);
}


void SCL_OUT(void)
{
 P1SEL &= ~(1 << 5);
 P1DIR |= (1 << 5);
}


void SDA_IN(void)
{
 P1SEL &= ~(1 << 6);
 P1DIR &=~(1 << 1);
}


void SDA_HIGH(void)
{
 SDA = HIGH;
}


void SDA_LOW(void)
{
 SDA = LOW;
}


void SCL_HIGH(void)
{
 SCL = HIGH;
}


void SCL_LOW(void)
{
 SCL = LOW;
}


uint SDA_READ(void)
{
  uint i = 0;
  i = SDA;
  
  if (LOW == SDA)
    i = 0;
  else if (HIGH == SDA)
    i = 1;
  else
    return 0xFF;
  
  return i;
      
}


void delay_1ms(void)    
{
    uchar a,b,c;    
    for(c=4;c>0;c--)
    {
        //for(b=142;b>0;b--)
        {
            for(a=2;a>0;a--)
            {
            }
        }
    }
}


void IIC_DELAY(void)
{
 delay_1ms();
}


void IIC_Init(void)
{
    SDA_OUT();
    SCL_OUT();
    
    SDA_HIGH();
    IIC_DELAY;
    SCL_HIGH();
    IIC_DELAY();
}


void Signal_Start(void)
{
   SDA_OUT();      
    SDA_HIGH();   
    SCL_HIGH();
    IIC_DELAY();
    SDA_LOW();
    IIC_DELAY();  
    SCL_LOW();
}
void Signal_Stop(void)
{
    SDA_OUT(); 
    
    SDA_LOW();
    IIC_DELAY();
    SCL_HIGH();
    IIC_DELAY();
    SDA_HIGH();
    IIC_DELAY(); 
}


void Respons(void) /*wait_ack*/
{        
    SDA_IN();
    
    SCL_HIGH();
    IIC_DELAY();
    SCL_LOW();
    IIC_DELAY();
 
#if (0)  /*this part is to match ACK or nACK. I don't really know the implement*/
    uint i = 0;
    
    if(i>=300)
    {
      delay_1ms();
      i++;
    }
#endif   
    
}


void Write_Byte(uchar wdata)
{
    uchar i,mdata;

    SDA_OUT();
    SCL_OUT();
    
    mdata = wdata;
    for(i=0;i<8;i++)
    {        
        SCL_LOW();
        IIC_DELAY();
        
        if(mdata & 0x80)
        {
          SDA_HIGH();
        }
        else
        {
          SDA_LOW();
        }
        IIC_DELAY();
        SCL_HIGH();
        IIC_DELAY();  
        mdata <<= 1;
    }
    SCL_LOW();
    IIC_DELAY();
    SCL_HIGH();
    IIC_DELAY();
}


uchar Read_Byte()
{
    uchar i,rdata = 0;

    SDA_OUT();
    SCL_OUT();
    
    SCL_LOW();
    IIC_DELAY();
    SCL_HIGH();
        
    for(i=0;i<8;i++)
    {
        SCL_HIGH();
        IIC_DELAY();
        rdata = (rdata<<1)|SDA_READ();
        SCL_LOW();
        IIC_DELAY();
    }
    return rdata;
}


void Write_Add(uchar add,uchar wdata,uchar comd)
{
    Signal_Start(); 
    Write_Byte(comd);
    Respons();      
    Write_Byte(add);
    Respons();      
    Write_Byte(wdata);
    Respons();      
    Signal_Stop();  
}


uchar Read_Add(uchar add,uchar comd)/*read at specific addr in i2c*/
{
    uchar tdata;
    Signal_Start();     
    Write_Byte(comd);
    Respons();          
    Write_Byte(add);
    Respons();          
    Signal_Start();     
    Write_Byte(comd|0x01);
    Respons();          
    tdata = Read_Byte();
    Signal_Stop();      
    return tdata;       
}


mpu6050.h
#ifndef _MPU6050_H
#define _MPU6050_H

#define PORT_USED        0

#define MPU6050_ADDRESS_AD0_LOW     0x68 // address pin low (GND), default for InvenSense evaluation board
#define MPU6050_ADDRESS_AD0_HIGH    0x69 // address pin high (VCC)
#define MPU6050_DEFAULT_ADDRESS     (MPU6050_ADDRESS_AD0_LOW<<1)
#define MPU6050_RA_XG_OFFS_TC       0x00 //[7] PWR_MODE, [6:1] XG_OFFS_TC, [0] OTP_BNK_VLD
#define MPU6050_RA_YG_OFFS_TC       0x01 //[7] PWR_MODE, [6:1] YG_OFFS_TC, [0] OTP_BNK_VLD
#define MPU6050_RA_ZG_OFFS_TC       0x02 //[7] PWR_MODE, [6:1] ZG_OFFS_TC, [0] OTP_BNK_VLD
#define MPU6050_RA_X_FINE_GAIN      0x03 //[7:0] X_FINE_GAIN
#define MPU6050_RA_Y_FINE_GAIN      0x04 //[7:0] Y_FINE_GAIN
#define MPU6050_RA_Z_FINE_GAIN      0x05 //[7:0] Z_FINE_GAIN
#define MPU6050_RA_XA_OFFS_H        0x06 //[15:0] XA_OFFS
#define MPU6050_RA_XA_OFFS_L_TC     0x07
#define MPU6050_RA_YA_OFFS_H        0x08 //[15:0] YA_OFFS
#define MPU6050_RA_YA_OFFS_L_TC     0x09
#define MPU6050_RA_ZA_OFFS_H        0x0A //[15:0] ZA_OFFS
#define MPU6050_RA_ZA_OFFS_L_TC     0x0B
#define MPU6050_RA_XG_OFFS_USRH     0x13 //[15:0] XG_OFFS_USR
#define MPU6050_RA_XG_OFFS_USRL     0x14
#define MPU6050_RA_YG_OFFS_USRH     0x15 //[15:0] YG_OFFS_USR
#define MPU6050_RA_YG_OFFS_USRL     0x16
#define MPU6050_RA_ZG_OFFS_USRH     0x17 //[15:0] ZG_OFFS_USR
#define MPU6050_RA_ZG_OFFS_USRL     0x18
#define MPU6050_RA_SMPLRT_DIV       0x19
#define MPU6050_RA_CONFIG           0x1A
#define MPU6050_RA_GYRO_CONFIG      0x1B
#define MPU6050_RA_ACCEL_CONFIG     0x1C
#define MPU6050_RA_FF_THR           0x1D
#define MPU6050_RA_FF_DUR           0x1E
#define MPU6050_RA_MOT_THR          0x1F
#define MPU6050_RA_MOT_DUR          0x20
#define MPU6050_RA_ZRMOT_THR        0x21
#define MPU6050_RA_ZRMOT_DUR        0x22
#define MPU6050_RA_FIFO_EN          0x23
#define MPU6050_RA_I2C_MST_CTRL     0x24
#define MPU6050_RA_I2C_SLV0_ADDR    0x25
#define MPU6050_RA_I2C_SLV0_REG     0x26
#define MPU6050_RA_I2C_SLV0_CTRL    0x27
#define MPU6050_RA_I2C_SLV1_ADDR    0x28
#define MPU6050_RA_I2C_SLV1_REG     0x29
#define MPU6050_RA_I2C_SLV1_CTRL    0x2A
#define MPU6050_RA_I2C_SLV2_ADDR    0x2B
#define MPU6050_RA_I2C_SLV2_REG     0x2C
#define MPU6050_RA_I2C_SLV2_CTRL    0x2D
#define MPU6050_RA_I2C_SLV3_ADDR    0x2E
#define MPU6050_RA_I2C_SLV3_REG     0x2F
#define MPU6050_RA_I2C_SLV3_CTRL    0x30
#define MPU6050_RA_I2C_SLV4_ADDR    0x31
#define MPU6050_RA_I2C_SLV4_REG     0x32
#define MPU6050_RA_I2C_SLV4_DO      0x33
#define MPU6050_RA_I2C_SLV4_CTRL    0x34
#define MPU6050_RA_I2C_SLV4_DI      0x35
#define MPU6050_RA_I2C_MST_STATUS   0x36
#define MPU6050_RA_INT_PIN_CFG      0x37
#define MPU6050_RA_INT_ENABLE       0x38
#define MPU6050_RA_DMP_INT_STATUS   0x39
#define MPU6050_RA_INT_STATUS       0x3A
#define MPU6050_RA_ACCEL_XOUT_H     0x3B
#define MPU6050_RA_ACCEL_XOUT_L     0x3C
#define MPU6050_RA_ACCEL_YOUT_H     0x3D
#define MPU6050_RA_ACCEL_YOUT_L     0x3E
#define MPU6050_RA_ACCEL_ZOUT_H     0x3F
#define MPU6050_RA_ACCEL_ZOUT_L     0x40
#define MPU6050_RA_TEMP_OUT_H       0x41
#define MPU6050_RA_TEMP_OUT_L       0x42
#define MPU6050_RA_GYRO_XOUT_H      0x43
#define MPU6050_RA_GYRO_XOUT_L      0x44
#define MPU6050_RA_GYRO_YOUT_H      0x45
#define MPU6050_RA_GYRO_YOUT_L      0x46
#define MPU6050_RA_GYRO_ZOUT_H      0x47
#define MPU6050_RA_GYRO_ZOUT_L      0x48
#define MPU6050_RA_EXT_SENS_DATA_00 0x49
#define MPU6050_RA_EXT_SENS_DATA_01 0x4A
#define MPU6050_RA_EXT_SENS_DATA_02 0x4B
#define MPU6050_RA_EXT_SENS_DATA_03 0x4C
#define MPU6050_RA_EXT_SENS_DATA_04 0x4D
#define MPU6050_RA_EXT_SENS_DATA_05 0x4E
#define MPU6050_RA_EXT_SENS_DATA_06 0x4F
#define MPU6050_RA_EXT_SENS_DATA_07 0x50
#define MPU6050_RA_EXT_SENS_DATA_08 0x51
#define MPU6050_RA_EXT_SENS_DATA_09 0x52
#define MPU6050_RA_EXT_SENS_DATA_10 0x53
#define MPU6050_RA_EXT_SENS_DATA_11 0x54
#define MPU6050_RA_EXT_SENS_DATA_12 0x55
#define MPU6050_RA_EXT_SENS_DATA_13 0x56
#define MPU6050_RA_EXT_SENS_DATA_14 0x57
#define MPU6050_RA_EXT_SENS_DATA_15 0x58
#define MPU6050_RA_EXT_SENS_DATA_16 0x59
#define MPU6050_RA_EXT_SENS_DATA_17 0x5A
#define MPU6050_RA_EXT_SENS_DATA_18 0x5B
#define MPU6050_RA_EXT_SENS_DATA_19 0x5C
#define MPU6050_RA_EXT_SENS_DATA_20 0x5D
#define MPU6050_RA_EXT_SENS_DATA_21 0x5E
#define MPU6050_RA_EXT_SENS_DATA_22 0x5F
#define MPU6050_RA_EXT_SENS_DATA_23 0x60
#define MPU6050_RA_MOT_DETECT_STATUS    0x61
#define MPU6050_RA_I2C_SLV0_DO      0x63
#define MPU6050_RA_I2C_SLV1_DO      0x64
#define MPU6050_RA_I2C_SLV2_DO      0x65
#define MPU6050_RA_I2C_SLV3_DO      0x66
#define MPU6050_RA_I2C_MST_DELAY_CTRL   0x67
#define MPU6050_RA_SIGNAL_PATH_RESET    0x68
#define MPU6050_RA_MOT_DETECT_CTRL      0x69
#define MPU6050_RA_USER_CTRL        0x6A
#define MPU6050_RA_PWR_MGMT_1       0x6B
#define MPU6050_RA_PWR_MGMT_2       0x6C
#define MPU6050_RA_BANK_SEL         0x6D
#define MPU6050_RA_MEM_START_ADDR   0x6E
#define MPU6050_RA_MEM_R_W          0x6F
#define MPU6050_RA_DMP_CFG_1        0x70
#define MPU6050_RA_DMP_CFG_2        0x71
#define MPU6050_RA_FIFO_COUNTH      0x72
#define MPU6050_RA_FIFO_COUNTL      0x73
#define MPU6050_RA_FIFO_R_W         0x74
#define MPU6050_RA_WHO_AM_I         0x75

#define MPU6050_TC_PWR_MODE_BIT     7
#define MPU6050_TC_OFFSET_BIT       6
#define MPU6050_TC_OFFSET_LENGTH    6
#define MPU6050_TC_OTP_BNK_VLD_BIT  0

#define MPU6050_VDDIO_LEVEL_VLOGIC  0
#define MPU6050_VDDIO_LEVEL_VDD     1

#define MPU6050_CFG_EXT_SYNC_SET_BIT    5
#define MPU6050_CFG_EXT_SYNC_SET_LENGTH 3
#define MPU6050_CFG_DLPF_CFG_BIT    2
#define MPU6050_CFG_DLPF_CFG_LENGTH 3

#define MPU6050_EXT_SYNC_DISABLED       0x0
#define MPU6050_EXT_SYNC_TEMP_OUT_L     0x1
#define MPU6050_EXT_SYNC_GYRO_XOUT_L    0x2
#define MPU6050_EXT_SYNC_GYRO_YOUT_L    0x3
#define MPU6050_EXT_SYNC_GYRO_ZOUT_L    0x4
#define MPU6050_EXT_SYNC_ACCEL_XOUT_L   0x5
#define MPU6050_EXT_SYNC_ACCEL_YOUT_L   0x6
#define MPU6050_EXT_SYNC_ACCEL_ZOUT_L   0x7

#define MPU6050_DLPF_BW_256         0x00
#define MPU6050_DLPF_BW_188         0x01
#define MPU6050_DLPF_BW_98          0x02
#define MPU6050_DLPF_BW_42          0x03
#define MPU6050_DLPF_BW_20          0x04
#define MPU6050_DLPF_BW_10          0x05
#define MPU6050_DLPF_BW_5           0x06

#define MPU6050_GCONFIG_FS_SEL_BIT      4
#define MPU6050_GCONFIG_FS_SEL_LENGTH   2

#define MPU6050_GYRO_FS_250         0x00
#define MPU6050_GYRO_FS_500         0x01
#define MPU6050_GYRO_FS_1000        0x02
#define MPU6050_GYRO_FS_2000        0x03

#define MPU6050_ACONFIG_XA_ST_BIT           7
#define MPU6050_ACONFIG_YA_ST_BIT           6
#define MPU6050_ACONFIG_ZA_ST_BIT           5
#define MPU6050_ACONFIG_AFS_SEL_BIT         4
#define MPU6050_ACONFIG_AFS_SEL_LENGTH      2
#define MPU6050_ACONFIG_ACCEL_HPF_BIT       2
#define MPU6050_ACONFIG_ACCEL_HPF_LENGTH    3

#define MPU6050_ACCEL_FS_2          0x00
#define MPU6050_ACCEL_FS_4          0x01
#define MPU6050_ACCEL_FS_8          0x02
#define MPU6050_ACCEL_FS_16         0x03

#define MPU6050_DHPF_RESET          0x00
#define MPU6050_DHPF_5              0x01
#define MPU6050_DHPF_2P5            0x02
#define MPU6050_DHPF_1P25           0x03
#define MPU6050_DHPF_0P63           0x04
#define MPU6050_DHPF_HOLD           0x07

#define MPU6050_TEMP_FIFO_EN_BIT    7
#define MPU6050_XG_FIFO_EN_BIT      6
#define MPU6050_YG_FIFO_EN_BIT      5
#define MPU6050_ZG_FIFO_EN_BIT      4
#define MPU6050_ACCEL_FIFO_EN_BIT   3
#define MPU6050_SLV2_FIFO_EN_BIT    2
#define MPU6050_SLV1_FIFO_EN_BIT    1
#define MPU6050_SLV0_FIFO_EN_BIT    0

#define MPU6050_MULT_MST_EN_BIT     7
#define MPU6050_WAIT_FOR_ES_BIT     6
#define MPU6050_SLV_3_FIFO_EN_BIT   5
#define MPU6050_I2C_MST_P_NSR_BIT   4
#define MPU6050_I2C_MST_CLK_BIT     3
#define MPU6050_I2C_MST_CLK_LENGTH  4

#define MPU6050_CLOCK_DIV_348       0x0
#define MPU6050_CLOCK_DIV_333       0x1
#define MPU6050_CLOCK_DIV_320       0x2
#define MPU6050_CLOCK_DIV_308       0x3
#define MPU6050_CLOCK_DIV_296       0x4
#define MPU6050_CLOCK_DIV_286       0x5
#define MPU6050_CLOCK_DIV_276       0x6
#define MPU6050_CLOCK_DIV_267       0x7
#define MPU6050_CLOCK_DIV_258       0x8
#define MPU6050_CLOCK_DIV_500       0x9
#define MPU6050_CLOCK_DIV_471       0xA
#define MPU6050_CLOCK_DIV_444       0xB
#define MPU6050_CLOCK_DIV_421       0xC
#define MPU6050_CLOCK_DIV_400       0xD
#define MPU6050_CLOCK_DIV_381       0xE
#define MPU6050_CLOCK_DIV_364       0xF

#define MPU6050_I2C_SLV_RW_BIT      7
#define MPU6050_I2C_SLV_ADDR_BIT    6
#define MPU6050_I2C_SLV_ADDR_LENGTH 7
#define MPU6050_I2C_SLV_EN_BIT      7
#define MPU6050_I2C_SLV_BYTE_SW_BIT 6
#define MPU6050_I2C_SLV_REG_DIS_BIT 5
#define MPU6050_I2C_SLV_GRP_BIT     4
#define MPU6050_I2C_SLV_LEN_BIT     3
#define MPU6050_I2C_SLV_LEN_LENGTH  4

#define MPU6050_I2C_SLV4_RW_BIT         7
#define MPU6050_I2C_SLV4_ADDR_BIT       6
#define MPU6050_I2C_SLV4_ADDR_LENGTH    7
#define MPU6050_I2C_SLV4_EN_BIT         7
#define MPU6050_I2C_SLV4_INT_EN_BIT     6
#define MPU6050_I2C_SLV4_REG_DIS_BIT    5
#define MPU6050_I2C_SLV4_MST_DLY_BIT    4
#define MPU6050_I2C_SLV4_MST_DLY_LENGTH 5

#define MPU6050_MST_PASS_THROUGH_BIT    7
#define MPU6050_MST_I2C_SLV4_DONE_BIT   6
#define MPU6050_MST_I2C_LOST_ARB_BIT    5
#define MPU6050_MST_I2C_SLV4_NACK_BIT   4
#define MPU6050_MST_I2C_SLV3_NACK_BIT   3
#define MPU6050_MST_I2C_SLV2_NACK_BIT   2
#define MPU6050_MST_I2C_SLV1_NACK_BIT   1
#define MPU6050_MST_I2C_SLV0_NACK_BIT   0

#define MPU6050_INTCFG_INT_LEVEL_BIT        7
#define MPU6050_INTCFG_INT_OPEN_BIT         6
#define MPU6050_INTCFG_LATCH_INT_EN_BIT     5
#define MPU6050_INTCFG_INT_RD_CLEAR_BIT     4
#define MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT  3
#define MPU6050_INTCFG_FSYNC_INT_EN_BIT     2
#define MPU6050_INTCFG_I2C_BYPASS_EN_BIT    1
#define MPU6050_INTCFG_CLKOUT_EN_BIT        0

#define MPU6050_INTMODE_ACTIVEHIGH  0x00
#define MPU6050_INTMODE_ACTIVELOW   0x01

#define MPU6050_INTDRV_PUSHPULL     0x00
#define MPU6050_INTDRV_OPENDRAIN    0x01

#define MPU6050_INTLATCH_50USPULSE  0x00
#define MPU6050_INTLATCH_WAITCLEAR  0x01

#define MPU6050_INTCLEAR_STATUSREAD 0x00
#define MPU6050_INTCLEAR_ANYREAD    0x01

#define MPU6050_INTERRUPT_FF_BIT            7
#define MPU6050_INTERRUPT_MOT_BIT           6
#define MPU6050_INTERRUPT_ZMOT_BIT          5
#define MPU6050_INTERRUPT_FIFO_OFLOW_BIT    4
#define MPU6050_INTERRUPT_I2C_MST_INT_BIT   3
#define MPU6050_INTERRUPT_PLL_RDY_INT_BIT   2
#define MPU6050_INTERRUPT_DMP_INT_BIT       1
#define MPU6050_INTERRUPT_DATA_RDY_BIT      0

// TODO: Need to work on DMP related things
#define MPU6050_DMPINT_5_BIT            5
#define MPU6050_DMPINT_4_BIT            4
#define MPU6050_DMPINT_3_BIT            3
#define MPU6050_DMPINT_2_BIT            2
#define MPU6050_DMPINT_1_BIT            1
#define MPU6050_DMPINT_0_BIT            0

#define MPU6050_MOTION_MOT_XNEG_BIT     7
#define MPU6050_MOTION_MOT_XPOS_BIT     6
#define MPU6050_MOTION_MOT_YNEG_BIT     5
#define MPU6050_MOTION_MOT_YPOS_BIT     4
#define MPU6050_MOTION_MOT_ZNEG_BIT     3
#define MPU6050_MOTION_MOT_ZPOS_BIT     2
#define MPU6050_MOTION_MOT_ZRMOT_BIT    0

#define MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT   7
#define MPU6050_DELAYCTRL_I2C_SLV4_DLY_EN_BIT   4
#define MPU6050_DELAYCTRL_I2C_SLV3_DLY_EN_BIT   3
#define MPU6050_DELAYCTRL_I2C_SLV2_DLY_EN_BIT   2
#define MPU6050_DELAYCTRL_I2C_SLV1_DLY_EN_BIT   1
#define MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT   0

#define MPU6050_PATHRESET_GYRO_RESET_BIT    2
#define MPU6050_PATHRESET_ACCEL_RESET_BIT   1
#define MPU6050_PATHRESET_TEMP_RESET_BIT    0

#define MPU6050_DETECT_ACCEL_ON_DELAY_BIT       5
#define MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH    2
#define MPU6050_DETECT_FF_COUNT_BIT             3
#define MPU6050_DETECT_FF_COUNT_LENGTH          2
#define MPU6050_DETECT_MOT_COUNT_BIT            1
#define MPU6050_DETECT_MOT_COUNT_LENGTH         2

#define MPU6050_DETECT_DECREMENT_RESET  0x0
#define MPU6050_DETECT_DECREMENT_1      0x1
#define MPU6050_DETECT_DECREMENT_2      0x2
#define MPU6050_DETECT_DECREMENT_4      0x3

#define MPU6050_USERCTRL_DMP_EN_BIT             7
#define MPU6050_USERCTRL_FIFO_EN_BIT            6
#define MPU6050_USERCTRL_I2C_MST_EN_BIT         5
#define MPU6050_USERCTRL_I2C_IF_DIS_BIT         4
#define MPU6050_USERCTRL_DMP_RESET_BIT          3
#define MPU6050_USERCTRL_FIFO_RESET_BIT         2
#define MPU6050_USERCTRL_I2C_MST_RESET_BIT      1
#define MPU6050_USERCTRL_SIG_COND_RESET_BIT     0

#define MPU6050_PWR1_DEVICE_RESET_BIT   7
#define MPU6050_PWR1_SLEEP_BIT          6
#define MPU6050_PWR1_CYCLE_BIT          5
#define MPU6050_PWR1_TEMP_DIS_BIT       3
#define MPU6050_PWR1_CLKSEL_BIT         2
#define MPU6050_PWR1_CLKSEL_LENGTH      3

#define MPU6050_CLOCK_INTERNAL          0x00
#define MPU6050_CLOCK_PLL_XGYRO         0x01
#define MPU6050_CLOCK_PLL_YGYRO         0x02
#define MPU6050_CLOCK_PLL_ZGYRO         0x03
#define MPU6050_CLOCK_PLL_EXT32K        0x04
#define MPU6050_CLOCK_PLL_EXT19M        0x05
#define MPU6050_CLOCK_KEEP_RESET        0x07

#define MPU6050_PWR2_LP_WAKE_CTRL_BIT       7
#define MPU6050_PWR2_LP_WAKE_CTRL_LENGTH    2
#define MPU6050_PWR2_STBY_XA_BIT            5
#define MPU6050_PWR2_STBY_YA_BIT            4
#define MPU6050_PWR2_STBY_ZA_BIT            3
#define MPU6050_PWR2_STBY_XG_BIT            2
#define MPU6050_PWR2_STBY_YG_BIT            1
#define MPU6050_PWR2_STBY_ZG_BIT            0

#define MPU6050_WAKE_FREQ_1P25      0x0
#define MPU6050_WAKE_FREQ_2P5       0x1
#define MPU6050_WAKE_FREQ_5         0x2
#define MPU6050_WAKE_FREQ_10        0x3

#define MPU6050_BANKSEL_PRFTCH_EN_BIT       6
#define MPU6050_BANKSEL_CFG_USER_BANK_BIT   5
#define MPU6050_BANKSEL_MEM_SEL_BIT         4
#define MPU6050_BANKSEL_MEM_SEL_LENGTH      5

#define MPU6050_WHO_AM_I_BIT        6
#define MPU6050_WHO_AM_I_LENGTH     6

#define MPU6050_DMP_MEMORY_BANKS        8
#define MPU6050_DMP_MEMORY_BANK_SIZE    256
#define MPU6050_DMP_MEMORY_CHUNK_SIZE   16

#define uint8_t unsigned char   
#define int16_t int             
#define uint32_t unsigned long  


void MPU6050_Read(unsigned char SlaveAddress,unsigned char REG_Address,unsigned char readNum);

void MPU6050_WriteBits(uint8_t slaveAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data);
void MPU6050_WriteBit(uint8_t slaveAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data);
void MPU6050_ReadBits(uint8_t slaveAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data);

void MPU6050_Initialize(void);              
uint8_t MPU6050_GetDeviceID(void);       

void MPU6050_GetRawAccelGyro(int16_t* ax, int16_t* ay, int16_t* az, \
    int16_t* temperature, int16_t* gx, int16_t* gy, int16_t* gz);


unsigned char MPU6050_Read_1BYTE(unsigned char SlaveAddress,unsigned char REG_Address);
typedef signed   char   int8;
typedef unsigned char   uint8;


//***********************************************************************************
// Function prototypes
void accInit(void);
void accStop(void);
void accWriteReg(uint8 reg, uint8 val);
void accReadReg(uint8 reg, uint8 *pVal);
void accReadAcc(int8 *pXVal, int8 *pYVal, int8 *pZVal);
void accReadAccGro(int8 *pXAcc, int8 *pYAcc, int8 *pZAcc, int8 *pXGro, int8 *pYGro, int8 *pZGro);




#endif

mpu6050.c
#include <ioCC2540.h>
#include "IIC.h"
#include "MPU6050.h"

#define I2C_PORT_NUM        1
#define BUFSIZE             14  


volatile uint8_t I2CMasterBuffer[I2C_PORT_NUM][BUFSIZE];
volatile uint8_t I2CSlaveBuffer[I2C_PORT_NUM][BUFSIZE];
volatile uint32_t I2CReadLength[I2C_PORT_NUM];
volatile uint32_t I2CWriteLength[I2C_PORT_NUM];

void DelayI2C(uint32_t m)
{
  uint32_t i;
  
  for(; m != 0; m--)    
       for (i=0; i<5; i++);
}

void MPU6050_Read(unsigned char SlaveAddress,unsigned char REG_Address,unsigned char readNum)
{
    unsigned char i; 
    for(i = 0; i<readNum; i++)
    {        
        I2CSlaveBuffer[PORT_USED][i] = Read_Add(REG_Address + i, SlaveAddress);
    }
}

unsigned char MPU6050_Read_1BYTE(unsigned char SlaveAddress,unsigned char REG_Address)
{
    return Read_Add(REG_Address, SlaveAddress);
}


void MPU6050_Write(unsigned char SlaveAddress,unsigned char REG_Address,unsigned char REG_data) 
{
    Write_Add(REG_Address, REG_data, SlaveAddress);
}

void MPU6050_WriteBits(uint8_t slaveAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t data) 
{
    //      010 value to write
    // 76543210 bit numbers
    //    xxx   args: bitStart=4, length=3
    // 00011100 mask byte
    // 10101111 original value (sample)
    // 10100011 original & ~mask
    // 10101011 masked | value
    uint8_t tmp;
    uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
    MPU6050_Read(slaveAddr, regAddr, 1);
    tmp = I2CSlaveBuffer[PORT_USED][0];  
//    uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
    data <<= (bitStart - length + 1); // shift data into correct position
    data &= mask;   // zero all non-important bits in data
    tmp &= ~(mask); // zero all important bits in existing byte
    tmp |= data;    // combine data with existing byte
    MPU6050_Write(slaveAddr,regAddr,tmp);   
}

void MPU6050_WriteBit(uint8_t slaveAddr, uint8_t regAddr, uint8_t bitNum, uint8_t data) 
{
    uint8_t tmp;
    MPU6050_Read(slaveAddr, regAddr, 1);
    tmp = I2CSlaveBuffer[PORT_USED][0];  
    tmp = (data != 0) ? (tmp | (1 << bitNum)) : (tmp & ~(1 << bitNum));
    MPU6050_Write(slaveAddr,regAddr,tmp); 
}

void MPU6050_ReadBits(uint8_t slaveAddr, uint8_t regAddr, uint8_t bitStart, uint8_t length, uint8_t *data) 
{
    // 01101001 read byte
    // 76543210 bit numbers
    //    xxx   args: bitStart=4, length=3
    //    010   masked
    //   -> 010 shifted

#if 1 
    uint8_t tmp;
    uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
    MPU6050_Read(slaveAddr, regAddr, 1);
    tmp = I2CSlaveBuffer[PORT_USED][0]; 
//    uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
    tmp &= mask;
    tmp >>= (bitStart - length + 1);
    *data = tmp;
#else
    uint8_t tmp;
    MPU6050_Read(slaveAddr, regAddr, 1);
    tmp = I2CSlaveBuffer[PORT_USED][0]; 
    *data = tmp;
#endif
}

void MPU6050_Initialize(void)
{
    MPU6050_WriteBits(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_PWR_MGMT_1, 
        MPU6050_PWR1_CLKSEL_BIT, MPU6050_PWR1_CLKSEL_LENGTH, MPU6050_CLOCK_PLL_XGYRO);
    MPU6050_WriteBits(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_GYRO_CONFIG,
        MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH, MPU6050_GYRO_FS_250);
    MPU6050_WriteBits(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_ACCEL_CONFIG, 
        MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH, MPU6050_ACCEL_FS_2);
    MPU6050_WriteBit(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_SLEEP_BIT, 0);//(DISABLE); 
}

uint8_t MPU6050_GetDeviceID()
{
    uint8_t tmp;

    MPU6050_ReadBits(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_WHO_AM_I, \
        MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH, &tmp);
    
    return tmp<<(MPU6050_WHO_AM_I_BIT-MPU6050_WHO_AM_I_LENGTH+1);  // 注意这里的移位  amomcu
}


void MPU6050_GetRawAccelGyro(int16_t* ax, int16_t* ay, int16_t* az, int16_t* temperature, int16_t* gx, int16_t* gy, int16_t* gz) 
{
//    u8 tmpBuffer[14]; 
    //int i;
    MPU6050_Read(MPU6050_DEFAULT_ADDRESS, MPU6050_RA_ACCEL_XOUT_H, 14); 

    /* Get acceleration */
 //   for(i=0; i<3; i++) 
//      AccelGyro[i]=((int16_t)((uint16_t)I2CSlaveBuffer[PORT_USED][2*i] << 8) + I2CSlaveBuffer[PORT_USED][2*i+1]);
   /* Get Angular rate */
//    for(i=4; i<7; i++)
//      AccelGyro[i-1]=((int16_t)((uint16_t)I2CSlaveBuffer[PORT_USED][2*i] << 8) + I2CSlaveBuffer[PORT_USED][2*i+1]); 
    *ax = (((int16_t)I2CSlaveBuffer[PORT_USED][0]) << 8) | ((int16_t)I2CSlaveBuffer[PORT_USED][1]); 
    *ay = (((int16_t)I2CSlaveBuffer[PORT_USED][2]) << 8) | ((int16_t)I2CSlaveBuffer[PORT_USED][3]); 
    *az = (((int16_t)I2CSlaveBuffer[PORT_USED][4]) << 8) | ((int16_t)I2CSlaveBuffer[PORT_USED][5]); 

    // 温度
    *temperature = (((int16_t)I2CSlaveBuffer[PORT_USED][6]) << 8) | ((int16_t)I2CSlaveBuffer[PORT_USED][7]); 
    
    *gx = (((int16_t)I2CSlaveBuffer[PORT_USED][8]) << 8) | ((int16_t)I2CSlaveBuffer[PORT_USED][9]); 
    *gy = (((int16_t)I2CSlaveBuffer[PORT_USED][10]) << 8) | ((int16_t)I2CSlaveBuffer[PORT_USED][11]); 
    *gz = (((int16_t)I2CSlaveBuffer[PORT_USED][12]) << 8) | ((int16_t)I2CSlaveBuffer[PORT_USED][13]); 
}


#if 1
uint8_t bIfConnected = 0;
void accInit(void)
{
    unsigned char tempV = 0;
    IIC_Init();                     

    tempV = MPU6050_GetDeviceID();
    if(tempV == MPU6050_ADDRESS_AD0_LOW)          
    {           
        bIfConnected = 1;
    }
    else
    {
        bIfConnected = 0;
    }
    
    if(bIfConnected)
    {        
        MPU6050_Initialize();        
    }
}
void accStop(void)
{

}
void accWriteReg(uint8 reg, uint8 val)
{
    if(bIfConnected)
    {
        MPU6050_Write(0x68<<1, reg, val);
    }
}
void accReadReg(uint8 reg, uint8 *pVal)
{
    if(bIfConnected)
    {
        *pVal = MPU6050_Read_1BYTE(0x68<<1, reg);
    }
}
void accReadAcc(int8 *pXVal, int8 *pYVal, int8 *pZVal)
{
    int16_t ax, ay, az;
    int16_t gx, gy, gz;    
    int16_t temperature;
    if(bIfConnected)
    {         
        MPU6050_GetRawAccelGyro(&ax, &ay, &az, &temperature, &gx, &gy, &gz);

        *pXVal = ax/100;
        *pYVal = ay/100;
        *pZVal = az/100;
    }
}

void accReadAccGro(int8 *pXAcc, int8 *pYAcc, int8 *pZAcc, int8 *pXGro, int8 *pYGro, int8 *pZGro)
{
    int16_t ax, ay, az;
    int16_t gx, gy, gz;    
    int16_t temperature;
    if(bIfConnected)
    {               
        MPU6050_GetRawAccelGyro(&ax, &ay, &az, &temperature, &gx, &gy, &gz);

        *pXAcc = ax/100;
        *pYAcc = ay/100;
        *pZAcc = az/100;

        *pXGro = gx/100;
        *pYGro = gy/100;
        *pZGro = gz/100;        
    }
}

#endif

STEP 2  Add test code in simpleBLEPeripheral.c

about line 90
#include "mpu6050.h"


about line 241
void simpleBLE_Delay_1ms(int times);
void mpu6050_gpio_iic_Test();


about line 479  in SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
uint16 SimpleBLEPeripheral_ProcessEvent( uint8 task_id, uint16 events )
{

  VOID task_id; // OSAL required parameter that isn't used in this function

  if ( events & SYS_EVENT_MSG )
  {
    uint8 *pMsg;

    if ( (pMsg = osal_msg_receive( simpleBLEPeripheral_TaskID )) != NULL )
    {
      simpleBLEPeripheral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );

      // Release the OSAL message
      VOID osal_msg_deallocate( pMsg );
    }

    // return unprocessed events
    return (events ^ SYS_EVENT_MSG);
  }

  if ( events & SBP_START_DEVICE_EVT )
  {
    // Start the Device
    VOID GAPRole_StartDevice( &simpleBLEPeripheral_PeripheralCBs );

    // Start Bond Manager
    VOID GAPBondMgr_Register( &simpleBLEPeripheral_BondMgrCBs );
    
    /*agatha:just for test mpu6050 iic 6/16*/
    mpu6050_gpio_iic_Test();
    
    return ( events ^ SBP_START_DEVICE_EVT );
  }  
  
  if ( events & SBP_PERIODIC_EVT )
  {
    // Restart timer
    if ( SBP_PERIODIC_EVT_PERIOD )
    {
      osal_start_timerEx( simpleBLEPeripheral_TaskID, SBP_PERIODIC_EVT, SBP_PERIODIC_EVT_PERIOD );
    }
    // Perform periodic application task       
    performPeriodicTask();
    
    return (events ^ SBP_PERIODIC_EVT);
  }

#if defined ( PLUS_BROADCASTER )
  if ( events & SBP_ADV_IN_CONNECTION_EVT )
  {
    uint8 turnOnAdv = TRUE;
    // Turn on advertising while in a connection
    GAPRole_SetParameter( GAPROLE_ADVERT_ENABLED, sizeof( uint8 ), &turnOnAdv );

    return (events ^ SBP_ADV_IN_CONNECTION_EVT);
  }
#endif // PLUS_BROADCASTER

  // Discard unknown events
  return 0;
}

about line 873
void simpleBLE_Delay_1ms(int times)
{
  while(times--)
  {
      int i=0;
      for(i=1500;i>0;i--)
      {
       asm("nop");
      }
  }
}



about line 887
void mpu6050_gpio_iic_Test()
{
    while(1)
    {
        uint16 numBytes;
        char pktBuffer[128];
        int8 XAcc, YAcc, ZAcc;
        int8 XGro, YGro, ZGro;

        accInit();  
        
        accReadAccGro(&XAcc, &YAcc, &ZAcc, &XGro, &YGro, &ZGro);
        sprintf((char *)pktBuffer, "%d,%d,%d,%d,%d,%d\r\n", XAcc, YAcc, ZAcc, XGro, YGro, ZGro);
        
        UartSendString(strTemp, strlen(strTemp));
        
        simpleBLE_Delay_1ms(200);        
  }



Then press "rebuild all" --> "download and debug " --> "Go" on IAR

the result will be like :



















Notes:

1. noticed insufficiency
my software implement I2C is not comprehensive. I didn't implement some functions like
I2C as External interrupt to wake up SoC ...etc.

2. software implement still need some API of CC2540, and that is why I include <iocc2540.h>.

However, software GPIO pins simulate I2C can be used on any chips basically, so actually you can replace those API to those of your platform in order to make the sw_iic.c/h to be cross-platform.








2017年5月30日 星期二

nRF52 in SDK12 : activate the UART function

There are few articles about nRF52 SDK12, and UART print is a basic function for developers.

This example is modified from ble_app_template
located in : nRF5_SDK_12.2.0_f012efa\examples\ble_peripheral\ble_app_template

Board:nRF52832/ SDK12/s132

STEP 0. project config
I create a project folder "ble_app_uart_porting_file"
located in : nRF5_SDK_12.2.0_f012efa\examples\ble_peripheral\ble_app_uart_porting_file

add  these files into nrf_library
"app_uart_fifo.c"
"app_fifo.c"
"retarget.c"
located in nRF5_SDK_12.2.0_f012efa\components\libraries\uart

and remove "app_uart.c"

next  include path to project option

STEP 1. modify "sdk_config"
I suggest first open sdk_config.h

add these about line  3004
// <h> nRF_Libraries 
//==========================================================
// <q> APP_FIFO_ENABLED  - app_fifo - Software FIFO implementation
 

#ifndef APP_FIFO_ENABLED
#define APP_FIFO_ENABLED 1
#endif

then add these about line 3080
// <e> APP_UART_ENABLED - app_uart - UART driver
//==========================================================
#ifndef APP_UART_ENABLED
#define APP_UART_ENABLED 1
#define APP_UART_DRIVER_INSTANCE 0
#endif

then add these about line 3506

// <q> RETARGET_ENABLED  - retarget - Retargeting stdio functions
 

#ifndef RETARGET_ENABLED
#define RETARGET_ENABLED 1
#endif

and then, go to  Configuration wizard
open nrf_libraries and check :

 then open nrf_drivers and check


for your UART configuration, I suggest to select in configuration wizard - nrf_drivers
in this example, I select as




































but if you prefer to add code , please add in sdk_config.h Text Editor
about line  2724

// <e> UART_ENABLED - nrf_drv_uart - UART/UARTE peripheral driver
//==========================================================
#ifndef UART_ENABLED
#define UART_ENABLED 1
#endif
#if  UART_ENABLED
// <o> UART_DEFAULT_CONFIG_HWFC  - Hardware Flow Control
 
// <0=> Disabled 
// <1=> Enabled 

#ifndef UART_DEFAULT_CONFIG_HWFC
#define UART_DEFAULT_CONFIG_HWFC 0
#endif

// <o> UART_DEFAULT_CONFIG_PARITY  - Parity
 
// <0=> Excluded 
// <14=> Included 

#ifndef UART_DEFAULT_CONFIG_PARITY
#define UART_DEFAULT_CONFIG_PARITY 0
#endif

// <o> UART_DEFAULT_CONFIG_BAUDRATE  - Default Baudrate
 
// <323584=> 1200 baud 
// <643072=> 2400 baud 
// <1290240=> 4800 baud 
// <2576384=> 9600 baud 
// <3862528=> 14400 baud 
// <5152768=> 19200 baud 
// <7716864=> 28800 baud 
// <10289152=> 38400 baud 
// <15400960=> 57600 baud 
// <20615168=> 76800 baud 
// <30801920=> 115200 baud 
// <61865984=> 230400 baud 
// <67108864=> 250000 baud 
// <121634816=> 460800 baud 
// <251658240=> 921600 baud 
// <268435456=> 57600 baud 

#ifndef UART_DEFAULT_CONFIG_BAUDRATE
#define UART_DEFAULT_CONFIG_BAUDRATE 30801920
#endif

// <o> UART_DEFAULT_CONFIG_IRQ_PRIORITY  - Interrupt priority
 

// <i> Priorities 0,2 (nRF51) and 0,1,4,5 (nRF52) are reserved for SoftDevice
// <0=> 0 (highest) 
// <1=> 1 
// <2=> 2 
// <3=> 3 
// <4=> 4 
// <5=> 5 
// <6=> 6 
// <7=> 7 

#ifndef UART_DEFAULT_CONFIG_IRQ_PRIORITY
#define UART_DEFAULT_CONFIG_IRQ_PRIORITY 7
#endif

// <q> UART_EASY_DMA_SUPPORT  - Driver supporting EasyDMA
 

#ifndef UART_EASY_DMA_SUPPORT
#define UART_EASY_DMA_SUPPORT 1
#endif

// <q> UART_LEGACY_SUPPORT  - Driver supporting Legacy mode
 

#ifndef UART_LEGACY_SUPPORT
#define UART_LEGACY_SUPPORT 1
#endif

// <e> UART0_ENABLED - Enable UART0 instance
//==========================================================
#ifndef UART0_ENABLED
#define UART0_ENABLED 1
#endif
#if  UART0_ENABLED
// <q> UART0_CONFIG_USE_EASY_DMA  - Default setting for using EasyDMA
 

#ifndef UART0_CONFIG_USE_EASY_DMA
#define UART0_CONFIG_USE_EASY_DMA 1
#endif

#endif //UART0_ENABLED
// </e>

// <e> UART_CONFIG_LOG_ENABLED - Enables logging in the module.
//==========================================================
#ifndef UART_CONFIG_LOG_ENABLED
#define UART_CONFIG_LOG_ENABLED 0
#endif
#if  UART_CONFIG_LOG_ENABLED
// <o> UART_CONFIG_LOG_LEVEL  - Default Severity level
 
// <0=> Off 
// <1=> Error 
// <2=> Warning 
// <3=> Info 
// <4=> Debug 

#ifndef UART_CONFIG_LOG_LEVEL
#define UART_CONFIG_LOG_LEVEL 3
#endif

// <o> UART_CONFIG_INFO_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 

#ifndef UART_CONFIG_INFO_COLOR
#define UART_CONFIG_INFO_COLOR 0
#endif

// <o> UART_CONFIG_DEBUG_COLOR  - ANSI escape code prefix.
 
// <0=> Default 
// <1=> Black 
// <2=> Red 
// <3=> Green 
// <4=> Yellow 
// <5=> Blue 
// <6=> Magenta 
// <7=> Cyan 
// <8=> White 

#ifndef UART_CONFIG_DEBUG_COLOR
#define UART_CONFIG_DEBUG_COLOR 0
#endif

#endif //UART_CONFIG_LOG_ENABLED
// </e>

#endif //UART_ENABLED
// </e>

STEP 2.  add code in main.c


#include "app_uart.h"

#define UART_TX_BUF_SIZE                256                                         
#define UART_RX_BUF_SIZE                256
#define UART_MAX_DATA_LEN  (20)   


void uart_event_handle(app_uart_evt_t * p_event)
{

    static uint8_t data_array[UART_MAX_DATA_LEN]; 
    static uint8_t index = 0;
    uint32_t       err_code;

    switch (p_event->evt_type)
    {
        case APP_UART_DATA_READY:
            break;

        case APP_UART_COMMUNICATION_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_communication);
            break;

        case APP_UART_FIFO_ERROR:
            APP_ERROR_HANDLER(p_event->data.error_code);
            break;

        default:
            break;
    }
}


static void uart_init(void)
{
    uint32_t                     err_code;
    const app_uart_comm_params_t comm_params =
    {
        RX_PIN_NUMBER,
        TX_PIN_NUMBER,
        RTS_PIN_NUMBER,
        CTS_PIN_NUMBER,
        APP_UART_FLOW_CONTROL_DISABLED,
        false,
        UART_BAUDRATE_BAUDRATE_Baud115200
    };

    APP_UART_FIFO_INIT( &comm_params,
                       UART_RX_BUF_SIZE,
                       UART_TX_BUF_SIZE,
                       uart_event_handle,
                       APP_IRQ_PRIORITY_LOWEST,
                       err_code);
    APP_ERROR_CHECK(err_code);
}


int main(void)
{
    uint32_t err_code;
    bool     erase_bonds;

    // Initialize.  
    APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_OP_QUEUE_SIZE, false);
    uart_init();   
    printf("system start\r\n");
 
    err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);

    //timers_init();
    buttons_leds_init(&erase_bonds);
    ble_stack_init();
    peer_manager_init(erase_bonds);
    if (erase_bonds == true)
    {
        NRF_LOG_INFO("Bonds erased!\r\n");
    }
    gap_params_init();
    advertising_init();
    services_init();
    conn_params_init();

    // Start execution.
    NRF_LOG_INFO("Template started\r\n");
    application_timers_start();
    err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
    APP_ERROR_CHECK(err_code);
    

    // Enter main loop.
    for (;;)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            power_manage();
        }
    }
}

and the result print by UART will be like :
(I used SSCOM. a UART print console on PC )




























NOTE:
1. in SDK12, the developer must assign UART, PWM,WDT...etc in sdk_config.h
otherwise, even they include all the paths and files needed, they still can not open UART.


reference:
https://devzone.nordicsemi.com/question/107836/undefined-symbol-problem-app_uart_get/

http://gaiger-programming.blogspot.tw/2016/12/nrf51-make-printf-works-well.html?m=1

2017年5月28日 星期日

nRF52 fstorage (1):a simple example

There are few examples about SDK12, and that is the reason why I wrote this.

the pstorage function(persistent storage)  of nRF5X has been changed as fstorage in SDK12.
the APIs have been changed. So I write the example for demonstrating how to adopt those .

Board :nRF52832/SDK12/s132

STEP 0.
I create the project file "ble_app_fstoarge_test_file" in example\ble_peripheral
And the example is coopied from  nRF5_SDK_12.2.0_f012efa\examples\ble_peripheral\ble_app_template


project config:
please include all the files in this folder
nRF5_SDK_12.2.0_f012efa\components\libraries\fds

include
"fds.h"
"fds.c"
"fstorage.h"
"fds.c"

and do not forget to paste the path to project option



STEP 1.
the line begins about 3124 in "sdk_config.h" should be modified as  following for fds purpose.
("sdk_config.h" is located in nRF5_SDK_12.2.0_f012efa\examples\ble_peripheral\ble_app_fstorage_test_file\pca10040\s132\config)

add these codes to test fstorage

// <e> FDS_ENABLED - fds - Flash data storage module
//==========================================================
#ifndef FDS_ENABLED
#define FDS_ENABLED 1
#endif
#if  FDS_ENABLED
// <o> FDS_OP_QUEUE_SIZE - Size of the internal queue. 
#ifndef FDS_OP_QUEUE_SIZE
#define FDS_OP_QUEUE_SIZE 4
#endif

// <o> FDS_CHUNK_QUEUE_SIZE - Determines how many @ref fds_record_chunk_t structures can be buffered at any time. 
#ifndef FDS_CHUNK_QUEUE_SIZE
#define FDS_CHUNK_QUEUE_SIZE 8
#endif

// <o> FDS_MAX_USERS - Maximum number of callbacks that can be registered. 
#ifndef FDS_MAX_USERS
#define FDS_MAX_USERS 8
#endif

// <o> FDS_VIRTUAL_PAGES - Number of virtual flash pages to use. 
// <i> One of the virtual pages is reserved by the system for garbage collection.
// <i> Therefore, the minimum is two virtual pages: one page to store data and
// <i> one page to be used by the system for garbage collection. The total amount
// <i> of flash memory that is used by FDS amounts to @ref FDS_VIRTUAL_PAGES
// <i> @ref FDS_VIRTUAL_PAGE_SIZE * 4 bytes.

#ifndef FDS_VIRTUAL_PAGES
#define FDS_VIRTUAL_PAGES 3
#endif

// <o> FDS_VIRTUAL_PAGE_SIZE  - The size of a virtual page of flash memory, expressed in number of 4-byte words.
 

// <i> By default, a virtual page is the same size as a physical page.
// <i> The size of a virtual page must be a multiple of the size of a physical page.
// <1024=> 1024 
// <2048=> 2048 

#ifndef FDS_VIRTUAL_PAGE_SIZE
#define FDS_VIRTUAL_PAGE_SIZE 1024
#endif

#endif //FDS_ENABLED
// </e>

// <e> FSTORAGE_ENABLED - fstorage - Flash storage module
//==========================================================
#ifndef FSTORAGE_ENABLED
#define FSTORAGE_ENABLED 1
#endif
#if  FSTORAGE_ENABLED
// <o> FS_QUEUE_SIZE - Configures the size of the internal queue. 
// <i> Increase this if there are many users, or if it is likely that many
// <i> operation will be queued at once without waiting for the previous operations
// <i> to complete. In general, increase the queue size if you frequently receive
// <i> @ref FS_ERR_QUEUE_FULL errors when calling @ref fs_store or @ref fs_erase.

#ifndef FS_QUEUE_SIZE
#define FS_QUEUE_SIZE 4
#endif

// <o> FS_OP_MAX_RETRIES - Number attempts to execute an operation if the SoftDevice fails. 
// <i> Increase this value if events return the @ref FS_ERR_OPERATION_TIMEOUT
// <i> error often. The SoftDevice may fail to schedule flash access due to high BLE activity.

#ifndef FS_OP_MAX_RETRIES
#define FS_OP_MAX_RETRIES 3
#endif

// <o> FS_MAX_WRITE_SIZE_WORDS - Maximum number of words to be written to flash in a single operation. 
// <i> Tweaking this value can increase the chances of the SoftDevice being
// <i> able to fit flash operations in between radio activity. This value is bound by the
// <i> maximum number of words which the SoftDevice can write to flash in a single call to
// <i> @ref sd_flash_write, which is 256 words for nRF51 ICs and 1024 words for nRF52 ICs.

#ifndef FS_MAX_WRITE_SIZE_WORDS
#define FS_MAX_WRITE_SIZE_WORDS 1024
#endif

#endif //FSTORAGE_ENABLED
// </e>

the "sdk_config.h" is first time added in SDK12, almost every function must config in this file.


STEP 2.
example code:
add these functions to test fstorage
about  line 706

/*the definition for fstorage*/
static volatile uint8_t write_flag=0;
static uint8_t fs_callback_flag; 
#define NUM_PAGES 4
#define PAGE_SIZE_WORDS 256

static uint32_t data;
static uint32_t flash_data[4];

/**@brief Function for the Power manager.
 */
static void power_manage(void)
{
    uint32_t err_code = sd_app_evt_wait();

    APP_ERROR_CHECK(err_code);
}


static void fs_evt_handler(fs_evt_t const * const evt, fs_ret_t result)
{
    if (result != FS_SUCCESS)
    {
        bsp_indication_set(BSP_INDICATE_FATAL_ERROR);
    }
  else
  {
    NRF_LOG_INFO("fstorage command successfully completed\n\r");    
    fs_callback_flag = 0;
  }
}


static void fstorage_test(void)
{
 PRINTF("fstorage_test\r\n");
 
 FS_REGISTER_CFG(fs_config_t fs_config) =
 {
  .callback  = fs_evt_handler, // Function for event callbacks.
  .num_pages = NUM_PAGES,      // Number of physical flash pages required.
  .priority  = 0xFE            // Priority for flash usage.
 };

 fs_ret_t ret = fs_init();
 if (ret != FS_SUCCESS)
 {
  bsp_indication_set(BSP_INDICATE_FATAL_ERROR);
 }
  
 // Erase one page (256*4).
 NRF_LOG_INFO("Erasing a flash page at address 0x%X\r\n", (uint32_t)fs_config.p_start_addr);  
 
 fs_callback_flag = 1;
 ret = fs_erase(&fs_config, fs_config.p_start_addr, 1, NULL);
 if (ret != FS_SUCCESS)
 {
  bsp_indication_set(BSP_INDICATE_FATAL_ERROR);
 }
 while(fs_callback_flag == 1)  { power_manage(); }
 
 //Read the first 4 words of the page
 NRF_LOG_INFO("Data read from flash address 0x%X: \r\n", (uint32_t)fs_config.p_start_addr);  
  
 for(int i=0; i<4; i++)
 {
  flash_data[i] = *(fs_config.p_start_addr + i);
  NRF_LOG_INFO("%X \r\n", flash_data[i]);    
 } 
  
  /*agatha*/  
 NRF_LOG_INFO("from agatha\r\n"); 
 
 data = 0x19950225;
 NRF_LOG_INFO("Writing data 0x%X to address 0x%X\r\n", data, (uint32_t)fs_config.p_start_addr );
 
 fs_callback_flag = 1;
 ret = fs_store(&fs_config, fs_config.p_start_addr, &data, 1, NULL); 
 if (ret != FS_SUCCESS)
 {
  bsp_indication_set(BSP_INDICATE_FATAL_ERROR);
 }
 while(fs_callback_flag == 1)  { power_manage(); }
 
 //Read the first 4 words of the page
 NRF_LOG_INFO("Data read from flash address 0x%X: \r\n", (uint32_t)fs_config.p_start_addr);  
    
 flash_data[2] = *(fs_config.p_start_addr);
 NRF_LOG_INFO("%X ", flash_data[2]);     
}


/**@brief Function for application main entry.
 */
int main(void)
{
 PRINTF("DEVICE START \r\n");
 
 uint32_t err_code;
    bool     erase_bonds;

    // Initialize.
    err_code = NRF_LOG_INIT(NULL);
    APP_ERROR_CHECK(err_code);

    
    ble_stack_init();
 
    peer_manager_init(erase_bonds);
    if (erase_bonds == true)
    {
        NRF_LOG_INFO("Bonds erased!\r\n");
    }
    gap_params_init();
    advertising_init();
 
    services_init();
    conn_params_init();
 
  // Start execution.
    NRF_LOG_INFO("Proximity Start!\r\n");
    advertising_start();
  
  /*the example function of  fstorage*/
  PRINTF("start fstorage test\r\n");
  fstorage_test();
  

    // Enter main loop.
    for (;;)
    {
        if (NRF_LOG_PROCESS() == false)
        {
            power_manage();
        }   
    }
}


these code demo how to :
initialize fstorage ->clear the code page  -> write at specific address (0x79000) ->read the address

and I define
the number of code pages and page_size should be a multiple of 4.

/*the definition for fstorage*/
static volatile uint8_t write_flag=0;
static uint8_t fs_callback_flag; 
#define NUM_PAGES 4
#define PAGE_SIZE_WORDS 256

static uint32_t data;
static uint32_t flash_data[4];

and the result print in segger_RTT will be like this :


NOTES:

1.this article only shows  the most basic way to use fstorage, and how to prevent the conflict of
power_manage and  fstorage. 

2.I register the space and clear/ write at the same time, so the space for data to store is limited .

3.I did not define the start code page , so the fstorage will start at 0x79000 (in default)
but the start point is able to be assigned by yourself.

try to assign start point in 
fs_config.p_start_addr

your could change the address 0x79000 as 0x78000 to observe the storaging address be entailed changed.

4.KNOWN insuffience :I have not implement how to use fstorage in interrupt (press button, UART...etc). Maybe I should write an example  relate to fstorage and interrupt ?

2017年4月19日 星期三

nRF5X: prevent bootloader from erased after programming

Board : nRF52832_xxac / SDK11/s132  (but not only these have the problem)

After add DFU service in application, we have to program bootloader. In nRFgo , the IROM must be look like this :


but after you compile and program your application again, and open nRFgo next time , you might see :
and that means your bootloader is erased by application.

That's because a mistake of project setting of application



this is project setting of SDK11/ble_app_template
the start point + size = 0x1c000 + 0x64000 = 0x7f000 = the end point.
So, the application is end at 0x7f000 in default.

But in the project setting of SDK 11/bootloader/ dual_bank_dfu_s132
It shows that bootloader start at 0x7a000.

So, if you program application again , it is necessary to erase bootloader for application space.


And the solution I suggest you is :


change application size  0x62000 ->0x5e000


0x1c000+ 0x5d000 = 0x79000 to prevent bootloader from erased after programming


Note:
let the application size smaller than the start point of bootloader for 0x2000 is more stable.

Reference :
https://devzone.nordicsemi.com/question/100609/sdk-12-bootloader-erased-after-programming/

nRF5x: how to use UICR as your signature

board: nRF52832_xxac_s132/ SDK11

After developing a firmware, you can use UICR as a mark to use .
because UICR can not be erased by DFU-OTA

STEP 1
copy file "uicr_config.h" at:
C:\..\nRF5x_SDK_11.0.0\examples\peripheral\uicr_config
to your project file.









STEP 2
open your project in IDE
add this in main.c :


//power by Agatha Kuan
//add uicr
#include "uicr_config.h"
then compile your project first.

STEP 3
open uicr_config.h
I add my family name like this:


// const uint32_t UICR_CLENR0    __attribute__((at(0x10001000))) __attribute__((used)) = 0xFFFFFFFF;
// const uint32_t UICR_RBPCONF   __attribute__((at(0x10001004))) __attribute__((used)) = 0xFFFFFFFF;
// const uint32_t UICR_XTALFREQ  __attribute__((at(0x10001008))) __attribute__((used)) = 0xFFFFFFFF;
const uint32_t UICR_ADDR_0x04 __attribute__((at(0x10001004))) __attribute__((used)) = 0x6e61754b;
//const uint32_t UICR_ADDR_0x80 __attribute__((at(0x1000108c))) __attribute__((used)) = 0x69617354;
//const uint32_t UICR_ADDR_0x84 __attribute__((at(0x10001084))) __attribute__((used)) = 0x6e656843;
//const uint32_t UICR_ADDR_0x88 __attribute__((at(0x10001090))) __attribute__((used)) = 0x53334955;
// const uint32_t UICR_ADDR_0x8C __attribute__((at(0x1000108C))) __attribute__((used)) = 0xFFFFFFFF;
// const uint32_t UICR_ADDR_0x90 __attribute__((at(0x10001090))) __attribute__((used)) = 0xFFFFFFFF;
// const uint32_t UICR_ADDR_0x94 __attribute__((at(0x10001094))) __attribute__((used)) = 0xFFFFFFFF;
// const uint32_t UICR_ADDR_0x98 __attribute__((at(0x10001098))) __attribute__((used)) = 0xFFFFF
then compile , program to your nRF52

STEP 4
open command line, type :


:: power by Agatha Kuan  2017.04.18

.\nrfjprog.exe --family NRF52 --memrd 0x10001004 --n 4

it shows:














be careful that the ascii shows in Little Endian
parameter "--n" write the length to read, "4" means 4 bytes.

Reference:
https://devzone.nordicsemi.com/documentation/nrf51/4.4.1/html/group__uicr__config__example.html

nRF52 avoid "DfuTarg": how to prevent from staying stuck in bootloader mode without starting the application

board: nRF52832_xxac_s132 nordic / SDK 11

While you try to add DFU  OTA service and flash softdevice, application ,and bootloader to your nRF52 (by nRFgo or command line tools),  you might see its BLE Advertising name as "Dfutarg". Like this :



and that means your application does not start. The device stays stuck in bootloader.

There are 2 ways to solve this problem:

First solution: program by command line tools and write memory

1. go to
C:\..\Nordic Semiconductor\nrf5x\bin
open command line, and write :


:: power by Agatha Kuan 20170419

.\nrfjprog.exe --family NRF52 --eraseall
.\nrfjprog.exe --family NRF52 --program %your_softdevice_name%
.\nrfjprog.exe --family NRF52 --program %your_application_name%
.\nrfjprog.exe --family NRF52 --program %your_bootloader_name%
.\nrfjprog.exe --family NRF52 --memwr 0x7f000 --val 1
.\nrfjprog.exe --family NRF52 --reset

then after it reset , the application will start.

Second solution : add patch file 

I provide you a patch file to force the device to start application after reset.
please download by this link :
https://drive.google.com/open?id=0ByqJaZSFoV7Hb190d1l4UjNzb28

and program by command line tools. Open command line and write:



:: power by Agatha Kuan 20170419

.\nrfjprog.exe --family NRF52 --eraseall
.\nrfjprog.exe --family NRF52 --program %your_softdevice_name%
.\nrfjprog.exe --family NRF52 --program %your_application_name%
.\nrfjprog.exe --family NRF52 --program %your_bootloader_name%
.\nrfjprog.exe --family NRF52 --program patch.hex
.\nrfjprog.exe --family NRF52 --reset

Note:
1.the patch.hex file can only use on nRF52832 SDK11
2.these 2 solution does not work after reset or DFU
3.if you want to use the first solution on nRF51, please see  here
(it is 0x3FC00 for nrf51)



Reference:

https://devzone.nordicsemi.com/question/22056/combining-sd-dfu-and-application-hex-and-programming/
https://devzone.nordicsemi.com/question/37880/initdat-file-for-dfu-gets-crc-error-correct-order-nrf-beacon-help/
https://devzone.nordicsemi.com/question/70738/bootloader-does-not-start-application/

2017年2月8日 星期三

J-Link as UART- Logging Output for nRF51/52

I use SEGGER RTT to replace UART logging .

STEP 1.
Download J-Link RTT Viewer and install it.
Download the RTT library files from SEGGER site and unzip them into a folder of your BLE SDK:

nRF51_SDK_10.0.0\nRF51_SDK_10.0.0\components\RTT










STEP 2.
Add the folder to  your project.

STEP 3.
add the RTT folder path to config your Project

STEP 4. my example code for main function printf


#include "SEGGER_RTT.h"

//SEGGER Delay
static void _Delay(int period) {
  int i = 100000*period;
  do { ; } while (i--);
}

int main(void)
{
    uint32_t err_code;
    bool erase_bonds;

    // Initialize.
    timers_init();
    buttons_leds_init(&erase_bonds);
    ble_stack_init();
    device_manager_init(erase_bonds);
    gap_params_init();
    advertising_init();
    services_init();
    conn_params_init();

    // Start execution.
    application_timers_start();
    err_code = ble_advertising_start(BLE_ADV_MODE_FAST);
    APP_ERROR_CHECK(err_code);

    // Enter main loop.
    for (;;)
    {
        power_manage();
    SEGGER_RTT_SetTerminal(0);
    SEGGER_RTT_WriteString(0, "Hello from SEGGER!\r\n");
    _Delay(100);
   
    SEGGER_RTT_TerminalOut(1,"terminalOut 1 \r\n");
    _Delay(100);
   
   int terminalNumber=2;
    SEGGER_RTT_SetTerminal(terminalNumber);
    SEGGER_RTT_printf(0, "terminal = %u \r\n",terminalNumber);
    _Delay(100);
   
    SEGGER_RTT_WriteString(0, "terminal 2\r\n");
    _Delay(100);
   
    SEGGER_RTT_TerminalOut(1,"terminalOut from 1 \r\n");
    _Delay(100);    
    }
}
then rebuild.

 If nothing is configured, all data is sent to Terminal 0.

The Teminal to output all following via Write(), WriteString() or printf() can be set with SEGGER_RTT_SetTerminal() .

Output of only one string via a specific Terminal can be done with SEGGER_RTT_TerminalOut(). I could set the parameter to specify which terminal would be the output target.

STEP 5. Open J-Link RTT Viewer

While I want 2 threads( maybe one is main thread, the other one is  interrupt thread) to print in the same terminal, the output message might be disorder or  tattered.

First, config your channel

press "OK".
press File-> connect


the main function output will be like :

STEP 6. my example code for button interrupt printf

add the following code demonstrating a button interrupt

//Add SEGGER_RTT
#include "SEGGER_RTT.h"

void bsp_event_handler(bsp_event_t event)
{
    uint32_t err_code;
    switch (event)
    {
        case BSP_EVENT_SLEEP:
            sleep_mode_enter();
            break;

        case BSP_EVENT_DISCONNECT:
            err_code = sd_ble_gap_disconnect(m_conn_handle,
                       BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
            if (err_code != NRF_ERROR_INVALID_STATE)
            {
                APP_ERROR_CHECK(err_code);
            }
            break;

        case BSP_EVENT_WHITELIST_OFF:
            err_code = ble_advertising_restart_without_whitelist();
            if (err_code != NRF_ERROR_INVALID_STATE)
            {
                APP_ERROR_CHECK(err_code);
            }
            break;
 
// add button interrupt      
 case BSP_EVENT_KEY_0:
     break;       

        default:
            break;
    }
}


// add button interrupt handler
static void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
    uint32_t err_code;

    switch (pin_no)
    {
        case BSP_BUTTON_0:
  if(0 != button_action)
  {       
   SEGGER_RTT_TerminalOut(3,"BUTTON ACTION \r\n"); 
   button_action = 1; 
  } 
        
  if(1 == button_action)
  {
   LEDS_ON(BSP_LED_1_MASK);
     
   SEGGER_RTT_TerminalOut(3,"BUTTON on \r\n");
   break;
  }
  else
  {    
   LEDS_OFF(BSP_LED_1_MASK); 
    
   SEGGER_RTT_TerminalOut(3,"BUTTON off \r\n");
   break;
  }
    
   
        default:
            APP_ERROR_HANDLER(pin_no);
            break;
    }
}



/**@brief Function for initializing buttons and leds.
 *
 * @param[out] p_erase_bonds  Will be true if the clear bonding button was pressed to wake the application up.
 */
static void buttons_leds_init(bool * p_erase_bonds)
{
    bsp_event_t startup_event;

#if (0)
    uint32_t err_code = bsp_init(BSP_INIT_LED | BSP_INIT_BUTTONS,
                                 APP_TIMER_TICKS(100, APP_TIMER_PRESCALER), 
                                 bsp_event_handler);
#else
  uint32_t err_code = bsp_init(BSP_INIT_NONE,
                                 APP_TIMER_TICKS(100, APP_TIMER_PRESCALER), 
                                 bsp_event_handler);
 static app_button_cfg_t buttons[] =
    {
        {BSP_BUTTON_0, false, BUTTON_PULL, button_event_handler}
    };

    err_code = app_button_init(buttons, sizeof(buttons) / sizeof(buttons[0]),
                               APP_TIMER_TICKS(300, APP_TIMER_PRESCALER));
    APP_ERROR_CHECK(err_code);
 app_button_enable();
#endif
    APP_ERROR_CHECK(err_code);

    err_code = bsp_btn_ble_init(NULL, &startup_event);
    APP_ERROR_CHECK(err_code);

    *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA);
}
then rebuild.


Now,  press button 0 (for pin define, please open  pca100xx.h)













the output will be

























You can try what will happen if 2 threads(interrupt and main thread) print in same terminal.

while you press down, it shows "BUTTON ACTION" and "BUTTON on".
And while you release the button, it shows "BUTTON off"




APPENDIX.
0.For more example, please check the following web site:

https://www.segger.com/jlink-rtt.html#RTT_Example_Code
http://blog.blecentral.com/2015/06/22/rtt_debugging/
http://dl.btc.pl/kamami_wa/j_link_edu_segger.pdf


1.J-Link RTT has function to input , just like what UART logging has done.