Kategorie: Programming

  • The Purpose of Being Agile

    Introduction

    Why, would you think, are we (oh!) so agile? Why do we do Kanban or Scrum?

    a) To have more fun?
    b) To become a better team?
    c) To follow industry standards?

    „Take a wild guess!“

    Laury Anderson

    It is neither of it. To give you a hint, I quote the very first Google hits for „purpose of agile“:

    To me, agile is all about embracing change to make our customers awesome.

    Jezza Sutton in https://www.quora.com/What-is-the-purpose-of-Agile-and-why-are-so-many-companies-using-it

    It puts more emphasis on creativity and innovation that is needed to maximize the business value of the solution

    Chuck Cobb in https://www.quora.com/What-is-the-purpose-of-Agile-and-why-are-so-many-companies-using-it

    Go down the list of all the most successful companies. They are all delivering products faster, better, and cheaper than the competition because they are Agile…

    Jeff Sutherland in https://www.quora.com/What-is-the-purpose-of-Agile-and-why-are-so-many-companies-using-it

    Got it? Good. So, let me summarize it. In the software industry we are Agile, because we want to
    a) deliver products the customers benefit from and thus are willing to buy,
    b) be more efficient (AKA faster, better, cheaper) to gather higher profits (AKA business value),
    c) to stay in the market, because everybody else does it and proves it right.

    Everything else comes second. To be precise about what comes second, third, fourth, or even fifth:
    a) your fun, happiness,
    b) team building,
    c) Good parentship,
    d) work-life ballance,
    e) becoming a better person,
    f) work from home,
    g) healthy snacks.

    All of these points are nice, but basically they are just a means of the primary purposes found above. They are contributing to the primary purposes, or will become obsolete, when management finds out it is not contributing.

    Efficiency vs. Effectiveness

    Efficiency

    Efficiency can be summarized as minimizing waste or „to do things well“. Oh. Waste = Muda, which is a central Kanban term for a good reason.

    Applied to requirements management, the founders of Scrum have found out, it may be less wasteful to replace fixed requirements specifications documents by a volatile and continuously reprioritized, hence more efficient product backlog.

    Applied to team building, intense and immediate collaboration of all required skilled workers seem to be more efficient than silo organizations.

    The push principle puts pressure on your people. Often this leads to errors, stress, unnecessary task switches, low throughput, unpredictable processing times. The promise of the pull principle in conjunction with a limitation of work in progress (WIP-limit) is the exact opposite: Happier workers produce better output more predictable.

    Effectiveness

    Effectiveness can be summarized as „getting the right thing done„.

    This is especially tricky in volatile environments. But one thing should be immediately clear: Long cycle times lengthen the periods of feedback points, which is the main reason why a lot (not all..) of waterfall projects fail to produce good marketable products, especially compared to those with short cycle times, AKA Scrum sprints.

    BTW: in our context efficacy = effectiveness.

    To be continued.

  • Arduino photo resistor with potentiometer++

    If we knew what we were doing, it wouldn’t be called research. 

    Albert Einstein

    In https://www.youtube.com/watch?v=dp_gSye8ke4 Dom’s MOBa channel the author wants to improve a simple photo resistor sketch/circuit by throwing a potentiometer into the game. His primary idea seems to be: with a separate potentiometer he could adjust the threshold of the circuit without changing the program. So far so good.

    Sadly, he connects the potentiometer to a second Arduino input, gauges this port and uses this as an input threshold value for the other port. 

    This seems to be a waste of resources, because actually you do not need the second port. And I am very stingy, when it comes to Arduino ports. 

    So, if the photo resistor has a total reading range of let’s say 0..1023 and a useful threshold somewhere between 20 and 800, all you need is a ~ 20 Ω potentiometer, set in series with the photo resistor pin connected with A0. And here comes my sketch:

    const int photoPort = A0;   // the port
    const int threshold = 800;  // adjust for correct value
    const int DELAY = 100;      // adjust delay between measurements
    
    const char *message[] = {"DARKNESS", "ENLIGHTENMENT"}; // the const messages
    
    void setup() {
      Serial.begin(9600);
    }
    
    void loop() {
      if (analogRead(photoPort) < threshold)
        action(0);
      else
        action(1);
      delay(DELAY);
    }
    
    // do something dependent on the photoPort value
    void action(int msg) {
      Serial.println(message[msg]);
    }
  • Model Railroad Block Detection with Arduino.

    Here we show how to secure a certain track section by signaling in which direction a train enters the section is occupied and if the block has been left again. 

    Our model railroad block detection scenario.

    In pseudo code the system works like this:

    // enter the section from the left
    if isFree(BC) then {
      if sensor(A) then {
        preOccupy(BC);
      }
      
    } 
      enterSection("BC");
    IF sectionStatusIsEntered("BC") AND enterTimeout("BC")
      releaseSection("BC");
    IF readSensor(B) AND sectionStatusIsEntered("BC") THEN
        blockSection("BC");
  • Arduino IR sensor to trigger onboard LED

    Use this sketch to detect an object very close to the IR sensor. This could be useful for model railroading where a train should be detected to trigger a warning light at a level-crossing.

    // hardware: Arduino UNO, IR sensor from funduinoshop.de
    // https://funduino.de/arduino-infrarot-abstandssensor
    
    // port connected to analog read of IR sensor module
    const int ANALOG_IN = A0;  
     
    // onboard LED
    const int LED = 13;   
    
    // threshold, to be set to values which work in your situation
    const int THRESHOLD = 300;
    
    // value in ms, delay between measurements
    const int DELAY = 100;      
    
    void setup() {
      pinMode(LED, OUTPUT);     
    }
    
    void loop() {
      digitalWrite(
        LED,
        (analogRead(ANALOG_IN) < THRESHOLD) ? HIGH : LOW
      );     
      delay(DELAY);
    }
  • How to control effects via MIDI with a Teensy 3.6/LC

    Introduction

    A friend of mine, a keen professional guitar player, wanted a small box to control settings of a looper (a box with which can be used to store audio fragments, loop and stack these fragments).

    MVP

    • MIDI out (DIN)
    • at least three (configurable) push buttons which send a MIDI control change message
    • a configurable MIDI channel

    This system is realized with a Teensy 3.6, but a much cheaper Teens LC will work as good.

    Step 1: Get the MIDI out going

    If you use a Teensy LC or 3.x this is a very easy exercise:

    A MIDI out for the Teensy 3.6 (or LC) using serial send port 1 (TX1). Cf. https://www.pjrc.com/teensy/td_libs_MIDI.html

    Be aware that Arduino is based on 5V and then the resistors have to be different (220 Ω). Too low resistors will cause too high currents on the instrument’s side. So it is not my fault, if you have to send in your Dave Smith…

    This quite simple setup can be used by our (quite simple…) first sketch. In step one we want to play a halftone scale from C1 to C2, each note will be played for a 10th of a second and then stopped. The loop should do nothing. 

    #include <MIDI.h> 
    
    // connect the MIDI library to serial port TX1
    MIDI_CREATE_DEFAULT_INSTANCE();
    
    void setup() {
      MIDI.begin();
      for (int note=60; note <= 72; note++) {
          MIDI.sendNoteOn(note, 100, 1);
          delay(100);
          MIDI.sendNoteOff(note, 100, 1);
      }
    }
    
    void loop() {
    }

    You will have to connect some MIDI instrument via the old fashioned MIDI cable, and have to listen on MIDI channel 1. If you don’t hear anything, you may switch on your amp, move the MIDI plug to your instrument’s MIDI in, or swap MIDI pin 4 and 5 (a wrong connection won’t do any harm). 

    Step 2: ‚Press the sustain pedal‘ if a push button is pressed

    We will use the code from above, but will check the status in the loop() function. To avoid multiple sends we have to capture the send status, thus we only send the control message ’sostenuto pedal = ON‘ if the button is pressed AND the message hasn’t been sent already.

    Here comes the fritzing board:

    Same as above, but now we have to react to the push button…

    Step 2 a): Send a C when you press the button (sketch is the same)

    #include <MIDI.h>
    
     // connect the MIDI library to serial port TX1
     MIDI_CREATE_DEFAULT_INSTANCE();
    
     const unsigned int PUSH_BUTTON_PIN = 2;
     const byte INTRO_NOTE = 108;
     const byte BUTTON_NOTE = 60;
     const byte CHANNEL = 1;
     const byte VELOCITY = 100;
    
     bool sent;
    
     void setup() {
       sent = false;
       MIDI.begin();
       pinMode(PUSH_BUTTON_PIN, INPUT_PULLUP); 
       MIDI.sendNoteOn(INTRO_NOTE, 100, 1);
       delay(500);
       MIDI.sendNoteOff(INTRO_NOTE, 100, 1);
     }
     void loop() {
       unsigned int buttonState = digitalRead(PUSH_BUTTON_PIN);
       // if button pressed and not  sent
         // send note on
       if (LOW == buttonState && !sent) {
         MIDI.sendNoteOn(BUTTON_NOTE, VELOCITY, CHANNEL);
         sent = true;      
       }
       // if button not pressed and sent
         // send note off
       if (HIGH == buttonState && sent) {
         MIDI.sendNoteOff(BUTTON_NOTE, VELOCITY, CHANNEL);
         sent = false;  
       }
       delay(10);
     }

    Step 2 b): Send the Control Change when you press the button

    #include <MIDI.h>
    
    MIDI_CREATE_DEFAULT_INSTANCE();
    
    const unsigned int PUSH_BUTTON_PIN = 2;
    
    const unsigned int SUSTAIN_PEDAL = 64;
    const unsigned int SOSTENUTO_PEDAL = 66;
    
    const byte INTRO_NOTE = 108;
    const byte BUTTON_NOTE = 60;
    const byte CHANNEL = 1;
    const byte VELOCITY = 100;
    const byte CC_OFF = 0;
    const byte CC_ON = 127;
    
    bool sent;
    void setup() {
      sent = false;
      MIDI.begin();
      pinMode(PUSH_BUTTON_PIN, INPUT_PULLUP); 
      MIDI.sendNoteOn(INTRO_NOTE, 100, 1);
      delay(500);
      MIDI.sendNoteOff(INTRO_NOTE, 100, 1);
    }
    
      void loop() {
        unsigned int buttonState = digitalRead(PUSH_BUTTON_PIN);
        if (LOW == buttonState && !sent) {
          MIDI.sendControlChange(SUSTAIN_PEDAL, CC_ON, CHANNEL);
          sent = true;
        }
        if (HIGH == buttonState && sent) {
          MIDI.sendControlChange(SUSTAIN_PEDAL, CC_OFF, CHANNEL);
          sent = false;
        }
        delay(10);
      }

    Step 3: Add DIP switches for the controller number and the MIDI channel

    There are 16 MIDI channels (1..16) which could be defined by a four way DIP-switch connected to ground and four input channels. And if we understand how to read these four ( 4 bit) switches, we easily could extend our code to define the control change number (0..127, thus 7 bit).

    At the moment we can take this route but we already have in mind that this approach consumes a hefty 11 Teensy input channels.

    The code to read the MIDI channel DIP switch is pretty straight forward. Obviously this has to be placed in the setup() function. Since we placed this routine in the setup() function, it will only be read once – during startup.

    To be consistent we read from left to right, thus the control channel bit 0 is the left DIP switch labeled with ‚1‘, etc. (BTW: In the original setting I used a 4 way DIP switch instead of two two way ones…)

    #include <MIDI.h> 
    
     MIDI_CREATE_DEFAULT_INSTANCE();
    
     const unsigned int PUSH_BUTTON_PIN = 2;
    
     const unsigned int SUSTAIN_PEDAL = 64;
     const unsigned int SOSTENUTO_PEDAL = 66;
     
     const byte INTRO_NOTE = 108;
     const byte BUTTON_NOTE = 60;
     const byte VELOCITY = 100;
     
     const byte CC_OFF = 0;
     const byte CC_ON = 127;
    
     bool sent;
     unsigned int channel;
    
     void setup() {
      
       sent = false;
       MIDI.begin();
    
       pinMode(PUSH_BUTTON_PIN, INPUT_PULLUP); // button
    
       pinMode(3, INPUT_PULLUP);
       pinMode(4, INPUT_PULLUP);
       pinMode(5, INPUT_PULLUP);
       pinMode(6, INPUT_PULLUP);
       
       channel = digitalRead(6) << 3;
       channel |= digitalRead(5) << 2;
       channel |= digitalRead(4) << 1;
       channel |= digitalRead(3); 
       channel++; // 1..16!
       
     }
     
     void loop() {
       unsigned int buttonState = digitalRead(PUSH_BUTTON_PIN);
       if (LOW == buttonState && !sent) {
         MIDI.sendControlChange(SUSTAIN_PEDAL, CC_ON, channel);
         sent = true;
       }
       if (HIGH == buttonState && sent) {
         MIDI.sendControlChange(SUSTAIN_PEDAL, CC_OFF, channell);
         sent = false;  
       }
       delay(10);
     }

    The control change DIP switch will be set up accordingly. But as you can imagine, we are running out of pins pretty quickly. Since we want three push buttons in our sketch, we would need 3×8+4 = 28 ports just for the three buttons.

    Future improvements

    • Step 4: Add an input shift register to reduce the number of Teensy ports. 
    • Step 5: Cater for different types of control change messages
    • Step 6: Add rotary input controls
    • Step 7: Add status save buttons for the rotary controls
  • Arduino state machines with function pointers

    Rudysmodelrailway implements a railway crossing with blinking lights by introducing a state rdudiagram, which he then in turn implements by switch statements. Here is my take on the state diagram of a (one way) railway crossing with sensor S1 detecting an incoming train and sensor S2 detecting if the train has passed the crossing:

    This looks a bit too messy (but maybe I thought a bit too complicated), so let’s split the problem in two parts: In the first part we just have the blinking lights in the second, we add the gates.

    Now let’s have a look at the blinking-only version: Let’s assume the sensors are less then one train lengths apart and installed on both sides of the railway crossing. The following pictures give us an impression on what to show when.

    In state 0 the crossing is idle. In state 1 the first sensor sees the train, this the blinking should start.
    In state 2 both sensor see the train, blinking is ON. In state 3 only the left sensor sees the train, the blink continues. 

    So, the bottom line is: „Blink if at least one sensor is detecting something, otherwise be quiet“. To describe this behavior we use a thing called a ’state transition table‘ (https://en.wikipedia.org/wiki/Finite-state_machine) :[table id=8 /]

    This state transition table can be realized as so:

    // teensy 3.6
    
     const unsigned int S1_PORT = 1;
     const unsigned int S2_PORT = 2;
     const unsigned int LED1_PORT = 3;
     const unsigned int LED2_PORT = 4;
     unsigned int blinkingLightsDuration = 300;
     unsigned int blinkingLightsLeft;
     unsigned int blinkingLightsRight;
     unsigned long oldSensorTimer;
    
     void setup() {
       oldSensorTimer = millis();  
       pinMode(LED1_PORT, OUTPUT);
       pinMode(LED2_PORT, OUTPUT);
       pinMode(S1_PORT, INPUT_PULLUP);
       pinMode(S2_PORT, INPUT_PULLUP);
     }
    
     void loop() {
       unsigned int sensorValue = detectSensor();
       switch (sensorValue) {
         case HIGH:
           blinkingLightsOn();
           break;
         case LOW:
           blinkingLightsOff();
           break;
       }
       blinkingLightsSend();
       delay(123);
     }
    
     unsigned int detectSensor(void) {
       // if one or both of the buttons are pressed, return 1
       return 
        (!digitalRead(S1_PORT) || !digitalRead(S2_PORT)) ? 1 : 0;
     }
     void blinkingLightsOn() {
       unsigned long timer = millis();
       if (timer - oldSensorTimer > blinkingLightsDuration) {
         blinkingLightsLeft = 
              (blinkingLightsLeft == LOW) ? HIGH : LOW;
         blinkingLightsRight = !blinkingLightsLeft;
         oldSensorTimer = timer;
       }
     }
     void blinkingLightsOff() {
       blinkingLightsLeft = LOW;
       blinkingLightsRight = LOW;
     }
     void blinkingLightsSend() {
       digitalWrite(LED1_PORT, blinkingLightsLeft);
       digitalWrite(LED2_PORT, blinkingLightsRight);
     }

    The loop function looks already a bit messy, but bear in mind we haven’t even introduced the gates yet.

    This is one of the standard ways to implement finite state automatons: write down the state transition table and implement it as cascading switch clauses.[table id=9 /]

    Here we have a slightly improved version of the state transition table. Instead of text we use a function style syntax. How would this better implemented in C?

    To answer this we need a bit of knowledge about function pointers, so have a look at this: http://www.newty.de/fpt/index.html

    If you want to understand function pointers a bit better, have a look at http://johnsantic.com/comp/state.html. The way he implements the FSA is quite straight forward, but not at all easy to understand. 

    Let’s try to implement the transition table in a way similar to John’s way.

    // teensy 3.6
    
    // cf. http://johnsantic.com/comp/state.html
    
     const unsigned int S1_PORT = 1;
     const unsigned int S2_PORT = 2;
    
     const unsigned int LED1_PORT = 3;
     const unsigned int LED2_PORT = 4;
    
     unsigned int blinkingLightsDuration = 300;
     unsigned int blinkingLightsLeft;
     unsigned int blinkingLightsRight;
     unsigned long oldSensorTimer;
    
     void blinkingLightsOn();
     void blinkingLightsOff();
     void doNothing();
    
     enum States {IS_OFF, IS_ON, MAX_STATES} states;
     enum Events 
        {BUTTON_NOT_PRESSED, 
           AT_LEAST_ONE_BUTTON_PRESSED, MAX_EVENTS} events;
    
     // { action_s1_e1, action_s1_e2, action_s1_e3, action_s1_e4 },
     // { action_s2_e1, action_s2_e2, action_s2_e3, action_s2_e4 }
    
     void (*const state_table [MAX_STATES][MAX_EVENTS]) (void) = {
       { doNothing, blinkingLightsOn },
       { blinkingLightsOff, blinkingLightsOn }
     };
    
     States state = IS_OFF;
    
     void setup() {
       oldSensorTimer = millis();  
       pinMode(LED1_PORT, OUTPUT);
       pinMode(LED2_PORT, OUTPUT);
       pinMode(S1_PORT, INPUT_PULLUP);
       pinMode(S2_PORT, INPUT_PULLUP);
     }
    
     void loop() {
       Events event = detectSensor();
       state_table[state][event]();
       delay(123); 
     }
    
     Events detectSensor(void) {
       Events e;
       if (
         LOW == digitalRead(S1_PORT) || 
         LOW == digitalRead(S2_PORT)
       )
         e = AT_LEAST_ONE_BUTTON_PRESSED;
       else
         e = BUTTON_NOT_PRESSED;
       return e;
     }
    
     void doNothing() {};
    
     void blinkingLightsOn() {
       unsigned long timer = millis();
       if (timer - oldSensorTimer > blinkingLightsDuration) {
         blinkingLightsLeft = 
            (blinkingLightsLeft == LOW) ? HIGH : LOW;
         blinkingLightsRight = !blinkingLightsLeft;
         oldSensorTimer = timer;
       }
       blinkingLightsSend();
       state = IS_ON;
     }
    
     void blinkingLightsOff() {
       blinkingLightsLeft = LOW;
       blinkingLightsRight = LOW;
       blinkingLightsSend();
       state = IS_OFF;
     }
    
     void blinkingLightsSend() {
       digitalWrite(LED1_PORT, blinkingLightsLeft);
       digitalWrite(LED2_PORT, blinkingLightsRight);
     }

    You find the tricky bits in the loop() function. 

    It is tricky, because the switch statement has magically disappeared. Instead of the switch statement, you just call (!) an array element, which turns out to be a function, indexed by state and event. 

    To implement it you have to do this:

    • You define an enum for the states of the finite state machine, for your convenience add a MAX_STATES to it. This field is helpful in loops.
    • You define an enum for the events of the finite state machine, for your convenience add a MAX_EVENTS to it. 
    • You define all functions before referring to them.
    • You create a two dimensional table with MAX_STATES rows and MAX_EVENTS columns containing pointers to the functions which process the given combination. In case of doNothing() at an empty function…

    Example: When the FSM is in state „IS_OFF“ and receives an event „AT_LEAST_ONE_BUTTON_PRESSED“ then the function pointer table is referring to the function blinkingLightsOn(). Thus this function will be called. Within this function the state will be set accordingly (new state: „IS_ON“, leading to a new route, when the next events is read.

    How to extend to the final version with railway gates and IR sensors

    How IR sensors can replace the simple micro buttons can be learned here:https://cms.vp-consulting.de/arduino-ir-sensor-to-trigger-onboard-led/

    If you now want to extend this solution then to the version with gates, it seems to be very easy:

    • Add the servo to the sketch.
    • Add two function, one for raising the bars, one for lowering them.
    • Add these two functions to the functions which now trigger the blinkingLightsSend() function.

    If you see the risk the bars are not lowered before the train passes the crossing, place the detectors further apart and add a detector in the middle. 

    The logic with three sensors seems to be 100% identical.