首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在pic微控制器中使用端口作为变量

在pic微控制器中使用端口作为变量
EN

Stack Overflow用户
提问于 2022-02-22 18:09:00
回答 1查看 210关注 0票数 0

我使用PIC18f45k22,并试图制作一个热电偶库。此库要求将闩锁指定为参数变量。这是创建的代码。

代码语言:javascript
复制
#define B4_LATCH LATB4
unsigned short Thermo1;

unsigned short thermal (unsigned char* Latch) {
unsigned short thermocouple;
    Latch = 0;
    thermocouple  = spiRead(0)<<8; //Read first byte
    thermocouple |= spiRead(0); //add second byte with first one
    thermocouple  = (thermocouple>>4)*0.5;
    Latch = 1;
return thermocouple;
}

void main (){
 while (1){
thermo1 = thermal (B4_LATCH);
printf ("%u" , thermo1);
}

但是,我使用了相同的代码,而没有在函数中使用它,并且它工作了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-07 07:18:20

你可以通过使用间接的方法来实现它。如果您查看MPLAB中的PIC18头或任何PIC头,您将看到每个寄存器都分配了一个内存地址,并且它们也是用如下易失性限定符定义的:volatile unsigned char LATB __at(0xF8A),因此可以通过指针访问端口,而由于using的性质,不能使用指针访问位字段。因此,对端口的位进行一般修改访问的一个方便的方法是使用宏。因此,让我们首先定义位集和位清除宏:

代码语言:javascript
复制
#define mBitClear(var, n) var &= ~(1 << n)
#define mBitSet(var, n) var |= 1 << n

现在我们已经有了通用的C风格的位操作宏,只要端口存在,并且端口宽度不超过7,我们就可以将任何端口和位号作为变量传递。但请注意,某些端口的位数可能最少。现在,让我们将这些宏应用于您的函数:

代码语言:javascript
复制
#define B4_LATCH 4 // Define the bit number
unsigned short Thermo1;

unsigned short thermal (volatile unsigned char* Port, const unsigned char Latch) {
unsigned short thermocouple;
    mBitClear(*Port, Latch); // Clear the bit
    thermocouple  = spiRead(0)<<8; //Read first byte
    thermocouple |= spiRead(0); //add second byte with first one
    thermocouple  = (thermocouple>>4)*0.5;
    mBitSet(*Port, Latch); // Set the bit
    return thermocouple;
}

void main (){

    while (1){
        thermo1 = thermal (&LATB, B4_LATCH); //< Note the indirection symbol (&) it is important
        printf ("%u" , thermo1);
    }
}

您可以使用此方法传递任何具有有效位号的有效端口或甚至变量。如果你看到什么不清楚的话问我。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71226298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档