Convert to Registers only code

Hi all,

I'm new to arduino and I cannot figure how to convert in registers only code.

Can someone help me with the conversion to registers only for the following code?

long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}

This is how i tried to do it but failed miserably.

long readUltrasonicDistance(int triggerPin, int echoPin)
{
DDRD = 1 << DDB1;
PORTB = 0 << PORTB1;
delayMicroseconds(2);
PORTB = 1 << PORTB1;
delayMicroseconds(2);
PORTB = 0 << PORTB1;
DDRD = 0 << DDB2;
return pulseIn(DDB2, HIGH);
}

I cannot figure how to convert in registers only code.

Why are you trying to do this? It makes the code unreadable and unportable. You don't need the speed gain for that usage. So I really see no need for it.

The first two lines would read:

  DDRD |= 1 << DDB1;
  PORTB &= ~(1 << PORTB1);

So you should be able to adapt the rest of the lines yourself (if you still think you need it).

It certainly makes no sense to mix register and port pin mnemonics like this.

  DDRD |= 1 << DDB1;

DDRD is the data direction register for port D.
DDB1 is pin 1 of data direction register for port B.

If you are writing to port B, consider modifying DDRB instead.

It certainly makes no sense to mix register and port pin mnemonics like this.

This is the bit layout for DDRD Register of ATmega328; where, the symbolic names of the bits are not recognized by Arduino Compiler; but, DDB1 (Bit-1 of DDRD Register?) is recognized by the compiler. I am curious to know the source of DDB1.

Bit-1 of DDRD Register

No. The ATmega328 data sheet states:

DDB1.png

DDB1.png

Now, we may find that the following symbolic names are accepted to the compiler for the implied meanings:

DDRB : DDB7, ..., DDB0
DDRC : DDC5, ..., DDC0
DDRD : DDD7, ..., DDD0

What are these?

If one wants to output a value on a port B pin, it is wise to ensure that the data direction register for port B is set appropriately.

What are these?

I don't know. I have seen that data sheet with the DDRxn identification for the bits. I believe it is from Atmel in 2016, and it is conflict with a different version I have from 2015 which uses the DDxn identifier.

The latest sheet I see from Microchip with a 2018 date shows the DDxn instead of the DDRxn notation. The compiler supports the DDxn through iom328p.h with this

#define DDRB _SFR_IO8(0x04)
#define DDB0 0
#define DDB1 1
#define DDB2 2
#define DDB3 3
#define DDB4 4
#define DDB5 5
#define DDB6 6
#define DDB7 7

Cool! :slight_smile: