Search code examples
buttonpicbasicled

Simple PIC16F684 Input/Output


I'm having trouble with what should be a very simple piece of code. My objective is to turn an LED on while a button is being pressed. In this case the input logic will go low when I press the button. The LED is connected to PORTC.2 and the button is connected to PORTC.0. Here is the code:

dim test as bit

main:
TRISC = %00000001 
ANSEL = %00000000
PORTC= 0
cmcon0=0

Testbutton:

 test = PORTC.0
 if test = 0 then
    PORTC = %00000100
    goto Testbutton
    end if
    PORTC = %00000000

  end.

The problem is the PIC always outputs high no matter what the input is. So far I have used a multimeter to verify that the input is indeed changing from 5V to 0V when the button is pressed, I have tried using a different input pin, and I have tried using a different PIC. I suspect that since the input is always being read as low that the PIC may not be properly initialized but I'm not entirely sure.

Thanks for any insight that you might be able to give me


Solution

  • The datasheet of 16f684 states on page 42 that :

    The ANSEL and CMCON0 registers must be initialized to configure an analog channel as a digital input. Pins configured as analog inputs will read ‘0’.

    These registers are actually initialized in your code. ANSEL is initialized to 0, so all analog input are deactivated. Yet, the CMCON0 register should be initialized to xxxxx111 or 07h. See the example 4.3 on page 42. The last three bits of CMCON0 correspond to the mode of operation of comparators and choosing 111 turns them off. See page 60.

    Don't forget to add goto Testbutton if you want the led to light up again as the button is released. It may be intentional though : it's up to you !