Skip to content

Commit

Permalink
Test LED in Nim
Browse files Browse the repository at this point in the history
  • Loading branch information
lupyuen committed Dec 25, 2023
1 parent 6912373 commit 36bd4aa
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 6 deletions.
7 changes: 5 additions & 2 deletions examples/hello/hello_main.c
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ int main(int argc, FAR char *argv[])
if (fd < 0)
{
int errcode = errno;
printf("ERROR: Failed to open %s: %d\n",
CONFIG_EXAMPLES_LEDS_DEVPATH, errcode);
printf("ERROR: Failed to open /dev/userleds: %d\n",
errcode);
return EXIT_FAILURE;
}

Expand Down Expand Up @@ -78,5 +78,8 @@ int main(int argc, FAR char *argv[])
return EXIT_FAILURE;
}

// Close the LED Driver
close(fd);

return 0;
}
44 changes: 40 additions & 4 deletions examples/hello_nim/hello_nim_async.nim
Original file line number Diff line number Diff line change
@@ -1,19 +1,55 @@
import std/strformat ## String Formatting

## Import ioctl() from C
## Import Standard Functions from C.
## Based on /home/vscode/.choosenim/toolchains/nim-#devel/lib/std/syncio.nim
proc c_open(filename: cstring, mode: cint): cint {.
importc: "open", nodecl.}
proc c_close(fd: cint): cint {.
importc: "close", nodecl.}
proc c_ioctl(fd: cint, request: cint): cint {.
importc: "ioctl", header: "<sys/ioctl.h>", varargs.}
proc c_usleep(usec: cuint): cint {.
importc: "usleep", nodecl.}
var O_WRONLY {.importc: "O_WRONLY", header: "<fcntl.h>".}: cint
var ULEDIOC_SETALL {.importc: "ULEDIOC_SETALL", header: "<nuttx/leds/userled.h>".}: cint

proc blink_led() =
## Open the LED driver
echo "Opening /dev/userleds"
var fd = c_open("/dev/userleds", O_WRONLY)
if fd < 0:
echo "Failed to open /dev/userleds"
return

## Turn on LED
echo "Set LED 0 to 1"
var ret = c_ioctl(fd, ULEDIOC_SETALL, 1)
if ret < 0:
echo "ioctl(ULEDIOC_SETALL) failed"
return

## Sleep a while
echo "Waiting..."
discard c_usleep(500 * 1000)

## Turn on LED
echo "Set LED 0 to 0"
ret = c_ioctl(fd, ULEDIOC_SETALL, 0)
if ret < 0:
echo "ioctl(ULEDIOC_SETALL) failed"
return

## Close the LED Driver
discard c_close(fd)

## Main Function in Nim
proc hello_nim() {.exportc, cdecl.} =

## Print something
echo "Hello Nim!"

## Test ioctl
var ret = c_ioctl(0, 0)
echo &"ret={ret}"
## Blink the LED
blink_led()

## Finish
## waitFor launch()
Expand Down

0 comments on commit 36bd4aa

Please sign in to comment.