我的AVR PWM库代码中的错误

error in my AVR PWM library code

本文关键字:错误 代码 AVR PWM 我的      更新时间:2023-10-16

嗨,我正在在我的项目中创建一个C 中的PWM库。我已经开始在下面处理它是我的代码的一部分,尚未完成。我用位代码写一些并构建它以查找错误,然后发现了一些错误,所以我停了下来。即使我定义了正确的参数,也会出现错误。它应该首先预处理#if,并用0x80分配TCC0A。但是它跳过#if,#elif和最后一个#else正在执行。请帮助我更正给定的代码。

IDE:Atmel Studio 7.0

MCU:ATMEGA328P

代码:

/************************************************************ 
PWM.h file
************************************************************/
#ifndef PWM_H_
#define PWM_H_
//PWM outputs
#define OC0A 1
#define OC0B 2
//PWM modes
#define NINV 0b10000000      //Non-inverting Mode
#define INV  0b11000000      //Inverting Mode
#include <avr/io.h>
class PWM
{ 
public:
void Initialize(unsigned char PWMoutputpin,  unsigned char PWMmode)
{
TCCR0A = 0x00; TCCR0B = 0x00;
#if ((PWMoutputpin == OC0A) && (PWMmode == NINV))
      TCCR0A |= NINV;
#elif ((PWMoutputpin == OC0A) && (PWMmode == INV))
      TCCR0A |= INV;
#elif ((PWMoutputpin == OC0B) && (PWMmode == NINV))
      TCCR0A |= (NINV >> 2);
#elif ((PWMoutputpin == OC0B) && (PWMmode == INV))
      TCCR0A |= (INV >> 2);
#else
  #error PWM::Initialize() parameters not defined properly.
#endif
}
};
#endif /* PWM_H_ */
/******************************* END **********************/

/************************************************************
main.cpp file
************************************************************/
#include <avr/io.h>
#include "PWM.h"
int main(void)
{
PWM p;                    //define PWM as p object
p.Initialize(OC0A,NINV);  //initialize PWM with OC0A as output with non-inverting mode
return 0;
}

正如已经评论的那样,您无法按照自己的方式使用 #if。编译器在执行#if语句时只能在编译时间进行一次决定。您正在尝试根据更改的参数输入或运行时使用#if语句。当您的库代码由另一个函数调用时,#if不能在运行时使用,此时编译已经完成。

代码更改

您的代码应更改为:

void Initialize(unsigned char PWMoutputpin,  unsigned char PWMmode)
{
  TCCR0A = 0x00; TCCR0B = 0x00;
  if ((PWMoutputpin == OC0A) && (PWMmode == NINV))
      TCCR0A |= NINV;
  else if ((PWMoutputpin == OC0A) && (PWMmode == INV))
      TCCR0A |= INV;
  else if ((PWMoutputpin == OC0B) && (PWMmode == NINV))
      TCCR0A |= (NINV >> 2);
  else if ((PWMoutputpin == OC0B) && (PWMmode == INV))
      TCCR0A |= (INV >> 2);
  else
      // #error PWM::Initialize() parameters not defined properly.
      // Your error output message can be sent by `cout` or some
      // other method like `assert()`.
}

更多代码更改

您甚至可以进一步简化代码。请注意,如果您的输出引脚是OC0A,那么TCCR0A值仅具有PWM模式的or'D?OC0B也是如此:

void Initialize(unsigned char PWMoutputpin,  unsigned char PWMmode)
{
  TCCR0A = 0x00; TCCR0B = 0x00;
  if (PWMoutputpin == OC0A)
      TCCR0A |= PWMmode;
  else if (PWMoutputpin == OC0B)
      TCCR0A |= (PWMmode >> 2);
  else
      // #error PWM::Initialize() parameters not defined properly.
      // Your error output message can be sent by `cout` or some
      // other method like `assert()`.
}

这仅假定NINVINV的两种模式/值将传递。如果用户通过另一个值传递,则您将获得一些奇怪的结果,但是您也可以在if语句之前检查PWMmode,以确保它是有效。