Nov 3, 2011. (translation
of a prev) Ok Alex - this is a situation – the
magnetometer – yesterday (all my troubles seemed so far away…) got from it
accuracy 0.3 degree with capability to increase accuracy to any desired
precision (first luck in last month). For sure in the magnetometer exists error
related to a different measurements on different axis, but this error can be
corrected by calibration, on big paper sheet I just marked angles – taped
magnetometer to a wooden cube (yes, I am still playing with a wooden cubes – the
are not magnetic) with long aluminum ruler, do measurement on each axis and
corrections hammered directly into a (flash memory) table.
Magnetometer allowed to confirm (surprise!) latitude of aVancouver– yesterday on
my uneven table 18.1 degrees matched perfectly (angle btw horizon and direction
of a magnetic field’s vector).
Model of a (earth) magnetic field is simple – some cos() – sin() functions and
somewhere (already forget where – in saved spreadsheet) something divided in
half. Loaded yesterday (year 1977) FORTRAN’s programs by Nikolai Tzigankov. He
made nice model of Earth magnetic field including influence of a solar wind on
far distances from the earth. Needs to convert code to C, and adapt it to my
simulator/tra-calculator. This for sure will take a time (no less a week),
conversion takes no longer then hour(s), but needs to be careful with default
names of integer/float variables, and mostly time spend on each line
verification.
About “gyro navigation device” == “my shame” == “not finished” – one week ago
understood what needs to do (or may be just foolish-ing myself that understood)
– after magnetometer calibrations and implementing (magnetic) model plan-b for
software == 2 second on a orbit == 16 km == vector of a magnetic field can
change 0.3 degree – the same error will be in the magnetometer – for one second
confirmed error is 0.3 (for 2 seconds it will be 0.15-0.2 degree ), then gyro’s
readings corrected by temperature calibration, that will give: (a) gyro angles,
(b) magnetometers angles, (c) difference in angles by gyro, (d) difference in
angles by magnetometer. (a) + (b) flying independently against each other, but
if (d) is less 0.3 on all axis then (c) is a correction’s value. On my
microprocessor with 500 bytes can be perfectly implemented (c) and (d) without
losing single bit – 2000 readings == 32K, dividing (like in a school) by
logarithms and arctan(sqrt()) from Bradis table (school’s technology proved
faster 100 times). Correction on magnetometer axis’s readings is in flash table
too. I think it can be fit into 1MB (1.20$). if (not) then 1.81$ (4MB) will be
suitable;
Difference in gyro implementation for rover – instead of a magnetometer it will
be accelerometer – all software is the same.
Difference in gyro implementation for a ground station == zero (it is possible
to use magnetometer + gyro + accelerometer to demonstrate effective trick ==
detection of earth rotation with a device totally not capable to so – trick will
be nice but it is extra == does not worth spend time on it).
I thought that I was loosing time (and time is not my friend for today), but
after careful examination Boris Chertok’s book I found that story about Luna9
has had similar problems/questions – 1 second (1/60 degree) error == 200km error
on the moon, gyro, not enough power for a gyro, burned devices at tests, power
station does not work, absence of telemetry out of a ground stations,
orientation using sun-earth-moon, gyro does not get enough time to reach
precision because of a power limitation, earth’s image was on a corner of
sensor, failed deadlines, lost money and etc. One of a sample “bug” reported by
Boris – after lost probe was found that one department (hundreds of people
assigned to do trajectory calculation) understood “clockwise” direction totally
opposite the understanding by another department. Only 14th attempt was
successful.
Oct 25, 2011..Саня,
докладаю - ситуевина значит такая – магнитометр == позавчера - получил от него
наконецто точность в 0.3 градуса - могу теперь эту точность повышать практически
до бесконечного нуля - в магнитометре конечно присутствует ошибка связанная с
неравномерностью замера силы магнитного поля (полля!) по осям – но эту ошибку
приготовился исправлять с помощью калибровки - на листе бумаги нарисовал углы -
прискотчил прибор к детскому деревянному кубику с люминевой линейкой, замеряю по
трем осям и прямиком в таблицу.
Магнитометр позволил определить широту Ванкувера по наклону магнитного поля -
вчера для моего колченогого стола 18.1 градус совпали прекрасно.
Модель магнитного поля простая - синус - косинус и уж непомню где, но пополам .
Загрузил вчера 1977 года фортрановские программы Николая Циганкова - он сделал
достаточно точную модель магнитного поля земли - включая солнечный ветер на
больших расстояниях от земли. Нужно будет переводить код в Си для моделирования
- займет конечно временя - не меньше недели.
По поводу гироскопа - незакончил - неделю назад понял что нужно делать (или
думаю что понял)- после проверок точности магнитометра буду с софтвером так - 2
секунды полета == 16 км - за две секунды магнитное поле уйдет на 0.3 градуса -
та же точность будет у магнитометра - за одну секунду 0.3, (за две будет гдето
0.15-0.2) - т.е. порог замера. Затем гироскоп считывает по уже существующей
температурной калибровке и получаю- (а) гироскоповские углы (бэ)
магнетометоровские углы (цэ) гиро за 2 секунды (дэ) магнитометр за две сукунды -
(а) и (бэ) плывут друг от друга как труба им на душу положит. Но если
магнитометр покажет (дэ) меньше 0.3 по всем осям - значит (це) это ошибка -
которую и принимаем в какчестве корректировки. На своем микрочипе в 500 байов
памяти прекрасно могу сделать (цэ) и (дэ) плавющими без потери точности -2000
замеров == всего лишь 32К - деление как в школе по логарифмам - арктангенс из
квадратного корня по таблице брадиса (разов 100 быстрее) - коррекция осей
магнитометра в ней же - даже думаю в доллар 20 умесчюсь (1МБ), если нет - то
доллар 81 пойдет (4МБ). Может придется делать температурную калибровку гироскопа
по каждой оси отдельно (перпендикулярно земле).
Разница в гироскопе для луного трактора - вместо магнитометра беру акселерометр
и весь софтвер тот же. Разница в гироскопе для наземной станции – никакой
(моожно конечно испоользовать магнитометр для эффектного фокуса –
демонстрировать вращение земли на обрудовании неспособном такое вращение
детектировать – но это лишнее). Думал что теряю вермя - затем заглянул в книгу
Бориса Чертока – все теже мои проблемы - гироскоп - его питание – спалили прибор
при тестирвании - отсутствие телеметрии вне наземной станции - ориентировка по
солнцу земле луне - гироскопу дали недостаточно времени на раскрутку, земля
попала в край картинки. С четырнадцатого раза только удалось все правильно
сделать.
Oct 11, 2011.
Fiasco with Gyro. Hope with magneto sensor
Testing gyro was calibrated for range of temperatures, calibrating values 64K of
3x16-bit words was stored in memory. Gyro has fixed in stable position with X
axe oriented to a North Star, Y to the West and Z orthogonal to X-Y forward to
the Earth’s rotation axe. Drift of a zero was in a range of 5 degree per 256sec
(4 minutes). Sensor was forced to max possible sensitivity (undocumented future
in ITG-3200, but it gives 1/115=0.009 degree per sec – it still require 10
better sensitivity to detect earth rotation). Sensor set to 296 samples per sec
(microprocessor is slow – needs to be at least 32MHz).
Zero drift was random (range from 0.01 – 5.0 degree per 4 minutes) and not
depend of a derivative of a temperature. Drift was related to an orientation of
a gyro, and on a previous gyro’s readings (possible that factory calibration
gives drift).
Such drift is totally not acceptable for navigation, needs to eliminate error
first.
On The Earth or on The Moon it is possible to do this by reading accelerometer
and magnetic sensor orientation. Field of gravity is stable on the Earth and the
Moon, and magneto sensor readings on the Earth are stable too (for sure to some
extend). Reading from accelerometer gives absolute reading. Flying average from
accelerometer can give good indication of an absence or existence of rotation
and can allow to exterminate gyro’s zero drift.
Normally this is done by Kalman filter, it assuming that absolute direction is
for a gravity field and based on that assumption correction to gyro’s readings
(speed of a rotation) can be done. Kalman filter works good when noisy
measurements done for predictable object. It is nice and well known approach,
source code available for such filters including combination of 3-x
accelerometer and 3-x magneto sensor. But such approach is not working on the
low Earth orbit.
Hope is for a magneto sensors – first needs to calculate flying average of a 3D
magnetic field orientation. If flying average during 2 sec (500 samples) is not
in moving than current drift of a gyro assumed as a zero. Then time measured for
a slowest changes (derivative of a orientation) gives point on a orbit when
satellite crossed equator. Two times btw crossing the equator can give Keplers
elements of a orbit. Checking point will be apogee and perigee – direction of a
magnetic field at those two points must achieve maximum of a derivative of a
direction of a magnetic field. Current position of a magnetic poles will give
offset for a final Kepler position’s calculations (offsets unlikely will be
known until reaching the orbit).
To fire engine at precision direction offsets of a targeting magnetic fields
series of magentic sensor orientations can be downloaded to onboard microchip
and verified during 15-20 minutes before engine’s ignition. This will require
8Mb data transfer from ground station 1-2 orbits prior engines firing. Less
precision will require for antenna orientation to support such data transfer
session. The same approach but with accelerometer can be done for orientation
antenna on the Moon surface. For testing magnetic sensors approach can be used
rotated magnet in shielded camera, different plane rotation gives simulation a
different inclination of the orbit.
Oct 3, 2011.
Power Plant.
Solar panels combined in 4 groups. 4 high capacitance capacitors can be charged
by any solar panel’s groups . To control such process require 16 pins for a
control. Then 4 charged capacitors can give power to 4 main users of a power –
(a) backup micropocessor and main electronic including main computer;
(b) backup communication;
(c) main communication amplifiers;
(d) orientation stepper motors/ 2.4GHz antenna deployment.
This power distribution require another 16 pins.
Power source for main communication amplifier controls by pins on a STM_BT
microprocessor. Power source for stepper motors controls by STM_SM
microprocessor. Power source for a main electronics controls by STM_MEM
microprocessor.
Assumed 3 different mode of power operation.
- Initially first capacitor gives power to STM_MEM module. When it powered up it
can monitor state of any 4 capacitors and switch itself power source to any of
it. At this point all onboard electronics and users are switched off.
- Then at a time when it is enough power accumulated by power plant STM_MEM can
go to second mode - powered backup communication module, gyro module, camera
module, stepper motors/orientation module, main communication module. Each of
the modules on a request from command stream from STM_MEM can initiate backup
communication, make a picture, store it in STM_MEM flash memory.
- All power mode can be initiated from this moment – STM_MEM can power main
processor module (80-90 mA 3.3 V). From this point of a time main processor
takes care of all control. Main processor can prepare sequence of a commands and
stored it back to STM_MEM module and can send a request to power down itself to
save power in orientation stage and backup communication time. Main computer has
to be powered on for a communication session with a ground station, session time
window is 5 minutes.
Goals for a test flight are: see ref.
Sep 17, 2011. Supporting commands for transport layer reduced to 3:
1) <unit>~<unit>
serial communication loop is functional.
2) <unit>=XCY<unit> Where:
X
– unit to retransmit data
C – command to retransmit
Y == ‘I’ – retransmit output
from com to I2C
== ‘C’ – retransmit output from I2C to com
== ‘i’ - I2C output
expected to be processed inside unit
In unit allocated 3 queue – One for serial
input, another for I2C input, and third for output (output can be serial or I2C,
but output queue is only one). Command “=XCI” force input from serial to be
transmitted to unit ‘X’ with command ‘C’ over I2C line. Command “=XCc” force
input from I2C to be transmitted over serial output to unit ‘X’ with command
‘C’. CMD ‘C’ can be set as ‘ ‘ (space) this will skip inserting command into a
retransmission. The same correct for a ‘X’ unit address for retransmission –
setting ‘ ‘ (space) will force retransmit but without sending unit address. This
is convenient to retransmit data from memory storage over I2C to any unit. Also
setting X =’ ‘ and C = ‘ ‘, useful to accept stream from a file on memory
storage as a command stream. Stream from serial (like camera data) can be
processed as a command or as not command stream. “=XCy” command take effect
after finishing process of a CMD stream of ether from serial or I2C. Y == ‘i’
placed for convenience – normally unit commands can manipulate flag
I2CReplyExpected and I2CReplyCMD for process responses (read operation) from I2C
devices.
3) <unit> ‘<’ <I2Caddr><data>’@’
or:
<unit> ‘<’ <I2Caddr><data><unit> or:
<unit>‘<’ <I2Caddr><data> ‘>’
<bytes-to-read>'@' or:
<unit> ‘<’ <I2Caddr>
<data> ‘>’<bytes-to-read><unit>
When received this command (from I2C or serial input) this force
retransmit data over I2C to device with I2Caddr. Placing ‘>’ at the end of the
command with force I2C set Stop-Start condition and read response data from I2C
device.
Unit processing individual commands can insert sequence ‘<’ to work with
I2C device. For doing this needs to call the same function ProcessCMD.
For
command/stream handling used 3 callback functions.
unsigned char
CallBkComm(void) // return 1 == process queue;
// 0 == do not process;
// 2 = do
not process and finish process
// 3 == process and finish internal process
Function called in a serial->I2C retransmit state each time before processing
bytes from input queues. Return code allows specify end conditions for
retransmission. In case 0 function needs to pop queue byte by itself.
unsigned
char CallBkI2C(void) // return 1 == process queue;
// 0 == do not process;
// 2
= do not process and finish process
// 3 == process and finish internal process
With the same logic for handling retransmit conditions I2C -> serial.
unsigned
char CallBkMain(void) // 0 = do continue; 1 = process queues
This function calls
each time in a loop of processing both input queues. I2C queue has priority over
serial.
Timer / clock layer:
Timer / clock to measure correct time inside unit – it
has 5 bytes
unsigned char TMR130;
unsigned char TMR1SEC;
unsigned char TMR1MIN;
unsigned char TMR1HOUR;
unsigned char TMR1DAY;
Clock based on 8Mhz internal
oscillator and it gives around 30 interrupts per second, seconds accuracy depend
only on a stability of a internal oscillator. 29 counts of a 1/30 of a second
different from last count – last count adjusted to properly set seconds. For
synchronization of a timer command is:
‘T’<Day<hour><min><sec><adjust1>
Next MCR will be set clock to adjusted value. Setting any of day/min/hh/sec
as a (space) will skip adjusting corresponded parameter.
Second timer can be
used for setting any timers events – CallBkMain can be used to check firing
timer conditions via Timer0Fired flag. ‘t’ prescaler timeout can set both
prescaler and timeout value.
Source code organization for units:
1.
For retransmission serial->I2C, I2C -> serial, code for individual unit can be
placed in call back functions for handling retransmissions.
2. For out of queue
processing and for timer related events code for individual unit can be laced in
Main Call Back function.
3. For processing stream out of CMD, code can be placed
in a section before commc3.h include.
4. For processing executing prioritized
CMD execution, code can be placed before commc4.h include.
5. For processing CMD
normally, code can be placed after commc4.h include (till end of a function
ProcessCMD).
Design considerations:
1. Each unit can accept command from each
unit. Each command can produce commands for any unit. Functionality of each unit
independent from other unit. Stream of a commands traveling over serial and I2C
support functionality of a vehicle and craft. Functionality of each unit for
craft should be used for vehicle.
2. Protocol layers separated into a modules
and can be included in individual unit’s source code by include statement (not
library).
3. Debugging of a code has to be done over simulators as much as
possible.
4. Debugging of a code out of simulator has to be done by LD
indicators with traps to switch LED on-off. This make debugging process more
complicated but force to keep all code "in-head".
5. Encouraged to use
“goto” operators – this gives a real binary size savings (50%). Saving the size
can give advantage to place two version of the same software in the same unit
and quickly switch use of not damaged part of a binary.
6. For each individual
unit must be accomplished testing serial sequence with verification expected
output.
7. This is not a “good” design according modern technique software
practice. All modern recommendations about software design was analyzed and
accepted as not suitable for critical missions like space flight.
see download page for source code
Camera unit
commands (module STM_CM.C controls available Jpeg camera):
“R” – reset camera
“P” – take picture
“G” – transfer image file serial->I2C
“B” – picture size
640x480
“M” – picture size 320x240
“S” – picture size 160x120 0x76 – responses
from camera
Format of transferring file <0x76> <length-of-the-file-4-bytes><jpeg stream>
Memory storage unit commands (module
STM_MEM.C controls OpenLog flash memory
storage);
“S” set file name for a storage
“G” prepare to get file from any unit
“O” output file to any unit
“E” executes file as a command stream
0x76 store
stream from I2C to memory unit
Gyro control and stepper’s motor units (for now
they are the same unit, module STM_GYRO.C)
“t” – set percaler and timer
“w” –
wait for timer’s timeout
“s” set bits control on stepper motor
“p” – plus step
“m” – minus step
“g” – hold Gyro position X Y Z
“G” – hold Gyro position X Y Z
with delta offset DX, DY, DZ, in N steps with delay btw steps T
“l” – learn
response on a step of a stepper motor.
Sep 12, 2011.
Protocol supporting commands (I2C multimaster, com as a loop):
=X
- reply to unit
!X
- reply CMD to unit
~
- com loop is working
"<"<I2CAddr><DATA>@ or:
"<" <I2Caddr><data> <unit> - for transfer data to <I2CAddr>
via I2C
"<" <I2Caddr><data>">"L@ or:
"<"<I2Caddr><data>">"L<unit> - where L is a
length data to read – transfer data to via I2C and wait for reply from
the I2C unit
^ - retransmit reply from com to I2C
% - stop retransmit reply
from com to I2C
+ - starts to treat everything from a com as a CMD
- - stop
to treat everything from a com as a CMD
For camera CMD:
'B' - big picture 640
480
'M' - medium picture 320 240
'S' - medium picture 160 120
0x76 - this will
be response from camera
'R' - reset camera
'P' - take picture
'G' - get jpeg
picture
Testing source code for camera on PC : cm_test.cpp,
cm_test.h,
cm_test.rc,
cm_test.sln,
cm_test.vcxproj,
Resource.h,
stdafx.cpp,
stdafx.h,
targetver.h
Camera module source code in progress: commc0.h,
commc1.h, commc2.h,
commc3.h, commc4.h,
commc5.h, commc6.h,
commc7.h, serial.txt,
STM_CM.c,
STM_CM.mcp,
STM_CM.mcw
Testing source code for Gyro on PC: gyro_test.cpp,
gyro_test.h,
gyro_test.rc,
gyro_test.sln,
gyro_test.vcxproj,
Resource.h,
stdafx.cpp,
stdafx.h,
targetver.h.
Gyro module source code in progress:
STM_GYRO.c,
STM_GYRO.mcp,
STM_GYRO.mcw,
serial.txt
Sept 6, 2011
- Communication protocol changes. (Source code in progress). Unit
must be capable to support serial and I2C multi-master protocol in different
configuration. Unit interfacing “serial device” needs to relay received and
transmitted data from “serial device” to another unit via I2C. Units interfacing
“I2C devices” needs to relay received / transmitted data via serial. All serial
units linked each other into a ring. Serial out of each unit connects to serial
in of a next unit. Propagation delay (in transfer data from unit N to unit K
will depend on an amount of units btw N and K. Serial communication speed -
56K/s, I2C around 200-300Kbit/s. Un-standard speed for serial can be set to
100Kbit/s, but temperature instability can reduce speed back to 56-32k. Each
unit can change speed of communication. On master reset serial speed is 9600.
Each unit on “power-on” transfer over serial loop sends greetings message.
Traveling over the loop this message ended up at originated unit and loops
functionality verified. Main processor unit can monitor traffic and detect all
functional units. The same technique of traffic monitoring can be useful to
avoid re-transition the same data. I.e. “Camera unit” send data to a “memory”
unit at the same time main processor grab data for IKV processing and/or “24Ghz
communication” unit can relay packages from “Camera unit” to “memory” with
retransmitting same packages to ground station.
Packets over I2C addressed to a unit process as CMD stream inside the unit.
Serial packets format:
<unit><packet><unit>
Unit scans serial stream for matching unit’s address, relay data not addressed
to unit. If inside a packet present byte equal any Unit-Address-In-System, the
byte has to be escaped (by transmitter) with ESC char = “#’. Out of packed data
stream also can have ESC chars to distinguish data from a packets.
3 queues: (a) for input serial stream, (b) for a output serial stream/I2C, (c)
for input I2C stream. If unit require I2C communication output queue was to be
emptied. The same with serial - only when output queue will be empty from I2C
write stream, then serial output takes control.
Packets:
<unit>~[message]<unit> - serial loop test message – unit send its own address – message
will end up in originated unit. Command “~” is indication that loop is
functional.
<unit>Ayyyyyxx@<unit> - request for unit to send a message “yy..yy” over I2C to unit
“A”; “xx” is requests of a bytes to be read from the I2C. If message is big it
sends over I2C by 10 bytes packets.
<units><speed><unit> - where speed = ‘9’(9600)| ‘1’(19200) | ‘3’(38400)| ’5’(57600)|
’0’ (max)
<unit>=A<unit> - request to set address of the “reply” unit.
<unit>!C<unit> - request to set CMD in reply packet.
i.e unit <5> needs to check on unit
<3. what is a clock reading – it send this stream:
3=#5!t$3 - <3> is a target
unit address,
“=#5” == “=5” set reply address
“!t” = set “t” command for reply
“$” – read timer value
Response (reply) from unit 3 will be:
5t#1#2#3#4#5#6#7#895 – <5> is a target unit
“t” timer reading 12:34:56 counter
789 (with maximum units in system ==8)
Over I2C first packet will be 3=5*t$ and
response packet will be 5t12345678.
Another sample: Power plant unit <4> needs
to orient satellite by XXX YYY ZZZ for better energy harvesting. It send packet
to a stepper motor unit <3>:
3-XXXYYYZZZ3
Stepper motor will compare readings
from gyro and adjust positions.
Same command can be send by main processor to
adjust direction to a ground station.
Command 3+xxxyyyzzzDvxDvyDvzNNNLLLL3 can
be send by backup communication to set communication session. Xxx yyy zzz is a
starting orientation, and Dvx, Dvy, Dvz is a delta for a linear approximation of
motion on the orbit, NNN is delay to apply delta, LLLL is amount of cycles to
perform.
Sequence for commands like 3+xx..3 can be presorted in a memory unit.
At the finish of command execution unit can send request to memory for another
command.
<unit>^<unit> - echo everything from serial-in to out with ESC insertion
<unit>v<unit> - remove any ESC from serial-in
i.e. Main processor unit <8> using com1 as
IP dial up connection. Communication <2> unit’s TX connects to <8> unit’s RX.
<8> unit’s TX connects to power plant <3> unit’s RX. At the end of the loop
communication <2> unit’s RX getting the stream. Sequence send by unit <8> is :
2v23^3 . . . . . . . whatever stream require for IP communication. ….
To switch
off that mode needs to set MCLR for unit <2> and <3>
Packets can be inside each other
– for example last sample 2v23^3 can be changed to
2v3^32.
If serial stream is
out of packet any unit can insert its own packets for transfer.
If unit echoing
some serial packed addressed to unit N, then unit can insert another packet
addressed to unit K, where K < N, otherwise it needs to wait for the end of the
packet.
Execution of a CMD can be immediate after receiving command or delayed
to the end of the package.
Each unit has MCLR(RA5) (h-l-h for reset),
PRG(RB3,RB6,RB7) pins. Units with less pins used can be utilized to perform
reset and reprogramming functions for neighbor unit. Four unused pins can
reprogram / reset one unit, 5 unused pin – 2 unit, 8 can reprogram and reset 5
units. Separate programming port and reset shell be used for a main processor
unit.
June 17, 2011 – IUP
(Inter Unit Protocol) was re-designed from old code – now each unit has serial
output connected to nearest unit’s serial input. I.e. main computer serial
output connect to Transmitter’s serial input, then Transmitter’s serial output
connected to Receiver’s serial input, and Receiver output connected back to main
computer serial input. In passive state bytes from any units travels (looping)
over entire net. Integrity of all network can be verified by any units
individually. NAND gates can be used to bypass un-functional unit. RST in high
state will enable transmit data btw nearest units, and pull-down resistor can be
used to skip broken. Both microcontrollers (16LF88) for LDF (Laser Distance
Finder) transmitter and receiver designed to be exactly the same (difference in
command “wW” and “wV’ – W set W/R high, and V set ports bus into input mode).
Source code: STM_LTRX.c, and for and
project: STM_LTRX.mcp,
STM_LTRX.mcw
Everything under this line when to the garbage.
================================================================================
Feb 5, 2011 – From
redirection cases one remain unimplemented – in a time of receiving /
transmitting packet needs to switch (by default) two remain channels in
redirection state. It will be not a problem but needs to find “good” solution.
Good in sense to be a small code. Also implementation of a time sensitive motor
commands will require some tailoring – ether it will require special event block
for TMR1/TMR0 or independent implementation using TMR2. Main function 0x3X for
stepper motor implemented (by the way it takes only one processor command MOV).
Now it is possible to port protocol to communication unit (modem), guidance
unit, storage unit, and camera unit.
For stepper motor also needs
to implement temperature sensor reading via analog/serial input.
Power station for stepper
motor will include analog reading on capacitor/battery.
Changes in design was updated
blow.
Jan 26 2011 – Original
design was changed - 3 pins only will be available to connect network
RB7,RB6,RB4 (or RB5 depended on communication serial/ I2C / serial asynchronous)
speed was reduced dramatically to 8 kbit per second (data actually can be
transferred twice faster 16 kbit) for now the code works with send/receive.
Redirection will be later. Commands for discovery neighbourhood will be on Unit
level. Code size for communication (only) 1024 bytes. Communication code will be
base for another Units like Storage, Cameras, BT, Gyro, accelerometers. Left to
implement Redirection (will add some size), stepper motors commands.
Source code here.
Jan 11 2011 – well – it
is hard to mix together coding and
birthday
party
+ Christmas
celebration – but it is not evening et. Interrupts on PIC16F88 are working –
max # channels per unit limited to 3 (one pin has to be reserved to Serial/ I2C
communication- it is pity), and serial communication over channels better be
coded not using regular algorithms (check for high-low transition – delay time=
½ of a bit’s speed – delay time= bit’s speed – read bit and accumulate byte –
delay –read-delay-read, etc.). Better approach (in view of saving progr memory)
is to – interrupt on pin changes – then check time elapsed from first high-low
transition – timing will give nice transmitting byte – and if value of a byte
can be ignored (re-transmission from neighbor unit) it give processor time for
control unit.
Jan 7, 2011
– controller communication design. Target device PIC16F88. Design target - to
get communication independent from connection’s configuration. Each unit
(Stepper motors, transmitter/receiver, main on-board computer, gyro-system,
power station, backup control unit, cameras) will be connected based on topology
of a probe/vehicle.
Targets in development on Jan 7, 2011:
-
Jan 10 2011, get draft communication working
-
Jan 17 2011, get working on-board computer with
stepper motor unit.
-
XXXX 2011, get working on-board computer with
transmitter/receiver.
Lets see how it will go.
Stepper motor
controller communication draft.
UNIT – internal unit number 1 byte
U – 0xXX – copy of the unit number stored in offset 0x00
Unit address is 6
bit long, total 63 addresses. Address 0x3f reserved for all units.
CLOCK - Internal clock format 6 bytes:
for set time copy in EEPROM offset 0x01
DHMSXX
D
0xDD - day
H
0xHH – hour
M
0xMM – minute
S
0xSS - second
XX 0xXXXX – 1/65535 of
a second
DELAY - Internal delay for a steps in
sequence, 2 bytes
copy delay's value stored in EEPROM offset 0x07
DD
0xDDDD – delay btw steps in sequence of 4
1000 – 0010 – 0100 – 0001 or 1001 – 1010 –
0110 – 0101
SEQ - internal sequence for movement 4
bytes
copy stored in EEPROM offset 0x09
SSSS -
S
- 1 step
S - 2
step
S - 3 step
S - 4 step
ISPC - next CMD in sequence (in EEPROM), one byte:
C
0x00 execute command from a memory buffer
0xCC – read command from 0xCC EEPROM location and execute it
0xFF – nothing to do – controller in wait state (not a "sleep)
commands:
in EEPROm offset starting from address pointed by ISPC
NBR - Neighbor Unit
1000 0000 -
(implemented) received message used as to identify neighbor unit –
basically this is NOP operation – one unit inform its address.
1100 0000 -
(implemented) received message used as to identify neighbor unit –
and ask to transmit back its address In response unit send back 1000 0000
command.
OUTPUT –
(implemented) output 4 bits for stepper motor
0011 XXXX – set bits for Stepper motor
FWD – forward movements movements
0001 0001 - 1
step FWRD
0001 xxxx
- '0001' – '1110' 1-14 steps forward
0001 1111
- continuous forward
BWD – backward movements
0010 0001 – 1 step back
0010 xxxx – '0001' – '1110' 1-14 steps backward
0010 1111 – continuous backward
WAIT – switch controller in wait/SLEEP state
1111 0000 – controller in wait state (different from a
SLEEP state)
1111 0001 dddd dddd dddd dddd – wait DD timer ticks
1111 0010 DHMSXX
- wait clock for DHMSXX
in this mode controller can not be in SLEEP state
this command has to be
1111 0011 – switch controller to SLEEP state (low power) –
switching to SLEEP state makes clock unpredictable
WRT – write to program memory
1110 0000 LLLL LLLL AAAA AAAA AAAA AAAA DDDD
L-L bytes to write
A-A – address
D-D – data
RDM – read program memory and send to U
1101 0000 LLLL LLLL AAAA AAAA AAAA AAAA UUUU UUUU
L-L bytes to read
A-A – address
U-U – byte receiver unit
RDA – read analog inputs from A1-A4 and send to U
1101 00XX UUUU UUUU
RDE – read EEPROM and send to U
1101 0100 LLLL LLLL AAAA AAAA UUUU UUUU
CHK – calculate checksum for a EEPROM and send it to Unit
1011 0001 LLLL LLLL AAAA AAAA AAAA AAAA UUUU UUUU
L-L bytes to read
A-A – address
U-U – byte receiver unit
CHK – calculate checksum for a program memory and send it
to Unit
1011 0000 LLLL LLLL LLLL LLLL AAAA AAAA AAAA AAAA UUUU UUUU
L-L bytes to read
A-A – address
U-U – byte receiver unit
SET
1100 0001 D
set byte D to ISPC
1100 0010 DHMSXX – set Clock to DHMSXX
1100 0011 DD -
set 2 bytes delay btw sequence
1100 0100 P -
set presaler
1100 0101 SSSS – set 4 bytes sequence for motor movement
1100 0110 B – set mask for Port B input bus
1100 0111 B – set mask for Port B output bus
Each unit set status “BUSY” on command execution. In "WAIT"
state unit can accept new command. If unit in “BUSY” state it can be interrupted
by command with interruption request.
Changes in design.
Case 1:

message from ch0:a0 02 11 80
a0
to neighbor
02
len = 2 bytes
11 from unit 11
80 store neighbor adr
then second message
ch1:81 02 21 80
81
to unit 81
02
len = 2 bytes
21
from unit 21
80
store neighbor adr
fc /b test_1_nbr_adr.bmp test_1_nbr_adr.sam
>error.txt
if errorlevel 1 goto ERROR1
echo test_1_nbr_adr OK
goto nexttest
:ERROR1
echo ERROR in test_1_nbr_adr
:nexttest
case2:

message from ch0:81 02 11 c0
81
to unit 81
02 len = 2 bytes
11 from unit 11
c0 store neighbor adr
and sand back on same ch CMD 80 on ch0 unit will
response:
11 02 81 80
11
to unit 11
02
len = 2 bytes
81
from unit 81
80
CMD 80
case 3:

message from ch0:21 02 11 80
21
to 21
02 len = 2 bytes
11 from unit 11
80 store neighbor adr
this will redirect to ch1 all message
21 ->
wait for OK impulse
02 11 c0
case 4:

message from ch0:21 02 11 c0
21
to unit 21
02 len = 2 bytes
11 from unit 11
80 store neighbor adr
this will redirect to ch1 all message:
21 -> "NO" impulse
to ch2
21 -> wait for "OK" impulse
02 11 c0
case 5:

message from ch0:21 02 11 80
21
to unit 21
02 len = 2
bytes
11 from unit 11
80 store neighbor adr
this will redirect to ch1 all message:
21 -> "NO" impulse
to ch2:
21 -> "NO" impulse
case 6:

message from ch0: 81 + timeout
case 7:

Communication protocol (see changes above).
Input buses monitored and serial input from any - read,
stored internally into buffer, and then executed if unit’s address matched. If
unit’s address does not match then data transferred to neighbour unit. On each
session neighbour’s addresses updated. Direction chooses by closest addresses in
unit’s neighbourhood.
Connection btw units can be in state “BUSY”. When data
transfer finished by event
(a)end-of-data +checksum
(b)end-of-data-TO(timeout)
(c)TO(timeout)
connection’s status assigned “FREE”.
Packets are:
<TO><I_AM><FROM><LENGTH><DATA>[<CHSUM>]
<TO> - 1 byte, whom this message to be delivered
<I_AM> - 1 byte, transmitting unit number
<FROM> - 1 byte, original message from
<LENGTH> - 2 bytes – length max 64K
<CHSUM> - 2 bytes CRC checksum. Can be skipped
<DATA>:
<FLAG> <COMMAND>
<FLAG='0x00'> – execute <CMD> immediately
<FLAG= 0xAA'> – store <CMD> in EEPROM at address 0xAA
If in field <TO>
high bit set ‘1’ – unit <TO> needs to interrupt execution of a command.
If in field <TO> high
bit cleared ‘0’ – and unit <TO> in “BUSY” state then response from<TO> unit fill
be with high bit set ‘1’. This bit will propagated to original transmitter
station and transmitter stop transfer.
If on
re-transmitter station all connections will be in “BUSY” state, then
re-transmitter reply its address with high bit set and transmitter will stop
transfer.
Samples 1.
On-board computer (Unit 0x01) needs to set a clock to day 7 hour 12
min 15
sec 16 xsec 0000 in stepper motor (unit 0x14):
first packed it send data to EPPROM memory for each unit
3F 01 01 00 09 10 c2 07 0c 0f 10 00 00 F0
3F
-
stepper motor 4 and all units
01
– On-board computer
01
– On-board computer
00 09
- 9 bytes of data
10
- store to EEPROM adr 0x10
c2
- cmd set clock
07 0c 0f 10 00 00
F0 – cmd WAIT
then On-board computer send command at 07 12:15:15:YYY
time:
3F 01 01 cc 00 03 00 c1 10
3F
-
stepper motor 4 and all units
01
-
On-board computer
01
- On-board computer
00 03
- 3 bytes of data
00
- execute immediately
C1
- cmd set ISPC
10 - execute at EEPROM
0x10
(where prev cmd stored)
YYY calculates by – 1000 msc - minus time for transmission
– minus time for EEPROM read 7 bytes – minus time to store 6 bytes into internal
clock.
Addressing unit 0x3f instead of 0x14 will sets clock for
all units.