Spin Indexer Plate Calculator (python)

I did up this program to calculate out the amount of divisions that a spin indexer could do, and calculate out the degrees that each needs. I designed it because If you have custom plates, you’ll get different values for everything, and this program will calculate everything out for you, with the degrees needed to achieve each division. Just change num to whatever you want to get the divisions and list of degrees to get those numbers.

num = 360

for i in range(1, num + 1):
    if num % i == 0:
        print'\n', i, '\n'
        t=num/i
        j=0
        while True:
          j=t+j
          print(j)
          if j==num:
             break
			

If you dont want to mess with it, and only want the 360 degrees printout, I have it here:

https://drive.google.com/file/d/0BwYG1PFb3ZBydFZrUWpMTVZJNUk/view?usp=sharing

I had mine start at 0 and removed the 360 to make it easier for my indexer.

Hex to Decimal Python Program

Here’s a clip of code to convert either a hex to decimal value, or decimal to hex.

copied from here:

http://www.daniweb.com/software-development/python/code/216638/hexadecimal-to-decimal-python

Just modify it for your needs, and it’ll help with sending the commands from the Robosapien arduino library.


# change a hexadecimal string to decimal number and reverse
# check two different representations of the hexadecimal string
# negative values and zero are accepted
# tested with Python24 vegaseat 11oct2005
def dec2hex(n):
  """return the hexadecimal string representation of integer n"""
  return "%X" % n
def hex2dec(s):
  """return the integer value of a hexadecimal string s"""
  return int(s, 16)
print "dec2hex(255) =", dec2hex(255) # FF
print "hex2dec('FF') =", hex2dec('FF') # 255
print
print "hex(255) =", hex(255) # 0xff
print "hex2dec('0xff') =", hex2dec('0xff') # 255

My FreeCAD addon

Ive been working on a FreeCAD addon since I use kisslicer to slice up my stl files for my 3d objects I design, so eventually, I got tired of constantly having to search for the stl files, and designed this code. The code will automatically convert only the visible parts that you want, group them together, and export it as an stl file next to the original design file, with the same filename except with stl extension. Then it’ll open the STL file automatically for you ready to slice and to create gcode from your settings.

I designed it on linux, but it should easily be converted to be used on windows or any other system. Just create a macro in freecad, and paste this into the macro, then save it. Then you can go to tools/customize and set up the macro to a button on the toolbar, so you can just click the button and it converts everything for you.

import FreeCAD
import Mesh
import sys
import math
import os
import subprocess

# some fuctions

def getPlacement(quat,vect,obj):
  if quat[3] > -1  and quat[3] < 1:
    delta = math.acos(quat[3])*2.0
    scale = math.sin(delta/2)
    rx = quat[0]/scale
    ry = quat[1]/scale
    rz = quat[2]/scale
  else:
    delta = 0
    rx = 0
    ry = 0
    rz = 1

info0 = "translation "+str(vect.x)+" "+str(vect.y)+" "+str(vect.z)
info1 = "rotation "+str(rx)+" "+str(ry)+" "+str(rz)+" "+str(delta)
return info0+" "+info1
# some definitions
placement = App.Placement(App.Vector(0,0,0),App.Rotation(0,0,0,1))

# user need to set this directory where STL files will be placed
OutDir = FreeCAD.ActiveDocument.FileName.replace(FreeCAD.ActiveDocument.Label + ".fcstd", "")
visible_objs = []
KISSlicer = "/kisslicer location/"     #put the location of your kisslicer directory here
os.chdir(KISSlicer)

# Get Objects in document
doc = App.ActiveDocument
objs = doc.Objects

# hide all
for obj in objs:
  if obj.ViewObject.isVisible():
    visible_objs.append(obj)

print "number of volumes "+str(len(visible_objs))

for obj in visible_objs:
# {
  # get volume
  volume = obj.Shape.Volume

  # get Rotation and translation of volume
  quat = obj.Placement.Rotation.Q
  vect = obj.Placement.Base
  pinfo = getPlacement(quat,vect,obj)

  # reset placement, export it and set at original placement
  oldPlacement = obj.Placement
  obj.Placement = placement
  obj.Placement = oldPlacement

stlFile = OutDir+str(doc.Label)+".stl"
Mesh.export(visible_objs,stlFile)
subprocess.Popen([KISSlicer + "KISSlicer", stlFile])

You’ll have to change the values of the location of KISSlicer, or modify it for whatever slicer software you use, and it should work fine.

Robosapian v2 PC control/New Toy

I know I havnt posted any posts in a while, but been busy working with a new project. I recently came across a robosapian v2 that someone tossed in the trash, that I rescued and got working again. The only thing is, he had no remote, so this is what I did to get control of him using the computer.

I rewired him and replaced all of the original and crumbling wires, and cleaned out the battery compartments since the batteries had exploded inside of him, then I found the wire running from his IR sensor to the motherboard inside of his back. I cut the wire and added a normally closed mono headphone jack, the type that when nothing’s plugged in, it shorts the two contacts together. The contact that gets disconnected, I ran to the IR sensor, then the other, I ran to the motherboard so the tip of the headphone jack will connect into the motherboard when it’s plugged in, and will disconnect the IR sensor so there is no false signals coming from the IR sensor in the head while it’s plugged in, then it will connect back up the IR sensor in the head when the headphone jack isnt plugged in. I put the headphone jack into his back, he usually has something that looks like a button on his back and front, but I just popped the one out on his back, and drilled it out slightly to put the jack in it, and now it looks like it was just designed into it by default.

Then I took an arduino and on a protoboard I found for dirt cheap on ebay, I soldered another headphone jack to it with 3 pin header so you can use it as you wish. I then used a 1.8k ohm resistor and a 3.3k ohm resistor to hook up a voltage divider between pin 13 and gnd, and the divided voltage went to the tip of the headphone jack on the protoshield.

Using this code below, I am able to send commands to the robosapian v2 by a python program called robomoco.py that I found online, Ill post a link to it below also. I had to modify the code slightly because newer arduino software deprecated a few things that was in the old code.

// rs_commander.c - Arduino-based serial port controller for Robosapiens
// Modified: 9/15/10
// Author: Ben Bongalon (ben@borglabs.com)
// Adapted from Karl Castlet's code
// I refactored it a bit and added support for the Robosapien V2 and
// other models (untested).
// Robosapien's model types. Credit to AiboPet's BoneYard
#define RS_MODEL_ROBOSAPIEN_V1   0x00
#define RS_MODEL_ROBORAPTOR      0x01
#define RS_MODEL_ROBOPET         0x02
#define RS_MODEL_ROBOSAPIEN_V2   0x03
#define RS_MODEL_ROBOREPTILE     0x04
#define RS_MODEL_RSMEDIA         0x05
#define RS_MODEL_ROBOQUAD        0x06
#define RS_MODEL_ROBOBOA         0x07
#define RS_BIT_HIGH    1
#define RS_BIT_LOW     0
// User-configurable parameters
int RSModel = RS_MODEL_ROBOSAPIEN_V2;  // your Robosapien model
boolean RSEcho = true;          // echo commands to host PC?
int irSignalPin = 2;             // Infrared wire connects to this Pin
int ctrlPin = 13;                // Generate the pulses on this Pin
volatile int RSIRCommand;        // Single byte command from IR
volatile int RSBit=9;            // Total bits of data
boolean RSIRCommandReady=false// IR command was received?
int bitTime = 833;               // bit width in microseconds (1/1200 second clock)
#define INTER_CMD_TIME    10     // msecs before sending next command
// Encode a binary '1' or '0' on the wire
void WriteBit(int bit)
{
  digitalWrite(ctrlPin, HIGH);
  delay_ticks((bit == RS_BIT_HIGH) ? 4 : 1);
  digitalWrite(ctrlPin, LOW);
  delay_ticks(1);
}
// Send a byte down the wire (MSB first)
void WriteByte(byte b)
{
    WriteBit( (b & 0x80) == 0x80 );
    WriteBit( (b & 0x40) == 0x40 );
    WriteBit( (b & 0x20) == 0x20 );
    WriteBit( (b & 0x10) == 0x10 );
    WriteBit( (b & 0x08) == 0x08 );
    WriteBit( (b & 0x04) == 0x04 );
    WriteBit( (b & 0x02) == 0x02 );
    WriteBit( (b & 0x01) == 0x01 );
}
// Start each Robosapien commands with a preamble
void WritePreamble()
{
   // Pull down the I/O line for 8 ticks
   digitalWrite(ctrlPin, LOW);
   delay_ticks(8);
   // Send the Robosapien model type (not needed for the orginal Robosapien)
   if (RSModel != RS_MODEL_ROBOSAPIEN_V1) {
     WriteBit( (RSModel & 0x08) == 0x08 );
     WriteBit( (RSModel & 0x04) == 0x04 );
     WriteBit( (RSModel & 0x02) == 0x02 );
     WriteBit( (RSModel & 0x01) == 0x01 );
   }
}
// Add N clock ticks of delay
void delay_ticks(int ticks)
{
  delayMicroseconds(ticks*bitTime);
}
// Receive a bit at a time.
void RSReadCommand()
{
  delayMicroseconds(bitTime + bitTime/4);      // about 1 1/4 bit times
  int bit = digitalRead(irSignalPin);
  if (RSBit==9) { // Must be start of new command
    RSIRCommand=0;
    RSBit=0;
    RSIRCommandReady = false;
  }
  if (RSBit<8) {
    RSIRCommand <<= 1;
    RSIRCommand |= bit;
  }
  RSBit++;
  if (RSBit==9) {
    RSIRCommandReady=true;
  }
}
void RSSendCommand(int opcode)
{
  WritePreamble();
  WriteByte(opcode & 0xFF);
  digitalWrite(ctrlPin, HIGH);
  if (RSEcho) {
    Serial.print(opcode);
  }
  delay(INTER_CMD_TIME);    // buffer time before processing next command
}
// Initialize the serial port, GPIO pins and interrupts
void setup()
{
  Serial.begin(9600);
  pinMode(irSignalPin, INPUT);
  pinMode(ctrlPin, OUTPUT);
  digitalWrite(ctrlPin, HIGH);
  attachInterrupt(0,RSReadCommand,RISING);
}
// Main program loop
void loop()
{
  // If a command was received from the IR remote, relay it to the robot
  if (RSIRCommandReady) {
    RSSendCommand(RSIRCommand);
  // otherwise, check the serial port for new commands sent by computer
  else if (Serial.available() > 0) {
    int opcode = Serial.read();
    RSSendCommand(opcode);
  }
}

And here is the link for robomoco.py

http://borglabs.com/projects/robosapien-v2/using_robomoco

Ill try to post pictures later, but dont feel like tearing him all back apart again atm. 😛

ps, if your having trouble with the code I posted, just grab the code from the site with robomoco, under the part 1 link,  and look for “serial.print(opcode, BYTE” and change it to “serial.print(opcode)”, then it should compile fine.

Short tutorial on Raspberry Pi’s GPIO pins in Python

Here is a short tutorial on how to use the GPIO pins in python and the labeling on them. Alot of people seem confused about this and I figured I’d explain how the labeling works. There’s a third labeling part too, but from what Ive discovered, it’s only used with shell commands and C/C++, not with python.

In python with the RPi.GPIO package, there’s two common numbering systems to describe the pins on the GPIO header, there’s the BCM layout and Board layout.

BCM labeling: The pin labeling from the BCM2835 IC itself (The main Processor), Here’s an example in python:

import time
import RPi.GPIO as GPIO
LED = 4               #Physical pin 7, BCM pin GPIO.4 on the BCM2835
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)

while 1:
GPIO.output(LED, True)
time.sleep(0.5)
GPIO.output(LED, False)
time.sleep(0.5)

Board Labeling: the physical pinout on the GPIO header, and here’s the same example using the same pin but using board layout:

import time
import RPi.GPIO as GPIO
LED = 7               #Physical pin 7, BCM pin GPIO.4 on the BCM2835
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED, GPIO.OUT)

while 1:
GPIO.output(LED, True)
time.sleep(0.5)
GPIO.output(LED, False)
time.sleep(0.5)

This tabel below is the labeling of both the physical board pinout (inside numbers) to the BCM layout (outside labels):

Image

I hope this helps those that are starting out with programming the GPIO pins in python on your Raspberry Pi.

Update: on version 2 raspberry pi boards, GPIO 21 is renamed GPIO 27, so dont think the pin was broken like I did. 😛

Interfacing GPIO pins with python

A few days ago, I found this, which explains everything from the basic blinking of an LED to reading inputs and doing things with those inputs on the raspberry pi.

http://lwk.mjhosting.co.uk/?p=376

PySerial autofind serial port

here’s a small script that I found somewhere online, and heavily modified to auto search for and connect to the first serial port it can find, skipping the built in serial port for last.

import serial
locations=[‘/dev/ttyACM0’, ‘/dev/ttyACM1′,’/dev/ttyACM2’, ‘/dev/ttyACM3′,’/dev/ttyACM4’, ‘/dev/ttyACM5′,’/dev/ttyUSB0′,’/dev/ttyUSB1′,’/dev/ttyUSB2′,’/dev/ttyUSB3’, ‘/dev/ttyUSB4’, ‘/dev/ttyUSB5’, ‘/dev/ttyUSB6’, ‘/dev/ttyUSB7’, ‘/dev/ttyUSB8’, ‘/dev/ttyUSB9’, ‘/dev/ttyUSB10′,’/dev/ttyS0’, ‘/dev/ttyS1’, ‘/dev/ttyS2’, ‘com2’, ‘com3’, ‘com4’, ‘com5’, ‘com6’, ‘com7’, ‘com8’, ‘com9’, ‘com10’, ‘com11’, ‘com12’, ‘com13’, ‘com14’, ‘com15’, ‘com16’, ‘com17’, ‘com18’, ‘com19’, ‘com20’, ‘com21’, ‘com1’, ‘end’]

for device in locations:
try:
serialport = serial.Serial(device, 2400, timeout = 0)
break
except:
if device == ‘end’:
print “Unable to find Serial Port, Please plug in cable or check cable connections.”
exit()