数码管应用层控制
循环依次显示0~9
驱动代码
#include <linux/init.h>
#include <linux/module.h>
#include <linux/spi/spi.h>
int major;
struct class *cls;
struct device *dev;
struct spi_device *spi;
int m74hc595_open(struct inode *inode, struct file *file)
{
printk("%s:%s:%d\n", __FILE__, __func__, __LINE__);
return 0;
}
ssize_t m74hc595_write(struct file *file, const char __user *ubuf, size_t size, loff_t *loff)
{
char buf[2] = {};
copy_from_user(buf, ubuf, sizeof(buf));
spi_write(spi, buf, sizeof(buf));
return 0;
}
int m74hc595_close(struct inode *inode, struct file *file)
{
printk("%s:%s:%d\n", __FILE__, __func__, __LINE__);
return 0;
}
//定义操作方法结构体
struct file_operations fops = {
.open = m74hc595_open,
.write = m74hc595_write,
.release = m74hc595_close,
};
int m74hc595_probe(struct spi_device *spi_d)
{
spi = spi_d;
//注册字符设备
major = register_chrdev(0, "m74hc595", &fops);
if (major < 0)
{
printk("注册字符设备驱动失败\n");
return major;
}
printk("注册字符设备驱动成功\n");
//自动创建设备节点
//向上提交目录
cls = class_create(THIS_MODULE, "m74hc595");
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");
return 0;
}
int m74hc595_remove(struct spi_device *spi)
{
char buf[] = {0xf, 0x0};
spi_write(spi, buf, sizeof(buf));
//销毁设备节点
device_destroy(cls, MKDEV(major, 0));
class_destroy(cls);
//注销字符设备
unregister_chrdev(major, "m74hc595");
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");
应用层代码
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int i, j;
char msg[2] = {};
char buf[4] = {0x1, 0x2, 0x4, 0x8};
char num[10] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7f, 0x6F};
int fd = open("/dev/m74hc595", O_RDWR);
if (fd < 0)
{
printf("open err\n");
exit(-1);
}
printf("打开设备文件成功\n");
for (i = 0, j = 0;; i = (i + 1) % 10, j = (j + 1) % 4)
{
msg[0] = buf[j];
msg[1] = num[i];
write(fd, msg, sizeof(msg));
sleep(1);
}
return 0;
}