pointers - pic33 指向位对象的指针
问题描述
我有一个关于微芯片 PIC33E512MU810 的项目,我想设置一个指向位对象地址的指针。像这样的东西:
bool *pointer1 = &LATGbits.LATG12;
我知道根据文档,微芯片的编译器不允许这样做,我什至尝试过,它显然弹出了一个错误。
不能声明指向位类型的指针或将位对象的地址分配给任何指针。也不可能静态初始化位变量,因此必须在代码本身中为它们分配任何非零起始值(即 1)。位对象将在启动时被清除,除非该位是持久的。
我想知道是否有一些方法可以实现同样的目标?
谢谢
解决方案
不幸的是,这是不可能的。但是您可以利用 C 宏的强大功能。我不确定这是否能解决您的确切问题。但也许至少给你一个想法。下面是我在 MPLABX 模拟器中编写和测试并运行良好的示例代码。如果它有助于解决您的问题,那么您可以为您的 32 位系统修改一些定义,因为我测试了 8 位系统。在这段代码中,setBit
andclearBit
宏可以解决问题。这是代码:
#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;
}
如果您感到困惑,请向我询问任何部分。
推荐阅读
- reactjs - 使用 SWR 进行类型安全数据获取时的“any”替代方案?
- service - 如何添加新的 Android /init.rc 服务?
- kubernetes - 如何将一个服务的外部 ip 模板化到另一个服务
- scikit-learn - 如何从 sklearn 中的 .mat 文件中拆分训练和测试数据?
- powerbi - 计算的列平均最后 X 值
- c# - SonarQube 运行代码分析 Azure DevOps 任务失败,因为无法找到 xunit.runner.visualstudio.dotnetcore.testadapter.dll
- python - 获取 pandas.groupBy 中的最大值行,而无需在具有 DatetimeIndex 的数据框中应用
- javascript - import { fs } from 'fs' 出错,解析模块失败
- python - 如何删除熊猫数据框的第一列,列名未知
- react-native - 错误'未定义不是对象'使用@react-navigation/drawer(检查文档和问题)