Back to PCAM+ page.
Back to Chapter 2 Toggle LEDs with Switch on 89S52 MicrocontrollerThis is another simple yet important tutorial for 89S52 or 8051 interfacing.We are covering basic interface applications so that you will understand the concept rather than getting into the complex interfacing logic. Let's discover how to turn LEDs On/Off using a switch, and learn the BIT value handling for the 89S52 microcontroller. First, start the 8051 IDE and type the following code: SETB P2.0 Loop: JB P1.0, Loop CPL P2.0 Debounce: JNB P1.0, Debounce SJMP Loop The code uses Bit 0 of PORT2 to connect to the LED. Therefore, use a jumper wire now to connect PORT2.0 to one of the LEDs. The code is using P1.0 to read the switch status. Therefore, use another jumper wire to connect a switch (button) to P1.0 of the 89S52. The SETB P2.0 code line will turn the LED OFF to start with. Loop: is a section label. The JB P1.0, Loop command checks the status of Port pin P1.0. The JB stands for JUMP if BIT is HIGH.Thus, if the PORT1.0 bit is HIGH, then it will JUMP to Loop. When the switch is not pressed, the P1.0 will remain HIGH, thus the program restarts the loop. When the switch is pressed, P1.0 goes LOW. This action of pressing the switch means the JB command's condition (P1.0 being HIGH) is not met, thus it does not jump to Loop, so the program moves to the next line: CPL P2.0. CPL is Complement. This line will Complement the PORT pin P2.0 (in other words, invert). Thus, the LED status will be inverted — from OFF to ON ... at first. The Debounce section is like the Loop section, only note its command of JNB P1.0, Debounce. The JNB means JUMP NOT if BIT is HIGH. Thus, as long as the switch remains pressed, keeping P1.0 LOW, the code remains in the Debounce loop here. When you release the switch, SJMP Loop returns the program to the Loop section. The LED remains ON because P2.0 was toggled by CPL earlier, and now the code is looping on JB P1.0, Loop again, waiting for another button press. When you press the switch button again, the CPL command again inverts the LED state, thus now turning it OFF. This tutorial has explained Bit commands like JB, SETB, JNB & CPL. Thus you can now read input for the microcontroller. Proceed to Chapter 4
Back to PCAM+ page. |