import java.net.*; import java.io.*; import java.util.Scanner; /** * A binary counter showing the bits for a numner 0 to 15 * for 4 LEDs at pin 6 using software Pulse Width Modulation (Soft PWD). * * This class controls the PWM LED programatically. * */ public class Counter implements ButtonListener { // The Adjustable LED private pwmLED[] leds; private Button button; /** * Constructor for objects of class Controller. */ public Counter() { // initialise instance variables leds = new pwmLED[4]; leds[0] = new pwmLED(25);//wPi25 is BCM 26 phys 37 leds[1] = new pwmLED(23);//wPi23 is BCM 13 phys 33 leds[2] = new pwmLED(29);//wPi29 is BCM 21 phys 40 leds[3] = new pwmLED(27);//wPi27 is BCM 16 phys 36 button = new Button(7); // Create the Button at pin 7 controlled by this button.addListener(this); // Make the button tell us when it has changed (See buttonChanged() below) } public void allOn() { for (int i=0 ; i<4 ; i++){ leds[i].on(); } } public void shutdown() { allOff(); button.removeAllListeners(); } public void allOff() { for (int i=0 ; i<4 ; i++){ leds[i].off(); } } /** * This method should set the LED to full brightness. * (Exercise 3.2) * */ public void setLedBrightness(int index, int value) { leds[index].setValue(value); } public void leftShift() { leds[3].setValue(leds[2].getValue() ); leds[2].setValue(leds[1].getValue() ); leds[1].setValue(leds[0].getValue() ); leds[0].setValue(0); } public void rightShift() { leds[0].setValue(leds[1].getValue() ); leds[1].setValue(leds[2].getValue() ); leds[2].setValue(leds[3].getValue() ); leds[3].setValue(0); } public void setValue(int v) { if (v >= 0 && v<16) { allOff(); if (v-8 >= 0){ leds[3].on(); v -= 8; } if (v -4 >=0){ leds[2].on(); v -= 4; } if (v - 2 >= 0){ leds[1].on(); v -= 2; } if (v == 1) leds[0].on(); } } public int getValue() { int result = 0; for (int i=0; i<4; i++) if (leds[i].isOn() ) result += Math.pow(2,i); return result; } public void addOne() { if (getValue() >= 15){ // is this overflow? allOff(); //overflow return; } if (! leds[0].isOn() ){ // if even just turn on the last bit leds[0].on(); return; } // otherwise it is odd, so need to carry the ones place leds[0].off(); if (! leds[1].isOn() ){ leds[1].on(); return; } // already on, so carry the next digit leds[1].off(); if( ! leds[2].isOn() ){ leds[2].on(); return; } // already on, so carry the next digit leds[2].off(); if (! leds[3].isOn() ){ leds[3].on(); return; } return; } public void buttonChanged(boolean isPressed) { if(!isPressed) { addOne(); //try {Thread.sleep(100);} catch(Exception e) {} System.out.println(getValue() ); } } public static void main(String[] args) { System.out.println("Count in binary\nPress black button to count, Type to quit"); Counter c = new Counter(); Scanner kb = new Scanner(System.in); kb.nextLine(); c.shutdown(); c =null; // otherwise, the count and its LEDs continue to function. System.out.println("That's All Folks..."); } }