问题描述:
八位寄存器里的部分位有一个功能,但是不能位寻址,如下图,应该怎么把这个寄存器对影成结构体,然后结构体的值直接赋给寄存器呢?
- 使用位域,将八位寄存器对影成一个结构体,考虑大小端的问题,PC机把第七位放到高位,MCU把第七位放到低位.
struct PWM_CFG{
unsigned char PWMIE:1;// no.7bit
unsigned char PWMOCP:1;
unsigned char PWMOCN:1;
unsigned char PWMnOCM:1;
unsigned char reserver:2;
unsigned char PWMnCKS:2;
};
- 将PWM封装成一个结构体
struct PWMResiger
{
unsigned char IO_P;
unsigned char IO_N;
unsigned char channal;
struct PWM_CFG CFG;
unsigned char DTS;
unsigned char PRL;
unsigned char PRH;
unsigned char CCRL;
unsigned char CCRH;
};
- 定义联合体,准备数据交换
union srr2uchar
{
PWM_CFG data;
unsigned char val;
};
- 主函数
enum PWMnCKS{
PWM_HRC=0,//16M
PWM_LRC,//32K
PWM_FRE4M
};
typedef enum {RESET = 0, SET = !RESET} FlagStatus, ITStatus;
int _main(int argc, _TCHAR* argv[])
{
struct PWMResiger PWMresiger;
//select HRC
PWMresiger.channal=0;
PWMresiger.CFG.PWMnCKS = PWM_LRC ;
//
PWMresiger.CFG.PWMOCP = SET;
PWMresiger.CFG.PWMOCN = SET;
PWMresiger.CFG.PWMnOCM =RESET;
unsigned char val=0;
union srr2uchar var;
var.data = PWMresiger.CFG;
val =var.val;
printf("size = %d\r\n",sizeof(PWM_CFG));
printf("val = %x;\r\n",val );
printf("val = %x;\r\n",PWMresiger.CFG);
getchar();
}
控制台输出结果:
size = 1
val = 46;
val = 46;
从结果中来看就是结果是正确的,但是不知道心梗怎样,还有就是需要一个联合体变量,比较麻烦,寻找着直接把结构体给寄存器赋值给地址的方法.
VS完整代码
// Debug.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<stdio.h>
#define ROR_8BIT(X,Y) ((X<<(8-Y))|(X>>Y))
#define ROL_8BIT(X,Y) ((X>>(8-Y))|(X<<Y))
struct PWM_CFG{
unsigned char PWMIE:1;// no.7bit
unsigned char PWMOCP:1;
unsigned char PWMOCN:1;
unsigned char PWMnOCM:1;
unsigned char reserver:2;
unsigned char PWMnCKS:2;
};
union srr2uchar
{
PWM_CFG data;
unsigned char val;
};
struct PWMResiger
{
unsigned char IO_P;
unsigned char IO_N;
unsigned char channal;
struct PWM_CFG CFG;
unsigned char DTS;
unsigned char PRL;
unsigned char PRH;
unsigned char CCRL;
unsigned char CCRH;
};
enum PWMnCKS{
PWM_HRC=0,//16M
PWM_LRC,//32K
PWM_FRE4M
};
typedef enum {RESET = 0, SET = !RESET} FlagStatus, ITStatus;
int _tmain(int argc, _TCHAR* argv[])
{
struct PWMResiger PWMresiger;
//select HRC
PWMresiger.channal=0;
//大端模式 VS
PWMresiger.CFG.PWMnCKS = PWM_LRC ;
//
PWMresiger.CFG.PWMOCP = SET;
PWMresiger.CFG.PWMOCN = SET;
PWMresiger.CFG.PWMnOCM =RESET;
unsigned char val=0;
union srr2uchar var;
var.data = PWMresiger.CFG;
val =var.val;
printf("size = %d\r\n",sizeof(PWM_CFG));
printf("val = %x;\r\n",val );
printf("val = %x;\r\n",PWMresiger.CFG);
getchar();
}