Passing port to a function using pointer

General discussion on mikroC PRO for 8051.
Post Reply
Author
Message
croket_2512
Posts: 41
Joined: 05 Aug 2014 03:35

Passing port to a function using pointer

#1 Post by croket_2512 » 23 Dec 2014 08:19

With C for 8051, can I code as the following:

Code: Select all

unsigned char Button(unsigned char *PORT, unsigned char pin, unsigned char active_state)
{
  switch(active_state)
  {
    case LOW_STATE: if((((*PORT) >> pin) & 1) == LOW_STATE)
                             {
                                 //My code
                              }
  }
}

void main(void)
{
  unsigned char button_state;
  while(1)
  {
    button_state = Button(&P2, 0, LOW_STATE);
  }
}
My code doesn't work. Can somebody help me?

User avatar
darko.minic
Posts: 747
Joined: 01 Dec 2014 11:10

Re: Passing port to a function using pointer

#2 Post by darko.minic » 23 Dec 2014 15:58

Hello,

The switch statement is used to pass control to a specific program branch, based on a certain condition. The syntax of the switch statement is:

Code: Select all

switch (expression) {
  case constant-expression_1 : statement_1;
    .
    .
    .
  case constant-expression_n : statement_n;
  [default : statement;]
}
For example, if a variable i has value between 1 and 3, the following switch would always return it as 4:

Code: Select all

switch (i) {
  case 1: i++;
  case 2: i++;
  case 3: i++;
}
For further information please refer Help in our compiler:
mikroC PRO for 8051 Language Reference > Statements > Selection Statements > Switch Statement

Regards,
Darko

croket_2512
Posts: 41
Joined: 05 Aug 2014 03:35

Re: Passing port to a function using pointer

#3 Post by croket_2512 » 28 Dec 2014 16:34

Hi,

How can I pass a bit of port into a function? I want write a function like this: Button(&P2, 0, 1) where 0 is pin number, 1 is active state. I want to check the state at pin, for example: button_state = Button(&P2, 0, 1).

Thank you!

User avatar
darko.minic
Posts: 747
Joined: 01 Dec 2014 11:10

Re: Passing port to a function using pointer

#4 Post by darko.minic » 30 Dec 2014 11:47

Hello,

You should refer Button examples in our compiler, and try from our example to form your code gradually.

Regards,
Darko

Post Reply

Return to “mikroC PRO for 8051 General”