3 * Arduino BrainFuck Interpreter
6 * Wanna real hardware BF processor?!
15 void brainfuck(int memory, char cycle, char *bfcode, char pwmpin, char ainpin) {
16 //Serial.println("BF-STARTED");
17 unsigned char tape[memory]; memset(tape, 0, sizeof(tape)); memory = 0;
18 int stack[cycle]; memset(stack, 0, sizeof(stack)); cycle = -1;
20 for(int i = 0;bfcode[i]!=0;i++) {
22 //Basic BF instructions
23 case '>': memory++; if(memory>=sizeof(tape)) { Serial.println("BF-EXIT-MEM-OVERFLOW!"); return; } break;
24 case '<': memory--; if(memory<0) { Serial.println("BF-EXIT-MEM-UNDERFLOW!"); return; } break;
25 case '+': tape[memory]++; break;
26 case '-': tape[memory]--; break;
27 case '.': Serial.print(tape[memory], BYTE); break;
28 case ',': while(Serial.available()<=0) delay(30); tape[memory] = Serial.read(); break;
29 case '[': cycle++; if(cycle>=sizeof(stack)) { Serial.println("BF-EXIT-STACK-OVERFLOW!"); return; } stack[cycle] = i; break;
30 case ']': if(tape[memory] != 0) { i = stack[cycle]-1; } cycle--; if(cycle<-1) { Serial.println("BF-EXIT-STACK-UNDERFLOW!"); return; } break;
31 //Optional BF instructions
32 case '#': Serial.print("BF-DEBUG: POS: "); Serial.print(memory, DEC);
33 Serial.print(" TAPE: "); Serial.println(tape[memory], BYTE);
34 Serial.print(" TAPE: "); Serial.println(tape[memory], BYTE);
36 case '@': Serial.println("BF-EXIT-BY-CODE!"); return; break;
37 //Arduino extensions for BF
38 case '!': if(pwmpin>=0 && tape[memory]>0 && tape[memory]<255) analogWrite(pwmpin, tape[memory]); break; //Set pwmpin output value
39 case '?': if(ainpin>=0) tape[memory]=analogRead(ainpin); break; //Read ainpin analog value (sux-a-bit)
40 case '_': delay(10); break; //Wait for a while
43 //Serial.println("BF-ENDED");
47 void setup() // run once, when the sketch starts
49 Serial.begin(baudrate);
51 //"++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."; //Hello World
53 //"[?!+]"; //Read ananlog input pin and write it's value to pwm output pin
54 //"[+[-!__]+++++++++++++++++++++++++++++++++++++++]"; //Fade LED on pwmpin
55 "[[-]++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.[-]<[-]<[-]<[-!_]<+]"; //Hello World with pwm fading
57 brainfuck(memsize, stacksize, bfcode, pwmoutpin, analoginpin);
61 void loop() { // run over and over again