No Frills LED Clock - 16F54 controller - Flicker free

Discussion in 'Embedded Systems and Microcontrollers' started by takao21203, Apr 24, 2016.

  1. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    I need a LED clock so I used a PCB I made some years ago.
    Soldering the TSSOP IC on the small pads isnt comfortable.

    Added a watch crystal and 6pF capacitors.

    There is no schematic but a table how the display is wired to the controller.
    Most of the work here is done in software with two decoding tables so how the display is wired is secondary.
    Such clocks have been done before- in assembler, and requiring to wire the display to 8bit port straight.
    Of course in such a case, IO is easy and fast. But its bound to a particular kind display then.

    Ive rewitten the firmware completely.

    Now I use 4 copies of the 7segment decoding table, for each multiplex phase (the data is same but sink bits change),
    and for two IO ports. Its about the limit what the 16F54 can contain!

    Second topic that bothered me was the flickering its almost unbearable at 32 KHz when C language is used.
    But the 7segment data is only updated once a minute! Table reads with offset take quite a long time.
    While using a pointer dereference in C is much faster.

    So Im buffering the data for each digit in the small RAM. It works out well.

    Heres the complete source code, that is, a push button query should be added to set the time, or its just a timer, not a clock.
    It has a blinking dot too!

    Code (C):
    2. #include  <xc.h> // 32 KHZ LEd 7 segment clock
    3. #pragma config OSC = LP  WDT = OFF CP = OFF // configuration 16F54
    5. const unsigned char dig_PORTA[] @0x01a ={0b1111,0b0011,0b1011,0b1011,\
    6. 0b0111,0b1110,0b1110,0b1011,\
    7. 0b1111,0b1111,0b1111,0b0110,\
    8. 0b1110,0b0011,0b1010,0b1010,\
    9. 0b1101,0b0001,0b1001,0b1001,\
    10. 0b0101,0b1100,0b1100,0b1001,\
    11. 0b1101,0b1101,0b1101,0b0100,\
    12. 0b1100,0b0001,0b1000,0b1000,\
    13. 0b1111,0b0011,0b1011,0b1011,\
    14. 0b0111,0b1110,0b1110,0b1011,\
    15. 0b1111,0b1111,0b1111,0b0110,\
    16. 0b1110,0b0011,0b1010,0b1010,\
    17. 0b1111,0b0011,0b1011,0b1011,\
    18. 0b0111,0b1110,0b1110,0b1011,\
    19. 0b1111,0b1111,0b1111,0b0110,\
    20. 0b1110,0b0011,0b1010,0b1010}; // segment and sink driving table for PORTA
    22. const unsigned char dig_PORTB[] @0x60 ={0b11010110,0b11010000,0b11100110,0b11110100,\
    23. 0b11110000,0b11110100,0b11110110,0b11110000,\
    24. 0b11110110,0b11110100,0b11110010,0b11100110,\
    25. 0b11000110,0b11010110,0b11110110,0b11100110,\
    26. 0b11010111,0b11010001,0b11100111,0b11110101,\
    27. 0b11110001,0b11110101,0b11110111,0b11110001,\
    28. 0b11110111,0b11110101,0b11110011,0b11100111,\
    29. 0b11000111,0b11010111,0b11110111,0b11100111,\
    30. 0b01010111,0b01010001,0b01100111,0b01110101,\
    31. 0b01110001,0b01110101,0b01110111,0b01110001,\
    32. 0b01110111,0b01110101,0b01110011,0b01100111,\
    33. 0b01000111,0b01010111,0b01110111,0b01100111,\
    34. 0b10010111,0b10010001,0b10100111,0b10110101,\
    35. 0b10110001,0b10110101,0b10110111,0b10110001,\
    36. 0b10110111,0b10110101,0b10110011,0b10100111,\
    37. 0b10000111,0b10010111,0b10110111,0b10100111}; // segment and sink driving table for PORTB
    39. unsigned char* tptr;
    40. unsigned char v_phase,v_digphase,hrh,hrl,minh,minl,secs;
    41. unsigned char ddata[8];
    43. void update() // precompute the display data, load from ROM table
    44. {
    45. *(tptr)=dig_PORTA[hrh];
    46. *(tptr+1)=dig_PORTB[hrh];
    47. *(tptr+2)=dig_PORTA[hrl+0x10];
    48. *(tptr+3)=dig_PORTB[hrl+0x10];
    49. *(tptr+4)=dig_PORTA[minh+0x20];
    50. *(tptr+5)=dig_PORTB[minh+0x20];
    51. *(tptr+6)=dig_PORTA[minl+0x30];
    52. *(tptr+7)=dig_PORTB[minl+0x30];
    53. }
    55. void display() // update the multiplex display
    56. {
    57.   TRISA=0xff;TRISB=0xff;
    58.   PORTA=*(tptr+v_digphase);
    59.   PORTB=*(tptr+1+v_digphase);
    60.   TRISA=0;TRISB=0;
    61.   v_phase+=0x10;v_phase&=0x30;
    62.   v_digphase+=2;v_digphase&=0x07;
    63. }
    65. void main(void)
    66. {
    67. v_phase=0;v_digphase=0; //initialization
    68. secs=0;minl=0;minh=0;hrl=0;hrh=0;
    69. TRISB=0;TRISA=0;OPTION=0x07;
    70. tptr=&ddata[0];
    71. update(); // display 00.00
    73. while(1)
    74. {
    75.   if(TMR0&0x20) // clock logic, quite simple
    76.   {
    77.    TMR0&=0x1f; secs++;
    78.    *(tptr+3)^=0x8; // blink rhe LED
    79.   }else if(secs==60)
    80.   {
    81.    secs=0;minl++;if(minl==10)
    82.    {
    83.     minl=0;minh++;if(minh==6)
    84.     {
    85.      minh=0;
    86.      hrl++;if(hrl==10){hrh++;hrl=0;}
    87.      if(hrl==4)if(hrh==2){hrh=0;hrl=0;}
    88.     }
    89.    }  
    90.    update();
    91.   }  
    92. display();      
    93. }
    94. }
    The display used is a very common one. At first I did run into the trap to enter the bits backwards, had to enter them again.
    Using a table like this you can use any IO bits, though, if you use 3 or 4 ports you need as many tables.
    When you share the ports you need extra masking tables as well.
    SAM_1103.JPG SAM_1104.JPG SAM_1105.JPG SAM_1107.JPG
  2. ScottWang


    Aug 23, 2012
    The project post on Completed Projects Forum, should be easy to let our members to follow and duplicate, if miss something like hardware or software and some completed clear photos then it is not a completed project, please attach the schematic and some completed clear photos, otherwise we don't know exactly what to do from your table, when your complement is completed and our Mods team will discuss and approve then you can post the new completed project to the Completed Projects Forum including all stuffs the forum should have.
  3. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    I think the project is not suitable for people who never used embedded C. Schematic is pointless as you could connect it in any way then do in software.

    I have added a pushbutton today, however.

    There are so many led displays then need different schematic or do you wish a BOM with ordering numbers?

    Missed software, need link for downloads the compiler, IDE and datasheet right?
    I've seen programming books full of these frills but something essential is missing.

    So you wish a novice guidance including all you need. I can do schematic as there are some new small parts. Should I do BOM
  4. ScottWang


    Aug 23, 2012
    If you could provide the BOM is better, and attach a *.hex.
    You just post the 7-segs leds you used in schematic and BOM, if you want then you can suggest some 7-segs leds suit for your project.

    If you providing some more infos then the members who can write the program then they can modify the program by themselves, this uC project already has its limits for some members to duplicate, that is not your fault, you just provide that you should provide, you don't have to worry about the compiler and IDE environments, that's their problem, if you attach the *.hex then the members need to solve the problem as how to write the hex code into uC.

    A explanation as how to run the project and the functions of keys should be included.
  5. dannyf

    Well-Known Member

    Sep 13, 2015
    Some suggestions - feel free to discard:

    Code (Text):
    2. #pragma config OSC = LP  WDT = OFF CP = OFF // configuration 16F54
    You want to specify all fuse settings, even if you don't use them for this application. It helps to establish what fuse settings you are using and to change them in the future.

    Code (Text):
    2. const unsigned char dig_PORTA[] @0x01a ={0b1111,0b0011,0b1011,0b1011,\
    Try to document what the array is for and how you arrive at those values.

    If you have to use allocation it to a particular address, try to use the macros if possible.

    Code (Text):
    2. unsigned char* tptr;
    3. unsigned char v_phase,v_digphase,hrh,hrl,minh,minl,secs;
    4. unsigned char ddata[8];
    Try to comment on those variables, as well as your code, so people know what they are for

    Code (Text):
    2. void update() // precompute the display data, load from ROM table
    3. ...
    4. void display() // update the multiplex display
    When you write those pieces, always ask yourself how those pieces can be reused in a future project, where the hardware may be different, there may be other devices on the ports, and the wiring may be different. The purpose of writing any code, in my view, is so that you don't have to write them in the future.

    Code (Text):
    2. void main(void)
    Try to use int main(void) if possible.

    Also, if your piece of code utilizes a peripheral, explicitly initialize it - it improves the code's re-usability and helps you a year from now undestand how the code works.

    Code (Text):
    2.   if(TMR0&0x20) // clock logic, quite simple
    Try to see if you could put it in an interrupt so it runs all by itself in the background.

    Hope it helps.
  6. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    Thanks for your requests.

    I can outline how to get the bits table for just any display.

    The 16f54 is no frills mcu, no interrupt, it only has very few configuration bits. Basically the oscillator selection, then wdt and code protection which I don't use.

    The absolute allocation is required because the banking of this mcu. Only the lower half can be used for const ROM.

    I'll add the setting key, draw schematic, hex file, and give more comments as well general outline how to derive the io tables.

    Actually I've done random io with 16f884 before, because ports are shared need to use masking tables as well. It's almost as much info to fill a chapter in a book in this case.

    So I'm using the 16f54 because it's so easy to work with, be it, the ram is painfully small, table reads are slow and costly, and it has banking for the program memory

    I can really improve performance of my c script, better say I have to
  7. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    Ive changed the code since there was only 80 words left, a little narrow to add time setting function.

    Its 163 words free, 68% used.
    The decoding table is omitted.

    Ive really concluded most 7segment programs only have a small table, sometimes 10 values.
    The IO assignment is done inside the code.
    So the code is not reuseable.

    Theres multiplexing also needs to hardcode the required bits into code.

    But in the end, a microcontroller just has IO ports. This is the interface to the outside.
    A 7segment LED display has pins which are connected to internal LEDs. This is the interface.
    Then you want numbers to show on the display. This can be transribed into a certain bit pattern on the 7segment displays external interface.

    My new approach is to put the patterns for all IO ports and all possible multiplexing phases into tables.
    It does simplify the code down to a few lines, as well this code is not dependent on some display or controller.

    Code (Text):
    2. unsigned char* tptr;
    3. unsigned char v_phase,v_digphase,secs,i,i2;
    4. unsigned char ddata[8];
    5. unsigned char timet[4];
    6. #define hrh 0
    7. #define hrl 1
    8. #define minh 2
    9. #define minl 3
    11. void update() // precompute the display data, load from ROM table
    12. {
    13.     for(i=0;i<4;i++)
    14.     {
    15.         i2=timet[i]+(i<<4);
    16.         *(tptr+i+i)=dig_PORTA[i2];
    17.         *(tptr+1+i+i)=dig_PORTB[i2];
    18.     }
    19. }
    21. void display() // update the multiplex display
    22. {
    23.   TRISA=0xff;TRISB=0xff;
    24.   PORTA=*(tptr+v_digphase);
    25.   PORTB=*(tptr+1+v_digphase);  
    26.   TRISA=0;TRISB=0;
    27.   v_phase+=0x10;v_phase&=0x30;
    28.   v_digphase+=2;v_digphase&=0x07;
    29. }
    31. void main(void)
    32. {
    33.  v_phase=0;v_digphase=0; //initialization
    34.  secs=0;
    35.  timet[minl]=0;timet[minh]=0;timet[hrl]=0;timet[hrh]=0;
    36.  TRISB=0;TRISA=0;OPTION=0x07;
    37.  tptr=&ddata[0];
    38.  update(); // display 00.00
    40.  while(1)
    41.  {
    42.   if(TMR0&0x20) // clock logic, quite simple
    43.   {
    44.    TMR0&=0x1f; secs++;
    45.    *(tptr+3)^=0x8; // blink rhe LED
    46.   }else if(secs==60)
    47.   {
    48.    secs=0;
    49.    if(++timet[minl]==10)
    50.    {
    51.     timet[minl]=0;if(++timet[minh]==6)
    52.     {
    53.      timet[minh]=0;
    54.      if(++timet[hrl]==10){timet[hrh]+=1;timet[hrl]=0;}
    55.      if(timet[hrl]==4)if(timet[hrh]==2){timet[hrh]=0;timet[hrl]=0;}
    56.     }
    57.    }    
    58.    update();
    59.   }    
    60.  display();        
    61.  }
    62. }
    I understand the code needs better explanation, but I make use of ROM table, pointer and array.
    I can not explain these techniques from ground zero.

    So the time is now kept in an array. The individual statements were too costly in terms of code size.
  8. ScottWang


    Aug 23, 2012
    How is the hex code?
  9. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    I need to add pushbutton query or its just a timer.
    Need to do more documentation.

    HEX code is only good for 3461AS though its a common kind.
  10. ScottWang


    Aug 23, 2012
    This is your project, so don't worry, just take your time as your schedule, I'm not pushing you, just mention something you should know.
  11. dannyf

    Well-Known Member

    Sep 13, 2015
    The chip has 500+ words in flash space. so 70% used or 350 words are a lot.

    I think I can write a more modular / re-usable, more readable, more user-configurable piece of code that's otherwise equivalent function-wise within 350 words
  12. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    Simply put I don't think so at all.

    Assembler is not allowed.
    The io is allowed random
    The crystal is 32 kHz means 8000 cycles per second.

    Can you give just some idea how to?
    Don't come up with a small table and assigning all the sinks to the 4 bit port. There are reasons why the sinks are distributed across ports. For instance reduce brightness variation. So the io bits could be totally random.

    There's little space for additional variables.

    Without ram buffering the table read is so slow the display flickers.

    I really wonder how it could be possible.
  13. dannyf

    Well-Known Member

    Sep 13, 2015
    Exactly 300 words, in MPLAB Express, using a free compiler.

    Code (Text):
    2. Starting Build...
    3. >make -f Makefile CONF=free
    4. make -f nbproject/ SUBPROJECTS= .build-conf
    5. make -f nbproject/ dist/free/production/16f54_ledx7.production.hex
    6. "xc8.exe" --pass1 --chip=16F54 -Q -G --double=24 --float=24 --opt=default,+asm,+asmfile,-speed,+space,-debug --addrqual=ignore --mode=free -P -N255 --warn=0 --asmlist --summary=default,-psect,-class,+mem,-hex,-file --output=default,-inhx032 --runtime=default,+clear,+init,-keep,-no_startup,-osccal,-resetbits,-download,-stackcall,+clib --output=-mcof,+elf:multilocs --stack=compiled:auto "--errformat=%f:%l: error: (%n) %s" "--warnformat=%f:%l: warning: (%n) %s" "--msgformat=%f:%l: advisory: (%n) %s" -obuild/free/production/main.p1 main.c
    7. "xc8.exe" --chip=16F54 -G -mdist/free/production/ --double=24 --float=24 --opt=default,+asm,+asmfile,-speed,+space,-debug --addrqual=ignore --mode=free -P -N255 --warn=0 --asmlist --summary=default,-psect,-class,+mem,-hex,-file --output=default,-inhx032 --runtime=default,+clear,+init,-keep,-no_startup,-osccal,-resetbits,-download,-stackcall,+clib --output=-mcof,+elf:multilocs --stack=compiled:auto "--errformat=%f:%l: error: (%n) %s" "--warnformat=%f:%l: warning: (%n) %s" "--msgformat=%f:%l: advisory: (%n) %s" --memorysummary dist/free/production/memoryfile.xml -odist/free/production/16f54_ledx7.production.elf build/free/production/main.p1
    8. Microchip MPLAB XC8 C Compiler (Free Mode) V1.35
    9. Build date: Jul 7 2015
    10. Part Support Version: 1.35
    11. Copyright (C) 2015 Microchip Technology Inc.
    12. License type: Node Configuration
    14. Memory Summary:
    15. Program space used 12Ch ( 300) of 200h words ( 58.6%)
    16. Data space used 12h ( 18) of 19h bytes ( 72.0%)
    17. EEPROM space None available
    18. Data stack space used 0h ( 0) of 7h bytes ( 0.0%)
    19. Configuration bits used 0h ( 0) of 1h word ( 0.0%)
    20. ID Location space used 0h ( 0) of 4h bytes ( 0.0%)
    22. You have compiled in FREE mode.
    23. Using Omnicient Code Generation that is available in PRO mode,
    24. you could have produced up to 60% smaller and 400% faster code.
    25. See [URL][/URL] for more information.
    this is how the hardware connection is specified - fully user configurable.

    Code (Text):
    2. //hardware configuration
    3. //Pin12/Dig1 on RA1
    4. #define DIG1_PORT                   PORTA
    5. #define DIG1_DDR                    TRISA
    6. #define DIG1                        (1<<1)          //D1 on RA1
    8. //Pin11/SegA on RA0
    9. #define SEGA_PORT                   PORTA
    10. #define SEGA_DDR                    TRISA
    11. #define SEGA                        (1<<0)
    13. //Pin10/SegF on RB7
    14. #define SEGF_PORT                   PORTB
    15. #define SEGF_DDR                    TRISB
    16. #define SEGF                        (1<<7)
    18. //Pin9/Dig2 on RB6
    19. #define DIG2_PORT                   PORTB
    20. #define DIG2_DDR                    TRISB
    21. #define DIG2                        (1<<6)
    23. //Pin8/Dig3 on RB5
    24. #define DIG3_PORT                   PORTB
    25. #define DIG3_DDR                    TRISB
    26. #define DIG3                        (1<<5)
    28. //Pin7/SegB on RB4
    29. #define SEGB_PORT                   PORTB
    30. #define SEGB_DDR                    TRISB
    31. #define SEGB                        (1<<4)
    33. //Pin6/Dig4 on RB3
    34. #define DIG4_PORT                   PORTB
    35. #define DIG4_DDR                    TRISB
    36. #define DIG4                        (1<<3)
    38. //Pin5/SegG on RB2
    39. #define SEGG_PORT                   PORTB
    40. #define SEGG_DDR                    TRISB
    41. #define SEGG                        (1<<2)
    43. //Pin4/SegC on RB1
    44. #define SEGC_PORT                   PORTB
    45. #define SEGC_DDR                    TRISB
    46. #define SEGC                        (1<<1)
    48. //Pin3/SegDP on RB0
    49. #define SEGDP_PORT                  PORTB
    50. #define SEGDP_DDR                   TRISB
    51. #define SEGDP                       (1<<0)
    53. //Pin2/SegD on RA3
    54. #define SEGD_PORT                   PORTA
    55. #define SEGD_DDR                    TRISA
    56. #define SEGD                        (1<<3)
    58. //Pin1/SegE on RA2
    59. #define SEGE_PORT                   PORTA
    60. #define SEGE_DDR                    TRISA
    61. #define SEGE                        (1<<2)
    All the TRIS bits are not necessary on this chip.

    With minimum reconfiguration, you can pretty much run it on any mcu.
    Last edited: Apr 26, 2016
  14. dannyf

    Well-Known Member

    Sep 13, 2015
    Worst case scenario: the C routines take 90 ticks to update the display buffer, and 130 ticks to update the display. So running off a 32Khz crystal, the led display is updated at least 40x per second. Flicker free I guess for the mortal mass, :)
  15. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    so heres my criticism. No source code.
    No configuration bits even. Are you kidding me.

    If you dont want to show source code then dont reply to my thread where I put the full source.
    And say your code is better in any kind.
    Sorry for being blunt.
  16. dannyf

    Well-Known Member

    Sep 13, 2015
    At the appropriate time / venue, i will share the source code - it basically incorporates what I told you to do earlier.

    So no need to hyperventilate.

    As to your code, you should read the datasheet a little bit carefully, because as written, this little statement of yours has TWO bugs:

    Code (Text):
    2.    TMR0&=0x1f;
    You will find that the timing is just slightly longer than you had anticipated.

    Again, don't hyperventilate. Just go back and read the timer section thoroughly and you will figure it out.
  17. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    No, now you are being cryptic.
    I want to be frank I dont believe your code is faster or smaller.
    You dont want to show it, fine. But then you compare two different things.

    Sure I need to keep secrect a small script doing something that was done 30 years ago.

    Hyperventilating? Now youre crazy. The matter leaves me cold. I just would like to verify your statements.
    For this purpose, please show the complete source.

    90 cycles sure. You do all in 22.5 cycles. I believe it. But seeing is better than believing.
  18. dannyf

    Well-Known Member

    Sep 13, 2015
    for your coding enjoyment, :)

    The code running on a 16F84A - minimal changes from a 16F54.
  19. dannyf

    Well-Known Member

    Sep 13, 2015
    I told you earlier about this line of your code being buggy - the timing will be longer than you expected:

    Code (Text):
    2. TMR0&=0x1f;
    Here is a simulation of your code running on a 16F84A (pretty much identical to 16F54). I was running to the line mentioned earlier, and counting time - the mcu is running on a 32Khz crystal.

    At the bottom of the picture is time elapsed since the last time the code executed to the above line. In a correctly designed code, it should be exactly 1.0 second. It took your code 1.0011 second to do that. ie, your time-keeping is off roughly 4 seconds off per hour, or 2 minutes per day.

    That's a very poor clock. Even a knock-off Rolex is better than that.
  20. takao21203

    Thread Starter Distinguished Member

    Apr 28, 2012
    OK according to my calculations, I used a CASIO calculator, the deviation is 1 second every 4096

    Since the prescaler is 256 the write is every 32 timer increments.
    I never actually understood if this stalling affects the prescaler or just the timer register update. Anyway Ive added code to correct this.

    Its not fair to use 16F84. You use division as well. Lets say, division also is not allowed.
    How you do the multiplexing isnt clear either. Does the 16f84 for instance have the restriction on lower 256 words for ROM constants? Does it have 25 bytes only? At 1K the savings wont be required but I need some extra space for the drift correction so maybe, just 50 remaining.

    OK your go-cart is faster and better just for some reason, you cant demonstrate it, instead you bring another with a slightly different engine kind, and say, for some reason, this engine even cant be looked at.

    Sure I have many other PICs around, DS1307, even completely ready made RTC modules. Sure maybe in some way youre right.

    But also for sure I did these small 7seg tables years ago and did set port bits explicitely and I wasnt too happy about it.

    I dont yet understand if your program is equal in all details and if it is really faster and or shorter.

    And yes in some way, correcting the drift and having a pushbutton, these are already frills of some kind. Just for a timer, the drift makes little difference, and if you start the clock at midnight, well there you go...

    When the overhead added is 2 cycles, on top of 256, and this occurs every one in 32 times, its 1/4096? 68 minutes, 16 seconds. Its not explained in the datasheet if this affects the prescaler or just the timer register. At least its not spelled out.

    When the pushbutton works I will do a long time test. And prep up the documentation.
    I had the crystall cap ground soldered to a display pin of course this caused drifting visible after just 1/2 hour.
    Last edited: Apr 26, 2016