-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_machine.ino
More file actions
84 lines (77 loc) · 1.69 KB
/
stack_machine.ino
File metadata and controls
84 lines (77 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const int STACK_SIZE = 10;
float stack[STACK_SIZE];
int top = -1;
void push(float value) {
if (top < STACK_SIZE - 1) {
top++;
stack[top] = value;
}
}
float pop() {
if (top >= 0) {
float value = stack[top];//commit
top--;
return value;
}
return 0.0;
}
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
String instruction = Serial.readStringUntil('\n');
executeInstruction(instruction);
}
}
void executeInstruction(String instruction) {
instruction.trim();
Serial.print("Received: ");
Serial.println(instruction);
if (instruction.startsWith("PUSH")) {
float value = instruction.substring(5).toFloat();
push(value);
} else if (instruction == "POP") {
float value = pop();
Serial.print("Popped: ");
Serial.println(value);
} else if (instruction == "ADD") {
if (top >= 1) {
float b = pop();
float a = pop();
push(a + b);
} else {
Serial.println("Not enough operands for ADD");
}
} else if (instruction == "MUL") {
if (top >= 1) {
float b = pop();
float a = pop();
push(a * b);
} else {
Serial.println("Not enough operands for MUL");
}
} else if (instruction == "DIV") {
if (top >= 1) {
float b = pop();
float a = pop();
if (b != 0) {
push(a / b);
} else {
Serial.println("Division by zero");
}
} else {
Serial.println("Not enough operands for DIV");
}
} else {
Serial.println("Invalid instruction");
}
Serial.print("Stack: [");
for (int i = 0; i <= top; i++) {
Serial.print(stack[i]);
if (i < top) {
Serial.print(", ");
}
}
Serial.println("]");
}