Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <avr\io.h>
- #include <util\delay.h>
- #include <stdio.h>
- #include "moreTypes.h"
- #define true -1
- #define false 0
- #define F_CPU 16000000UL // Frequency of processor
- #define BAUD 9600 // Baud rate of serial connections
- void initUART() {
- #include <util\setbaud.h>
- UBRR0H = UBRRH_VALUE;
- UBRR0L = UBRRL_VALUE;
- #if USE_2X
- UCSR0A |= _BV(U2X0);
- #else
- UCSR0A &= ~_BV(U2X0);
- #endif
- UCSR0C = _BV(UCSZ01) | _BV(UCSZ00); // Use 8-bit data
- UCSR0B = _BV(RXEN0) | _BV(TXEN0); // Enable RX/TX
- }
- // Read a byte from the UART
- ubyte getByte(int iWaitData) {
- // If wait flag set, loop until data is ready on RX
- if (iWaitData)
- loop_until_bit_is_set(UCSR0A, RXC0);
- // Return byte from serial UART
- return UDR0;
- }
- int readString(char* str, int iMaxLength) {
- ubyte tmpByte;
- int iDataRead = 0;
- while (1) {
- tmpByte = getByte(true);
- switch(tmpByte) {
- // If we read a newline the string parsing is done
- case '\r': case '\n':
- str[iDataRead] = '\0'; // Set last char to null-terminator
- return iDataRead; // Return length of string read
- case 0x7F: // Backspace
- str[iDataRead] = '\0'
- if (iDataRead > 0)
- iDataRead--;
- break;
- case else:
- str[iDataRead++] = tmpByte;
- if (iDataRead >= iMaxLength)
- return iDataRead;
- }
- }
- }
- // Send a byte to the UART
- void sendByte(ubyte data) {
- loop_until_bit_is_set(UCSR0A, UDRE0); // Wait until data register empty
- UDR0 = data;
- }
- // Send raw data of specified size over serial
- void sendData(ubyte* data, int dataLen) {
- for (int i = 0; i < dataLen; i++)
- sendByte(data[i]);
- }
- // Send a null-terminated string over serial
- void sendString(char* str) {
- int i = 0;
- while (str[i] != 0) {
- sendByte(str[i++]);
- }
- }
- char* sBuff = "Read byte: 0xFF\r\n\0";
- void main() {
- initUART();
- while (1) {
- sprintf(sBuff, "Read byte: 0x%02X\r\n\0", getByte(true));
- sendString(sBuff);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement