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

  • 本文关键字:变量 pic 控制器 c pic
  • 更新时间 :
  • 英文 :


我使用PIC18f45k22,正在尝试制作热电偶库。此库要求将LATCH指定为参数变量。这是创建的代码。

#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);
}

然而,我使用了相同的代码,但没有在函数中使用它,它起到了作用。

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

#define mBitClear(var, n) var &= ~(1 << n)
#define mBitSet(var, n) var |= 1 << n

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

#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);
}
}

通过使用此方法,您可以传递任何有效的端口,甚至带有有效位数的变量。如果你看到不清楚的地方,问我。

最新更新