Flash | Ram | EEPROM | |
tiny 2313 | 2K | 128B | 128B |
tiny 84 | 4K | 512B | 512B |
tiny 85 | 8K | 512B | 512B |
mega 328 | 32KB | 2k | 1k |
The mega 328 has enough ram to use it carelessly. It's flash size is huge. translating a basic Arduino program into a tiny2313 might be a little challenging. So lets go over a few memory tricks worth mentioning. today we're still going to be using an Arduino as a target since I have one here and most people will too.
Data types int and char are very different beasts. Char is an integer type guaranteed to be 8 bits in size, int is 16bits. so a char is 1 byte, where as an int is 2 bytes. In general, use char when you can. unsigned it'll hold numbers 127 to -126, unsigned will get you 0-255. a trick that helps at least me is declaring the following at the top of my program: unless you need to go larger, chars will make that 128 bytes last a little longer.
Macros are the next bit of memory stretching arduino doesn't teach. if you have unchanging data, or constants, a define is better than a variable. take the following:
#define NUM_PINS 4
int num_pins 4;
The first line will insert a 4 anywhere the compiler sees NUM_PINS. This allows for centralized information without using ram to do it. The second line uses 16 bits to sore 3 bits of data. a char, or unsigned char is better fit, since it only uses 8 bits.
These are basic C items that you can use in the standard Arduino stuff. To get in the habit.
Lets revamp the fade code from the arduino examples a bit. The original uses 15 bytes of memory. the bare example uses 9, so those 6 bytes are from the 3 variables. This one does it in 12 bytes.
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
This example code is in the public domain.
*/
#define LED 9; // the pin that the LED is attached to
unsigned char fadeAmount 10; // how many points to fade the LED by
unsigned char brightness = 0; // how bright the LED is we need 0 to 255
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(LED, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(LED, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
No comments:
Post a Comment