Você está na página 1de 40

Notas de Apoio a

Sistemas de Automação

Simulação em Robótica

Paulo Leitão
URL: http://www.ipb.pt/~pleitao
E-mail: pleitao@ipb.pt

Contextualização
• Estudo de sistemas, para suporte à tomada de decisões
sobre a sua composição, filosofia e desempenho
• Requer um conjunto de pressupostos sobre o funcionamento
do sistema, constituindo o modelo do sistema
• Diferentes tipos de modelo:
– Modelo físico: representação palpável do sistema, muitas vezes com
dimensões mais reduzidas
– Modelo matemático: representação em termos de relações lógicas e
quantitativas que são manipuladas de forma a ver como o sistema reage

• Complexidade do modelo:
– simples  possível manipular as suas relações e quantidades de forma a
obter uma solução exata ou analítica
– complexo  estudo recorrendo à simulação
2

Page 1
Contextualização (2)

Sistema

Ensaio com o Ensaio com o


próprio sistema modelo do sistema

Modelo físico Modelo matemático


do sistema do sistema

Solução analítica SIMULAÇÃO

Objetivos da simulação

• O objetivo dos modelos de simulação é imitar o


comportamento do sistema ao longo do tempo através de
um modelo capaz de:
– Reproduzir a sucessão de estados pelos quais o sistema passa
– Registar medidas relevantes para a definição da performance do sistema
simulado

• SIMULAÇÃO: exercitar o modelo numericamente para as


entradas em questão de forma a verificar como elas afetam
as medidas de performance da saída

Page 2
Caraterísticas da simulação

• A simulação permite o estudo de sistemas complexos, ou de


um subsistema desse sistema complexo
• Após a criação de um modelo consistente, diversos tipos de
alterações podem ser testadas e as suas implicações
observadas de forma direta
• Perceção das variáveis críticas para o desempenho do
sistema
• Suporte às tomadas de decisão empíricas ou como auxilio
de outra ferramenta
• Usada para testar novas metodologias ou para prever o que
aconteceria ao sistema real perante um cenário hipotético
5

Vantagens da simulação

• Novas filosofias de operação, regras de decisão e


procedimentos podem ser estudados sem prejuízo do
sistema real que permanece inalterado
• Novas soluções podem ser testadas sem a necessidade de
aquisição/utilização de equipamento
• Aquisição de conhecimento sobre a interação de diferentes
variáveis e a importância relativa das variáveis para o
desempenho global do sistema
• Análise de pontos críticos do sistema (bottlenecks)
• Resposta a perguntas to tipo “What happen If … ?”

Page 3
Desvantagens da simulação
• A construção de um modelo exige uma experiência elevada
na área e com formação elevada
• Uma vez que todos os resultados são variáveis aleatórias
(porque são gerados a partir de entradas aleatórias), os
resultados da simulação podem ser difíceis de interpretar
• A modelação pode ser demorada e cara
– Por vezes a simplificação pode tornar o mesmo inapto para a solução do
problema

• Por vezes soluções baseadas na simulação são utilizadas


quando podiam ser encontradas soluções analíticas

Áreas de aplicação
• Estudar sistemas produtivos e de manipulação
• Avaliar software e hardware para sistemas de
computadores
• Avaliar o desempenho de novas armas e/ou técnicas
militares
• Determinar políticas de encomendas para um sistema de
stocks
• Projetar sistemas e protocolos de comunicação
• Estudar o funcionamento de instituições públicas de
atendimento, como hospitais, correios, etc
• Analisar sistemas económicos e financeiros
• …
8

Page 4
Exemplos de aplicação

Breve história
• Late ‘50s, early ‘60s
– Appearance of initial computers (e.g. ENIAC); hardware predominance
– First languages introduced
• Late ‘60s, early ‘70s
– Accessibility and interaction provided by initial computers was limited
– General Purpose Simulation System (GPSS) by IBM
– Significant evolution of simulation
• Late ‘70s, early ‘80s
– Advanced modelling and results analysis tools were developed
– First languages to run in microcomputers
• Today
– Powerful PCs
– Languages are very sophisticated and powerful
– Models can now be animated (3-D graphics and real time animation)
10

Page 5
Componentes de um Sistema

• Entidade: qualquer objeto de interesse para o sistema (e.g., máquina,


peça, operador)

• Atributo: propriedade de um objeto (e.g., tempo de processamento e


tempo de setup de uma máquina)

• Atividade: representa ações que decorrem durante um determinado


período de tempo (e.g., realização de uma peça numa máquina)

• Estado: conjunto de variáveis capazes de caracterizar o sistema num


determinado instante de tempo

• Evento: ocorrência instantânea que pode ou não alterar o estado do


sistema (e.g., chegada de uma ordem de fabrico)
11

Sistemas Discretos e Contínuos

• Sistema Discreto
– Quando o conjunto de variáveis que o caracteriza só são alteradas num
conjunto discreto de unidades de tempo
– Exemplo: sistema em que se pretende simular uma fila de espera junto a
uma máquina, onde os eventos são a chegada de uma nova peça ao
sistema e o fim de operação da máquina

• Sistema Contínuo
– Quando as variáveis vão sendo continuamente alteradas ao longo do tempo
– Exemplo: simulação de um sistema de aquecimento para estudo de como
evolui o nível da água na caldeira principal (neste exemplo podemos
também encontrar eventos discretos, como por exemplo os instantes em
que são ligados e desligados os radiadores em vários pontos do sistema)

12

Page 6
Passos num Estudo de Simulação

• Formulação do problema
– Descrição e compreensão total do problema

• Estabelecimento de objetivos e alternativas


– Enumeração das questões a responder no fim do estudo
– Análise das alternativas existentes à realização do estudo
– Elaboração do plano para o estudo em termos de pessoas envolvidas,
horas necessárias e custo global

• Conceptualização do modelo
– Consiste em perceber o sistema real e o problema, por forma a criar um
modelo exequível mas suficientemente detalhado para dar solução ao
problema
– Inclui a escolha das entidades com os respetivos atributos, as atividades e
eventos, e a relação destes componentes entre si e com o mundo exterior
13

Passos num Estudo de Simulação (2)


• Recolha de informação
– Exemplos típicos de variáveis num processo industrial são os tempos de
maquinação, o tempo entre avarias, o tempo entre chegadas de ordens ou
encomendas, etc.

• Tradução do modelo
– Transformação do conceito anteriormente idealizado numa forma que seja
percebida por um meio de calculo, normalmente o computador
– Linguagens especificas de simulação: GPSS/H, SIMAN V, etc.; pacotes de
software: QUEST, AUTOMOD, etc.; linguagens genérica: C++, Pascal, etc.

• Verificação do programa de simulação


– Processo interativo de garantir que o programa criado respeita o modelo
idealizado, ou seja verificar se os parâmetros de entrada e os mecanismos
de decisão obedecem às regras impostas pelo modelo
– Técnicas: ocorrência de erros, TRACE, animação, etc.
14

Page 7
Passos num Estudo de Simulação (3)
• Validação do modelo
– Consiste em garantir que o modelo é uma representação suficientemente
detalhada da realidade e suficiente para responder aos objetivos do estudo
– Normalmente é conseguida através do processo de calibração do modelo,
em que se compara o desempenho do modelo com o do sistema real

• Execução da simulação e análise de resultados


– Os resultados obtidos devem ser analisados e tratados por forma a
responder às perguntas realizadas na fase de especificação dos objetivos
– Estimam-se os parâmetros que medem a performance do sistema que está
a ser simulado

• Documentação
– Permite que o estudo possa ser reutilizado no futuro e permite uma melhor
compreensão e confiança nos resultados por parte do cliente
– Normalmente existem dois tipos de documentação: interna e externa
15

Vantagens da simulação na robótica


• Reduce costs involved in robot production
• Diagnose source code that controls a particular resource or a mix
of resources
• Simulate various alternatives without involving physical costs
• Robot or components can be tested before implementation
• Simulation can be done in stages, beneficial for complex projects
• Demonstration of a system to determine if is viable or not
• Compatibility with a wide range of programming languages
• Shorter delivery times

16

Page 8
Desvantagens da simulação na robótica
• An application can simulate just what it is programmed to
simulate
– it will not simulate internal or external factors which are overlooked in the
development phase

• A robot can encounter many more scenarios in the real


world than there can be simulated

17

Softwares de simulação para robótica


ABB
RobotStudio

MotoSim® EG
KUKA.SIM (Motoman Simulator FANUC ROBOGUIDE
Enhanced Graphics)
18

Page 9
Outros simuladores
• RoKiSim
• SimTwo
• Webots
• Gazebo
• Actin Simulation
• Microsoft Robotics Studio
• Unity
• Simspark
• MURoSimF
• V-REP (https://www.youtube.com/watch?v=bwGYUayglHY)
19

RobotStudio
• Software de simulação da ABB
• Disponível para download (versão 6.04.01) em:
– http://new.abb.com/products/robotics/robotstudio/downloads

20

Page 10
Tutorial for manipulating 1 piece
• Objective:
1. move a piece from place A to place B

p_repouso

p4 p2

p3 p1

B A

2. Move the piece back to place A

21

Creating a new project

• Create a new project:


– “New” > “Solution with Station and Robot Controller”
– Select “IRB_1410_5kg_1.44m” > “Create”

• CTRL+wheel: to
zoom +/-
• CTRL+right
button: to move
the cell’s view
• CTRL+SHIFT+
left button: to
rotate the cell’s
view

22

Page 11
Creating the model of the cell
• Include the metallic sheet (pedestal) where the robot is
located:
– “Import geometry” > “User Geometry” > Select the “Pedestal Robot”
(or selecting the file “pedestal.SAT” in the folder
“documentos\RobotStudio\Geometry”)

• Move the robot to the center of the pedestal:


– Right click in the robot object (menu layout in the left side of screen)
– “Position” > ”Set Position”
– “Snap Center” > put the cursor in the
field XX of the “Set Position” area
– Right click in the “pedestal” object > “Apply”

23

Creating the model of the cell (2)


• Include the perforated metallic sheet:
– “Import geometry” > User Geometry” > Select “chapa”
(or selecting the file “chapa.SAT” in the folder
“documentos\RobotStudio\Geometry”)
– “Position” > ”Rotate” > 270º in ZZ (rotation)
– “Position” > ”Set Position” > -185 mm in XX (position)

• Include the gripper:


– “Import library” > User library > Select “SC_PINCA1”
– Right click in the “SC_PINCA1” object > “Disconnect Library”
– Move the PINCA1 object to the robot (in the layout menu)
(the gripper is automatically attached to the robot)
– To test the opening and closing of the gripper: right click in “SC_PINCA”
object > “Properties” > “abre_garra” or “fecha_garra””

• “Home” > “Graphics Tools” > “Settings” > “Reset Floor Size”
24

Page 12
Marking the points
• Moving the robot:
– Joint movement: right click > “Mechanism Joint Jog”
– Linear movement: right click > “Mechanism Linear Jog”

• Points are stored in “Workobject & Targets”!


• Define the rest point:
– Right click on the robot object > “Mechanism Joint Jog”
– Change the joints for: J1= -90, J5= 90, others = 0
– “TeachTarget” > OK
– Rename the point to “p_repouso”

25

Marking the points (2)


• Add the piece in the model
– “Import geometry” > User Geometry” > Select “Peca”
(or selecting the file “peca.SAT” in the folder “documentos\RobotStudio\Geometry”)
– Right click in the “peca” object (menu layout in the left side of screen)
– “Position” > ”Set Position” > “Snap Center” > put the cursor in the
field XX of the “Set Position” area
– Right click in the “chapa” object > 800 mm in XX > “Apply”

• Define the point in the piece (p1):


– “Target” > Select “peca” object > “Create”
– Rename the point to “p1”
– Right click in “p1” > “Modify Target” > ”Set Position” > -15 mm in ZZ
– Verify if it is reachable: right click in “p1” > “Reachability”
– “If not “Copy orientation” of “p_repouso” and “Apply orientation” for “p1”
– Select “Configurations” and select one > “Apply”
26

Page 13
Marking the points (3)
• Define the approximation point to the piece (p2):
– “Copy” and “Paste” the point “p1”
– Change the name to “p2”
– “Modify Target” > “Offset Position” > -150 mm in ZZ
– Select “Configurations” and select one > “Apply”

• Define the target point in the floor (p3):


– “Copy” and “Paste” the point “p1”
– Change the name to “p3”
– “Modify Target” > “Set Position” > -400 mm in XX
– Select “Configurations” and select one > “Apply”

27

Marking the points (4)


• Define the target approximation point to the piece (p4):
– “Copy” and “Paste” the point “p2”
– Change the name to “p4”
– “Modify Target” > “Set Position” > -400 mm in XX
– Select “Configurations” and select one > “Apply”

28

Page 14
Defining the paths
• Define the sequence of paths for the movement A  B:
– “Path” > “Empty path”
– Change the name into “path_a_b”
– Drag the sequence of points that define this movement into the “path_a_b”
path
– Right click in the “path_a_b” > “Move Along Path”

• Define the sequence of paths for the movement B  A:


– Execute the same previous procedure
– Change the name into “path_b_a”

• Create the main:


– “Path” > “Empty path”
– Change the name into “main”
– Drag the “path_a_b” and “path_b_a” into the “main” path
29

Synchronizing with RAPID


• RAPID menu > “Synchronize to RAPID” (selecting all items)
• Verify the program in RAPID
• If necessary, we can modify the parameters in RAPID
– In this case, it is necessary to make “Synchronize Station” at the end

• Execute the simulation:


– Simulation > Play

• Save the RAPID program:


– “RAPID” > “Program” > “Save Program as” > …

30

Page 15
Add functions to open and close gripper
• Add “abre_garra” and “fecha_garra” functions in the
RAPID code
• Add calls to “abre_garra” and “fecha_garra” in the
“path_a_b” and “path_b_a” paths
• Need to define the variables “DOabre” and “DOfecha”
– “Controller” menu > “Configuration Editor” > “I/O System”
– Right click in “Signal” > “New Signal” > introduce the parameter “DOabre”:
» Name: “DOabre”
» Type of signal: “Digital Output”
» Access Level: “All”
– Make the same procedure for “DOfecha”
– “Restart (warmstart)” the controller
31

Logic to control the gripper


• Select SC_PINCA1
– Right click > “Edit Component”
– Select component “FechaPinca” > “Properties” > duration: 0,1 s; J1: 11 mm
– Make the same procedure for “AbrePinca” > duration: 0,1 s; J1: 0 mm
– Select “Attacher” component
» Parent: “SC_PINCA1/PINCA1”
» Child: “Peca” > “Apply”
– Select “Detacher” component
» Child: “Peca” > Apply
– Select “Design” menu in the “SC_PINCA1” panel
– Right click on “SC_PINCA1” object > “Save as Library”

32

Page 16
Logic to control the gripper (2)
• “Simulation” > “Station Logic” > “Design” menu
– In the controller block > add “DOabre” and “DOfecha”
– Link “DOabre” to “abre_garra” block and “DOfecha” to the “fecha_garra”
block

• I/O simulator > “Filter” > “User List”


– Create a new list with the two
variables (“DOabre” and
“DOfecha”)

• Execute the simulation:


– Simulation > Play

33

Showing the collisions

• In the “Simulation” menu > “Create Collision Set”


• Right click on “Collision_Set_1
• Drag “PINCA1” object to “ObjectsA” and “Chapa” object to
“ObjectsB”
• Use the “Freehand” > “Linear Jog” to move the robot and
test the collision!

34

Page 17
Exercises to be done:

• Manipulate a stack of 3 parts

• Manipulate a stack of n parts

• After simulating, test the programs in the real robot

35

Other notes:

• Use “SC_PINCA” object that already has the PlanSensor


component: allowisto pick any piece
• Add the instructions TPReadNum, TPWrite, FOR ..THEN,
etc. directly in the RAPID code
• Select “Controller””VirtuaFlexPendent” to support the
interaction with the user
– Move PP to Main  “Enable” motors “Play”
– After pressing “emergency”: “Control Panel”  ”Push Motors Button”

Generate the code to be executed in real environment:


– “RAPID”  ”Program”  ”Save As …”

36

Page 18
Simulador V-REP

• Virtual Robot Experimentation Platform


• Possui um ambiente de desenvolvimento integrado
• Arquitetura de controlo
distribuída:
– cada objeto/modelo pode ser
individualmente controlado através de
script, plugin, nó ROS, cliente API
remoto, ou solução customizada

• Ideal e versátil para aplicações


multi-robots
• Controladores escritos em C/C++, Python, Java, Lua,
Matlab, Octave or Urbi
37

Aplicações

• Desenvolvimento rápido de algoritmos


• Simulação de sistemas de automação fabril
• Prototipagem e verificação rápida
• Monitorização remota
• Educação em robótica
• Etc.

38

Page 19
Principais caraterísticas

• Dynamics / physics
• Inverse / forward kinematics
• Collision detection
• Minimum distance calculation
• Dynamic particles
• Proximity sensor simulation
• Visor sensor simulation
• Path/motion planning
• Data recording and visualization
39

Instalar V-REP PRO EDU V3.3.0

• Download em: http://www.coppeliarobotics.com/downloads.html

• Interfaces em V-REP
– Menus no V-rep
– Camaras disponíveis em V-rep
– Cinemática inversa
– Parâmetros de colisão
– Propriedades do objeto no espaço
– Propriedades cinemáticas do objeto

40

Page 20
User interface elements

41

Caso de estudo #1

• Objetivo:
– Criar um robot autónomo e móvel
– Aplicar cinemática para o mover ao longo
de uma linha

• Procedimentos básicos:
– Criar objetos em V-REP (cubo, cilindro, …)
– Criar juntas em V-REP (i.e. ligações entre objetos)
– Fazer uma árvore hierárquica (agrupamento entre objetos, juntas, …)
– Modificar formas (shapes)
– Programar em V-REP
» Aplicar cinemática direta
» Aplicar condições de teste

42

Page 21
Criar objetos (cubo, cilindro, …)

• Menu bar > Add > Primitive Shape > Cuboid


• Janela ‘Primitive Cuboid’ > OK
• Selecionar o cubo e clicar em ‘Scene Object Properties’
– View/modify geometry > Apply

• Mudar o nome para ‘Base’


43

Criar objetos (2)

• Menu Bar > Add > Primitive Shape >


Cylinder
• Janela ‘Primitive cylinder’: X-size=0.1; Z-
size=0.01 > OK
• Mudar nome para ‘Roda1’
• Selecionar ‘Roda1’ > Object/item shift
– Orientation: alfa = 90º;
– Position: x = 0.07; y = 0.055 ; z = 0.05

• Selecionar ‘Roda1’ > Menu bar > Edit > Copy selected objects
• Menu Bar > Edit > Paste buffer
• Repetir para as restantes rodas
44

Page 22
Criar objetos (3)

45

Criar juntas

• Menu Bar > Add > Joint > Revolute


• Mudar o nome para ‘joint1’
• Selecionar ‘joint1’ > Object/item shift
– Orientation: alfa = 90º;

• Selecionar o joint e clicar em


‘Scene Object Properties’
– Joint visual properties:
» length = 0.02
» diameter = 0.02

46

Page 23
Criar juntas (2)

• Selecionar ‘joint1’ > Menu Bar > Edit > Copy selected
objects
• Menu Bar > Edit > Paste buffer (3 vezes)
• Selecionar ‘joint1’ e ‘roda1’ simultaneamente
(joint1+ctrl+roda1)
– Object/item shift > Apply to selection

• Repetir para os
restantes pares
{roda, junta}

47

Fazer uma árvore hierárquica

• Selecionar ‘roda1’+’joint1’ > Menu


Bar > Edit > Make last selected
object parent
• Repetir para cada roda
• Selecionar ‘joint1’ + ’joint2’ + ’joint3’
+ ’joint4’ + ’Base’ > Menu Bar > Edit
> Make last selected object parente

• NOTA:
– Neste momento todos os objetos estão ligados e constituem um corpo
– O robô não executa nenhum movimento concreto

48

Page 24
Aplicar cinemática direta

• Menu Bar > Add > Dummy


• Selecionar ‘Dummy’+’Base’ > Menu Bar > Edit > Make last
selected object parent
• Selecionar ‘Dummy’ e ‘Base’
simultaneamente (Dummy + ctrl
+ Base) > Object/item shift
> Apply to selection
• Selecionar o botão ‘Layers’

49

Aplicar cinemática direta (2)

• Selecionar o botão Scripts > Insert


new script > New script > opção ‘child
script (non- threaded)’ > OK
– Associated object > opção ‘Dummy’

• Abrir o script
associado ao
Dummy e adicionar
código em anexo

50

Page 25
Aplicar cinemática direta (3)

• Selecionar o ‘joint4’ >


Object/item shift
– Show dynamic parameters
dialog > Ativar Motor enabled

• Selecionar Start/resume
simulation

51

Aplicar condições de teste


• Robot stops after three seconds:
– Save time present time
– Get the current time
– Calculate the difference between current time and previous time

52

Page 26
Aplicar condições de teste
• Robot stops after moving 1 meter forward

Finish
(without odometry):
– Get the joint Position
– Get the absolute joint position
– Get the number of turns of wheel
– Establish a relation between
Vr Vl
the wheel position and distance

Start
– Distance is equal to:
• Dist=turnCount*2*π*r
– When the robot reaches the
predefined distance it stops

53

Odometry Formulas

y
𝑽𝒍 + 𝑽𝒓
𝑽=
2
x
α
𝑽𝒍 − 𝑽𝒓
𝒘=
Vl V Vr 𝒃

W
x= 𝒗 ∗ 𝒄𝒐𝒔(α)

b
y= 𝒗 ∗ 𝒔𝒊𝒏(α)

54

Page 27
Get joint position

RightWheel=simGetObjectHandle("joint4")
local dx=simGetJointPosition(RightWheel)- prevPosR
if (dx > = 0) then
dx=math.mod(dx+math.pi,2*math.pi)-math.pi
else
dx=math.mod(dx-math.pi,2*math.pi)+math.pi
end
AbsolutePosR=AbsolutePosR+dx
prevPosR=simGetJointPosition(RightWheel …

55

Odometry

rightPos = AbsolutePosR * (180 / math.pi)


click = (math.pi * 0.1) / 360
v = (distL+distR) / 2
w = (distL-distR) / 0.11
alpha = alpha + w
-- normalize angle (returns angle between -180 and 180)
if (alpha > math.pi) then
alpha = alpha - 2 * math.pi;
end
if (alpha < = -math.pi) then
alpha = alpha + 2 * math.pi;
end
x = v * math.cos(alpha)
y = v * math.sin(alpha)

56

Page 28
State machine

if (state == 0) then
simSetJointTargetVelocity(LeftWheel,0)
simSetJointTargetVelocity(RightWheel,0)
alpha=0
x=0
y=0
end
if (state == 1) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,1)
if (x > = 1) then
state=0
end
end

57

Code
if (sim_call_type==sim_childscriptcall_initialization) then
-- motor initialization
LeftWheel=simGetObjectHandle("joint3")
RightWheel=simGetObjectHandle("joint4")
prevPosR=simGetJointPosition(RightWheel)
prevPosL=simGetJointPosition(LeftWheel)
AbsolutePosR=prevPosR
AbsolutePosL=prevPosL
alpha=0
x=0
y=0
state=1
-- sensor initialization
sensor=simGetObjectHandle("FrontSensor")
-- Console Initialization
myconsole=simAuxiliaryConsoleOpen('Debug',5,0,{0.5,0.9},{0.2,0.2},NULL,NULL)
simAuxiliaryConsoleShow(myconsole,1)
end

58

Page 29
Code (2)
if (sim_call_type==sim_childscriptcall_actuation) then
-- Calculate right wheel joint position
local dr=simGetJointPosition(RightWheel)-prevPosR
if (dr>=0) then
dr=math.mod(dr+math.pi,2*math.pi)-math.pi
else
dr=math.mod(dr-math.pi,2*math.pi)+math.pi
end
AbsolutePosR=AbsolutePosR+dr
prevPosR=simGetJointPosition(RightWheel)
-- Calculate left wheel joint position
local dl=simGetJointPosition(LeftWheel)-prevPosL
if (dl>=0) then
dl=math.mod(dl+math.pi,2*math.pi)-math.pi
else
dl=math.mod(dl-math.pi,2*math.pi)+math.pi
end
AbsolutePosL=AbsolutePosL+dl
prevPosL=simGetJointPosition(LeftWheel)

59

Code (3)
---------------- Calcules based on perimeter ----------------
-- Turn count
turnCountL = (AbsolutePosL / (math.pi * 2))
turnCountR = (AbsolutePosR / (math.pi * 2))
-- Distance based on Perimeter(2*pi*r)
distP = (turnCountL * 2 *math.pi * 0.05)
---------------- Calcules based on odometry -----------------
-- 360 click per revolution
leftPos = AbsolutePosL * (180 / math.pi) -- left joint position in degrees
rightPos = AbsolutePosR * (180 / math.pi) -- right joint position in degrees
click = (math.pi * 0.1) / 360 -- distance per click ((pi*diameter)/360)
distL = click*leftPos -- distance of left wheel travelled
distR = click*rightPos -- distance of right wheel travelled
-- Average motion of the two wheels (distance travelled by robot)
-- v = (left_encoder + right_encoder) / 2.0
v = (distL+distR) / 2
-- w = (left_encoder - right_encoder) / WHEEL_BASE
w = (distL-distR) / 0.11
-- orientation
alpha = alpha + w

60

Page 30
Code (4)
-- normalize angle returns equivalent angle between -180 and +180
if (alpha > math.pi) then
alpha = alpha - 2 * math.pi;
end
if (alpha <= -math.pi) then
alpha = alpha + 2 * math.pi;
end
-- (x,y)
x=v*math.cos(alpha)
y=v*math.sin(alpha)
-- State Machine
if (state == 0) then
simSetJointTargetVelocity(LeftWheel,0)
simSetJointTargetVelocity(RightWheel,0)
alpha=0
x=0
y=0
end

61

Code (5)
if (state == 1) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,1)
if (x >= 1) then
state=0
end
end
-- Print Values
simAuxiliaryConsolePrint(myconsole,string.format("state %d\n", state))
simAuxiliaryConsolePrint(myconsole,string.format("X %2f\n", x))
simAuxiliaryConsolePrint(myconsole,string.format("Y %2f\n", y))
simAuxiliaryConsolePrint(myconsole,string.format("w %2f\n",
w*180/math.pi))
end
if (sim_call_type==sim_childscriptcall_sensing) then
currentTime=simGetSimulationTime()
end
if (sim_call_type==sim_childscriptcall_cleanup) then
simAuxiliaryConsoleClose(myconsole)
end
62

Page 31
Robot makes a quadrangular trajectory
Vr

Vl

Vr Vl

Vr Vl
Start

Finish

63

State Machine
if (state == 0) then
simSetJointTargetVelocity(LeftWheel,0)
simSetJointTargetVelocity(RightWheel,0)
alpha=0
x = 0
y = 0
end
if (state == 1) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,1)
if (x >= 0.4) then
state=2
end
end
if (state == 2) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,-1)
if (alpha >= 3*math.pi/2) then
state=3
end
end
64

Page 32
Code (2)
if (state == 3) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,1)
if (y <= -0.8) then
state=4
end
end
if (state == 4) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,-1)
if (alpha >= 2*math.pi+math.pi) then
state=5
end
end
if (state == 5) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,1)
if (x <=-1.2) then
state=6
end
end
65

Code (3)
if (state == 6) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,-1)
if (alpha >= 6*math.pi+math.pi/3) then
state=7
end
end

if (state == 7) then
simSetJointTargetVelocity(LeftWheel,1)
simSetJointTargetVelocity(RightWheel,1)
if (y >= 1.4) then
state=0
end
end

66

Page 33
Adicionar sensor de proximidade

• Menu Bar > Add > Proximity Sensor > Disc Type

• Object/Item position/orientation
X-coord. [m] -0,10 Alpha[deg] 0

Y-coord. [m] 0,00 Beta[deg] -90

Z-coord. [m] 0,05 Gamma[deg] 90

• Scene hierrarchy > Double click on icon “Proximity_sensor”


> Select Object Proprieties > Show volume parameters
Offset [m] 0,00

Range [m] 0,20

Angle [deg] 130

67

Adicionar sensor de proximidade

• Attach the sensor to base


– Scene hierarchy > Select “Proximity_sensor” + ctrl + “Base”, then
» Right click > Edit > Make last selected object parent

– In Scene hierarchy, drag the Select “Proximity_sensor” onto Base


68

Page 34
Ler sensor de proximidade
• Adicionar condição na script
– Open the Script
» Associate a name to “Proximity_sensor”
• Sensor=simGetObjectHandle(“Proximity_sensor”)

» Read the state of the sensor


0 – no object detected
• result=simReadProximitySensor(Sensor) 1 – object detected

• Selecionar Start/resume simulation


69

Adicionar obstáculo à cena


• Menu bar > Add > Primitive shape > Cylinder
– Define dimensions
– Disable body is dynamic

• Selecionar “Cylinder” > Object/item shift


> Common
– Make the object
» Collidable, Measurable, Detectable, Renderable
– Define position/orientation
» While cylinder selected
• Define Position

• Define Orientation

70

Page 35
Caso de estudo #2
• Objetivo:
– Movimentar o braço robótico utilizando um
modelo existente
– Aplicar a cinemática inversa para mudar a
posição das garras do robô
• Procedimentos básicos:
– Utilização de modelos do V-REP (e.g. ´7 DoF manipulator´)
– Reestruturar a árvore hierárquica (agrupamento entre objetos, juntas, …)
– Modificar a estrutura do robô para aplicar a cinemática inversa (i.e. apagar
e/ou alterar as propriedades dos objetos)
– Criar conjuntos IK (cinemática inversa)
– Criar uma coleção (agrupamentos de objetos)
– Utilizar detetor de colisão
– Programação em lua
71

Utilização de modelos do V-REP

• Janela ‘Model browser’ > ‘robots’ >


‘non-mobile’ > ’7 DoF manipulator’
• Selecionar o robô > ‘Object/item
shift’
– Position: x = 0.00; y = 0.00

72

Page 36
Reestruturar a árvore hierárquica

• Selecionar os objetos não puros e


ligar as juntas (‘joints’)
• Exemplo:
– Selecionar o objeto
‘redundantRob_link1’+’redundantRob_joint1’
> Menu Bar > Edit > Make last selected
object parent
– Selecionar o objeto
’redundantRob_link2’+‘redundantRob_joint2’
> Menu Bar > Edit > Make last selected
object parent

73

Modificar a estrutura do robô para


aplicar a cinemática inversa

• Apagar os objetos puros


que compõem o braço
robótico, com exceção do
último (‘Rectangle4’)
• ‘Start Simulation’

74

Page 37
Modificar a estrutura do robô para
aplicar a cinemática inversa (2)

• Alterar as propriedades das


juntas
• Selecionar a junta >
Object/item shift > Joint
mode > desativar a opção
‘Hybrid operation’
• Repetir para todas as juntas

75

Criar conjuntos IK (cinemática inversa)

• Selecionar ‘Calculation Modules’ > ‘Inverse


Kinematics’
• Apagar os grupos existentes e criar três novos:
– IK_Group
– IK_Group2
– IK_Group3

76

Page 38
Criar uma coleção (agrupamento de
objetos)
• Selecionar
‘Collections’

77

Utilizar detetor de colisão

• Selecionar ‘Calculation
Modules’ > ‘Collision
Detec.’

78

Page 39
Programação em lua

• Criar um novo script


• Copiar código do ficheiro
‘Manipulator.txt’
• Criar o(s) ponto(s) de
referência (Dummys)
• ‘Start Simulation’

79

Page 40

Você também pode gostar