✍ diale.org

Webpage of Tiago Charters de Azevedo

Início/Start Arquivo/Archive AdNauseum Notas/Notes Contact me RSS


OpenSCAD mode for emacs

... my hack.

2017/03/01-12:44:47

;;scad.el --- Major mode for editing SCAD files
;;; scad.el --- Major mode for editing SCAD files

;; Original author: Len Trigg <lenbok@gmail.com>
;; Maintainer: This hack is maintained by tca  <tca@diale.org>
;; Created:    20141107
;; Modified:   20141107
;; Keywords:   OpenSCAD, emacs, mode
;; URL:        http://diale.org/scad.el.html
;; Version:    0.1
;; Comments: Added a bunch of skeletons and keymaps.
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2 of the License, or
;; (at your option) any later version.
;; 
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;; 
;; You should have received a copy of the GNU General Public License
;; along with this program; see the file COPYING.  If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;
;;; Commentary:
;;
;; This is a major-mode to implement the SCAD constructs and
;; font-locking for openscad
;;; Code:

;;;###autoload

(add-to-list 'auto-mode-alist '("\\.scad$" . scad-mode))

(defcustom scad-command
  '"~/Downloads/openscad-2014.03/local_inst/bin/openscad"
  "Path to openscad executable"
  :type 'string)

(defcustom scad-keywords
  '("return" "true" "false")
  "SCAD keywords."
  :type 'list
  :group 'scad-font-lock)

(defcustom scad-functions
  '("cos" "acos" "sin" "asin" "tan" "atan" "atan2"  
    "abs" "sign" "rands" "min" "max" 
    "round" "ceil" "floor" 
    "pow" "sqrt" "exp" "log" "ln"
    "str" 
    "lookup" "version" "version_num" "len" "search"
    "dxf_dim" "dxf_cross")
    "SCAD functions."
  :type 'list
  :group 'scad-font-lock)

(defcustom scad-modules
  '("child" "children" "echo" "assign" "for" "intersection_for" "if" 
    "else" "cube" "sphere" "cylinder" "polyhedron" "square" "circle" 
    "polygon" "scale" "rotate" "translate" "mirror" "multmatrix" "union"
    "difference" "intersection" "render" "color" "surface" 
    "dxf_linear_extrude" "linear_extrude" "dxf_rotate_extrude" 
    "rotate_extrude" "import_stl" 
    "import_off" "import_dxf" "import" "group" 
    "projection""minkowski" "glide" "subdiv" "hull" "resize")
    "SCAD modules."
  :type 'list
  :group 'scad-font-lock)

(defcustom scad-operators
  '("+" "-" "*" "/" "%" 
    "&&" "||" "!" 
    "<" "<=" "==" "!=" ">" ">="
    "?" ":" "=")
  "SCAD operators."
  :type 'list
  :group 'scad-font-lock)

;; "C-c letter"  are reserved for users

(defvar scad-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "\t" 'scad-indent-line)
    (define-key map (kbd "C-c C-v") 'scad-open-current-buffer)
    (define-key map (kbd "C-c C-c") 'scad-output-stl)

    ;; s for solid
    (define-key map (kbd "C-c C-s c") 'scad-cylinder)
    (define-key map (kbd "C-c C-s u") 'scad-cube)
    (define-key map (kbd "C-c C-s y") 'scad-cylinder)
    (define-key map (kbd "C-c C-s p") 'scad-polyhedron)

    ;; b for Boolean
    (define-key map (kbd "C-c C-b u") 'scad-union)
    (define-key map (kbd "C-c C-b d") 'scad-difference)
    (define-key map (kbd "C-c C-b i") 'scad-intersection)

    ;; t for transformations
    (define-key map (kbd "C-c C-t t") 'scad-translate)
    (define-key map (kbd "C-c C-t r") 'scad-rotate)
    (define-key map (kbd "C-c C-t s") 'scad-scale)
    (define-key map (kbd "C-c C-t z") 'scad-resize)
    (define-key map (kbd "C-c C-t m") 'scad-mirror)
    (define-key map (kbd "C-c C-t x") 'scad-multmatrix)
    (define-key map (kbd "C-c C-t c") 'scad-color)
    (define-key map (kbd "C-c C-t h") 'scad-hull)
    (define-key map (kbd "C-c C-t k") 'scad-minkowski)

    ;; s for syntax
    (define-key map (kbd "C-c C-s m") 'scad-module)
    (define-key map (kbd "C-c C-s f") 'scad-function)
    (define-key map (kbd "C-c C-s i") 'scad-include)
    (define-key map (kbd "C-c C-s u") 'scad-use)

    ;; m for math
    ;; Is this really needed;)

    ;; f for functions
    (define-key map (kbd "C-c C-f l") 'scad-lookup)
    (define-key map (kbd "C-c C-f r") 'scad-str)
    (define-key map (kbd "C-c C-f c") 'scad-chr)
    (define-key map (kbd "C-c C-f s") 'scad-search)
    (define-key map (kbd "C-c C-f n") 'scad-version-num)
    (define-key map (kbd "C-c C-f n") 'scad-norm )
    (define-key map (kbd "C-c C-f c") 'scad-cross)
    (define-key map (kbd "C-c C-f m") 'scad-parent-module)

    ;; o for others
    (define-key map (kbd "C-c C-o r") 'scad-render)
    (define-key map (kbd "C-c C-o f") 'scad-for)
    (define-key map (kbd "C-c C-o t") 'scad-intersection-for)
    (define-key map (kbd "C-c C-o i") 'scad-if)
    (define-key map (kbd "C-c C-o a") 'scad-assign)
    (define-key map (kbd "C-c C-o m") 'scad-import)
    (define-key map (kbd "C-c C-o x") 'scad-linear-extrude)
    (define-key map (kbd "C-c C-o o") 'scad-rotate-extrude)
    (define-key map (kbd "C-c C-o s") 'scad-surface)
    (define-key map (kbd "C-c C-o p") 'scad-projection)
    (define-key map (kbd "C-c C-o c") 'scad-children)

    ;; p for on the plane
    (define-key map (kbd "C-c C-p c") 'scad-circle)
    (define-key map (kbd "C-c C-p s") 'scad-square)
    (define-key map (kbd "C-c C-p p") 'scad-polygon)

    (define-key map [return] 'newline-and-indent)
    map)
  "Keymap for `scad-mode'.")

(defvar scad-mode-syntax-table
  (let ((st (make-syntax-table)))
    ;; support comment style: “// ...” 
    ;; support comment style: “/* ... */” 
    (modify-syntax-entry ?\/ ". 124b" st)
    (modify-syntax-entry ?\n "> b" st)
    (modify-syntax-entry ?* ". 23" st)

    ;; Extra punctuation
    (modify-syntax-entry ?+  "." st)
    (modify-syntax-entry ?-  "." st)
    (modify-syntax-entry ?%  "." st)
    (modify-syntax-entry ?<  "." st)
    (modify-syntax-entry ?>  "." st)
    (modify-syntax-entry ?&  "." st)
    (modify-syntax-entry ?:  "." st)
    (modify-syntax-entry ?|  "." st)
    (modify-syntax-entry ?=  "." st)
    (modify-syntax-entry ?\;  "." st)

    ;; _ allowed in word (alternatively "_" as symbol constituent?)
    (modify-syntax-entry ?_  "w" st) st)
  "Syntax table for `scad-mode'.")

(defvar scad-keywords-regexp (regexp-opt scad-keywords 'words))
(defvar scad-modules-regexp (regexp-opt scad-modules 'words))
(defvar scad-functions-regexp (regexp-opt scad-functions 'words))
(defvar scad-operators-regexp (regexp-opt scad-operators))

(defvar scad-font-lock-keywords
  `(
    ("\\(module\\|function\\)[ \t]+\\(\\sw+\\)" (1 'font-lock-keyword-face nil) (2 'font-lock-function-name-face nil t))
    ("\\(use\\|include\\)[ \t]*<\\([^>]+\\)>" (1 'font-lock-preprocessor-face nil) (2 'font-lock-type-face nil t))
    ("<\\(\\sw+\\)>" (1 'font-lock-builtin-face nil))
    ("$\\(\\sw+\\)" (1 'font-lock-builtin-face nil))
    (,scad-keywords-regexp . font-lock-keyword-face)
    (,scad-modules-regexp .  font-lock-builtin-face)
    (,scad-functions-regexp .  font-lock-function-name-face)
    ;(,scad-operators-regexp .  font-lock-operator-face) ;; This actually looks pretty ugly
    ;("\\(\\<\\S +\\>\\)\\s *(" 1 font-lock-function-name-face t) ;; Seems to override other stuff (e.g. in comments and builtins)
    )
  "Keyword highlighting specification for `scad-mode'.")

;(defvar scad-imenu-generic-expression ...)
;(defvar scad-outline-regexp ...)

;;;###autoload
(define-derived-mode scad-mode fundamental-mode "SCAD"
  "A major mode for editing SCAD files."
  :syntax-table scad-mode-syntax-table
  (set (make-local-variable 'font-lock-defaults) '(scad-font-lock-keywords))
  (set (make-local-variable 'indent-line-function) 'scad-indent-line)
                                        ;(set (make-local-variable 'imenu-generic-expression) scad-imenu-generic-expression)
                                        ;(set (make-local-variable 'outline-regexp) scad-outline-regexp)
  ;; set comment styles for scad mode
  (set (make-local-variable 'comment-start) "//")
  (set (make-local-variable 'comment-end) "")
  (set (make-local-variable 'block-comment-start) "/*")
  (set (make-local-variable 'block-comment-end) "*/"))


;; From: http://stackoverflow.com/questions/14520073/add-words-for-dynamic-expansion-to-emacs-mode
(defun scad-prime-dabbrev ()
  "Makes a hidden scad-mode buffer containing all the scad keywords, so dabbrev expansion just works."
  (unless (get-buffer " *scad words*")
    (with-current-buffer (get-buffer-create " *scad words*")
      (scad-mode)
      (insert "module function use include")  ; Explicitly add these -- they're not in the below vars
      (insert (mapconcat 'identity (append scad-keywords scad-functions scad-modules) " ")))))

(add-hook 'scad-mode-hook 'scad-prime-dabbrev)

;;; Indentation, based on http://www.emacswiki.org/emacs/download/actionscript-mode-haas-7.0.el

(defun scad-indent-line ()
  "Indent current line of SCAD code."
  (interactive)
  (let ((savep (> (current-column) (current-indentation)))
        (indent (max (scad-calculate-indentation) 0)))
    (if savep
        (save-excursion (indent-line-to indent))
      (indent-line-to indent))))

(defun scad-calculate-indentation ()
  "Return the column to which the current line should be indented."
  (save-excursion
    (scad-maybe-skip-leading-close-delim)
    (let ((pos (point)))
      (beginning-of-line)
      (if (not (search-backward-regexp "[^\n\t\r ]" 1 0))
          0
        (progn
          (scad-maybe-skip-leading-close-delim)
          (+ (current-indentation) (* standard-indent (scad-count-scope-depth (point) pos))))))))

(defun scad-maybe-skip-leading-close-delim ()
  (beginning-of-line)
  (forward-to-indentation 0)
  (if (looking-at "\\s)")
      (forward-char)
    (beginning-of-line)))

(defun scad-face-at-point (pos)
  "Return face descriptor for char at point."
  (plist-get (text-properties-at pos) 'face))

(defun scad-count-scope-depth (rstart rend)
  "Return difference between open and close scope delimeters."
  (save-excursion
    (goto-char rstart)
    (let ((open-count 0)
          (close-count 0)
          opoint)
      (while (and (< (point) rend)
                  (progn (setq opoint (point))
                         (re-search-forward "\\s)\\|\\s(" rend t)))
        (if (= opoint (point))
            (forward-char 1)
          (cond
           ;; Don't count if in string or comment.
           ((scad-face-at-point (- (point) 1)))
           ((looking-back "\\s)")
            (setq close-count (+ close-count 1)))
           ((looking-back "\\s(")
            (setq open-count (+ open-count 1)))
           )))
      (- open-count close-count))))

(defun scad-open-current-buffer ()
  (interactive)
  (call-process scad-command nil 0 nil (buffer-file-name)))

(defun scad-output-stl ()
  (interactive)
  (async-shell-command (concat  scad-command " -o " (buffer-file-name) ".stl "
                              (buffer-file-name))))

;; Skeleton for easy editing
;; 3D
(define-skeleton scad-sphere
  "Insert sphere."
  "Sphere:"
  "sphere:(" str ");")

(define-skeleton scad-cube
  "Insert cube."
  "Cube:"
  "cube:(" str ");")

(define-skeleton scad-cylinder
  "Insert cylinder."
  "Cylinder:"
  "cylinder(" str ");")

(define-skeleton scad-polyhedron
  "Insert polyhedron."
  "Polyhedron:"
  "polyhedron(" str ");")

;; 2D

(define-skeleton scad-circle
  "Insert square."
  "Square:"
  "square(" str ");")

(define-skeleton scad-square
  "Insert square ."
  "Square:"
  "square(" str ");")

(define-skeleton scad-polygon
  "Insert polygon."
  "Polygon:"
  "Polygon(" str ");")

;; Transformations

(define-skeleton scad-translate
  "Insert translate."
  "translate:"
  "translate(" str "){"_"}")

(define-skeleton scad-rotate
  "Insert rotate."
  "rotate:"
  "rotate(" str "){"_"}")

(define-skeleton scad-scale
  "Insert scale."
  "Scale:"
  "scale(" str "){"_"}")

(define-skeleton scad-resize
  "Insert resize."
  "Resize:"
  "resize(" str "){"_"}")

(define-skeleton scad-mirror
  "Insert mirror."
  "Mirror:"
  "mirror(" str "){"_"}")

(define-skeleton scad-multmatrix
  "Insert multmatrix."
  "Multmatrix:"
  "multmatrix:(" str "){"_"}")

(define-skeleton scad-color
  "Insert color."
  "Color:"
  "color(" str "){"_"}")

(define-skeleton scad-hull
  "Insert hull."
  "Hull:"
  "hull(" str "){"_"}")

(define-skeleton scad-minkowski
  "Insert minkowski."
  "Minkowski:"
  "minkowski(){"_"}")

;; Boolean

(define-skeleton scad-union
  "Insert union."
  "Union:"
  "union(){}")

(define-skeleton scad-difference
  "Insert difference."
  "Difference:"
  "difference(){"_"}")

(define-skeleton scad-intersection
  "Insert intersection."
  "Intersection:"
  "intersection(){"_"}")

;; Syntax

(define-skeleton scad-module
  "Insert module."
  "Module:"
  "module " str "("_"){}")

(define-skeleton scad-function
  "Insert function."
  "Function:"
  "function " str "("_"){}")

(define-skeleton scad-include
  "Insert include."
  "Include:"
  "include <" str ".scad>")

(define-skeleton scad-use
  "Insert use."
  "Use:"
  "use <" str ".scad>")

;; Other

(define-skeleton scad-render
  "Insert render."
  "Render:"
  "render(){"_"}")


(define-skeleton scad-translate
  "Insert translate."
  "translate:"
  "translate(" str "){"_"}")

(define-skeleton scad-rotate
  "Insert rotate."
  "rotate:"
  "rotate(" str "){"_"}")

(define-skeleton scad-scale
  "Insert scale."
  "Scale:"
  "scale(" str "){"_"}")

(define-skeleton scad-resize
  "Insert resize."
  "Resize:"
  "resize(" str "){"_"}")

(define-skeleton scad-mirror
  "Insert mirror."
  "Mirror:"
  "mirror(" str "){"_"}")

(define-skeleton scad-multmatrix
  "Insert multmatrix."
  "Multmatrix:"
  "multmatrix:(" str "){"_"}")

(define-skeleton scad-color
  "Insert color."
  "Color:"
  "color(" str "){"_"}")

(define-skeleton scad-hull
  "Insert hull."
  "Hull:"
  "hull(" str "){"_"}")

(define-skeleton scad-minkowski
  "Insert minkowski."
  "Minkowski:"
  "minkowski(){"_"}")

;; Boolean

(define-skeleton scad-union
  "Insert union."
  "Union:"
  "union(){}")

(define-skeleton scad-difference
  "Insert difference."
  "Difference:"
  "difference(){"_"}")

(define-skeleton scad-intersection
  "Insert intersection."
  "Intersection:"
  "intersection(){"_"}")

;; Syntax

(define-skeleton scad-module
  "Insert module."
  "Module:"
  "module " str "("_"){}")

(define-skeleton scad-function
  "Insert function."
  "Function:"
  "function " str "("_"){}")

(define-skeleton scad-include
  "Insert include."
  "Include:"
  "include <" str ".scad>")

(define-skeleton scad-use
  "Insert use."
  "Use:"
  "use <" str ".scad>")

;; Other

(define-skeleton scad-render
  "Insert render."
  "Render:"
  "render(){"_"}")

(define-skeleton scad-for
  "Insert for."
  "For:"
  "for  (i=" str ")" "{" _ "}")
  

;; (define-skeleton scad-
;;   "Insert ."
;;   ":"
;;   "(" str ");")


(provide 'scad)
;;; scad-mode.el ends here

Enjoy.

Etiquetas/Tags: emacs, openscad

Guitar fuzzbox under 3$

Craig Anderton, Popular Electronics, January 1967

2017/02/10-14:03:34

Etiquetas/Tags: fuzz, guitar, audio

Uma aproximação ou conveniência

... dizer que a ciência é uma aproximação da realidade.

2017/01/23-12:52:54

Dizer que as afirmações da ciência não são a verdade mas a uma aproximação à verdade corresponde a atribuir o mesmo estatuto da ciência a outras actividades intelectuais não científicas tais como religiões, crenças, ideologias etc.

Uma afirmação é verdadeira se está de acordo com os factos que descreve, caso contrário é falsa, não há aproximações.

O facto de o mundo poder ser descrito, bem descrito, por uma certa teoria científica nada diz acerca do mundo ou como ele é realmente, mas diz-nos no entanto alguma coisa sobre ele, i.e., que pode ser bem descrito por essa teoria científica e não outra.

Atribuir à ciência o mero estatuto de uma actividade de produção de afirmações aproximadas à verdade legitima outro tipo de afirmações que, com semelhantes argumentos interiores a elas, podem ser tomadas como afirmações verdadeiras, aproximadas ou não, ou mesmo considerar-se possuir-se a totalidade da verdade num sistema formal imaginado.

Na base da toda a visão moderna do mundo reside a ilusão de que as chamadas de leis da natureza são explicações dos fenómenos naturais. Assim ficamos com a ideia de que as leis da natureza são como coisas inatacáveis, da mesma forma o faziam os antigos com Deus e o Destino. E ambos estão certos e errados. Mas os antigos eram mais claros, reconheciam um fim claro, enquanto o sistema moderno torna-a como se tudo estivesse explicado.

Etiquetas/Tags: ciência, verdade, Wittgenstein

Wharfedale 15 woofer

... que tenho aqui em casa

2017/01/14-16:23:40

Finalmente consegui descobrir qual o altifalante que tinha aqui para casa (era do meu avô): um Wharfedale de 15 polegadas. Precisa de um restauro mas o cone e a spider parecem estar em boas condições!

Etiquetas/Tags: Wharfedale, 15'', woofer, W15/cs

Pavilhões acústicos: ideias e construções

... para alunos de design e outros mini engenheiros

2016/12/15-15:24:21

Espiral de Cornut

Paper horns

Impressão 3D

(em actualização)

Etiquetas/Tags: acústica, pavilhões, altifalantes

Vaso 3D

... obtido por rotação em torno de um eixo

2016/11/27-13:47:37

A visualização tridimensional é um ingrediente importante na comunicação e estudo da matemática. Figuras e modelos expressam ideias e antecipam o estabelecimento de um formalismo matemático mais rigoroso. Embora a imaginação visual não substitua o conceito de demonstração dá-nos uma prova visual convincente e permite construir uma intuição sobre os resultados a perseguir e ideias a aprofundar.

A figura seguinte mostra a modelação 3D de uma "jarra" construída através da rotação em torno de um eixo.

Ao contrário do que acontece com outros tipos de software, os softwares usados em matemática permitem de uma forma muito económica a modelação e construção de estruturas não triviais, especificando simplesmente a expressão que as definem.

phi=(1+sqrt(5))/2;

n=100;

r=40;
l=152;
mu=3;
mv=2;
a=.25;
b=a/phi;
lambda=1.5;

nu=.2;
[u,v]=meshgrid([linspace(0,2*pi,n) 2*pi/n],linspace(0,l,n));

x=r*cos(u).*abs(cos(u)).^nu.*(1+a*cos(mu*u+mv*pi*v/l).^5+b*cos(mv*2*pi*v/l));
y=r*sin(u).*abs(sin(u)).^nu.*(1+a*cos(mu*u+mv*phi*pi*v/l).^5+b*cos(mv*2*pi*v/l));
z=v;

simplef2stl("vase.stl",x,y,z)

Depois de impresso o resultado é muito apelativo!

... e não é uma curva.

Função para gerar STL em GNU/Octave

## Author: Tiago Charters de Azevedo 
## Maintainer: Tiago Charters de Azevedo 

## Copyright (c) - 2016 Tiago Charters de Azevedo

## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3, or (at your option)
## any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor,
## Boston, MA 02110-1301, USA.

function simplef2stl(filename,x,y,z)
  fid=fopen(filename,'w');
  title_str=sprintf('%s',datestr(now));
  fprintf(fid,'solid %s\r\n',title_str);

  zmin=min(min(z));
  z=z-zmin;
  nfacets=0;
  nx=size(z,1);
  ny=size(z,2);
  for i=1:nx-1;
    for j=1:ny-1
      p1=[x(i,j) y(i,j) z(i,j)];
      p2=[x(i,j+1) y(i,j+1) z(i,j+1)];
      p3=[x(i+1,j+1) y(i+1,j+1) z(i+1,j+1)];
      writefacet(fid,p1,p2,p3);

      p1=[x(i+1,j+1) y(i+1,j+1) z(i+1,j+1)];
      p2=[x(i+1,j) y(i+1,j) z(i+1,j)];
      p3=[x(i,j) y(i,j) z(i,j)];        
      writefacet(fid,p1,p2,p3);
    end
  end
  fprintf(fid,'endsolid');
  fclose(fid);
end  
  
function num=writefacet(fid,p1,p2,p3)
    n=normal(p1,p2,p3);
    fprintf(fid,'facet normal %.7E %.7E %.7E\r\n',n(1),n(2),n(3));
    fprintf(fid,'outer loop\r\n');        
    fprintf(fid,'vertex %.7E %.7E %.7E\r\n',p1);
    fprintf(fid,'vertex %.7E %.7E %.7E\r\n',p2);
    fprintf(fid,'vertex %.7E %.7E %.7E\r\n',p3);
    fprintf(fid,'endloop\r\n');
    fprintf(fid,'endfacet\r\n');
end

function n=normal(p1,p2,p3)
  v1=p2-p1;
  v2=p3-p1;
  v3=cross(v1,v2);
  n=v3./sumsq(v3);
end

Etiquetas/Tags: 3d, print, reprap, GNU/Octave, STL

OD-11 Carlsson-cube

Omnidirectional, bass reflex type.

2016/11/21-11:53:44

Box volume: 10 litres
Measures: B x W x D: 26 x 26 x 26 cm
Weight: 6 Kg
Principle: Omnidirectional, bass reflex type. Diagonally facing speaker-
elements for frontfacing wall or bookshelf placement or upwardsfacing floor-position
Impedance: 8 ohms
Frequency range: 45-18.000 Hz
Frequency response: 52-15.000 Hz ± 4dB
Crossover frequency: 1800 Hz
Mid-bass: 1pc 6.5 inch 8 ohms Peerless SC165.
Tweeters: 1 pc 5 cm 8 ohms Peerless MT20HFC 

Ref.: http://www.carlssonplanet.com/od11.php

Etiquetas/Tags: hifi, od-11, Carlsson, cube

RepRap Printing on Fabric

testing...

2016/10/25-12:17:49

After seeing the post RepRap Printing on Fabric, I had to try it out.

It works nicely!

Etiquetas/Tags: 3d printing, 3dp, cloth, fabric, reprap

All work and no play...

with Arduino and TVout

2016/07/23-00:01:49

So I've been playing with Arduino and the TVout library... fun, fun, fun!

#include <TVout.h>
#include <TVoutfonts/fontALL.h>
#include "TVOlogo.h"

TVout TV;

void setup(){
  TV.begin(_PAL); // for PAL system
  TV.clear_screen();
}

void loop(){
  TV.select_font(font4x6);
  
  TV.set_cursor(0,0);
  TV.print("All work");

  TV.set_cursor(0,7);
  TV.print("and no play");
  
  TV.set_cursor(0,14);
  TV.print("makes Jack a dull boy...");

  TV.bitmap(0,21,TVOlogo);
}

Refs.:

Happy hacking!

Etiquetas/Tags: Arduino, TVout

Doing a drawbot...

using servos and arduino

2016/06/30-12:53:08

First the results... it really does not work.

Lots of vibrations and errors... but a lot of fun.

Here's the GNU/Octave code to generate the .ino file.

Happy hacking!

clear all

l1=18.5;
l2=20;
d=-15;
n=200;
t=linspace(0,20*pi,n);
x=d+5*cos(t).*exp(-.05*t);
y=5*sin(t).*exp(-.05*t);
alpha(1)=   -4.5980
beta(1)=   4.3070

for i=1:n-1
  aux= newtonsys([alpha(i) beta(i)],[x(i+1) y(i+1)],1e-3,l1,l2);
  
  alpha(i+1)=aux(1);
  beta(i+1)=aux(2);
end


theta1=-alpha*180/pi-180;
theta2=beta*180/pi-180;


## Write to INO
filename="~/Arduino/examples/servo/servo.ino"

comment_str="This is a comment on the begining of the .ino file ;)";
fid=fopen(filename,'w');
fprintf(fid,'/* %s */\n',comment_str);

header_str="\n#include <Servo.h>\n\nServo Servo1;\nServo Servo2;\n\n";
preamble_str="\nvoid setup()\{\n    Servo2.attach(10);\n    Servo1.attach(9);\}\n\nvoid loop(){\n";

fprintf(fid,'%s',header_str);
fprintf(fid,'%s',preamble_str);

for i=1:n
  fprintf(fid,'%s%f%s',"Servo1.write(",theta1(i),");\n");
  fprintf(fid,'%s%f%s',"Servo2.write(",theta2(i),");\n");
  fprintf(fid,'%s',"delay(100);\n");


end
fprintf(fid,'%s',"}");
fclose(fid);

############################################################
figure(1)
clf
hold on
plot(x,y)
u=l1*cos(alpha)+l2*cos(beta);
v=l1*sin(alpha)+l2*sin(beta);
plot(u,v,'r-')

############################################################
figure(2)
clf
hold on
plot(l1*cos(theta1)+l2*cos(theta2),l1*sin(theta2)+l2*cos(theta2),'-')
plot(l2*cos(beta),l2*sin(beta),'r-')
plot(l1*cos(alpha(1)),l1*sin(alpha(1)),'o')

[t' alpha' beta' theta1' theta2']

function Fv=Ffun(x,xpos,l1,l2)
  Fv(1,1)=xpos(1)-l1*cos(x(1))-l2*cos(x(2));
  Fv(2,1)=xpos(2)-l1*sin(x(1))-l2*sin(x(2));
end
function Jv=Jfun(x,l1,l2)
  Jv(1,1)=l1*sin(x(1));
  Jv(1,2)=l2*sin(x(2));
  Jv(2,1)=-l1*cos(x(1));
  Jv(2,2)=-l2*cos(x(2));
end
function x=newtonsys(xo,xpos,tol,l1,l2)
  Niter=1000;
  x=xo';
  delta=eye(length(xo),1);

  i=0;
  while or(i<=Niter, abs(max(delta))>tol)
      Jv=Jfun(x,l1,l2);
      Fv=Ffun(x,xpos,l1,l2);
      delta=-Jv\Fv;
      x=x+delta;
      i=i+1;
  endwhile
end

Etiquetas/Tags: arduino, draw bot, Octave, ino

Palavras chave/keywords: página pessoal, blog

Criado/Created: NaN

Última actualização/Last updated: 01-03-2017 [12:44]


GNU/Emacs

1999-2017 (ç) Tiago Charters de Azevedo

São permitidas cópias textuais parciais/integrais em qualquer meio com/sem alterações desde que se mantenha este aviso.

Verbatim copying and redistribution of this entire page are permitted provided this notice is preserved.