Created
January 7, 2019 06:09
-
-
Save kcal2845/a2b53e2931c488c515351792ad4ab87c to your computer and use it in GitHub Desktop.
simple bf interpreter in arduino. original C interpreter : https://gist.github.com/maxcountryman/1699708
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#define TAPE_LENGTH 1000 | |
#define INPUT_LENGTH 300 | |
void interpret(char input[INPUT_LENGTH]) { | |
unsigned char tape[TAPE_LENGTH] = {0}; | |
unsigned char* ptr = tape; | |
char current_char; | |
size_t i; | |
size_t loop; | |
Serial.println("program loaded"); | |
for (i = 0; input[i] != 0; i++) { | |
current_char = input[i]; | |
if (current_char == '>') { | |
++ptr; | |
} else if (current_char == '<') { | |
--ptr; | |
} else if (current_char == '+') { | |
++*ptr; | |
} else if (current_char == '-') { | |
--*ptr; | |
} else if (current_char == '.' ) { | |
Serial.write(*ptr); | |
} else if (current_char == ',') { | |
while(1){ | |
if(Serial.available()>0){ | |
*ptr = Serial.read(); | |
break; | |
} | |
} | |
} else if (current_char == '[') { | |
continue; | |
} else if (current_char == ']' && *ptr) { | |
loop = 1; | |
while (loop > 0) { | |
current_char = input[--i]; | |
if (current_char == '[') { | |
loop--; | |
} else if (current_char == ']') { | |
loop++; | |
} | |
} | |
} | |
} | |
} | |
void setup(){ | |
Serial.begin(9600); | |
Serial.println("brainfuck interpreter. type your code."); | |
} | |
void loop(){ | |
String input_string; | |
char input_char[INPUT_LENGTH]; | |
if(Serial.available()>0){ | |
input_string = Serial.readString(); | |
input_string.toCharArray(input_char,INPUT_LENGTH); | |
interpret(input_char); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment