# Magic squares in a box

The aim of this project was to present all 4x4 magic squares. As calculation on a standard Arduino is rather slow it was decided to precalculate all the solutions and store them in the flash memory. They will be shown one after another while the speed of the performance can be controlled by a potentiometer, either upwards or downwards (or even zero).

It was decided not to use a 4x20 LCD rather than a 1.8"-TFT (128x160 pixels) which looks more square than the LCD type (if you are lucky you get that even cheaper). The wooden box contains

• a breadboard with the ATmega328, a small potentiometer, the crystal and capacitors
• the TFT display
• the batteries
• a switch like the one in your fridge (power off when the box is closed)

The potentiometer connected to A0 controls the delay time. If the position is in the middle the delay will be infinite. otherwise the number of the solution shown goes up or down. You can select the speed that gives you enough time to recheck all the sums. A small bar on the bottom of the screen shows the position of the potentiometer.

And a small red box flashes in the upper left corner to indicate the display currently is updated.

What you need:

 download the source: magic_square_precalc.ino download the solutions array: array4x2.h

If you prefer a version which sequentially highlights the groups of four which match 34 take this:

 download the source: magic_square_precalc2.ino download the solutions array: array4x2.h

How are the solutions stored in array4x2.h?

Well, you only need to store 8 cells for any solution as the other 8 ones can be calculated as you know the sum of four must be 34.

 16 12 1 5 9 3 14 8 7 13 4 10 2 6 15 11

Only the values of the cells printed in green have to be stored. To save memory, the values were decremented by 1 to fit into a nibble (0 - 15), two nibbles were joined to a byte, and four bytes were grouped to an array.

So the result looks like this:
 byte solutions[] PROGMEM = { { 251, 8, 45, 108 }, 251 = 15*16+11, 8 = 0*16+8, 45 = 2*16+13, 108 = 6*16+12 => 1st row: 16 12 1, 2nd row: 9 3 14, third row: 7 13 { 251, 6, 45, 140 }, 251 = 15*16+11, 6 = 0*16+6, 45 = 2*16+13, 140 = 8*16+12 => 1st row: 16 12 1, 2nd row: 7 3 14, third row: 9 13

Don't be surprised to hear that the calculation of this file was produced by an Arduino using this.

contact: nji(at)gmx.de 