Linux设备驱动程序学习(1)

(嵌入式软件设计)驱动程序 1、 完成Demo虚拟驱动程序 demo.c #include #include #include #include /* everything... */ #include /* COPY_TO_USER */ #define DEVICE_NAME "demo" #define demo_MAJOR 249 #define demo_MINOR 0 #define MAX_BUF_LE 阅读详情
今天进入《Linux设备驱动程序(第3版)》 第三章字符设备驱动程序的学习。
这一章主要通过介绍字符设备scull(Simple Character Utility for Loading Localities,区域装载的简单字符工具)的
驱动程序编写,来学习Linux设备驱动的基本知识。scull可以为真正的设备驱动程序提供样板。


一、主设备号和此设备号
主设备号表示设备对应的驱动程序;次设备号由内核使用,用于正确确定设备文件所指的设备。
内核用dev_t类型(<linux/types.h>)来保存设备编号,dev_t是一个32位的数,12位表示主设备号,20为表示次设备号。
在实际使用中,是通过<linux/kdev_t.h>中定义的宏来转换格式。
 (dev_t)-->主设备号、次设备号 MAJOR(dev_t dev)
 MINOR(dev_t dev)
 主设备号、次设备号-->(dev_t) MKDEV(int major,int minor) 

建立一个字符设备之前,驱动程序首先要做的事情就是获得设备编号。其这主要函数在<linux/fs.h>中声明:

int register_chrdev_region(dev_t first, unsigned int count,
char *name);   //指定设备编号

int alloc_chrdev_region(dev_t *dev, unsigned int firstminor,
unsigned int count, char *name);   //动态生成设备编号

void unregister_chrdev_region(dev_t first, unsigned int count)
;      //释放设备编号


分配之设备号的最佳方式是:默认采用动态分配,同时保留在加载甚至是编译时指定主设备号的余地。

以下是在scull.c中用来获取主设备好的代码:

if (scull_major) {
    dev = MKDEV(scull_major, scull_minor);
    result = register_chrdev_region(dev, scull_nr_devs, "scull");
} else {
    result = alloc_chrdev_region(&dev, scull_minor, scull_nr_devs,"scull");
    scull_major = MAJOR(dev);
}
if (result < 0) {
    printk(KERN_WARNING "scull: can't get major %d/n", scull_major);
    return result;
}


在这部分中,比较重要的是在用函数获取设备编号后,其中的参数name是和该编号范围关联的设备名称,它将出现在/proc/devices和sysfs中。

看到这里,就可以理解为什么mdev和udev可以动态、自动地生成当前系统需要的设备文件。
udev就是通过读取
sysfs下的信息来识别硬件设备的.
(请看《
理解和认识udev》
URL:http://blog.chinaunix.net/u/6541/showart_396425.html)

 


 

二、一些重要的数据结构
大部分基本的驱动程序操作涉及及到三个重要的内核数据结构,分别是file_operations、file和inode,它们的定义都在
<linux/fs.h>。

 


 

三、字符设备的注册

内核内部使用struct cdev结构来表示字符设备。在内核调用设备的操作之前,必须分配并注册一个或多个struct cdev。代码应包含<linux/cdev.h>,它定义了struct cdev以及与其相关的一些辅助函数。

注册一个独立的cdev设备的基本过程如下:

1、为struct cdev 分配空间(如果已经将struct cdev 嵌入到自己的设备的特定结构体中,并分配了空间,这步略过!)

struct cdev *my_cdev = cdev_alloc();

2、初始化struct cdev

void cdev_init(struct cdev *cdev, const struct file_operations *fops)

3、初始化cdev.owner

cdev.owner = THIS_MODULE;

4、cdev设置完成,通知内核struct cdev的信息(在执行这步之前必须确定你对struct cdev的以上设置已经完成!)

int cdev_add(struct cdev *p, dev_t dev, unsigned count)

从系统中移除一个字符设备:void cdev_del(struct cdev *p)

以下是scull中的初始化代码(之前已经为struct scull_dev 分配了空间):

/*
 * Set up the char_dev structure for this device.
 */

static void scull_setup_cdev(struct scull_dev *dev, int index)
{
    int err, devno = MKDEV(scull_major, scull_minor + index);
    
    cdev_init(&dev->cdev, &scull_fops);
    dev->cdev.owner = THIS_MODULE;
    dev->cdev.ops = &scull_fops; 
 //这句可以省略,在cdev_init中已经做过
    err = cdev_add (&dev->cdev, devno, 1);
    /* Fail gracefully if need be 这步值得注意*/
    if (err)
        printk(KERN_NOTICE "Error %d adding scull%d", err, index);
}


四、scull模型的内存使用

 

以下是scull模型的结构体:

/*
 * Representation of scull quantum sets.
 */

struct scull_qset {
    void **data;
    struct scull_qset *next;
};

struct scull_dev {
    struct scull_qset *data; /* Pointer to first quantum set */
    int quantum; /* the current quantum size */
    int qset; /* the current array size */
    unsigned long size; /* amount of data stored here */
    unsigned int access_key; /* used by sculluid and scullpriv */
    struct semaphore sem; /* mutual exclusion semaphore */
    struct cdev cdev;     /* Char device structure        */
};

scull驱动程序引入了两个Linux内核中用于内存管理的核心函数,它们的定义都在<linux/slab.h>:

void *kmalloc(size_t size, int flags);
void kfree(void *ptr);

以下是scull模块中的一个释放整个数据区的函数(类似清零),将在scull以写方式打开和scull_cleanup_module中被调用:

int scull_trim(struct scull_dev *dev)
{
  struct scull_qset *next, *dptr;
     int qset = dev->qset; /* 量子集中量子的个数*/
     int i;
     for (dptr = dev->data; dptr; dptr = next) { /* 循环scull_set个数次,直到dptr为NULL为止。*/
         if (dptr->data) {
               for (i = 0; i < qset; i++
)/* 循环一个量子集中量子的个数次*/
                    kfree(dptr->data[i]);/* 释放其中一个量子的空间*/

               kfree(dptr->data);/* 释放当前的scull_set的量子集的空间*/
               dptr->data = NULL;/* 释放一个scull_set中的void **data指针*/
          }
      next = dptr->next; /* 准备下个scull_set的指针*/

      kfree(dptr);/* 释放当前的scull_set*/
      }
  dev->size = 0; /* 当前的scull_device所存的数据为0字节*/

  dev->quantum = scull_quantum;/* 初始化一个量子的大小*/
  dev->qset = scull_qset;/* 初始化一个量子集中量子的个数*/
  dev->data = NULL;/* 释放当前的scull_device的struct scull_qset *data指针*/
  return 0;
}

以下是scull模块中的一个沿链表前行得到正确scull_set指针的函数,将在read和write方法中被调用:

/*Follow the list*/
struct scull_qset *scull_follow(struct scull_dev *dev, int n)
{
    struct scull_qset *qs = dev->data;
        /* Allocate first qset explicitly if need be */
    if (! qs) {
        qs = dev->data = kmalloc(sizeof(struct scull_qset), GFP_KERNEL);
        if (qs == NULL)
            return NULL; /* Never mind */
        memset(qs, 0, sizeof(struct scull_qset));
    }
    /* Then follow the list */
    while (n--) {
        if (!qs->next) {
            qs->next = kmalloc(sizeof(struct scull_qset), GFP_KERNEL);
            if (qs->next == NULL)
                return NULL; /* Never mind */
            memset(qs->next, 0, sizeof(struct scull_qset));
        }
        qs = qs->next;
        continue;
    }
    return qs;
}

其实这个函数的实质是:如果已经存在这个scull_set,就返回这个scull_set的指针。如果不存在这个scull_set,一边沿链表为scull_set分配空间一边沿链表前行,直到所需要的scull_set被分配到空间并初始化为止,就返回这个scull_set的指针。

 


五 、open和release

 

open方法提供给驱动程序以初始化的能力,为以后的操作作准备。应完成的工作如下:

(1)检查设备特定的错误(如设备未就绪或硬件问题);

(2)如果设备是首次打开,则对其进行初始化;

(3)如有必要,更新f_op指针;

(4)分配并填写置于filp->private_data里的数据结构。

而根据scull的实际情况,他的open函数只要完成第四步(将初始化过的struct scull_dev dev的指针传递到filp->private_data里,以备后用)就好了,所以open函数很简单。但是其中用到了定义在<linux/kernel.h>中的container_of宏,源码如下:

#define container_of(ptr, type, member) ({            /
    const typeof( ((type *)0)->member ) *__mptr = (ptr);    /
    (type *)( (char *)__mptr - offsetof(type,member) );})

其实从源码可以看出,其作用就是:通过指针ptr,获得包含ptr所指向数据(是member结构体)的type结构体的指针。即是用指针得到另外一个指针。

release方法提供释放内存,关闭设备的功能。应完成的工作如下:

(1)释放由open分配的、保存在file->private_data中的所有内容;

(2)在最后一次关闭操作时关闭设备。

由于前面定义了scull是一个全局且持久的内存区,所以他的release什么都不做。

 


六、read和write

 

 read和write方法的主要作用就是实现内核与用户空间之间的数据拷贝。因为Linux的内核空间和用户空间隔离的,所以要实现数据拷贝就必须使用在<asm/uaccess.h>中定义的:

unsigned long copy_to_user(void __user *to,
                           const void *from,
                           unsigned long count);
unsigned long copy_from_user(void *to,
                             const void __user *from,
                             unsigned long count);

而值得一提的是以上两个函数和

#define __copy_from_user(to,from,n)    (memcpy(to, (void __force *)from, n), 0)
#define __copy_to_user(to,from,n)    (memcpy((void __force *)to, from, n), 0)

之间的关系:通过源码可知,前者调用后者,但前者在调用前对用户空间指针进行了检查。

至于read和write 的具体函数比较简单,就在实验中验证好了。

 

 


 

七、模块实验


这次模块实验的使用是友善之臂SBC2440V4,使用Linux2.6.22.2内核。

模块程序链接:scull模块源程序
模块测试程序链接:模块测试程序

测试结果:

量子大小为6:

[Tekkaman2440@SBC2440V4]#cd /lib/modules/ [Tekkaman2440@SBC2440V4]#insmod scull.ko scull_quantum=6

[Tekkaman2440@SBC2440V4]#cat /proc/devices
Character devices:
  1 mem
  2 pty
  3 ttyp
  4 /dev/vc/0
  4 tty
  4 ttyS
  5 /dev/tty
  5 /dev/console
  5 /dev/ptmx
  7 vcs
 10 misc
 13 input
 14 sound
 81 video4linux
 89 i2c
 90 mtd
116 alsa
128 ptm
136 pts
180 usb
189 usb_device
204 s3c2410_serial
252 scull
253 usb_endpoint
254 rtc

Block devices:
  1 ramdisk
256 rfd
  7 loop
 31 mtdblock
 93 nftl
 96 inftl
179 mmc
[Tekkaman2440@SBC2440V4]#mknod -m 666 scull0 c  252 0
[Tekkaman2440@SBC2440V4]#mknod -m 666 scull1 c  252 1
[Tekkaman2440@SBC2440V4]#mknod -m 666 scull2 c  252 2
[Tekkaman2440@SBC2440V4]#mknod -m 666 scull3 c  252 3


启动测试程序

[Tekkaman2440@SBC2440V4]#./scull_test

write error! code=6

write error! code=6

write error! code=6

write ok! code=2

read error! code=6

read error! code=6

read error! code=6

read ok! code=2

[0]=0 [1]=1 [2]=2 [3]=3 [4]=4

[5]=5 [6]=6 [7]=7 [8]=8 [9]=9

[10]=10 [11]=11 [12]=12 [13]=13 [14]=14

[15]=15 [16]=16 [17]=17 [18]=18 [19]=19


改变量子大小为默认值4000:
[Tekkaman2440@SBC2440V4]#cd /lib/modules/
[Tekkaman2440@SBC2440V4]#rmmod scull
[Tekkaman2440@SBC2440V4]#insmod scull.ko


启动测试程序
[Tekkaman2440@SBC2440V4]#./scull_test
write ok! code=20
read ok! code=20
[0]=0 [1]=1 [2]=2 [3]=3 [4]=4
[5]=5 [6]=6 [7]=7 [8]=8 [9]=9
[10]=10 [11]=11 [12]=12 [13]=13 [14]=14
[15]=15 [16]=16 [17]=17 [18]=18 [19]=19

[Tekkaman2440@SBC2440V4]#   

改变量子大小为6,量子集大小为2:
[Tekkaman2440@SBC2440V4]#cd /lib/modules/
[Tekkaman2440@SBC2440V4]#rmmod scull
[Tekkaman2440@SBC2440V4]#insmod scull.ko scull_quantum=6 scull_qset=2

启动测试程序
[Tekkaman2440@SBC2440V4]#./scull_test
write error! code=6
write error! code=6
write error! code=6
write ok! code=2
read error! code=6
read error! code=6
read error! code=6
read ok! code=2
[0]=0 [1]=1 [2]=2 [3]=3 [4]=4
[5]=5 [6]=6 [7]=7 [8]=8 [9]=9
[10]=10 [11]=11 [12]=12 [13]=13 [14]=14
[15]=15 [16]=16 [17]=17 [18]=18 [19]=19
              

 

实验不仅测试了模块的读写能力,还测试了量子读写是否有效。 
保姆级教程:用星宸科技SSD20x/21X的官方Demo快速上手嵌入式开发(含编译踩坑记录) 本文提供星宸科技SSD20x/21X嵌入式开发的保姆级教程,涵盖从Demo编译到功能验证的全流程。重点解析开发环境搭建、Demo编译实战中的常见问题及解决方案,包括交叉编译工具链选择、SDK版本兼容性等关键细节,帮助开发者快速上手并避开典型陷阱。 阅读详情

相关推荐

最简单的嵌入式字符设备驱动源代码和Makefile编译文件

最简单的嵌入式字符设备驱动源代码和Makefile编译文件

2021-09-13嵌入式学习笔记--基于C++的环形缓冲区demo

最近学习了韦东山老师的RTOS训练营相关的知识后想自己实现一下环形缓冲区,具体的实现如下: 注意: 缓冲区的大小要比实际的小一个! 我也是查了半天才知道的! 代码中对于未使用的空间写入了 -1 主要是方便查看,如果实际的应用中可以去掉 这一步 降低资源开销 // circleBuffer.h #ifndef _CIRCLE_BUFFER_H_ #define _CIRCLE_BUFFER_H_ #include <stdio.h> #include <cstdio> #in

jeason的博客 771

嵌入式学习之QT学习---14 QT跨平台运行之把QT程序交叉编译到ARM开发板

想要把qt工程放到开发板上运行,就需要用到交叉编译。由于qt是跨平台的,所以只需要换个编译器编译一下就可以。 以“定时器”的例子为例,在移植之前还需要进行一个准备工作,在windows下运行的时候,电脑屏幕很大,但是运行的窗口只有一点点大,开发板也有外接屏幕,如何让运行窗口自动适配开发板的外接屏幕呢?令其占满屏幕显示,而不是一小块。 第一步:需要设置一下,先给ui布局,如果不布局,控件就不会随着屏幕的大小的变化而变化。 第二步:利用代码来获取屏幕的大小,给widget.cpp文件下添加如下代码 #inclu

qq_42822743的博客 5459

分享一个嵌入式中Makefile的通用Demo

国庆在家事情比较少,之前因为稍微学了点Makefile的基本语法,所以就想着自己写个Makefile,一来以后自己作参考,二来也是可以复习下之前的一些命令,三来就是分享啦~,哈哈。

weixin_46582567的博客 857

计算机模拟爆破过程,基于LSDYNA岩石爆破模拟建模分析

原标题:基于LSDYNA岩石爆破模拟建模分析 Ls Dyna岩石爆破模拟仿真作者:dyna_focus擅长领域:dyna/abaqus/hypermesh一、 数值模型的建立1.1 单元及算法的选择岩石,炸药,空气都采用solid164实体单元。岩石采用常应力实体单元,该种单元属于纯粹的lagrange算法,该种算法单元网格附着在材料上,随着材料的流动而产生单元网格的变形,但是在结构变形巨大时,有...

weixin_29494379的博客 7317

健康保险费用预测:可解释机器学习在精算建模中的实战落地

健康保险费用预测是医疗AI与保险科技交叉领域的核心任务,本质是基于临床变量与社会因素对个体医疗支出进行风险量化。其技术原理需兼顾统计建模能力与监管可解释性,XGBoost+SHAP组合因支持特征归因、边际效应分析和临床可干预推演,成为保险精算场景的主流选择。该技术显著提升保费定价精度、降低偿付风险,并支撑DRG费用预警、团险核保辅助及再保险尾部风险评估等关键应用。本文聚焦真实产线中的时间序列验证、临床分层特征工程与监管红线指标(如Bias@90th、Calibration Slope),深入解析如何让模型不

weixin_33702545的博客 307

LVGL嵌入式GUI入门:从基础Demo到MVP架构实战

本文介绍了LVGL嵌入式图形库的基础使用和优化方案。主要内容包括:1)LVGL核心概念和基础Demo实现;2)原生开发的痛点分析,如代码耦合度高、维护困难等;3)提出MVP分层架构解决方案,详细说明视图层、模型层和调度层的分工;4)介绍帧动画实现方法,包括图片资源工程化处理和自动转换脚本。通过LVGL+MVP架构+资源自动化处理的组合方案,可有效解决嵌入式GUI开发中的代码混乱问题,提升项目的可维护性和开发效率。

LinuxRos 1059

PADS安装教程(超详细)

声明:个人实践 一、工具准备 pads9.5完整破解版百度网盘提取码【wjx9】 链接:https://pan.baidu.com/s/1pIP6BJO435ssmF7Hjwyz8A 提取码:wjx9 安装环境:win10 64位 二、开始解压安装 关闭杀毒,exe以管理员身份运行 点击【skip】,不然又得licese 点击【agree】 点击【modify】 设置安装的工具、路径及工程路径 设置完成后,开始【install】 在之后注册。 将Crack复制到PADS安装目录

qq_42057393的博客 5万+

linux设备驱动程序简介,Linux设备驱动程序学习----1.设备驱动程序简介

设备驱动程序简介1. 简介Linux系统的优点是,系统内部实现细节对所有人都是公开的。Linux内核由大量复杂的代码组成,设备驱动程序可以作为进入Linux内核世界大门的切入口。设备驱动程序在Linux内核中,是一个个独立的黑盒子,在调用内部接口时某个特定硬件做出响应,这些接口隐藏了设备的工作细节。用户的操作通过独立于特定驱动程序的一组标准化调用执行,将这些调用映射到作用于实际硬件的设备特有操作上...

weixin_39783156的博客 209

Python-自动化绘制股票价格通道线

创建更强大、更可靠的价格通道检测算法。

探索人工智能领域 950

【Py/Java/C++/C/JS/Go六种语言OD独家2024E卷真题】20天拿下华为OD笔试之【固定滑窗】2024E-考勤信息【欧弟算法】全网注释最详细分类最全的华为OD真题题解

可上练习华子OD、大厂真题绿色聊天软件戳oj1441了解算法冲刺训练(备注【优快云】否则不通过)

weixin_48157259的博客 621

Linux设备驱动程序学习----1.设备驱动程序简介

设备驱动程序简介 更多内容请参考Linux设备驱动程序学习----目录 1. 简介   Linux系统的优点是,系统内部实现细节对所有人都是公开的。Linux内核由大量复杂的代码组成,设备驱动程序可以作为进入Linux内核世界大门的切入口。   设备驱动程序在Linux内核中,是一个个独立的黑盒子,在调用内部接口时某个特定硬件做出响应,这些接口隐藏了设备的工作细节。用户的操作通过独立于特定驱动程序...

micro虾米的博客 265

无线通信技术及其在机器人中的应用

本文系统阐述了无线通信技术在机器人领域的应用框架与技术选型。首先构建了无线通信的三层理论架构:物理层解决信号传输问题,链路层处理接入控制,网络层实现组网管理。随后详细分析了主流无线技术的特性与适用场景:BLE适用于低功耗传感器节点,Wi-Fi适合高带宽视频传输,5G专网满足工业AGV的广域覆盖需求,星闪技术凭借20μs超低时延和4096台并发连接能力,为高端机器人应用提供突破性解决方案。通过鄂尔多斯隆基5G专网等典型案例,验证了5G在工业AGV规模化部署中的优势,并展望了通感算智融合、星闪+5G协同等未来发

weiyvyy的博客 1117

Linux设备驱动程序学习1-环境搭建和第三章学习

在这里是按照百度里面“小爱程序员”的相关文章进行环境搭建,搭建完成之后运行第三章中scull程序,没有问题。 环境搭建系列文章: linux设备驱动程序(LDD3)环境搭建1 - vmware虚拟机设置 linux设备驱动程序(LDD3)环境搭建2 - Ubuntu5.04的安装 linux设备驱动程序(LDD3)环境搭建3 - linux2.6.10的编译 linux设备驱动程序(LDD3)环境...

qq_40788950的博客 543

【深度学习新浪潮】Token经济学深度解析:从AI“新智元”梗到产业核心,研究成果+标杆产品全拆解

在正式深入研究和产品分析前,必须先破除概念误区:行业内常说的Token经济学,并非单一概念,而是分为AI词元Token经济学和Web3通证Token经济学两大核心分支,二者底层逻辑、应用场景天差地别,也是大众最容易混淆的点。Token是AI时代的新大宗商品:黄仁勋将Token类比为工业时代的电力、石油,是AI时代的核心生产资料与基础计价单位,不再是单纯的技术单元,而是具备标准化、可计量、可交易、可分层的数字商品,其价值由算力消耗、推理效率、实际应用价值共同决定,而非虚拟炒作。Token五层定价模型。

专注:太空算力、AI infra、异构调度、大模型成本工程 686

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Linux系统--设备驱动程序学习记录1

说明:以下是自己阅读《linux设备驱动程序》(美)科波特  部分章节的笔记 (《Linux Device Drivers 3rd》  Corbet Jonathan & Rubini Alessandro & Kroah-Hartman Greg) Chapter 1. 设备驱动程序简介 1)编程问题: 机制——需要提供什么功能               策略——如

南柯一梦 517

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

Linux设备驱动程序--学习笔记(1)

1.设备文件是OS对硬件设备的抽象,用户操作设备文件其实是内核调用驱动程序去操作实际硬件 ,实际的硬件设备通过驱动程序和内核交互 2.驱动程序跟内核和硬件交互,设备文件跟OS和用户交互,所以说驱动可以不用管设备文件的东西 3.模块初始化函数的任务就是为以后调用模块函数预先做准备 4.模块卸载前会调用模块的退出函数,退出函数必须撤销初始化函数所做的一切 5.内核函数头文件包含在usr/src

you_shou的博客 806

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

linux设备驱动程序-第六章1(ioctl操作)学习总结

一、前言 在第三章,我们已经构建了一个结构完整的可读写设备驱动程序。但一个实际可用的设备除了提供同步读取和写入之外,还会提供更多的功能。而现在我们拥有调试工具,掌握相关的调试方法,并且对并发问题有了坚实的理解。这样,构建更高级的驱动程序相对容易了。 在本节,我们实现ioctl系统调用,他用于设备控制的公共接口。 二、ioctl 除了读取和写入设备,大部分驱动程序还需要另外一种能力,即通过设备驱动程...

Feng_8071的博客 1224

Linux设备驱动程序学习(1)-字符设备驱动程序

Linux设备驱动程序学习(1)-字符设备驱动程序一、分配设备号   1、 对字符设备的访问是通过文件系统内的设备名称进行的(/dev/ttyS0)。在内核中,#include    dev_t  用来保存设备编号——包括主设备号和次设备号。由dev_t获得主次设备号:                         MAJOR(dev_t dev);           

robot_cn的专栏 607

Linux设备驱动程序学习(1)--字符设备驱动

本文一些内容转自《Linux 设备驱动程序》。 scull的设计         编写驱动程序的第一步就是定义驱动程序为用户程序提供的能力(机制)。而scull这个设备是内存的一部分,本文中主要着手实现这样的一个scull设备:由一个全局持久的内存区域组成。“全局”是指设备如果被多次打开,打开它的所有文件描述符可共享该设备所包含的数据;“持久”是指如果该设备关闭后再打开,则其中的数据不会丢失。

咕唧咕唧 725

Linux设备驱动程序学习(1) -字符设备驱动程序

Linux设备驱动程序学习(1) -字符设备驱动程序 今天进入《Linux设备驱动程序(第3版)》第三章字符设备驱动程序的学习。 这一章主要通过介绍字符设备scull(Simple Character Utility for Loading Localities,区域装载的简单字符工具)的驱动程序编写,来学习Linux设备驱动的基本知识。scull可以为真正的设备驱动程序提供样板。

tigerly的专栏 507

Linux设备驱动程序学习笔记1

系统linux2.6.32.2 +arm-linux-gcc 4.3.2  Hello World模块 #include #include static int hello_init(void) {  printk(KERN_ALERT"this is hel

aoxiang2012的专栏 299

linux设备驱动ioctl,Linux设备驱动程序学习(4)-高级字符驱动程序操作[(1)ioctl and llseek]...

Linux设备驱动程序学习(4)-高级字符驱动程序操作[(1)ioctland llseek]Linux设备驱动程序学习(4)-高级字符驱动程序操作[(1)ioctl and llseek]今天进入《Linux设备驱动程序(第3版)》第六章高级字符驱动程序操作的学习。一、ioctl大部分设备除了读写能力,还可进行超出简单的数据传输之外的操作,所以设备驱动也必须具备进行各种硬件控制操作的能力. 这些...

weixin_36378771的博客 163
上一篇: Linux设备驱动程序学习(0)
下一篇: Linux设备驱动程序学习(2)-调试技术
Slancer
博客等级 码龄21年 41粉丝 1原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值