Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

how to use switch to control output?

Status
Not open for further replies.

cyteh

Newbie level 6
Joined
Jun 17, 2010
Messages
13
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Location
malaysia
Activity points
1,379
there are 4 switches where i named it as button1, button2, button3, button4
and they are originally connected to 2.5v.
once i press the button, it'll go to LOW.
When PIC detect LOW from the input, output=1.
However, the program i did was not functioning well...it execute "LATBbits.LATB2=1" even when i did not press the button( input is still high).
anyone know what mistake had i did?

this is my program:

#include "p18f24k20.h"

#define button1 LATAbits.LATA1
#define button2 LATAbits.LATA2
#define button3 LATAbits.LATA3
#define button4 LATAbits.LATA4

#define ON 1
#define OFF 0

void main (void)
{
LATA= 0x00;
TRISA=0b00011110;/* initialize RA<4:1> as input*/
LATB= 0x00;
TRISB=0b11100011;/* initialize RB<4:2> as output*/
LATC=0x00;
TRISC=0b11001011;/* initialize RC<5:4> and RA2 as output*/

while(1)
{
if(!button1)/*PIC detect LOW*/
{
LATBbits.LATB2=1;
}
else if(!button2)
{
LATBbits.LATB3=1;
}
else if(!button3)
{
LATBbits.LATB4=1;
}
else if (!button4)
{
LATCbits.LATC2=1;
}
else
{
LATBbits.LATB2=0;
LATBbits.LATB3=0;
LATBbits.LATB4=0;
LATCbits.LATC2=0;
}
}
} //main
 

Take a look at the ANSEL register.
On power up port A pins are configured as analog input pins. You have to clear the ANSEL register bits to make them digital I/O.
 

    cyteh

    Points: 2
    Helpful Answer Positive Rating
yes, you use the lat bits to set the output, but use the port bits to read the input.
 

    cyteh

    Points: 2
    Helpful Answer Positive Rating
Thanks for ur guide, here are my program after those correction and it's working now. :D

#include "p18f24k20.h"

#define button1 PORTAbits.RA1
#define button2 PORTAbits.RA2
#define button3 PORTAbits.RA3
#define button4 PORTAbits.RA4

void main (void)
{
ANSELbits.ANS1=0;
ANSELbits.ANS2=0;
ANSELbits.ANS3=0;
ANSELbits.ANS4=0;
PORTA= 0x00;
TRISA=0b00011110;/* initialize RA<4:1> as input*/
LATB= 0x00;
TRISB=0x00;/* initialize RB<4:2> as output*/
LATC=0x00;
TRISC=0x00;/* initialize RC<5:4> and RA2 as output*/

while(1)
{
if(!button1)/*PIC detect LOW*/
{
LATBbits.LATB2=1;
}
else if(!button2)
{
LATBbits.LATB3=1;
}
else if(!button3)
{
LATBbits.LATB4=1;
}
else if (!button4)
{
LATCbits.LATC2=1;
}
else
{
LATBbits.LATB2=0;
LATBbits.LATB3=0;
LATBbits.LATB4=0;
LATCbits.LATC2=0;

}
}
} //main
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top