Author Topic: PIC and AVR thinking of a switch but need more info  (Read 23792 times)

0 Members and 1 Guest are viewing this topic.

Offline blewisjr

  • Frequent Contributor
  • **
  • Posts: 301
Re: PIC and AVR thinking of a switch but need more info
« Reply #50 on: March 21, 2013, 03:58:08 pm »
Well here is a small update.

I implemented a little project using the PIC16F1829 (The one that has banks unlike the PIC18 series).  The project was an 8 bit number counter which displays over 8 LED's.  Really fun little project and as my first solo project on the PIC it was really easy to do.  As far as I can see through a quick analysis it took about 7 extra instructions to implement due to having to pass through the single accumulator and switching banks.  So in all honesty it was not bad and I felt very comfortable implementing the project.

Next I will have to convert the project over to the Arduino's AVR chip to see how the ASM is with that.  This will take tons of setup due to the fact that I do not have a AVR programmer so I would need to configure Atmel Studio to upload via the Arduino bootloader with avrdude.

If anyone is interested here is the PIC code.

Code: [Select]
; =============================================================================
; Project: Binary Counter
; File:    binary_counter.asm
; Date:    3/21/2013
;
; This project is a 8 bit binary counter.  The number of the current count
; is displayed on a set of 8 LED's hooked to pins RC0 - RC7 on the uC.
; There is about a 1 second delay between each number increment.
; =============================================================================

; =============================================================================
; PIC:      16F1829
; Board:    Breadboard
; IDE:      MPLABX v1.70
; Compiler: MPASM v5.49
; =============================================================================

    #include <p16f1829.inc>

    ; Fuse Configuration
    #define CFGW1A (_FOSC_INTOSC & _WDTE_OFF & _PWRTE_OFF & _MCLRE_OFF & _CP_OFF)
    #define CFGW1B (_CPD_OFF & _BOREN_ON & _CLKOUTEN_OFF & _IESO_OFF & _FCMEN_OFF)

    __CONFIG _CONFIG1, (CFGW1A & CFGW1B)
    __CONFIG _CONFIG2, (_WRT_OFF & _PLLEN_OFF & _STVREN_OFF & _LVP_OFF)

    ; supress not in bank0 warning
    errorlevel -302

    ; create file registers in bank shared memory
    cblock 0x70
        Dly1                        ; Dly1 is a file register for the delay
        Dly2                        ; Dly2 is a file register for the delay
        Cnt                         ; Cnt is a file register for our count
    endc

    org 0                           ; Start program at 0x00

Start:
                                    ; Initialization code
    movlw       0x00                ; Move 0 to W register
    movwf       Dly2                ; Move W register to Dly2
    movlw       0x00                ; Move 0 to W register
    movwf       Cnt                 ; Move W register to Cnt
    banksel     OSCCON              ; select bank1
    movlw       b'00111000'         ; We want a clock of 500kHZ giving us (1/(500k/4)) per instruction
    movwf       OSCCON              ; Move W register into OSCCON
    clrf        TRISC               ; Make RC0 - RC7 and output
    banksel     LATC                ; select bank2
    clrf        LATC                ; clear the latch

Main:
                                    ; Main code block
    incf        Cnt, 1              ; Increment count and store back in Cnt
    movf        Cnt, 0              ; Move Cnt into the W register
    movwf       LATC                ; Move W register into the latch
    call        Delay               ; Exectute the Delay routine
    bra         Main                ; Repeat process

Delay:
                                    ; Delay Routine uses formula {[(Dly1 * 3) + 4] * Dly2 + 1} * 8uS
    movlw       0xA1                ; Move 161 into W register
    movwf       Dly1                ; Move W register into Dly1
    decfsz      Dly1, 1             ; Decrement Dly1 skip next instruction if 0
    bra         $-1                 ; Re run previous instruction gives us 487 instructions
    decfsz      Dly2, 1             ; Decrement Dly2 skip next instruction if 0
    bra         Delay               ; Re run whole loop gives us an additional 256 instructions
                                    ; the return will give us + 1 to the delay
    return                          ; so our (476 * 256 + 1) * 8uS gives us 0.997384 seconds.

    end                             ; end of code
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2009
  • Country: au
Re: PIC and AVR thinking of a switch but need more info
« Reply #51 on: March 21, 2013, 04:29:15 pm »
...as far as I know the PIC18 still only has 1 accumulator
How many accumulators do you actually need when the instruction set allows you to do a lot of stuff directly on ram? Its a bit like having an entire ram's worth of accumulators. Granted they are 4 clock cycle instructions, but how many does it take to fetch, store, operate and possibly write back?
 

Offline blewisjr

  • Frequent Contributor
  • **
  • Posts: 301
Re: PIC and AVR thinking of a switch but need more info
« Reply #52 on: March 21, 2013, 04:47:59 pm »
...as far as I know the PIC18 still only has 1 accumulator
How many accumulators do you actually need when the instruction set allows you to do a lot of stuff directly on ram? Its a bit like having an entire ram's worth of accumulators. Granted they are 4 clock cycle instructions, but how many does it take to fetch, store, operate and possibly write back?

It is more of a efficiency and read ability thing.

say you need to store the value 0xA1.
On 8 bit PIC you only have 1 general purpose register W.  So instead you need to first Allocate a piece of memory so you can access it across banks.
cblock 0x70
    Reg1
endc

Then you need to
movlw 0xA1
movwf Reg1

AVR comes with 16 general purpose registers you can use so unless you need more then 16 self defined variables you can just use those ie.

ldi r16, 0xA1

So 5 lines becomes 1 line.

With PIC it is possible to remove the cblock and replace it with a 1 liner which gives 3 lines to 1 line.  The 16 registers will be more then enough for all but the most complex projects.  You can achieve the same concept with PIC as the Common Ram is indeed 16 bytes on my PIC16F1829 which is 16 registers you just have to go through the process of defining them, and moving data to them which could be shortened with a macro I guess.

It really comes down to personal preference I just don't see why they could not give the 8 bit pics a load immediate opcode and 16 pre defined registers in that common ram saves typing which saves making mistakes.

The more I look into it and learn more it is very possible for me to create some convenience code in an include file to deal with a majority of these issues I have.
« Last Edit: March 21, 2013, 05:03:01 pm by blewisjr »
 

Offline ecat

  • Frequent Contributor
  • **
  • Posts: 296
  • Country: gb
Re: PIC and AVR thinking of a switch but need more info
« Reply #53 on: March 21, 2013, 05:20:32 pm »
It really comes down to personal preference I just don't see why they could not give the 8 bit pics a load immediate opcode and 16 pre defined registers in that common ram saves typing which saves making mistakes.

Because they are maintaining backward compatibility with a 1970s architecture, this compatibility is the hallmark of the pic16 devices. If you're after a pic with a more up to date design then use a more up to date pic (18, 24, 32).

The AVR is a 1990s design, so naturally it makes the pic16 look old fashioned.
 

Offline ve7xen

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: ca
    • VE7XEN Blog
Re: PIC and AVR thinking of a switch but need more info
« Reply #54 on: March 21, 2013, 11:55:31 pm »
What does Future charge for overnight delivery for Canucks? Do they take care of any brokerage customs crap in the price. Both Newark and Digikey do. I like Mouser as well but the 20 bucks for overnight delivery makes them my last choice and only if they have someting I can't get at Newark or Digikey.
I found Newark to be the cheapest for micro's and the majority of other stuff, you might want to check them. They charge flat rate 8 bucks overnight delivery.
Future is similar to the rest. I think it's $8 FedEx Economy (2-3 day). They charge the GST/HST directly, and there are no brokerage fees.
73 de VE7XEN
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2009
  • Country: au
Re: PIC and AVR thinking of a switch but need more info
« Reply #55 on: March 22, 2013, 01:47:53 am »
...as far as I know the PIC18 still only has 1 accumulator
Just to be clear, I thought we were talking about PIC18's now...

It is more of a efficiency and read ability thing.

say you need to store the value 0xA1.
On 8 bit PIC you only have 1 general purpose register W.  So instead you need to first Allocate a piece of memory so you can access it across banks.
cblock 0x70
    Reg1
endc

Then you need to
movlw 0xA1
movwf Reg1

AVR comes with 16 general purpose registers you can use so unless you need more then 16 self defined variables you can just use those ie.

ldi r16, 0xA1

So 5 lines becomes 1 line.
In your example movlw 0XA1 is identical to ldi r16, 0xA1 and loading more literals into accumulators for further processing is a little futile as you can have the compiler pre-process these literals to give you a result that doesn't need to be calculated at run time.

As a possible game leveller PIC's have a lot of instructions that allow you to operate on the memory directly, where as it appears that the AVR's require you to load them into one of the regs first. If you combine this with overlay memory you can create a volatile memory buffer that is accessible across all banks

Quote
With PIC it is possible to remove the cblock and replace it with a 1 liner which gives 3 lines to 1 line.  The 16 registers will be more then enough for all but the most complex projects.  You can achieve the same concept with PIC as the Common Ram is indeed 16 bytes on my PIC16F1829 which is 16 registers you just have to go through the process of defining them, and moving data to them which could be shortened with a macro I guess.
I don't remember the compiler directive but have a look for overlay in the asm manual as I mentioned above. You don't have to define each and every slot just create a block and index into it.

Quote
It really comes down to personal preference I just don't see why they could not give the 8 bit pics a load immediate opcode and 16 pre defined registers in that common ram saves typing which saves making mistakes.

The more I look into it and learn more it is very possible for me to create some convenience code in an include file to deal with a majority of these issues I have.
Macro's play a massive part of your assembly development environment. Unfortunately as time progresses and you invest more time and energy into this you run the risk of not wanting to dump your setup in favour of higher level languages

The pic16's where not designed as "C compiler friendly" and thus are more suited to asm whilst the AVR's with their registers and hardware stack manipulation commands are ideally suited for C compiler constructs.

As you start moving to more complex architectures you start seeing more and more features aimed squarely at supporting compilers. With this in mind the architecture designers start taking advantage of the fact that the assembly will be generated by algorithms in compilers and it becomes difficult to keep these "rules" in your head as you hand assemble.

For example a different set of assembly instructions sequences may seem to do the same thing but due to the pipelined nature of command processing one sequence may create a stall in the pipeline because the following instruction has to wait for the previous one to complete its operation before it can continue.

I guess the crux of what I am trying to get at here is that you are learning asm on an architecture that was "designed" for it. If you are going to move to an architecture that's been designed for programming with a more advanced tool then take advantage of it and use it (ie C/C++)
« Last Edit: March 22, 2013, 01:49:53 am by AlfBaz »
 

Offline blewisjr

  • Frequent Contributor
  • **
  • Posts: 301
Re: PIC and AVR thinking of a switch but need more info
« Reply #56 on: March 22, 2013, 02:45:15 am »
Yes the cblock directive is for that in my above code you define the block and it works from that memory address up auto placing each register in the appropriate address.

I do agree with you that AVR, PIC18, 16 bit PIC, and 32 bit PIC are designed with C in mind.  Actually the enhancements to the Enhanced mid range PIC16's was designed to make it more C friendly as well as it states directly in the Power Point and the Data Sheet for the Enhanced Mid-Range 8 bit PICs.

I love C and I can't wait to start using it.  I actually built the same binary number counter on my Arduino using C in the Arduino IDE and it was very nice and quick.  Much less typing for sure.  The reason I am dealing with ASM is to get a feel and better understand it at that level incase I need to use it to optimize my code.  I am not planning on learning everything there is about PIC or AVR ASM or any chips ASM for that matter I just want to know enough to be comfortable with the basics so that if I do need to inline some ASM I can do it just by looking up the instructions I need in the datasheet and doing it.

I feel I will indeed be moving to C very soon as I am becoming somewhat comfortable I wrote the PIC binary number counter without looking anything up at all.

In all honesty I think I was over reacting when I said pic is a mess I should have said pic is very different then what I would expect from an architecture in 2013.  Like you said it is a very old architecture and they improved in the PIC18 + chips which I agree.

The only issue with PIC at the moment for me from the C perspective is the compiler price.  This is rather steep $450 + a yearly subscription seems a bit steep but for a while I should be able to just use the free compiler.  If it does become a sever problem it is probably time to shell out the cash anyway.

Thanks for all the help everyone much appreciated.  For now I am going to stick with PIC I don't see why not I am becoming comfortable with working with the chips.  I will also start dabbling more with my Arduino as well it was really quite interesting with how easy it was to just move the jumpers from my PIC plug it into the header and write the code and boom just works.

No matter what I am having tons of fun working with these chips and I am learning quite a bit about circuits in the process too.  I am so glad I picked this up for my hobby.  So much to learn and the possibilities for projects go as far as the imagination can dream.
 

Offline ptricks

  • Frequent Contributor
  • **
  • Posts: 670
  • Country: us
Re: PIC and AVR thinking of a switch but need more info
« Reply #57 on: March 22, 2013, 03:46:13 am »
I mainly use PIC based chips and the first tip I can give beginners is learn some basic asm and then start using c and most of your frustration with PIC will go away.  You need asm for understanding debugging if something goes really wrong but otherwise don't spend a lot of time with it.

The PIC chips have been around for a long time, I have chips from the 1990's. Microchip doesn't make things easier either , where most chips are released with the numbers incremental , like 8051,8052 , etc. Microchip jumps all over the place with creations like 16F917 released in 2007 and the 16f887 released 2012. I stay with PIC for a lot of reasons but the main ones are price and availability . If you need a chip for a certain project chances are they have one with the on board peripherals to match. Sometimes I think the engineers at Microchip write down features on slips of paper , toss them all in a hat and draw out what mix of features will be the next chip.

They have some interesting features like the 16f1783 chips I am currently experimenting with, has internal opamps ,every pin can do interrupt on change, and a programmable switch mode power controller with 16bit PWM channels
 
If you really want to go modern with asm and C look at the Pic32 line, they are mips cores , designed with c in mind and really have nothing in common with the 16f/18f line.
 

Offline poorchava

  • Super Contributor
  • ***
  • Posts: 1547
  • Country: pl
  • Troll Cave Electronics!
Re: PIC and AVR thinking of a switch but need more info
« Reply #58 on: March 22, 2013, 09:57:07 am »
In Europe it's kinda harder than in US. Digikey, Mouser, Future, Newark are almost non-existant for hobbyists. RS-components in my country refuses to sell to people who don't run their own business. Out of large suppliers (in Poland) we have only Farnell (where lots of interesting stuff has to be shipped from
Newark adding $35 shipping charge to the bill - unacceptable), TME and a few smaller ones.

Booooy, would I be happy if we had Digikey with cheap shipping locally.
I love the smell of FR4 in the morning!
 

Offline blewisjr

  • Frequent Contributor
  • **
  • Posts: 301
Re: PIC and AVR thinking of a switch but need more info
« Reply #59 on: March 22, 2013, 12:52:02 pm »
I mainly use PIC based chips and the first tip I can give beginners is learn some basic asm and then start using c and most of your frustration with PIC will go away.  You need asm for understanding debugging if something goes really wrong but otherwise don't spend a lot of time with it.

The PIC chips have been around for a long time, I have chips from the 1990's. Microchip doesn't make things easier either , where most chips are released with the numbers incremental , like 8051,8052 , etc. Microchip jumps all over the place with creations like 16F917 released in 2007 and the 16f887 released 2012. I stay with PIC for a lot of reasons but the main ones are price and availability . If you need a chip for a certain project chances are they have one with the on board peripherals to match. Sometimes I think the engineers at Microchip write down features on slips of paper , toss them all in a hat and draw out what mix of features will be the next chip.

They have some interesting features like the 16f1783 chips I am currently experimenting with, has internal opamps ,every pin can do interrupt on change, and a programmable switch mode power controller with 16bit PWM channels
 
If you really want to go modern with asm and C look at the Pic32 line, they are mips cores , designed with c in mind and really have nothing in common with the 16f/18f line.

Yes I do agree that they have amazingly priced chips if only there compilers were amazingly priced.  I decided to experiment and covert the PIC 16F1829 ASM binary counter code to C so that I can see the difference between the PIC C code and the Arduino C code.  Arduino is a little odd but it can probably be cleaned up more as I am not sure if I can get direct PIN access using the Arduino libraries or not.  I will say I think the C is much nicer then ASM but I already knew that because I love C.

Here is the PIC code followed by the Arduino code if anyone cares to compare.

Code: [Select]
/******************************************************************************
 * Program: BinaryCounter
 * File:    binary_counter.c
 * Date:    3/22/2013
 *
 * This program is an 8 bit binary counter.  The program loops through the
 * the numbers 0 - 255 in binary and displays each number on a line of 8 LED's.
 * There is a 1 second delay between each number change to make the count
 * visible to the human eye.
 *
 * PIC:      16F1829
 * Compiler: XC8 v1.12
 * IDE:      MPLABX v1.70
 *****************************************************************************/

#include <xc.h>

#define _XTAL_FREQ 500000  // 500kHz frequency for __delay_ms()

// Config Word 1
#pragma config FOSC = INTOSC
#pragma config WDTE = OFF
#pragma config MCLRE = OFF
#pragma config CP = OFF
#pragma config CPD = OFF
#pragma config BOREN = ON
#pragma config CLKOUTEN = OFF
#pragma config IESO = OFF
#pragma config FCMEN = OFF

// Config Word 2
#pragma config WRT = OFF
#pragma config PLLEN = OFF
#pragma config STVREN = OFF
#pragma config LVP = OFF

void main(void)
{
    // 8 bit number (1 byte)
    unsigned char cnt = 0;

    // set internal oscillator to 500kHZ
    OSCCON = 0b00111000;

    // make all of PORTC (RC0 - RC7) and output
    TRISC = 0;

    while (1) {
        LATC = cnt;

        // 1 second delay
        __delay_ms(1000);
       
        // increment count by 1
        // when it overflows passed 255 it will reset to 0
        cnt++;
    }
}

Code: [Select]
byte cnt = B00000000;

void setup()
{
  for (int i = 0; i <= 7; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop()
{
  for (int i = 0; i <= 7; i++) {
    digitalWrite(i, bitRead(cnt, i));
  }
 
  cnt += 1;
 
  delay(1000);
}
 

Offline Slothie

  • Regular Contributor
  • *
  • Posts: 63
Re: PIC and AVR thinking of a switch but need more info
« Reply #60 on: March 22, 2013, 02:17:57 pm »
Arduino is a little odd but it can probably be cleaned up more as I am not sure if I can get direct PIN access using the Arduino libraries or not.  I will say I think the C is much nicer then ASM but I already knew that because I love C.


Yes, you can access all the AVR ports & registers from an Arduino sketch;
http://tronixstuff.wordpress.com/2011/10/22/tutorial-arduino-port-manipulation/
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2009
  • Country: au
Re: PIC and AVR thinking of a switch but need more info
« Reply #61 on: March 22, 2013, 02:33:44 pm »
Yes, you can access all the AVR ports & registers from an Arduino sketch;
http://tronixstuff.wordpress.com/2011/10/22/tutorial-arduino-port-manipulation/

Code: [Select]
void loop()
{
  PORTD = B11111111;
  PORTD = B00000000;
  PORTD = B11111111;
  PORTD = B00000000;
  PORTD = B11111111;
  PORTD = B00000000;
  PORTD = B11111111;
  PORTD = B00000000;
  PORTD = B11111111;
  PORTD = B00000000;
}
  :palm:
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2009
  • Country: au
Re: PIC and AVR thinking of a switch but need more info
« Reply #62 on: March 22, 2013, 02:53:16 pm »
Code: [Select]
...// Config Word 1
#pragma config FOSC = INTOSC
#pragma config WDTE = OFF
#pragma config MCLRE = OFF
#pragma config CP = OFF
#pragma config CPD = OFF
I don't know about yourself or others but I had a hard time digging through all the documentation to get the appropriate config pragma's

MPLAB IDE had a dialog box that allowed you to select them which was handy but you would be crazy not to put them in one of your source files. Myself and others ask MC to have this IDE function generate an include file from this selection dialog but it never eventuated.

What I did was copy the config text from the help file and created a header file that contained all the possible config permutations.
and then you simply included it in your c file.

At the start of the project you would go through and uncomment the configs you wanted and you could be sure you hadn't forgotten any or rely on the programmer setting all the ones you don't use to defaults.

Ive attached an example one I created for the 18f4550
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 3066
  • Country: us
Re: PIC and AVR thinking of a switch but need more info
« Reply #63 on: March 22, 2013, 04:08:30 pm »
Note that it seems to be "standard practice" NOT to include fuse settings in AVR C source code...
(For something like Arduino, the fuses are "set" during the bootloader burn, and not changeable anyway.)

 

Offline blewisjr

  • Frequent Contributor
  • **
  • Posts: 301
PIC and AVR thinking of a switch but need more info
« Reply #64 on: March 22, 2013, 04:35:59 pm »
Code: [Select]
...// Config Word 1
#pragma config FOSC = INTOSC
#pragma config WDTE = OFF
#pragma config MCLRE = OFF
#pragma config CP = OFF
#pragma config CPD = OFF
I don't know about yourself or others but I had a hard time digging through all the documentation to get the appropriate config pragma's

MPLAB IDE had a dialog box that allowed you to select them which was handy but you would be crazy not to put them in one of your source files. Myself and others ask MC to have this IDE function generate an include file from this selection dialog but it never eventuated.

What I did was copy the config text from the help file and created a header file that contained all the possible config permutations.
and then you simply included it in your c file.

At the start of the project you would go through and uncomment the configs you wanted and you could be sure you hadn't forgotten any or rely on the programmer setting all the ones you don't use to defaults.

Ive attached an example one I created for the 18f4550

I just grab the config pragmas from the data sheet config section all the bits are listed with their possible values.
 

jucole

  • Guest
Re: PIC and AVR thinking of a switch but need more info
« Reply #65 on: March 22, 2013, 04:42:47 pm »
very neat and tidy code! ;-)
 

Offline AlfBaz

  • Super Contributor
  • ***
  • Posts: 2009
  • Country: au
Re: PIC and AVR thinking of a switch but need more info
« Reply #66 on: March 22, 2013, 04:52:17 pm »
Note that it seems to be "standard practice" NOT to include fuse settings in AVR C source code...
(For something like Arduino, the fuses are "set" during the bootloader burn, and not changeable anyway.)
That seems like a strange practice. Saving fuse settings in a proprietary project file isn't a very good idea, especially if they change its format.
 

Offline ve7xen

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: ca
    • VE7XEN Blog
Re: PIC and AVR thinking of a switch but need more info
« Reply #67 on: March 22, 2013, 06:20:04 pm »
Note that it seems to be "standard practice" NOT to include fuse settings in AVR C source code...
(For something like Arduino, the fuses are "set" during the bootloader burn, and not changeable anyway.)
That seems like a strange practice. Saving fuse settings in a proprietary project file isn't a very good idea, especially if they change its format.
Yeah it's pretty common, and pretty stupid. avr-libc even supports setting the fuses in the source file, and saving them in ELF output, which avrdude can burn for you. See http://www.nongnu.org/avr-libc/user-manual/group__avr__fuse.html

Be careful though, the fuses are inverted logic; 1 is clear and 0 is set. In avr-libc this is reflected in the macro definitions.

Not sure why nobody does this...
73 de VE7XEN
 

Offline blewisjr

  • Frequent Contributor
  • **
  • Posts: 301
Re: PIC and AVR thinking of a switch but need more info
« Reply #68 on: March 22, 2013, 06:36:56 pm »
Yes, you can access all the AVR ports & registers from an Arduino sketch;
http://tronixstuff.wordpress.com/2011/10/22/tutorial-arduino-port-manipulation/

Code: [Select]
void loop()
{
  PORTD = B11111111;
  PORTD = B00000000;
  PORTD = B11111111;
  PORTD = B00000000;
  PORTD = B11111111;
  PORTD = B00000000;
  PORTD = B11111111;
  PORTD = B00000000;
  PORTD = B11111111;
  PORTD = B00000000;
}
  :palm:

I agree with a  :palm: and raise you one  :palm:

Then again it could be worse....  But could be much much better.

Would much rather see this which makes much more sense since he is just flip flopping the whole port high low.

Code: [Select]
void setup()
{
  PORTD = B00000000;
}

void loop()
{
  for (int i = 0; i <= 9; i++) {
    PORTD ^= B11111111;
  }
}

Also thanks for the tip on writing directly to the port here is the updated arduino code to be more efficient with less loops.

Code: [Select]
/******************************************************************************
 * Program: BinaryCounter
 * File:    binary_counter.ino
 * Date:    3/22/2013
 *
 * This program is an 8 bit binary counter.  The program loops through the
 * the numbers 0 - 255 in binary and displays each number on a line of 8 LED's.
 * There is a 1 second delay between each number change to make the count
 * visible to the human eye.
 *
 * uC:       Arduino Uno Rev3 ATmega328P-PU
 * Compiler: AVR-GCC
 * IDE:      Arduino 1.0.3
 *****************************************************************************/

unsigned char cnt = 0;

void setup()
{
  DDRD = B11111111;
}

void loop()
{
  PORTD = cnt;
  delay(1000);
  cnt++;
}
 

Offline mrflibble

  • Super Contributor
  • ***
  • Posts: 1947
  • Country: nl
Re: PIC and AVR thinking of a switch but need more info
« Reply #69 on: March 22, 2013, 08:09:09 pm »
And 100% guessing, just going by name of function ... you can probably get away with:

Code: [Select]
void loop()
{
    PORTD ^= B11111111;
}

Because we all know how this sort of code grows historically. :P Some monkey does this, some other monkey copies that, etc. I suspect that loop() is getting called from somewhere else already in an infinite loop. Unless there is a very specific reason why you toggle the port 10 times, which I doubt.

But as  :palm: goes ... this isn't so bad. I've seen worse. Much much worse.  ;D This just looks like My First Attempt At Code, so as long as people learn from that and get better at it, who cares if it's suboptimal. :P
 

Offline ve7xen

  • Frequent Contributor
  • **
  • Posts: 671
  • Country: ca
    • VE7XEN Blog
Re: PIC and AVR thinking of a switch but need more info
« Reply #70 on: March 22, 2013, 08:25:38 pm »
Unrolling loops is pretty common. I wouldn't quite call it a :palm:, though I'm not sure I see the point for an infinite loop, it will bring down the average loop iteration time slightly (though for an infinite loop, probably only the one jump instruction...), but introduce inconsistency after each iteration.

Also it's ugly if you don't need the tighter timing...
73 de VE7XEN
 

Offline andersm

  • Super Contributor
  • ***
  • Posts: 1060
  • Country: fi
Re: PIC and AVR thinking of a switch but need more info
« Reply #71 on: March 22, 2013, 08:36:38 pm »
MPLAB IDE had a dialog box that allowed you to select them which was handy but you would be crazy not to put them in one of your source files. Myself and others ask MC to have this IDE function generate an include file from this selection dialog but it never eventuated.
In MPLAB X you open the config bits memory view, edit them as you see fit, click the "Generate Source Code to Output" button and the #pragma statements will be generated into the IDE message area from where you can copy them into your source code.

And 100% guessing, just going by name of function ... you can probably get away with:

Code: [Select]
void loop()
{
    PORTD ^= B11111111;
}
If you want to flip bits on an AVR, use the PINx registers, none of this read-modify-write nonsense.

Offline blewisjr

  • Frequent Contributor
  • **
  • Posts: 301
Re: PIC and AVR thinking of a switch but need more info
« Reply #72 on: March 22, 2013, 10:01:12 pm »
And 100% guessing, just going by name of function ... you can probably get away with:

Code: [Select]
void loop()
{
    PORTD ^= B11111111;
}

Because we all know how this sort of code grows historically. :P Some monkey does this, some other monkey copies that, etc. I suspect that loop() is getting called from somewhere else already in an infinite loop. Unless there is a very specific reason why you toggle the port 10 times, which I doubt.

But as  :palm: goes ... this isn't so bad. I've seen worse. Much much worse.  ;D This just looks like My First Attempt At Code, so as long as people learn from that and get better at it, who cares if it's suboptimal. :P

It is a Arduino required function a hidden main calls it from a while(1) infi loop.  As far as my for loop goes the original link used 10 port modifications so I did the same thing because I believe the original author was using it to generate something to demonstrate what is happening on the oscilloscope.
 

Offline westfw

  • Super Contributor
  • ***
  • Posts: 3066
  • Country: us
Re: PIC and AVR thinking of a switch but need more info
« Reply #73 on: March 23, 2013, 01:34:55 am »
Quote
avr-libc even supports setting the fuses in the source file, and saving them in ELF output, which avrdude can burn for you. See http://www.nongnu.org/avr-libc/user-manual/group__avr__fuse.html
Apparently, this is a relatively recent "feature."  Sort-of an avr-gcc problem;  the output format of the compiler doesn't really include the idea of fuses, so everyone has to agree on some "section" that is going to contain the fuse data, and what it looks like, and etc.

Including fuse data in the source code is pretty ambiguous.  Fine for reproducing exactly the original firmware configuration, but wrong for so many other applications.  For example, when using a bootloader, fuse values would have to be ignored because bootloaders can't burn fuses.  Also, incorrect fuse values for the actual hardware can "brick" AVRs in various ways.
 

Offline blewisjr

  • Frequent Contributor
  • **
  • Posts: 301
Re: PIC and AVR thinking of a switch but need more info
« Reply #74 on: March 23, 2013, 02:05:43 am »
Quote
avr-libc even supports setting the fuses in the source file, and saving them in ELF output, which avrdude can burn for you. See http://www.nongnu.org/avr-libc/user-manual/group__avr__fuse.html
Apparently, this is a relatively recent "feature."  Sort-of an avr-gcc problem;  the output format of the compiler doesn't really include the idea of fuses, so everyone has to agree on some "section" that is going to contain the fuse data, and what it looks like, and etc.

Including fuse data in the source code is pretty ambiguous.  Fine for reproducing exactly the original firmware configuration, but wrong for so many other applications.  For example, when using a bootloader, fuse values would have to be ignored because bootloaders can't burn fuses.  Also, incorrect fuse values for the actual hardware can "brick" AVRs in various ways.

Yes I have heard that about AVR's many people have bricked their Arduino's by screwing up the fuses when using Atmel Studio when using a programmer instead of the bootloader.  Some people could not even recover the chips.  I can see the advantage of the bootloader forcing fusing settings so you can't muck them up.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf