ATTiny104 Xplained Nano – Blink Code

ATTiny104 Xplained Nano – Blink Code

This is the code used in the following Tweet.

/*
 * Blink.cpp
 *
 * Created: 27/08/2019 18:57:18
 * Author : HiboTronix
 */ 

// 8MHz Internal Oscillator
#define F_CPU 8000000UL

#include <avr/io.h>
#include <util/delay.h>
#include <string.h>
#include "delay_timer.h"
#include "Serial.h"

int main(void) {
	Serial_Init();
	CCP = 0xD8; // CCP_IOREG_gc Set The Configuration Change Protection 
	            // Register To 0xD8 And Change CLKPSR Within 4 Clock Cycles 
	
	CLKPSR = 0; // Set Clock Prescaler To 1 For 8MHz Internal Clock
	DDRA = 0x20; // PA5 as output, Led Cathode Connected To Pin
	PORTA |= (1<<5); // PA5 High = Led Off
    while (1) {  // Equivilent To The Arduino Loop
		PORTA |= (1<<5); // PA5 High = Led Off
		Serial_println("Led Off");
		delay_ms(1000);
		PORTA &= ~(1<<5); //PA5 Low = Led On
		Serial_println("Led On");
		delay_ms(1000);
    }	
}
/*
 * Serial.h
 *
 * Created: 27/08/2019 18:57:18
 * Author : HiboTronix
 */ 

void Serial_Init() {
	UBRR = 0x33; // Set Baud To 9600
	UCSRA = (0<<U2X) | (0<<MPCM); // MCPM Off, Single Speed
	UCSRB = (1<<RXEN) | (1<<TXEN) | (0<<UCSZ2); // Enable Receiver And Transmitter
	UCSRC = (0<<UMSEL1) | (0<<UMSEL0) | (0<<UPM1) | (0<<UPM0) | (0<<USBS) | (1<<UCSZ1) | (1<<UCSZ0) | (0<<UCPOL); // Set Frame Format: 8N1
}

void Serial_Write(char data ) {
	/* Wait for empty transmit buffer */
	while (!(UCSRA & (1<<UDRE))) {}
	/* Put data into buffer, sends the data */
	UDR = data;
}

void Serial_Print(const char c[]) {
	for (uint8_t i = 0; i < strlen(c); i++) { // Loop Through Each Char
		Serial_Write(c[i]);
	}
}

void Serial_PrintLn(const char c[]) {
	for (uint8_t i = 0; i < strlen(c); i++) { // Loop Through Each Char
		Serial_Write(c[i]);
	}
	Serial_Write(13); // CR, Carriage Return
	Serial_Write(10); // LF, Line Feed	
}

unsigned char Serial_ReadByte( void ) {
	/* Wait For Data To Be Received */
	while (!(UCSRA & (1<<RXC))) {}
	/* Get And Return Received Data From Buffer */
	return UDR;
}

void Serial_Flush( void ) {
	unsigned char dummy;
	while (UCSRA & (1<<RXC)) {
		dummy = UDR;
	}
}
/*
 * Delay_Timer.h
 *
 * Created: 27/08/2019 18:57:18
 * Author : HiboTronix
 */ 

void delay_ms(uint16_t ms){
	while(ms){
		_delay_ms(1);
		ms--;
	}
}

Download “Blink.cpp” Blink.zip – Downloaded 41 times – 1 KB

Tagged with: , , , , ,

Leave a Reply