# Switch on a LED: why doesn't this code work?

I am using DEMO9S08AW60E and using Codewarrior(Version: 5.9) with Processor Expert.

PTFDD = 0x00;  // to activate/intialize the port F and D
PTDDD = 0x00;

if ((PTDD_PTDD2 |= 0x02))
{
PTFD_PTFD0 |=0x01;
}
else
{
PTFD_PTFD0 &=0x01;
}


According to the schematic of the board, Switch 4 is connected to PortD/Pin2. And the set of LED are connected to the PortF/Pin(0-7). The idea is to switch the LED on when the button is pressed: I have used a pull up resistor with the help of PROCESSOR EXPERT. Logically, I feel my code is fine but there doesn't seem to be any effect.

I would like to know where I am going wrong and hope you will able to help.

• There is a proper formatting style for code, using four whitespaces as indentation. You can find it in the toolbar – clabacchio Dec 5 '12 at 10:25
• Is that all your code? Don't you need to set data direction registers for input on D and output on F? – Garrett Fogerlie Dec 5 '12 at 10:33
• @GarrettFogerlie: Data direction registers have been set Please note: PTFDD = 0x00; PTDDD = 0x00; – sheetansh Dec 5 '12 at 11:01
• @sheetansh Yes but they are both set as inputs, the led should be an output. Look at my answer below – Garrett Fogerlie Dec 5 '12 at 11:03

if ((PTDD_PTDD2 |= 0x02))


This is equal to:

PTDD_PTDD2 |= 0x02;
if (1)


This does probably not what you want either:

PTFD_PTFD0 &=0x01;


The resulting value of PTFD_PTFD0 is 0x00 or 0x01, depending on the value of least sigificant Bit.

It looks like you wanted:

PTFD_PTFD0 &= ~ 0x01;


This sets the LSB to zero.

• Thanks for your input, let me explain what i understood by your solution: the LSB is set to zero, considering, the logic on the board says 1 as HIGH and 0 as LOW. SO, if i set the LSB as zero, the LED remains OFF. Thats what i need from the else statement. but my prob is, the led doesnt understand whether the switch is on or off. – sheetansh Dec 6 '12 at 12:47

I have finally understood the reason why it didnt work the way as stated above. After using debugging techniques, i realised that the program control never crosses the if loop condition therefore, the condition for my "if" loop has to be written as:PTDD_PTDD2 & 0x02. Thats it. I know some of the answers were in the same lines but this one worked. I am still not sure whether it was the problem with the software or the logic. it works and my colleagues also confirmed that USE OF MASK is prefferable when working with CPU coding. Thank you again!!