jueves, 21 de agosto de 2014

GPIO CubieBoard with Java

Hi all, this is the first part in which show you a simple code in Java that enables position control system development CubieBoard, these examples are run using Cubian (http://cubian.org/). I have tried all methods for control and configuration of the pins, be very similar to the Arduino. Subsequent deliveries shall see, pin reading and servos managing.
this is the project in eclipse.

Regards

lunes, 27 de agosto de 2012

Controlling Robot with Cell Phone, Second Part


In this part I'm going to explain how the robot works with distance sensor. The arduino program is the same to the first part, but now I add one menu, this menu allows select the work function of the robot.
Now in this moment we have two function, the first is Bluetooth control and the second is semi autonomous robot. I said semi, because the robot only do evade object or obstacle.
For this part we´ve needed a distance sensor.In my case I use three sensor Sharp with a max distance of 150 cm, using the ADC convert to acquire the signal.

When I have the signal the sensor acquired, we need to calculate the distance, to do this I implemented the next code:
 int Cal_Dis_0(){
Dis_0 = analogRead(3);
volts = (float)Dis_0 * VOLTS_PER_UNIT; // ("proxSens" is from analog read)
inches = 23.897 * pow(volts,-1.1907); //calc inches using "power" trend line from Excel
cm = 60.495 * pow(volts,-1.1904); // same in cm
if (volts < .2) inches = -1.0;
return cm;
}
The result of this operation, is sending to the mobile. when I want to send this data is necessary a encoding. We need a beginning byte and a end byte, as show below.
 void Send(){
Serial2.print("@");
Serial2.print(cm_0);
Serial2.print(",");
Serial2.print(cm_1);
Serial2.print(",");
Serial2.print(cm_2);
Serial2.print(",");
Serial2.print('&');
Serial2.print(':');
//delay(200);
}
 The second step is to capture and decode data. The data is store in a list and then decrypted. Then we will have to make the implementation of actions. This is shown below:
class RobotAction:
def Robot(self, dis0,dis1,dis2):
Distancia = 20
if(dis0<Dist):# and dis1<Dist and dis2<Dist):
# backward
app.SendArduino('$')
app.SendArduino(0)
app.SendArduino(',')
app.SendArduino(17)
app.SendArduino('&')
elif(dis0>Dist and dis1>Dist and dis2>Dist):
# forward
app.SendArduino('$')
app.SendArduino(0)
app.SendArduino(',')
app.SendArduino(16)
app.SendArduino('&')
elif(dis1<Dist):
# right
app.SendArduino('$')
app.SendArduino(0)
app.SendArduino(',')
app.SendArduino(15)
app.SendArduino('&')
elif(dis2<Dist):
# left
app.SendArduino('$')
app.SendArduino(0)
app.SendArduino(',')
app.SendArduino(14)
app.SendArduino('&')
else:
# stop
app.SendArduino('$')
app.SendArduino(0)
app.SendArduino(',')
app.SendArduino(167)
app.SendArduino('&')
That´s it!!!
Material:
In the third part I will show how to make the robot move with the accelerometer of the phone.
 thanks



martes, 21 de agosto de 2012

Controlling Robot with Cell Phone



Currently in progress the mobile telephony grows exponentially to the point that we can have Mhz to Ghz processors in our cellphones, this begs the question, if I have this in my hands can I do more with my phone and not just to call, be on the Internet or play?
But how we can attach high tech or middle tech phone to a robot? well to do this you need to use a device that for me revolutionized the world of electronics or microcontrollers programmed and that is Arduino.
Arduino is an open development platform more versatile of the world there is nothing else to compare with it, because it opened the doors of electronics programmed everyone, so today we see a lot of people without to do with the electronics that make interesting applications, that’s not my case, I do go through stages of electronics and programming with PIC, Freescale and finally Arduino and stayed with Arduino.

What is about the Project?


1 4WD platform

1 lipo battery

2 buck converter (* not strictly necessary)

1 Arduino ( I use Mega)

1 Bluetooth Module

1 GPS (not used in part one)

1 Compass (not used in part one)

1 Mobile Nokia Symbian S60

We now turn to the programming of the phone, I have obtained information on this page:
This is the code for using blutooth communication between Nokia and the robot:
Thanks

Material

2 H Bridge (in my case using two H bridge Pololu)

The first thing we must do is make the reception of data by the Arduino. we have to connect our computer to Arduino and program the serial communication. we must bear in mind that we are going to send several data through the serial port so it is important that at the time of making the communication we have to have a start and an end character.

Keep in mind that in my case when using an arduino mega, I have several serial communication ports so you can use the library "NewSoftSerial" but the baud can not be very high as you run the risk of information loss. This project works at a speed of 9600 baud

Arduino code:

void ReadData(){
  if (Serial2.available()){
    digitalWrite(13,LOW);
    Dato = Serial2.read();

    if(Dato==’$’){
      while(1){
        if(Serial2.available()){
          Dato = Serial2.read();

          Data_Array[conta] = Dato;
          if(Dato==’&’){
            int A = Data_Array[0]-48;
            int B = Data_Array[1]-48;
            int C = Data_Array[2]-48;
            int D = Data_Array[3]-48;

            if(C == -10){
              Action = A*10 + B*1;
            }
            else if(D == -100){
              Action = A*100 + B*10 + C*1;
            }
            else{
              Action = 0;
            }
            Serial.print(A);
            Serial.print(B);
            Serial.print©;
            Serial.print(D);
Serial.print(“Action: 
            “);
            Serial.println(Action);

            Data_Array[0] = 0;
            Data_Array[1] = 0;
            Data_Array[2] = 0;
            Data_Array[3] = 0;
            Data_Array[4] = 0;
            Data_Array[5] = 0;
            Data_Array[6] = 0;
            conta=0;
            break;
          }
          conta++;
        }
      }
    }
  }
}

The array size depends on the amount of data you are sending, in my case the start character is "$" and the end character is"&". With the stored data in the array we only need to subtract 48, this is done becouse the mobile or the serial port of your computer sends data in ASCII, and mobile sends one character at a time. For example if we have the number "17", the mobile phone or the computer sends "49 = 1 and 55 = 7" and now if we subtract "48" have to "49-48 = 1 and 55-48 = 7" but these are two separate issues but we sent the seventeen for this reason we have to multiply units by 1 and tens by 10. If we have hundreds as one number it has to be multiplied by 100 and so on.
Right now we do this "(1 * 10) + (7 * 1) = 17. This is shown below:

if(Dato==’&’){
int A = Data_Array[0]-48;
int B = Data_Array[1]-48;
int C = Data_Array[2]-48;
int D = Data_Array[3]-48;

if(C == -10){
Action = A*10 + B*1;
}
else if(D == -10){
Action = A*100 + B*10 + C*1;
}
else{
Action = 0;
}

Why I ask ift "C == -10", this is because inside I'm sending data in the time that I want my robot to stop, I send a 3-digit number is the number 167. As the size of the array varies if I send two-digit number or three by the time it reaches the end of data character "&", this value is stored in the 4-position of the array and subtract "48" the result is -10 and this is because the "& = 38" with this result if the value sent is two or three digit numbers.

Once the data is stored in a array related to variable called "Acction" we can start the motor control, in this part I'll explain just how it has to be because the reader may have another H bridge

if(Acction==16){
Adelante
}
else if(Acction==17){
Atras
}
else if(Acction==14){
Izquierda
}
else if(Acction==15){
Derecha
}
else if(Acciton == 167 | Acction == 0){
Stop
}

and tha´s it!!!we have motor control.

http://www.developer.nokia.com/Community/Wiki/Python_on_Symbian here you will find all the information needed to program a Nokia with python.


Código Python para Nokia 5230 y Nokia C5


import os
import e32
import sys
import time
import math
import audio
import string
import camera
import thread
import appuifw
import key_codes 
from sensor import *
from graphics import *
from array import array
from graphics import Image


pys60_version_number = e32.pys60_version_info[0] * 10 + e32.pys60_version_info[1]
if pys60_version_number <= 14:
    import socket as btsocket
elif pys60_version_number >= 19:
    import btsocket

appuifw.app.orientation = "landscape"

# ---------------------------------------------------------------------------
# Constantes
BACKGROUND = (255, 255, 255)
# ---------------------------------------------------------------------------
# Variables
keyboard_state={}
last_keycode=0
Dat = [0,0]

app_lock = e32.Ao_lock()
# ---------------------------------------------------------------------------
#prepare canvas for drawing
canvas = appuifw.Canvas()    
appuifw.app.body = canvas
appuifw.app.screen = "full"
w, h = canvas.size
img = Image.new((w, h))
img.clear(BACKGROUND)

# ---------------------------------------------------------------------------
# Activar el Boton de salida
appuifw.app.exit_key_handler = quit

# ---------------------------------------------------------------------------
# Clase Bluetooth 
class BlueArduino:
   
def ConectarArduino(self):
print "Conectando..."
self.sock = btsocket.socket(btsocket.AF_BT,btsocket.SOCK_STREAM)
print "Buscando"
#only serial services are found. 
addr,services = btsocket.bt_discover()
print str(addr) + "Tiene " + str(len(services)) +" Servicios" 
print str(services)
if len(services):
   #create a choiselist and let the user choose which service to use.
   choiseList = services.keys()
   choiseList.sort()
   selected=appuifw.popup_menu([unicode(services[x])+": "+x for x in choiseList],u'select service:')
   self.host = (addr,services[choiseList[selected]])
else:
   raise(IOError)

print "connecting to " + str(self.host)
#bug? extended access software crashes on accept request from this device
self.sock.connect(self.host)

def EnviarArduino(self, data):
if(data=='$'):
self.sock.send(chr(36))
elif(data==','):
self.sock.send(chr(44))
elif(data=='&'):
self.sock.send(chr(38))
else:
self.sock.send(str(data))

    def flush(self):
        self.EnviarArduino(''.join([]))
           

def quit():
    global LOOP
    print "Quit!"
accelerometer.stop_listening()
    app_lock.signal()
    datafile.close()
# ---------------------------------------------------------------------------
# Inicializacion de Graficas 
def draw_text():
canvas.text(TEXT_LOC, u"" + TEXT, fill = TEXT_COLOR)
pass

def draw_background():
    canvas.clear(COLOR)
    handle_redraw(None)
pass

def handle_redraw(rect):
    if img:
        canvas.blit(img)
pass

def handle_event(event):
    handle_redraw(None)

# ---------------------------------------------------------------------------
# Inicializacion de las Teclas 
def draw_state():
    canvas.clear()
canvas.text((w-100,50),u' '.join([unicode(k) for k in keyboard_state if keyboard_state[k]]))
#app.EnviarArduino(u' '.join([unicode(k) for k in keyboard_state if keyboard_state[k]]))

def callback(event):
    global last_keycode
    if event['type'] == appuifw.EEventKeyDown:
        keyboard_state[event['scancode']]=1
    elif event['type'] == appuifw.EEventKeyUp:
        keyboard_state[event['scancode']]=0
    elif event['type'] == appuifw.EEventKey:
        last_keycode=event['keycode']
    #draw_state()

# ---------------------------------------------------------------------------
def Flechas():
    Dato = []
    canvas.clear()
    canvas.text((0,50),u' '.join([unicode(k) for k in keyboard_state if keyboard_state[k]]))
    Dato = u' '.join([unicode(k) for k in keyboard_state if keyboard_state[k]])     
    return Dato

# ---------------------------------------------------------------------------
# Interfaz Grafica
canvas=appuifw.Canvas(event_callback=callback,redraw_callback=lambda rect:draw_state())
appuifw.app.body=canvas

# ---------------------------------------------------------------------------
# Programa Principal

app = BlueArduino() # Invocamos la clase para la comunicacion Bluetooth
app.ConectarArduino() # Realizamos la Coneccion con el dispositivo Bluetooth

while 1:
e32.ao_yield()
canvas.text((w/2-20,20),u"Teclado")
Dat = Flechas()  # envia los codigos, correspondiente a la flecha
app.EnviarArduino('$')
app.EnviarArduino(Dat)
app.EnviarArduino('&')


In part two, I will explain how to make our mobile robot control and evade the obstacles with sharp distance sensors.













Thanks