Accessing AVR GPIOs via bit fields

atmega328

I noticed that the TMS320F2809 examples accessed GPIOs by bits rather than as 32-bit ints. For example, it’s possible to set a GPIO like this on the TMS320F280x:

GpioDataRegs.GPADAT.bit.GPIO12 = 1; // Sets GPIO12 to high.

Normally when working with AVRs, I would set bits like this:

PORTB |= (1<<PB3); // Sets port b, bit 3 to high.

After a bit of tinkering, I came up with this (for AVRs):

portb.bit.b3 = HIGH; // Sets port b, bit 3 to high.

I personally think it looks a bit cleaner, so I’ll probably be using it in the future. If you’re interested in trying it out, you can download a full example here: bitfields.zip.



Side note: It is also possible to access GPIOs as 32-bit ints on the TMS320F280x like this:

GpioDataRegs.GPADAT.all |= (1<<12); // Sets GPIO12 to high.


Edit: Looks like I’m not alone.

Posted in Electronics, Programming | Leave a comment

Arduino 0017 on 64-bit Ubuntu 9.04 and 9.10

Edit: This post isn’t really relevant anymore—Arduino 0018 has a 64 bit binary. Original post follows.
Continue reading

Posted in Electronics, Linux | 1 Comment

Computers are toys, not tools.

Posted in Silly Ideas | Leave a comment

RK4 in Haskell

Ran across this today. It’s a well written implementation of RK4.
4th order Runge-Kutta (RK4) integration in Haskell

Posted in Mathematics, Programming | Leave a comment

Line Segment to Circle Collision/Intersection Detection

Style and Notation

  • All variables are represented in italics except in the diagrams and Python code.
  • Vectors are shown in bold except in the diagrams and Python code.
  • The notation |a| is used to represent the length of a vector named a.

Introduction to the problem

Start by defining a few points (vectors from the world origin):
2

Now, from these points, you can easily calculate two useful values, the segment vector, seg_v (from seg_a to seg_b) and the position of circ_pos relative to seg_a, pt_v.

31

seg_v = seg_bseg_a

pt_v = circ_posseg_a

Closest point to the circle’s center on the segment

The next step is to find the closest point to the circle’s center on the segment (labeled “closest” on the diagram). To do this, we must project pt_v onto seg_v:

4

To project on vector onto another, take the dot product of the vector and the unit vector of the projection target. That is:

|proj\_v| = \textbf{pt\_v} \cdot \frac{\textbf{seg\_v}}{|seg\_v|}

Note that this dot product returns a scalar value (the length of proj_v), not a vector.

We now need to take a small break from the main goal and look into a special case: the ends of the segment. If |proj_v| is less than 0 or greater than |seg_v|, the closest point to circ_pos on the segment will be one of the segment’s endpoints. That is:
if |proj_v| < 0: closest = seg_a
if |proj_v| > |seg_v|: closest = seg_b

Next, calculate the actual proj_v vector, rather than just its length (|proj_v|). To do this, simply multiply by the seg_v unit vector:

\textbf{proj\_v} = |proj\_v| \frac{\textbf{seg\_v}}{|seg\_v|}

The only thing left to do is to convert this into world coordinates (rather than coordinates relative to seg_a) to get the closest point:

closest = seg_a + proj_v

Checking for a intersection

Now that we’ve calculated the closest point on the segment (the variable “closest“), we can check if the circle and segment intersect. To do this, first find the vector from closest to circ_pos:

dist_v = circ_posclosest

If the length of this vector is less than the circle’s radius, the circle and segment are intersecting:
if |dist_v| < circ_rad: They are intersecting
else: They are not intersecting

Collision response

A useful bit of data in collision response is the amount of overlap between two shapes and the direction a shape must be moved in order to resolve the collision. This can be represented as a vector that points in the same direction as dist_v whose length is equal to the difference between circ_rad and |dist_v|.

\textbf{offset} = (circ\_rad - |dist\_v|) \frac{\textbf{dist\_v}}{|dist\_v|}

Python implementation

Here is a Python implementation of everything in this post. For the sake of clarity, I avoided optimizations. vec is assumed to be a fully implemented 2d vector class.

def closest_point_on_seg(seg_a, seg_b, circ_pos):
	seg_v = seg_b - seg_a
	pt_v = circ_pos - seg_a
	if seg_v.len() <= 0:
		raise ValueError, "Invalid segment length"
	seg_v_unit = seg_v / seg_v.len()
	proj = pt_v.dot(seg_v_unit)
	if proj <= 0:
		return seg_a.copy()
	if proj >= seg_v.len():
		return seg_b.copy()
	proj_v = seg_v_unit * proj
	closest = proj_v + seg_a
	return closest
 
def segment_circle(seg_a, seg_b, circ_pos, circ_rad):
	closest = closest_point_on_seg(seg_a, seg_b, circ_pos)
	dist_v = circ_pos - closest
	if dist_v.len() > circ_rad:
		return vec(0, 0)
	if dist_v.len() <= 0:
		raise ValueError, "Circle's center is exactly on segment"
	offset = dist_v / dist_v.len() * (circ_rad - dist_v.len())
	return offset

Similar algorithms

Collisions involving stadiums (a type of rounded rectangle) can be calculated in a similar manner. A stadium is essentially a line segment with a radius.

A stadium-point collision is the same as a segment-circle collision with a circle whose radius is equal to the stadium’s radius.

A stadium-circle collision is the same as a segment-circle collision with a circle whose radius is equal to the sum of the original circle’s radius and the stadium’s radius.

Download

segment_circle.zip – An implementation in Python and Cython.

Conclusion

If you find this post useful or have any questions, please leave a comment.

Posted in Computational Geometry, Mathematics, Physics, Programming | 6 Comments

JavaScript Image Animation

I made a small script to produce an animation with a series of images and JavaScript. I only tested it in Firefox 3, but I don’t see any reason why it wouldn’t work in other browsers.

Try it: http://doswa.com/projects/animate/
Download it: http://doswa.com/projects/animate/animate.zip

http://trac.sagemath.org/sage_trac/ticket/1483 inspired me to make this, since the sagenb.org server doesn’t have ImageMagick installed.

Posted in Programming | Leave a comment

PHPNotify: Debug Notifications From PHP

This is a little program to help debug AJAX (or anything else) from PHP.

PHP Debug Notification

Read the README file to instructions on setting it up on Ubuntu. Note that you must first install python-notify through apt-get for this to work correctly.

Download PHPNotify

If the function name notify() conflicts with any of your functions, you can change it on lines 2 and 3 of prepend.php

Posted in Programming | Leave a comment

Improved RK4 Implementation

Damped harmonic motion

This is a Python implementation of the RK4 numerical integrator that works with differential functions of all orders. That is, any function in the form F(x, y, y’, y”, …, y^{(n)}).

If you’re new to numerical integration or even RK4 integration, please read my other post first. It’s easier to understand because it’s a less generalized function.

def rk4(t0, h, s0, f):
	"""RK4 implementation.
	t = current value of the independent variable
	h = amount to increase the independent variable (step size)
	s0 = initial state as a list. ex.: [initial_position, initial_velocity]
	f = function(state, t) to integrate"""
	r = range(len(s0))
	s1 = s0 + [f(t0, s0)]
	s2 = [s0[i] + 0.5*s1[i+1]*h for i in r]
	s2 += [f(t0+0.5*h, s2)]
	s3 = [s0[i] + 0.5*s2[i+1]*h for i in r]
	s3 += [f(t0+0.5*h, s3)]
	s4 = [s0[i] + s3[i+1]*h for i in r]
	s4 += [f(t0+h, s4)]
	return t+h, [s0[i] + (s1[i+1] + 2*(s2[i+1]+s3[i+1]) + s4[i+1])*h/6.0 for i in r]

An example usage of this function is:

def damped_spring_accel(t, state):
	x = state[0]
	v = state[1]
	stiffness = 1
	damping = 0.005
	return -stiffness*x - damping*v
 
t = 0
h = 1/40.0
s = [50, 5]
 
while t<100:
	t, s = rk4(t, h, s, damped_spring_accel)
print "Final state: t=%.2f x=%.2f v=%.2f"%(t,s[0],s[1])

On a side note, I recently found out about Sage (sagemath.org and sagenb.org). Its plotting capabilities and convenient mathematical notation are especially useful. Plus, it uses Python!

Posted in Mathematics, Physics, Programming | Leave a comment

Chain

I made a little Processing sketch based on the same physics as JavaScript physics.

Screenshot of "Chain"

(View the full post to try it out.)

Continue reading

Posted in Physics, Programming | 2 Comments

JavaScript physics

I made a very basic physics demo in JavaScript to practice using the MooTools library. It uses Verlet integration as outlined in Thomas Jakobsen’s paper.

To try out the demo, go to http://doswa.com/projects/physics_js/

Chain of particles attached by joints

Chain of particles attached by joints

Posted in Physics, Programming | 6 Comments