Author Archive

Temperatur und Luftfeuchtigkeit messen mit dem Arduino I

Vor ein paar Tagen habe ich mir zwei DHT22 Sensoren bei Watterott bestellt, die sowohl Temperatur als auch Luftfeuchtigkeit mit ausreichender Genauigkeit messen können.

Im ersten Sketch lese ich die Daten aus und gebe sie seriell sowohl auf einem angeschlossenen Sparkfun LCD als auch über die serielle Schnittstelle aus. Zum Auslesen des Sensors gibt es von Adafruit eine Bibliothek, die folgende Seite zeigt auch die Beschaltung: http://learn.adafruit.com/dht/connecting-to-a-dhtxx-sensor

IMG_8173

// Beispielcode, um Temperatur/Luftfeuchtigkeit
// eines DHT22 auf einem Sparkfun SerialLCD auszugeben
 
#include "DHT.h"
#include <SoftwareSerial.h>
 
#define DHTPIN 2     // Pin für den DHT22
SoftwareSerial mySerial(4,3); // SoftwareSerial für das LCD
 
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);
 
void setup() {
  mySerial.begin(9600); // starte LCD Verbindung
  Serial.begin(9600); // starte zus. serielle Verbindung
  delay(500); // wait for display to boot up
 
  mySerial.write(254); // setze Cursor in die erste Zeile
  mySerial.write(128);
 
  mySerial.write("                "); // clear LCD
  mySerial.write("                ");
  delay(500);
  mySerial.write("  DHT22 Sensor");
 
  dht.begin();
}
 
char tempstring[10], humstring[10];
 
void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  delay(5000); // lese alle 5 Sekunden ein
 
  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (isnan(t) || isnan(h)) {
    mySerial.write(254); // move cursor to beginning of first line
    mySerial.write(128);
    mySerial.println("DHT22 nicht gefunden");
  } else {
    mySerial.write(254); // move cursor to beginning of first line
    mySerial.write(128);
    mySerial.write("                "); // clear display
    mySerial.write("                ");
    mySerial.write(254); // move cursor to beginning of first line
    mySerial.write(128); 
    mySerial.print("Luftf: ");  
    mySerial.print(h);
    mySerial.print(" %");      
    Serial.println(h);
    mySerial.write(254); // move cursor to beginning of 2nd line
    mySerial.write(192);
    mySerial.print("Temp: ");  
    mySerial.print(t);
    mySerial.print(" *C");   
    Serial.println(t);
  }
}

Im nächsten Schritt werde ich die Daten per WLAN oder Ethernet in eine Datenbank schreiben.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Pie-Charts mit R und ggplot2

Here’s a simple example how to create a pie-chart (in PDF format) with R’s ggplot2 library.

pdf(file = "g:/test.pdf")
library("ggplot2")

df <- data.frame(
  Legende = c("male", "female", "child"),
  werte = c(20, 20,60)
)

blue <- rgb(26/255, 115/255, 186/255, 1) 
yellow <- rgb(255/255, 219/255, 67/255, 1) 
orange <- rgb(181/255, 75/255, 5/255, 1)

ggplot(df, aes(x = "", y = werte, fill = Legende)) +
	geom_bar(width = 1, stat = "identity") +
  	scale_fill_manual(values =  c(blue, yellow, orange)) +
  	coord_polar("y", start = 0) +
	labs(title = "Ein einfacher Pie-Chart")  +
	xlab("X-Achse") +
	ylab("Y-Achse") 
  
dev.off()

pie1

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Palatino Sans zum 95. Geburtstag von Hermann Zapf

Anlässlich des 95. Geburtstags von Hermann Zapf hat Linotype momentan die Palatino Sans im Angebot. Hier ein Beispiel, wie man sie mit xeLaTeX nutzen kann.

% !TEX TS-program = XeLaTeX
\documentclass[fontsize=12pt,ngerman]{scrartcl}
\usepackage[a4paper]{geometry}
\usepackage{fontspec,xcolor}
 
\usepackage{xkeyval,polyglossia}
\setmainlanguage[spelling=new]{german}
\usepackage{graphicx}
\usepackage{csquotes}
\usepackage{paralist}
\usepackage{blindtext}
 
\setmainfont[ItalicFont={Palatino Sans Com Italic},BoldFont={Palatino Sans Com Bold},%
BoldItalicFont={Palatino Sans Com Bold Italic}]{Palatino Sans Com Regular} 
 
\newfontfamily\light[ItalicFont={Palatino Sans Com Light Italic}]{Palatino Sans Com Light}
 
\newfontfamily\ultralight[ItalicFont={Palatino Sans Com Ultra Light Italic}]{Palatino Sans Com Ultra Light}
 
\newfontface\ultralightarrows{Palatino Sans Com Ultra Light Arrows}
 
\begin{document}
 
\blindtext
 
{\bfseries \blindtext}
 
{\itshape \blindtext}
 
{\itshape \bfseries \blindtext}
 
{\light \blindtext} 
 
{\light\itshape \blindtext} 
 
{\ultralight \blindtext} 
 
{\ultralight\itshape \blindtext} 
 
\end{document}

pala_sans

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

My .emacs file (Org-Mode)

Here’s my .emacs file, from time to time this entry will be updated.

2016-08-17 added „distraction free“ part

2016-01-03 added key assignment for „duplicate line“ command

2015-12-30 added line for UTF-8 default encoding

2015-04-24 added German local for days and months

2014-12-22: latest update: F8 copies current entry to next week/day

2014-07-06: Added code to a) postpone one task and set it to todo for the next week using the key

2014-05-10: Added autoload buffer code

2014-03-30: Added colors for orgmode status

2013-11-17: moved loading the org-file behind setting the orgmode variables.

;; UTF-8 as default encoding
(set-language-environment "UTF-8")

;; Autoload buffers if they were changed outside Emacs
(global-auto-revert-mode t)  

;; ReStructured Text for Emacs
; http://docutils.sourceforge.net/docs/user/emacs.html#introduction
(require 'rst)

;; CCrypt Support
(setq load-path (cons "G:/Programme/emacs-24.3/myLisp/ccrypt" load-path))
(require 'ps-ccrypt "ps-ccrypt.el")


;; distraction-free
;;  https://nickhigham.wordpress.com/2016/01/14/distraction-free-editing-with-emacs/
(scroll-bar-mode 0)    ; Turn off scrollbars.
(tool-bar-mode 0)      ; Turn off toolbars.
(fringe-mode 0)        ; Turn off left and right fringe cols.
(menu-bar-mode 0)      ; Turn off menus.
;; bind fullscreen toggle to f9 key
(global-set-key (kbd "") 'toggle-frame-fullscreen)

;; http://emacs.stackexchange.com/questions/2999/how-to-maximize-my-emacs-frame-on-start-up
;; Start fullscreen (cross-platf)
(add-hook 'window-setup-hook 'toggle-frame-fullscreen t)
; emacs-doctor.com/emacs-strip-tease.html
;; Prevent the cursor from blinking
(blink-cursor-mode 0)
;; Don't use messages that you don't read
(setq initial-scratch-message "")
(setq inhibit-startup-message t)
;; Don't let Emacs hurt your ears
(setq visible-bell t)
(custom-set-faces
  '(default ((t (:background "black" :foreground "darkgrey"))))
  '(fringe ((t (:background "black")))))

;; Do not show welcome screen at startup
(setq inhibit-startup-message t)

;; just answer Emacs' question with 'y' or 'n' instead of 'yes'or 'no'
(defalias 'yes-or-no-p 'y-or-n-p)

;; Load org mode
;; update this line for your setup
(add-to-list 'load-path "G:/Programme/emacs-24.3/myLisp/org-8.2.10/lisp")

;; establish a globally accessible GTD TODO file
(setq org-default-notes-file (expand-file-name "~/Dropbox/central-notes.org"))

;; global key bindings for org mode
;; http://orgmode.org/manual/Activation.html#Activation
(global-set-key "\C-cl" 'org-store-link)
(global-set-key "\C-cc" 'org-capture)
(global-set-key "\C-ca" 'org-agenda)
(global-set-key "\C-cb" 'org-iswitchb)

;; Start Calendar View
(setq calendar-week-start-day 1)


;; http://blog.gmane.org/gmane.emacs.orgmode/day=20140530

(defun tj/copy-entry-to-next-day (); (state)
  (interactive)     ; add interactive to let emacs know to call it interactively
    "Copy entry at point to next parent and change its STATE."
    ; (interactive "sState: ")
    (setq state "POSTPONED")
    (save-excursion
      (save-restriction
        (widen)
        (unless (org-on-heading-p)
          (outline-previous-heading))
        (org-copy-subtree)
        (org-todo state)
        (org-up-heading-safe)
        (org-forward-heading-same-level 1)
        (forward-line)
        (org-yank))))


(global-set-key (kbd "") 'tj/copy-entry-to-next-day)


;; some org mode settings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(setq org-todo-keyword-faces
      '(
        ("TODO" . (:foreground "red" :weight bold))
        ("PROGRESSING" . (:foreground "blue" :weight bold))
        ("FEEDBACK" . (:foreground "brown" :weight bold))
        ("VERIFY" . (:foreground "orange" :weight bold))
        ("POSTPONED" . (:foreground "LightSalmon4" :weight bold)) 
        ("DONE" . (:foreground "MediumSeaGreen" :weight bold)) 
	("DELEGATED" . (:foreground "ForestGreen" :weight bold))      
	("CANCELLED" . (:foreground "goldenrod" :weight bold))
        ))



;; no idea what the following does
(font-lock-add-keywords 'org-mode
  '(("^.*:write:.*$" . font-lock-keyword-face)))

(setq org-agenda-face-for-tagged-lines
   '(("write" . bold)))

;; Locales for Germany

;; see http://www.emacswiki.org/emacs/CalendarLocalization#toc8

(setq calendar-week-start-day 1
calendar-day-name-array ["Sonntag" "Montag" "Dienstag" "Mittwoch" "Donnerstag" "Freitag" "Samstag"]
calendar-month-name-array ["Januar" "Februar" "Maerz" "April" "Mai" "Juni" "Juli" "August" "September" "Oktober" "November" "Dezember"])

;; deprecated, use agenda mode instead
(setq org-tag-alist '(("Montag" . ?1)
                      ("Dienstag" . ?2)
                      ("Mittwoch" . ?3)
                      ("Donnerstag" . ?4)
                      ("Freitag" . ?5)
		      ("Sonnabend" . ?6)
		      ("Sonntag" . ?7)))

;; define some additional status 
;; http://orgmode.org/org.html#TODO-extensions
(setq org-todo-keywords
       '((sequence "TODO" "PROGRESSING" "FEEDBACK" "VERIFY" "POSTPONED" "|" "DELEGATED" "CANCELLED" "DONE")))

;; whenever some entry is set to done, log the timestamp
;; (setq org-log-done 'time)



;; some LaTeX-specific export settings
;; load the latex extensions
; (Require 'org-latex) # deprecated!
(require 'ox-html)
(require 'ox-latex)
(require 'ox-ascii)

; kick out all packages from org-mode's default list
; gives maximum of flexibility
;;(setq org-latex-packages-alist nil)
;;(setq org-latex-default-packages-alist nil)

;; now let's add a few custom class export templates
(add-to-list 'org-latex-classes
          '("koma-article"
	    "\\documentclass{scrartcl}
              \\usepackage[utf8]{inputenc}\n\\usepackage[T1]{fontenc}\n
\\usepackage{hyperref}\n"
             ("\\section{%s}" . "\\section*{%s}")
             ("\\subsection{%s}" . "\\subsection*{%s}")
             ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
             ("\\paragraph{%s}" . "\\paragraph*{%s}")
             ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))

(add-to-list 'org-latex-classes  ;; org-export-latex-classes is deprecated
'("scrlttr"
     "\\documentclass[11pt]{scrlttr2}\n
      \\usepackage[utf8]{inputenc}\n
      \\usepackage[T1]{fontenc}\n
      \\usepackage{xcolor}"
     
     ("\\section{%s}" . "\\section*{%s}")
     ("\\subsection{%s}" . "\\subsection*{%s}")
     ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
     ("\\paragraph{%s}" . "\\paragraph*{%s}")
     ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))


;; load a specific file at startup
(find-file "~/Dropbox/orgmode.org")

;; allow quick search links, here Google
(setq org-link-abbrev-alist 
      '(("google" . "https://www.google.com/search?q=%s")
        ("spiegel" . "http://www.spiegel.de/%s")
	("uwe" . "http://uweziegenhagen.de/?s=%s")))


;; local in a org mode document they can be set using
;; #+LINK: uwe http://uweziegenhagen.de/?s=%s
;; usage after definition: [[uwe:Arduino]]

;; enable python for in-buffer evaluation
;; http://orgmode.org/manual/Languages.html
(org-babel-do-load-languages
 'org-babel-load-languages
 '((python . t)))


;; let's define all python code as safe
(defun my-org-confirm-babel-evaluate (lang body)
(not (string= lang "python")))
(setq org-confirm-babel-evaluate nil)



;; duplicate current line, bind command to Ctrl-d
;; from http://stackoverflow.com/questions/88399/how-do-i-duplicate-a-whole-line-in-emacs
(defun duplicate-line (arg)
  "Duplicate current line, leaving point in lower line."
  (interactive "*p")
  ;; save the point for undo
  (setq buffer-undo-list (cons (point) buffer-undo-list))
  ;; local variables for start and end of line
  (let ((bol (save-excursion (beginning-of-line) (point))) eol)
    (save-excursion
      ;; don't use forward-line for this, because you would have
      ;; to check whether you are at the end of the buffer
      (end-of-line)
      (setq eol (point))
      ;; store the line and disable the recording of undo information
      (let ((line (buffer-substring bol eol))
            (buffer-undo-list t)
            (count arg))
        ;; insert the line arg times
        (while (> count 0)
          (newline)         ;; because there is no newline in 'line'
          (insert line)
          (setq count (1- count)))
        )
      ;; create the undo information
      (setq buffer-undo-list (cons (cons eol (point)) buffer-undo-list)))
    ) ; end-of-let
  ;; put the point in the lowest line and return
  (next-line arg))
(global-set-key "\C-d" 'duplicate-line)


;; load recentfile extension, 2nd menu item in 'file'
(require 'recentf)
(recentf-mode 1)
;; limit to 10 entries
(setq recentf-max-menu-items 10)
;; create global key to access the list
(global-set-key "\C-x\ \C-r" 'recentf-open-files)
(custom-set-variables
 ;; custom-set-variables was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 )
(custom-set-faces
 ;; custom-set-faces was added by Custom.
 ;; If you edit it by hand, you could mess it up, so be careful.
 ;; Your init file should contain only one such instance.
 ;; If there is more than one, they won't work right.
 '(default ((t (:family "Courier New" :foundry "outline" :slant normal :weight normal :height 158 :width normal)))))

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Dynamische Reports mit R

Vor kurzem hat mich jemand gefragt, wie man denn mit R Reports dynamisch gestalten könne. Ausgehend von Erfahrungen, die ich damals beim automatisierten Textsatz eines Konferenzprogramms sammeln konnte, war die Lösung nicht schwer.

Ausgangspunkt ist eine CSV Datei, die über das RSQLite Paket in eine in-memory Datenbank geladen wird. Auf des Basis dieser Datenbank werden dann ein paar SQL-Statements aufgebaut, die dann beliebig ausgewertet werden können.

# read excel table from csv to dataframe
df = read.table("g:/datasource.csv",sep=";",header=TRUE)
 
# set up plot window
par(mfrow = c(3,2))
 
# load SQlite library
library("RSQLite")
 
# create fresh database in memory
db <- dbConnect(SQLite(),dbname=".memory.")
 
# write dataframe to database
dbWriteTable(db, "kpi", df) 
 
# list all tables in db 
dbListTables(db)
 
# get a vector of all departments
departments = dbGetQuery(db, "Select distinct(department) from kpi")
 
 
for(i in 1:nrow(departments)){
	print(paste("Department",departments[i,1],sep=" "))
	statement = paste("Select distinct(manager) from kpi where department='",departments[i,1],"'",sep="")
	# print(statement)
	manager = dbGetQuery(db, statement)
 
	for(j in 1:nrow(manager)){
		print(paste("Manager",manager[j,1],sep=" "))
		statement = paste("Select distinct(employee) from kpi where department='",departments[i,1],"'"," and manager='",manager[j,1],"'",sep="")
		# print(statement)
		employee = dbGetQuery(db, statement)
 
		for(k in 1:nrow(employee)){
			print(paste("Employee",employee[k,1],sep=" "))
			statement = paste("Select kpi1,kpi2,kpi3 from kpi where department='",departments[i,1],"'"," and manager='",manager[j,1],"' and employee='",employee[k,1],"'",sep="")
			# print(statement)
			fulldata_employee = dbGetQuery(db, statement)
			# print(fulldata_employee)
			x <- c(1,2,3)
			plot(x,fulldata_employee,type="l",main=paste(departments[i,1],manager[j,1],employee[k,1],sep=" "))
		}
	}
}
 
dbDisconnect(db)

R

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Kostenlose LaTeX-Referenz von Herbert Voß

Lehmanns hat in Zusammenarbeit mit Herbert Voß eine kostenlose LaTeX-Referenz herausgebracht, die Mitglieder von Dante e.V. mit der nächsten DTK erhalten. Unter http://www.lehmanns.de/page/latexreferenz gibt es das Heft auch als PDF zum kostenlosen Download.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Rolling dice with Python / Würfeln mit Python II

Based on http://uweziegenhagen.de/?p=2741 I created another example, this time the algorithm returns a list of the rolled values.

# for the random selection
from random import choice
# to create the sorted dictionary
import collections
 
def throwDiceList(*args):
	if not args: 
		L = []	
	else:
		L = args[0]
	x = choice(range(1,7))
	L.append(x)
	if x == 6:
		return throwDiceList(L)	
	else:
		return L
 
# little test function
def TestDiceList(n):
	# create a dictionary
	d = {}
	for x in range(0, n):
		wurf = sum(throwDiceList())	
 		# if key is found, just increase its frequency by 1 
		if wurf in d:
			d.update({wurf:d[wurf]+1})
		else:
			# else create new key with initiL frequency 1 
			d.update({wurf:1})
	od = collections.OrderedDict(sorted(d.items()))
	for k, v in od.iteritems(): 
		print k, v
 
TestDiceList(60000)

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Mit Excel führende Leerzeichen entfernen und hinzufügen

Hier ein kurzes Beispiel, wie man mit Excel führende Leerzeichen entfernen und auch wieder hinzufügen kann.

excel_zehn

Sei in B2 die Zahl im Format „drei Ziffern“-„10 Ziffern“:

Dann ermittelt

=WERT(LINKS(B2;FINDEN("-";B2)-1)) die Zahl vor dem Bindestrich.

=WERT(RECHTS(B2;LÄNGE(B2)-FINDEN("-";B2))) die Zahl hinter dem Bindestrich

und

=TEXT(C2;"000") & "-" & TEXT(D2;"0000000000") fügt die Zahl aus beiden Teilen wieder im ursprünglichen Format zusammen.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Spendenquittungen mit LaTeX

Die offizielle Webseite der Financedirektion hält leider keine Formulare in LaTeX vor, daher habe ich diese nachgebaut.

Die Quellen liegen unter http://code.google.com/p/spendenquittungen-mit-latex/, bis Jahresende soll der Code noch vereinfacht und bereinigt werden.

Update: Nach https://github.com/UweZiegenhagen/spendenquittungen-mit-latex umgezogen.

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website

Emacs neuen Dateityp zum Org Mode hinzufügen

Hier eine Zeile, wie man Emacs beibringt, auch *.text Dateien im Org Mode zu öffnen:

(add-to-list 'auto-mode-alist '("\\.text" . org-mode))

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website