Factory 7: Power grid, on an Arduino Uno
A generator feeds the machines you build. Overbuild and the grid browns out, then blacks out; a governor mode matches supply to demand. Lamps, a servo meter and a buzzer report the state. The whole build, an Arduino Uno and 13 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Advanced About 50 minutes to build and run. Runs in your browser. Free, and no account needed.
The parts retail for about $40. On Mokxi they're free.
What you'll learn
- Displays
- Motors
- Sensors
- Reading a button
- Choosing and reading a resistor
- Difficulty: Advanced
- Time: About 50 minutes
- Board: Arduino Uno R3
- Parts: 19
How it works
A generator feeds the machines you build. Overbuild and the grid browns out, then blacks out; a governor mode matches supply to demand. Lamps, a servo meter and a buzzer report the state.
Arduino Uno R3 runs the sketch below. The circuit around it: TFT display, 240x320, Pushbutton, Resistor, 220 Ω, LED, green, LED, yellow, LED, red. pinMode sets BUILD_PIN as an input with its pull-up on. digitalRead reads whether b.pin is HIGH or LOW. analogRead measures the voltage on THROTTLE_KNOB as a number. Serial.begin opens the serial port at 9600 baud. tone plays a note on PIEZO_PIN.
Parts list
19 parts, plus the jumper wires. They retail for about $40; on Mokxi they're free.
- 1 × Arduino Uno R3In Starter Kit, Claw Machine Kit, Vending Machine Kit.
- 1 × TFT display, 240x320In Handheld Console Kit.
- 3 × PushbuttonIn Starter Kit, Christmas Lights Kit, Logic Lab Kit.
- 3 × Resistor, 220 ΩIn Starter Kit, Claw Machine Kit, Halloween Prop Kit.
- 1 × LED, greenIn Starter Kit, Halloween Prop Kit, Logic Lab Kit.
- 1 × LED, yellowIn Starter Kit, Halloween Prop Kit, Logic Lab Kit.
- 1 × LED, redIn Starter Kit, Halloween Prop Kit, Logic Lab Kit.
- 1 × Piezo speakerIn Starter Kit, Claw Machine Kit, Vending Machine Kit.
- 1 × Hobby servoIn Halloween Prop Kit, Christmas Lights Kit, Starter Projects Kit.
- 1 × PotentiometerIn Halloween Prop Kit, Starter Projects Kit.
- 5 × Power, 5 V
Wiring table
Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.
| Part and pin | Connects to |
|---|---|
| TFT display, 240x320 pin SCK | Arduino Uno R3 pin 13 |
| TFT display, 240x320 pin MOSI | Arduino Uno R3 pin 11 |
| TFT display, 240x320 pin CS | Arduino Uno R3 pin 10 |
| TFT display, 240x320 pin DC | Arduino Uno R3 pin 9 |
| Resistor, 220 Ω (3) pin 1 | Arduino Uno R3 pin 8 |
| Pushbutton (3) pin 1a | Arduino Uno R3 pin 7 |
| Piezo speaker pin 1 | Arduino Uno R3 pin 6 |
| Resistor, 220 Ω (2) pin 1 | Arduino Uno R3 pin 5 |
| Pushbutton (2) pin 1a | Arduino Uno R3 pin 4 |
| Resistor, 220 Ω (1) pin 1 | Arduino Uno R3 pin 3 |
| Pushbutton (1) pin 1a | Arduino Uno R3 pin 2 |
| Arduino Uno R3 pin GND | Ground |
| Potentiometer pin 2 | Arduino Uno R3 pin A0 |
| Hobby servo pin PWM | Arduino Uno R3 pin A1 |
| TFT display, 240x320 pin VCC | 5 V |
| TFT display, 240x320 pin GND | Ground |
| TFT display, 240x320 pin RST | 5 V |
| TFT display, 240x320 pin LED | 5 V |
| Pushbutton (1) pin 2a | Ground |
| Pushbutton (2) pin 2a | Ground |
| Pushbutton (3) pin 2a | Ground |
| LED, green pin A | Resistor, 220 Ω (1) pin 2 |
| LED, green pin C | Ground |
| LED, yellow pin A | Resistor, 220 Ω (2) pin 2 |
| LED, yellow pin C | Ground |
| LED, red pin A | Resistor, 220 Ω (3) pin 2 |
| LED, red pin C | Ground |
| Piezo speaker pin 2 | Ground |
| Hobby servo pin GND | Ground |
| Hobby servo pin VCC | 5 V |
| Potentiometer pin 1 | Ground |
| Potentiometer pin 3 | 5 V |
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Factory 7: Power grid. Every machine you build draws power.
//
// A generator feeds a row of machines. Press BUILD to add a machine and SCRAP
// to remove one. Each machine wants 30 units of power and the generator can
// give at most 100. Build too many and the grid cannot keep up: first it browns
// out (every machine runs slower in proportion), and past half power it
// blacks out and everything stops.
//
// The THROTTLE knob sets how much the generator tries to make. A real
// generator cannot change its output instantly, so it ramps toward the target
// at 15 units a second. Press GOVERNOR and the sketch steers the throttle for
// you, keeping supply just above demand.
//
// Wiring, board to parts:
// TFT CS -> pin 10 DC -> pin 9 SCK -> pin 13 MOSI -> pin 11
// RST and LED -> 5 V, VCC -> 5 V, GND -> GND
// BUILD button pin 2 SCRAP button pin 4 GOVERNOR button pin 7
// (each button from its pin to GND)
// Throttle knob (10k pot): middle leg -> A0
// Lamps through 220 ohm to GND: green pin 3, yellow pin 5, red pin 8
// Meter needle servo: signal -> A1 Piezo: pin 6 to GND
//
// # What this teaches
//
// 1. A shared resource. Supply is one number, demand is another, and every
// machine is slowed by the same ratio supply / demand. Nothing is switched
// off until the grid is really short, which is how a brownout feels.
// 2. Limits. The generator has a ceiling. No amount of knob turning gives more
// than 100, so past about three machines you are overbuilt, and the only fix
// is to build less or add generation.
// 3. Control and lag. Manual mode is open loop: you watch the numbers and
// turn the knob. Governor mode is closed loop: the sketch measures demand
// and sets the target to match. The ramp rate means a sudden jump in demand
// still causes a short brownout while the generator catches up.
// 4. Thresholds with hysteresis: the lamps and the alarm use three states, OK,
// BROWNOUT and BLACKOUT, chosen from the supply ratio.
#include <Servo.h>
#include "mokxi_ili9341.h"
const uint8_t TFT_CS = 10;
const uint8_t TFT_DC = 9;
const uint8_t TFT_SCK = 13;
const uint8_t TFT_MOSI = 11;
const uint8_t BUILD_PIN = 2;
const uint8_t GREEN_PIN = 3;
const uint8_t SCRAP_PIN = 4;
const uint8_t YELLOW_PIN = 5;
const uint8_t PIEZO_PIN = 6;
const uint8_t GOVERNOR_PIN = 7;
const uint8_t RED_PIN = 8;
const uint8_t METER_PIN = A1;
const uint8_t THROTTLE_KNOB = A0;
SoftSpi spi(TFT_SCK, TFT_MOSI, TFT_CS);
Ili9341 tft(spi, TFT_DC);
Servo meter;
const int16_t TILE = 16;
const int16_t WORLD_X = 8;
const int16_t WORLD_Y = 8;
const uint16_t STEEL = 0x8c71;
const uint16_t DARK = 0x10a2;
const uint16_t COPPER = 0xfc60;
const uint16_t GOOD = ILI9341_GREEN;
const uint16_t WARN = ILI9341_YELLOW;
const uint16_t BAD = ILI9341_RED;
const int MAX_MACHINES = 8;
const int DEMAND_PER_MACHINE = 30;
const int CAPACITY = 100; // the most the generator can make
const long RAMP_PER_SECOND = 15; // how fast output can change
const unsigned long CYCLE_MS = 4000; // one item per machine at full power
const int BAR_MAX = 240; // the bars show 0 to 240 units
// A button that reports a press once, after the contacts have stopped bouncing.
struct Button {
uint8_t pin;
bool raw;
bool stable;
unsigned long since;
};
static bool pressedOnce(Button &b) {
bool down = digitalRead(b.pin) == LOW;
unsigned long now = millis();
if (down != b.raw) {
b.raw = down;
b.since = now;
}
if (now - b.since >= 20 && b.stable != b.raw) {
b.stable = b.raw;
return b.stable;
}
return false;
}
Button buildButton = {BUILD_PIN, false, false, 0};
Button scrapButton = {SCRAP_PIN, false, false, 0};
Button governorButton = {GOVERNOR_PIN, false, false, 0};
enum GridState { OK, BROWNOUT, BLACKOUT };
int machines = 1;
long supplyMilli = 0; // thousandths of a unit, so a ramp is smooth
int demand = 0;
int satisfaction = 100; // percent of demand met, 0..100
GridState grid = OK;
bool governor = false;
unsigned long progress[MAX_MACHINES]; // ms of work done on the current item
unsigned long output = 0;
unsigned long lastFrame = 0, lastSpin = 0, lastReport = 0;
bool spinFrame = false;
bool alarmOn = false;
unsigned long lastBeep = 0;
// What the screen last showed.
int shownMachines = -1, shownSupply = -1, shownDemand = -1, shownSat = -1;
int8_t shownGrid = -1, shownMode = -1;
unsigned long shownOutput = 0xffffffffUL;
int shownSupplyBar = -1, shownDemandBar = -1;
uint8_t shownBar[MAX_MACHINES];
uint8_t nextMachineToDraw = 0;
static int16_t tileX(uint8_t c) { return (int16_t)(WORLD_X + c * TILE); }
static int16_t tileY(uint8_t r) { return (int16_t)(WORLD_Y + r * TILE); }
static uint16_t gridColour() { return grid == OK ? GOOD : (grid == BROWNOUT ? WARN : BAD); }
static void drawGenerator() {
tft.fillRect(tileX(0), tileY(3), 2 * TILE, 2 * TILE, STEEL);
tft.rect(tileX(0), tileY(3), 2 * TILE, 2 * TILE, DARK, 2);
uint16_t rotor = supplyMilli > 0 ? (spinFrame ? WARN : COPPER) : DARK;
tft.fillRect((int16_t)(tileX(0) + 9), (int16_t)(tileY(3) + 9), 14, 14, rotor);
tft.fillRect((int16_t)(tileX(0) + (spinFrame ? 14 : 9)), (int16_t)(tileY(3) + (spinFrame ? 9 : 14)), 4, 4, DARK);
}
// The power line runs from the generator along row 4 under every machine.
static void drawLine() {
tft.fillRect(tileX(2), (int16_t)(tileY(4) + 7), 8 * TILE, 2, COPPER);
}
static void drawMachine(uint8_t i) {
uint8_t col = (uint8_t)(2 + i);
bool built = i < machines;
uint16_t body = !built ? DARK : (grid == BLACKOUT ? 0x4208 : (grid == BROWNOUT ? 0x8400 : 0x2c0a));
tft.fillRect(tileX(col), tileY(5), TILE, TILE, built ? STEEL : DARK);
tft.fillRect((int16_t)(tileX(col) + 2), (int16_t)(tileY(5) + 2), TILE - 4, TILE - 4, body);
tft.fillRect(tileX(col), (int16_t)(tileY(4) + 8), 2, 8, built ? COPPER : DARK); // its tap off the line
shownBar[i] = 255;
}
static void drawBar(uint8_t i) {
uint8_t col = (uint8_t)(2 + i);
uint8_t filled = (uint8_t)((progress[i] * (TILE - 2)) / CYCLE_MS);
shownBar[i] = filled;
tft.fillRect((int16_t)(tileX(col) + 1), (int16_t)(tileY(6) + 3), TILE - 2, 4, DARK);
if (i < machines && filled > 0) {
tft.fillRect((int16_t)(tileX(col) + 1), (int16_t)(tileY(6) + 3), filled, 4, gridColour());
}
}
static void drawMeter(int16_t y, int value, uint16_t colour) {
int width = (int)(((long)value * 14 * TILE) / BAR_MAX);
if (width > 14 * TILE) {
width = 14 * TILE;
}
tft.fillRect(tileX(0), y, 14 * TILE, 8, DARK);
if (width > 0) {
tft.fillRect(tileX(0), y, (int16_t)width, 8, colour);
}
// a tick where the generator tops out
tft.fillRect((int16_t)(tileX(0) + (CAPACITY * 14 * TILE) / BAR_MAX), (int16_t)(y - 2), 2, 12, ILI9341_WHITE);
}
static void drawLabels() {
tft.text(8, 176, "SUP", ILI9341_WHITE, ILI9341_BLACK, 2);
tft.text(96, 176, "DEM", ILI9341_WHITE, ILI9341_BLACK, 2);
tft.text(8, 198, "MACH", ILI9341_WHITE, ILI9341_BLACK, 2);
tft.text(96, 198, "SAT", ILI9341_WHITE, ILI9341_BLACK, 2);
tft.text(192, 198, "%", ILI9341_WHITE, ILI9341_BLACK, 2);
}
static const char *gridName() {
return grid == OK ? "OK " : (grid == BROWNOUT ? "BROWNOUT" : "BLACKOUT");
}
// The same words without the padding, for the serial monitor.
static const char *gridWord() {
return grid == OK ? "OK" : (grid == BROWNOUT ? "BROWNOUT" : "BLACKOUT");
}
static void report() {
Serial.print("mach ");
Serial.print(machines);
Serial.print(" sup ");
Serial.print((int)(supplyMilli / 1000));
Serial.print(" dem ");
Serial.print(demand);
Serial.print(" sat ");
Serial.print(satisfaction);
Serial.print(" out ");
Serial.print(output);
Serial.print(" ");
Serial.print(gridWord());
Serial.print(" ");
Serial.println(governor ? "AUTO" : "MANUAL");
}
// One drawing job per call.
static void refresh() {
int supply = (int)(supplyMilli / 1000);
if (machines != shownMachines) {
int old = shownMachines < 0 ? 0 : shownMachines;
shownMachines = machines;
for (int i = old < machines ? old : machines; i < MAX_MACHINES && i <= (old > machines ? old : machines); i++) {
drawMachine((uint8_t)i);
}
tft.number(8 + 5 * 12, 198, machines, ILI9341_YELLOW, ILI9341_BLACK, 2, 1);
} else if (supply != shownSupply) {
shownSupply = supply;
tft.number(8 + 4 * 12, 176, supply, ILI9341_YELLOW, ILI9341_BLACK, 2, 3);
} else if (demand != shownDemand) {
shownDemand = demand;
tft.number(96 + 4 * 12, 176, demand, ILI9341_ORANGE, ILI9341_BLACK, 2, 3);
} else if (satisfaction != shownSat) {
shownSat = satisfaction;
tft.number(96 + 4 * 12, 198, satisfaction, gridColour(), ILI9341_BLACK, 2, 3);
} else if ((int8_t)grid != shownGrid) {
shownGrid = (int8_t)grid;
tft.text(8, 220, gridName(), gridColour(), ILI9341_BLACK, 2);
for (uint8_t i = 0; i < MAX_MACHINES; i++) {
shownBar[i] = 254; // repaint the machines in the new colour, one per call below
}
nextMachineToDraw = 0;
} else if ((int8_t)governor != shownMode) {
shownMode = (int8_t)governor;
tft.text(136, 220, governor ? "AUTO " : "MANUAL", ILI9341_CYAN, ILI9341_BLACK, 2);
} else if (supply / 4 != shownSupplyBar) {
shownSupplyBar = supply / 4;
drawMeter(tileY(1) + 4, supply, GOOD);
} else if (demand / 4 != shownDemandBar) {
shownDemandBar = demand / 4;
drawMeter(tileY(2) + 4, demand, ILI9341_ORANGE);
} else if (output != shownOutput) {
shownOutput = output;
tft.number(168, 176, (long)output, ILI9341_WHITE, ILI9341_BLACK, 2, 3);
} else {
// machine bars, one machine per call, round robin
uint8_t i = nextMachineToDraw;
nextMachineToDraw = (uint8_t)((nextMachineToDraw + 1) % MAX_MACHINES);
if (shownBar[i] == 254) {
drawMachine(i);
}
uint8_t filled = (uint8_t)((progress[i] * (TILE - 2)) / CYCLE_MS);
if (filled != shownBar[i]) {
drawBar(i);
}
}
}
void setup() {
Serial.begin(9600);
pinMode(BUILD_PIN, INPUT_PULLUP);
pinMode(SCRAP_PIN, INPUT_PULLUP);
pinMode(GOVERNOR_PIN, INPUT_PULLUP);
pinMode(GREEN_PIN, OUTPUT);
pinMode(YELLOW_PIN, OUTPUT);
pinMode(RED_PIN, OUTPUT);
meter.attach(METER_PIN);
meter.write(180);
tft.begin();
tft.rect(WORLD_X - 3, WORLD_Y - 3, 14 * TILE + 6, 10 * TILE + 6, 0x4a49, 2);
drawLabels();
drawLine();
drawGenerator();
for (uint8_t i = 0; i < MAX_MACHINES; i++) {
drawMachine(i);
drawBar(i);
}
for (uint8_t i = 0; i < 16; i++) {
refresh();
}
report();
lastFrame = lastSpin = lastReport = millis();
}
void loop() {
unsigned long now = millis();
unsigned long elapsed = now - lastFrame;
lastFrame = now;
if (pressedOnce(buildButton) && machines < MAX_MACHINES) {
machines++;
tone(PIEZO_PIN, 800, 40);
report();
}
if (pressedOnce(scrapButton) && machines > 0) {
machines--;
tone(PIEZO_PIN, 500, 40);
report();
}
if (pressedOnce(governorButton)) {
governor = !governor;
tone(PIEZO_PIN, governor ? 1000 : 600, 60);
report();
}
// Demand is what the machines want. The target is what the generator is told
// to make: the knob in manual mode, demand plus a small margin in auto mode.
demand = machines * DEMAND_PER_MACHINE;
long target;
if (governor) {
target = demand > 0 ? demand + 4 : 0;
} else {
target = ((long)analogRead(THROTTLE_KNOB) * CAPACITY) / 1023L;
}
if (target > CAPACITY) {
target = CAPACITY;
}
// The generator ramps toward the target, never faster than RAMP_PER_SECOND.
long step = (long)elapsed * RAMP_PER_SECOND; // thousandths of a unit
long goal = target * 1000L;
if (supplyMilli < goal) {
supplyMilli = supplyMilli + step > goal ? goal : supplyMilli + step;
} else if (supplyMilli > goal) {
supplyMilli = supplyMilli - step < goal ? goal : supplyMilli - step;
}
// How much of the demand is met, and what state that is.
long supply = supplyMilli / 1000;
satisfaction = demand == 0 ? 100 : (int)((supply * 100L) / demand);
if (satisfaction > 100) {
satisfaction = 100;
}
GridState now_state = satisfaction >= 97 ? OK : (satisfaction > 50 ? BROWNOUT : BLACKOUT);
if (now_state != grid) {
grid = now_state;
report();
}
// Lamps, the meter needle and the alarm.
digitalWrite(GREEN_PIN, grid == OK ? HIGH : LOW);
digitalWrite(YELLOW_PIN, grid == BROWNOUT ? HIGH : LOW);
digitalWrite(RED_PIN, grid == BLACKOUT ? HIGH : LOW);
meter.write(satisfaction * 180 / 100);
if (grid == BLACKOUT && now - lastBeep >= 600) {
lastBeep = now;
tone(PIEZO_PIN, 250, 200);
}
// Each machine's work moves at the supplied fraction of full speed, and
// stops completely in a blackout.
if (grid != BLACKOUT) {
for (int i = 0; i < machines; i++) {
progress[i] += (elapsed * (unsigned long)satisfaction) / 100UL;
if (progress[i] >= CYCLE_MS) {
progress[i] -= CYCLE_MS;
output++;
report();
}
}
}
if (now - lastSpin >= 150) {
lastSpin = now;
spinFrame = !spinFrame;
drawGenerator();
}
refresh();
}
Code walkthrough
The key functions of the sketch, and what each one does.
setup sketch.ino
Runs once when the board starts. It gets the pins and libraries ready.
void setup() {
Serial.begin(9600);
pinMode(BUILD_PIN, INPUT_PULLUP);
pinMode(SCRAP_PIN, INPUT_PULLUP);
pinMode(GOVERNOR_PIN, INPUT_PULLUP);
pinMode(GREEN_PIN, OUTPUT);
pinMode(YELLOW_PIN, OUTPUT);
pinMode(RED_PIN, OUTPUT);
meter.attach(METER_PIN);
meter.write(180);
tft.begin();
tft.rect(WORLD_X - 3, WORLD_Y - 3, 14 * TILE + 6, 10 * TILE + 6, 0x4a49, 2);
drawLabels();
drawLine();
drawGenerator();
for (uint8_t i = 0; i < MAX_MACHINES; i++) {
drawMachine(i);
drawBar(i);
}
for (uint8_t i = 0; i < 16; i++) {
refresh();
}
report();
lastFrame = lastSpin = lastReport = millis();
}loop sketch.ino
Runs over and over for as long as the board has power. This is where the project does its work.
void loop() {
unsigned long now = millis();
unsigned long elapsed = now - lastFrame;
lastFrame = now;
if (pressedOnce(buildButton) && machines < MAX_MACHINES) {
machines++;
tone(PIEZO_PIN, 800, 40);
report();
}
if (pressedOnce(scrapButton) && machines > 0) {
machines--;
tone(PIEZO_PIN, 500, 40);
report();
}
if (pressedOnce(governorButton)) {
governor = !governor;
tone(PIEZO_PIN, governor ? 1000 : 600, 60);
report();
}
// Demand is what the machines want. The target is what the generator is told
// to make: the knob in manual mode, demand plus a small margin in auto mode.
demand = machines * DEMAND_PER_MACHINE;
long target;
if (governor) {
target = demand > 0 ? demand + 4 : 0;
} else {
// ... 57 more lines in the editorTroubleshooting
The usual mistakes with this circuit, and the fix for each.
- The screen stays white or black. TFT display
Check the SPI wiring: CS, DC, RST, MOSI, SCK. Power the module at 3.3 V logic, or use level shifting on 5 V boards. Call begin() and set the rotation. - Slow drawing or garbled colors. TFT display
Use hardware SPI pins and avoid redrawing the whole screen. Fill only changed areas. Confirm the library matches ILI9341 and the color order. - The input reads random HIGH and LOW when the button is not pressed. Pushbutton
A floating pin picks up noise. Add a 10 k pull-down or pull-up resistor, or use INPUT_PULLUP and wire the button between the pin and GND. Then pressed reads LOW. - The button seems always pressed, or never changes. Pushbutton
A 4-leg tactile switch has legs joined in pairs. Place it across the breadboard center gap so the pairs sit on different rows. Wired along one side, the legs are already connected. - The LED is dim, burns out, or the pin reads wrong because the resistor value is off. Resistor
Read the color bands again. A 220 ohm to 330 ohm resistor suits a typical LED on 5 V. 10k is a common pull-up or pull-down value. Check with a multimeter if unsure. - A pull-up or pull-down resistor is missing, so the input floats and reads random values. Resistor
Tie the input to 5 V or ground through about 10k. Or use INPUT_PULLUP and wire the switch to ground. - The LED does not light, or it lights once and then dies. LED
LEDs have polarity. The longer leg (anode) goes toward the positive side. Always add a series resistor, about 220 ohms to 1 k ohm on a 5 V pin. - A blue or white LED stays dark on 3.3 V. LED
Blue and white LEDs drop about 3 V, so 3.3 V leaves almost nothing for the resistor. Use a 5 V supply, or a smaller resistor and a red or green LED.
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.