LINUX学习笔记:(1)编写应用程序
宿主机 : 虚拟机 Ubuntu 16.04 LTS / X64
目标板[底板]: Tiny4412SDK - 1506
目标板[核心板]: Tiny4412 - 1412
LINUX内核: 4.12.0
交叉编译器: arm-none-linux-gnueabi-gcc(gcc version 4.8.3 20140320)
日期: 2018-2-28 19:23:15
作者: SY
简介
本章节主要介绍如何编写应用程序运行在基于 ARM
的 Linux
上。对于 Linux
来说一切设备皆文件,比如开发板上的 LED
,在驱动程序中可以设定文件名为 LED
,存放在 /dev
目录中。可以使用 open
、ioctl
等函数读写。
APP
led.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#define CMD_LED_ON (0)
#define CMD_LED_OFF (1)
#define DEVICE_PATH "/dev/LED"
static void usage( const char *module_name )
{
printf("usage:\n");
printf("%s <led_num> <on/off>\n",module_name);
printf("led_num = 1, 2, 3, 4\n");
}
enum
{
DEVICE_OFF = 0,
DEVICE_ON,
DEVICE_ERR,
};
int main(int argc, char **argv)
{
int fd;
int led_num;
int device_status = DEVICE_ERR;
if (argc != 3) {
goto exception;
}
sscanf(argv[1],"%d",&led_num);
led_num -= 1;
if (strcmp(argv[2],"on") == 0) {
device_status = DEVICE_ON;
} else if (strcmp(argv[2],"off") == 0) {
device_status = DEVICE_OFF;
}
if ( (led_num < 0) || (led_num > 3) || (device_status == DEVICE_ERR) ) {
goto exception;
}
fd = open(DEVICE_PATH,O_WRONLY);
if (fd < 0) {
printf("open %s error!\n",DEVICE_PATH);
return 1;
}
if (device_status == DEVICE_ON) {
ioctl(fd, CMD_LED_ON, led_num);
} else {
ioctl(fd, CMD_LED_OFF, led_num);
}
close(fd);
return 0;
exception:
{
usage(argv[0]);
return 1;
}
}
Makefile
Makefile
CC = arm-linux-gcc
CFLAGS = -Wall
TARGET = led
SOURCE = led.c
$(TARGET) : $(SOURCE)
$(CC) $(CFLAGS) -o $@ $<
clean:
rm -rf *.o $(TARGET)
编译
在当前目录下使用:
$ make
即可生成可执行文件 led
测试
将文件拷贝到开发板中:
$ ./led 1 on
LED1
打开。
$ ./led 2 off
LED2
关闭。