Mandelbrot Set


With a 2.2" TFT you can do a lot of nice things. One of them is calculating the Mandelbrot set. People used to do it in the late 80s. Actually, there is nothing special about it, just take the standard algorithm and insert the graphic commands that are supported by the library you are using. With 320 x 240 pixels, the Arduino will take some three minutes to produce the picture.

When you are using the QVGA 2.2 TFT SPI 240x320 which is designed for 3.3 volt have a look at the level shifter.

#define FILENAME "APFELMAN"
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9340.h"

//#define _sclk 13
//#define _miso 12
//#define _mosi 11
#define _cs 10
#define _dc 9
#define _rst 8
Adafruit_ILI9340 tft = Adafruit_ILI9340(_cs, _dc, _rst);

void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit_ILI9340");
  Serial.println(FILENAME); 
  tft.begin();
  tft.setRotation(3);
  tft.fillScreen(ILI9340_BLACK);
  tft.println("Apfelman");
  int w = tft.width();
  int h = tft.height();
  int i, j;
  float x, y;
  float x1 = -1.5; float x2 = 0.5;
  float y2 = +1.0; float y1 = y2 - (x2 - x1) * h / w; 
  float dx = (x2 - x1) / w;
  float dy = dx;
  const float limit =  2;
  const int depth = 30;  
  float c, d;
  long t = millis();
  for (j = 0, y = y2; j < h; j++, y = y - dy) {
    for (i = 0, x = x1; i < w; i++, x = x + dx) {
      float real = x;
      float imag = y;
      float L = 0;
      int n = -1;
      while ( (L < limit) && (n < depth) ) {
        c = real; 
        d = imag;
        real = c * c - d * d + x;
        imag = 2 * c * d + y;
        L = sqrt(real * real + imag * imag);
        n++;        
      }
      if (n == depth) tft.drawPixel(i, j, 0);
      else {
        n = n & 0x0F;
        tft.drawPixel(i, j, 0x07 << n);
      }
    }
  }
  t = millis()- t;
  tft.setCursor(0,0);
  tft.print(t/1000);
  tft.print(" seconds");
  int x3 = -x1 * w / (x2-x1);
  int x4 = 0.5 * w / (x2-x1);
  int y3 = y2 * h / (y2-y1);
  tft.drawFastHLine(0, y3, w, 0xffff);
  tft.drawFastVLine(x3, 0, h, 0xffff);
  tft.drawFastVLine(x4, 0, h, 0x1111);
  tft.setCursor(x3+2,y3+2);
  tft.println(0);
  tft.setCursor(x4-10,y3+2);
  tft.println(-1);
}

void loop() { }




contact: nji(at)gmx.de