我使用PIC18f45k22,并试图制作一个热电偶库。此库要求将闩锁指定为参数变量。这是创建的代码。
#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);
}但是,我使用了相同的代码,而没有在函数中使用它,并且它工作了。
发布于 2022-03-07 07:18:20
你可以通过使用间接的方法来实现它。如果您查看MPLAB中的PIC18头或任何PIC头,您将看到每个寄存器都分配了一个内存地址,并且它们也是用如下易失性限定符定义的:volatile unsigned char LATB __at(0xF8A),因此可以通过指针访问端口,而由于using的性质,不能使用指针访问位字段。因此,对端口的位进行一般修改访问的一个方便的方法是使用宏。因此,让我们首先定义位集和位清除宏:
#define mBitClear(var, n) var &= ~(1 << n)
#define mBitSet(var, n) var |= 1 << n现在我们已经有了通用的C风格的位操作宏,只要端口存在,并且端口宽度不超过7,我们就可以将任何端口和位号作为变量传递。但请注意,某些端口的位数可能最少。现在,让我们将这些宏应用于您的函数:
#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);
}
}您可以使用此方法传递任何具有有效位号的有效端口或甚至变量。如果你看到什么不清楚的话问我。
https://stackoverflow.com/questions/71226298
复制相似问题