【问题标题】:reading from pipe for SPI从管道读取 SPI
【发布时间】:2023-03-06 12:51:01
【问题描述】:

我在 microblaze 上使用 ulinux。

我的 SPI 有一些问题。 我的代码有效,我看到管道已被读出。但是我如何检查数据(rdata) printf 不起作用。

这是我的代码

//slavetool

int main(int argc, char **argv)
{

    uint8_t rdata[1500];
    int ctrl = 0;
    int fd;
    int pipenr = 9;
    int n;
    char device[15];
    fd_set socks;

    //open codec
    sprintf(device,"/dev/spi/pipe%d", pipenr);
    fd = open(device, O_RDWR);
    if(fd < 0)
        {
        printf("Failed to open pipe %s\n", device);
        return 0;
        } else 
        {
        printf("openend %s\n", device);
        }   
    printf("fd = %i\n", fd);

    printf("Initialisation complete!\n");


while(1)
    {
        printf("try to set!\n");

        FD_ZERO(&socks);
        FD_SET(fd, &socks);

        printf("fd_set set!\n");

        n = select(fd + 1, &socks, NULL, NULL, NULL);   

        //printf("Select is %i!\n", n);

        if(FD_ISSET(fd, &socks)) 
        {
           ctrl = read(fd, &rdata, 1500);
           printf("entered data: %s", rdata);  //DOESN'T WORK
           printf("ctrl: %i", ctrl);           //DOESN'T WORK
           printf("Check1\n");                 // WORK

                if(ctrl<0) 
                {
                    perror("read");
                    printf("Ende ctrl ist %i!\n",ctrl);
                    FD_ZERO(&socks);
                    close(fd);
                    return -1;
                }  

                printf("Check2\n"); 



        } else {printf("FD_ISSET not set");}


    }

    close(fd);


    return 0;
}

终端:

# ./spiread
openend /dev/spi/pipe9
fd = 3
Initialisation complete!
try to set!
fd_set set!
Select is 1!
Wait:
Check1
Check2 

*编辑感谢您的快速回答。不要工作!跳过那个 print()。 **编辑哦,它有效!谢谢阿尔特曼。不能投票 -.-

【问题讨论】:

  • 看看我的答案的编辑,它不正确

标签: c linux spi


【解决方案1】:
uint8_t rdata[1500];
...
ctrl = read(fd, &rdata, 1500);
printf("entered data: %s", rdata);  //DOESN'T WORK

我建议将其更改为:

char rdata[1500];
...
ctrl = read(fd, rdata, sizeof(rdata) - 1);
if (ctrl == -1) {
  perror("read");
  exit(EXIT_FALURE);
}
rdata[ctrl] = '\0'; // read() doesn't add a trailing 0
printf("entered data: %s", rdata);

请注意,recv 在现代系统上优于 read

【讨论】:

  • @AlterMann:您的代码中有缓冲区溢出。它应该是“ctrl = read(fd, rdata, sizeof(rdata) - 1);”。如果您读取完整的 1500 个字节,则空字节将超出数组的范围。
  • @DoxyLover,我觉得你错了:pubs.opengroup.org/onlinepubs/009604499/functions/read.html,看看最后的例子。
  • @AlterMann:不同之处在于,在该示例中,它们没有写入额外的空字节。在您的代码中, read() 可能会读取 1500 个字节 (sizeof(rdata)) 来填充缓冲区。在这种情况下,您的最后一个分配将写入 rdata[1500] 溢出数组。我支持我的评论!
  • @DoxyLover,ops,你是对的,现在我明白我的错误了,谢谢指正。
  • 是的,存在堆栈溢出。再次感谢!^^
猜你喜欢
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2017-07-26
  • 1970-01-01
相关资源
最近更新 更多