Starting with microcontrollers,  need some help. - Page 1
Forum section: electronics / general

author: Refrigerator
author_rank: Super Contributor
timestamp: February 18, 2014, 07:20:32 pm
content: I recently discovered this thing called micro controller and i immedeatly got hooked up by it.So far i've done some research, but didn't find what i was looking for.I've already ordered some ATtiny45, ATtiny2313, and some Atmega328 and some basic AVR and PIC programmers to go with them, but while they're being shipped i want to know some things.I already know how to hook the microcontroller up and put a program into it but i don't really know How to write the program.So far i know that there are such thing in those programs likevoid Setup () {pinMode (3, OUTPUT)}void loop () {digitalWrite (3, HIGH)delay 1000digitarWrite (3, LOW)delay 1000}This is a blinker if i'm right.But i don't really know much else like:What do those brackets mean - VoidLoop().What if i want to make the delay shorter or longer by a selected number each time when receiving a HIGH or LOW input from a selected pin what should i write in?Is this like programming with a calculator ( i have a TI-82 Stats ).Is there a book or something to read where i could learn the specific commands and how to use them?Thanks in advance.

author: madires
author_rank: Super Contributor
timestamp: February 18, 2014, 07:31:30 pm
content: The example code is for an Arduino which is basically C++. The best way to get started is to look for some literature about C basics and embedded C. I won't recommend any specific books because you should choose the ones which work for you. And please be patient with yourself. Learning a programming language, especially the very first, takes time.

author: Rerouter
author_rank: Super Contributor
timestamp: February 18, 2014, 07:44:17 pm
content: Quote from: Refrigerator on February 18, 2014, 07:20:32 pmJust fair warning that programming in arduino is simplified compared to say a raw pic or AVR due to there little functions like digital write,now as far as explaining the layout a bit, Void is the type of function (it returns nothing), "loop" is the name of the function, The brackets like in digitalWrite are used to pass through values to the function,Also to help you keep track as your new, on any line by typing "//" after the code you can write a comment e.g. "this sets off the self destruct"now as for varying the delay, you will likely want to look at the blink without delay example, as the function delay just makes the micro sit there doing nothing until the time arrives, without letting you check for say a button press, (yes i know it looks a bit more difficult)in that it has a space in the comments saying put your code that will run all the time here, this is where you put your button press checker,As for an actual bit of code, its approaching too close to my time for work, so if no one else hops in, i'll write it up in about 8 hours

author: Refrigerator
author_rank: Super Contributor
timestamp: February 18, 2014, 08:35:10 pm
content: Ok, so far so good.I've read some writing about C++ and it's functions, and i feel like getting the hang of it.So, could i write something like,This might be like a mix up of C and C++int a = 1000void Setup () {pinMode (4, INPUT)pinMode (3, OUTPUT)}void loop () {digitalWrite (3, HIGH)delay 1000 // maybe i could replace it with the a=1000 thing that i just wrote in?:digitarWrite (3, LOW)delay a //like this :while check (4) //maybe put this in somewhere:if (4, HIGH)a + 10if (4, LOW)a - 10 // or something like that:}Am i getting closer to, like, making a suitable program?And it seems like there's really quite some to read about C and C++ so that will keep me busy for a while.

author: uwezi
author_rank: Unknown
timestamp: February 18, 2014, 08:43:40 pm
content: Hi!Without knowing anything about your background, my suggestion would be to not go for Arduino, but use plain-C as the programming language for your AVR microcontrollers. Why - you might ask? Well, you will havecomplete control over all the hardwarean increadibly detailed source of information in the form of the internet and the devices datasheets.AVR is the collective name for the controllers you listed in your question - and as you might already know, these are made by a company called Atmel.I am currently teaching a university course on the programming of these controllers here in Uppsala/Sweden. Today we had our 4th lab exercise in this course, taking control over analog input/output...A plain-C program for such a microcontroller with the same function as your snippet would look something like this:Code:// this is just a comment/*so is this*/#define F_CPU 1000000UL // tell the compiler about the 1 MHz clock#include <avr/io.h> // standard input/output definitions#include <util/delay.h> // time delay functionsint main (void) // this is the part of the program which is executed when power is connected{DDRB = 0b00000001; // declare pin PB0 as outputwhile (1) // start an infinite loop - 1 is always true{PORTB = 0b00000001; // switch PB0 to high_delay_ms(1000); // wait 1000ms=1secPORTB = 0b00000000; // switch PB0 to low_delay_ms(1000); // wait 1000ms=1sec}}I used the GPIO (general purpose input/output) port B here, because it is present in all the devices you listed. The detailed features of your controllers you can find in the datasheets on Atmel's homepage. The datasheet for the Atmega328 alone is over 600 pages long!In order to write your programs I would recommend the Atmel Studio (MS Windows only) which you can get for free on Atmel's homepage. It contains everything you need to write, check and compile your source code into something your AVR controller will understand.At the end you will have a .hex file which - depending on which type of programmer you have - you can easily transfer into your microcontroller.There might and will be a threshold at the beginning - as with everything - but is well worth fighting. I myself started with the AVR controllers less than 4 years ago (http://www.sciencetronics.com/greenphotons/?p=337) and now I am teaching this stuff in university courses at Master's level...

author: Refrigerator
author_rank: Super Contributor
timestamp: February 18, 2014, 09:17:48 pm
content: Wow, and i thought i knew something.By the way i kinda start understanding C.So in the real C ( not the arduino one ) HIGH and LOW are replaced by true and false ?How is DDRB related to PB0, would i have to change the command DDRB if i was to write PB3 as an output? ( like DDRB3 )And does " 0b00000001 " mean a 8-bit signal ?@DawgieYeah, i guess i should really spend more time reading and trying to understand C before asking such questions.

author: uwezi
author_rank: Unknown
timestamp: February 18, 2014, 09:20:46 pm
content: Quote from: Refrigerator on February 18, 2014, 08:35:10 pmIf you use the code-tags here in the forum your code will be much more readableYour code - I suppose, because I don't speak it - looks like Arduino-lingo. But even there commands have to be terminated by semicolon, if I'm not mistaken.It highlights one limitation with Arduino: the more limited number of available port pins. In the AVR controllers many pins have a magnitude of different possible functions - not all of which are available in the Arduino environment.Let us take the medium-sized controller from your list, the Attiny2313 (hopefully this image will stay around):The pins are grouped in three general purpose ports: A, B, and D. Where is C? Well, not in this device!Each of these pins can be declared and used as input and output, which is controlled by the individual bits in a binary number which you store in a variable called DDRx (data direction register, x stands for A/B/D). A1at a certain position will declare the corresponding pin as output, a0as input.Having declared a pin as an output you will be able to change its level from LOW to HIGH by setting the corresponding bit in the variable PORTx to0or1.Let's declare pin 12 to 19 on the package as outputs, i.e. the whole port B:Code:DDRB = 0b11111111;Yes, you can write binary numbers directly! Otherwise you could also have writtenCode:DDRB = 0xFF; // in hexadecimalorCode:DDRB = 255; // in plain old human decimalNow you could attach 8 LEDs to the eight port pins, each with a small ~330 ohm series resistor. Connect one resistor to each port pin, the anode (positive lead) of the LED to the other end of the resistor and the cathde (negative lead) of the LED to GND.The following small code snippet - when placed in a slightly bigger context - would count binary from 0 to 255 on the LEDs:Code:uint8_t i = 0; // declare an unsigned integer, 8-bit variable, initialize to 0while (1) // infinite loop{PORTB = i; // push variable's value to port pins_delay_ms(100); // give it a small delayi = i + 1; // for clarity I am not using shortcuts here}Back to your code, in pure-C it could look something like this:Code:#define F_CPU 1000000UL // tell the compiler about the 1 MHz clock#include <avr/io.h> // standard input/output definitions#include <util/delay.h> // time delay functions// int a = 1000uint16_t = 1000; // better choose _exactly_ the type you wantvoid init (void) // declare a function for initialization{DDRB = 0b00001000; // setting pin PB3 as output, everything else as input}int main (void){PORTB = 0b00011000; // setting PB3 to HIGH level, activating pull-up on PB4_delay_ms(1000); // wait 1 secPORTB = 0b00010000; // setting PB3 to LOW, keeping pull-up on PB4_delay_ms(a); // wait (a) millisecondsif (PINB & 0b00010000){if (a < 5000) // limit wait-time to 5 sec{a = a + 10;}}else{if (a > 10) // avoid under-flow{a = a - 10;}}}

author: uwezi
author_rank: Unknown
timestamp: February 18, 2014, 09:23:52 pm
content: Quote from: Refrigerator on February 18, 2014, 09:17:48 pmThis is almost like a chat - I was writing the answer to your question the same time you were asking itSend me a message with your email-address and I will send you the lecture slides and lab-instruction to my course...Just found one of manygetting startedpages:http://www.micahcarrick.com/tutorials/avr-microcontroller-tutorial/getting-started.htmlanother one:http://imakeprojects.com/Projects/avr-tutorial/

author: Refrigerator
author_rank: Super Contributor
timestamp: February 18, 2014, 09:43:00 pm
content: Quote from: uwezi on February 18, 2014, 09:23:52 pmThanks, i've sent you a PM, i just don't know if it worked or not.

author: dannyf
author_rank: Super Contributor
timestamp: February 18, 2014, 10:11:59 pm
content: Code:PORTB = 0b00011000; // setting PB3 to HIGH level, activating pull-up on PB4Two suggestions:1) Write to a logical "name", rather than hard coding it. For example, you can define your led connection by naming the port and pin it is attached and write to that instead. With that approach, if you ever change the pin assignment, you can simply change it in one place and recompile, knowing with confidence that the code will work.2) Set / clear individual bits: don't write to port (unless you want to change the whole port). This allows other pins on the same port undisturbed when you set or clear a pin on the same port.For example, I would do something like this:Code:#define LED_PORT PORTB#define LED_DDR DDRB#define LED0 (1<<1) //led0 connected to pb1#define LED1 (1<<5) //led1 connected to pb5#define BIT_SET(var, bits) var |= (bits) //set bits on var#define BIT_CLR(var, bits) var &=~(bits) //clear bits on var#define PIN_SET(port, pins) BIT_SET(port, pins) //set pins on port#define PIN_CLR(port, pins) BIT_CLR(port, pins) //clear pins on port#define PIN_GET(port, pins) ((port) & (pins)) //read pins on port#define PIN_OUT(ddr, pins) BIT_SET(ddr, pins) //pins as output#define PIN_IN(ddr, pins) BIT_CLR(ddr, pins) //pins as output....PIN_CLR(LED_PORT, LED0 | LED1); //clear led0/1PIN_OUT(LED_DDR, LED0 | LED1); //led0/1 as outputPIN_SET(LED_PORT, LED0); //set led0...PIN_SET(LED_PORT, LED1); PIN_IN(LED_DDR, LED1); //enable wpu on led1...The macros (PIN_SET/CLR, PIN_OUT/IN) can be easily put in a common file, and by defining them for your target, your user code remains the same, as long as you access the pins via the same macros - you know for sure that they would work.

author: uwezi
author_rank: Unknown
timestamp: February 18, 2014, 10:36:34 pm
content: Quote from: dannyf on February 18, 2014, 10:11:59 pmWhile I completely agree with you in principle: I wanted tokeep it simpleand clear for someone who was just taking his first baby steps in microcontroller programming...In my opinion you first have to grasp that the individual bits in a number stored in a variable which represents a register in the controller actually do something to the hardware. And in my opinion (and experience as a teacher) this is most easily seen if you first present the number in full binary format.

author: Refrigerator
author_rank: Super Contributor
timestamp: February 19, 2014, 01:49:44 pm
content: Damn, if those codes get so complicated when programming a blinker, i can't even imagine what should i write to make a CNC.Making a CNC is actually my main goal right now, i've seen someone make a mini CNC with a ATtiny 2313,But i want to make mine just a bit bigger, for PCB milling, i'm thinging of getting theese steppers,http://www.ebay.com/itm/DC-5V-Stepper-Motor-28BYJ-48-5-Line-4-Phase-Drive-Test-Module-Board-ULN2003-OH/261340060655?_trksid=p2045573.c100033.m2042&_trkparms=aid%3D111000%26algo%3DREC.RVI%26ao%3D1%26asc%3D20131017132637%26meid%3D4946761125304976223%26pid%3D100033%26prg%3D20131017132637%26rk%3D1%26rkt%3D4%26sd%3D2213727And probably a 550 brushed motor for the engraver.

author: uwezi
author_rank: Unknown
timestamp: February 19, 2014, 05:05:46 pm
content: Did you get my files?The codes do not necessarily get more complex or difficult. You will learn how to find and use ready-made libraries, hide away things in your own functions etc.

author: MatCat
author_rank: Frequent Contributor
timestamp: February 19, 2014, 05:19:35 pm
content: Programming is no more complicated then hardware, sure the programming code for a CNC machine is going to look big and complex, but so will a circuit board that is doing much more then a simple LED blink, it's all just parts combined together to make the whole.I really recommend you read a good C book, it's an entire language and you have to learn it to properly use it. What has been posted sofar is good stuff, but you really need to know why you put a ; at the end of the line, how variables actually work, how AVR LIBC works even, lot's to learn but well worth it, plus once you learn C most other languages will be fairly easy to jump into.

author: Refrigerator
author_rank: Super Contributor
timestamp: February 19, 2014, 05:49:48 pm
content: Quote from: uwezi on February 19, 2014, 05:05:46 pmYep, i've sent you a reply. Thanks, i really appreciate your help.

author: zapta
author_rank: Super Contributor
timestamp: February 20, 2014, 06:16:59 am
content: Quote from: Refrigerator on February 18, 2014, 09:17:48 pmThere is no difference between 'arduino C' and 'real C'. It's exactly the same language and compiler, with exactly the same syntax.In C/C++ you can write functions. That is, some sequences of instructions that you give a name and can then invoke with a single instruction. They are typically put in files called libraries. Standard C/C++ come with some function and the arduino environment has a few additional ones. You can also write your own functions and libraries, and it is up to use what portion of the Arduino additional functions you use.

author: Stonent
author_rank: Super Contributor
timestamp: February 21, 2014, 04:43:46 pm
content: If you're interested in exploring the capabilities of the Arudino and how to program them in the Arduino language look at the videos by Jeremy Blum on Youtube, that's what got me started.From a hardware standpoint the capabilities of the Arduino would apply to the ATMega series chips and in a reduced way to the ATTiny chips.The ATTiny 25/45/85 are very similar in features to the ATMega but with less pins. The ATTiny2313/4313 are bigger than the 45/85 but have no analog capabilities. Those are just a few examples.Also when you write programs in the Arduino language, they tend to be bigger (in compiled size) than writing them directly in C since you may be compiling in a lot of things you don't need.So I'd recommend writing small Arduino programs and then rewriting them in AVR C (you can use the free Atmel Studio). If your Arduino programs are dependent on additional libraries, open those up in a text editor and see what they're doing. Those will be more like AVR C. You can also try googling things like AVR Servo control instead of Arduino Servo Control and you'll likely find some info on controlling a servo without using the Arduino software.

author: dannyf
author_rank: Super Contributor
timestamp: February 21, 2014, 07:24:01 pm
content: QuoteWhy?The Arduino environment is fully capable of compiling c-styled code pieces and downloading it to the chip. It makes no sense to switch to AS to do that.

author: Refrigerator
author_rank: Super Contributor
timestamp: February 21, 2014, 07:28:21 pm
content: @Stonent.Thanks for help.I've actually just installed the atmel studio and was actually starting "programming", i love how the atmel studio tells me if i made a mistake or gives me some command options, makes stuff so much easier.I think of making an arduino type thing myself, like the one seen in the video below.Ps: I don't have an arduino and i don't have the money to spend right now.

author: zapta
author_rank: Super Contributor
timestamp: February 23, 2014, 07:43:47 pm
content: Quote from: Refrigerator on February 21, 2014, 07:28:21 pmDoes avr studio have an avr simulator?

author: uwezi
author_rank: Unknown
timestamp: February 23, 2014, 07:59:32 pm
content: Quote from: zapta on February 23, 2014, 07:43:47 pmYes, it does......but not expect too much from any microcontroller simulator. Rarely is your real-world system/project so slow that you can simulate it at actual speed, and rarely does your system only consist of the controller without additional digital/analog periphery.

author: Stonent
author_rank: Super Contributor
timestamp: February 25, 2014, 01:48:45 am
content: Quote from: dannyf on February 21, 2014, 07:24:01 pmTrue, but compiling for other chips like the 2313 or 85 is a bit easier to do in Atmel Studio. Then just set up the arduino as an ISP and flash with appropriate avrdude parameters.

author: GiskardReventlov
author_rank: Frequent Contributor
timestamp: February 26, 2014, 05:54:09 pm
content: Quote from: uwezi on February 18, 2014, 09:23:52 pmIs the course available online? I looked at the univ. site you hinted at but did not find it.

author: uwezi
author_rank: Unknown
timestamp: February 26, 2014, 11:44:38 pm
content: Quote from: GiskardReventlov on February 26, 2014, 05:54:09 pmIt's not an online course, it is a regular course at Uppsala university. Since the legal aspects about open-access and alike are not fully established here yet, I will not put the material online.

author: GiskardReventlov
author_rank: Frequent Contributor
timestamp: February 27, 2014, 05:26:27 pm
content: Quote from: uwezi on February 26, 2014, 11:44:38 pmOk, understand. The lawyers always get in the way. I did find some other podcasts and videos.

author: Refrigerator
author_rank: Super Contributor
timestamp: February 27, 2014, 05:52:02 pm
content: Wait, once you program your micro you can't erase it, or can you?By the way, i can't wait to program my micros, i've already written so many programs for them.Oh and how should i write a program if i wanted to make different modes like:voidmain () {$#%$^$#%$; // my program...;// and then;break;if ( "selected pin gets input" ) {goto ( B )}}Or do i write:voidmain () {$#%$^$#%$; // my program...;// and then;if ( "selected pin gets input" ) {goto ( B )}break; // maybe like this;}Why i'm asking this is because i want to make different librarys with different modes that would get changed in between when a selected input becomes " true ".

author: suicidaleggroll
author_rank: Super Contributor
timestamp: February 27, 2014, 06:30:21 pm
content: Quote from: Refrigerator on February 27, 2014, 05:52:02 pmOf course you can. There are some models out there that are one-time-flash only, but they're going to be few and far between. None of the AVRs, PICs, MSP430s, etc. that you find are going to be that way. The flash does have a limited write limit, but we're talking thousands of write cycles.Quote from: Refrigerator on February 27, 2014, 05:52:02 pmIt really depends on what you're trying to do with the uC.

author: Refrigerator
author_rank: Super Contributor
timestamp: February 27, 2014, 06:59:59 pm
content: What i'm trying to do is:Place #1If input= trueGoto (place #2 )This way i want to make a menu system for selecting different modes, for different applications.Like a mini computer.

author: uwezi
author_rank: Unknown
timestamp: February 27, 2014, 07:30:25 pm
content: Quote from: Refrigerator on February 27, 2014, 05:52:02 pmThat has already been answered. Flash-micros can be reprogrammed a couple of thousand times. Everytime you send a new code to the controller the old one is erased and replaced.In the good old times the program memory in microcontrollers was either extern or in the form UV-erasable EPROM memory. There you had to erase the memory yourself before re-programming the chip. With today's Flash controllers you don't have to take care about anything...Quotebreak;is only needed in a certain structure in C, aswitch:Code:int main (void) // the start of the main program{uint8_t choice; // define a variablewhile (1) // infinite loop for the main program code{// here should come some code which modifies the variable// ...//// and here you react to the contents of the variableswitch (choice){case 0 :do_what_needs_to_be_done_here();break; // exit switch-blockcase 1 :do_what_else_needs_to_be_done_here();break; // exit switch-block// more cases if neededdefault: // all the rest goes heredo_whatever();break;}}}which does about the same asCode:int main (void) // the start of the main program{uint8_t choice; // define a variablewhile (1) // infinite loop for the main program code{// here should come some code which modifies the variable// ...//// and here you react to the contents of the variableif (choice == 0){do_what_needs_to_be_done_here();}else if (choice == 1){do_what_else_needs_to_be_done_here();}else // more cases if needed{do_whatever();}}}By the way you don't have to end comments with a semicolon, only instructions.