首页 > 解决方案 > pic33 指向位对象的指针

问题描述

我有一个关于微芯片 PIC33E512MU810 的项目,我想设置一个指向位对象地址的指针。像这样的东西:

bool *pointer1 = &LATGbits.LATG12;

我知道根据文档,微芯片的编译器不允许这样做,我什至尝试过,它显然弹出了一个错误。

不能声明指向位类型的指针或将位对象的地址分配给任何指针。也不可能静态初始化位变量,因此必须在代码本身中为它们分配任何非零起始值(即 1)。位对象将在启动时被清除,除非该位是持久的。

我想知道是否有一些方法可以实现同样的目标?

谢谢

标签: pointerspic

解决方案


不幸的是,这是不可能的。但是您可以利用 C 宏的强大功能。我不确定这是否能解决您的确切问题。但也许至少给你一个想法。下面是我在 MPLABX 模拟器中编写和测试并运行良好的示例代码。如果它有助于解决您的问题,那么您可以为您的 32 位系统修改一些定义,因为我测试了 8 位系统。在这段代码中,setBitandclearBit宏可以解决问题。这是代码:

#include <xc.h>
#include <stdint.h>

// Macros for setting bits in C style
#define setBit(reg, bit) reg |= 1 << bit
#define clearBit(reg, bit) reg &= ~(1 << bit)

typedef struct {
    int var1;
    char var2;
    /* Holds a reference to any SFR register change the type to uint32_t
    * if your system is 32 bit. I tested it for 8 bit in simulator*/
    volatile uint8_t *latReg; 
    char bitno; // Holds bit number
} mixedTypes_t;

void initMyMixedTypes(
            mixedTypes_t *mixedtype,
            int v1, char v2, volatile uint8_t *preg, char bitno) {
    mixedtype->var1 = v1;
    mixedtype->var2 = v2;
    mixedtype->latReg = preg;
    mixedtype->bitno = bitno;
}

// A sample function that take a sample action according to structure's var1
void makeSomething(mixedTypes_t *mtype) {
    if(mtype == NULL) return; // Make nothing if null
    if(mtype->var1 > 100) {
        setBit(*(mtype->latReg), mtype->bitno);
    }
    else {
        clearBit(*(mtype->latReg), mtype->bitno);
    }
}

void main(void) {
    
    mixedTypes_t aMixedType; // Declare your struct
    
    // Here you init your struct
    initMyMixedTypes(&aMixedType, 500, 'k', &LATA, _LATA_LA3_POSN);

    while(1) {
        setBit(LATA, 0);
        clearBit(LATA, 0);
        
        // Make something with the structure by calling some function
        makeSomething(&aMixedType); 
        
        aMixedType.var1 = 58; // Set it to a value less than 100
        
        // Now the function will evaluate again and clear the associated bit
        makeSomething(&aMixedType);
        
    }

    // Never reach here
    return;
}

如果您感到困惑,请向我询问任何部分。


推荐阅读