[Dev Log] Knock : Part 5

Serial on an 8 bit controller is hard to grasp. Especially if you're working in C. I mean you've got to take care of memory etc. So yeah, it's a bit annoying. No wonder Arduino was born. But hey, after much tinkering I finally did crack the code, so to speak. I had some help from the EvilMadScientist code. So here's my progress.


/*
Author: Pronoy Chopra
Description: Serial implementation and test.
*/
#define F_CPU 8000000UL /*Using the internal clock with 8 prescalar*/
#define BAUD 9600UL
#define BAUD_PRESCALE ((F_CPU / 16 / BAUD) - 1)

#include <avr/io.h>
#include <util/delay.h>
#include <util/setbaud.h>    


void SerialWrite(unsigned long Data) {
    while(!(UCSRA & (1 << UDRE)));
    UDR = Data;
}

int main(void) {

    UBRRH = (BAUD_PRESCALE >> 8);
    UBRRL = BAUD_PRESCALE;

    //UCSRA |= (1 << U2X);
    UCSRB |= (1 << TXEN); //| (1 << RXEN);
    UCSRC |= (1 << UCSZ1) | (1 << UCSZ0);

    while(1) {

        while(!(UCSRA & (1 << RXC))) {
            SerialWrite('Hello');
            _delay_ms(100);         
        }
    }
    return 0;
}

So when I configured pyserial to receive data from the controller, I received \x00 instead of the 'A' that I sent. It took me a while to realize that the compiler was throwing warnings. The BAUD and F_CPU were supposed to be configured as unsigned long types so the UBRR calculation wasn't correct. Now, when I fixed this, it worked just fine. So that's a good lesson. Heed the compiler's warnings yo.

The other thing now left to do is to understand if I can receive longer strings. I might have to look at what Arduino does for that. If they do something stupid like writing another subroutine to get it to work, I am gonna write it from scratch. Okay so, now since serial is done, I think I should start with the Analog sensor. I mean the Knock sensor is pretty unreliable, so I have to look into making it better.

Oh! There's something else I forgot to mention. Makefiles! I started using makefiles instead of going through the effort of compiling and linking and creating hex files from source code. Thanks to the guys at EMS, it's a hoot. It's all available on Github. The code and modified Makefile. One thing I am going to do is try to get Makefile accept file names *args. Lets see what can be done.

Oh by the way, apparently if you're using the internal clock, F_CPU has to be defined as the clock frequency without prescalar division.

The ATTiny2313 code that I learnt from is available on the EvilMadScientist website.