Jump to content

Recommended Posts

Posted

Bom dia tenho um programa em c que lê dados da porta rs232, e que traz dados de um arduino.

E neste momento o que estou a receber é isto:

Luminosidade: 450

Temperatura: 18

e isto tem um delay, e isto vai mandando sempre de novo conforme o que medir o sensor.

O que eu precisava era de tratar aquilo da seguinte forma: Ter num lado a temperatura e noutro a luminosidade, e guardar o valor de cada uma em variáveis diferentes.

Alguém me pode ajudar?

Aqui está o meu código

#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
int set_interface_attribs (int fd, int speed, int parity)
{
 struct termios tty;
 memset (&tty, 0, sizeof tty);
 if (tcgetattr (fd, &tty) != 0)
 {
		 perror("error from tcgetattr");
		 return -1;
 }
 cfsetospeed (&tty, speed);
 cfsetispeed (&tty, speed);
 tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;	 // 8-bit chars
 // disable IGNBRK for mismatched speed tests; otherwise receive break
 // as \000 chars
 tty.c_iflag &= ~IGNBRK;		 // ignore break signal
 tty.c_lflag = 0;			 // no signaling chars, no echo,
								 // no canonical processing
 tty.c_oflag = 0;			 // no remapping, no delays
 tty.c_cc[VMIN] = 0;		 // read doesn't block
 tty.c_cc[VTIME] = 5;		 // 0.5 seconds read timeout
 tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
 tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
								 // enable reading
 tty.c_cflag &= ~(PARENB | PARODD);	 // shut off parity
 tty.c_cflag |= parity;
 tty.c_cflag &= ~CSTOPB;
 tty.c_cflag &= ~CRTSCTS;
 if (tcsetattr (fd, TCSANOW, &tty) != 0)
 {
		 perror("error from tcsetattr");
		 return -1;
 }
 return 0;
}
void set_blocking (int fd, int should_block)
{
 struct termios tty;
 memset (&tty, 0, sizeof tty);
 if (tcgetattr (fd, &tty) != 0)
 {
		 perror("error from tggetattr");
		 return;
 }
 tty.c_cc[VMIN] = should_block ? 1 : 0;
 tty.c_cc[VTIME] = 5;		 // 0.5 seconds read timeout
 if (tcsetattr (fd, TCSANOW, &tty) != 0)
		 perror("error setting term attributes");
}

int main () {
char *portname = "/dev/ttyACM0";
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{

perror("Impossivel abrir a porta: ");
//error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
 return;
}
set_interface_attribs (fd, 9600, 0); // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0);			 // set no blocking
//write (fd, "hello!", 7);		 // send 7 character greeting
char c, buf [100];
int n=1, i=0;

while(1)
{
n = read (fd, &c, sizeof(char));
//printf("%c",c);
if(n>0)
{
buf[i]=c;
i++;
}
else
{
if(i==0) printf("VAzia\n");
else {
buf[i]='\0';
i=0;
printf("(%s)", buf);
} }
}
}

Peace, Love & Empathy by: Kurt Cobain

Posted

http://www.linguagemc.xpg.com.br/strings.html

manipulaçao de strings.. ve la se ajuda :pp

NAO TE ESQUEÇAS NUNCA DAS BIBLIOTECAS* (eu vi que as tens, mas nunca e demais confirmar ahah)

  • Vote 1

"Hello guys. You don't know me, but I know you. I want to play a game. Here's what happens if you lose"

"Só erra quem produz... Mas só produz quem não tem medo de errar"

irc @Login

NickServ Acesso a Number1 autorizado

Posted

É isto só que recebo:

Luminosidade: 450

Temperatura: 18

e durante o delay que não recebe nada ele escreve Vazia

e quando lê aquilo acima lê assim:

(Luminosidade: 450

Temperatura: 18

)

Peace, Love & Empathy by: Kurt Cobain

Posted

Obrigado 🙂

Só mais uma coisa, como eu não tenho o arduino em casa, tenho de testar isto de outra forma, e eu ja fiz uma especie de programa, mas dá-me uma sério de warnings, e quando faço ./a.out ele aparece isto: segmentation fault (core dumped).

Alguém sabe o que pode ser?

Aqui está o código

#include<stdio.h>
#include<string.h>

int main (){


int lum;
int temp;


 char str = "(luminosidade: 30O\ntemperatura:18\n)";

 sprintf("%s",str);
 if (sscanf(str, "Luminosidade: %d\nTemperatura: %d", &lum, &temp) != 2) {
 printf("Erro de leitura de dados\n");
} else {
 printf("Luminosidade: %d\nTemperatura: %d\n", lum, temp);

}
}

Peace, Love & Empathy by: Kurt Cobain

Posted
//char str = "(luminosidade: 30O\ntemperatura:18\n)"; //tas a declarar um char mas estas a instanciar como um array de char...
char *str = "(luminosidade: 30O\ntemperatura:18\n)";

Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender.

A beleza de um código está em decompor problemas complexos em pequenos blocos simples.

"learn how to do it manually first, then use the wizzy tool to save time."

"Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."

Posted

Sim isso estava mal, tens razão, obrigado, mas ainda da um warning, e depois a fazer ./a.out dá o mesmo erro :x

já descobri porque, tinha sprintf, e era printf, pq ja era um char

só que o programa está a dar: Erro de leitura de dados e não devia dar

Peace, Love & Empathy by: Kurt Cobain

Posted

@tu

só que o programa está a dar: Erro de leitura de dados e não devia dar

@happy

tens de dizer o que tens na variável buf (exactamente, sem tirar nem por !!), sem isso é impossível te dizer o que fazer !!

@tu

É isto só que recebo:

Luminosidade: 450

Temperatura: 18

como tens no teu programa de teste:

"(luminosidade: 30O\ntemperatura:18\n)";

como e' que estas a ler:

  if (sscanf(str, "Luminosidade: %d\nTemperatura: %d", &lum, &temp) != 2) //...
  • Vote 1

Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender.

A beleza de um código está em decompor problemas complexos em pequenos blocos simples.

"learn how to do it manually first, then use the wizzy tool to save time."

"Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."

Posted

Continua a dar erro de leitura de dados, acho que agora esta certo, mas não deve estar, o programa tem sempre razao xD

#include <stdio.h>
#include <string.h>

int main (){


int lum;
int temp;


 char *str = "(luminosidade:30O\ntemperatura:18\n)";

 printf("%s",str);
 if (sscanf(str, "(luminosidade:300\ntemperatura:18\n)", &lum, &temp) != 2) {
 printf("Erro de leitura de dados\n");
} else {
 printf("luminosidade:300\ntemperatura:18\n", lum, temp);

}
}

Peace, Love & Empathy by: Kurt Cobain

Posted (edited)
30O

o que esta' escrito: tres, zero, O maisculo.

mete assim:

char *str = "(luminosidade:300\ntemperatura:18\n)";

EDIT:

(sscanf(str, "(luminosidade:300\ntemperatura:18\n)", &lum, &temp) != 2)
isto esta' mal!! Edited by pikax

Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender.

A beleza de um código está em decompor problemas complexos em pequenos blocos simples.

"learn how to do it manually first, then use the wizzy tool to save time."

"Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."

Posted
(sscanf(str, "(luminosidade:300\ntemperatura:18\n)", &lum, &temp) != 2)

qual e' a diferenca?

(sscanf(str, "Luminosidade: %d\nTemperatura: %d", &lum, &temp) != 2)

Por muito mais que que estude só aprendo uma coisa, que ainda tenho muita coisa para aprender.

A beleza de um código está em decompor problemas complexos em pequenos blocos simples.

"learn how to do it manually first, then use the wizzy tool to save time."

"Kill the baby, don't be afraid of starting all over again. Fail soon, learn fast."

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.