Mapping outputs across ports? How to do?

geezer88

Senior Member
Here's a hypothetical question for you gurus: Let's suppose I'm programming an 18M2 to do a job that requires out-putting byte data to eight outputs. But, on port B, I want to use b.1 and b.4 for i2c communication, and therefor use two pins from port C, say c.6 and c.7.

I could use symbols to assign names to the individual output pins. Then break down the data byte into individual bits, sending them to the appropriate outputs. But this seems clumsy and slow.

Is there a better way? Like create a virtual port that could be printed in one command?

thanks,
tom
 

hippy

Technical Support
Staff member
Follow the link Texasclodhopper gives. It can often be done simpler than shown there but it's a standard technique in a lot of programming, so-called using Hardware Abstraction Layers.

Basically create a variable which holds the bits as you'd like them, then call a routine to put them out. That routine is the only one which has to do anything complicated, any bit shuffling. The nice thing is that it allows code to be more easily ported to a different chip or to differently wired hardware.

You can program using these virtual registers and not have to worry about how the chip will actually be wired or what the chip is. There's a slight overhead ( extra variables used, having to call routines to read data and put it out ) but the gains usually outweigh the disadvantages, particularly in making it easier to write code and treat the virtual registers how you'd like rather than however they actually are.


An example; a BCD counter display. Pin mapping is easy for a 18M2 ( say C.0-C.3 ), but someone wired the 28X2 board backwards and used different pins( B.3-B.0 ) and there's no output pin 3 for the 08M version. This code will work for all three chips, you just have to alter what's in the 'bcd' variable and 'Gosub SetOutputs' when you want the outputs updating ...

Code:
Symbol bcd = b7
Do
  For b0 = 0 To 9
     bcd = b0
     Gosub SetOutputs
  Next
Loop

SetOutputs:
  #IfDef 08M
    pin0 = bcd / 1
    pin1 = bcd / 2
    pin2 = bcd / 4
    pin4 = bcd / 8
  #EndIf
  #IfDef 18M2
    pinC.0 = bcd / 1
    pinC.1 = bcd / 2
    pinC.2 = bcd / 4
    pinC.3 = bcd / 8
  #EndIf
  #IfDef 28X2
    pinB.3 = bcd / 1
    pinB.2 = bcd / 2
    pinB.1 = bcd / 4
    pinB.0 = bcd / 8
  #EndIf
  Return
You can optimise to 'pinX = bitY' if you can 'Symbol bcd = b0' or '= b1'. You also need a routine to set the pins as outputs.
 
Last edited:

geezer88

Senior Member
Thanks, gents for the references. I'll keep them in my bag of other folks' tricks. The forum is so useful.

tom
 
Top