[General] 18F4520 Switch Input <Help>

Status
Not open for further replies.

Justin Hendrix

Newbie level 4
Joined
Nov 10, 2014
Messages
6
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Visit site
Activity points
32
How do I read the status of switches (1 or 0) using a 18F4520?

Code:
#include <p18F4520.h>
void main ()
{
}

Regards.
 

Something like this. If there is a switch on RB0 then there are two ways depending upon how switch is connected.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
if(PORTBbits.RB0) {
       _delay_ms(50);
       while(PORTBbits.RB0);
 
             //do what you want here
}
 
if(!PORTBbits.RB0) {
       _delay_ms(50);
       while(!PORTBbits.RB0);
 
             //do what you want here
}

 
Hi Milan.rajak, thanks for the prompt reply.

Let's say I would like to connect it to an LED and that whenever the output is high (which is 1), the led will light up.
How do I do that in the script?

*P.S. Is it possible if you could come up with the full working script. I'd appreciate it a lot.

Code:
#include <p18F4520.h>

void main ()
{
 

Try this code. Connect an LED to PORTD.7, connect one end of switch to PORTD.0 and other end to +5V. Also connect one end of a resistor to PORTD.0 and other end to GND.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <p18f4520.h> 
 
#pragma config OSC = XT 
#pragma config PWRT = ON
#pragma config WDT = OFF
#pragma config LVP = OFF 
#pragma config DEBUG = OFF 
#pragma config CPB = OFF
#pragma config MCLRE = ON 
 
void Delay_ms(unsigned int);
 
void msdelay(unsigned int ms) { 
    unsigned int x; 
    unsigned int z; 
 
    for (x = 0; x < ms ; x++) 
        for(z = 0; z < 165; z++); 
}
 
void main(void) { 
 
    TRISD = 0x01;
    PORTD = 0X00;
    LATD = 0x00;
    
    while(1)  {
 
        if(PORTDbits.RD0) {
                Delay_ms(50);
                while(PORTDbits.RD0);
 
                LATDbits.LATD7 = ~LATDbits.LATD7
        }       
    } 
}





MPLAB X + C18 + Proteus 8.1 SP1 Project attached.
 

Attachments

  • LED SW.rar
    46.9 KB · Views: 67
Last edited:
Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…