如何用位域给8位寄存器赋值

问题描述:

八位寄存器里的部分位有一个功能,但是不能位寻址,如下图,应该怎么把这个寄存器对影成结构体,然后结构体的值直接赋给寄存器呢?

  1. 使用位域,将八位寄存器对影成一个结构体,考虑大小端的问题,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;

};

  1. 将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;

 

};

  1. 定义联合体,准备数据交换

union srr2uchar

{

PWM_CFG data;

unsigned char  val;

};

  1. 主函数

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值