JohnMerlino
JohnMerlino

Reputation: 3928

embedded c and the 8051 microcontroller

Upon reset of the 8051 microcontroller, all the port-pin latches are set to values of ‘1’. Now I am reading this book "Embedded C" and it states thr problem with the below code is that it can lull the developer into a false sense of security:

// Assume nothing written to port since reset
// – DANGEROUS!!!
Port_data = P1;

If, at a later date, someone modifies the program to include a routine for writing to all or part of the same port, this code will not generally work as required:

unsigned char Port_data;
P1 = 0x00;
. . .
// Assumes nothing written to port since reset
// – WON’T WORK BECAUSE SOMETHING WAS WRITTEN TO PORT ON RESET
Port_data = P1;

Anyone with knowledge of embedded c can explain to me why this code won't work? All it does is assign 0 to a char variable.

Upvotes: 5

Views: 1395

Answers (2)

UnicornTYW
UnicornTYW

Reputation: 1

I was reading the same book and having the same confusion few months ago. Latter working on projects with PIC18 and M0+ and being kind of figuring out what it's really about.

Actually, this is not a software/programming issue but rather a hardware/electronic one. If your 805X code want to be able to read both 1 and 0 from an outside input on a pin, the code has to write 1 to the pin in advance. If your code write 0 to the pin in advance, the outside peripheral won't be able to pull the pin high and allow the code to read 1. Why?? electronic stuff!! Imagining that if you want to enjoy the wind outside the window, you have to open the window first.

If you are really interested, google "pin value vs latch value" by yourself. I think it's okay for programmer to leave that to hardware engineer.I believe 805Xs don't have DDR as advanced ones. Switching a pin between input and output mode may be easy but confusing.

Upvotes: -1

chux
chux

Reputation: 153303

Potential issues.

1) The data direction register (DDR) associated with the port may not be set as expected, thus on power-up, the DDR may be set to "input". So writing the port to 0 may unexpectedly not read read 0.

2) The data direction register associated with the port may have been set to "output" and "reading" the data may not have a clear meaning. Depending on architecture, phantom bits may be needed to shadow the output bits for read-back.

3) Power-up code may get entered via a reset command that is nothing more than a jump to "reset vector". So any hardware specific action associated with a "cold" power-up did not occur as this is a "warm" power-up.

Solution:

On power-up code, explicitly set the DDR and output values (and shadow bits as needed).

May not apply to 8051 - speaking to embedded processor in general.

Upvotes: 2

Related Questions