天天看點

LINUX學習筆記:(1)編寫應用程式LINUX學習筆記:(1)編寫應用程式

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 = ,
    DEVICE_ON,
    DEVICE_ERR,
};

int main(int argc, char **argv)
{
    int fd;
    int led_num;
    int device_status = DEVICE_ERR; 

    if (argc != ) {
        goto exception;
    }

    sscanf(argv[],"%d",&led_num);
    led_num -= ;   

    if (strcmp(argv[],"on") == ) {
        device_status = DEVICE_ON;
    } else if (strcmp(argv[],"off") == ) {
        device_status = DEVICE_OFF;
    }

    if ( (led_num < ) || (led_num > ) ||  (device_status == DEVICE_ERR) ) {
        goto exception;
    }

    fd = open(DEVICE_PATH,O_WRONLY);
    if (fd < ) {
        printf("open %s error!\n",DEVICE_PATH);

        return ;
    }

    if (device_status == DEVICE_ON) {
        ioctl(fd, CMD_LED_ON, led_num);
    } else {
        ioctl(fd, CMD_LED_OFF, led_num);
    }

    close(fd);

    return ;

exception:
{
    usage(argv[]);

    return ;
}

}
           

Makefile

Makefile

CC          = arm-linux-gcc
CFLAGS      = -Wall

TARGET      = led
SOURCE      = led.c

$(TARGET) : $(SOURCE)
    $(CC) $(CFLAGS) -o [email protected] $<

clean:
    rm -rf *.o $(TARGET)
           

編譯

在目前目錄下使用:

$ make 
           

即可生成可執行檔案

led

測試

将檔案拷貝到開發闆中:

$ ./led  on
           

LED1

打開。

$ ./led  off
           

LED2

關閉。

繼續閱讀