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]);
}
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
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…)
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
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?
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.
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.