C 在8位UART上发送16位值

C 在8位UART上发送16位值,c,uart,psoc,cypress-psoc,C,Uart,Psoc,Cypress Psoc,我们正在尝试将一个16位值从一个PSoC发送到另一个PSoC。 此操作的本质应该非常简单: 将该值拆分为两个8位值,一个用于MSB,另一个用于LSB 从系统1发送MSB和LSB 在系统2上接收MSB和LSB 通过位移位MSB和或屏蔽LSB合并两个字节 利润 因此,我们在实践中的做法是: //Split and send uint16 utest = (uint16)test; uint8 hibyte = utest>>8; uint8 lowbyte = utest;

我们正在尝试将一个16位值从一个PSoC发送到另一个PSoC。 此操作的本质应该非常简单:

  • 将该值拆分为两个8位值,一个用于MSB,另一个用于LSB
  • 从系统1发送MSB和LSB
  • 在系统2上接收MSB和LSB
  • 通过位移位MSB和或屏蔽LSB合并两个字节
  • 利润
因此,我们在实践中的做法是:

//Split and send
uint16 utest = (uint16)test;
uint8 hibyte = utest>>8;
uint8 lowbyte = utest;        
UART_PutChar(hibyte);
UART_PutChar(lowbyte);
系统2(接收字节上的ISR):

//接收和合并
uint8 rx_msb=UART_GetByte();
uint8 rx_lsb=UART_GetByte();

rx_udata=((uint16)rx_msb首先,在中断例程中使用sprintf是一个非常糟糕的主意,即使您禁用了中断。更糟糕的是将数据发送到那里:) 你可能是一个非常非常初学者。始终保持中断例程尽可能短

将调试代码移到中断之外

其次,您只能读取在中断中接收到的内容(即一个字节),然后读取两个字节

最后,我不认为UART\u GetByte
是为在中断例程中使用而发明的。只需读取数据寄存器即可

我个人更喜欢工会

typedef union
{
    uint16_t u16;
    int16_t i16;
    uint8_t b[2];
}data16;

volatile data16 revcb, tb;  // tb can be local and not volatile
volatile int pointer = 0;
volatile int flag = 0;

CY_ISR(UART_ISR){
    Status_pin_Write(0xFF); //Used for debugging
    revcb.b[pointer] = dataregister;  // place the appripriate code here
    pointer = ! pointer;
    if(!pointer) flag = 1;
    Status_pin_Write(0x00);
}

//in the main function

while(1)
{
    if(flag) 
    {
        ISR_Rx_Disable();   // make it atomic
        tb = recv;
        flag = 0;
        ISR_Rx_Enable();
        sprintf(TransmitBufferUSB,"%d\n\r",tb.u16);
        UART_USB_PutString(TransmitBufferUSB);
    }
}

但是请记住,当您发送调试数据时,可能会出现许多其他值,您可能会丢失一些内容。您需要实现一个循环缓冲区-但这超出了这个问题的范围。

转储hexa中的值以检查格式。@rel这没关系-代码只是可笑地坏了try
sprintf(TransmitBufferUSB,“%hd\n\r”,rx_data)。(或将其转换为int)@joop这不是问题所在。我们尝试了您的代码,现在可以接收我们的号码。但新问题是:我们正在尝试发送号码16789。16789的十六进制数为0x4195。我们在两个不同的8位整数中接收65和149。我们知道65=0x41和149=0x95。如何将两个8位整数合并为一个16位整数?@de_rush有一个输入错误:指针=!!指针;而不是指针=!指针;你可以自己玩unins嗨,peter,我们已经让工会工作了,再次感谢你的帮助:)我们在一点混乱之后注意到了拼写错误。
typedef union
{
    uint16_t u16;
    int16_t i16;
    uint8_t b[2];
}data16;

volatile data16 revcb, tb;  // tb can be local and not volatile
volatile int pointer = 0;
volatile int flag = 0;

CY_ISR(UART_ISR){
    Status_pin_Write(0xFF); //Used for debugging
    revcb.b[pointer] = dataregister;  // place the appripriate code here
    pointer = ! pointer;
    if(!pointer) flag = 1;
    Status_pin_Write(0x00);
}

//in the main function

while(1)
{
    if(flag) 
    {
        ISR_Rx_Disable();   // make it atomic
        tb = recv;
        flag = 0;
        ISR_Rx_Enable();
        sprintf(TransmitBufferUSB,"%d\n\r",tb.u16);
        UART_USB_PutString(TransmitBufferUSB);
    }
}