这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 综合技术 » 基础知识 » winavr winavr指针奇怪问题

共2条 1/1 1 跳转至

winavr winavr指针奇怪问题

院士
2006-09-17 18:14:16     打赏
winavr winavr指针奇怪问题



关键词: winavr     指针     奇怪     问题    

院士
2006-12-22 22:43:00     打赏
2楼
问 用mega8的twi写max518。函数是参照winAVR的例子写的,基本没变。
奇怪的是我用数组赋值给buf就可以,可是用普通的指针就不行
    uint8_t i, *p;    /* 这样不行 */
    p = &i;
    *p = 0x00;
    *(p+1) = 0xff;   

    uint8_t data[2];    /* 这样就行 */
    data[0] = 0x00;
    data[1] = 0xff;

下面是程序

int twi_write_bytes(uint8_t addr, int len, uint8_t *buf)
{
    uint8_t n = 0;
    int st = 0;
  
    restart:
    if (n++ >= MAX_ITER)
    {
        return -1;
    }
    
    begin:
    TWCR = _BV(TWINT) | _BV(TWSTA) | _BV(TWEN); /* send start condition */
    
    while ((TWCR & _BV(TWINT)) == 0)
    {
    
    }; /* wait for transmission */
    
    switch ((twst = TW_STATUS))
    {
        case TW_REP_START:        /* OK, but should not happen */
        
        case TW_START:
            break;
        
        case TW_MT_ARB_LOST:
            goto begin;
        
        default:
            return -1;        /* error: not in start condition */
                /* NB: do /not/ send stop condition */
    }

    /* send ADDR+W */
    TWDR = addr | TW_WRITE;
    TWCR = _BV(TWINT) | _BV(TWEN); /* clear interrupt to start transmission */
    
    while ((TWCR & _BV(TWINT)) == 0)
    {
    
    }; /* wait for transmission */
    
    switch ((twst = TW_STATUS))
    {
        case TW_MT_SLA_ACK:
            break;
        
        case TW_MT_SLA_NACK:    /* nack during select: device busy writing */
            goto restart;
       
        case TW_MT_ARB_LOST:    /* re-arbitrate */
            goto begin;
        
        default:
            goto error;        /* must send stop condition */
    }
  
    for (; len > 0; len--)
    {
        TWDR = *buf++;
        TWCR = _BV(TWINT) | _BV(TWEN); /* start transmission */
        
        while ((TWCR & _BV(TWINT)) == 0)
        {
        
        }; /* wait for transmission */
        
        switch ((twst = TW_STATUS))
        {
            case TW_MT_DATA_NACK:
           goto error;        /* device write protected -- Note [14] */
            
            case TW_MT_DATA_ACK:
           st++;
           break;
            
       default:
           goto error;
         }
    }
    
    quit:
    TWCR = _BV(TWINT) | _BV(TWSTO) | _BV(TWEN); /* send stop condition */
    return st;

    error:
    st = -1;
    goto quit;
}
   1: 你写越界了uint8_t i, *p;    /* 这样不行 */
    p = &i;
    *p = 0x00;
    *(p+1) = 0xff;

*(p+1)超过了i的范围。

uint8_t i[2], *p;
    p=i;
    *p = 0x00;
    *(p+1) = 0xff;
这样就可以了。

共2条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]