sve*_*ven 5 c linux posix ioctl
我使用下面的代码从嵌入式电路板的SPI端口输出数据(olimex imx233-micro - 它不是特定于电路板的问题).当我运行代码ioctl
返回" 坏地址 ".我正在修改http://twilight.ponies.cz/spi-test.c上的代码,工作正常.谁能告诉我我做错了什么?
root@ubuntu:/home# gcc test.c -o test
test.c:20: warning: conflicting types for ‘msg_send’
test.c:16: note: previous implicit declaration of ‘msg_send’ was here
root@ubuntu:/home# ./test
errno:Bad address - cannot send SPI message
root@ubuntu:/home# uname -a
Linux ubuntu 3.7.1 #2 Sun Mar 17 03:49:39 CET 2013 armv5tejl GNU/Linux
Run Code Online (Sandbox Code Playgroud)
码:
//test.c
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#include <errno.h>
static uint16_t delay;
int main(int argc,char *argv[]){
msg_send(254); //the message that I want to send decimal "254"
return 0;
}
void msg_send(int msg){
int fd;
int ret = 0;
fd = open("/dev/spidev32766.1", O_RDWR); //ls /dev outputs spidev32766.1
if(fd < 0){
fprintf(stderr, "errno:%s - FD could be not opened\n ", strerror(errno));
exit(1);
}
struct spi_ioc_transfer tr = {
.len = 1,
.delay_usecs = delay,
.speed_hz = 500000, //500 kHz
.bits_per_word = 8,
.tx_buf = msg,
.rx_buf = 0, //half duplex
};
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
if (ret <1 ){
fprintf(stderr, "errno:%s - cannot send SPI message\n ", strerror(errno));
}
close(fd);
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Ada*_*eld 12
错误消息"错误地址"来自错误代码EFAULT
,当您将地址传递给进程虚拟地址空间中的有效虚拟地址的内核时会发生错误代码.您的tr
结构的地址显然是有效的,因此问题必须与其成员之一有关.
根据定义struct spi_ioc_transfer
,.tx_buf
和.rx_buf
成员必须是指向用户空间缓冲区的指针,或者为null.您将设置.tx_buf
为整数254,它不是有效的用户空间指针,因此这是坏地址的来源.
我不熟悉这个IOCTL,所以我最好的猜测是你需要用二进制来对数据进行低音.一种方法是这样做:
struct spi_ioc_transfer tr = {
.len = sizeof(msg), // Length of rx and tx buffers
...
.tx_buf = (u64)&msg, // Pointer to tx buffer
...
};
Run Code Online (Sandbox Code Playgroud)
如果您需要将其作为ASCII发送,那么您应该使用诸如snprintf(3)
将整数转换为ASCII字符串之类的函数,然后将TX缓冲区指向该字符串并相应地设置长度.