SX Microcontroller Range Check Program Flow Methods

Test if a value is in a certain range

Reg = value

	;offset Reg value so that Hi value in Reg becomes 255
	mov	W, #255 - Hi
	add	Reg, W		;Reg is influenced!

	;add to offset value the span value plus one
	mov	W, #(Hi - Lo) + 1
	add	W, Reg

Carry is set if Lo < Reg < Hi.

If Reg should be restored:

	mov	W, #Hi - 255	;restore Reg
	add	Reg, W		;

It works for all values of Hi and Lo although it is not optimal for 255 and 0. It even works for ranges that wrap around 255 back to 0. For instance, if you set Lo to 240 and Hi to 15, it will match 0..15 and also 240..255. And it works for signed numbers. You can set Lo to -3 and Hi to 5 to match -3..+5.

The only requirement is that your assembler must truncate literals to eight bits. If not, you can still use it by masking the literals yourself:

	mov	W, #(255 - Hi) & $FF
	mov	W, #((Hi - Lo) + 1) & $FF

For example:

Lower = 50
Upper = 60
	mov	W, #195	;255 - Hi = 255 - 60 = 195
	add	Reg, W
	mov	W, #11		;(Hi - Lo) + 1
	add	W, Reg

W = 50          ; lower limit
	mov	W, #195
	add	Reg, W		;Reg = 50 + 195 = 245
	mov	W, #11
	add	W, Reg		;w = 245 + 11 = 0, C = 1, result = OK

W = 55          ; in range
	mov	W, #195
	add	Reg, W		;Reg = 55 + 195 = 250
	mov	W, #11
	add	W, Reg		;w = 250 + 11 = 5, C = 1, result = OK

W = 60          ; upper limit
	mov	W, #195
	add	Reg, W		;Reg = 60 + 195 = 255
	mov	W, #11
	add	W, Reg		;w = 255 + 11 = 10, C = 1, result = OK

W = 49          ; under minimum
	mov	W, #195
	add	Reg, W		;Reg = 49 + 195 = 244
	mov	W, #11
	add	W, Reg		;w = 244 + 11 = 255, C = 0, result = Not OK

W = 61          ; over maximum
	mov	W, #195
	add	Reg, W		;Reg = 61 + 195 = 0
	mov	W, #11
	add	W, Reg		;w = 0 + 11 = 11, C = 0, result = Not OK

Code: