Ir para conteúdo
Fórum Script Brasil
  • 0

Problema com buffer em C


Cleber Marques

Pergunta

Espero conseguir alguma ajuda aqui. Eu estou programando para Beaglebone Black usando sensores I2C através do Eclipse IDE para C/C ++ Developers, Versão: Luna Service Release 2 (4.4.2).
Meu problema é com o desenvolvimento do código para o I2C, especialmente entre as funções initializingACC e readingDATA do meu código. Acho que o problema é com a variável buf, acredito não estar usando o buffer corretamente.
Eu desenvolvi o código abaixo, onde o comando read (na função readingDATA) só funciona se eu inserir duas linhas acima o último comando write (na função initializingACC) que fazem o último comando write parar de funcionar.
O objetivo do último write é escrever o valor 0x08 no registrador 0x2d do dispositivo I2C 0x53. É por isso que este write para de funcionar quando eu insiro as duas linhas (buf [0] = ACC_OUT_LSB_X; e buf [1 ] = NULL;). Por outro lado, estas linhas fazem com o que o comando read (na função readingDATA) funcione corretamente.
Eu tenho realizado os testes utilizando os comandos abaixo no terminal do Linux:
sudo i2cset -y 1 0x53 0x31 0x01 (Equivalente de primeira gravação para a função initializingACC)
sudo i2cset -y 1 0x53 0x08 0x2d (Equivalente de segunda gravação para a função initializingACC)
sudo i2cget -y 1 0x53 0x32 (Equivalente de ler para a função readingDATA)

Eis o meu código:

#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


#define ACC_ADDRESS 0x53
#define ACC_READ_ADDR  0XA7
#define ACC_PWRCTRL_ADDR  0x2D
#define ACC_MEASURE_MODE  0x08
#define ACC_DATA_FORMAT  0x31
#define ACC_OUT_LSB_X 0x32
#define ACC_OUT_MSB_X 0x33
#define ACC_OUT_LSB_Y 0x34
#define ACC_OUT_MSB_Y 0x35
#define ACC_OUT_LSB_Z 0x36
#define ACC_OUT_MSB_Z 0x37


int i2cbus = 1;
int file;
char absolute_path[20];
char buf[10];


void settingIOCTL(){


    printf("Function to set the ioctl up\n");


    snprintf(absolute_path, 19, "/dev/i2c-%d", i2cbus);
    file = open(absolute_path, O_RDWR);
    if (file < 0) {
        // ERROR HANDLING; you can check errno to see what went wrong
        exit(1);
    }
    if (ioctl(file, I2C_SLAVE, ACC_ADDRESS) < 0) {
        // ERROR HANDLING; you can check errno to see what went wrong
        exit(1);
    }
    printf("Function to set the ioctl up processed\n");
}
void initializingACC(){


    printf("function to initialize\n");


    // Using I2C Write
    buf[0] = ACC_DATA_FORMAT;
    buf[1] = 0x01;
    if (write(file, buf, 2) != 2) { // Equivalent of sudo i2cset -y 1 0x53 0x31 0x01
        // ERROR HANDLING: i2c transaction failed
        }
    buf[0] = ACC_PWRCTRL_ADDR;
    buf[1] = ACC_MEASURE_MODE;


    /*These 2 lines below predictably make this function stop working (next writing)
      otherside, them make the next function (readingDATA/read) work properly*/
    buf[0] = ACC_OUT_LSB_X;
    buf[1] = NULL;


    if (write(file, buf, 2) != 2) { // Equivalent of sudo i2cset -y 1 0x53 0x2d 0x08
        // ERROR HANDLING: i2c transaction failed
        }
    printf("Function to initialize processed\n");
}


void readingDATA(int register_address){


    printf("Function to read\n");


    buf[0] = register_address; //I thought this line would be above the reading line but it makes the reading stop working
    // Using I2C Read
    if (read(file, buf, 1) != 1) { // Equivalent of sudo i2cset -y 1 0x53 0x2d 0x08
        // ERROR HANDLING: i2c transaction failed
     } else {
             // buf[0] contains the read byte
             printf("read byte: %x\n",buf[0]);
     }
  printf("Function to read processed\n");
}


int main(void){


      settingIOCTL();
      initializingACC();
      readingDATA(ACC_OUT_LSB_X);


      return 0;
}
Link para o comentário
Compartilhar em outros sites

1 resposta a esta questão

Posts Recomendados

  • 0

buf[0] = ACC_PWRCTRL_ADDR;

buf[1] = ACC_MEASURE_MODE;

/*These 2 lines below predictably make this function stop working (next writing)

otherside, them make the next function (readingDATA/read) work properly*/

buf[0] = ACC_OUT_LSB_X;

buf[1] = NULL;

if (write(file, buf, 2) != 2) { // Equivalent of sudo i2cset -y 1 0x53 0x2d 0x08

// ERROR HANDLING: i2c transaction failed

}

Não entendi isso aí. você está setando buf com 2 bytes ACC_PWRCTRL_ADDR(0x2D) e ACC_MEASURE_MODE(0x08) e antes de usá-los você está alterando o valor do buf pra ACC_OUT_LSB_X(0x32) e NULL(0x00). Quando o programa chama a função write, ele está na verdade enviando 0x32 0x00.

Outra coisa.

buf[0] = ACC_PWRCTRL_ADDR; //0x2d

buf[1] = ACC_MEASURE_MODE; //0x08

sudo i2cset -y 1 0x53 0x08 0x2d (Equivalente de segunda gravação para a função initializingACC)

Os bytes foram invertidos de propósito?

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...