数码管流水灯实现
.h
#ifndef __M74HC595_H__
#define __M74HC595_H__
#define SPI_WHICH _IOW('a',0,int)
#define SPI_NUM _IOW('a',1,int)
char code[]={
0x3f,
0x06,
0x5b,
0x4f,
0x66,
0x6d,
0x7d,
0x07,
0x7f,
0x6f,
0x77,
0x7c,
0x39,
0x5e,
0x79,
0x71,
};
char light[]={
0x1,
0x2,
0x4,
0x8,
};
#endif
驱动.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);
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;
}