Posted at
ArduinoDay 7

arduinoでアセンブラ

More than 3 years have passed since last update.

arduino unoでインライン アセンブラをやってみました。


サンプルコード

byte b[32];

byte g;
void print_r()
{
asm volatile(
"push r16 \n\t"
"push r17 \n\t"
"push r18 \n\t"
"push r19 \n\t"
"push r20 \n\t"
"push r21 \n\t"
"push r22 \n\t"
"push r23 \n\t"
"push r24 \n\t"
"push r25 \n\t"
"push r26 \n\t"
"push r27 \n\t"
"push r28 \n\t"
"push r29 \n\t"
"push r30 \n\t"
"push r31 \n\t"
"sts (b), r0 \n\t"
"sts (b + 1), r1 \n\t"
"sts (b + 2), r2 \n\t"
"sts (b + 3), r3 \n\t"
"sts (b + 4), r4 \n\t"
"sts (b + 5), r5 \n\t"
"sts (b + 6), r6 \n\t"
"sts (b + 7), r7 \n\t"
"sts (b + 8), r8 \n\t"
"sts (b + 9), r9 \n\t"
"sts (b + 10), r10 \n\t"
"sts (b + 11), r11 \n\t"
"sts (b + 12), r12 \n\t"
"sts (b + 13), r13 \n\t"
"sts (b + 14), r14 \n\t"
"sts (b + 15), r15 \n\t"
"sts (b + 16), r16 \n\t"
"sts (b + 17), r17 \n\t"
"sts (b + 18), r18 \n\t"
"sts (b + 19), r19 \n\t"
"sts (b + 20), r20 \n\t"
"sts (b + 21), r21 \n\t"
"sts (b + 22), r22 \n\t"
"sts (b + 23), r23 \n\t"
"sts (b + 24), r24 \n\t"
"sts (b + 25), r25 \n\t"
"sts (b + 26), r26 \n\t"
"sts (b + 27), r27 \n\t"
"sts (b + 28), r28 \n\t"
"sts (b + 29), r29 \n\t"
"sts (b + 30), r30 \n\t"
"sts (b + 31), r31 \n\t"
"in r16, 0x3f \n\t"
"sts (g), r16 \n\t"
::: "r16"
);
for (int i = 0; i < 32; i++)
{
Serial.print("r");
if (i < 10)
{
Serial.print(0);
}
Serial.print(i);
Serial.print(" = ");
Serial.print(b[i] >> 4, HEX);
Serial.print(b[i] & 0x0f, HEX);
if ((i + 1) % 8)
{
Serial.print(" ");
}
else
{
Serial.println(";");
}
}
Serial.print("flag: c = ");
Serial.print(g & 0x01);
Serial.print(" z = ");
Serial.print((g >> 1) & 0x01);
Serial.print(" n = ");
Serial.print((g >> 2) & 0x01);
Serial.print(" v = ");
Serial.print((g >> 3) & 0x01);
Serial.print(" s = ");
Serial.print((g >> 4) & 0x01);
Serial.print(" h = ");
Serial.print((g >> 6) & 0x01);
Serial.print(" t = ");
Serial.print((g >> 6) & 0x01);
Serial.print(" i = ");
Serial.println(g >> 7);
Serial.println(";");
asm volatile(
"lds r31, (g) \n\t"
"out 0x3f, r31 \n\t"
"pop r31 \n\t"
"pop r30 \n\t"
"pop r29 \n\t"
"pop r28 \n\t"
"pop r27 \n\t"
"pop r26 \n\t"
"pop r25 \n\t"
"pop r24 \n\t"
"pop r23 \n\t"
"pop r22 \n\t"
"pop r21 \n\t"
"pop r20 \n\t"
"pop r19 \n\t"
"pop r18 \n\t"
"pop r17 \n\t"
"pop r16 \n\t"
:::
);
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
print_r();
delay(900);
}