Search code examples
assemblyavratmega

Port G ATmega128 AVR Assembly


I am trying to create a simple functionality by using portG.

If the switch in PG0 is closed, The led in PG1 should be turned on. Else, The led should be off. However, I do not know how to use one bit as output while the other one is input.

enter image description here


Solution

  • A C program like this should work:

    #include <avr/io.h>
    
    void main() {
      DDRG |= (1 << 1);
      while (true) {
        if (PING & (1 << 0)) {
          // Button is pressed so drive PG1 high.
          PORTG |= (1 << 1);
        }
        else {
          PORTG &= ~(1 << 1);
        }
      }
    }
    

    We can use Godbolt.org to convert that program to assembly:

    main:
            lds r24,100
            ori r24,lo8(2)
            sts 100,r24
    .L2:
            lds r24,99
            sbrs r24,0
            rjmp .L3
            lds r24,101
            ori r24,lo8(2)
            rjmp .L5
    .L3:
            lds r24,101
            andi r24,lo8(-3)
    .L5:
            sts 101,r24
            rjmp .L2
    

    (That's not a very good-looking assembly program because of the arbitrary numbers like 99 and 101, but you can probably figure out what registers those numbers refer to and replace those numbers with regester names. You'd also want to rename the labels.)