main.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <signal.h>
#include "myled.h"
#include <unistd.h>
#include <arpa/inet.h>
#define SEND_MSG _IOW('c',0,short)
void delay_ms(int ms)
{
int i,j;
for(i = 0; i < ms;i++)
for (j = 0; j < 1800; j++);
}
int main(int argc, char const *argv[])
{
char num[10] = {0x3f,0x6,0x5b,0x4f,0x66,0x6d,0x7d,0x7,0x7f,0x6f};
int fd;
int n;
char buf[2];
int index=0;
fd=open("/dev/m74hc595",O_RDWR);
if(fd<0)
{
printf("打开m74hc595设备失败\n");
exit(-1);
}
printf("打开m74hc595设备成功\n");
for(int i=1;i<9;i=i*2)
{
buf[0]=i;
if(index>9)
{
index=0;
}
buf[1]=num[index];
ioctl(fd,SEND_MSG,buf);
sleep(1);
buf[1]=0;
ioctl(fd,SEND_MSG,buf);
index++;
sleep(1);
}
close(fd);
return 0;
}
spi.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/spi/spi.h>
#define SEND_MSG _IOW('c',0,short)
int major;
struct class *cls;
struct device *dev;
struct spi_device *spi1;
int m74hc595_open(struct inode *inode, struct file *file)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
int m74hc595_close(struct inode *inode, struct file *file)
{
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
long m74hc595_ioctl(struct file *file,unsigned int cmd,unsigned long arg)
{
int ret;
char buf[2]={};
switch(cmd)
{
case SEND_MSG:
{
ret=copy_from_user((void*)buf,(void*)arg,sizeof(buf));
if(ret)
{
printk("给用户拷贝失败\n");
return -EINVAL;
}
spi_write(spi1,buf,sizeof(buf));
}
break;
}
return 0;
}
//定义操作方法结构体
struct file_operations fops={
.open=m74hc595_open,
.unlocked_ioctl=m74hc595_ioctl,
.release=m74hc595_close,
};
int m74hc595_probe(struct spi_device *spi)
{
spi1=spi;
major=register_chrdev(0,"m74hc595",&fops);
if(major<0)
{
printk("注册字符设备失败\n");
return major;
}
printk("注册字符设备成功\n");
//自动创建设备节点
cls=class_create(THIS_MODULE,"si7006");
if(IS_ERR(cls))
{
printk("向上提交目录失败\n");
return PTR_ERR(cls);
}
printk("向上提交目录成功\n");
dev=device_create(cls,NULL,MKDEV(major,0),NULL,"m74hc595");
if(IS_ERR(dev))
{
printk("向上提交节点信息失败\n");
return PTR_ERR(dev);
}
printk("向上提交节点信息成功\n");
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
int m74hc595_remove(struct spi_device *spi)
{
//注销字符设备驱动
device_destroy(cls,MKDEV(major,0));
class_destroy(cls);
unregister_chrdev(major,"m74hc595");
printk("%s:%s:%d\n",__FILE__,__func__,__LINE__);
return 0;
}
struct of_device_id oftable[]={
{.compatible="hqyj,m74hc595"},
{},
};
MODULE_DEVICE_TABLE(of,oftable);
//分配对象并初始化
struct spi_driver m74hc595 ={
.probe=m74hc595_probe,
.remove=m74hc595_remove,
.driver ={
.name = "m74hc595_driver",
.of_match_table = oftable,
},
};
//声明遵循GPL开源协议
module_spi_driver(m74hc595);
MODULE_LICENSE("GPL");