• stm32 cortext-M3 类型对齐问题【worldsing笔记】


    经过细测,Cortex-M3的double类型必须4字节对齐访问,其他诸如float,int,short 可以非对齐访问。否则将会产生硬件异常!即访问double类型地址必须能被4整除,测试代码如下:

       1: /* 测试Cortex-M3类型对齐访问
       2:  * i,j,k,l控制对齐长度,对齐
       3:  * 长度不符合是将产生HardFault
       4:  * 异常
       5:  */
       6: double *p;
       7: float  *q;
       8: int    *t;
       9: short  *r;
      10: char buf[32] __attribute__((at(0X20002000)));
      11:  
      12: int main(void)
      13: {
      14:     int i, j, k, l;
      15:     i = 0;
      16:     j = 0;
      17:     k = 0;
      18:     l = 0;
      19:     while(1)
      20:      {
      21:         p =  (double *)(0x20000000 + i);
      22:         *p = 890.0;
      23:         i += 4;                         //double 地址增量,只能是4的整数倍
      24:         
      25:         q =  (float *)(0x20001000 + j); 
      26:         *q = 890.0; 
      27:         j += 1;                         //float 地址增量
      28:         
      29:         t =  (int   *)(0x20002000 + k);
      30:         *t = 890;
      31:         k += 1;                         //int 地址增量 
      32:         
      33:         r =  (short *)(0x20003000 + l);
      34:         *r = 890; 
      35:         l += 1;                         //short 地址增量 
      36:     
      37:   }
      38:     return 0;
      39:     
      40: }
      41:  
      42:  
      43:  
      44:  

    测试环境:

    软件:windows xp + Keil Mdk4.7

    硬件:stm32f103vb

    代码:点击下载

    在程序中使用double类型指针时,容易产生硬件异常,所以,double指针指向的地址最好是被4整除,但的多文件的代码中ROM分配是编译器会做优化,造成double指针指向的地址非4字节对齐。

    如:

       1: char tem[33];
       2:  
       3: char buf[65];
       4:  
       5: char ch;
       6:  
       7: double p;
       8:  
       9: p = (double *)buf;
      10:  

    p = 0x20000000 + 33; 非4字节对齐,所以*p = 56.78;时会产生HardFault_Handler;

    处理办法是:

    1、用在Keil Mdk 中用,__attribute__((at(address))) 指定stm32 变量地址, 如char buf[56] __attribute__((at(0X20002000))) ; 指定buf在内存的地址为0X20002000;且是以4字节对齐;

    2、在应用*p时对buf地址判断做偏移; 对多浪费3字节;

    3、对链接脚本文件定位buf位置;

  • 相关阅读:
    leetcode562- Longest Line of Consecutive One in Matrix- medium
    leetcode118- Pascal's Triangle I & II- easy
    leetcode524- Longest Word in Dictionary through Deleting- medium
    leetcode128- Longest Consecutive Sequence- hard
    leetcode22- Generate Parentheses- medium
    leetcode17- Letter Combinations of a Phone Number- medium
    leetcode678- Valid Parenthesis String- medium
    php截取字符串的实例代码(支持utf-8)
    php中封装的curl函数(抓取数据)
    linux计划任务运行php文件的方法分享
  • 原文地址:https://www.cnblogs.com/worldsing/p/3296479.html
Copyright © 2020-2023  润新知