This post summarises the process of developing a new program for a PIC18F under Linux and downloading it onto the microcontroller.
- Firstly, download the Linux version of XC8 from microchip.com and install it. Accept all default options. When it asks for a registration key, just leave it blank to install the free version.
- Secondly, download the Linux version of the pk2cmd utility that matches your Linux kernel version. You’ll need to scroll down to the “Downloads” section of that page and look for the “Linux & Mac OS X Software” sub-section. The one I downloaded was titled “PK2CMD V1.20 Linux Kernel 2.6 Executable Binary”.
This is a simple C example program to try out the XC8 compiler.
// // LED blink example for PIC18F4520 // Written by Ted Burke // Last updated 5-3-2013 // #include <xc.h> #pragma config OSC=INTIO67,MCLRE=OFF,WDT=OFF,LVP=OFF,BOREN=OFF int main(void) { // Make RD0 a digital output TRISD = 0b11111110; // Blink LED on RD0 (pin 19) while(1) { LATDbits.LATD0 = 1 - LATDbits.LATD0; _delay(100000); } }
Create a directory for the program and save the above code in it as a file called “main.c”.
I use the simple build script below to compile the program and (assuming it compiles without errors) download the updated hex file onto the PIC. Save the following into the same directory as a file called “build_and_program”.
#!/bin/bash /mnt/sdb2/microchip/xc8/v1.12/bin/xc8 --chip=18F4520 main.c && sudo ./pk2cmd -PPIC18F4520 -F./main.hex -M -T
I installed XC8 in the directory “/mnt/sdb2/microchip/xc8”, so that’s the location specified above. The build script needs to modified according to the actual installation directory on a particular computer. If the installation directory was added to the path, the installation directory may not need to be specified at all.
To make the build script executable, use the following command:
chmod 755 build_and_program
To keep things simple, I create a separate directory for each PIC program and store all of the following files in it:
- main.c – The actual C program (see above).
- build_and_program – The build script (see above).
- pk2cmd – This the command line utility for programming PIC microntrollers using the PICkit 2. It’s a very compact program, so I just place a copy of it in the folder along with each of my programs.
- PK2DeviceFile.dat – This file is required by pk2cmd, so I place a copy of it into the folder with each of my programs.
To run the build script and download the hex file to the PIC, just type the following command:
./build_and_program
Here’s how it looks in my terminal window:
Concise, and cool! Thanks…
You’re welcome! Glad you found it useful.
Thanks a lot!!
I am grateful for your code.
This code make me happy.
I looked around almost all the websites, most useful, most concise code is yours.
Thanks again.
I am writing from Türkiye/İSTANBUL
Excuse my bad English!
Thanks Mehmet, I’m glad you found it useful!