Skip to content
TheChatArchiveThe Chat Archive
gpt-4-1106-preview· openaiHugging Face Suzhen/CodeChat

I HAVE THIS tp i know the pdf is hard to make up since i scanned it in a weird way but…

  1. User

    I HAVE THIS tp i know the pdf is hard to make up since i scanned it in a weird way but try to make the best of it TRAVAUX PRATIQUES Atelier N°: 8

    Module : Informatique Industrielle Enseignant: L. Bouhouch | Systeme de Management Qualité - ISO 9001, version 2000 voo _|

    2-4. Squelette du programme & compléter associé au clignotement d'une Led par le WDT

    PRRICC CBC EI COCCI TOS IOCIE CCC RCC IOISIORI CICK AC ICICI I AACR Ae sck A A AOR IEC oo lc ae se ak

    Commande par un interrupteur sur le port A du clignotement de LEDs sur le port B par le WDT.

    Microcontréleur : PIC] 6F84A Oscillateur : 4 MHz,

    EE EE SII II II AIT OIE AI STEAD OSETIA SEI A ASA A ASO SE AEA AAA A

    #define LED Vi PORTB.FO ## La LED Verte connectée A RBO #define LED _J PORTB.F7 // La LED Jaune connectée 4 RB7 #define SW PORTA.FO // L'interrupteur connectée 4 RAO

    void main()

    ‘/ Configurer les Ports A et B en éteignant les 2 LED

    ‘/ SLEEP est une instruction assembleur, Elle sera utilisée grace a la ligne : asm SLEEP

    while(1) // Boucle infinie

    {

    // Si SW est Ouvert ==> La LED_V reste éteinte alors que la LED _J clignote par I'instruction SLEEP

    ECOLE POLYTECHNIQUE PRIVEE D'AGADIR ~ 4 -© Propriété Exclusive de I'Ecole Polytechnique Privée d'Agadir Av. Hassan te" Cité Dakhla, Agadir - Tét : 028 23 34 34 | | TRAVAUX P RATIQUES Atelier N° : 8

    | Module : Informatique Industrielle Enseignant : L. Bouhouch

    | Systéme de Management Qualité - ISO 9001, version 2000 | voo

    ATELIER n° 8

    Commande de clignotement de LEDs par microcontréleur PICI6F84A

    La fiche de TP décrite ci-dessous a pour but, d'une part de proposer un programme C qui, selon Je choix avec un interrupteur relié 4 une entrée du PIC16F84A de faire clignoter infiniment unc des deux Leds reliées aux sorties du microcontréleur PICI6F84A. D'autre part, programmer réellement le microcontréleur et faire le test de cette application.

    1. Enonceé du Sujet :

    ~ Etre apte 4 développer un programme en langage C, permettant de commander les interfaces d'entrées/sorties du PICI6F84A.

    • Etre capable de programmer le PICI6F84A en utilisant un programmateur fourni et un logiciel de programmation.

    Objectifs :

    1- Création d'un projet sous MikroC PRO for PIC avec la cible un PICIGF84A.

    2- Compléter le programme C réalisant le clignotement infini, selon I'état de la broche RAO, d'une des deux LEDs reliées aux broches PBO et RB7 du Port B du PIC en se servant du WDT (WatchDog Timer) pour mettre le PIC en pause, grace a l'instruction assembleur SLEEP.

    3- Test de l'application sur le simulateur fourni aprés la programmation du PIC.

    Cahier des charges :

    Materiels et logiciels nécessaires :

    • Micro-ordinateur de type PC sous Windows,

    • Outil de développement MikroC PRO for PIC version 6.5 ou 6.6.

    ~ Programmateur de PIC de type K150 sur USB avec son logiciel de programmation.

    • Simulateur de test des PIC avec alimentation.

    Durée : 3 heures

    ECOLE POLYTECHNIQUE PRIVEE D'AGAI

    • 1 -© Propriété Exctusive de Ecole Polytechnique Privée d'Agadir Ay. Hassan Ler Cite Dakhla, Agadir - Tél : 028 23 34 TRAVAUX PRATIQUES Atelier N°: 8 a

    | | J Module : Informatique Industrielle Enseignant : L. Bouhouch |

    Systeme de Management Qualité — ISO 9001, version 2000 | voo

    1. Projet sous MikroC PRO for PIC

    Dans cet atelier, nous nous intéressons 4 simuler et a programmer réellement le clignotement infini, selon l'état de la broche RAO, d'une des deux LEDs reliées aux broches PBO et RB7 du Port B du PIC! 6F84A, en se servant du WDT (WatchDog Timer) pour mettre le PIC en pause durant environ 2,3 seconde, grace a l'instruction assembleur SLEEP. Le quartz utilisé est de valeur 4 MHz,

    2-1. Rappeis

    La programmation des entrées/sortics (Port A et Port B) du microcontréleur PIC16F84 nécessite l'utilisation des registres suivants : (TRISA, PORTA) et (TRISB, PORTB).

    Les registres TRISA et TRISB contiennent 8 bits chacun pour le choix de la direction du port A ou B: 1 => Entrée et 0 > Sortie.

    Les registres PORTA et PORTB sont composés chacun de 8 bits pour lire l'état d'une entrée ou forcer l'état d'une sortie des ports A ou B.

    La programmation du WDT du microcontréleur PICI6F84A_ nécessite la configuration du registre OPTION_REG.

    Le registre OPTION_REG cst composé des bits suivants :

    OPTION REG pang _INTEDG | TOCS | TOSE | PSA | PS? | PSI) PSO |

    • /RBPU : Résistances de tirage 4 Vdd des Entrées du Port B (Validé par 0).
    • INTEDG : Front actif provoquant une interruption sur

    la borne RBO (1 pour montant). - | Valeur des Bits) Diviseur (TMRO) | Diviseur (WDT)

    • TOCS : Source utilisée par le Timer (0 pour horloge 000 1:2 Tel interne, 1 pour externe sur RA4). 001 1:4 1:2

    • TOSE : Front actif sur RA4 faisant avancer le 910 1:8 1:4 compteur Timer (0 pour front montant) O11 1:16 1:8

    • PSA: Pré-diviseur associé au Timer si (0) ou au chien 100 a 1:16 de garde WDT si (1). 101 1: 64 1:32

    • PS2 ... 0: Valeur du Diviseur de fréquence pour le 10 I 128 1:64 Timer ou le WDT. 111 1: 256 1: 128

    2-2. Travail a faire 1- Créer un dossier personnel dans le disque F:\ ou H:\EspaceStockage
    (Exemple H:\EspaceStockage\V otreNom). 2- Lancer le logiciel ISIS, réaliser et compléter le schéma donné ci-dessous. 3- Sauvegarder ce schéma dans Je dossier personnel (H:\EspaceStockage\V otreNom). 4- Exécuter le logiciel MikroC PRO for PIC. 5- En cas de besoin fermer ie projet actuel en utilisant le menu Project/Close Project.

    6- Créer un nouveau projet sous MikroC PRO jor PIC dans votre dossier personnel, en utilisant le menu

    Project/New Project... ou en cliquant sur loption New Project... de la page principale Start Page, puis en cliquant sur Next.

    1. Donner un nom & votre projet en le plagant dans votre dossier de travail, tout en choisissant la cibie PICI6F84A ainsi aue fa valeur de la fréquence du quartz (4 MHz) utilisé pour "horloge de fonctionnement. Puis cliquer sur Next, Next, Next et enfin Finish.

    2. En cas de doute, vous pouvez 4 tout moment changer le microcontréleur cible ainsi que la fréquence, en cliquant 4 gauche sur la fenétre Project Settings.

    ECOLE POLYTECHNIQUE PRIVEE D'AGADIR ~ 2 -© Propriété Exclusive de Ecole Polytecnnique Privée d’Agadir Av. Hassan 1 Cité Dakhla, Agadir - Tél : 028 23 34 34

    ~~ TRAVAUX PRATIQUES ~— Atelier N°: 8

    Module : Informatique Industrielle Enseignant : L. Bouhouc: voo

    ecoLE Systéme de Management Qualité — ISO 9001, version 2000

    POLYTECHNIQUE

    PRIVEE D?- BADIR

    1. Afin d'activer le WDT, faites un clic sur le menu Project puis sur Edit Project puis choisir Enabled pour

    Watchdog Timer.

    BQ IKTOU FRU FOP FIL Ye LUPE Ur ory Il é- 1o\lt Edit Project

    File Edit View [oProject.| Build Run Fools General project settings |)

    &, New Project... Shift+ Ctrl Oxci .

    . XT

    Be pen Project. one aie Watchdog Fm ‘Enabled we Power-up Ti

    | Edit Search Paths... shite Lire? pg EE

    ‘Deebled »

    Edit Project... Shifts Ctrl+E CodeProtection

    i i Code protection off v

    es} «Clean Project Fotder... Seed a

    1. Compléter et compiler le programme proposé ci-dessous, afin de générer le fichier xxxx.HEX. Votre programme doit traiter les opérations suivantes :
    • Utilisation du WDT du PIC qui le réveille au bout d'un certain temps d'inactivité. On rappelle que, sans pré-diviseur, le PICI6F84A est réveillé au bout d'environ 18 ms. Dans notre cas, on souhaite que la période entre deux changements d'état de la LED soit d'environ 2,3 s.

    • Ne pas utiliser d'interruption.

    • Le Timer reste inactif.

    • Selon l'état de RAO (broche 17), faire clignoter l'une des LEDs {(LED_V ou LED_J) reliées aux broches 6 et 13 (RBO et RB7) du PICIGF84A.

    1. Expliquer la ligne _ Config qui est choisi dans votre programme.

    2. Embarquer dans le microcontréleur du schéma le fichier xxxx.HEX. Tester enfin l'application en Ja simulant par ISIS.

    3. En utilisant le logiciel de programmation fourni avec fe programmateur mis 4 votre disposition, procéder a la programmation du microcontréleur PIC 16F84.

    4. Enfin, en utilisant le simulateur de test fourni et le schémas ci-contre, faite le cablage et le test de votre application.

    5. Dans votre compte rendu, expliquer les différentes étapes et procédure en donnant une conclusion.

  2. Assistant

    I see that you have provided a partially readable text which seems to reference a practical work (Travaux Pratiques) related to industrial computing and microcontroller programming, specifically for the PIC16F84A microcontroller. The objective appears to be to create a program in C that will make an LED blink using a Watchdog Timer (WDT) and to implement this on the actual hardware.

    To provide you with a more comprehensive understanding and potential completion of the skeleton program provided, here's a step-by-step guide on what might be expected:

    1. Setting Up the Environment:

      • Create a new project in MikroC PRO for PIC and set the target microcontroller to PIC16F84A with an oscillator frequency of 4MHz.
      • Set up Watchdog Timer (WDT) by enabling it in the project settings.
    2. Writing the C Program:

      • The skeleton provided defines two LEDs connected to RB0 and RB7 and a switch connected to RA0.
      • You need to configure the TRIS registers to define the direction of the ports (input for the switch on PORTA and output for the LEDs on PORTB).
      • Set up the OPTION_REG register to configure the WDT.
      • Write the main program loop to monitor the state of the switch and blink the LED using the WDT to create the delay.

    Here's a basic completion of the given skeleton code:

    #include <16F84A.h>
    
    #define LED_V PORTB.F0 // The green LED connected to RB0
    #define LED_J PORTB.F7 // The yellow LED connected to RB7
    #define SW PORTA.F0    // The switch connected to RA0
    
    void setup() {
        TRISA = 0xFF; // Set PORTA to input
        TRISB = 0;    // Set PORTB to output
        
        // Initialize LEDs to OFF
        LED_V = 0;
        LED_J = 0;
        
        OPTION_REG = 0x07; // Configure WDT postscaler for approx. 2.3 second timeout
    }
    
    void main() {
        setup();
    
        while(1) {
            if (SW == 1) {
                // If switch is pressed, blink green LED
                LED_V = ~LED_V; // Toggle LED_V state
                asm SLEEP;      // Initiates sleep, WDT will wake up microcontroller
            } else {
                // If switch is not pressed, keep green LED off and blink yellow LED
                LED_V = 0;
                LED_J = ~LED_J; // Toggle LED_J state
                asm SLEEP;      // Initiates sleep, WDT will wake up microcontroller
            }
        }
    }
    
    1. Compiling and Testing:

      • Compile the program in MikroC PRO for PIC and resolve any syntax or logical errors.
      • Load the resulting HEX file into the microcontroller in the ISIS simulation.
      • Test the program using the simulator and then on the actual PIC16F84A microcontroller with the LED and switch connected.
    2. Documentation:

      • Document your work in a report explaining the functionality of the code, the setup process, and the outcomes of your tests.
    3. Conclusion:

      • Summarize the result of the practical task, highlighting successfully achieved objectives and any challenges encountered.

    In practice, the details such as the OPTION_REG configuration will depend on the exact timing requirements for the WDT and how the WDT prescaler should be set for your specific need. The 2.3 second delay might require fine-tuning of the WDT settings. Always refer to the PIC16F84A datasheet for precise register configuration.

  3. User

    how would we set up the watch dog timer to 2.3

  4. Assistant

    Setting up the Watchdog Timer (WDT) on the PIC16F84A to achieve a delay of approximately 2.3 seconds requires configuring the prescaler and understanding the time-out period of the WDT for the given oscillator frequency.

    The PIC16F84A's WDT has a nominal time-out period of approximately 18 ms without a prescaler at a 4 MHz oscillator frequency. The WDT time-out can be extended by assigning the prescaler to the WDT.

    The OPTION_REG register is used to configure the prescaler. The prescaler can be set to divide the WDT oscillator frequency by a factor ranging from 1:1 (no prescaling) to 1:128. In this case, you would need to select a prescaler that results in a period close to 2.3 seconds when multiplied by the base period (approximately 18 ms).

    Given that 2.3 seconds is approximately 2300 ms, you can calculate the required prescaler value as follows:

    Prescaler value = Desired WDT period / Base WDT period

    Let's calculate the required prescaler for an approximate 2.3-second delay:

    Prescaler value = 2300 ms / 18 ms ≈ 127.78

    The closest prescaler value from the available options that does not exceed the required delay is 1:128.

    The following bits in OPTION_REG are relevant for WDT prescaler settings:

    • PSA (Prescaler Assignment bit): Must be set to 1 to assign the prescaler to the WDT.
    • PS2:PS0 (Prescaler Rate Select bits): Set these bits to 111 for a 1:128 prescale ratio.

    Here is the appropriate configuration for the OPTION_REG register:

    // OPTION_REG bits:
    // 7    - RBPU: PORTB Pull-ups (1 = disabled)
    // 6    - INTEDG: Interrupt Edge Select (not used for WDT)
    // 5    - T0CS: TMR0 Clock Source Select (not used for WDT)
    // 4    - T0SE: TMR0 Source Edge Select (not used for WDT)
    // 3    - PSA: Prescaler Assignment (1 = WDT)
    // 2:0  - PS2:PS0: Prescaler Rate Select bits (111 = 1:128)
    
    OPTION_REG = 0b10000111; // Set prescale ratio to 1:128 for WDT, disable PORTB pull-ups
    

    The exact delay cannot be guaranteed to be precisely 2.3 seconds due to the tolerance of the internal WDT oscillator and the specified prescale ratios, but it will be close.

    Now, when the WDT is enabled and you use the SLEEP instruction, the PIC will go to sleep and wake up approximately every 2.3 seconds when the WDT times out and resets the microcontroller unless it is periodically cleared in software.

    Here's how you incorporate this into a MikroC PRO for PIC program for the PIC16F84A:

    // Define the LEDs and Switch
    #define LED_V PORTB.F0
    #define LED_J PORTB.F7
    #define SW PORTA.F0
    
    void setup() {
        // Set up PORT directions
        TRISB = 0x00; // Set PORTB as outputs for the LEDs
        TRISA = 0xFF; // Set PORTA as inputs for the switch
    
        // Set prescaler for WDT: approximately 2.3 seconds
        OPTION_REG = 0b10000111; // WDT prescaler set to 1:128 and no PORTB pull-ups
    
        // Enable WDT
        // This is often done through a #pragma config or through project settings rather than code
        // Check your compiler documentation on enabling WDT
    }
    
    void main() {
        setup();
    
        while (1) {
            if (SW == 0) { // Assuming the switch is active low
                LED_V = 1; // Turn on the green LED
                LED_J = 0; // Turn off the yellow LED
            } else {
                LED_V = 0;       // Turn off the green LED
                LED_J = ~LED_J;  // Toggle the yellow LED
            }
            asm SLEEP; // Microcontroller sleeps here, wakes up on WDT overflow/reset
        }
    }
    

    Keep in mind that the SLEEP instruction will halt the CPU until a WDT time-out or another interrupt event occurs. Make sure your code is designed to handle these wake-up events accordingly.

  5. User

    cant we just do option_reg = 0x07

  6. Assistant

    Yes, you can indeed use OPTION_REG = 0x07; directly to set the WDT prescaler to 1:128, which is the highest prescaler value for the WDT in the PIC16F84A microcontroller.

    In binary, the value 0x07 is 00000111, which sets the PSA bit high (assigning the prescaler to the WDT) and the PS2:PS0 bits to 111 (selecting the 1:128 prescaler ratio). This is the appropriate setting to achieve the longest WDT time-out and thus the longest sleep period for each WDT cycle.

    Here is how you can set it up in your C program:

    // OPTION_REG configuration for WDT prescaler 1:128
    OPTION_REG = 0x07;
    

    This will configure the prescaler to approximately 2.3 seconds assuming an 18 ms nominal period without the prescaler. That being said, the actual WDT time-out can vary due to production variations, temperature changes, and supply voltage fluctuations, so the resulting WDT period may not be precisely 2.3 seconds but should be within that ballpark range.

    To use the WDT in your main code loop, you'd still continue with the asm SLEEP command to put the microcontroller to sleep, allowing the WDT to wake it up after the timeout.

    void main() {
        setup();
    
        while (1) {
            if (SW == 0) { // Check the state of the switch
                // Code for LED behavior when the switch is on
                // ...
            } else {
                // Code for LED behavior when the switch is off
                // ...
            }
            asm SLEEP; // Put the MCU to sleep, WDT will wake it up
        }
    }
    

    By using OPTION_REG = 0x07;, you have achieved the right configuration quickly and efficiently for the WDT to reach a 2.3 seconds delay as close as possible given the 18 ms base period without prescaling.

  7. User

    Why asm sleep]

  8. Assistant

    The asm keyword is used in C programming to embed assembly language instructions directly within the C code. In this particular context, asm SLEEP; is an embedded assembly instruction that tells the PIC microcontroller to enter into a sleep mode.

    When the microcontroller executes the SLEEP instruction, it goes into a low-power state to conserve power until it is woken up by an interrupt or a reset. In the case of using the Watchdog Timer (WDT), the microcontroller will sleep until the WDT overflows and causes a wake-up/reset event.

    Here's why we use the SLEEP instruction in this case:

    1. Power Conservation: While in sleep mode, the microcontroller consumes significantly less power, which is highly beneficial in battery-operated or power-sensitive applications.

    2. Controlled Wake-ups: In sleep mode, the microcontroller will do nothing until an interrupt occurs. With the WDT enabled, this interrupt will happen when the WDT overflows, based on the preconfigured WDT time-out period. This allows the execution of code at controlled intervals without an active wait loop consuming power.

    3. Simple Syntax: Using inline assembly for certain tasks, such as invoking the SLEEP command, can allow for more direct control and a clearer expression of the programmer's intention. Since SLEEP is an actual CPU instruction and not a C-level construct, inline assembly is a straightforward way to use it.

    Using asm SLEEP; in your main loop, along with the WDT, serves to periodically wake up the PIC16F84A microcontroller from sleep mode, toggle the state of an LED, and then put it back to sleep, creating a blinking effect.

    The alternative to using asm SLEEP; is to use a native C function provided by the compiler that invokes the SLEEP instruction. In some compilers, such as MPLAB XC8, you might write SLEEP(); as a standard C function call, which internally compiles into the SLEEP assembly instruction.

    It's important to ensure that compiler directives or pragmas do not disable the WDT during sleep because, in that case, there will be nothing to wake up the microcontroller, and it will remain in sleep mode indefinitely (or until a different interrupt event occurs or a hardware reset is triggered).

  9. User

    Should we wait 2.3 seconds while its turned on or off

  10. Assistant

    When configuring the Watchdog Timer (WDT) for a 2.3-second timeout on the PIC16F84A microcontroller to control an LED's blinking, the intention is to alternate the LED state between on and off with each timeout period. This means that with each WDT reset, you would toggle the state of the LED, effectively creating a blink where the LED is on for 2.3 seconds and then off for 2.3 seconds, and so on.

    Here is a pseudocode representation of the logic:

    while (true) {
        if ( /* condition to blink LED */ ) {
            toggle_LED_state();  // Change the LED from on to off, or off to on
            asm SLEEP;           // Enter sleep mode (WDT starts counting)
            // The MCU will now sleep until the WDT times out after ~2.3 seconds
            // On WDT timeout, the MCU wakes up, and execution resumes here
        }
        else {
            // Code for what to do when the LED is not supposed to blink
        }
    }
    

    And here is the C code tailored for the PIC16F84A which achieves the blinking behavior:

    void main() {
        // Initialization code ...
    
        while (1) {  // Infinite loop
            LED_V = ~LED_V; // Toggle the state of the green LED
            asm SLEEP;      // Put the MCU to sleep. WDT will wake it after ~2.3 seconds
    
            // Execution will resume here after WDT timeout and MCU reset
        }
    }
    

    In this code snippet, each iteration of the loop will first toggle the state of the LED (LED_V) and then put the microcontroller to sleep (asm SLEEP). After approximately 2.3 seconds, the WDT times out and resets the microcontroller, causing it to restart execution after the sleep command, and the next toggle of the LED occurs. This results in the LED being in each state (on or off) for roughly 2.3 seconds.

    To summarize:

    • The LED will be on for approximately 2.3 seconds.
    • Then, the PIC goes into sleep mode and remains there until the WDT times out.
    • When the WDT times out (after another ~2.3 seconds), the MCU is reset, the LED is toggled, and the cycle continues.

    This creates a blinking pattern where the duration of the LED being on and off is approximately equal to the configured WDT interval (~2.3 seconds each).

  11. User

    is this code right #define LED_V PORTB.F0 #define LED_J PORTB.F7 #define SW PORTA.F0 void main(){ TRISB = 0x00; TRISA.F0 = 1;

    LED_V = 0; LED_J = 1;

    OPTION_REG = 0x07;

    while(1){ if(SW = 1){ LED_J = 0; asm SLEEP; LED_J = 1; asm SLEEP; } if(SW = 0){ LED_V = 1; asm SLEEP; LED_V = 0; asm SLEEP; } } }

  12. Assistant

    The intention behind your code seems clear, but there are some errors and potential misunderstandings in the provided code. Here's what needs to be corrected or clarified:

    1. In C, the equality comparison operator is ==, not =, which is the assignment operator. So if(SW = 1) and if(SW = 0) should be if(SW == 1) and if(SW == 0), respectively.

    2. TRISA.F0 = 1; is not valid C syntax for configuring individual bits of a port. You should set the entire TRISA register to 0xFF if all pins on PORTA are being used as inputs or manipulate individual bits with bitwise operations.

    3. If PORTA is entirely used for input, then setting TRISA to 0xFF is appropriate, which means all bits are set as inputs.

    4. The logic within the while loop should be adjusted to reflect toggle behavior for the LEDs.

    Here is the corrected and improved version of your code:

    #define LED_V PORTB.F0
    #define LED_J PORTB.F7
    #define SW PORTA.F0
    
    void main() {
        // Set all pins of PORTB as outputs for the LEDs
        TRISB = 0x00;
        
        // Set all pins of PORTA as inputs, only RA0 is actually used here
        TRISA = 0xFF;
    
        // Initialize LED states
        LED_V = 0;  // Turn off green LED
        LED_J = 1;  // Turn on yellow LED
    
        // Set prescaler for WDT: approximately 2.3 seconds
        OPTION_REG = 0x07; 
    
        while (1) {
            if (SW == 1) {  // If the switch is pressed (assuming high level means pressed)
                // Toggle the yellow LED state and sleep for ~2.3 seconds
                LED_J = ~LED_J;
                asm SLEEP;
            }
            if (SW == 0) {  // If the switch is not pressed
                // Toggle the green LED state and sleep for ~2.3 seconds
                LED_V = ~LED_V;
                asm SLEEP;
            }
        }
    }
    

    In this corrected code, a few key changes were made:

    • The TRISA register is set to 0xFF to make all pins of PORTA input, which is commonly done even if you're only interested in a single pin, like RA0.
    • Avoiding using TRISA.F0 syntax and instead using the whole register assignment.
    • Using the correct comparison operator == for checking the state of the switch.
    • The toggle behavior for the LEDs is maintained within the loop, and the microcontroller is put to sleep after each toggle, which will result in roughly 2.3-second intervals of blinking, based on your WDT configuration.
  13. User

    so the programs instruction is for the led to stay on for 2.3 seconds then turn off for 2.3 seconds

  14. Assistant

    If the program's intention is to have an LED stay on for 2.3 seconds and then turn off for 2.3 seconds in an infinite loop, you will need to ensure that there is only one SLEEP instruction in the loop for each LED state change, not two as seen in your code.

    Each SLEEP will cause the microcontroller to wait approximately 2.3 seconds (based on the WDT configuration) before waking up. Thus, to create a toggle with 2.3 seconds on and 2.3 seconds off, you should toggle the LED, sleep, wake up, toggle the LED again, and sleep again.

    In addition, your code currently has two separate if statements for checking SW. Instead, you should use an if-else construct to ensure that only one block of code runs depending on the switch state.

    Here's how you can modify your code to achieve the desired LED toggle behavior:

    #define LED_V PORTB.F0
    #define LED_J PORTB.F7
    #define SW PORTA.F0
    
    void main() {
        // Set all pins of PORTB as outputs for the LEDs
        TRISB = 0x00;
        // Set all pins of PORTA as inputs (or use bitwise operation to set only RA0 as input)
        TRISA = 0xFF;
    
        // Initialize LED states
        LED_V = 0;  // Turn off the green LED initially
        LED_J = 0;  // Turn off the yellow LED initially
    
        // Set prescaler for WDT: approximately 2.3 seconds
        OPTION_REG = 0x07; 
    
        while (1) {
            // Check the state of the switch
            if (SW == 0) {  // If switch is pressed/active (assuming active low)
                // Toggle the yellow LED state
                LED_J = 1;
                asm SLEEP;   // Sleep for ~2.3 seconds, LED_J is on during this period
                LED_J = 0;
            } else {        // If switch is not pressed/inactive
                // Toggle the green LED state
                LED_V = 1;
                asm SLEEP;   // Sleep for ~2.3 seconds, LED_V is on during this period
                LED_V = 0;
            }
            asm SLEEP;       // Sleep for another ~2.3 seconds, LED is off during this period
        }
    }
    

    In the code above:

    • If the switch is active (SW == 0), the yellow LED (LED_J) is turned on, the microcontroller sleeps for 2.3 seconds, and then the yellow LED is turned off.
    • If the switch is inactive (SW == 1), the green LED (LED_V) is turned on, the microcontroller sleeps for 2.3 seconds, and then the green LED is turned off.
    • After either LED on-off sequence, there is another sleep instruction to ensure the LED remains off for 2.3 seconds before the next loop iteration.

    Remember that the actual wake-up time can vary due to production variances, temperature, and voltage changes. The WDT should periodically be cleared if you're not using it to reset the microcontroller. In this example, however, the WDT is used to create the delay and the microcontroller is expected to be reset when the WDT times out, starting the loop again.

  15. User

    seems like it turns on for about 2.8 seconds

  16. Assistant

    The Watchdog Timer (WDT) in a PIC microcontroller is an independent timer that can cause a microcontroller reset upon timing out. The WDT is designed to help recover from situations where the program may become stuck due to unforeseen circumstances.

    The nominal timeout period of the WDT for a PIC microcontroller like the PIC16F84A is often given in the datasheet, but this period can vary due to several factors including temperature, voltage, and individual chip variances. Additionally, the accuracy of the internal oscillator that drives the WDT is not as precise as the main system oscillator.

    Given that you've set up the WDT with a prescaler of 1:128 and an approximate base timeout period of 18 ms, the expected timeout should indeed be near 2.3 seconds (18 ms * 128 = 2304 ms). However, if you're observing a timeout of approximately 2.8 seconds instead, this could be due to the tolerances and inaccuracies involved with the WDT oscillator.

    To adjust for this discrepancy, you have a few options:

    1. Trial and Error Adjustment: You can experiment with a smaller prescaler value if you have observed that the current setting is consistently yielding a longer delay than intended. Note that the options for prescaler settings are limited, and the next step down is a prescaler of 1:64, which will approximately halve the delay.

    2. Calibration: If precision is essential and the application allows it, you could attempt to calibrate your delays by measuring the actual timeout and then adjusting your software routine accordingly.

    3. External Timer: If the imprecision of the WDT is problematic for your application, you might want to consider using an external timer or the internal Timer0 module of the PIC16F84A for more accurate timing, though this would not conserve power the same way that the WDT allows.

    4. Additional Software Delays: If the WDT cannot give you the precise timing you need, and power consumption is not a critical factor, you might incorporate additional software delays or loops to adjust the timing. However, this approach could lead to less efficient code.

    5. Hardware Solutions: For critical timing applications, a real-time clock (RTC) or other dedicated timing hardware might be necessary.

    Here's an example of slightly adjusting your WDT configuration to use a smaller prescaler (1:64), which corresponds to 0x06 in the OPTION_REG:

    // Set prescaler for WDT: approximately 1.15 seconds with a prescaler of 1:64
    OPTION_REG = 0x06; 
    

    You'd then need to adjust your program logic to account for this new, shorter delay, possibly by adding additional code to effectively double the wait period or by re-evaluating your system requirements against the capabilities and limitations of the WDT.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.