I´m trying to make a simple caltulator using PIC18F46K22 microcontroler and UART. However it works only for adding two numbers, even though the strstr cor comparison and finding the “+” / “-“.
Can someone please spot the problem?
Code:
`#include <xc.h> //-- for XC8 compiler
#include <stdio.h> // for printf
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define _XTAL_FREQ 32E6
typedef struct
{
char data[32];
char full;
int index;
} mailbox;
void main(void)
{
while(1)
{
if(g_mail.full)
{
while(!TX1IF);
char *ptr;
int num1, num2;
char operator;
// Determine the operator using strstr
if (strstr(g_mail.data, "+")) {
operator = '+';
} else if (strstr(g_mail.data, "-")) {
operator = '-';
}
int result = 0;
// Perform the calculation
if (operator == '+') {
result = num1 + num2;
} else if (operator == '-') {
result = num1 - num2;
}
// Prepare the result string
char resultStr[16];
sprintf(resultStr, "%d", result); // Convert result to a string
// Send each character in the result string
for (int i = 0; i < strlen(resultStr); i++) {
while (!TXSTAbits.TRMT); // Wait for TX buffer to be ready
TXREG = resultStr[i]; // Send character
}
g_mail.full = 0; // Reset mailbox flag
memset(g_mail.data, 0, sizeof(g_mail.data)); // Clear the data array
}
}
}
Thanks everyone for your help and tips!
I have tried changing syntax and few different approches but nothing works. Chat also cannot find a problem and writes the same answe a little bit differently.
New contributor
Lucie Oborná is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.