【MYD-JX8MMA7】 (二)GPIO控制-Python&C
一、C语言LED
1.程序代码
/* Copyright 2018 Tronlong Elec. Tech. Co. Ltd. All Rights Reserved. */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <getopt.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <libgen.h>
/* Get array size */
#define ARRAY_SIZE(array) sizeof(array) / sizeof(array[0])
/* User-operable LEDs */
static char *g_leds[] = {
"/sys/class/leds/user1",
"/sys/class/leds/user1",
"/sys/class/leds/user1",
"/sys/class/leds/user1"
};
/* Exit flag */
volatile bool g_quit = false;
/* Short option names */
static const char g_shortopts [] = ":n:vh";
/* Option names */
static const struct option g_longopts [] = {
{ "number", required_argument, NULL, 'n' },
{ "version", no_argument, NULL, 'v' },
{ "help", no_argument, NULL, 'h' },
{ 0, 0, 0, 0 }
};
static void usage(FILE *fp, int argc, char **argv) {
fprintf(fp,
"Usage: %s [options]\n\n"
"Options:\n"
" -n | --number Number of LEDs, range of 1 to 4 \n"
" -v | --version Display version information\n"
" -h | --help Show help content\n\n"
"", basename(argv[0]));
}
static void opt_parsing_err_handle(int argc, char **argv, int flag) {
/* Exit if no input parameters are entered */
int state = 0;
if (argc < 2) {
printf("No input parameters are entered, please check the input.\n");
state = -1;
} else {
/* Feedback Error parameter information then exit */
if (optind < argc || flag) {
printf("Error: Parameter parsing failed\n");
if (flag)
printf("\tunrecognized option '%s'\n", argv[optind-1]);
while (optind < argc) {
printf("\\tunrecognized option '%s'\\n", argv[optind++]);
}
state = -1;
}
}
if (state == -1) {
printf("Tips: '-h' or '--help' to get help\\n\\n");
exit(EXIT_FAILURE);
}
}
void sig_handle(int arg) {
g_quit = true;
}
int main(int argc, char **argv) {
int i = 0;
int c = 0;
int num = 0;
int flag = 0;
char cmd[64] = {0};
/* Parsing input parameters */
while ((c = getopt_long(argc, argv, g_shortopts, g_longopts, NULL)) != -1) {
switch (c) {
case 'n':
num = atoi(optarg);
break;
case 'v':
/* Display the version */
printf("version : 1.0\\n");
exit(EXIT_SUCCESS);
case 'h':
usage(stdout, argc, argv);
exit(EXIT_SUCCESS);
default :
flag = 1;
break;
}
}
opt_parsing_err_handle(argc, argv, flag);
/* Check if the number of LEDs is out of preset range */
if ((num > ARRAY_SIZE(g_leds)) || (num < 1)) {
printf("Error: The number of LEDs entered exceeds the preset range(1-4)\\n");
exit(EXIT_FAILURE);
}
/* Ctrl+c handler */
signal(SIGINT, sig_handle);
/* Print LEDs */
printf("\\nSystem leds :\\n");
system("find /sys/class/leds/*");
printf("\\nFlashing leds :\\n");
for (i = 0; i < num; i++)
printf("%s\\n",g_leds[i]);
while (!g_quit) {
/* Turn on LEDs */
for (i = 0; i < num; i++) {
/* Set the LED brightness value to 1 to turn on the led */
snprintf(cmd, 64, "echo 1 > %s/brightness", g_leds[i]);
if (system(cmd) != 0) {
fprintf(stderr, "Error: Failed to turn on %s\\n", g_leds[i]);
exit(EXIT_FAILURE);
}
}
/* Keep the LEDs on for 500 ms */
usleep(500 * 1000);
/* Turn off LEDs */
for (i = 0; i < num; i++) {
/* Set the LED brightness value to 0 to turn off the LED */
snprintf(cmd, 64, "echo 0 > %s/brightness", g_leds[i]);
if (system(cmd) != 0) {
fprintf(stderr, "Error: Failed to turn off %s\\n", g_leds[i]);
exit(EXIT_FAILURE);
}
}
/* Keep the LEDs off for 500 ms */
usleep(500 * 1000);
}
printf("Exit\\n");
return 0;
}
2、makefile 代码
tl_led_flash:tl_led_flash.c
(CC) -Wall < -o $@
clean:
rm -f tl_led_flash *.o *~
install:
cp tl_led_flash $(PREFIX)
2.将代码文件和makefile文件上传到开发板
3.LED引脚查看
因为开发应用程序需要知道系统内LED的定义
4.代码编译和运行
5.开发板上蓝色LED正常按设计交替闪烁。
二、Python代码
1.python代码
Python代码文件尾椎是.py,python代码属于脚本文件,所以不用在进行编译,相对很方便。
#!/usr/bin/env python3
'''
[url=home.php?mod=space&uid=1455510]@file[/url] : tl_led_flash.py
[url=home.php?mod=space&uid=26400]@TIME[/url] : 2020/04/26 09:05:54
[url=home.php?mod=space&uid=284375]@desc[/url] : None
'''
import signal, time
import os, sys, getopt
version = "1.0"
class Led(object):
quit_flag = False
def __init__(self, led_path):
self.led_path = led_path # Led path
self.leds = [] # Save the led found
""" enumerate all led """
def enumerate_led(self):
led_name = "user1"
""" find led """
for filename in os.listdir(self.led_path):
if led_name in filename:
self.leds.append(os.path.join(self.led_path, filename))
if len(self.leds) == 0:
return False
"""
led sort, e.g.
/sys/class/leds/user-led0
/sys/class/leds/user-led1
/sys/class/leds/user-led2
"""
self.leds.sort()
print ("find leds:")
for led in self.leds:
print (led)
return True
""" control led flash """
def flash_led(self):
led_num = len(self.leds)
while not Led.quit_flag:
""" Turn on leds """
for i in range(led_num):
""" Set the led brightness value to 1 to turn on the led """
ret = os.system("echo 1 > %s/brightness" % (self.leds[i]))
if ret != 0:
print ("Error: Failed to turn on %s" % self.leds[i])
""" Keep the leds on for 500 ms """
time.sleep(0.5)
for i in range(led_num):
""" Set the led brightness value to 0 to turn off the LED """
os.system("echo 0 > %s/brightness" % (self.leds[i]))
""" Keep the leds off for 500 ms """
time.sleep(0.5)
@classmethod
def stop(cls):
cls.quit_flag = True
def sig_handle(signum, frame):
print ("ctrl + c ...")
Led.stop()
def usage():
print ("Usage: %s [options]\n"
"Options: \n"
" -v | --version Display version information\n"
" -h | --help Display help\n"
% sys.argv[0])
if name == ' main ':
""" parse parameter """
try:
options, remainder = getopt.getopt(sys.argv[1:], 'vh', ['version', 'help'])
for opt, arg in options:
if opt in ('-v', '--version'):
print ('version: %s' % version)
exit(0)
elif opt in('-h', '--help'):
usage()
exit(0)
except getopt.GetoptError as err:
print ('ERROR: %s' % err)
exit(1)
""" Ctrl+c handler """
signal.signal(signal.SIGINT, sig_handle)
led = Led("/sys/class/leds/")
""" enumerate all led """
ret = led.enumerate_led()
""" can not find led """
if not ret:
print ("can not find led!")
exit(3)
""" control flash all led """
print ("\\nflash led ...")
led.flash_led()
2.代码上传至开发板
3.运行python文件
4.实际效果
蓝色LED指示灯交替闪烁。。。
更多回帖