PIC microcontroller development on FreeBSD

Tags:  bsd · programming

Prerequisites

sdcc is a C compiler for microprocessors. It says that PIC microprocessors are unmaintained, but I’ve found it to be pretty reliable so far (take this with a grain of salt, I’m no expert). The port can be found under:

lang/sdcc

Page 75 of the sdcc user manual lists the supported PIC devices. Header files can be found under /usr/local/share/sdcc.

For programming the MCU, I’ve found pk2cmd to work alright with PICKit2 (or Chinese clones), but there’s no port for FreeBSD anymore. The Makefile won’t install files properly, so we have some extra work to do afterwards:

$ git clone https://github.com/psmay/pk2cmd.git
$ cd pk2cmd/pk2cmd
# gmake freebsd install clean
# mv /usr/share/pk2/PK2DeviceFile.dat /usr/local/bin
# rm -rf /usr/share/pk2

Supported devices for pk2cmd are listed here.

Detecting and programming the MCU

Avoid using just the -P option to auto-detect the MCU, as the VPP the PICKit2 applies to the chip trying to detect it can damage the MCU. Instead, use the chip number beforehand as shown below. Also, use the -C option to check if the chip is blank.

If any of the following pk2cmd commands fail, make sure everything really is wired properly:

$ pk2cmd -P PIC16F877A -C
Device is blank

Operation Succeeded

Compile your source code. The target executable is the .hex file sdcc will output. Replace pic14 and 16f877a with the appropriate names for your device:

$ sdcc --use-non-free -mpic14 -p16f877a main.c

Erase the PIC (if it wasn’t already blank) and flash the new code. Again, use the appropriate names:

$ pk2cmd -P PIC16F877A -E
$ pk2cmd -P PIC16F877A -X -M -F main.hex

If all went well, you should get an output similar to this:

PICkit 2 Program Report
23-1-2022, 21:01:29
Device Type: PIC16F877A

Program Succeeded.

Operation Succeeded