simpctr.html 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. <html>
  2. <head>
  3. <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  4. <title>Contador simples em código de Gray</title>
  5. </head>
  6. <body bgcolor="FFFFFF">
  7. <h1>Contador simples em código de Gray</h1>
  8. <p> Muitas vezes queremos componentes que não são exclusivamente combinacionais
  9. em sua natureza - ou seja, queremos que o componente tenha alguma memória.
  10. Há uma sutileza importante na definição de tais componentes: você
  11. não poderá ter o componente armazenando por si mesmo o estado, porque um
  12. componente individual poderá aparecer várias vezes no mesmo circuito.
  13. Ele poderá até não aparecer diretamente dentro de um circuito, mas
  14. poderá ser contado mais de uma vez se existir em um subcircuito que
  15. seja usado várias vezes.
  16. </p>
  17. <p> A solução será criar uma nova classe para representar o estado atual do objeto
  18. e, associar instâncias a esse componente através do estado do circuito do qual
  19. for herdado. Neste exemplo, que implementa um contador em código de Gray de 4 bits
  20. sensível à borda, definimos uma classe <code> CounterData </code> para representar
  21. o estado do contador, além da subclasse <code> InstanceFactory </code> como
  22. ilustrado anteriormente.
  23. Um objeto <code> CounterData </code> se lembrará tanto do valor atual do contador,
  24. bem como da entrada de clock visto pela última vez (para detectar a borda de subida).
  25. </p>
  26. <h2>CounterData</h2>
  27. <pre>
  28. package com.cburch.gray;
  29. import com.cburch.logisim.data.BitWidth;
  30. import com.cburch.logisim.data.Value;
  31. import com.cburch.logisim.instance.InstanceData;
  32. import com.cburch.logisim.instance.InstanceState;
  33. /** Represents the state of a counter. */
  34. class CounterData implements InstanceData, Cloneable {
  35. /** Retrieves the state associated with this counter in the circuit state,
  36. * generating the state if necessary.
  37. */
  38. public static CounterData get(InstanceState state, BitWidth width) {
  39. CounterData ret = (CounterData) state.getData();
  40. if(ret == null) {
  41. // If it doesn't yet exist, then we'll set it up with our default
  42. // values and put it into the circuit state so it can be retrieved
  43. // in future propagations.
  44. ret = new CounterData(null, Value.createKnown(width, 0));
  45. state.setData(ret);
  46. } else if(!ret.value.getBitWidth().equals(width)) {
  47. ret.value = ret.value.extendWidth(width.getWidth(), Value.FALSE);
  48. }
  49. return ret;
  50. }
  51. /** The last clock input value observed. */
  52. private Value lastClock;
  53. /** The current value emitted by the counter. */
  54. private Value value;
  55. /** Constructs a state with the given values. */
  56. public CounterData(Value lastClock, Value value) {
  57. this.lastClock = lastClock;
  58. this.value = value;
  59. }
  60. /** Returns a copy of this object. */
  61. public Object clone() {
  62. // We can just use what super.clone() returns: The only instance variables are
  63. // Value objects, which are immutable, so we don't care that both the copy
  64. // and the copied refer to the same Value objects. If we had mutable instance
  65. // variables, then of course we would need to clone them.
  66. try { return super.clone(); }
  67. catch(CloneNotSupportedException e) { return null; }
  68. }
  69. /** Updates the last clock observed, returning true if triggered. */
  70. public boolean updateClock(Value value) {
  71. Value old = lastClock;
  72. lastClock = value;
  73. return old == Value.FALSE && value == Value.TRUE;
  74. }
  75. /** Returns the current value emitted by the counter. */
  76. public Value getValue() {
  77. return value;
  78. }
  79. /** Updates the current value emitted by the counter. */
  80. public void setValue(Value value) {
  81. this.value = value;
  82. }
  83. }
  84. </pre>
  85. <h2>SimpleCounter</h2>
  86. <pre>
  87. package com.cburch.gray;
  88. import com.cburch.logisim.data.BitWidth;
  89. import com.cburch.logisim.data.Bounds;
  90. import com.cburch.logisim.data.Direction;
  91. import com.cburch.logisim.instance.InstanceFactory;
  92. import com.cburch.logisim.instance.InstancePainter;
  93. import com.cburch.logisim.instance.InstanceState;
  94. import com.cburch.logisim.instance.Port;
  95. import com.cburch.logisim.util.GraphicsUtil;
  96. import com.cburch.logisim.util.StringUtil;
  97. /** Manufactures a simple counter that iterates over the 4-bit Gray Code. This
  98. * example illustrates how a component can maintain its own internal state. All
  99. * of the code relevant to state, though, appears in CounterData class. */
  100. class SimpleGrayCounter extends InstanceFactory {
  101. private static final BitWidth BIT_WIDTH = BitWidth.create(4);
  102. // Again, notice how we don't have any instance variables related to an
  103. // individual instance's state. We can't put that here, because only one
  104. // SimpleGrayCounter object is ever created, and its job is to manage all
  105. // instances that appear in any circuits.
  106. public SimpleGrayCounter() {
  107. super("Gray Counter (Simple)");
  108. setOffsetBounds(Bounds.create(-30, -15, 30, 30));
  109. setPorts(new Port[] {
  110. new Port(-30, 0, Port.INPUT, 1),
  111. new Port( 0, 0, Port.OUTPUT, BIT_WIDTH.getWidth()),
  112. });
  113. }
  114. public void propagate(InstanceState state) {
  115. // Here I retrieve the state associated with this component via a helper
  116. // method. In this case, the state is in a CounterData object, which is
  117. // also where the helper method is defined. This helper method will end
  118. // up creating a CounterData object if one doesn't already exist.
  119. CounterData cur = CounterData.get(state, BIT_WIDTH);
  120. boolean trigger = cur.updateClock(state.getPort(0));
  121. if(trigger) cur.setValue(GrayIncrementer.nextGray(cur.getValue()));
  122. state.setPort(1, cur.getValue(), 9);
  123. // (You might be tempted to determine the counter's current value
  124. // via state.getPort(1). This is erroneous, though, because another
  125. // component may be pushing a value onto the same point, which would
  126. // "corrupt" the value found there. We really do need to store the
  127. // current value in the instance.)
  128. }
  129. public void paintInstance(InstancePainter painter) {
  130. painter.drawBounds();
  131. painter.drawClock(0, Direction.EAST); // draw a triangle on port 0
  132. painter.drawPort(1); // draw port 1 as just a dot
  133. // Display the current counter value centered within the rectangle.
  134. // However, if the context says not to show state (as when generating
  135. // printer output), then skip this.
  136. if(painter.getShowState()) {
  137. CounterData state = CounterData.get(painter, BIT_WIDTH);
  138. Bounds bds = painter.getBounds();
  139. GraphicsUtil.drawCenteredText(painter.getGraphics(),
  140. StringUtil.toHexString(BIT_WIDTH.getWidth(), state.getValue().toIntValue()),
  141. bds.getX() + bds.getWidth() / 2,
  142. bds.getY() + bds.getHeight() / 2);
  143. }
  144. }
  145. }
  146. </pre>
  147. <p><strong>Próximo:</strong> <a href="counter.html">Contador em código de Gray</a>.</p>
  148. </body>
  149. </html>