Unable to Break Out of if Statement After Button Depression - Microchip - c

I'm unable to break out of an if statement after a button has been depressed. The button activates a relay and the depression turns the relay off.
Here is my full code: I'm new to C so all comments and suggestions are much appreciated.
#include "mcc_generated_files/mcc.h"
#define FCY 8000000UL
#include <libpic30.h>
//#define baudrate 19200
int main(void)
{
// Initialise the device
SYSTEM_Initialize();
while(1)
{
LED4_SetLow(); // Turn on 3v3 LED
LED12v_SetHigh();
LED3_SetHigh();
LED1_SetHigh();
int button;
button = UART5_Read();
if (button == 0x08)
{
RLY1_SetHigh();
RLY3_SetHigh();
if (button == 0x00)
goto finished;
}
finished:
RLY1_SetLow();
RLY3_SetLow();
}
return (0);
}
I have now edited the code as follows. The relays are able to be set high but the condition 0x00 is never reached. Can someone please explain?
#include "mcc_generated_files/mcc.h"
#define FCY 8000000UL
#include <libpic30.h>
//#define baudrate 19200
int main(void)
{
// Initialise the device
SYSTEM_Initialize();
while(1)
{
LED4_SetLow(); // Turn on 3v3 LED
LED12v_SetHigh();
LED3_SetHigh();
LED1_SetHigh();
int button;
int release;
button = UART5_Read();
release = UART5_Read();
if (button == 0x08)
{
RLY1_SetHigh();
RLY3_SetHigh();
}
if (release == 0x00)
{
RLY1_SetLow();
RLY3_SetLow();
}
__delay_ms(1000);
}
return (0);
}

I haven't used this MCU nor its libs, but I believe correct code should look something along the lines of this:
#include "mcc_generated_files/mcc.h"
#include <libpic30.h>
#include <stdint.h>
#define BUTTON_CODE 0x8u // use named constants instead of magic numbers
void main (void)
{
// Initialise the device
SYSTEM_Initialize();
for(;;)
{
uint8_t data;
LED4_SetLow(); // Turn on 3v3 LED
LED12v_SetHigh();
LED3_SetHigh();
LED1_SetHigh();
if(UART5_Data_Ready())
{
data = UART5_Read();
if(data == BUTTON_CODE)
{
RLY1_SetHigh();
RLY3_SetHigh();
}
else
{
RLY1_SetLow();
RLY3_SetLow();
}
}
}
}

Related

KEIL4 where the lpc2148 ADC Interrupts or IRQs wont execute

I have configured for the ADC channel AD0.1 of processor LPC 2148, with ISR. But while ADC value changes ISR is not executing. Because of this VICVectAddr contains the value of ISR function. This program is part of learning.
Please find the Code below. It is very help full if anybody has given solution
#include <lpc214x.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SBIT_RESULT 6u
#define SBIT_CLCKDIV 8u
#define SBIT_BURST 16u
#define SBIT_START 24u
#define SBIT_PDN 21u
#define SBIT_EDGE 27u
#define SBIT_DONE 31u
void ADC_Init (void);
__irq void ADC_ISR (void) ;
void main(void) {
AD0CR=0x0;
ADC_Init ();
while(1){
}
}
void ADC_Init (void)
{
PINSEL1 = 0x01000000 ; // ADC P0.28, AD0.1
AD0INTEN =0x02; //On completetion of ADC channel 1 generate interupt
VICVectAddr5 = (unsigned int)ADC_ISR; // address of the ISR
VICVectCntl5 = (1<<5) | 18;
VICIntSelect &= ~ (1<<18);
VICIntEnable = (1<<18);
AD0CR = 0X00200D02;
AD0CR |= 0x01000000;
}
// Interrupt Service Routine-ISR
__irq void ADC_ISR(void) {
static int flag=0 ;
int val;
unsigned int data;
bool readStatus;
data = AD0GDR ;
readStatus = data & 0x80000000;
if(readStatus){
val = data >>=6;
val= val & 0x3FF;
val=((val/1023.0)*3.3);
}
Delay(1000000);
AD0INTEN =0x0; //clear ADC interrupt
VICVectAddr = 0;
}
```

Embedded C (FreeRTOS)

Trying to create a reaction timer. Timer rand counts down from 10. LED is red and turns green when the user has pressed the switch. The user has to press either sw2 or sw3 when prompted has a 5 second gap to press switch. Once switch is pressed, the time is recorded and printed to putty. Game then resets and user can play again.
I'm current stuck trying to implement the LED and rand timer, could anyone help:
#include "freeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "queue.h"
#include "timers.h"
#include "event_groups.h"
#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MK64F12.h"
#include "fsl_debug_console.h"
#include "fsl_UART.h"
#include "fsl_device_registers.h"
/* TODO: insert other definitions and declarations here. */
QueueHandle_t switchQueue = NULL;
TaskHandle_t displayHandle = NULL, UARTHandle =NULL, LED_TaskHandle = NULL;
static void displayTask(void * pvParameters);
static void LED_Task(void *pvParameters);
static EventGroupHandle_t SW_Group = NULL;
#define SW2_bit 1<<0
#define SW3_bit 1<<1
/*
* #brief Application entry point.
*/
void BOARD_SW2_IRQ_HANDLER(){
static int8_t count = 0;
static uint32_t buffer[5];
BaseType_t xHigherPriorityTaskWoken;
PORT_ClearPinsInterruptFlags(BOARD_SW2_PORT, 1<<BOARD_SW2_GPIO_PIN);
buffer[count] = xTaskGetTickCountFromISR()*(1000/configTICK_RATE_HZ);
printf("\n\rSW2 pressed at %d", buffer[count]);
/* if(GPIO_PinRead(BOARD_INITPINS_SW2_GPIO,BOARD_INITPINS_SW2_PIN)== 0)
{
PRINTF("Switch pressed!.\r\n");
xEventGroupSetBits(SW_Group, SW2_bit);
while(GPIO_PinRead(BOARD_INITPINS_SW2_GPIO,BOARD_INITPINS_SW2_PIN) == 0){}
//vTaskSuspend(NULL);
if(++count==5){
count=0;
xHigherPriorityTaskWoken = pdFALSE;
//send copy of buffer to queue
xQueueSendFromISR(switchQueue, buffer, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
}*/
vTaskDelay(pdMS_TO_TICKS(100));
}
int main(void) {
/* Init board hardware. */
BOARD_InitBootPins();
BOARD_InitBootClocks();
BOARD_InitBootPeripherals();
/* Init FSL debug console. */
BOARD_InitDebugConsole();
BOARD_InitLEDsPins();
//configure sw2 interrupt
NVIC_SetPriority(BOARD_SW2_IRQ, 10);
NVIC_ClearPendingIRQ(BOARD_SW2_IRQ);
NVIC_EnableIRQ(BOARD_SW2_IRQ);
SW_Group = xEventGroupCreate();
switchQueue = xQueueCreate(5,20); //5 item queue of 20 bytes per item
if(xTaskCreate(displayTask, "Time Display", 100, NULL, 3, &displayHandle)== pdFALSE)
{
printf("UART task not created\n\r");
while(1)
;
}
if (xTaskCreate(LED_Task, "LED_Task", configMINIMAL_STACK_SIZE + 10, NULL, 4, &LED_TaskHandle) != pdPASS)
{
PRINTF("LED_Task creation failed!.\r\n");
while (1)
;
}
vTaskStartScheduler();
volatile static int i = 0;
/* Enter an infinite loop, just incrementing a counter. */
while(1){
i++;
}
return 0 ;
}
static void displayTask(void * pvParameters){
uint32_t rxBuffer[5];
printf("Starting display task\n\r");
while(1){
if(xQueueReceive(switchQueue, &rxBuffer, portMAX_DELAY) == pdTRUE){
//print data
printf("\n\n\rData Received from Queue:");
int x;
for(x=0;x<5;x++){
printf("\n\rData %d: %d",x,rxBuffer[x]);
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}
}
void LED_Task(void *pvParameters)
{
EventBits_t event_bits;
for (;;) //no conditions in the for loop, will run forever
{
event_bits = xEventGroupWaitBits(SW_Group, SW2_bit | SW3_bit, pdTRUE, pdFALSE, portMAX_DELAY);
if(event_bits & SW2_bit){
PRINTF("Event bit set, RED LED Toggled!.\r\n");
LED_RED_TOGGLE();
}
else if(event_bits & SW3_bit){
PRINTF("Event bit set, GREEN LED Toggled!.\r\n");
LED_GREEN_TOGGLE();
}
}
}

Can someone explain what does the interrupt "Trap" do in the micro controller

I am using stm8l - discovery board and I am curious about the functionality of trap in the micro controller. My program stops instead of running continously in the while loop, Is the functionality of trap interrupt that if it occurs, it does not execute (similar to reset)?
#include <iostm8l.h>
#include <stdio.h>
#include <stdint.h>
void Cus_delay(uint32_t ntime)
{
while(ntime!=0)
{
ntime--;
}
}
main()
{
CLK_DIVR = 0x00; // Set the frequency to 16Mhz
PC_DDR = 0x80; // direction output for led
PC_CR1 = 0x80; // fast push pull mode
int a = 10;
while(1)
{
Cus_delay(400000);
Cus_delay(400000);
PC_ODR ^= 0x80;
a = a/0;
}
}

Checking file exist in raspberry pi 2 using C language

I am new to C language and learning it by experimenting.
My challenge: I am trying to verify if a file "Command.txt" exist in a folder in raspberry pi and then I have to read the content of the file.
My Code:
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <wiringPi.h>
// Pin number declarations. We're using the Broadcom chip pin numbers.
const int pwmPin = 18; // PWM LED - Broadcom pin 18, P1 pin 12
const int ledPin = 23; // Regular LED - Broadcom pin 23, P1 pin 16
const int butPin = 17; // Active-low button - Broadcom pin 17, P1 pin 11
const int pwmValue = 75; // Use this to set an LED brightness
int file_exist(char *filename)
{
struct stat buffer;
return (stat(filename, &buffer) == 0);
}
int main(void)
{
// Setup stuff:
wiringPiSetupGpio(); // Initialize wiringPi -- using Broadcom pin numbers
pinMode(pwmPin, PWM_OUTPUT); // Set PWM LED as PWM output
pinMode(ledPin, OUTPUT); // Set regular LED as output
pinMode(butPin, INPUT); // Set button as INPUT
pullUpDnControl(butPin, PUD_UP); // Enable pull-up resistor on button
printf("Blinker is running! Press CTRL+C to quit.\n");
while(1)
{
FILE *command_file;
char command[255];
while(file_exist("/home/pi/FTP/command.txt"))
{
command_file = fopen("/home/pi/FTP/command.txt", "r");
fgets(command, 255, (FILE*)command_file);
printf("1: %s\n", command );
if(command == "First Light ON")
{
digitalWrite(ledPin, HIGH); //Change the raspberryPi pin state to 1
}
else if(command == "First Light OFF")
{
digitalWrite(ledPin, LOW); //Change the raspberryPi pin state to 0
}
else
{
printf("Command is not yet defined");
}
fclose(command_file);
}
while(!(file_exist("/home/pi/FTP/command.txt")))
{
printf("File does not exist\n");
delay(1000); // Wait 1s again
}
}
return 0;
}
When I run this code using the gcc command in my raspberry pi, The program is executed but I only see "File does not exist" message even if the file exist in the given folder.
Please help me with the logic on this program.

I keep receiving 0 in the output no matter what I send

I am working on a project where I have to establish a communication between my microprocessor and a Bluetooth device. I established a communication, but no matter what I send, I only get 0 when I print it. Thanks for the help !
#include <asf.h>
#include <string.h>
#include <stdio.h>
#include "usart.h"
/**
* Configure serial console.
*/
static void configure_console(void)
{
const usart_serial_options_t uart_serial_options = {
.baudrate = CONF_UART_BAUDRATE,
#ifdef CONF_UART_CHAR_LENGTH
.charlength = CONF_UART_CHAR_LENGTH,
#endif
.paritytype = CONF_UART_PARITY,
#ifdef CONF_UART_STOP_BITS
.stopbits = CONF_UART_STOP_BITS,
#endif
};
/* Configure console. */
stdio_serial_init(CONF_UART, &uart_serial_options);
}
volatile uint32_t ul_ms_ticks = 0;
static void mdelay(uint32_t ul_dly_ticks)
{
uint32_t ul_cur_ticks;
ul_cur_ticks = ul_ms_ticks;
while ((ul_ms_ticks - ul_cur_ticks) < ul_dly_ticks) {
}
}
void SysTick_Handler(void)
{
ul_ms_ticks++;
}
#define USART_SERIAL USART1
#define USART_SERIAL_ID ID_USART1 //USART1 for sam4l
#define USART_SERIAL_BAUDRATE 9600
#define USART_SERIAL_CHAR_LENGTH US_MR_CHRL_8_BIT
#define USART_SERIAL_PARITY US_MR_PAR_NO
#define USART_SERIAL_STOP_BIT US_MR_NBSTOP_1
int main(void)
{
/* Initialize the SAM system */
sysclk_init();
board_init();
/* Initialize the console uart */
configure_console();
uint32_t a= 1234;
int bit_rx = 6;
if (SysTick_Config(sysclk_get_cpu_hz() / 1000)) {
while (1) { /* Capture error */
}
}
const sam_usart_opt_t usart_console_settings = {
USART_SERIAL_BAUDRATE,
USART_SERIAL_CHAR_LENGTH,
USART_SERIAL_PARITY,
USART_SERIAL_STOP_BIT,
US_MR_CHMODE_NORMAL
};
#if SAM4L
sysclk_enable_peripheral_clock(USART_SERIAL);
#else
sysclk_enable_peripheral_clock(USART_SERIAL_ID);
#endif
usart_enable_tx(USART_SERIAL);
usart_enable_rx(USART_SERIAL);
while (1) {
printf("%d \n", bit_rx );
usart_getchar(USART_SERIAL, &a);
bit_rx = a;
printf("%d \n",bit_rx );
if (a != 0) {
ioport_set_pin_level(LED_0_PIN, LED_0_ACTIVE);
} else {
ioport_set_pin_level(LED_0_PIN, !LED_0_ACTIVE);
}
}
}
Perhaps you shouldn't call usart_getchar() until usart_is_rx_ready() returns 1.
Thanks everyone !
I tried to cast the received variable first : bit_rx = (int) a;
And then I found that I needed this to make it work :
static usart_serial_options_t usart_options = {
.baudrate = USART_SERIAL_BAUDRATE,
.charlength = USART_SERIAL_CHAR_LENGTH,
.paritytype = USART_SERIAL_PARITY,
.stopbits = USART_SERIAL_STOP_BIT
};
usart_serial_init(USART_SERIAL, &usart_options);
And I disabled the stop bit, because my bluetooth didn't have one :
#define USART_SERIAL_STOP_BIT false
Now it works like a charm. Thanks all for your help !

Resources