Sending analog values over serial using a PIC 18F14K50

PICkit 2, pl2303 usb to serial converter and a PIC 18F14k50

PICkit 2, pl2303 usb to serial converter and a PIC 18F14k50

There’s a Robosumo competition coming up. The microcontroller chosen for the job was the PIC 18F14k50. The sensors being used are Sharp infrared rangefinder (to locate the opposing robot), and IR colour detecting sensors (to detect when the robot has reached the edge of the ring). All of these sensors give out a voltage somewhere between 0-5v. In order to start writing some code, it is extremely helpful to read the output of each analog channel in real time.

This is the code used to read from the analog channel and transmit it over serial:



void setup(void);
unsigned int read_analog_channel(void);
void config_usart(void);

int value,voltage = 0;

void main(void)
        value = read_analog_channel();

        printf("%d\n", value);



void putch(char data) // this function is required for printf to work properly, got it from the xc8 manual
     while (!TXIF)
     TXREG = data;

void setup(void)
    OSCCON = 0b01100011; //internal oscillator block, 8MHz clock speed.
    ANSELbits.ANS4 = 1; // pin 3 configured as an analog input
    TRISC = 0b00000000;
    TRISB = 0b00000000;
    ADCON0 = 0b00010000;// AN4 is the channel being looked at, analog channel currently disabled, ( less power consumption)
    ADCON2 = 0b00000011;// a/d conversion clock (dedicated clock)


void config_usart(void)
    TXSTAbits.TXEN = 1; // transmit enabled
    TXSTAbits.SYNC = 0; // asynchronous mode
    RCSTAbits.SPEN = 1; // usart enabled, tx set as output
    SPBRG = 12;         // baud rate = 9600

unsigned int read_analog_channel (void)
    voltage = 0;
    ADCON0bits.ADON = 1;
    Delay1TCY();// 8us Delay for capacitor charge
    ADCON0bits.GO = 1;

    while(ADCON0bits.GO); // wait for conversion to complete

    voltage = ADRESH;
    voltage = (voltage<<2) + (ADRESL>>6);
    return voltage;

On the computer end of things, a python script is used to print the incoming serial data to the screen.

import serial
import time
import numpy as np
import cv2

ser = serial.Serial('/dev/ttyUSB0', 9600)


while True:

	print ser.readline()

Link to the Python script :

Link to the C file :


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s