Saturday 21 December 2019

microcontroller - Stuck with deciding the location and the type of variable declarations for this MCU code


I'm using ATmega328P with Atmel Studio. In the following code I declare almost all the variables inside the while loop:


#include //this is to use the Serial library
#include
#include
#define F_CPU 16000000UL

const int DATA_PIN = 6;


int main(void) {

DDRD = B0100000;
DDRD |= 1<<5;
Serial.begin(57600);

while (1) {

unsigned long data = 0;

uint8_t val;

for (int i=0; i<25; i++) {
data <<= 1;
PORTD &= ~(1 << 5);
_delay_us(2);
PORTD |= (1 << 5);
_delay_us(2);

val = 1 & (PIND >> PIND6);


data |= val;
}

PORTD &= ~(1 << 5);
_delay_us(2);
PORTD |= (1 << 5);
_delay_us(2);

alarm = 1 & (PIND >> PIND6);


//rest of the code....

unsigned long angle_count = data & 0x1FFF;
unsigned long turn_count = data >> 14;
float angle = (angle_count * 360UL) / 8192.0;

Serial.print(angle);
Serial.print(";");
Serial.print(turn_count);

Serial.print(";");
Serial.println(alarm);
}
}

In terms of speed and efficiency, I cannot be sure where to declare them. There are two more alternative places such as in the main but outside the while loop or right at the very beginning of the code after #define and %include libraries. Also how can we make judgement whether we need to use volatile or not?




No comments:

Post a Comment

arduino - Can I use TI&#39;s cc2541 BLE as micro controller to perform operations/ processing instead of ATmega328P AU to save cost?

I am using arduino pro mini (which contains Atmega328p AU ) along with cc2541(HM-10) to process and transfer data over BLE to smartphone. I...