将单个位分配给字节 [英] Assigning individual bits to bytes

查看:114
本文介绍了将单个位分配给字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在微控制器和另一个芯片之间进行SPI通信.该芯片接受一个16位字.但是抽象库要求将数据作为两个8位字节发送.现在我想做一个包装器,这样我就可以轻松地创建读写请求...但是我还没有成功.这应该是这样的:

I have a to make a SPI communication between a microcontroller and another chip. The chip accepts a 16bit word. But the abstraction library requires the data to be sent as two 8bit bytes. Now I want to make a wrapper so I can easily create requests for read and write...but I have not yet got any success. Here is how it supposed to be:

下表显示了16位. MSB可以为0进行写入,也可以为1进行读取.地址可以从0x00x7,数据为11位.

The table below shows 16bits. The MSB can be 0 for write or 1 for read. The address can be from 0x0 to 0x7 and the data is 11 bits.

R/W  |      ADDRESS   |    DATA
 B15 |      B14-B11   |   B10-B0
 0   |        0000    | 00000000000
 W0  | A3, A2, A1, A0 | D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0

例如,如果我想从寄存器0x1中读取,我认为我必须设置以下位:

For example, if I want to read from register 0x1 I think I have to set the bits like this:

 W0  | A3, A2, A1, A0 | D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0
  1  | 0    0   0   1 |  0    0   0   0   0   0   0   0   0   0   0

或从寄存器0x7读取:

Or reading from register 0x7:

 W0  | A3, A2, A1, A0 | D10, D9, D8, D7, D6, D5, D4, D3, D2, D1, D0
  1  | 0    1   1   1 |  0    0   0   0   0   0   0   0   0   0   0

我尝试创建此struct/union以查看它是否可以工作:

I have tried to create this struct/union to see if it can work:

typedef struct{
    uint8_t acc_mode:1;
    uint8_t reg_addr:4;
    uint8_t reg_data:8; //TODO fix me should be 11
} DRVStruct;

typedef union {
    DRVStruct content;
    uint16_t all;
} DRVUnion;

void DRV_PrepareReadMsg(uint8_t reg, uint8_t* msgBuffer) {
    DRVUnion temp;
    temp.content.acc_mode = 1;
    temp.content.reg_addr = reg;
    temp.content.reg_data = 0; //read mode does not need data!

    msgBuffer[1] = temp.all & 0xFF;
    msgBuffer[0] = temp.all >> 8;
}

我得到的结果很奇怪...我不时从SPI得到答案(我确定SPI通信正常,但是我准备消息的代码就是问题).

I am getting strange results...from time to time I get answer from the SPI (I am sure the SPI communication is OK, but my code for preparing messages is the problem).

所以问题是:

  • 我在做正确的事情或方法吗?
  • 如何在不出现编译错误的情况下将reg_data的位宽从8增加到11?
  • 您对更好的方法有何建议?
  • Am I doing the right thing or approach?
  • How can I increase bit width of reg_data from 8 to 11 without getting compile error?
  • What do you suggest for a better approach?

推荐答案

这似乎可行:

#include <stdio.h>
#include <stdint.h>

typedef union {
    struct{     // no struct tag, since it is not needed...
        uint16_t acc_mode:1;
        uint16_t reg_addr:4;
        uint16_t reg_data:11; //TODO fix me should be 11
        } bits;
    uint16_t all;
    uint8_t bytes[2]; //extra bonus when lit;-)
        } DRVUnion;

int main(void)
{
DRVUnion uni,uni13[13];

printf("Size=%zu, %zu\n", sizeof uni, sizeof uni13);
return 0;
}

这篇关于将单个位分配给字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆