Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <avr/io.h>
void USART_Init( unsigned int ubrr){
/* Set baud rate */
UBRR1H = (unsigned char)(ubrr>>8);
UBRR1L = (unsigned char)ubrr;
/* Enable receiver and transmitter */
UCSR1B = (1<<RXEN1)|(1<<TXEN1);
/* Set frame format: 8data, 2stop bit */
UCSR1C = (1<<USBS1)|(1<<UCSZ11)|(1<<UCSZ10);
} // USART_Init
void USART_Transmit( unsigned char data )
{
/* Wait for empty transmit buffer */
while ( !( UCSR1A & (1<<UDRE1)) )
;
/* Put data into buffer, sends the data */
UDR1 = data;
}
void USART_TransmitStr ( char *data )
{
for (; *data; data++) {
USART_Transmit(*data);
}
}
unsigned char USART_Receive( void )
{
/* Wait for data to be received */
while ( !(UCSR1A & (1<<RXC1)) )
;
/* Get and return received data from buffer */
return UDR1;
}
int main() {
USART_Init(51);
uint32_t a = 0, b = 0, result = 0;
unsigned char operator = 0;
while (1) {
unsigned char ch = USART_Receive();
switch (ch) {
case 8:
// Backspace.
if (!operator) {
a /= 10;
} else {
b /= 10;
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (!operator) {
a = a * 10 + (ch - '0');
} else{
b = b * 10 + (ch - '0');
}
break;
case '+':
case '-':
case '*':
case '/':
case '%':
operator = ch;
break;
case '\r':
case '=':
result = 0;
switch (operator) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
case '%':
result = a % b;
break;
}
if (ch == '\r') {
USART_Transmit('=');
} else {
USART_Transmit(ch);
}
char buffer[20];
sprintf(buffer, "%d\r\n", result);
USART_TransmitStr(buffer);
operator = 0;
a = b = 0;
continue;
default:
continue;
}
USART_Transmit(ch);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment