Home > Software design >  Pause or Getchar with push button
Pause or Getchar with push button

Time:05-15

I'm new to programming and I'm trying to put a pause in my code before my while(1) loop in in my main(). The pause will be broken after the state of a push button is change. I'm not sure how this is achieved using the pause or getchar, I've seen it done with a key press but not sure how to achieve it with state change of a push button.

#define _XTAL_FREQ 16000000
#pragma config WDT = OFF

#include <xc.h>
#include <stdio.h>
#include <math.h>
#include "lcd.h"

#define UI_Go PORTCbits.RC5 //Go button

void main(void) {
    lcd_init();

    lcd_cmd(L_L4);
    sprintf(Start, "'Go' to Start");  //Start while loop
    lcd_str(Start);
    __delay_ms(10);

while(1){    
       Refill();
    }
}

CodePudding user response:

OK -

It looks like you're using MPLab, so you're probably interfacing to some embedded device.

It also sounds like you want your C code to respond to a physical buttonpress on that device.

Here's an example for a particular device:

https://electrosome.com/switch-pic-microcontroller-mplab-xc8/

#define _XTAL_FREQ 8000000

#include <xc.h>

// BEGIN CONFIG
#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = ON // Watchdog Timer Enable bit (WDT enabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming)
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)
//END CONFIG

int main()
{
  TRISB0 = 0; //RB0 as Output PIN
  TRISD0 = 1; //RD0 as Input PIN

  RB0 = 0; //LED Off

  while(1)
  {
    if(RD0 == 0) //If Switch Pressed
    {
      RB0 = 1; //LED ON
      __delay_ms(3000); //3 Second Delay
      RB0 = 0; //LED OFF
    }
  }
  return 0;
}

You'll notice that it polls for the device (RD0) to change state.

You'll also notice that the specific ports you need to read will vary from device to device.

You'll need to do something similar in your code, by adapting your "while (1){...}" polling loop to read the current state of your "button", pause a few milliseconds or so between reads, and "respond" accordingly if its value changes.

CodePudding user response:

not having the hardware i cannot test but taking your comment as gold

you need

  while(UI_Set==1);

this will loop waiting for the button to be pressed

or maybe

  while(UI_Set==0);

not sure which way round the logic is

  • Related