Autor Tema: SRF02 + I2CUSB Programar para llevar los datos a PHP  (Leído 1415 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado acarrillo16

  • PIC10
  • *
  • Mensajes: 3
SRF02 + I2CUSB Programar para llevar los datos a PHP
« en: 05 de Agosto de 2017, 15:09:52 »
Hola, Buenas tardes, soy nuevo en esto, tengo un Sensor ultrasonico SRF02 y un convertidor I2C a USB, dicho sensor lo tengo conectado por USB al Portail con Linux (Ubuntu). La Idea es que de alguna manera pueda leer la información de la distancia del sensor y se pueda mostrar en un archivo en PHP tipo web, donde diga algo como "su distancia es: XXcm", tengo un codigo php con php_serial.class.php, al principio daba error ya que los permisos del achivo /dev/ttyUSB0 no tenia permisos, ahora no da errores, pero simplemente no se generar las solicitudes de medida. simplemente en blanco. Si alguien pudiera ayudarme para hacerlo de esta manera o de alguna manera que consideren que sea mas efectiva les agradezco.

Desde ya Muchas Gracias!

Desconectado tsk

  • PIC18
  • ****
  • Mensajes: 257
Re:SRF02 + I2CUSB Programar para llevar los datos a PHP
« Respuesta #1 en: 05 de Agosto de 2017, 16:24:00 »
Lo que más te conviene aquí es usar python con algún web framework como bottle, flask, tornado entre otros más.

Por ejemplo algo sencillo en bottle sería

Código: Python
  1. import serial
  2. import time
  3. from bottle import run, route
  4. #Init the serial port
  5.  
  6. ser = serial.Serial("/dev/ttyUSB0",9600,timeout=1)
  7. time.sleep(2)
  8. @route("/srf02")
  9. def get_srf02():
  10.     ser.write('a')  #Comando para obtener lectura, no conozco como funciona tu dispositivo
  11.     read_val = ser.readline() # leer hasta obtener \n,aquí puede ser por cantidad de bytes a leer
  12.     return '{"id":23,"value":%s}'%read_val #Aquí esto retornando en formato json pero puede ser una página web.
  13.  
  14. run(host="localhost",port=8080)
  15. #close the serial port on exit
  16. ser.close()

Con flask
Código: Python
  1. import serial
  2. import time
  3. from flask import Flask
  4. #Init the serial port
  5.  
  6. ser = serial.Serial("/dev/ttyUSB0",9600,timeout=1)
  7. time.sleep(2)
  8.  
  9. app = Flask(__name__)
  10. @app.route('/srf02'):
  11.  ser.write('a')  #Comando para obtener lectura, no conozco como funciona tu dispositivo
  12.     read_val = ser.readline() # leer hasta obtener \n, aquí puede ser por cantidad de bytes a leer
  13.     return '{"id":23,"value":%s}'%read_val #Aquí esto retornando en formato json pero puede ser una página web.
  14.  
  15. app.run(host="0.0.0.0",debug=True)
  16. #close the serial port on exit
  17. ser.close()

Es cuestión de que adaptes el código a tus necesidades.

Desconectado acarrillo16

  • PIC10
  • *
  • Mensajes: 3
Re:SRF02 + I2CUSB Programar para llevar los datos a PHP
« Respuesta #2 en: 09 de Agosto de 2017, 00:00:12 »
Gracias por la respuesta, estuve intentando con esos códigos, sin embargo no logré mucho. Conseguí otros códigos python para hacerlo, pero sigo teniendo problemas, intento pasarle los comando para que genere las medidas, pero no regena resultados, ni en windows ni en linux. Si pudieran ayudarme un poco más, estaré muy agradecido.

Adjunto el Código que estoy trabajando:

Código: Python
  1. import serial
  2. import time
  3. import os
  4.  
  5. #set up the serial connection
  6. ser = serial.Serial(
  7.     port='COM3',
  8.     baudrate=9600,
  9.     parity=serial.PARITY_NONE,
  10.     stopbits=serial.STOPBITS_ONE,
  11.     bytesize=serial.EIGHTBITS,
  12.     timeout=1
  13. )
  14.  
  15. #start the main loop
  16. while True:
  17.     #basic error handling, occasionally the device fails to respond. This keeps the
  18.     #loop running.
  19.     try:
  20.         #send the 5 byte command to start a ranging ping.
  21.         #The 1st byte 0x55 is the start command for the USB-I2C module. 2nd byte 0xE0
  22.         #is the address of the SRF02 on the I2C bus. 3rd byte 0x00 is the address
  23.         #register of the SRF02 that we are writing the command to. 4th byte 0x01 is
  24.         #the number of bytes in the command we are about to send. 5th byte 0x51 is
  25.         #the command to tell the SRF02 to initiate a range in cm
  26.         if ser.is_open:
  27.             ser.close()
  28.         ser.open()
  29.        
  30.         #print(ser.write(0x55))
  31.         #ser.write(0x55+0xE0+0x00+0x01+0x51)
  32.         #ser.write(0)
  33.         ser.write(0xE0)
  34.         ser.write(0x00)
  35.         ser.write(0x01)
  36.         ser.write(0x51)
  37.         #ser.flush()
  38.         #wait for the range to finish
  39.         time.sleep(.1)
  40.        
  41.         #this 4byte command tells the SRF02 to send the result to the I2C bus for
  42.         #reading. The first byte 0x55 is the start command for the USB-I2C module.
  43.         #2nd byte 0xE1 is the SRF02s address plus one, this tells it that we are
  44.         #reading. 3rd byte 0x02 is
  45.         #the register thats holds the data we want to start reading from. 4th byte
  46.         #0x02 is the number of bytes to read. In this case we want 2bytes, the range
  47.         #high byte and the range low byte.
  48.         #ser.write(chr(0x55)+chr(0xE1)+chr(0x02)+chr(0x02))
  49.         print(ser.write(96))
  50.         ser.write(0xE1)
  51.         ser.write(0x02)
  52.         ser.write(0x02)
  53.        
  54.         #read 3 bytes. Why 3 when we only requested 2? The USB-I2C device returns a
  55.         #byte first to tell of success or fail
  56.         s = ser.read(96)
  57.         print(s)
  58.         #clear the screen so we are not repeating up the screen
  59.         #os.system('clear')
  60.        
  61.         #first check for a successful read response, first byte will be 1 if successful.
  62.         #Then print the second byte which is the range high followed byte the 3rd which
  63.         #is range low. Combine to get the actual range, we do this because each register
  64.         #is one byte of 8 bits, this only allows numbers to go to 255, this would give
  65.         #255cm on the low byte. But suppose we are measuring a range of 280cm, the low
  66.         #register maxes out at 255. We put a 1 in the high byte register to represent
  67.         #256 and the low byte starts again and counts to 24. So we can simply combine
  68.         #the high and the low bye h*256+l to get the range so in the example 1*256+24=280
  69.         if isinstance(s,list):            
  70.             if ord(s[0]) == 1:
  71.                 print ('high')
  72.                # print (ord(s[2]), 'low')
  73.                # print (ord(s[1]) * 256 + ord(s[2]), 'range in cm')
  74.             else:
  75.                 print ('error reading device')
  76.         else:
  77.             print("no es array")
  78.         #slow the loop down a bit to give our eyes a chance to read the response
  79.         time.sleep(1)
  80.    
  81.     #handle errors, the second "except" here takes all errors in it's stride and allows
  82.     #the loop to continue. I did this because every now and again the USB-I2C device
  83.     #fails to respond and breaks the loop. By having a blanket error handling rule you
  84.     #could no longer interrupt the loop with a keyboard interrupt so I had to add an
  85.     #"except KeyboardInterrupt" rule to allow this to break the loop.  
  86.     except KeyboardInterrupt:
  87.         print ('Exiting...Keyboard interrupt')
  88.         break
  89.    
  90.     except Exception as e:
  91.         print ('error: ', e)

Les dejo el link de los comandos del sensor: http://www.superrobotica.com/s320122.htm

Les dejo el link de un ejecutable que hace trabajar el sensor: http://www.robot-electronics.co.uk/files/USB_I2C_SRF02.exe

De antemano muchas Gracias!

Desconectado tsk

  • PIC18
  • ****
  • Mensajes: 257
Re:SRF02 + I2CUSB Programar para llevar los datos a PHP
« Respuesta #3 en: 09 de Agosto de 2017, 00:45:27 »
Si lees el código, te dice que es lo que debes de hacer, el primer byte es 0x55 que es el inicio para el módulo de USB-I2C el segundo byte es la dirección del módulo (0xE0) el tercer byte la dirección donde se va a escribir el comando (0x00) el 4 es el número de bytes a escribir y el último comando que en este caso es el inicio de conversión (0x51 para cm).

Después para leer el resultado inicias con el 0x55 (USB-I2C) dirección del módulo (0xE1 – Módo lectura) dirección a leer (0x02) números de bytes a leer (0x02)

Para leer el resultado es con

Código: Python
  1. s = ser.read(3)

no con
Código: Python
  1. s = ser.read(96)
Ya que sólo recibes 3 bytes.

De igual forma no necesitas enviar el comando 96. Sigue el código tal y como te indica el original.

http://www.strand.id.au/Mikes-stuff/usingthesrf02ultrasonicrangerwithpythonpyserial

Desconectado acarrillo16

  • PIC10
  • *
  • Mensajes: 3
Re:SRF02 + I2CUSB Programar para llevar los datos a PHP
« Respuesta #4 en: 09 de Agosto de 2017, 01:58:15 »
Si, Literal he utilizado esos códigos, tal como están en el ejemplo, sin embargo la respuesta siempre es vacío  :oops:  :8}

Código: Python
  1. import serial
  2. import time
  3. import os
  4.  
  5. ser = serial.Serial(
  6.     port='COM3',
  7.     baudrate=9600,
  8.     parity=serial.PARITY_NONE,
  9.     stopbits=serial.STOPBITS_TWO,
  10.     bytesize=serial.EIGHTBITS,
  11.     timeout=1
  12. )
  13.  
  14.  
  15. while True:
  16.     try:
  17.         if ser.is_open:
  18.             ser.close()
  19.         ser.open()
  20.                
  21.         frame = bytearray()
  22.         frame.append(0x55)
  23.         frame.append(0xE0)
  24.         frame.append(0x00)
  25.         frame.append(0x01)
  26.         frame.append(0x51)
  27.        
  28.         ser.write(frame)
  29.        
  30.         time.sleep(.1)
  31.        
  32.         frame2 = bytearray()
  33.         frame2.append(0x55)
  34.         frame2.append(0xE1)
  35.         frame2.append(0x02)
  36.         frame2.append(0x02)
  37.        
  38.         ser.write(frame2)
  39.  
  40.         s = ser.read(3)
  41.         print(s)
  42.  
  43.         if isinstance(s,list):            
  44.             if ord(s[0]) == 1:
  45.                 print ('high')
  46.                # print (ord(s[2]), 'low')
  47.                # print (ord(s[1]) * 256 + ord(s[2]), 'range in cm')
  48.             else:
  49.                 print ('error reading device')
  50.         else:
  51.             print("no es array")
  52.  
  53.         time.sleep(1)
  54.  
  55.     except KeyboardInterrupt:
  56.         print ('Exiting...Keyboard interrupt')
  57.         break
  58.    
  59.     except Exception as e:
  60.         print ('error: ', e)

la respuesta siempre de la variable "s" siempre es: b''

Desconectado tsk

  • PIC18
  • ****
  • Mensajes: 257
Re:SRF02 + I2CUSB Programar para llevar los datos a PHP
« Respuesta #5 en: 09 de Agosto de 2017, 10:35:21 »
de acuerdo al código fuente del programa con el que funciona el SR08 (https://www.robot-electronics.co.uk/files/usb_i2c_srf08.zip)

el baudrate es de 19200 y no de 9600

Código: C
  1. dcb.BaudRate = CBR_19200;