.c文件
#include <linux/init.h>
#include <linux/module.h>
#include <linux/spi/spi.h>
#include <linux/fs.h>
#include "M74HC595.h"
#define NAME "spi_m74hc595"
int major = 0;
struct class *cls;
struct device *dev;
struct spi_device *sspi;
long m74hc595_ioctl(struct file *file,unsigned int cmd,unsigned long args)
{
switch(cmd)
{
case SPI_WHICH:
{
spi_write(sspi,&light[args],1);
}break;
case SPI_NUM:
{
spi_write(sspi,&code[args],1);
}break;
default:
printk("功能码错误\n");
}
return 0;
}
struct file_operations fops = {
.unlocked_ioctl = m74hc595_ioctl,
};
int m74hc595_probe(struct spi_device *spi)
{
char buf[2]={0xf,0x0};
sspi=spi;//复制一份
printk("%s:%d\n",__FILE__,__LINE__);
spi_write(sspi,buf,sizeof(buf));
//动态注册字符设备驱动
major = register_chrdev(0,NAME,&fops);
if(major < 0)
{
printk("register chrdev error\n");
return major;
}
printk("字符设备驱动注册成功major=%d\n",major);
//向上提交节点目录
cls = class_create(THIS_MODULE,NAME);
if(IS_ERR(cls))
{
printk("class create error\n");
return PTR_ERR(cls);
}
//创建设备节点
dev = device_create(cls,NULL,MKDEV(major,0),NULL,NAME);
if(IS_ERR(dev))
{
printk("device create error\n");
return PTR_ERR(dev);
}
return 0;
}
int m74hc595_remove(struct spi_device *spi)
{
printk("%s:%d\n",__FILE__,__LINE__);
device_destroy(cls,MKDEV(major,0));
class_destroy(cls);
unregister_chrdev(major,NAME);
return 0;
}
//设备树匹配表
struct of_device_id of_table[]={
{.compatible="hqyj,m74hc595"},
{},
};
MODULE_DEVICE_TABLE(of,of_table);
//定义SPI对象并且初始化
struct spi_driver m74hc595 ={
.probe=m74hc595_probe,
.remove=m74hc595_remove,
.driver={
.name="m74hc595",
.of_match_table=of_table,
},
};
module_spi_driver(m74hc595);
MODULE_LICENSE("GPL");
test.c文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include "M74HC595.h"
int main(int argc, char const* argv[])
{
int which = 0;
int data = 0;
int fd;
fd = open("/dev/spi_m74hc595", O_RDWR);
if (fd < 0) {
perror("open error");
return -1;
}
while (1)
{
ioctl(fd, SPI_WHICH, which++);
ioctl(fd, SPI_NUM, data++);
if (which >= 4)
which = 0;
if (data >= 16)
data = 0;
sleep(1);
}
close(fd);
return 0;
}
.h文件
#ifndef __M74HC595_H__
#define __M74HC595_H__
#define SPI_WHICH _IOW('a',0,int)
#define SPI_NUM _IOW('a',1,int)
char code[]={
0x3f,//0
0x06,//1
0x5b,//2
0x4f,//3
0x66,//4
0x6d,//5
0x7d,//6
0x07,//7
0x7f,//8
0x6f,//9
0x77,//a
0x7c,//b
0x39,//c
0x5e,//d
0x79,//e
0x71,//f
};
char light[]={
0x1,//g0
0x2,//g1
0x4,//g2
0x8,//g3
};
#endif