Tom's Main Menu

Physical Computing Home

Intro to Physical Computing Syllabus

Networked Objects

Sustainable Practices

blog

Resources

code, circuits, & construction

my del.icio.us links

 

Multi-byte serial exchanges: a Call-and-Response method

(Max/MSP)

 
This example for Max/MSP shows how to take in a multi-byte string of serial data and process it byte by byte. In this example, the computer sends an "A" to the microcontroller, and the microcontroller sends three bytes in response. Each byte represents a sensor value.

After sending the "A", the computer reads the serial buffer in. It then parses each of the first three bytes received, using a zl object to pack the bytes into a list, and an unpack to separate them into numbers. The zl object waits for three bytes before packing.

As of Max/MSP v. 4.2.1, the serial object returns an odd range of values for a one-byte value (-1 to -128, then 127 to 0). a separate subpatch, osxbyte, converts that range to 0 to 255. It's not needed in Windows.

Note: in Windows, COM1 is porta, COM2 is port b, and so forth. In OSX, my usc-to-serial adaptor, a Keyspan USA19QW, showed up as port c. You may have to find your port.

Thanks to Michael Luck Schneider for help in writing this.

main serial patch:

oxsbyte patch:

Download the main patch here, and the osxbyte patch here.

The microprocessor is reading its sensors, then listening for a byte of data from the Director program. If it gets a byte, it sends out its five sensor readings. If it doesn't, it goes about its other business.

dim adc1Var as byte
dim adc2Var as byte
dim adc3Var as byte
dim inByte as byte
dim gotaByte as boolean
dim inputBuffer(1 To 13) As Byte
dim outputBuffer(1 To 10) As Byte
 
sub main ()
 ' set up serial port:
 call defineCom3(12,11,bx1000_1000)
 call openQueue(inputBuffer, 13)
 call openQueue(outputBuffer, 10)
 call openCom(3,9600,inputBuffer, outputBuffer)

	
 do
  ' read sensors:
  adc1Var = cByte(getADC(13)\4)
  adc2Var = cByte(getADC(14)\4)
  adc3Var = cByte(getADC(15)\4)
  		
  ' read serial data in:
  if statusQueue(inputBuffer) = true then
      call getQueue(inputBuffer, inByte, 1)

     ' if you got the message from director, send out data:
     if inByte = 65 then
       call putQueue(OutputBuffer, adc1Var, 1)
       call putQueue(OutputBuffer, adc2Var, 1)
       call putQueue(OutputBuffer, adc3Var, 1)
     end if
  end if
  loop
end sub

These methods won't work in every situation, and they will need to be modified to fit most situations, but they are a starting point.