Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

If-statement - Condition depending on output pin

Status
Not open for further replies.

eng1

New Member
Below I include simplified C code for a function 'read_ADC'.

RB0 is configured as output pin.

The function has to determine the state of RB0; then RB0 is cleared inside this function and other operations with ADC, etc. are implemented.
Then, RB0 must be restored, according to its original state.

Code:
void read_ADC()
{

	if(RB0)	// CORRECT ??
		RB0_state = 1;
	else
		RB0_state = 0;


	RB0 = 0;

	DelayMs(200);    // 200 ms
	
	Read_Ch(1);      // read ADC

	RB0 = RB0_state;  // restore RB0
}

Is it ok to check the state of RB0 (which is configued as outout pin) directly on the PORTB register?
The program runs correctly as I expected with the hardware. Do you see anything wrong/drawbacks with this solution? Of course I could update the variable RB0_state throughout the program, anywhere RB0 is changed; but this would require additional works and tests.
 
You don't say whether you are using an 18F or 16F series PIC, the answer may be a little different. It is perfectly fine to check port bits to see what the current output state is.

You can simplify your code to this though:

Code:
void Read_ADC()
{
	char original_state = RB0;	// Save original state
	RB0 = 0;			// Force pin low
	DelayMs(200);			// Delay
	Read_Ch(1);			// Read ADC
	RB0 = original_state;		// Restore original state
}
 
Thank you for your comments.

I am using a PIC16F. And of course I'll simplify the first lines as you have suggested.
 
OK, on a 16F the only thing you can do is read from the port itself (unlike the 18F, which has a data latch). You should also be aware of the read-modify-write problem just in case (see ).

As you rightly said earlier in the thread a good solution is to have a variable that keeps track of the current state of RB0 throughout the code.
 
Status
Not open for further replies.

Latest threads

New Articles From Microcontroller Tips

Back
Top