Dear users,
From a USB proximity sensor (MB1403 HRUSB-MaxSonar-EZ0 |),
SerialPort in SC receives the following ASCII numbers:
-> 82
-> 48
-> 51
-> 48
-> 48
-> 13
The first and the last number is fixed, and the others are variable from 48 to 57.
I only need the values from the second one to the fifth one.
Converting these series with Code I
~port = SerialPort( "/dev/ttyUSB0", baudrate: 57600, databits: 8, stopbit: 1, parity: 0 );
fork{ 4.do { var received = 6.collect{~port.next.asAscii}; ~val = received[1..4].postln; 4.reciprocal.wait}};
returns the followings:
For example,
[ 0, 3, 0, 0 ]
[ 0, 3, 0, 1 ]
[ 0, 3, 0, 2 ]
[ 0, 3, 0, 3 ]
However, what I need is not these arrays but the numbers such as 300, 301, 302, 303, etc.
I made the following two algorithms to get those numbers:
The first algorithm is as follows:
Code II
~received = [ 1, 5, 0, 8]
~converted1 = (b = ""; ~received.collect{|item| b = b ++ item.asString;}; b.asInteger)
The second algorithm is as follows:
Code III
~received = [ 1, 5, 0, 8]
~converted2 = (~received * [1000,100,10,1]).sum
I think the second algorithm is better than the first one because the second one is simpler and shorter than the first one.
The following code block is the result of combining Code I with each algorithm
(
fork{
4.do {
var received = 6.collect{~port.read.asAscii};
~val = received[1..4].postln;
~converted1 = (b = ""; ~val.collect{|item| b = b ++ item.asString;}; b.asInteger).postln;
~converted2 = (~val.collect{ |val| val.asString.asInteger} * [1000,100,10,1]).sum.postln;
4.reciprocal.wait}};
)
The second algorithm could not be directly combined with Code I, so I used some conversions.
I think it works but would like to know if there would be a more sophisticated way to do this.
The code above seems a bit clumsy.