collapse

* Posts Recentes

Amplificador - Rockboard HA 1 In-Ear por almamater
[Ontem às 19:13]


O que é isto ? por KammutierSpule
[26 de Março de 2024, 19:35]


Bateria - Portátil por almamater
[25 de Março de 2024, 22:14]


Emulador NES em ESP32 por dropes
[13 de Março de 2024, 21:19]


Escolher Osciloscópio por jm_araujo
[06 de Fevereiro de 2024, 23:07]


TP4056 - Dúvida por dropes
[31 de Janeiro de 2024, 14:13]


Leitura de dados por Porta Serie por jm_araujo
[22 de Janeiro de 2024, 14:00]


Distancia Cabo por jm_araujo
[08 de Janeiro de 2024, 16:30]


Meu novo robô por josecarlos
[06 de Janeiro de 2024, 16:46]


Laser Engraver - Alguém tem? por almamater
[16 de Dezembro de 2023, 14:23]

Autor Tópico: Arduino + Nunchuck + Python  (Lida 8756 vezes)

0 Membros e 1 Visitante estão a ver este tópico.

Offline xiserre

  • Mini Robot
  • *
  • Mensagens: 277
Re: Arduino + Nunchuck + Python
« Responder #15 em: 23 de Fevereiro de 2011, 11:22 »
o s e o que indica ao python o inicio da informação enviada pelo arduino.. assim que o pyhton recebe S,x,123,y,456,z,789,P, vai assumir como 123 o valor do x, 456 como y e  789 para o y. claro que podes meter dos dados de todos os botoes do nunchuck... e apenas um exemplo para o arduino comunicar com o python

Offline zordlyon

  • Mini Robot
  • *
  • Mensagens: 1.768
Re: Arduino + Nunchuck + Python
« Responder #16 em: 23 de Fevereiro de 2011, 12:16 »
Mas como imprimo isso para poder ler do lado do python?
é assim? :
Código: [Seleccione]
void print_for_python(int x, int y) {
    Serial.print(0x00, BYTE);   
    Serial.print(x, BYTE);
    Serial.print(0x01, BYTE);
    Serial.print(y, BYTE);
}

depois no python fiz assim:
Código: [Seleccione]
import serial
import struct
ser = serial.Serial('/dev/tty.usbserial-A6008muZ')
ser.baudrate = 19200
print ser.portstr
while True:
    line = ser.read(1)
    b = struct.unpack('<B', line)[0]
    if b == 0x00:
        x = ser.read(1)
        x = struct.unpack('<B', x)[0]
        print ('X:', x)
    elif b == 0x01:
        y = ser.read(1)
        y = struct.unpack('<B', y)[0]
        print ('Y:',  y)
    else:
        print('b', b)

Bem e para avisar que ja consigo ler os dados do joystick...mas está com um bug que não estou a ter ideia do que poderá ser...

Isto e o print que me da a certo momento depois de ler os dados do joystick no python...
Código: [Seleccione]
('X:', 48)
('Y:', 54)
('b', 13)
('b', 10)
('b', 49)
('b', 9)
('b', 52)
('b', 52)
('b', 52)
('b', 9)
('b', 53)
('b', 48)
('b', 48)
('b', 9)
('b', 54)
('b', 55)
('b', 54)
('b', 9)
('b', 49)
('b', 9)
('b', 49)
('b', 9)
('X:', 143)
('Y:', 34)
('b', 13)
('b', 10)
Traceback (most recent call last):
  File "Nunchuck.py", line 7, in <module>
    line = ser.read(1)
  File "/Library/Python/2.5/site-packages/serial/serialposix.py", line 456, in read
    raise SerialException('device reports readiness to read but returned no data (device disconnected?)')
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)

Basicamente chega a certo momento e falha a comunicação e o que eu penso...Mas não estou a ver do que possa ser...se alguem souber agradeço...


Cumprimentos..

« Última modificação: 23 de Fevereiro de 2011, 13:34 por zordlyon »
Cumprimentos,
André Carvalho.

Offline senso

  • Global Moderator
  • Mini Robot
  • *****
  • Mensagens: 9.733
  • Helpdesk do sitio
Re: Arduino + Nunchuck + Python
« Responder #17 em: 24 de Fevereiro de 2011, 00:16 »
Alguma coisa se passa ai então, o baudrate é o correcto, esse /dev/tty.usbserial-A6008muZ tem um nome muito estranho.
Avr fanboy

Offline zordlyon

  • Mini Robot
  • *
  • Mensagens: 1.768
Re: Arduino + Nunchuck + Python
« Responder #18 em: 24 de Fevereiro de 2011, 13:52 »
Sim, julgo que o baudrate seja o correcto, no terminal do arduino funciona perfeitamente...

Em relação a porta, eu tb achei estranho mas é a serial na qual o arduino se encontra ligado...fui ao menu do arduino e vi e era esta porta que estava activa...e como se pode ver no print ele de longe a longe manda me os valores de X e Y....Mas manda me muito mais vezes o do 'b'...

ou seja esta a receber coisas da serial que não são o 0x00 ou o 0x01...

Cumprimentos..
Cumprimentos,
André Carvalho.

Offline senso

  • Global Moderator
  • Mini Robot
  • *****
  • Mensagens: 9.733
  • Helpdesk do sitio
Re: Arduino + Nunchuck + Python
« Responder #19 em: 24 de Fevereiro de 2011, 13:55 »
E ele não manda nada sem lhe metermos isso no programa, mostra ai o código todo que tens no arduino.
Avr fanboy

Offline zordlyon

  • Mini Robot
  • *
  • Mensagens: 1.768
Re: Arduino + Nunchuck + Python
« Responder #20 em: 24 de Fevereiro de 2011, 20:39 »
Desculpa o atraso mas aqui fica o codigo que tenho no arduino...
Código: [Seleccione]

#include <Wire.h>;

int sensorPin = 0;    // seleciona o pin para o potenciometro
int sensorValue = 0;  // guarda o valor do sensor

void setup()
{
Serial.begin(19200);
nunchuck_setpowerpins();
nunchuck_init();
Serial.print("Nunchuck Estabilizado:\n");
}

void loop()
{
nunchuck_get_data();
nunchuck_print_data();
delay(50);
}

//

// Funçoes do Nunckuck

//

static uint8_t nunchuck_buf[6]; // array para guardar a data do nunchuck

// Uses port C (analog in) pins as power & ground for Nunchuck

static void nunchuck_setpowerpins()
{
#define pwrpin 3
#define gndpin 2

DDRC |= _BV(pwrpin) | _BV(gndpin);
PORTC &=~ _BV(gndpin);
PORTC |= _BV(pwrpin);
}


// initialize the I2C system, join the I2C bus,
// and tell the nunchuck we're talking to it

void nunchuck_init()
{
Wire.begin(); // join i2c bus as master
Wire.beginTransmission(0x52); // transmit to device 0x52
Wire.send(0x40); // sends memory address
Wire.send(0x00); // sends sent a zero.
Wire.endTransmission(); // stop transmitting
}


// Send a request for data to the nunchuck
// was "send_zero()"
void nunchuck_send_request()
{
Wire.beginTransmission(0x52); // transmit to device 0x52
Wire.send(0x00); // sends one byte
Wire.endTransmission(); // stop transmitting
}


// Receive data back from the nunchuck,
// returns 1 on successful read. returns 0 on failure
int nunchuck_get_data()
{
int cnt=0;
Wire.requestFrom (0x52, 6); // request data from nunchuck
while (Wire.available ()) {
// receive byte as an integer
nunchuck_buf[cnt] = nunchuk_decode_byte(Wire.receive());
cnt++;
}

nunchuck_send_request(); // send request for next data payload
// If we recieved the 6 bytes, then go print them
if (cnt >= 5) {
return 1; // success
}
return 0; //failure
}


// Print the input data we have recieved
// accel data is 10 bits long
// so we read 8 bits, then we have to add
// on the last 2 bits. That is why I
// multiply them by 2 * 2

void nunchuck_print_data()
{
static int i=0;
int joy_x_axis = nunchuck_buf[0];
int joy_y_axis = nunchuck_buf[1];
int accel_x_axis = nunchuck_buf[2]; // * 2 * 2;
int accel_y_axis = nunchuck_buf[3]; // * 2 * 2;
int accel_z_axis = nunchuck_buf[4]; // * 2 * 2;
int z_button = 0;
int c_button = 0;

// byte nunchuck_buf[5] contains bits for z and c buttons
// it also contains the least significant bits for the accelerometer data
// so we have to check each bit of byte outbuf[5]

if ((nunchuck_buf[5] >> 0) & 1)
z_button = 1;

if ((nunchuck_buf[5] >> 1) & 1)
c_button = 1;

if ((nunchuck_buf[5] >> 2) & 1)
accel_x_axis += 2;

if ((nunchuck_buf[5] >> 3) & 1)
accel_x_axis += 1;

if ((nunchuck_buf[5] >> 4) & 1)
accel_y_axis += 2;

if ((nunchuck_buf[5] >> 5) & 1)
accel_y_axis += 1;

if ((nunchuck_buf[5] >> 6) & 1)
accel_z_axis += 2;

if ((nunchuck_buf[5] >> 7) & 1)
accel_z_axis += 1;

//Imprime o numero de vezes que ja repetiu o processo
Serial.print(i,DEC);
Serial.print("\t");

//Imprime os valores do X e Y do Joystick
Serial.print("joystick:");
Serial.print(joy_x_axis,DEC);
Serial.print(",");
Serial.print(joy_y_axis, DEC);
Serial.print(" \t");

//Imprime os valores de X, Y e Z do acelerometro
Serial.print("Movimentacao:");
Serial.print(accel_x_axis, DEC);
Serial.print(",");
Serial.print(accel_y_axis, DEC);
Serial.print(",");
Serial.print(accel_z_axis, DEC);
Serial.print("\t");

//Imprime o valor dos botoes se primido ou nao
Serial.print("botoes_activos:");
Serial.print(z_button, DEC);
Serial.print(",");
Serial.print(c_button, DEC);
Serial.print("\r\n"); // newline

i++;

  if (c_button==0){//verifica se o botao C esta pressionado ou nao, caso esteja pressionado liga os 4 LED's
//  digitalWrite(pin2, HIGH);   
  delay(100);
}
 
if(joy_y_axis<115){//Verifica o eixo dos Y se estiver menor que 115 liga o LED 2 (de baixo) 
 // digitalWrite(pin2, HIGH); 
}
  else{
  //digitalWrite(pin2,LOW);
  }
 
if(joy_y_axis>140 && joy_y_axis<255){//Verifica se o Eixo dos Y esta entre 140 e 255, caso esteja liga o LED 3(de cima)   
 // digitalWrite(pin3, HIGH); 
}
  else{
 // digitalWrite(pin3,LOW);
  }
 
if(joy_x_axis>130 && joy_x_axis<255){//verifica se o eixo dos X esta entre 130 e 255, caso esteja, liga o LED 4(da direita)   
//  digitalWrite(pin4, HIGH); 
 }
  else{
 // digitalWrite(pin4,LOW);
  }
 
  if(joy_x_axis<115){//Verifica se o eixo dos X e menor que 115, caso esteja, liga o LED 5 (da esquerda)   
 // digitalWrite(pin5, HIGH); 
  }
  else{
 // digitalWrite(pin5,LOW);
  }
 
  if(z_button==0 && accel_x_axis>135 && accel_x_axis<258){//verifica atraves do acelerometro o valor do eixo dos X e acende o led correspondente
 // digitalWrite(pin4, HIGH); 
  }
 
  if(z_button==0 && accel_x_axis<115){//verifica atraves do acelerometro o valor do eixo dos X e acende o led correspondente
  //  digitalWrite(pin5, HIGH); 
  }

  if(z_button==0 && accel_y_axis<135){//verifica atraves do acelerometro o valor do eixo dos Y e acende o led correspondente
 //   digitalWrite(pin2, HIGH); 
  }
 
  if(z_button==0 && accel_y_axis>155 && accel_y_axis<258){//verifica atraves do acelerometro o valor do eixo dos Y e acende o led correspondente
//  digitalWrite(pin3, HIGH); 
  }
   
}


// Encode data to format that most wiimote drivers except
// only needed if you use one of the regular wiimote drivers
char nunchuk_decode_byte (char x)
{
x = (x ^ 0x17) + 0x17;
return x;
}


// retorna o Zbutton : 1=pressionado, 0=nao pressionado
int nunchuck_zbutton()
{
 return((nunchuck_buf[5] >> 0) & 1)? 0: 1; //voodoo
}

// retorna o Cbutton: 1=pressionado, 0=nao pressionado
int nunchuck_cbutton()
{
return ((nunchuck_buf[5] >> 1) & 1) ? 0 : 1; // voodoo
}

// retorna o valor do eixo dos X do joystick
int nunchuck_joyx()
{
return nunchuck_buf[0];
}

// Retorna o valor do eixo dos Y do Joystick
int nunchuck_joyy()
{
return nunchuck_buf[1];
}

// Retorna o valor do eixo do X do acelerometro
int nunchuck_accelx()
{
return nunchuck_buf[2]; // FIXME: this leaves out 2-bits of the data
}


// Retorna o valor do eixo dos Y do acelerometro
int nunchuck_accely()
{
return nunchuck_buf[3]; // FIXME: this leaves out 2-bits of the data
}


// Retorna o valor do eixo do Z do acelerometro
int nunchuck_accelz()
{
return nunchuck_buf[4]; // FIXME: this leaves out 2-bits of the data
}

Cumprimentos..
Cumprimentos,
André Carvalho.

Offline senso

  • Global Moderator
  • Mini Robot
  • *****
  • Mensagens: 9.733
  • Helpdesk do sitio
Re: Arduino + Nunchuck + Python
« Responder #21 em: 24 de Fevereiro de 2011, 22:10 »
Mas que misturada de código, quem é que fez isso?
Tem ai a mesma coisa igual 3 vezes, a tua funçao para imprimir nao está em lado nenhum e tens um monte de prints para ai perdidos, dai o python se engasgar, código indentado tambem nao há, eu nem consigo ler isso, já lhe vou dar uma limpeza..
Avr fanboy

Offline senso

  • Global Moderator
  • Mini Robot
  • *****
  • Mensagens: 9.733
  • Helpdesk do sitio
Re: Arduino + Nunchuck + Python
« Responder #22 em: 24 de Fevereiro de 2011, 22:36 »
Código: [Seleccione]
#include <Wire.h>;

#define pwrpin 3
#define gndpin 2

int sensorPin = 0;    // seleciona o pin para o potenciometro
int sensorValue = 0;  // guarda o valor do sensor

void setup()
{
Serial.begin(19200);
nunchuck_setpowerpins();
nunchuck_init();
}

void loop()
{
nunchuck_get_data();
nunchuck_print_data();
delay(50);
}

//

// Funçoes do Nunckuck

//

static uint8_t nunchuck_buf[6]; // array para guardar a data do nunchuck

// Uses port C (analog in) pins as power & ground for Nunchuck

static void nunchuck_setpowerpins()
{

DDRC |= _BV(pwrpin) | _BV(gndpin);
PORTC &=~ _BV(gndpin);
PORTC |= _BV(pwrpin);
}


// initialize the I2C system, join the I2C bus,
// and tell the nunchuck we're talking to it

void nunchuck_init()
{
Wire.begin(); // join i2c bus as master
Wire.beginTransmission(0x52); // transmit to device 0x52
Wire.send(0x40); // sends memory address
Wire.send(0x00); // sends sent a zero.
Wire.endTransmission(); // stop transmitting
}


// Send a request for data to the nunchuck
// was "send_zero()"
void nunchuck_send_request()
{
Wire.beginTransmission(0x52); // transmit to device 0x52
Wire.send(0x00); // sends one byte
Wire.endTransmission(); // stop transmitting
}


// Receive data back from the nunchuck,
// returns 1 on successful read. returns 0 on failure
int nunchuck_get_data()
{
int cnt=0;
Wire.requestFrom (0x52, 6); // request data from nunchuck
while (Wire.available ()) {
// receive byte as an integer
nunchuck_buf[cnt] = nunchuk_decode_byte(Wire.receive());
cnt++;
}

nunchuck_send_request(); // send request for next data payload
// If we recieved the 6 bytes, then go print them
if (cnt >= 5) {
return 1; // success
}
return 0; //failure
}


// Print the input data we have recieved
// accel data is 10 bits long
// so we read 8 bits, then we have to add
// on the last 2 bits. That is why I
// multiply them by 2 * 2

void nunchuck_print_data()
{
static int i=0;
int joy_x_axis = nunchuck_buf[0];
int joy_y_axis = nunchuck_buf[1];
int accel_x_axis = nunchuck_buf[2]; // * 2 * 2;
int accel_y_axis = nunchuck_buf[3]; // * 2 * 2;
int accel_z_axis = nunchuck_buf[4]; // * 2 * 2;
int z_button = 0;
int c_button = 0;

// byte nunchuck_buf[5] contains bits for z and c buttons
// it also contains the least significant bits for the accelerometer data
// so we have to check each bit of byte outbuf[5]

if ((nunchuck_buf[5] >> 0) & 1)
z_button = 1;

if ((nunchuck_buf[5] >> 1) & 1)
c_button = 1;

if ((nunchuck_buf[5] >> 2) & 1)
accel_x_axis += 2;

if ((nunchuck_buf[5] >> 3) & 1)
accel_x_axis += 1;

if ((nunchuck_buf[5] >> 4) & 1)
accel_y_axis += 2;

if ((nunchuck_buf[5] >> 5) & 1)
accel_y_axis += 1;

if ((nunchuck_buf[5] >> 6) & 1)
accel_z_axis += 2;

if ((nunchuck_buf[5] >> 7) & 1)
accel_z_axis += 1;

//Imprime os valores do X e Y do Joystick
Serial.print(0x00);
Serial.print(joy_x_axis,DEC);
Serial.print(0x01);
Serial.print(joy_y_axis, DEC);

}


// Encode data to format that most wiimote drivers except
// only needed if you use one of the regular wiimote drivers
char nunchuk_decode_byte (char x)
{
x = (x ^ 0x17) + 0x17;
return x;
}


Agora deve funcionar bem, nem sei como é que esse código alguma vez apanhava x ou y se não estava la nenhum print isolado só com x ou só com y.
Avr fanboy

Offline zordlyon

  • Mini Robot
  • *
  • Mensagens: 1.768
Re: Arduino + Nunchuck + Python
« Responder #23 em: 24 de Fevereiro de 2011, 23:36 »
Eu agora a reparar, e eu é que me enganei no codigo...Lol. :o..

mas de qualquer maneira o anterior estava a funcionar so para o arduino, na altura arranjei-o num forum qualquer...

Uma coisa que agora a olhar para o teu e foi uma estupidez absurda minha, e agradeço te teres te dado ao trabalho de fazeres o que fizes te, é que eu tinha a fazer o print para a consola do arduino, e tinha a fazer o print para o python.... Conclusão ele misturava os prints e obvio..
A identação eu só copiei e colei aqui e não ficou com a identação ;)

Infelizmente, por burrice minha, tambem moro em Castelo de Paiva, mas estudo no Porto, e deixei o arduino e o comando no Porto, logo so poderei testar o teu codigo no domingo...

Mas agradeço te na mesma Senso...e provavelmente funcionará porque imprime somente para o python claro...
Enfim quem sabe sabe...

Obrigadão, eu domingo já coloco ca alguma coisa  ;)

Cumprimentos..
Cumprimentos,
André Carvalho.

Offline zordlyon

  • Mini Robot
  • *
  • Mensagens: 1.768
Re: Arduino + Nunchuck + Python
« Responder #24 em: 24 de Fevereiro de 2011, 23:43 »
Tenho uma pequena dúvida embora ainda não tenha testado no comando...

Os exemplos que vi usavam os prints no segundo argumento com "Byte" e o senso colocou com "Dec", supostamente será decimal...
Mas o porque disto?
Código: [Seleccione]
//Imprime os valores do X e Y do Joystick
Serial.print(0x00);
Serial.print(joy_x_axis,DEC);
Serial.print(0x01);
Serial.print(joy_y_axis, DEC);

Cumprimentos..
Cumprimentos,
André Carvalho.

Offline senso

  • Global Moderator
  • Mini Robot
  • *****
  • Mensagens: 9.733
  • Helpdesk do sitio
Re: Arduino + Nunchuck + Python
« Responder #25 em: 25 de Fevereiro de 2011, 13:28 »
Eu usei os prints que ja la estavam, em DEC acho que ele converte para ASCII, nao sei bem, que nao uso o IDE do Arduino.
Avr fanboy

Offline zordlyon

  • Mini Robot
  • *
  • Mensagens: 1.768
Re: Arduino + Nunchuck + Python
« Responder #26 em: 25 de Fevereiro de 2011, 16:00 »
Hum ok ok..
Obrigado mais uma vez..
 ;)
Cumprimentos..
Cumprimentos,
André Carvalho.

Offline zordlyon

  • Mini Robot
  • *
  • Mensagens: 1.768
Re: Arduino + Nunchuck + Python
« Responder #27 em: 27 de Fevereiro de 2011, 22:31 »
Caro senso queria lhe agradecer...O codigo funcionou, so tive que fazer uma pequena alteração no print...

O print necessita ficar assim...
Código: [Seleccione]
Serial.print(0x00,BYTE);
Serial.print(joy_x_axis,BYTE);
Serial.print(0x01,BYTE);
Serial.print(joy_y_axis, BYTE);

Para quem estiver interessado, aqui fica o codigo em Python e o do arduino...
Para adicionar depois os valores do acelerometro e dos botoes é a mesma coisa, basta adicionar + if's no python e + prints no codigo do arduino...

Cumprimentos,
André Carvalho.