Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
en:multiasm:piot:chapter_4_9 [2026/02/06 16:33] raivo.sellen:multiasm:piot:chapter_4_9 [2026/02/27 01:13] (current) – [Examples] jtokarz
Line 8: Line 8:
  
 The choice of programming level depends on the project's specifics. C++ is ideal for creating complex applications, libraries facilitate rapid prototyping, and assembler provides maximum control and performance. Each of these levels has its place in AVR microcontroller programming. The choice of programming level depends on the project's specifics. C++ is ideal for creating complex applications, libraries facilitate rapid prototyping, and assembler provides maximum control and performance. Each of these levels has its place in AVR microcontroller programming.
 +
 +
 +Some AVR assembly examples for the Arduino Uno (ATmega328P), ready to drop directly into the Arduino IDE using inline assembly - asm volatile().
 +
 +===== Examples =====
 +
 +**Blink inbuilt LED on pin 13 (port PB5) using assembly**
 +<code c>
 +  void setup() {
 +    // Set PB5 (pin 13) as output  
 +    // if DDRB (Data Direction Register B) = 1, PORTB is output 
 +    asm volatile("sbi 0x04, 5");   // DDRB |= (1<<5)
 +  }
 +  void loop() {
 +    asm volatile("sbi 0x05, 5");   // LED ON  (PORTB |= (1<<5))
 +    delay(500);
 +    asm volatile("cbi 0x05, 5");   // LED OFF (PORTB &= ~(1<<5))
 +    delay(500);
 +  }
 +</code>
 +For Arduino Uno (ATmega328P):    
 +  * DDRB has address 0x04
 +  * PORTB has address 0x05
 +
 +----
 +
 +
 +**Add two numbers using AVR registers**
 +<code c>
 +  void setup() {
 +    Serial.begin(9600);
 +    uint8_t a = 7, b = 9, result;
 +    asm volatile(
 +      "mov r24, %1\n"   // r24 = a
 +      "mov r25, %2\n"   // r25 = b
 +      "add r24, r25\n"  // r24 = a + b
 +      "mov %0, r24\n"   // result = r24
 +      : "=r"(result)    // agrument %0
 +      : "r"(a), "r"(b)  // arguments %1, %2
 +      : "r24", "r25", "cc" // preserve the content of r24 and r25
 +    );
 +    Serial.println(result);
 +  }
 +  void loop() {}
 +</code>
 +----
 +
 +**Read digital input (PD2, bit 2 on PORTD)**
 +<code c>
 +  void setup() {
 +    Serial.begin(9600);
 +    asm volatile("cbi 0x0A, 2");   // DDRD &= ~(1<<2) → PD2 as input
 +  }
 +  void loop() {
 +    uint8_t value;
 +    asm volatile(
 +      "in %0, 0x09"     // Read PIND
 +      : "=r"(value)
 +    );
 +    Serial.println(value & (1<<2));
 +    delay(200);
 +  }
 +</code> 
en/multiasm/piot/chapter_4_9.1770388430.txt.gz · Last modified: by raivo.sell
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0