H Bridge ControllerIn this example switches are used to control the motor in an H Bridge configuration.

Open a new tab or window running the simulator. Click on SWITCHES (B) and HBRIDGE (B) to make the switches and the motor visible. Both are connected to PORTB. If necessary, move the switches and motor so they don't cover each other.

Use your mouse to switch off all the switches 0 to 7. Just click on the switches. Copy and paste the example code into the code editing area. Press F8 to assemble the code and run the program.

Turn on S4 only. The motor should run forwards.

Turn off S4. The motor should freewheel.


TASK:Add to this example.
If you close only switch 5, the motor should run in reverse.
If you close only switch 6, the motor should brake to a halt.
Switches 0, 1, 2, 3 and 7 should have no effect.

  • MOVRW copies data from the specified location into the Working register. PORTB in this example.
  • ANDW performs logical AND on the W register.
    Here it is used for a BIT MASK.
    Bits 0, 1, 2, 3 and 7 are forced to zero (masked) and bits 4, 5 and 6 are left unchanged.
  • SUBW 0x10 subtracts hexadecimal 10 from W.
    If only switch 4 was closed, this operation will leave zero in W.
    This will cause the Z flag to be set.
  • JPZ will perform the jump if the Z flag is set.
    The motor will run forwards.
; ===========================================
;       H  Bridge  Motor  Control
;       CONNECT  HBRIDGE TO PORTB
;       CONNECT SWITCHES TO PORTB
; ===========================================
        MOVW    0XF0    ; 4 Inputs & Outputs
        MOVWR   TRISB   ; Set PORTB direction
START:
        MOVRW   PORTB   ; READ PORTB
        ANDW    0X70    ; BIT MASK
        SUBW    0X10    ; TEST S4 CLOSED
        JPZ     FORWARD ; Jump If Closed
        
        JMP     COAST   ; Freewheel
; ===========================================
FORWARD:
        MOVW    0X09    ; Close bits 0 and 3
        MOVWR   PORTB
        JMP     START
; ===========================================
COAST:
        MOVW    0X0     ; Open all switches
        MOVWR   PORTB
        JMP     START
; ===========================================