Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

7 Dec 2013

#! shebang for C programs

For testing it is sometimes very tedious to always compile and run the small C programs I use as utilities. So I thought, why not use the shebang for this. After investigating how the shebang mechanism works I figured a small bash script would do the trick.

The following script needs to be somewhere in your $PATH, I call the script "C":

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env bash

filename=$(basename "$1")
filename="${filename%.*}"

# need to compile?
if [ "$1" -nt "/tmp/runcache/$filename" ]; then
 mkdir -p /tmp/runcache/
 # get rid of shebang line in C program and compile it
 tail -n +2 "$1" > /tmp/runcache/$filename.c
 gcc -Wall -std=c99 $CC_OPTS -o \
  /tmp/runcache/$filename \
  /tmp/runcache/$filename.c
fi

# first parameter is the old executable, 
# remove it and poitn to the new one
shift 

/tmp/runcache/$filename "$@"

Once in place, you can add the shebang line "!#/usr/bin/env C" to your C code in the first line, make it executable and run it like a script. Here is our test C program:


1
2
3
4
5
6
7
8
#!/usr/bin/env C 

#include <stdio.h>

int main() {
 printf("Hello World\n");
 return 0;
}

Then run it like this:

$ chmod 700 test.c
$ ./test.c
Hello World
$


22 Apr 2013

V-Tail mixer with low pass filter

/**
PPM V-Tail/elevon mixer

Input pins:
 2: aileron/rudder
 3: elevator

Output pins:
 9: servo left
10: servo right
*/


#include <math.h>
#include <Servo.h>

//#define DEBUG
#define START_OUTPUT_PIN 9
#define LOW_PASS_FILTER 50 // difference must be greater than X at 


int Chan1Interrupt = 0; // pin 2, aileron
int Chan2Interrupt = 1; // pin 3, elevator

unsigned long Chan1_startPulse, Chan2_startPulse;
volatile double Chan1_val, Chan2_val = 1500;
volatile double Chan1_val_last, Chan2_val_last = 1500;
long StartMillis=0;
long FrameCounter=0;

Servo ServoArray[2];

double reverse(double val) {
 return (val-1500) * -1 + 1500;
}

double add(double val1, double val2) {
 double out = (val1 -1500 + val2 -1500) + 1500;
 out = (out < 1000) ? 1000 : out;
 out = (out > 2000) ? 2000 : out;
 return out;
}

void serviceServos(long pFrameCounter) {
 
 // do the v-tail mixing 
 double left  = add(Chan2_val, Chan1_val);
 double right = add(reverse(Chan2_val), Chan1_val);
 
 ServoArray[0].writeMicroseconds(left);
 ServoArray[1].writeMicroseconds(right);
}

void setup() {
 attachInterrupt(Chan1Interrupt, Chan1_begin, RISING);
 attachInterrupt(Chan2Interrupt, Chan2_begin, RISING);
 
 ServoArray[0].attach(START_OUTPUT_PIN+0, 900, 2100); // aileron
 ServoArray[1].attach(START_OUTPUT_PIN+1, 900, 2100); // elevator

 StartMillis = millis();
#ifdef DEBUG
 Serial.begin(115200);
#endif
}

void loop() {
 long LocalMillis;
 long LocalFrameCounter;
 LocalMillis = millis();
 LocalFrameCounter = (LocalMillis - StartMillis) / 20;

 if (LocalFrameCounter > FrameCounter) {
  FrameCounter = LocalFrameCounter;
  serviceServos(FrameCounter);
 }
}

void Chan1_begin() {
 Chan1_startPulse = micros();
 detachInterrupt(Chan1Interrupt);
 attachInterrupt(Chan1Interrupt, Chan1_end, FALLING);
}

void Chan1_end() {
 Chan1_val = micros() - Chan1_startPulse;
 detachInterrupt(Chan1Interrupt);
 attachInterrupt(Chan1Interrupt, Chan1_begin, RISING);
 if (Chan1_val < 1000 || Chan1_val > 2000) {
  Chan1_val = Chan1_val_last;
 } else {
  if ((Chan1_val + LOW_PASS_FILTER) > Chan1_val_last || 
      (Chan1_val - LOW_PASS_FILTER) < Chan1_val_last)
   Chan1_val_last = Chan1_val;
  else
   Chan1_val = Chan1_val_last;
 }
}

void Chan2_begin() {
 Chan2_startPulse = micros();
 detachInterrupt(Chan2Interrupt);
 attachInterrupt(Chan2Interrupt, Chan2_end, FALLING);
}

void Chan2_end() {
 Chan2_val = micros() - Chan2_startPulse;
 detachInterrupt(Chan2Interrupt);
 attachInterrupt(Chan2Interrupt, Chan2_begin, RISING);
 if (Chan2_val < 1000 || Chan2_val > 2000) { 
  Chan2_val = Chan2_val_last;
 } else {
  if ((Chan2_val + LOW_PASS_FILTER) > Chan2_val_last || 
      (Chan2_val - LOW_PASS_FILTER) < Chan2_val_last)
   Chan2_val_last = Chan2_val;
  else
   Chan2_val = Chan2_val_last;
 }
}

21 Apr 2013

Elevon / V-Tail mixer with Arduino Pro Mini 5V



I got this new and and really handy r/c transmitter from multiplex: the SMART SX.



It's really a minimal approach. I have been a fan of multiplex for a long time because they have always been pioneers in their domain. This one is the first quality r/c transmitter with a gamepad layout (there are many technical features other will copy sooner or later but I bought it because of the layout primarily).

However, this being an entry level transmitter it is really limited in functionality. It has all the features a modern transmitter needs to have, configurable through 1 (yes ONE) button!

However, Elevon/Y-tail mixing isn't a feature baked in. I needed an elevon mixer for my new flying wing and couldn't get one quickly. Fortunately I have some unused micro controller boards laying around which just waited for this hack.


A 15$ Arduino Pro mini 5V seemed to be suitable (although overkill, I just needed something in a short time). Using 2 input interrupts  1 timer for the Servo.H library and 2 PWM pins as output, there is still a lot of unused hardware.

Code

/**
PPM V-Tail/elevon mixer

Input pins:
 2: aileron/rudder
 3: elevator

Output pins:
 9: servo left
10: servo right
*/


#include <math.h>
#include <Servo.h>

//#define DEBUG
#define START_OUTPUT_PIN 9

int Chan1Interrupt = 0; // pin 2, aileron
int Chan2Interrupt = 1; // pin 3, elevator

unsigned long Chan1_startPulse, Chan2_startPulse;
volatile double Chan1_val, Chan2_val = 1500;
volatile double Chan1_val_last, Chan2_val_last = 1500;
long StartMillis=0;
long FrameCounter=0;

Servo ServoArray[2];

double reverse(double val) {
 return (val-1500) * -1 + 1500;
}

double add(double val1, double val2) {
 double out = (val1 -1500 + val2 -1500) + 1500;
 out = (out < 1000) ? 1000 : out;
 out = (out > 2000) ? 2000 : out;
 return out;
}

void serviceServos(long pFrameCounter) {
 
 // do the v-tail mixing 
 double left  = add(Chan2_val, Chan1_val);
 double right = add(reverse(Chan2_val), Chan1_val);
 
 ServoArray[0].writeMicroseconds(left);
 ServoArray[1].writeMicroseconds(right);
}

void setup() {
 attachInterrupt(Chan1Interrupt, Chan1_begin, RISING);
 attachInterrupt(Chan2Interrupt, Chan2_begin, RISING);
 
 ServoArray[0].attach(START_OUTPUT_PIN+0, 900, 2100); // aileron
 ServoArray[1].attach(START_OUTPUT_PIN+1, 900, 2100); // elevator

 StartMillis = millis();
#ifdef DEBUG
 Serial.begin(115200);
#endif
}

void loop() {
 long LocalMillis;
 long LocalFrameCounter;
 LocalMillis = millis();
 LocalFrameCounter = (LocalMillis - StartMillis) / 20;

 if (LocalFrameCounter > FrameCounter) {
  FrameCounter = LocalFrameCounter;
  serviceServos(FrameCounter);
 }
}

void Chan1_begin() {
 Chan1_startPulse = micros();
 detachInterrupt(Chan1Interrupt);
 attachInterrupt(Chan1Interrupt, Chan1_end, FALLING);
}

void Chan1_end() {
 Chan1_val = micros() - Chan1_startPulse;
 detachInterrupt(Chan1Interrupt);
 attachInterrupt(Chan1Interrupt, Chan1_begin, RISING);
 if (Chan1_val < 1000 || Chan1_val > 2000) {
  Chan1_val = Chan1_val_last;
 } else {
  Chan1_val_last = Chan1_val;
 }
}

void Chan2_begin() {
 Chan2_startPulse = micros();
 detachInterrupt(Chan2Interrupt);
 attachInterrupt(Chan2Interrupt, Chan2_end, FALLING);
}

void Chan2_end() {
 Chan2_val = micros() - Chan2_startPulse;
 detachInterrupt(Chan2Interrupt);
 attachInterrupt(Chan2Interrupt, Chan2_begin, RISING);
 if (Chan2_val < 1000 || Chan2_val > 2000) { 
  Chan2_val = Chan2_val_last;
 } else {
  Chan2_val_last = Chan2_val;
 }
}

22 Mar 2013

C shared objects exported to python (ctypes)

Some C Projects need a quick extension which is not performance relevant. Sometimes I wish to use python because it is available on all modern *nix systems. Also, programming in python is very efficient.

To solve this I have created a small example project which puts the functionality into a shared object (dll in windows-speak) which can be used from python.

The library:

lib.c
This library contains a simple function which appends the string "->aaa" to an existing string. This is an interesting example since it involves dynamic memory allocation and pointers.


#include <stdlib.h>
#include <string.h>
#include "lib.h"

//int main() {return 0;}

char *append(char* str) {
 //char *n = "";
 char *b = "->aaa";
 char *n = malloc(strlen(str) + strlen(b) + 1);
 n[0] = '\0';
 strcat(n, str);
 strcat(n, b);
 return n;
}


lib.h
char *append(char* str);


test.c
used for testing the the library from C.

#include <stdio.h>
#include "lib.h"

int main(int argc, char* argv[]) {
 printf("%s\n", append(argv[1]));
 return 0;
}

Compiling
#!/usr/bin/env bash
gcc -std=c99 -Wall -c -fPIC lib.c -o lib.o
gcc -std=c99 -Wall -shared -Wl,-soname,libt.so -o libt.so lib.o
gcc -std=c99 -Wall -o test test.c -L. -lt
rm lib.o


pylibt.py
Because python uses dynamic data types we need to give some hints about data types. Also pointers need to be declared.
#!/usr/bin/env python

from ctypes import *

cdll.LoadLibrary("./libt.so")
_libt = CDLL("libt.so")

#def initpylibt():
# pass

def append(s):
 _append = _libt.append
 _append.argtypes = [c_char_p]
 _append.restype = c_char_p
 return _append(s)


test.py
let's use the python module from a script.

#!/usr/bin/env python

import pylibt

ret = pylibt.append("0123456789as dfasdf asdf asdf asdf asf asdf")
print ret


7 Mar 2013

gcc - compile shared library

the Program to compile as shared library

string.h

/** string.h
 *
 * $Id$
 */

#ifndef STINRG_H_
#define STINRG_H_

#ifndef DEFAULT_BLOCKSIZE
 // num. bytes of junks of memory to allocate from the heap
 #define DEFAULT_BLOCKSIZE 128
#endif

#include <stdio.h>
#include <stdlib.h>

/** datatype to hold the character data */
struct string_t {
 int memsize;
 int length;
 char *text;
 int error;
};
typedef struct string_t string;

// function declarations
string str_redfile(FILE *file, int bs);
void str_dump(string *s);
unsigned long str_memsize(string *s);

#endif /* STINRG_H_ */

string.c

/** C example for reading file and allocating memory dynamically.
 *
 * Will read a file from disk while dynamically allocating memory.
 *
 * Example usage: ./exe [file-name]
 *
 * $Id$
 */

#include "string.h"

/** Read file from FILE pointer
 *
 * Reads data from FILE *file and dynamically allocates memory from the heap
 * to store the read data. If memory allocation fails, the returned string
 * struct's member error will equal to 1.
 *
 * If reading the file works, string.error will be 0.
 */
string str_redfile(FILE *file, int bs) {
 int charsize = sizeof(char);
 int charcount = 0;
 int blocksize;
 if (!bs)
  blocksize = DEFAULT_BLOCKSIZE;
 else
  blocksize = bs;
 int memsize = blocksize;
 char *line = (char*) malloc(charsize * (memsize+1));
 char *linep = line;

 string l;
 l.error = 0;
 l.length = 0;
 l.memsize = memsize;
 l.length = charcount;
 l.text = linep;

 while (1) {

  if(charcount > memsize) {
   // reallocate memmory
   memsize = memsize+blocksize;
   char *al = (char*) realloc(linep, charsize * (memsize+1));

   if (al == NULL) {
    fprintf(stderr, "Error, out of memory.\n");
    *line = '\0';
    l.text = linep;
    l.error = 1;
    return l;
   }
  }

  char c = fgetc(file);

  //if (c == '\n' || c == '\r' || c == EOF) {
  if (c == EOF) {
   charcount--;
   break;
  }

  // remember input char
  *line = c;
  *(line++);
  charcount++;
 }

 *line = '\0';
 l.text = linep;
 l.memsize = memsize;
 l.length = charcount;

 return l;
}

/** return allocated memory of a string struct
 */
unsigned long str_memsize(string *s) {
 return sizeof(string) + (s->memsize) + 1;
}

/** print struct string info
 */
void str_dump(string *s) {
 if (s->error == 0) {
  printf("memsize: %d\n", s->memsize);
  printf("length:  %d\n", s->length);
  printf("error:   %d\n", s->error);
  printf("text:    %.*s\n", 10, s->text);
  printf("total:   %lu\n", str_memsize(s));
 } else
  printf("Error: %d.\n", s->error);
}

test.c

/** test shared library
 *
 * an example how to use a shared library in a C program.
 *
 * $Id$
 */

#include "string.h"

/** main entry point
 */
int main(int argc, char **argv) {

 // we need 1 argument, the file name
 if(argc < 2) {
  fprintf(stderr, "Usage: %s [file]\n", argv[0]);
  exit(1);
 }

 // try to open the file
 FILE *f = fopen(argv[1], "r");
 if (f == NULL) {
  fprintf(stderr, "Error: failed to open file: %s\n", argv[1]);
  exit(2);
 }

 // allocate memory for storing the string and read contents
 string l = str_redfile(f, 0);

 // close file
 fclose(f);

 // check if reading worked
 if (l.error != 0) {
  fprintf(stderr, "Error: str_redfile() error: '%d'\n", l.error);
  fclose(f);
  exit(l.error);
 }

 // dump file infos
 str_dump(&l);

 // TODO: deallocate the memory
 // free memory
 //free(l.text);

 exit(EXIT_SUCCESS);
}

compiling the shared library and the test program from a bash:

#!/usr/bin/env bash
#
# gcc, compile a shared object file
#
# This example shows how to compile a shared object for C with gcc on linux. 
# required files: string.c, string.h test.
#
# $Id$

# configuration
bin=test
libname=string
v[0]=1; v[1]=0; v[2]=1;

# dynamic library
rm lib$libname* $bin
gcc -c -fPIC $libname.c -o $libname.o
gcc -shared -Wl,-soname,lib$libname.so -o lib$libname.so $libname.o
# create links for ld
#ln -s lib$libname.so lib$libname.so.${v[0]}
#ln -s lib$libname.so.${v[0]} lib$libname.so.${v[0]}.${v[1]}
#ln -s lib$libname.so.${v[0]}.${v[1]} lib$libname.so.${v[0]}.${v[1]}.${v[2]}

# compile executable
gcc $bin.c -o $bin -L. -l$libname

# run with proper LD_LIBRARY env variable, example:
# $ LD_LIBRARY_PATH=. ./test [path-to-file]

Running the executable. Make the newly compiled library available to ld through an environment variable.

$ LD_LIBRARY_PATH=. ./test [path-to-file]

6 Mar 2013

Reading file with dynamic memmory allocation in C

/*
 Will read a file from disk while dynamically allocating memory.

 Example usage: ./exe [file-name]
 */

#include <stdio.h>
#include <stdlib.h>

typedef struct string_t {
 int memsize;
 int length;
 char *text;
 int error;
};
typedef struct string_t string;

string redfile(FILE *file);
void str_dump(string *s);

string redfile(FILE *file) {
 int charsize = sizeof(char);
 int charcount = 0;
 int blocksize = 10;
 int memsize = blocksize;
 char *line = (char*) malloc(charsize * (memsize+1));
 char *linep = line;

 string l;
 l.error = 0;
 l.length = 0;
 l.memsize = memsize;
 l.length = charcount;
 l.text = linep;

 while (1) {

  if(charcount > memsize) {
   // reallocate memmory
   memsize = memsize+blocksize;
   char *al = realloc(linep, charsize * (memsize+1));

   if (al == NULL) {
    fprintf(stderr, "Error, out of memory.\n");
    *line = '\0';
    l.text = linep;
    l.error = 1;
    return l;
   }
  }

  char c = fgetc(file);

  //if (c == '\n' || c == '\r' || c == EOF) {
  if (c == EOF) {
   charcount--;
   break;
  }

  // remember input char
  *line = c;
  *(line++);
  charcount++;
 }

 *line = '\0';
 l.text = linep;
 l.memsize = memsize;
 l.length = charcount;

 return l;
}

void str_dump(string *s) {
 if (s->error == 0) {
  printf("memsize: %d\n", s->memsize);
  printf("length:  %d\n", s->length);
  printf("error:   %d\n", s->error);
  printf("text:    %s\n", s->text);
  printf("total:   %lu\n", sizeof(*s)+1);
 } else
  printf("Error: %d.\n", s->error);
}

int main(int argc, char **argv) {
 // string l = redfile(stdin);

 if(argc < 2) {
  fprintf(stderr, "Usage: %s [file]\n", argv[0]);
  exit(1);
 }

 FILE *f = fopen(argv[1], "r");
 if (f == NULL) {
  fprintf(stderr, "Error: failed to open file: %s\n", argv[1]);
  exit(2);
 }

 string l = redfile(f);

 if (l.error != 0) {
  fprintf(stderr, "Error: redfile() error: '%d'\n", l.error);
  fclose(f);
  exit(l.error);
 }

 str_dump(&l);

 fclose(f);

 exit(0);
}

24 Feb 2013

Example using getopt from C


// $Id$

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>

struct opt_t {
 char* opt;
 char* arg;
};

int opt_parse(int argc, char *argv[], const char * optstring) {

 //Specifying the expected options
 //The two options l and b expect numbers as argument
 while ((option = getopt(argc, argv, optstring /*"apl:b:"*/)) != -1) {
  switch (option) {
   case 'd':
    printf("Database: %s\n", optarg);
    break;
   default: 
     printf("Huh?"); 
    return EXIT_FAILURE;
  }
 }
 
 return 0;
}

int main(int argc, char** argv) {
 const char* opts = "d:";
 
 int r = opt_parse(argc, argv, opts);
 
 return r;
}

13 Feb 2013

Problems programming ATtiny85 from Arduino IDE

After several successful firmware uploads from the Arduino IDE via Arduino Uno as ISP programmer to an ATtiny85 it suddenly stopped to work.

I have not figured out why this happens, a friend of mine has the same problem and couldn't find what caused it neither.

Long story short, the work around is to use Arduino IDE to compile the sketch and avrdude directly to do the uploading.

Compiling

Compiling code for ATtiny85/45 in Arduino IDE requires that the hardware definitions of these chips are installed in Arduino IDE:

Once the code is compiled it can be found in /tmp/build[0-9]*.tmp/*.hex on a *nix platform (C:\Windows\temp\... probably on windows, check the Arduino IDE manual).

Once the location of the hex file is known, I copy it to a safe place (data in the temp folder are purged occasionally).

Arduino as ISP

I am using Arduino Uno as programmer. For this wot work the arduino must be flashed with an already available sketch called: ArduinoISP (found under Examples).

Once this sketch is uploaded, the Arduino Uno works as In System Programmer and can be hooked up to your ATtiny device. The Arduino Uno is the used as "bridge" between your USB port on the computer and the tiny, as well as power supply.


Uploading

Using avrdude with the following parameters worked out of the box for me on a virgin ATTiny85 from linux:
$ avrdude -P /dev/ttyACM0 -p t85 -c avrisp -b 19200 \
          -v -F -U flash:w:pulse_in.cpp.hex



15 Jan 2013

APM Camera power control & CHDK intervalometer

Finally I made some progress on the r/c camera control. A fairly simple and cheap solution is to solder cables to the power button of a cannon camera. Hook these up to an ATtiny85 (45 would probably do as well). The ATtiny reads a PPM signal from an r/c receiver and switches the camera on or off accordingly.

ATtiny  pin layout:


Schema:


Demo:





ATTiny Code (C++ Arduino):

/**
 * Read PPM signal
 * 
 * Decode r/c receiver PPM servo signal and turn lights on 
 * according to stick position.
 *
 * $Id$
 */

// pin setup
#define PIN_PPM  0
#define PIN_POS1 4

unsigned long duration, lastgood = 0;
int position = 0;

void setup() {
  pinMode(PIN_PPM, INPUT);
  pinMode(PIN_POS1, OUTPUT);
  digitalWrite(PIN_POS1, LOW);
}

void loop() {
  // the length of the pulse (in microseconds) or 0 if no pulse 
  // started before the timeout (unsigned long)
  duration = pulseIn(PIN_PPM, HIGH, 20000); 
  if (duration == 0)
    duration = lastgood;
  else
    lastgood = duration;
  
  position = map(lastgood, 1000, 2000, 0, 1);
  
  if (position > 0)
    digitalWrite(PIN_POS1, HIGH);
  else
    digitalWrite(PIN_POS1, LOW);
}



Intervalometer Code (lua):

--[[
rem 2013-01-13 by Simon Wunderlin, ResearchDrones LLC
@title ResearchDrones Fast Interval
@param a = interval (sec/10)
@default a 10
--]]

function camera_close()
 click "display"
 sleep(1000)
 click "display"
 sleep(1000)
 shut_down()
 sleep(5000)
end

--[[
f = get_usb_power(1)
if f == 1 then camera_close() end 
]]--
--shoot()

repeat
 start = get_tick_count()
 
 press("shoot_half")
 repeat
  sleep(50)
  until get_shooting() == true
 click("shoot_full")
 release("shoot_half")
 
 sleep(a*100 - (get_tick_count() - start))
until ( false )

11 Aug 2012

Reading PPM Signal with arduino

I want to trigger additional logic in an UAV when I flip a 3 position switch on my R/C transmitter. This sketch will decode a PPM signal from an R/C receiver and will turn on two LEDs depending on switch position.

The code compiles for a Sparkfun Pro Micro 16MHz and also on an ATtiny85:


/**
 * Read PPM signal
 * 
 * Decode r/c receiver PPM servo signal and turn lights on 
 * according to servo position.
 *
 * $Id$
 */

// from which pin to read.
#define PIN_PPM   9
#define PIN_POS1 10
#define PIN_POS2 16

unsigned long duration, lastgood = 0;
int position = 0;

void setup() {
  pinMode(PIN_PPM, INPUT);
  pinMode(PIN_POS1, OUTPUT);
  pinMode(PIN_POS2, OUTPUT);
  digitalWrite(PIN_POS1, LOW);
  digitalWrite(PIN_POS2, LOW);
}

void loop() {
  // the length of the pulse (in microseconds) or 0 if no pulse 
  // started before the timeout (unsigned long)
  duration = pulseIn(PIN_PPM, HIGH, 20000); 
  if (duration == 0) {
    duration = lastgood;
  } else {
    lastgood = duration;
  }
  // map ppm values to 0, 1 and 2
  position = map(lastgood, 1000, 2000, 0, 2);
  // 0 == both off, 1 == LED1 on, LED2 off, 2 = both on 
  if (position > 0) {
    digitalWrite(PIN_POS1, HIGH);
  } else {
    digitalWrite(PIN_POS1, LOW);
  }
  if (position > 1) {
    digitalWrite(PIN_POS2, HIGH);
  } else {
    digitalWrite(PIN_POS2, LOW);
  }
}

28 Jun 2012

Compile and Run a C file from wihin gedit

I use gedit to write simple C programs. The External Tools plugin is really helpful for compiling and running them. Here is a simple example to invoke gcc and run the compiled file:

#!/bin/sh

EHOME=`echo $HOME | sed "s/#/\#/"`
DIR=$GEDIT_CURRENT_DOCUMENT_DIR
BASENAME=`echo "$GEDIT_CURRENT_DOCUMENT_NAME" | sed -e 's/\.c$//'`

cd "$GEDIT_CURRENT_DOCUMENT_DIR"
date
gcc -o "$BASENAME" "$GEDIT_CURRENT_DOCUMENT_NAME"

9 May 2012

Programming ATtiny45/ATtiny85 with Arduino

I have found many long winded HOWTOs on doing this, I love mini howtos, here we go:

I am using an Arduino UNO with Arduino IDE 0022.

The Arduino IDE needs some hardware information to support the ATtiny45/ATTiny85. Download the following zip file, create a hardware folder in your sketches folder and unzip it into the newly created hardware folder (you should now have the following folder structure in your sketches folder: hardware/attiny45_85/). Restart the Arduino IDE.

Flash your Arduino with the ArduinoISP sketch (File » Examples » ArduinoISP, compile and upload).

Connect the ATtiny45 or ATtiny85 to your Arduino as shown below:


(use a 10 uF capacitor between reset and ground, - on the capacitor goes to GND).


Pin layout of ATtiny45/ ATtiny85

That's it. Select "Tools » Board » ATtiny45 (w/ Arduino as ISP)" as board and you are good to go. While uploading the Arduino IDE will show the error "avrdude: please define PAGEL and BS2 signals in the configuration file for part ATtiny45". This doesn't have an effect, just disregard it.

To check if it works you may connect a LED from pin0 to GND and upload the following blink sketch (the LED will also flash on activity during MOSI while uploading a sketch).

// Blink for ATtiny45/ATtiny85 

#define PIN_LED 0

void setup() {                
  // initialize the digital pin as an output.
  // Pin 13 has an LED connected on most Arduino boards:
  pinMode(PIN_LED, OUTPUT);     
}

void loop() {
  digitalWrite(PIN_LED, HIGH);   // set the LED on
  delay(1000);              // wait for a second
  digitalWrite(PIN_LED, LOW);    // set the LED off
  delay(1000);              // wait for a second
}

23 Apr 2012

Display HEX and Binary representation of an integer with C

a little example in C on how to display an integer in hex an binary:

/**
 * Name        : bitwise.c
 * Author      : wus
 * Version     : $Id: bitwise.c 13 2012-04-23 15:37:41Z wus $
 * Copyright   : GPL
 * Description : Print an 8-64 bit integer in hex and binary to stdout.
 *
 * NOTE: gcc needs the -lm option enabled to include the math library (must add
 *       -lm after the source file, WTF?)
 * NOTE: compile flags: $ gcc -ofilename filename.c -lm
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>

int int_size = 64;  // num bits of integer

void usage(void) {
 printf("Usage: bitwise <%d bit int>\n\n", int_size);
 printf("Exit codes:\n");
 printf("  2 argument error\n");
 printf("  3 overflow error\n");
}

char dec2hex(int digit) {
 if (digit < 10) return (digit + 48);
 switch(digit) {
  case 10: return 'A';
  case 11: return 'B';
  case 12: return 'C';
  case 13: return 'D';
  case 14: return 'E';
  case 15: return 'F';
 }
 return '*';
}

/**
 * generate binary and hex string from an integer
 *
 * loop bit for bit (MSB) over an integer, generate binary and hex string
 *
 * param num:      the number
 * param result:   max. 64 bits + 7 spaces (pairs by 4 and an ending \0
 * param hex:      hex representation, 8 digits and one \0
 * param int_size: number of bits to represent in the output
 */
void format_bin(uint64_t num, char result[78], char hex[9], int int_size) {

 int pos_bit, pos_string = 0;
 int pos_hex = int_size / 4 - 1;
 int str_size = int_size + (int_size/4 - 1);
 hex[pos_hex] = 0;

 for(pos_bit=0; pos_bit < int_size; pos_bit++, pos_string++) {
  // add spaces
  if (pos_bit % 4 == 0 && pos_bit != 0) {
   result[str_size - 1 - pos_string++] = ' ';
  }

  // check if current bit is set
  int t = ((num & (1L<<pos_bit)) ? 1 : 0);
  result[str_size - 1 - pos_string] = t + 48;
  
  // handle hex
  int pot = pos_bit % 4;

  if (t) {
   switch (pot) {
    case 0: hex[pos_hex] += 1; break;
    case 1: hex[pos_hex] += 2; break;
    case 2: hex[pos_hex] += 4; break;
    case 3: hex[pos_hex] += 8; break;
   }
  }

  // next character
  if (pot == 3) {
   // make sure the int is a character and store it in the
   // result hex string
   hex[pos_hex] = dec2hex(hex[pos_hex]);
   hex[--pos_hex] = 0;
  }
 } // end for loop

 hex[int_size/4] = '\0';
 result[str_size] = '\0';
}

/**
 * generate binary and hex representation of an integer value
 */
int main(int argc, char* argv[]) {

 if (argc != 2) {
  usage();
  exit(2);  
 }

 int arg1 = atoi(argv[1]);
 // check overflow
 if (arg1 > (pow(2, int_size) - 1)) {
  printf("Overflow detected, we can handle max. %d bit integers!\n\n",
         int_size);
  usage();
  exit(3);
 }
 uint8_t input = arg1;
 
 char str[78];
 char hex[9];
 format_bin(input, str, hex, int_size);
 printf("\n0x%s - %s\n", hex, str);

 return EXIT_SUCCESS;
}

gcc math.h WTF!?

#include <math.h> in gcc will not automatically pull in the math implementation only the header. To make a file with this include compile you need to add -lm on the command line (linker option). To make it a bit more convenient, in my case I had to add the option after the source file on the command line.

Example:

$ gcc -omyfile myfile.c -lm

13 Oct 2011

Finally, a three some (74HC595)!

As a follow up to the first tests with the 74HC594 and 74HC595 with Arduino I got some more 595 delivered, finally chaining them together. This example uses the 74HC595 chip.



Code:

First, you need to install (extract) the MM74HC595 library I wrote into your "<\libraries>" folder.

/**
 * Board: Pro Mini 5V
 * 
 * Chained 74HC595 8 bit shift register demo. Knight Rider!
 *
 * $Id: test_74HC595.pde 319 2011-10-13 20:48:10Z wunderlins $
 */

// how many shift registers are we using in serie? (must be >=1)
#define NUM_SHIFT_REGISTERS 3

// include library (must be installed unter <sketches>/libraries/MM74HC595/)
// http://spliffy.freeshell.net/hardware/MM74HC595.zip
#include <MM74HC595.h>

/**
 * Arduino pins:
 * 
 * PIN_SER: is the arduino serial pin
 * PIN_SCK: is the arduino pin for the shift register
 * PIN_RCK: is the arduino pin for the output register
 */
int PIN_SER = 8;  // pin 14 on the 75HC595
int PIN_SCK = 9;  // pin 12 on the 75HC595
int PIN_RCK = 10; // pin 11 on the 75HC595

int i = 0;
int direction = 1; // 1 = L2R, -1 R2L

// shift register instance
MM74HC595 registers(PIN_SER, PIN_SCK, PIN_RCK, NUM_SHIFT_REGISTERS);

// module pins already initialzed
void setup() {;}               

void loop(){
 
 // reset all pins (set to LOW)
 registers.reset();
 
 // set pin(s) to high
 registers.set(i, true);
 
 // activate outputs
 registers.update();
 
 // check if we have to change direction
  if (i+1 == NUM_SHIFT_REGISTERS * 8) {
   direction = -1;
  } else if (i == 0) {
   direction = 1;
  }
  i += direction;

  delay(100);
}


11 Oct 2011

Knight Rider with 74HC594 8 bit shift register

Please note, the next article «Finally a threesome» includes an arduino library for the 74HC595 (not for the 74HC594) and probably obsoletes this post.



As a follow up to the bit shift register (74HC595) example I ordered some more of these. Unfortunately MM74HC594 (Datasheet) were delivered. These chips are a bit more complicated to handle. Here is the same example as in the previous post:


As a byproduct of the above drawing,  I have created a Fritzing part for the 74HC594 chip.


Code:

/**
 * Board: Pro Mini 5V
 * 
 * Chained 74HC595 8 bit shift register demo. Knight Rider!
 *
 * Based on: http://bildr.org/2011/02/74hc595/
 * 
 * $Id: test_74HC595.pde 309 2011-10-13 18:50:44Z wunderlins $
 */

int PIN_SER = 8;   //pin 14 on the 75HC595
int PIN_SCK = 9;  //pin 12 on the 75HC595
int PIN_RCK = 10; //pin 11 on the 75HC595

// how many shift registers are chained? (must be >=1)
#define NUM_SHIFT_REGISTERS 3

// store all LED states in this array. every element of the array stores a 
// binary mask of of 8 pin states (per chip).
uint8_t pins[NUM_SHIFT_REGISTERS];

// reset all chips to 0
void sr_reset() {
 for(int i=0; i<NUM_SHIFT_REGISTERS; i++)
  pins[i] = 0;
}

// set a pin high or low. if you have 1 chip use pins 0-7, if youhave 2 chips
// you might use 0-7, 8-15 as pin numbers. state sets LED on (true) or 
// off (false)
void sr_set(int pin, bool state) {
 
 // check which register to manipulate
 int current = pin / 8;
 int p = pin - current*8;
 
 if (state == true) // set pin to true
  pins[current] |= 1 << p;
 else { // set pin to false
  int tmp = ~pins[current];
  tmp |= 1 << p;
  pins[current] = ~tmp;
 }
 
}

// check if pin is set to high
boolean sr_isset(int pin) {
 int current = pin / 8;
 int p = pin - current*8;
 if ((1 << p) & pins[current])
  return true;
 return false;
}

// move data into shift register and from there into storage at once. make 
// sure to fill the shift pins before acitivating the storage pins.
void sr_update() {
 
 digitalWrite(PIN_SCK, LOW);
 
 // set state
 for(int i=8 * NUM_SHIFT_REGISTERS - 1; i >= 0 ; i--) {
  digitalWrite(PIN_RCK, LOW);
  
  if (sr_isset(i))
   digitalWrite(PIN_SER, HIGH); // ON
  else
   digitalWrite(PIN_SER, LOW); // OFF

  digitalWrite(PIN_RCK, HIGH);
 }
 
 digitalWrite(PIN_SCK, HIGH);
}

void setup(){
  pinMode(PIN_SER, OUTPUT);
  pinMode(PIN_SCK, OUTPUT);
  pinMode(PIN_RCK, OUTPUT);

 // initialize pin state
 sr_reset();
 
}               

int i = 0;
int direction = 1; // 1 = L2R, -1 R2L
void loop(){
 
 sr_reset();
 sr_set(i, true);
 sr_update();
 
  if (i+1 == NUM_SHIFT_REGISTERS * 8) {
   direction = -1;
  } else if (i == 0) {
   direction = 1;
  }
  i += direction;

  delay(100);
}

6 Oct 2011

Knight Rider with 74HC595 8 bit shift register

Please note, the next article «Finally a threesome» includes an arduino library for the 74HC595 (not for the 74HC594) and probably obsoletes this post.





 
/**
 * Board: Pro Mini 5V
 *
 *  $Id: test_74HC595.pde 293 2011-10-06 17:30:05Z wunderlins $
 */

int SER_Pin = 8;   //pin 15 on the 75HC595
int RCLK_Pin = 9;  //pin 12 on the 75HC595
int SRCLK_Pin = 10; //pin 10 on the 75HC595

//How many of the shift registers - change this
#define number_of_74hc595s 1 

#define numOfRegisterPins number_of_74hc595s * 8
boolean registers[numOfRegisterPins];

void setup(){
  pinMode(SER_Pin, OUTPUT);
  pinMode(RCLK_Pin, OUTPUT);
  pinMode(SRCLK_Pin, OUTPUT);

  //reset all register pins
  clearRegisters();
  writeRegisters();
}               

//set all register pins to LOW
void clearRegisters() {
  for(int i = numOfRegisterPins - 1; i >=  0; i--){
     registers[i] = LOW;
  }
} 

//Set and display registers
//Only call AFTER all values are set how you would like (slow otherwise)
int direction = 1; // 1 = L2R, -1 R2L
void writeRegisters(){

  digitalWrite(RCLK_Pin, LOW);

  for(int i = numOfRegisterPins - 1; i >=  0; i--){
    digitalWrite(SRCLK_Pin, LOW);

    int val = registers[i];

    digitalWrite(SER_Pin, val);
    digitalWrite(SRCLK_Pin, HIGH);

  }
  digitalWrite(RCLK_Pin, HIGH);

}

//set an individual pin HIGH or LOW
void setRegisterPin(int index, int value){
  registers[index] = value;
}

int i = 0;
void loop(){
 
 clearRegisters();
 
  setRegisterPin(i, HIGH);
  
  writeRegisters();  //MUST BE CALLED TO DISPLAY CHANGES
  //Only call once after the values are set how you need.
  
  if (i+1 == numOfRegisterPins) {
   direction = -1;
  } else if (i == 0) {
   direction = 1;
  }
  i += direction;

  delay(100);
} 
 
Code example is borrowed from here: http://bildr.org/2011/02/74hc595/

26 Sept 2011

Install maple-ide on 64 bit linux

The maple IDE is only offered as 32Bit java binary/bytecode. On a 64Bit linux with a default java installation maple-ide will refuse to start with the following error:

$ ./maple-ide 
java.lang.UnsatisfiedLinkError: /mnt/aaa/bin/maple-ide-v0.0.12/lib/librxtxSerial.so: /mnt/aaa/bin/maple-ide-v0.0.12/lib/librxtxSerial.so: wrong ELF class: ELFCLASS32 (Possible cause: architecture word width mismatch) thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: /mnt/aaa/bin/maple-ide-v0.0.12/lib/librxtxSerial.so: /mnt/aaa/bin/maple-ide-v0.0.12/lib/librxtxSerial.so: wrong ELF class: ELFCLASS32 (Possible cause: architecture word width mismatch)
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1807)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1732)
    at java.lang.Runtime.loadLibrary0(Runtime.java:823)
    at java.lang.System.loadLibrary(System.java:1028)
    at gnu.io.CommPortIdentifier.(CommPortIdentifier.java:123)
    at processing.app.Editor.populateSerialMenu(Editor.java:795)
    at processing.app.Editor.buildToolsMenu(Editor.java:612)
    at processing.app.Editor.buildMenuBar(Editor.java:413)
    at processing.app.Editor.(Editor.java:187)
    at processing.app.Base.handleOpen(Base.java:608)
    at processing.app.Base.handleOpen(Base.java:573)
    at processing.app.Base.handleNew(Base.java:475)
    at processing.app.Base.(Base.java:245)
    at processing.app.Base.main(Base.java:149)

You will be able to select a folder for your sketches and then the application will crash.

The problem can be solved by installing the 32Bit version of Java (i chose the sun/oracle one):

$ sudo apt-get install ia32-sun-java6-bin

Then modify the startup script maple-ide to point to the appropriate java installation. Adjust JAVA_HOME and the PATH environment variables:

#!/bin/sh
APPDIR="$(dirname -- "${0}")"

cd $APPDIR

# /usr/lib/jvm/ia32-java-6-sun/jre/bin/
export JAVA_HOME=/usr/lib/jvm/ia32-java-6-sun/jre
export PATH=$JAVA_HOME/bin:$PATH

for LIB in \
    java/lib/rt.jar \
    java/lib/tools.jar \
    lib/*.jar \
    ;
do
    CLASSPATH="${CLASSPATH}:${APPDIR}/${LIB}"
done
export CLASSPATH

LD_LIBRARY_PATH=`pwd`/lib:${LD_LIBRARY_PATH}
export LD_LIBRARY_PATH

export PATH="${APPDIR}/java/bin:${PATH}"

java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel processing.app.Base

10 Jun 2011

ArduPilotMega and qGroundControl for testing

ArduPilotMega (APM) is a very capable Auto Pilot solution based on an ATmel2650 micro controller and a powerful and complete software solution for fixed wing, helicopter and multi-copter aircrafts. Various sensor solutions are available and supported (gyro, accelerometer, barometric altimeter, pitot speed, gps, range sensors, telemetry comm, magnetometer, etc.).







qGroundControl lets you control your UAV/drone from software over various communication methods (wifi, bluetooth, GSM, USB, etc.). Communication between UAV and ground control software is achieved with the MAVLink protocol.




I have written a mini howto on how to setup ArduPilotMega and qGroundControl for testing sensor data of APM with qGroundControl with a USB connection.

11 May 2011

Fun with Arduino

Need a simple/small/cheap microprocessor with loads of peripherals (I2C) that is easy to tinker with? Arduino's products might be something for you. The Arduino Uno sports a atmega328 (Atmel 8-bit AVR RISC-based microcontroller) with 1K EEPROM, 2K SRAM and 32 KB Flash Memory.

Many devices can be connected trough I2C. Devices such as 3D gyros, temperature-, humidity-, brightness sensors, external storage as well as a gps receivers.

(c) ardunio.cc


Tools:

Documentation: