歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 自己動手寫最簡單的Android驅動---LED驅動的編寫

自己動手寫最簡單的Android驅動---LED驅動的編寫

日期:2017/3/1 10:34:20   编辑:Linux編程
開發平台:farsight s5pc100-a

內核:linux2.6.29

環境搭配:有博文介紹

開發環境:Ubuntu 、Eclipse

首先強調一下要點:

1.編寫Android驅動時,首先先要完成linux驅動,因為android驅動其實是在linux驅動基礎之上完成了HAL層(硬件抽象層),如果想要測試的話,自己也要編寫java程序來測試你的驅動。

2.android的根文件系統是eclair_2.1版本。我會上傳做好的根文件系統提供大家。這裡要說的是,android底層內核還是linux的內核,只是進行了一些裁剪。做好的linux內核鏡像,這個我也會上傳給大家。android自己做了一套根文件系統,這才是android自己做的東西。android事實上只是做了一套根文件系統罷了。

假設linux驅動大家都已經做好了。我板子上有四個燈,通過ioctl控制四個燈,給定不同的參數,點亮不同的燈。

相關文件下載:

本文源碼與Android根文件系統、內核zIamge下載

下載在Linux公社的1號FTP服務器裡,下載地址:

FTP地址:ftp://www.linuxidc.com

用戶名:www.linuxidc.com

密碼:www.muu.cc

在 2012年LinuxIDC.com\2月\自己動手寫最簡單的Android驅動---LED驅動的編寫

下載方法見 http://www.linuxidc.net/thread-1187-1-1.html

linux驅動代碼因平台不同而有所不同,這就不黏代碼了。

這是我測試linux驅動編寫的驅動,代碼如下:

[cpp]

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <string.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <sys/ioctl.h>
  9. #define LED_ON _IO ('k',1)
  10. #define LED_OFF _IO ('k',2)
  11. int main()
  12. {
  13. int i = 0;
  14. int dev_fd;
  15. dev_fd = open("/dev/led",O_RDWR);
  16. if ( dev_fd == -1 ) {
  17. printf("Cann't open file /dev/led\n");
  18. exit(1);
  19. }
  20. while(1)
  21. {
  22. ioctl(dev_fd,LED_ON,1);
  23. sleep(1);
  24. ioctl(dev_fd,LED_OFF,1);
  25. sleep(1);
  26. ioctl(dev_fd,LED_ON,2);
  27. sleep(1);
  28. ioctl(dev_fd,LED_OFF,2);
  29. sleep(1);
  30. ioctl(dev_fd,LED_ON,3);
  31. sleep(1);
  32. ioctl(dev_fd,LED_OFF,3);
  33. sleep(1);
  34. ioctl(dev_fd,LED_ON,4);
  35. sleep(1);
  36. ioctl(dev_fd,LED_OFF,4);
  37. sleep(1);
  38. }
  39. return 0;
  40. }

下面開始把linux驅動封裝成android驅動。

首先介紹一下android驅動用到的三個重要的結構體,

struct hw_module_t;

struct hw_device_t;

struct hw_module_methods_t;

android源碼裡面結構體的聲明

[cpp]
  1. typedef struct hw_module_t {
  2. uint 32_t tag;
  3. uint16_t version_major;
  4. uint16_t version_minor;
  5. const char *id;
  6. const char *name;
  7. const char *author;
  8. const hw_module_methods_t *methods;
  9. void* dso;
  10. uint32_t reserved[32-7];
  11. } hw_module_t;

[cpp]

  1. typedef struct hw_device_t {
  2. uint32_t tag;
  3. uint32_t version;
  4. struct hw_module_t* module;
  5. uint32_t reserved[12];
  6. int (*close) (struct hw_device_t *device);
  7. }hw_device_t;

[cpp]

  1. typedef struct hw_module_methods_t {
  2. int (*open) (const struct hw_module_t *module, const char *id,
  3. struct hw_device_t **device);
  4. } hw_module_methods_t;

我們經常會用到這三個結構體。

android驅動目錄結構:

led

|--- hal

| |----jni

| |----- Android.mk

| |----com_farsgiht_server_ledServer.cpp

| |----stub

| |---- include

| | |-----led.h

| |-----module

| |-----Android.mk

| |-----led.c

|--- linux_drv

Copyright © Linux教程網 All Rights Reserved