repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/PointerImplementation.h
/** * @author <NAME> 14.07.2016 * * Communication related implementation that is ought to be passed as pointer or callback. */ #pragma once #include "uc-core/configuration/IoPins.h" /** * Writes a logic high to the north transmission pin. */ void northTxHiImpl(void) { NORTH_TX_HI; } /** * Writes a logic low to the north transmission pin. */ void northTxLoImpl(void) { NORTH_TX_LO; } /** * Writes a logic high to the east transmission pin. */ void eastTxHiImpl(void) { EAST_TX_LO; // must be inverted due to missing MOSFET } /** * Writes a logic low to the east transmission pin. */ void eastTxLoImpl(void) { EAST_TX_HI; // must be inverted due to missing MOSFET } /** * Writes a logic high to the south transmission pin. */ void southTxHiImpl(void) { SOUTH_TX_HI; } /** * Writes a logic low to the south transmission pin. */ void southTxLoImpl(void) { SOUTH_TX_LO; } /** * Writes a logic high to the east and south transmission pins. */ void simultaneousTxHiImpl(void) { MEMORY_BARRIER; EAST_TX_LO; // must be inverted due to missing MOSFET MEMORY_BARRIER; // Since we observe a greater delay between the rising edges of the // east (with MOSFET) and south (with MOSFET) ports, we introduce a // synthetic delay at the falling edges to make both delays more similar. NOOP; MEMORY_BARRIER; SOUTH_TX_HI; MEMORY_BARRIER; } /** * Writes a logic low to east and south transmission pins. */ void simultaneousTxLoImpl(void) { MEMORY_BARRIER; EAST_TX_HI; // must be inverted due to missing MOSFET MEMORY_BARRIER; SOUTH_TX_LO; MEMORY_BARRIER; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/TimerCounter1.h
/** * @author <NAME> 20.07.2016 * * Timer / counter 1 related configuration. */ #pragma once #include <avr/interrupt.h> #include "TimerCounter.h" #if defined(__AVR_ATtiny1634__) || defined(__AVR_ATmega16__) # define __TIMER1_INTERRUPT_CLEAR_PENDING_COMPARE_A \ (((TIFR & (1 << OCF1A)) != 0) ? TIFR = (1 << OCF1A) : 0) # define __TIMER1_INTERRUPT_CLEAR_PENDING_COMPARE_B \ (((TIFR & (1 << OCF1B)) != 0) ? TIFR = (1 << OCF1B) : 0) # define __TIMER1_INTERRUPT_CLEAR_PENDING \ __TIMER1_INTERRUPT_CLEAR_PENDING_COMPARE_A; \ __TIMER1_INTERRUPT_CLEAR_PENDING_COMPARE_B # define __TIMER1_INTERRUPT_OUTPUT_MODE_DISCONNECTED_SETUP \ (TCCR1A unsetBit ((1 << COM1A1) | (1 << COM1A0) | (1 << COM1B1) | (1 << COM1B0))) # define __TIMER1_INTERRUPT_WAVE_GENERATION_MODE_CTC_SETUP \ TCCR1A unsetBit ((1 << WGM11) | (1 << WGM10)); \ TCCR1B unsetBit ((1 << WGM13) | (1 << WGM12)); \ TCCR1B setBit ((1 << WGM12)) # define __TIMER1_INTERRUPT_WAVE_GENERATION_MODE_NORMAL_SETUP \ TCCR1A unsetBit ((1 << WGM11) | (1 << WGM10)); \ TCCR1B unsetBit ((1 << WGM13) | (1 << WGM12)) # define __TIMER1_INTERRUPT_TIMER_VALUE_SETUP(timerValue) \ (TCNT1 = timerValue) # define __TIMER1_INTERRUPT_COMPARE_VALUE_A_SETUP(compareValue) \ (OCR1A = (compareValue)) # define __TIMER1_INTERRUPT_COMPARE_VALUE_B_SETUP(compareValue) \ (OCR1B = (compareValue)) # define __TIMER1_INTERRUPT_PRESCALER_ENABLE(prescaler) \ (TCCR1B setBit(prescaler)) # define __TIMER1_INTERRUPT_PRESCALER_DISABLE \ (TCCR1B unsetBit(__TIMER_COUNTER_PRESCALER_DISCONNECTED_FLAGS)) # define __TIMER1_COMPARE_A_INTERRUPT_ENABLE \ (TIMSK setBit bit(OCIE1A)) # define __TIMER1_COMPARE_A_INTERRUPT_DISABLE \ (TIMSK unsetBit bit(OCIE1A)) # define __TIMER1_COMPARE_B_INTERRUPT_ENABLE \ (TIMSK setBit bit(OCIE1B)) # define __TIMER1_COMPARE_B_INTERRUPT_DISABLE \ (TIMSK unsetBit bit(OCIE1B)) # define __TIMER1_OVERFLOW_INTERRUPT_ENABLE \ (TIMSK setBit bit(TOIE1)) # define __TIMER1_OVERFLOW_INTERRUPT_DISABLE \ (TIMSK unsetBit bit(TOIE1)) #else # error #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/CommunicationProtocol.h
/** * @author <NAME> 2016 * * Communication protocol related arguments. */ #pragma once /** * On timeout the current communication falls back to the communication's start state. The counter * is decremented each main loop. A zero value indicates the timeout. * Reasonable values are ∈ [128, UINT8_MAX]. */ #define COMMUNICATION_PROTOCOL_TIMEOUT_COUNTER_MAX ((uint8_t)250) #define COMMUNICATION_PROTOCOL_RETRANSMISSION_COUNTER_MAX ((uint8_t)3) /** * When a time synchronization package is broadcasted, each mcu introduces a lag of * approximate 6.5µS. Thus for 8MHz osc: 0.0065*8 = ~0.052clocks. * * rx: --<|||||||>---- * ^ * tx: -----<|||||||>---- * ^ introduced mcu lag */ // 32,64 #define COMMUNICATION_PROTOCOL_TIME_SYNCHRONIZATION_PER_NODE_INTERRUPT_LAG ((uint16_t)33) /** * Mean package reception duration approximate = ~57344 mcu clocks, or more accurate: * 8bytes*8bits*tx_clock_phase_delay => 8*8*1024 = 65536 * * rx: -----<|||||||>------ * ^-----^ sync. package reception duration */ //#define COMMUNICATION_PROTOCOL_TIME_SYNCHRONIZATION_PACKAGE_RECEPTION_DURATION ((uint16_t)57320) #define COMMUNICATION_PROTOCOL_TIME_SYNCHRONIZATION_PACKAGE_RECEPTION_DURATION ((uint16_t)0) /** * Mean reception to execution latency in between last interrupt and execution of sync command. * * tx (1,1): -----<|||||||>-------- * ^ last flank/package interrupt * receiver exec: --------------#----- * ^ command execution * ~334us */ #define COMMUNICATION_PROTOCOL_TIME_SYNCHRONIZATION_PACKAGE_EXECUTION_LAG ((uint16_t)2520) /** * In case of manual adjustment needed. */ #define COMMUNICATION_PROTOCOL_TIME_SYNCHRONIZATION_MANUAL_POSITIVE_ADJUSTMENT ((uint16_t)1476) #define COMMUNICATION_PROTOCOL_TIME_SYNCHRONIZATION_MANUAL_NEGATIVE_ADJUSTMENT ((uint16_t)0)
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/scheduler/SchedulerTypesCtors.h
/* * @author <NAME> 18.09.2016 * * Scheduler types constructor implementation. */ #pragma once #include "SchedulerTypes.h" #include "common/common.h" /** * constructor function * @param o the object to construct **/ void constructSchedulerTask(SchedulerTask *const o) { o->startTimestamp = 0; o->endTimestamp = 0; o->reScheduleDelay = 0; o->numCalls = 0; o->state = STATE_TYPE_IDLE; o->isNodeTypeLimited = NODE_TYPE_INVALID; o->startAction = NULL; o->endAction = NULL; o->isTimeLimited = false; o->isStateLimited = false; o->isEnabled = false; o->isExecuted = false; o->isStarted = false; o->isStartActionExecuted = false; o->isEndActionExecuted = false; o->isCyclicTask = false; o->__isExecutionRetained = false; o->isNodeTypeLimited = false; o->isCountLimitedTask = false; o->isLastCall = false; } /** * constructor function * @param o the object to construct **/ void constructScheduler(Scheduler *const o) { for (uint8_t idx = 0; idx < SCHEDULER_MAX_TASKS; idx++) { constructSchedulerTask(&o->tasks[idx]); } o->lastCallToScheduler = 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/ParticleTypesCtors.h
/* * @author <NAME> 2016 * * Particle types constructor implementation. */ #pragma once #include "ParticleTypes.h" #include "NodeAddressTypesCtors.h" #include "AlertsTypesCtors.h" #include "DiscoveryPulseCountersCtors.h" #include "CommunicationTypesCtors.h" #include "uc-core/communication/CommunicationTypesCtors.h" #include "uc-core/communication-protocol/CommunicationProtocolTypesCtors.h" #include "uc-core/actuation/ActuationTypesCtors.h" #include "uc-core/time/TimeTypesCtors.h" #include "uc-core/periphery/PeripheryTypesCtors.h" #include "uc-core/synchronization/SynchronizationTypesCtors.h" #include "uc-core/scheduler/SchedulerTypesCtors.h" #include "uc-core/evaluation/EvaluationTypesCtors.h" /** * constructor function * @param o the object to construct */ void constructNode(Node *o) { o->state = STATE_TYPE_UNDEFINED; o->type = NODE_TYPE_INVALID; constructNodeAddress(&o->address); } /** * constructor function * @param o the object to construct */ void constructParticle(Particle *const o) { constructNode(&(o->node)); constructDiscoveryPulseCounters(&o->discoveryPulseCounters); constructCommunication(&o->communication); constructPeriphery(&o->periphery); constructCommunicationProtocol(&o->protocol); constructActuationCommand(&o->actuationCommand); constructTimeSynchronization(&o->timeSynchronization); constructLocalTimeTracking(&o->localTime); constructDirectionOrientedPorts(&o->directionOrientedPorts); constructAlerts(&o->alerts); constructScheduler(&o->scheduler); constructEvaluation(&o->evaluation); #ifdef SIMULATION o->__structStartMarker = 0xaa; o->__structEndMarker = 0xaa; #endif }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/TimerCounter0.h
<gh_stars>1-10 /** * @author <NAME> 20.07.2016 * * Timer / counter 0 related configuration. */ #pragma once #include <avr/interrupt.h> #include "TimerCounter.h" #if defined(__AVR_ATtiny1634__) || defined(__AVR_ATmega16__) # if defined(__AVR_ATmega16__) # define __TIMER0_INTERRUPT_WAVE_GENERATION_MODE_PWM_PHASE_CORRECT_SETUP \ (TCCR0 setBit bit(WGM00)); \ (TCCR0 unsetBit bit(WGM01)) # define __TIMER0_INTERRUPT_PRESCALER_ENABLE(prescaler) \ (TCCR0 setBit (prescaler)) # define __TIMER0_INTERRUPT_PRESCALER_DISABLE \ (TCCR0 unsetBit(__TIMER_COUNTER_PRESCALER_DISCONNECTED_FLAGS)) # define __TIMER0_INTERRUPT_OUTPUT_MODE_DISCONNECTED_SETUP \ (TCCR0 unsetBit ((1 << COM01) | (1 << COM00))) # define __TIMER0_COMPARE_INTERRUPT_ENABLE \ (TIMSK setBit bit(OCIE0)) # define __TIMER0_COMPARE_INTERRUPT_DISABLE \ (TIMSK unsetBit bit(OCIE0)) # define __TIMER0_INTERRUPT_CLEAR_PENDING_COMPARE \ (((TIFR & (1 << OCF0A)) != 0) ? TIFR = (1 << OCF0) : 0) # define __TIMER0_INTERRUPT_COMPARE_VALUE_SETUP(compareValue) \ (OCR0 = compareValue) # elif defined(__AVR_ATtiny1634__) # define __TIMER0_INTERRUPT_WAVE_GENERATION_MODE_PWM_PHASE_CORRECT_SETUP \ (TCCR0A setBit bit(WGM00)); \ (TCCR0A unsetBit bit(WGM01)); \ (TCCR0A unsetBit bit(WGM02)) # define __TIMER0_INTERRUPT_OUTPUT_MODE_DISCONNECTED_SETUP \ (TCCR0A unsetBit ((1 << COM0A1) | (1 << COM0A0) | (1 << COM0B1) | (1 << COM0B0))) # define __TIMER0_INTERRUPT_PRESCALER_ENABLE(prescaler) \ (TCCR0A setBit (prescaler)) # define __TIMER0_INTERRUPT_PRESCALER_DISABLE \ (TCCR0A unsetBit(__TIMER_COUNTER_PRESCALER_DISCONNECTED_FLAGS)) # define __TIMER0_COMPARE_INTERRUPT_ENABLE \ (TIMSK setBit bit(OCIE0A)) # define __TIMER0_COMPARE_INTERRUPT_DISABLE \ (TIMSK unsetBit bit(OCIE0A)) # define __TIMER0_INTERRUPT_CLEAR_PENDING_COMPARE \ (((TIFR & (1 << OCF0A)) != 0) ? TIFR = (1 << OCF0A) : 0) # define __TIMER0_INTERRUPT_COMPARE_VALUE_SETUP(compareValue) \ (OCR0A = compareValue) # endif # define __TIMER0_INTERRUPT_TIMER_VALUE_SETUP(timerValue) \ (TCNT0 = timerValue) # define __TIMER0_OVERFLOW_INTERRUPT_ENABLE \ (TIMSK setBit bit(TOIE0)) # define __TIMER0_OVERFLOW_INTERRUPT_DISABLE \ (TIMSK unsetBit bit(TOIE0)) #else # error #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/evaluation/Evaluation.h
<reponame>ProgrammableMatter/particle-firmware<filename>src/avr-common/utils/uc-core/evaluation/Evaluation.h<gh_stars>1-10 /** * @author <NAME> 15.10.2016 * * Evaluation related implementation. */ #pragma once #include "uc-core/particle/Globals.h" void heatWiresTask(SchedulerTask *const task); #ifdef EVALUATION_ENABLE_FLUCTUATE_CPU_FREQUENCY_ON_PURPOSE /** * Increments/Decrements the current RC oscillator calibration value in between predefined boundaries. * Oscillating the MCU frequency is needed for evaluation purpose to prove the (receiver's) clock skew and * clock synchronization adjusts automatically to the newly observed (transmitter's) frequency. * One call to the function reflects one increment/decrement of the predefined step. The increment/decrement * is suspended once when the direction (increment -> decrement, decrement -> increment) is changed. */ void switchToNewOsccalValue(void) { if (ParticleAttributes.evaluation.oscCalibration.isDecrementing) { if (EVALUATION_OSC_CALIBRATION_REGISTER > ParticleAttributes.evaluation.oscCalibration.minOscCal) { EVALUATION_OSC_CALIBRATION_REGISTER -= ParticleAttributes.evaluation.oscCalibration.step; } else { ParticleAttributes.evaluation.oscCalibration.isDecrementing = false; } } else { if (EVALUATION_OSC_CALIBRATION_REGISTER < ParticleAttributes.evaluation.oscCalibration.maxOscCal) { EVALUATION_OSC_CALIBRATION_REGISTER += ParticleAttributes.evaluation.oscCalibration.step; } else { ParticleAttributes.evaluation.oscCalibration.isDecrementing = true; } } } #else # define switchToNewOsccalValue() #endif /** * Updates the task interval according to consumed sync packages in fast sync. mode * (switches to slow sync. mode). */ static void __updateSendSyncTimePackageTaskInterval(SchedulerTask *const task) { if (ParticleAttributes.timeSynchronization.totalFastSyncPackagesToTransmit <= 0) { // separation on default synchronization task->reScheduleDelay = ParticleAttributes.timeSynchronization.syncPackageSeparation; } else { // separation on fast synchronization task->reScheduleDelay = ParticleAttributes.timeSynchronization.fastSyncPackageSeparation; ParticleAttributes.timeSynchronization.totalFastSyncPackagesToTransmit--; } } void sendSyncTimePackageAndUpdateRequestFlagForInPhaseShiftingEvaluationTask(SchedulerTask *const task) { // TODO: shrink code by turning loops inside out if (false == task->isLastCall) { if (ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled) { // on call send next time package LED_STATUS2_TOGGLE; ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest = true; ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled = false; ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; } } else { // on last call send package with update flag set and re-enable task if (ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled) { LED_STATUS2_TOGGLE; // TEST_POINT1_TOGGLE; ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest = true; ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled = false; ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; switchToNewOsccalValue(); // re-enable task taskEnableCountLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, 5); taskEnable(SCHEDULER_TASK_ID_SYNC_PACKAGE); } } } /** * Sends the next sync time package. on last call sends the same package with * isNextSyncPackageTimeUpdateRequest flag set. */ void sendSyncTimePackageAndUpdateRequestFlagTask(SchedulerTask *const task) { // TODO: shrink code by turning loops inside out if (false == task->isLastCall) { if (ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled) { __updateSendSyncTimePackageTaskInterval(task); // on call send next time package LED_STATUS2_TOGGLE; ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest = false; ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled = false; ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; } } else { // on last call send package with update flag set and re-enable task if (ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled) { LED_STATUS2_TOGGLE; // TEST_POINT1_TOGGLE; ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest = true; ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled = false; ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; switchToNewOsccalValue(); // re-enable task taskEnableCountLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, 10); taskEnable(SCHEDULER_TASK_ID_SYNC_PACKAGE); } } } /** * Triggers the sending the next synchronization package, not "update time request" flag. */ void sendNextSyncTimePackageTask(SchedulerTask *const task) { if (false == task->isLastCall) { if (ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled) { __updateSendSyncTimePackageTaskInterval(task); LED_STATUS2_TOGGLE; ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest = false; ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled = false; ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; } } else { switchToNewOsccalValue(); // on last call enable heat wires task addCyclicTask(SCHEDULER_TASK_ID_HEAT_WIRES, heatWiresTask, task->startTimestamp + 400, 200); taskEnableNodeTypeLimit(SCHEDULER_TASK_ID_HEAT_WIRES, NODE_TYPE_ORIGIN); taskEnable(SCHEDULER_TASK_ID_HEAT_WIRES); } } #if defined(EVALUATION_SIMPLE_SYNC_AND_ACTUATION) || defined(EVALUATION_SYNC_CYCLICALLY) static bool __incrementAndSetNextHeatWiresAddress(void) { if (ParticleAttributes.evaluation.nextHeatWiresAddress.row < ParticleAttributes.protocol.networkGeometry.rows) { ParticleAttributes.evaluation.nextHeatWiresAddress.row++; } else { if (ParticleAttributes.evaluation.nextHeatWiresAddress.column < ParticleAttributes.protocol.networkGeometry.columns) { ParticleAttributes.evaluation.nextHeatWiresAddress.row = 2; ParticleAttributes.evaluation.nextHeatWiresAddress.column++; } else { return false; } } return true; } /** * triggers the sending of the next actuation (heat wires) command */ void heatWiresTask(SchedulerTask *const task) { if (__incrementAndSetNextHeatWiresAddress()) { // on having new address to traverse Actuators actuators; actuators.northLeft = true; actuators.northRight = true; NodeAddress nodeAddress; nodeAddress.row = ParticleAttributes.evaluation.nextHeatWiresAddress.row; nodeAddress.column = ParticleAttributes.evaluation.nextHeatWiresAddress.column; sendHeatWires(&nodeAddress, &actuators, task->startTimestamp + 50, 100); } else { // on no more address to traverse: enable cyclic sync. pkg. ParticleAttributes.evaluation.nextHeatWiresAddress.row = 1; ParticleAttributes.evaluation.nextHeatWiresAddress.column = 1; addCyclicTask(SCHEDULER_TASK_ID_SYNC_PACKAGE, sendNextSyncTimePackageTask, task->startTimestamp + 100, 100); taskEnableNodeTypeLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, NODE_TYPE_ORIGIN); taskEnableCountLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, 20); taskEnable(SCHEDULER_TASK_ID_SYNC_PACKAGE); taskDisable(SCHEDULER_TASK_ID_HEAT_WIRES); } } #endif #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_THEN_ACTUATE_ONCE void sendSyncTimeAndActuateOnceTask(SchedulerTask *const task) { if (ParticleAttributes.evaluation.totalSentSyncPackages >= EVALUATION_SYNC_PACKAGES_BEFORE_ACTUATION) { // disable all scheduled tasks for (int idx = 0; idx < SCHEDULER_MAX_TASKS; idx++) { ParticleAttributes.scheduler.tasks[idx].isEnabled = false; } // enable one actuation task Actuators actuators; actuators.northLeft = false; actuators.northRight = true; NodeAddress topLeft; topLeft.row = 1; topLeft.column = 1; NodeAddress bottomRight; bottomRight.row = ParticleAttributes.protocol.networkGeometry.rows; bottomRight.column = ParticleAttributes.protocol.networkGeometry.columns; sendHeatWiresRange(&topLeft, &bottomRight, &actuators, task->startTimestamp + 400, 400); return; } if (false == task->isLastCall) { if (ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled) { // on call send next time package LED_STATUS2_TOGGLE; ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest = true; ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled = false; ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; ParticleAttributes.evaluation.totalSentSyncPackages++; } } else { // on last call send package with update flag set and re-enable task if (ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled) { LED_STATUS2_TOGGLE; ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest = true; ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled = false; ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; // re-enable task taskEnableCountLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, ParticleAttributes.timeSynchronization.totalFastSyncPackagesToTransmit); taskEnable(SCHEDULER_TASK_ID_SYNC_PACKAGE); ParticleAttributes.evaluation.totalSentSyncPackages++; } } } #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/periphery/PeripheryTypesCtors.h
/* * @author <NAME> 18.09.2016 * * Periphery types constructor implementation. */ #pragma once #include "PeripheryTypes.h" /** * constructor function * @param o the object to construct **/ void constructBlinkAddress(BlinkAddress *const o) { o->blinkColumnCounter = 0; o->blinkRowCounter = 0; o->blinkAddressBlinkDelay = 0; o->lastExecutionTime = 0; o->blinkAddressState = ADDRESS_BLINK_STATES_START; } /** * constructor function * @param o the object to construct **/ void constructBlinkTimeInterval(BlinkTimeInterval *const o) { o->lastExecutionTime = 0; o->localTimeMultiplier = TIME_INTERVAL_BLINK_STATES_PERIOD_MULTIPLIER; o->blinkState = TIME_INTERVAL_BLINK_STATES_LED_OFF; } /** * constructor function * @param o the object to construct **/ void constructPeriphery(Periphery *const o) { constructBlinkAddress(&o->blinkAddress); constructBlinkTimeInterval(&o->blinkTimeInterval); o->doClearLeds = true; // // validation code for measuring forward latency // o->isTxSouthToggleEnabled = false; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/DiscoveryTimer.h
/** * @author <NAME> 20.07.2016 * * Discovery timer interrupt related configuration. */ #pragma once #include "TimerCounter1.h" // TODO: rename misleading "sense" to discovery pulse #define __TIMER_NEIGHBOUR_SENSE_PRESCALER_VALUE \ __TIMER_COUNTER_PRESCALER_8 #define __TIMER_NEIGHBOUR_SENSE_PRESCALER_ENABLE \ __TIMER1_INTERRUPT_PRESCALER_ENABLE(__TIMER_NEIGHBOUR_SENSE_PRESCALER_VALUE) #define TIMER_NEIGHBOUR_SENSE_SETUP __TIMER1_INTERRUPT_CLEAR_PENDING; \ __TIMER1_INTERRUPT_OUTPUT_MODE_DISCONNECTED_SETUP; \ __TIMER1_INTERRUPT_WAVE_GENERATION_MODE_CTC_SETUP; \ __TIMER1_INTERRUPT_COMPARE_VALUE_A_SETUP(DEFAULT_NEIGHBOUR_SENSING_COUNTER_COMPARE_VALUE); \ __TIMER1_INTERRUPT_PRESCALER_DISABLE; \ __TIMER1_COMPARE_A_INTERRUPT_ENABLE #define TIMER_NEIGHBOUR_SENSE_DISABLE \ __TIMER1_COMPARE_A_INTERRUPT_DISABLE #define TIMER_NEIGHBOUR_SENSE_ENABLE \ __TIMER1_COMPARE_A_INTERRUPT_ENABLE #define TIMER_NEIGHBOUR_SENSE_PAUSE \ __TIMER1_INTERRUPT_PRESCALER_DISABLE #define TIMER_NEIGHBOUR_SENSE_RESUME \ __TIMER_NEIGHBOUR_SENSE_PRESCALER_ENABLE #define TIMER_NEIGHBOUR_SENSE_COUNTER_VALUE \ TCNT1
ProgrammableMatter/particle-firmware
src/avr-common/utils/common/PortADefinition.h
<reponame>ProgrammableMatter/particle-firmware<filename>src/avr-common/utils/common/PortADefinition.h /** * @author <NAME> 2015 */ #pragma once #include <avr/io.h> #define AOut PORTA #define AIn PINA #define ADir DDRA
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/parity/Parity.h
<gh_stars>1-10 /** * @author <NAME> 22.09.2016 * * Parity related implementation. */ #pragma once #include "uc-core/communication/CommunicationTypes.h" #include "common/common.h" #include "simulation/SimulationMacros.h" /** * Stores the even parity bit of the TxPort's buffer to the same buffer. * The port data and data end position must be set up correctly. */ void setEvenParityBit(TxPort *const txPort) { Package *package = (Package *) txPort->buffer.bytes; package->asHeader.parityBit = 0; uint8_t evenParity = 0; uint8_t bitMask; // sum up the 1-bits of all full bytes for (int8_t byte = 0; byte < txPort->dataEndPos.byteNumber; byte++) { bitMask = 1; while (bitMask != 0) { if ((txPort->buffer.bytes[byte] getBit bitMask) != 0) { evenParity++; } bitMask <<= 1; } } bitMask = 1; // sum up te 1-bits of all subsequent bits while ((txPort->dataEndPos.bitMask != 0) && (bitMask != 0)) { // on end marker reached if ((txPort->dataEndPos.bitMask getBit bitMask) != 0) { break; } if ((txPort->buffer.bytes[txPort->dataEndPos.byteNumber] getBit bitMask) != 0) { evenParity++; } bitMask <<= 1; } package->asHeader.parityBit = (evenParity getBit 1); } /** * Tests received buffer for even parity. */ bool isEvenParity(const RxPort *const rxPort) { // on even parity if (rxPort->parityBitCounter == 0) { return true; } #ifdef SIMULATION DEBUG_CHAR_OUT('9'); #endif blinkParityErrorForever(rxPort->parityBitCounter); return false; }
ProgrammableMatter/particle-firmware
src/particle-simulation-sendheader-test/main/main.c
/** * @author <NAME> 21.07.2016 */ #define SIMULATION_SEND_HEADER_TEST #include <uc-core/particle/ParticleLoop.h> int main(void) { processLoop(); return 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication-protocol/CommunicationProtocolTypes.h
/** * @author <NAME> 13.07.2016 * * Communication related types definitions. */ #pragma once #include <stdint.h> /** * Describes communication states of the initiator. The initiator is the particle which * started the communication. */ typedef enum CommunicationInitiatorStateTypes { COMMUNICATION_INITIATOR_STATE_TYPE_IDLE, COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT, COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED, COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE, COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK, COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED } CommunicationInitiatorStateTypes; /** * Describes communication states of the receptionist. The receptionist is the particle * which reacts on a received package. */ typedef enum CommunicationReceptionistStateTypes { COMMUNICATION_RECEPTIONIST_STATE_TYPE_IDLE, COMMUNICATION_RECEPTIONIST_STATE_TYPE_RECEIVE, COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK, COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK_WAIT_TX_FINISHED, COMMUNICATION_RECEPTIONIST_STATE_TYPE_WAIT_FOR_RESPONSE } CommunicationReceptionistStateTypes; /** * Describes the communication port state. */ typedef struct CommunicationProtocolPortState { CommunicationInitiatorStateTypes initiatorState; CommunicationReceptionistStateTypes receptionistState; /** * value 0 indicates a timeout */ uint8_t stateTimeoutCounter; /** * retransmissions: value 0 indicates all retransmissions consumed */ uint8_t reTransmissions : 4; uint8_t __pad : 4; } CommunicationProtocolPortState; /** * Communication protocol ports bundle. */ typedef struct CommunicationProtocolPorts { CommunicationProtocolPortState north; CommunicationProtocolPortState east; CommunicationProtocolPortState south; } CommunicationProtocolPorts; /** * Describes the network geometry; valid row/col values are (> 0) && (<= UINT8_MAX). */ typedef struct NetworkGeometry { uint8_t rows; uint8_t columns; } NetworkGeometry; /** * The communication protocol structure. */ typedef struct CommunicationProtocol { CommunicationProtocolPorts ports; NetworkGeometry networkGeometry; uint8_t hasNetworkGeometryDiscoveryBreadCrumb : 1; volatile uint8_t isBroadcastEnabled : 1; volatile uint8_t isSimultaneousTransmissionEnabled : 1; uint8_t isLastReceptionInterpreted : 1; uint8_t __pad : 4; } CommunicationProtocol;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/discovery/DiscoveryTypesCtors.h
/* * @author <NAME> 09.10.2016 * * Discovery types constructor implementation. */ #pragma once #include "DiscoveryTypes.h" /** * constructor function * @param o the object to construct */ void constructDiscoveryPulseCounter(DiscoveryPulseCounter *const o) { o->counter = 0; o->isConnected = false; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/SampleFifoTypes.h
/** * @author <NAME> 26.09.2016 * * Synchronization FiFo related types. */ #pragma once #include <stdint.h> #include "BasicCalculationTypes.h" #include "uc-core/configuration/synchronization/SampleFifoTypes.h" #include "LeastSquareRegressionTypes.h" typedef struct FifoElement { SampleValueType value; uint8_t isRejected : 1; uint8_t __pad : 7; } FifoElement; /** * Simple first-in first-out buffer for 1-dimensional samples (y-values). * X-values the samples' index. */ typedef struct SamplesFifoBuffer { /** * samples buffer */ FifoElement samples[SAMPLE_FIFO_NUM_BUFFER_ELEMENTS]; /** * index of 1st valid element in buffer */ IndexType __startIdx; /** * index for next insert */ IndexType __insertIndex; /** * number of buffered samples */ IndexType numSamples; /** * index of iterator for outer access */ IndexType iterator; /** * the last FiFo value that has been dropped out of the queue */ FifoElement dropOut; /** * indicates whether the dropOut value is valid or not */ uint8_t isDropOutValid :1; uint8_t __isPreDropOutValid :1; uint8_t __pad :6; } SamplesFifoBuffer;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/time/TimeTypesCtors.h
/** * @author <NAME> 12.07.2016 * * Time types constructor implementation. */ #pragma once #include "TimeTypes.h" #include "uc-core/configuration/Time.h" /** * constructor function * @param o the object to construct */ void constructLocalTimeTracking(LocalTimeTracking *const o) { o->numTimePeriodsPassed = 0; o->newNumTimePeriodsPassed = 0; o->timePeriodInterruptDelay = LOCAL_TIME_TRACKING_INT_DELAY_MANCHESTER_CLOCK_INITIAL_VALUE; o->newTimePeriodInterruptDelay = LOCAL_TIME_TRACKING_INT_DELAY_MANCHESTER_CLOCK_INITIAL_VALUE; o->isTimePeriodInterruptDelayUpdateable = false; o->isNumTimePeriodsPassedUpdateable = false; o->newTimerCounterShift = 0; o->isNewTimerCounterShiftUpdateable = false; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/common/PortBDefinition.h
<reponame>ProgrammableMatter/particle-firmware<gh_stars>1-10 /** * @author <NAME> 2015 */ #pragma once #include <avr/io.h> #define BOut PORTB #define BIn PINB #define BDir DDRB
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/Synchronization.h
<gh_stars>1-10 /** * @author <NAME> 24.09.2016 * * Synchronization related implementation. */ #pragma once #include "uc-core/configuration/synchronization/Synchronization.h" #include "uc-core/configuration/communication/Communication.h" #include "uc-core/configuration/communication/Commands.h" #include "uc-core/particle/Globals.h" #include "SynchronizationTypes.h" #include "SamplesFifo.h" #include "uc-core/stdout/Stdout.h" #include "uc-core/stdout/stdio.h" #ifdef SYNCHRONIZATION_STRATEGY_LEAST_SQUARE_LINEAR_FITTING # include "LeastSquareRegression.h" #else # include "Deviation.h" #endif #include "uc-core/configuration/Time.h" #if defined(SYNCHRONIZATION_STRATEGY_RAW_OBSERVATION) \ || defined(SYNCHRONIZATION_STRATEGY_MEAN) \ || defined(SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_MARKED_OUTLIER) \ || defined(SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN) \ || defined(SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_OUTLIER) \ || defined(SYNCHRONIZATION_ENABLE_ADAPTIVE_MARKED_OUTLIER_REJECTION) \ || defined(SYNCHRONIZATION_STRATEGY_LEAST_SQUARE_LINEAR_FITTING) /** * Clock skew approximation entry point: Independent on which approximation strategy is chosen, * this approximation function is triggered after each TimePackage has been received correctly and * it's pdu reception duration offset has been stored to the fifo queue. */ void tryApproximateTimings(void) { if (isFiFoFull(&ParticleAttributes.timeSynchronization.timeIntervalSamples)) { // if ISR already considered previous new values if (ParticleAttributes.localTime.isTimePeriodInterruptDelayUpdateable == false && ParticleAttributes.communication.timerAdjustment.isTransmissionClockDelayUpdateable == false) { #ifdef SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_MARKED_OUTLIER # define __synchronization_meanValue ParticleAttributes.timeSynchronization.meanWithoutMarkedOutlier #endif #ifdef SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_OUTLIER # define __synchronization_meanValue ParticleAttributes.timeSynchronization.meanWithoutOutlier //@pre mean is valid calculateVarianceAndStdDeviance(); updateOutlierRejectionLimitDependingOnSigma(); calculateMeanWithoutOutlier(); #endif #ifdef SYNCHRONIZATION_STRATEGY_RAW_OBSERVATION # define __synchronization_meanValue ParticleAttributes.timeSynchronization.mean #endif #ifdef SYNCHRONIZATION_STRATEGY_MEAN # define __synchronization_meanValue ParticleAttributes.timeSynchronization.mean #endif #ifdef SYNCHRONIZATION_ENABLE_ADAPTIVE_MARKED_OUTLIER_REJECTION # define __synchronization_meanValue ParticleAttributes.timeSynchronization.mean #endif #ifdef SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN # define __synchronization_meanValue ParticleAttributes.timeSynchronization.progressiveMean #endif #ifdef SYNCHRONIZATION_STRATEGY_LEAST_SQUARE_LINEAR_FITTING # define __synchronization_meanValue ParticleAttributes.timeSynchronization.fittingFunction.d calculateLinearFittingFunctionVarianceAndStdDeviance(); #endif // shift mean value back by +UINT16_T/2 CalculationType observedPduDuration = __synchronization_meanValue + (CalculationType) TIME_SYNCHRONIZATION_SAMPLE_OFFSET; // calculate one manchester clock duration ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelay = observedPduDuration / (CalculationType) SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL; // calculate manchester clock/2 duration ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelayHalf = ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelay / (CalculationType) 2.0; // calculate the upper limit of measured short interval duration (manchester decoding decision limit) ParticleAttributes.communication.timerAdjustment.maxShortIntervalDuration = roundf((CalculationType) COMMUNICATION_DEFAULT_MAX_SHORT_RECEPTION_OVERTIME_PERCENTAGE_RATIO * (CalculationType) ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelay); // calculate the upper limit of measured long interval duration (manchester decoding decision limit) ParticleAttributes.communication.timerAdjustment.maxLongIntervalDuration = roundf((CalculationType) COMMUNICATION_DEFAULT_MAX_LONG_RECEPTION_OVERTIME_PERCENTAGE_RATIO * (CalculationType) ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelay); // calculate the new local time tracking interrupt delay ParticleAttributes.localTime.newTimePeriodInterruptDelay = roundf(ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelay * (CalculationType) LOCAL_TIME_TRACKING_INT_DELAY_MANCHESTER_CLOCK_MULTIPLIER); // printf("sync old %u new %u\n", // ParticleAttributes.localTime.timePeriodInterruptDelay, // ParticleAttributes.localTime.newTimePeriodInterruptDelay); MEMORY_BARRIER; ParticleAttributes.localTime.isTimePeriodInterruptDelayUpdateable = true; ParticleAttributes.communication.timerAdjustment.isTransmissionClockDelayUpdateable = true; } } } #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/communication/Commands.h
/** * @author <NAME> 3.10.2016 * * Communication related arguments. */ #pragma once #define COMMANDS_EXPECTED_TIME_PACKAGE_RECEPTION_DURATION UINT16_MAX
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/LocalTime.h
<reponame>ProgrammableMatter/particle-firmware /** * @author <NAME> 20.07.2016 * Local time tracking related configuration. */ #pragma once #include "TimerCounter1.h" #if defined(__AVR_ATtiny1634__) || defined(__AVR_ATmega16__) # define LOCAL_TIME_INTERRUPT_COMPARE_VALUE (OCR1B) # define LOCAL_TIME_INTERRUPT_CLEAR_PENDING \ __TIMER1_INTERRUPT_CLEAR_PENDING_COMPARE_B # define LOCAL_TIME_INTERRUPT_COMPARE_ENABLE \ LOCAL_TIME_INTERRUPT_CLEAR_PENDING; \ __TIMER1_COMPARE_B_INTERRUPT_ENABLE # define LOCAL_TIME_INTERRUPT_COMPARE_DISABLE \ __TIMER1_COMPARE_B_INTERRUPT_DISABLE # else # error # endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/CommunicationTypes.h
<gh_stars>1-10 /* * @author <NAME> 09.10.2016 * * Communication state definition. */ #pragma once #include <stdint.h> #include "uc-core/discovery/DiscoveryTypes.h" #include "uc-core/communication/CommunicationTypes.h" #include "uc-core/communication-protocol/CommunicationProtocolTypes.h" /** * facade to bundle port resources */ typedef struct DirectionOrientedPort { /** * discovery related */ DiscoveryPulseCounter *discoveryPulseCounter; /** * communication related */ TxPort *txPort; /** * communication related */ RxPort *rxPort; /** * pointer implementation: decode and interpret reception */ void (*receivePimpl)(void); void (*txHighPimpl)(void); void (*txLowPimpl)(void); /** * comm. protocol related */ CommunicationProtocolPortState *protocol; } DirectionOrientedPort; /** * facade to bundle port resources in a direction oriented way */ typedef struct DirectionOrientedPorts { /** * north port resources */ DirectionOrientedPort north; /** * east port resources */ DirectionOrientedPort east; /** * south port resources */ DirectionOrientedPort south; /** * on simultaneous transmission this port refers to the east port resources */ DirectionOrientedPort simultaneous; } DirectionOrientedPorts;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication-protocol/Commands.h
/** * @author <NAME> 12.07.2016 * * Received package/command related implementation. */ #pragma once #include "uc-core/configuration/communication/Commands.h" #include "CommunicationProtocolTypes.h" #include "CommunicationProtocolPackageTypesCtors.h" #include "uc-core/communication/ManchesterDecodingTypes.h" #include "uc-core/discovery/Discovery.h" #include "uc-core/communication/Transmission.h" #include "uc-core/communication/CommunicationTypesCtors.h" #include "uc-core/synchronization/Synchronization.h" #include "uc-core/configuration/interrupts/LocalTime.h" #include "uc-core/time/Time.h" /** * Executes a synchronize local time package. * Reads the delivered time adds a correction offset and updates the local time. * @param package the package to interpret and execute */ void executeSynchronizeLocalTimePackage(const TimePackage *const package, PortBuffer *const portBuffer) { // DEBUG_INT16_OUT(snapshotBuffer->temporaryTxStopSnapshotTimerValue - snapshotBuffer->temporaryTxStartSnapshotTimerValue); // DEBUG_INT16_OUT(TIMER_TX_RX_COUNTER_VALUE); LED_STATUS2_TOGGLE; // ------------------ update local time --------------------------- #ifndef LOCAL_TIME_IN_PHASE_SHIFTING_ON_LOCAL_TIME_UPDATE // consider the optional request to update the local time if (false == ParticleAttributes.localTime.isNumTimePeriodsPassedUpdateable) { ParticleAttributes.localTime.newNumTimePeriodsPassed = package->timePeriod + 2; MEMORY_BARRIER; ParticleAttributes.localTime.isNumTimePeriodsPassedUpdateable = package->forceTimePeriodUpdate; } #else uint8_t sreg = SREG; MEMORY_BARRIER; CLI; MEMORY_BARRIER; const uint16_t now = TIMER_TX_RX_COUNTER_VALUE; const uint16_t receptionEndTimestamp = portBuffer->localTimeTrackingTimerCounterValueOnPduReceived; const uint16_t nextLocalTimeTriggerAfterReception = portBuffer->nextLocalTimeInterruptOnPduReceived; MEMORY_BARRIER; SREG = sreg; MEMORY_BARRIER; const uint16_t preTxLatency = ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelay * 3; ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest = package->forceTimePeriodUpdate; // consider local time tracking ISR delay shift on local time update if (false == ParticleAttributes.localTime.isNewTimerCounterShiftUpdateable && package->forceTimePeriodUpdate) { const uint16_t sepPduEndToTimeIsrDelay = nextLocalTimeTriggerAfterReception - receptionEndTimestamp; // remote delay from time remote PDU was constructed until remote local time ISR trigger const uint32_t sepConstructUntilIsr = roundf( // factor of remote phase ((float) package->delayUntilNextTimeTrackingIsr / (float) package->localTimeTrackingPeriodInterruptDelay) * // apply to local time unit (float) ParticleAttributes.localTime.newTimePeriodInterruptDelay ); // ---------------------- phase shift calculation ---------------------- /** * Delay since the next remote local time tracking interrupt triggers after the PDU was constructed * until the next local time tracking interrupt triggers after the pdu was received * using locally skewed time units. */ const uint32_t totalShiftSeparation = // time from pdu reception until next local time ISR +sepPduEndToTimeIsrDelay // reception latency + portBuffer->receptionDuration // remote construction until transmission starts + preTxLatency // delay until remote time ISR triggers when PDU was constructed in local time units - sepConstructUntilIsr; int32_t shift = totalShiftSeparation; while (shift >= ParticleAttributes.localTime.newTimePeriodInterruptDelay) { shift -= ParticleAttributes.localTime.newTimePeriodInterruptDelay; } // cap the value for the next shift to the maximum step uint16_t step; if (shift > LOCAL_TIME_IN_PHASE_SHIFTING_MAXIMUM_STEP) { step = LOCAL_TIME_IN_PHASE_SHIFTING_MAXIMUM_STEP; } else { step = shift; } if (shift < (ParticleAttributes.localTime.newTimePeriodInterruptDelay / 2)) { // on short side is left, shift left (shorten the interval) shift = -step; } else { // on short side is right, sift right (extend the interval) shift = step; } // expose calculated phase shift to ISR ParticleAttributes.localTime.newTimerCounterShift = shift; MEMORY_BARRIER; ParticleAttributes.localTime.isNewTimerCounterShiftUpdateable = true; // ---------------------- reproduce passed time intervals ---------------------- // TODO: reading TIMER_TX_RX_COUNTER_VALUE should happen as late as possible // const uint16_t now = TIMER_TX_RX_COUNTER_VALUE; const uint16_t postRxToInterpeterDelay = now - receptionEndTimestamp; /** * Total delay since the next remote time ISR triggers when PDU was constructed until * now. */ uint32_t totalSeparation = // PDU received to interpreter latency postRxToInterpeterDelay // reception latency + portBuffer->receptionDuration // remote construction until transmission starts + preTxLatency // delay until remote time ISR triggers when PDU was constructed in local time units - sepConstructUntilIsr; uint16_t numTimeIntervals = 2; while (totalSeparation >= ParticleAttributes.localTime.newTimePeriodInterruptDelay) { totalSeparation -= ParticleAttributes.localTime.newTimePeriodInterruptDelay; ++numTimeIntervals; } // expose calculated number of passed periods to ISR ParticleAttributes.localTime.newNumTimePeriodsPassed = package->timePeriod + numTimeIntervals; MEMORY_BARRIER; ParticleAttributes.localTime.isNumTimePeriodsPassedUpdateable = true; } #endif // ------------------ approximate new clock skew --------------------------- // calculate observed PDU duration #ifdef SYNCHRONIZATION_TIME_PACKAGE_DURATION_COUNTING_FIRST_TO_LAST_BIT_EDGE const uint32_t sample = // remove delay from PDU start until 1st bit ((portBuffer->receptionDuration - ((uint32_t) portBuffer->firstFallingToRisingDuration)) // remove delay from last bit until PDU end - ((uint32_t) portBuffer->lastFallingToRisingDuration)) // shift value down by -UINT16_MAX/2 - (uint32_t) TIME_SYNCHRONIZATION_SAMPLE_OFFSET; #else // shift value down by -UINT16_MAX/2 const uint32_t sample = portBuffer->receptionDuration - (uint32_t) TIME_SYNCHRONIZATION_SAMPLE_OFFSET; #endif SampleValueType sampleValue = (SampleValueType) sample; samplesFifoBufferAddSample(&sampleValue, &ParticleAttributes.timeSynchronization); tryApproximateTimings(); // ------------------ schedule re-transmission of new time package --------------------------- // schedule when the new sync. package is to be forwarded according to the current local time ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; ParticleAttributes.protocol.isBroadcastEnabled = package->header.enableBroadcast; } /** * Executes a set local address package. * @param package the package to interpret and execute */ void executeSetLocalAddress(const EnumerationPackage *const package) { ParticleAttributes.node.address.row = package->addressRow; ParticleAttributes.node.address.column = package->addressColumn; ParticleAttributes.protocol.hasNetworkGeometryDiscoveryBreadCrumb = package->hasNetworkGeometryDiscoveryBreadCrumb; } /** * The rightmost bottommost node announces it's address. * This node relays the package if it is not the origin (top left), otherwise consumes it. * @param package the package to interpret and execute */ void executeAnnounceNetworkGeometryPackage(const AnnounceNetworkGeometryPackage *const package) { if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN) { ParticleAttributes.protocol.networkGeometry.rows = package->rows; ParticleAttributes.protocol.networkGeometry.columns = package->columns; ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; // ParticleAttributes.node.state = STATE_TYPE_SYNC_NEIGHBOUR; ParticleAttributes.node.state = STATE_TYPE_SYNC_NEIGHBOUR_DONE; setInitiatorStateStart(ParticleAttributes.directionOrientedPorts.simultaneous.protocol); } else { constructAnnounceNetworkGeometryPackage(package->rows, package->columns); setInitiatorStateStart(&ParticleAttributes.protocol.ports.north); ParticleAttributes.node.state = STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_RELAY; ParticleAttributes.protocol.isBroadcastEnabled = package->header.enableBroadcast; } } /** * Copies exactly 9 bytes from source to destination. * @param source where to read the bytes from * @param destination where to store the bytes to */ static void __volatileSram9ByteMemcopy(const void *const source, volatile void *const destination) { ((uint16_t *) destination)[0] = ((uint16_t *) source)[0]; ((uint16_t *) destination)[1] = ((uint16_t *) source)[1]; ((uint16_t *) destination)[2] = ((uint16_t *) source)[2]; ((uint16_t *) destination)[3] = ((uint16_t *) source)[3]; ((uint8_t *) destination)[8] = ((uint8_t *) source)[8]; } /** * Copies the buffer from the source port to destination port and prepares * but does not enable the transmission. * @param source reference to the package to relay * @param destination reference to the destination transmission port * @param dataEndPointer the pointer marking the data end on buffer * @param endState the node state to switch to */ static void __relayPackage(const Package *const source, const DirectionOrientedPort *const destination, uint16_t dataEndPointer, StateType endState) { clearTransmissionPortBuffer(destination->txPort); setInitiatorStateStart(destination->protocol); __volatileSram9ByteMemcopy(source, destination->txPort->buffer.bytes); setBufferDataEndPointer(&destination->txPort->dataEndPos, dataEndPointer); ParticleAttributes.node.state = endState; if (destination == &ParticleAttributes.directionOrientedPorts.simultaneous) { ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = true; } else { ParticleAttributes.protocol.isSimultaneousTransmissionEnabled = false; } } /** * Forward/route package and execute a set new network geometry command. * The network geometry spans a in a rectangular shape from node address * (1,1) to inclusive the address transported by the package. * If the current address resides outside the range, the particle relays * the package and switches to sleep mode. * Otherwise it preserves current state. * Forwarding is skipped in broadcast mode. * Performs simultaneous transmission on splitting points. * @param package the package to interpret and execute */ void executeSetNetworkGeometryPackage(const SetNetworkGeometryPackage *const package) { bool deactivateParticle = false; if (ParticleAttributes.node.address.row > package->rows || ParticleAttributes.node.address.column > package->columns) { deactivateParticle = true; ParticleAttributes.node.state = STATE_TYPE_PREPARE_FOR_SLEEP; } if (!ParticleAttributes.protocol.isBroadcastEnabled) { // on disabled broadcast: relay package bool routeToEast = ParticleAttributes.discoveryPulseCounters.east.isConnected; bool routeToSouth = ParticleAttributes.discoveryPulseCounters.south.isConnected; if (routeToEast && routeToSouth) { StateType nextState = (deactivateParticle) ? STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH_THEN_PREPARE_SLEEP : STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH; __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.simultaneous, SetNetworkGeometryPackageBufferPointerSize, nextState); } else if (routeToEast) { StateType nextState = (deactivateParticle) ? STATE_TYPE_SENDING_PACKAGE_TO_EAST_THEN_PREPARE_SLEEP : STATE_TYPE_SENDING_PACKAGE_TO_EAST; __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.east, SetNetworkGeometryPackageBufferPointerSize, nextState); } else if (routeToSouth) { StateType nextState = (deactivateParticle) ? STATE_TYPE_SENDING_PACKAGE_TO_SOUTH_THEN_PREPARE_SLEEP : STATE_TYPE_SENDING_PACKAGE_TO_SOUTH; __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.south, SetNetworkGeometryPackageBufferPointerSize, nextState); } } ParticleAttributes.protocol.isBroadcastEnabled = package->header.enableBroadcast; // update node type accordingly if (ParticleAttributes.node.address.row == package->rows) { ParticleAttributes.discoveryPulseCounters.south.isConnected = false; } if (ParticleAttributes.node.address.column == package->columns) { ParticleAttributes.discoveryPulseCounters.east.isConnected = false; } updateAndDetermineNodeType(); } static uint16_t __getHeatWiresDuration(HeatWiresPackage const *const package) { return (((uint16_t) package->durationMsb) << 8) | package->durationLsb; } static uint16_t __getHeatWiresRangeDuration(HeatWiresRangePackage const *const package) { return (((uint16_t) package->durationMsb) << 8) | package->durationLsb; } /** * Infer an actuation command from a heat wires package or a heat wires range package * for the the east actuator. * This ensures the adjacent node is closing the current loop at the respective actuator. * @param package the package to infer actuator actions from */ static void __inferEastActuatorCommand(const Package *const package) { if (ParticleAttributes.actuationCommand.executionState == ACTUATION_STATE_TYPE_IDLE && package->asHeader.id == PACKAGE_HEADER_ID_TYPE_HEAT_WIRES) { if (package->asHeader.isRangeCommand) { const HeatWiresRangePackage *const heatWiresRangePackage = &package->asHeatWiresRangePackage; if (heatWiresRangePackage->northRight) ParticleAttributes.actuationCommand.actuators.eastLeft = true; if (heatWiresRangePackage->northLeft) ParticleAttributes.actuationCommand.actuators.eastRight = true; ParticleAttributes.actuationCommand.actuationStart.periodTimeStamp = heatWiresRangePackage->startTimeStamp; ParticleAttributes.actuationCommand.actuationEnd.periodTimeStamp = heatWiresRangePackage->startTimeStamp + __getHeatWiresRangeDuration(heatWiresRangePackage); ParticleAttributes.actuationCommand.isScheduled = true; } else { const HeatWiresPackage *const heatWiresPackage = &package->asHeatWiresPackage; if (heatWiresPackage->northRight) ParticleAttributes.actuationCommand.actuators.eastLeft = true; if (heatWiresPackage->northLeft) ParticleAttributes.actuationCommand.actuators.eastRight = true; ParticleAttributes.actuationCommand.actuationStart.periodTimeStamp = heatWiresPackage->startTimeStamp; ParticleAttributes.actuationCommand.actuationEnd.periodTimeStamp = heatWiresPackage->startTimeStamp + __getHeatWiresDuration(heatWiresPackage); ParticleAttributes.actuationCommand.isScheduled = true; } } } /** * Infer an actuation command from a heat wires package or a heat wires range package * for the the south actuator. This ensures the adjacent node is closing the current loop at * the respective actuator. * @param package the package to infer actuator actions from */ static void __inferSouthActuatorCommand(const Package *const package) { if (package->asHeader.id == PACKAGE_HEADER_ID_TYPE_HEAT_WIRES && ParticleAttributes.actuationCommand.executionState == ACTUATION_STATE_TYPE_IDLE) { if (package->asHeader.isRangeCommand) { const HeatWiresRangePackage *const heatWiresRangePackage = &package->asHeatWiresRangePackage; if (heatWiresRangePackage->northRight) ParticleAttributes.actuationCommand.actuators.southLeft = true; if (heatWiresRangePackage->northLeft) ParticleAttributes.actuationCommand.actuators.southRight = true; ParticleAttributes.actuationCommand.actuationStart.periodTimeStamp = heatWiresRangePackage->startTimeStamp; ParticleAttributes.actuationCommand.actuationEnd.periodTimeStamp = heatWiresRangePackage->startTimeStamp + __getHeatWiresRangeDuration(heatWiresRangePackage); ParticleAttributes.actuationCommand.isScheduled = true; } else { const HeatWiresPackage *const heatWiresPackage = &package->asHeatWiresPackage; if (heatWiresPackage->northRight) ParticleAttributes.actuationCommand.actuators.southLeft = true; if (heatWiresPackage->northLeft) ParticleAttributes.actuationCommand.actuators.southRight = true; ParticleAttributes.actuationCommand.actuationStart.periodTimeStamp = heatWiresPackage->startTimeStamp; ParticleAttributes.actuationCommand.actuationEnd.periodTimeStamp = heatWiresPackage->startTimeStamp + __getHeatWiresDuration(heatWiresPackage); ParticleAttributes.actuationCommand.isScheduled = true; } } } /** * Interpret a heat wires or heat wires range package and schedule the command. * @param package the package to interpret and execute */ static void __scheduleHeatWiresCommand(const Package *const package) { if (package->asHeader.id == PACKAGE_HEADER_ID_TYPE_HEAT_WIRES) { if (package->asHeader.isRangeCommand) { const HeatWiresRangePackage *const heatWiresRangePackage = &package->asHeatWiresRangePackage; ParticleAttributes.actuationCommand.actuators.northLeft = heatWiresRangePackage->northLeft; ParticleAttributes.actuationCommand.actuators.northRight = heatWiresRangePackage->northRight; ParticleAttributes.actuationCommand.actuationStart.periodTimeStamp = heatWiresRangePackage->startTimeStamp; ParticleAttributes.actuationCommand.actuationEnd.periodTimeStamp = heatWiresRangePackage->startTimeStamp + __getHeatWiresRangeDuration(heatWiresRangePackage); ParticleAttributes.protocol.isBroadcastEnabled = heatWiresRangePackage->header.enableBroadcast; ParticleAttributes.actuationCommand.isScheduled = true; } else { const HeatWiresPackage *const heatWiresPackage = &package->asHeatWiresPackage; ParticleAttributes.actuationCommand.actuators.northLeft = heatWiresPackage->northLeft; ParticleAttributes.actuationCommand.actuators.northRight = heatWiresPackage->northRight; ParticleAttributes.actuationCommand.actuationStart.periodTimeStamp = heatWiresPackage->startTimeStamp; ParticleAttributes.actuationCommand.actuationEnd.periodTimeStamp = heatWiresPackage->startTimeStamp + __getHeatWiresDuration(heatWiresPackage); ParticleAttributes.protocol.isBroadcastEnabled = heatWiresPackage->header.enableBroadcast; ParticleAttributes.actuationCommand.isScheduled = true; } } } /** * Forward/route package and execute a heat wires package. * Forwarding is skipped in broadcast mode. * Performs simultaneous transmission on splitting points. * @param package the package to interpret and execute */ void executeHeatWiresPackage(const HeatWiresPackage *const package) { if (ParticleAttributes.node.address.row == package->addressRow && ParticleAttributes.node.address.column == package->addressColumn && ParticleAttributes.actuationCommand.executionState == ACTUATION_STATE_TYPE_IDLE) { // on package reached destination: consume package __scheduleHeatWiresCommand((Package *) package); return; } bool routeToEast = false, routeToSouth = false, inferLocalCommand = false; // on package forwarding if (ParticleAttributes.node.address.column < package->addressColumn) { routeToEast = true; } else if (ParticleAttributes.node.address.column == package->addressColumn) { routeToSouth = true; } if ((ParticleAttributes.node.address.row + 1 == package->addressRow && ParticleAttributes.node.address.column == package->addressColumn) || (ParticleAttributes.node.address.row == package->addressRow && ParticleAttributes.node.address.column + 1 == package->addressColumn)) { // on destination equals some subsequent neighbor inferLocalCommand = true; } if (routeToEast) { if (false == ParticleAttributes.protocol.isBroadcastEnabled) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.east, HeatWiresPackageBufferPointerSize, STATE_TYPE_SENDING_PACKAGE_TO_EAST); ParticleAttributes.protocol.isBroadcastEnabled = false; } if (inferLocalCommand) { __inferEastActuatorCommand((Package *) package); } } else if (routeToSouth) { if (false == ParticleAttributes.protocol.isBroadcastEnabled) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.south, HeatWiresPackageBufferPointerSize, STATE_TYPE_SENDING_PACKAGE_TO_SOUTH); ParticleAttributes.protocol.isBroadcastEnabled = false; } if (inferLocalCommand) { __inferSouthActuatorCommand((Package *) package); } } } /** * Forward/route package and execute a heat wires range package. * Forwarding is skipped in broadcast mode. * Performs simultaneous transmission on splitting points. * @param package the package to interpret and execute */ void executeHeatWiresRangePackage(const HeatWiresRangePackage *const package) { NodeAddress nodeAddressTopLeft; NodeAddress nodeAddressBottomRight; nodeAddressTopLeft.row = package->addressRow0; nodeAddressTopLeft.column = package->addressColumn0; nodeAddressBottomRight.row = package->addressRow1; nodeAddressBottomRight.column = package->addressColumn1; // route to east if // i) current node's address column is less than node range bottom right column bool routeToEast = false; if (ParticleAttributes.node.address.column < nodeAddressBottomRight.column && ParticleAttributes.directionOrientedPorts.east.discoveryPulseCounter->isConnected) { routeToEast = true; } // route to south if // i) current node's column is within node range columns boundary and // ii) current node's row is less than node range bottom right row bool routeToSouth = false; if ((nodeAddressTopLeft.column <= ParticleAttributes.node.address.column && ParticleAttributes.node.address.column <= nodeAddressBottomRight.column) && ParticleAttributes.node.address.row < nodeAddressBottomRight.row && ParticleAttributes.directionOrientedPorts.south.discoveryPulseCounter->isConnected) { routeToSouth = true; } // a) infer local command if // i) the current node address is within the node range or // ii) belongs to the row above and is within the range columns boundary bool inferLocalCommand = false; if ((nodeAddressTopLeft.row - 1 <= ParticleAttributes.node.address.row && ParticleAttributes.node.address.row < nodeAddressBottomRight.row) && (nodeAddressTopLeft.column <= ParticleAttributes.node.address.column && ParticleAttributes.node.address.column <= nodeAddressBottomRight.column)) { inferLocalCommand = true; } // b) also infer local command if the range top left node's north port is connected // to the parent's east port if (nodeAddressTopLeft.row == 1 && ParticleAttributes.node.address.row == 1 && ParticleAttributes.node.address.column == nodeAddressTopLeft.column - 1) { inferLocalCommand = true; } if (routeToEast && routeToSouth) { if (!ParticleAttributes.protocol.isBroadcastEnabled) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.simultaneous, HeatWiresRangePackageBufferPointerSize, STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH); } if (inferLocalCommand) { __inferEastActuatorCommand((Package *) package); __inferSouthActuatorCommand((Package *) package); } } else if (routeToEast) { if (!ParticleAttributes.protocol.isBroadcastEnabled) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.east, HeatWiresRangePackageBufferPointerSize, STATE_TYPE_SENDING_PACKAGE_TO_EAST); } if (inferLocalCommand) { __inferEastActuatorCommand((Package *) package); } } else if (routeToSouth) { if (!ParticleAttributes.protocol.isBroadcastEnabled) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.south, HeatWiresRangePackageBufferPointerSize, STATE_TYPE_SENDING_PACKAGE_TO_SOUTH); } if (inferLocalCommand) { __inferSouthActuatorCommand((Package *) package); } } // interpret heat wires range command if ((nodeAddressTopLeft.row <= ParticleAttributes.node.address.row && ParticleAttributes.node.address.row <= nodeAddressBottomRight.row) && (nodeAddressTopLeft.column <= ParticleAttributes.node.address.column && ParticleAttributes.node.address.column <= nodeAddressBottomRight.column)) { __scheduleHeatWiresCommand(((Package *) package)); } } /** * Forwards a header package to all connected ports and interpret the relevant content. * Forwarding is skipped in broadcast mode. * Performs simultaneous transmission on splitting points. * @param package the package to interpret and execute */ void executeHeaderPackage(const HeaderPackage *const package) { if (!ParticleAttributes.protocol.isBroadcastEnabled) { // on disabled broadcast: relay package bool routeToEast = ParticleAttributes.discoveryPulseCounters.east.isConnected; bool routeToSouth = ParticleAttributes.discoveryPulseCounters.south.isConnected; if (routeToEast && routeToSouth) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.simultaneous, HeaderPackagePointerSize, STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH); } else if (routeToEast) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.east, HeaderPackagePointerSize, STATE_TYPE_SENDING_PACKAGE_TO_EAST); } else if (routeToSouth) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.south, HeaderPackagePointerSize, STATE_TYPE_SENDING_PACKAGE_TO_SOUTH); } } ParticleAttributes.protocol.isBroadcastEnabled = package->enableBroadcast; } /** * Forwards package and interpret the relevant content. * Forwarding is skipped in broadcast mode. * Performs simultaneous transmission on splitting points. * @param package the package to interpret and execute */ void executeHeatWiresModePackage(const HeatWiresModePackage *const package) { if (!ParticleAttributes.protocol.isBroadcastEnabled) { // on disabled broadcast: relay package bool routeToEast = ParticleAttributes.discoveryPulseCounters.east.isConnected; bool routeToSouth = ParticleAttributes.discoveryPulseCounters.south.isConnected; if (routeToEast && routeToSouth) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.simultaneous, SetNetworkGeometryPackageBufferPointerSize, STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH); } else if (routeToEast) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.east, SetNetworkGeometryPackageBufferPointerSize, STATE_TYPE_SENDING_PACKAGE_TO_EAST); } else if (routeToSouth) { __relayPackage((Package *) package, &ParticleAttributes.directionOrientedPorts.south, SetNetworkGeometryPackageBufferPointerSize, STATE_TYPE_SENDING_PACKAGE_TO_SOUTH); } } ParticleAttributes.protocol.isBroadcastEnabled = package->header.enableBroadcast; ParticleAttributes.actuationCommand.actuationPower.dutyCycleLevel = package->heatMode; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/Time.h
<reponame>ProgrammableMatter/particle-firmware /** * @author <NAME> 12.07.2016 * * Local time related arguments. */ #pragma once #include "uc-core/configuration/communication/Communication.h" /** * Put the local time tracking ISR timer counter in phase once the local time is updated by a time package. * Disabling macro disables the feature. */ #define LOCAL_TIME_IN_PHASE_SHIFTING_ON_LOCAL_TIME_UPDATE /** * In case the phase has to be shifted more than the maximum step * the value is capped to the maximum step value. */ #define LOCAL_TIME_IN_PHASE_SHIFTING_MAXIMUM_STEP ((uint16_t) 2000) /** * Defines the working point of the local time tracking interrupt. * I.e. if the incoming manchester clock is observed to be 1021, the * local time tracking will trigger each 51*1021=52071 clocks. */ #define LOCAL_TIME_TRACKING_INT_DELAY_MANCHESTER_CLOCK_MULTIPLIER ((uint8_t) 51) /** * The initial local time tracking ISR separation in clocks. */ #define LOCAL_TIME_TRACKING_INT_DELAY_MANCHESTER_CLOCK_INITIAL_VALUE \ ((uint16_t) LOCAL_TIME_TRACKING_INT_DELAY_MANCHESTER_CLOCK_MULTIPLIER * \ COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY)
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/Leds.h
<filename>src/avr-common/utils/uc-core/configuration/Leds.h /** * @author <NAME> 2016 * * LEDs related arguments. */ #pragma once /** * Enable define to suppress all LED outputs. * Disable define to enable all LED outputs. */ #define LEDS_SUPPRESS_OUTPUT
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/synchronization/Synchronization.h
<filename>src/avr-common/utils/uc-core/configuration/synchronization/Synchronization.h /** * @author <NAME> 24.09.2016 * * Synchronization related arguments. */ #pragma once /** * The difference of measured synchronization package durations are shifted by the synthetic offset UINT16_MAX/2=0x7fff * to overcome the need of signed data types. */ #define TIME_SYNCHRONIZATION_SAMPLE_OFFSET ((uint16_t) INT16_MAX) /** * If defined the time approximation will take the time in between the 1st and the last * bit of the time package (1st rising, last falling edge). For more information see * __SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL_FIRST_RISING_TO_LAST_FALLING_EDGE_630. */ #define SYNCHRONIZATION_TIME_PACKAGE_DURATION_COUNTING_FIRST_TO_LAST_BIT_EDGE /** * Mean calculation on-line vs off-line. * Uses more flash memory, may speed up the synchronization approximation slightly. */ //#define SYNCHRONIZATION_STRATEGY_MEAN_ENABLE_ONLINE_CALCULATION /** * Synchronization strategy. */ //#define SYNCHRONIZATION_STRATEGY_RAW_OBSERVATION #define SYNCHRONIZATION_STRATEGY_MEAN //#define SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN //#define SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_OUTLIER //#define SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_MARKED_OUTLIER //#define SYNCHRONIZATION_ENABLE_ADAPTIVE_MARKED_OUTLIER_REJECTION //#define SYNCHRONIZATION_STRATEGY_LEAST_SQUARE_LINEAR_FITTING /** * Defines the factor f for outlier detection. Samples having values not within * [µ - f * σ, µ + f * σ] are rejected. */ //#define SYNCHRONIZATION_OUTLIER_REJECTION_SIGMA_FACTOR ((CalculationType) 3.0) //#define SYNCHRONIZATION_OUTLIER_REJECTION_SIGMA_FACTOR ((CalculationType) 2.8) #define SYNCHRONIZATION_OUTLIER_REJECTION_SIGMA_FACTOR ((CalculationType) 2.0) //#define SYNCHRONIZATION_OUTLIER_REJECTION_SIGMA_FACTOR ((CalculationType) 1.0) /** * Defines the number of manchester clocks in the reference time PDU. Instead measuring the whole package * duration (first falling to last rising edge) the the first rising to last falling edge is taken as * reference. This has two major reasons: * I) The transmitter's manchester coding has not the same delay when generating manchester clock or data * signals. Generating clock signals has approx. 6 to 8 instruction more latency versus clock signal. Thus we * take the first data signal as package start reference, which is the first riding edge since any package * starts with a start bit=1. As pdu end we take the last data bit, which is the last falling edge since the * time package has per definition the last bit=0. * II) To get slightly more accurate values, one should prefer using falling edges instead of rising, since * the flank is steeper. * * To overcome this complication one may refactor the coding implementation and calculate the manchester code * off line. The current design decision (on line coding) was based on saving SRAM. */ #define __SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL_FIRST_RISING_TO_LAST_FALLING_EDGE_630 ((float) 63.0) /** * Defines the number of manchester clocks in the reference time PDU. * First edge to last edge refers to the whole whole PDU length. */ #define __SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL_FIRST_FALLING_TO_LAST_EDGE_640 ((float) 64.0) #ifdef SYNCHRONIZATION_TIME_PACKAGE_DURATION_COUNTING_FIRST_TO_LAST_BIT_EDGE # define SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL \ __SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL_FIRST_RISING_TO_LAST_FALLING_EDGE_630 #else # define SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL \ __SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL_FIRST_FALLING_TO_LAST_EDGE_640 #endif #ifdef SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN //#define __SYNCHRONIZATION_STRATEGY_MEAN_OLD_VALUE_WEIGHT ((float)0.5) //#define __SYNCHRONIZATION_STRATEGY_MEAN_NEW_VALUE_WEIGHT ((float)0.5) //#define __SYNCHRONIZATION_STRATEGY_MEAN_OLD_VALUE_WEIGHT ((float)0.9) //#define __SYNCHRONIZATION_STRATEGY_MEAN_NEW_VALUE_WEIGHT ((float)0.1) #define __SYNCHRONIZATION_STRATEGY_MEAN_OLD_VALUE_WEIGHT ((float)0.75) #define __SYNCHRONIZATION_STRATEGY_MEAN_NEW_VALUE_WEIGHT ((float)0.25) //#define __SYNCHRONIZATION_STRATEGY_MEAN_OLD_VALUE_WEIGHT ((float)0.99) //#define __SYNCHRONIZATION_STRATEGY_MEAN_NEW_VALUE_WEIGHT ((float)0.01) #define SYNCHRONIZATION_STRATEGY_MEAN_OLD_VALUE_WEIGHT __SYNCHRONIZATION_STRATEGY_MEAN_OLD_VALUE_WEIGHT #define SYNCHRONIZATION_STRATEGY_MEAN_NEW_VALUE_WEIGHT __SYNCHRONIZATION_STRATEGY_MEAN_NEW_VALUE_WEIGHT #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/ManchesterDecodingTypesCtors.h
/** * @author <NAME> 2016 * * Manchester types constructor implementation. */ #pragma once #include "ManchesterDecodingTypes.h" /** * constructor function * @param o reference to the object to construct */ void constructSnapshot(Snapshot *const o) { o->isRisingEdge = false; o->timerValue = 0; } /** * constructor function * @param o reference to the object to construct */ void constructManchesterDecoderState(ManchesterDecoderStates *const o) { o->decodingState = DECODER_STATE_TYPE_START; o->phaseState = 0; } /** * constructor function * @param o reference to the object to construct */ void constructRxSnapshotBuffer(RxSnapshotBuffer *const o) { constructManchesterDecoderState(&o->decoderStates); o->startIndex = 0; o->endIndex = 0; o->temporarySnapshotTimerValue = 0; o->isOverflowed = false; o->numberHalfCyclesPassed = 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/scheduler/Scheduler.h
/** * @author <NAME> 11.10.2016 * * Scheduler related implementation. */ #pragma once #include "Scheduler.h" #include "uc-core/particle/Globals.h" #include "common/common.h" #include "uc-core/particle/types/ParticleStateTypes.h" void taskEnableNodeTypeLimit(uint8_t taskId, NodeType nodeType) { SchedulerTask *task = &ParticleAttributes.scheduler.tasks[taskId]; task->isNodeTypeLimited = true; task->nodeType = nodeType; } void taskEnableStateTypeLimt(uint8_t taskId, StateType stateType) { SchedulerTask *task = &ParticleAttributes.scheduler.tasks[taskId]; task->isStateLimited = true; task->state = stateType; } void taskEnableCountLimit(uint8_t taskId, uint16_t numCalls) { SchedulerTask *task = &ParticleAttributes.scheduler.tasks[taskId]; task->isCountLimitedTask = true; task->isLastCall = false; task->numCalls = numCalls; } void taskDisableCountLimit(uint8_t taskId) { SchedulerTask *task = &ParticleAttributes.scheduler.tasks[taskId]; task->isCountLimitedTask = false; task->isLastCall = false; } void taskDisable(uint8_t taskId) { ParticleAttributes.scheduler.tasks[taskId].isEnabled = false; } void taskEnable(uint8_t taskId) { ParticleAttributes.scheduler.tasks[taskId].isEnabled = true; } /** * Adds a single shot task to the scheduler. * @param taskId the id in the scheduler's array * @param task function pointer to execute * @param timestamp the 1st (desired) execution timestamp */ void addSingleShotTask(const uint8_t taskId, void (*const action)(SchedulerTask *const task), const uint16_t timestamp) { SchedulerTask *task = &ParticleAttributes.scheduler.tasks[taskId]; constructSchedulerTask(task); task->startAction = action; task->startTimestamp = timestamp; task->isEnabled = true; } /** * Adds a cyclic task to the scheduler. * @param taskId the id in the scheduler's array * @param task function pointer to execute * @param timestamp the 1st (desired) execution timestamp * @param separation the delay until the subsequent execution, must be < than UINT16_MAX */ void addCyclicTask(const uint8_t taskId, void (*const action)(SchedulerTask *const task), const uint16_t timestamp, const uint16_t separation) { SchedulerTask *task = &ParticleAttributes.scheduler.tasks[taskId]; constructSchedulerTask(task); task->isCyclicTask = true; task->startAction = action; task->startTimestamp = timestamp; task->reScheduleDelay = separation; task->isEnabled = true; } static void __onCountLimitedTaskDecrementCounter(SchedulerTask *const task) { if (task->isCountLimitedTask) { --task->numCalls; if (task->numCalls <= 0) { task->isLastCall = true; } } } /** * Assures a task's start action is executed once asap after the desired start timestamp * and (on time limited tasks) the task's end action executed once after the end time stamp. * If a node state is specified (state limited tasks) the actions are performed only within this states. * TODO: cyclic task */ void processScheduler(void) { uint8_t sreg = SREG; MEMORY_BARRIER; CLI; MEMORY_BARRIER; uint16_t const now = ParticleAttributes.localTime.numTimePeriodsPassed; MEMORY_BARRIER; SREG = sreg; MEMORY_BARRIER; for (uint8_t idx = 0; idx < SCHEDULER_MAX_TASKS; idx++) { SchedulerTask *task = &ParticleAttributes.scheduler.tasks[idx]; if (now < ParticleAttributes.scheduler.lastCallToScheduler) { // on local time tracking overflowed, unlock tasks kept back task->__isExecutionRetained = false; } // on disabled task if (!task->isEnabled) { continue; } // on state limited task if (task->isStateLimited) { if (task->state != ParticleAttributes.node.state) { continue; } } // on node type limited task if (task->isNodeTypeLimited) { if (task->nodeType != ParticleAttributes.node.type) { continue; } } // on count limited task if (task->isCountLimitedTask) { if (task->numCalls <= 0) { continue; } } // on time limited task if (task->isTimeLimited) { if (task->startTimestamp <= now && false == task->isStartActionExecuted) { task->startAction(task); task->isStartActionExecuted = true; } else if (task->endTimestamp <= now && true == task->isStartActionExecuted && false == task->isEndActionExecuted) { task->endAction(task); task->isEndActionExecuted = true; task->isExecuted = true; task->isEnabled = false; } } // on cyclic task, re-schedule next timestamp else if (task->isCyclicTask) { if (task->startTimestamp <= now && task->__isExecutionRetained == false) { __onCountLimitedTaskDecrementCounter(task); task->startAction(task); task->isExecuted = true; uint16_t nextExecution = now + task->reScheduleDelay; if (nextExecution < now) { // on timestamp overflow: the counter is updated is retained until the local // time has also overflowed task->__isExecutionRetained = true; } task->startTimestamp = nextExecution; } } // on single shot task else { if (task->startTimestamp <= now && false == task->isStartActionExecuted) { __onCountLimitedTaskDecrementCounter(task); task->startAction(task); task->isStartActionExecuted = true; task->isExecuted = true; task->isEnabled = false; } } } ParticleAttributes.scheduler.lastCallToScheduler = now; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/actuation/ActuationTypes.h
/** * @author <NAME> 12.07.2016 * * Actuation types definition. */ #pragma once #include <stdint.h> /** * Describes all possible output modes. */ typedef enum HeatingLevelType { HEATING_LEVEL_TYPE_MAXIMUM = 0x0, HEATING_LEVEL_TYPE_STRONG = 0x1, HEATING_LEVEL_TYPE_MEDIUM = 0x2, HEATING_LEVEL_TYPE_WEAK = 0x3, } HeatingLevelType; /** * Describes the actuation command execution state. */ typedef enum ActuationStateType { ACTUATION_STATE_TYPE_IDLE, ACTUATION_STATE_TYPE_START, ACTUATION_STATE_TYPE_WORKING, ACTUATION_STATE_TYPE_RELAXATION_PAUSE, ACTUATION_STATE_TYPE_DONE, } ActuationStateType; /** * Describes which wires are to be actuated. South and east wires will be * actuated passively (pulled up or low), whereas north wires will be pulsed * according to the power configuration. * Only north wires are driven by IDR, thus volatile. */ typedef struct Actuators { /** * north left wire */ volatile uint8_t northLeft : 1; /** * north right wire */ volatile uint8_t northRight : 1; /** * east left wire: in case of folding along x-axis */ uint8_t eastLeft : 1; /** * east right wire: in case of folding along x-axis */ uint8_t eastRight : 1; /** * south left wire */ uint8_t southLeft :1; /** * south right wire */ uint8_t southRight :1; uint8_t __pad : 2; } Actuators; /** * Describes the heating mode/output power. */ typedef struct HeatingMode { uint8_t dutyCycleLevel : 2; uint8_t __pad : 6; } HeatingMode; /** * describes a local time stamp */ typedef struct LocalTime { uint16_t periodTimeStamp; } LocalTime; /** * Describes an actuation command. */ typedef struct ActuationCommand { /** * actuator flags */ Actuators actuators; /** * power level configuration for all actuators */ HeatingMode actuationPower; /** * execution state machine states */ ActuationStateType executionState; /** * actuation start time */ LocalTime actuationStart; /** * actuation end time */ LocalTime actuationEnd; /** * scheduled flag: must be set to enable scheduling; * is unset when execution has finished */ uint8_t isScheduled : 1; uint8_t __pad : 7; } ActuationCommand;
ProgrammableMatter/particle-firmware
src/avr-common/utils/common/PortDDefinition.h
/** * @author <NAME> 2015 */ #pragma once #include <avr/io.h> #define DOut PORTD #define DIn PIND #define DDir DDRD
ProgrammableMatter/particle-firmware
src/avr-common/utils/common/PortCDefinition.h
<gh_stars>1-10 /** * @author <NAME> 2015 */ #pragma once #include <avr/io.h> #define COut PORTC #define CIn PINC #define CDir DDRC
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/LeastSquareRegressionTypes.h
/** * @author <NAME> 23.09.2016 * * Linear Least Squares Regression related types. */ #pragma once #include <stdint.h> #include "BasicCalculationTypes.h" typedef struct LeastSquareRegressionResult { /** * k as known of f(x)=k*x+d */ CalculationType k; /** * d as known of f(x)=k*x+d */ CalculationType d; } LeastSquareRegressionResult;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/NodeAddressTypes.h
<gh_stars>1-10 /* * @author <NAME> 2016 * * Node address state definition. */ #pragma once #include <stdint.h> /** * The node address in the network. The origin node is addressed as row=1, column=1. * Address (0,0) is reserved. */ typedef struct NodeAddress { uint8_t row; uint8_t column; } NodeAddress;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/discovery/DiscoveryTypes.h
/* * @author <NAME> 09.10.2016 * * Discovery state definition. */ #pragma once #include <stdint.h> /** * The discovery pulse counter stores the amount of discovery pulses and the connectivity state. */ typedef struct DiscoveryPulseCounter { // discovery pulse counter volatile uint8_t counter : 5; // connectivity flag volatile uint8_t isConnected : 1; volatile uint8_t __pad : 2; } DiscoveryPulseCounter;
ProgrammableMatter/particle-firmware
src/particle-simulation/main/main.c
/** * @author <NAME> 2015 */ #include <uc-core/particle/ParticleLoop.h> int main(void) { processLoop(); return 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/LeastSquareRegression.h
/** * @author <NAME> 23.09.2016 * * Linear Least Squares Regression related implementation. */ #pragma once #include "SynchronizationTypes.h" #include "Deviation.h" /** * Calculating Linear Least Squares fitting function for measured values: * https://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)#Orthogonal_decomposition_methods * The output (fitting function and several statistical values) are stored to the SamplesFifoBuffer. * The arithmetic mean is calculated in the same pass followed by a second std deviance pass. */ void calculateLinearFittingFunctionVarianceAndStdDeviance(void) { TimeSynchronization *const timeSynchronization = &ParticleAttributes.timeSynchronization; CumulationType a_ = 0, b_ = 0, c_ = 0, e_ = 0; SampleValueType y = 0; IndexType x = 1; // // TODO: evaluation code // CLI; // samplesFifoBufferIteratorStart(&timeSynchronization->timeIntervalSamples); // do { // printf("%u,\n", // timeSynchronization->timeIntervalSamples.samples[timeSynchronization->timeIntervalSamples.iterator].value); // samplesFifoBufferFiFoBufferIteratorNext(&timeSynchronization->timeIntervalSamples); // } while (timeSynchronization->timeIntervalSamples.iterator < // TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END); samplesFifoBufferIteratorStart(&timeSynchronization->timeIntervalSamples); do { y = timeSynchronization->timeIntervalSamples.samples[timeSynchronization->timeIntervalSamples.iterator].value; // printf("d%u\n", y); // a_ += 2 * x * x; a_ += (CumulationType) x * x; // b_ += 2 * x * y; b_ += (CumulationType) x * y; // c_ += 2 * x; c_ += x; // d_ += 2; --> same as numSamples * 2 e_ += y; // f += 2 * x; --> f == c // 2-factor pulled our of loop means each factor *= 2 // TODO: evaluation code // printf("[%u] --> a %lu b %lu c %lu e %lu\n", x, a_, b_, c_, e_); x++; samplesFifoBufferFiFoBufferIteratorNext(&timeSynchronization->timeIntervalSamples); } while (timeSynchronization->timeIntervalSamples.iterator < TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END); a_ *= 2; b_ *= 2; c_ *= 2; uint8_t d_ = timeSynchronization->timeIntervalSamples.numSamples * 2; e_ *= 2; CumulationType *f_ = &c_; // TODO: evaluation code // printf("a%lu b%lu c%lu d%u e%lu f%lu\n", a_, b_, c_, d_, e_, *f_); // we obtain two linear equations from the transformed partial derivatives to d and k // with k explicitly timeSynchronization->fittingFunction.k = ((CalculationType) d_ * b_ - (CalculationType) c_ * e_) / (a_ * d_ - (*f_) * c_); // and d explicitly timeSynchronization->fittingFunction.d = (timeSynchronization->fittingFunction.k * a_ + b_) / c_; // TODO: evaluation code // printf("k%li d%li\n", (int32_t) timeSynchronization->fittingFunction.k, // (int32_t) timeSynchronization->fittingFunction.d); }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/Vectors.h
<filename>src/avr-common/utils/uc-core/configuration/interrupts/Vectors.h /** * @author <NAME> 20.07.2016 * * ISR vector names related configuration. */ #pragma once #include <avr/interrupt.h> #define RESET_VECT _VECTOR(0) #if defined(__AVR_ATtiny1634__) # define NORTH_PIN_CHANGE_INTERRUPT_VECT \ PCINT2_vect # define EAST_PIN_CHANGE_INTERRUPT_VECT \ PCINT1_vect # define SOUTH_PIN_CHANGE_INTERRUPT_VECT \ PCINT0_vect # define ACTUATOR_PWM_INTERRUPT_VECT \ TIM0_COMPA_vect # define __UNUSED_TIMER0_OVERFLOW_INTERRUPT_VECT \ TIMER0_OVF_vect # define __UNUSED_TIMER1_OVERFLOW_INTERRUPT_VECT \ TIMER1_OVF_vect #elif defined(__AVR_ATmega16__) # define NORTH_PIN_CHANGE_INTERRUPT_VECT \ INT2_vect # define EAST_PIN_CHANGE_INTERRUPT_VECT \ INT1_vect # define SOUTH_PIN_CHANGE_INTERRUPT_VECT \ INT0_vect # define ACTUATOR_PWM_INTERRUPT_VECT \ TIMER0_COMP_vect # define __UNUSED_TIMER0_OVERFLOW_INTERRUPT_VECT \ TIMER0_OVF_vect # define __UNUSED_TIMER1_OVERFLOW_INTERRUPT_VECT \ TIMER1_OVF_vect #else # error #endif #if defined(__AVR_ATtiny1634__) || defined(__AVR_ATmega16__) # define TX_TIMER_INTERRUPT_VECT \ TIMER1_COMPA_vect # define LOCAL_TIME_INTERRUPT_VECT \ TIMER1_COMPB_vect #endif
ProgrammableMatter/particle-firmware
src/particle-transmission-simulation/main/main.c
/** * @author <NAME> 2016 */ #include "uc-core/particle/Particle.h" //unsigned char __stuff __attribute__((section(".noinit"))); /** * A mocked up particle loop. It puts the particle in an initialized reception state. */ void processLoop(void) { forever { process(); } } /** * starts a configured node in transmission state with preset transmission buffer */ int main(void) { constructParticle(&ParticleAttributes); ParticleAttributes.discoveryPulseCounters.loopCount = UINT8_MAX; ParticleAttributes.node.type = NODE_TYPE_MASTER; clearTransmissionPortBuffer(&ParticleAttributes.communication.ports.tx.south); ParticleAttributes.communication.ports.tx.south.dataEndPos.bitMask = 1; ParticleAttributes.communication.ports.tx.south.dataEndPos.byteNumber = 8; // least significant bit (start bit) must be set due tu the physically underlying protocol ParticleAttributes.communication.ports.tx.south.buffer.bytes[0] = 0b00100110 | 0x01; ParticleAttributes.communication.ports.tx.south.buffer.bytes[1] = 0b10101010; ParticleAttributes.communication.ports.tx.south.buffer.bytes[2] = 0b10101010; ParticleAttributes.communication.ports.tx.south.buffer.bytes[3] = 0b01010101; ParticleAttributes.communication.ports.tx.south.buffer.bytes[4] = 0b10101010; ParticleAttributes.communication.ports.tx.south.buffer.bytes[5] = 0b01111110; ParticleAttributes.communication.ports.tx.south.buffer.bytes[6] = 0b00100110; ParticleAttributes.communication.ports.tx.south.buffer.bytes[7] = 0b01010110; // configure input/output pins IO_PORTS_SETUP; SOUTH_TX_LO; // setup and enable transmission/reception counter interrupt __enableTxRxTimer(); enableTransmission(&ParticleAttributes.communication.ports.tx.south); DELAY_US_15; DELAY_US_15; DELAY_US_15; DELAY_US_15; DELAY_US_15; DELAY_US_15; DELAY_US_15; DELAY_US_15; DELAY_US_15; DELAY_US_15; SREG setBit bit(SREG_I); // processLoop(); // while (ParticleAttributes.node.state != STATE_TYPE_TX_DONE); // TIMER_TX_RX_DISABLE_COMPARE_INTERRUPT; // ParticleAttributes.node.state = STATE_TYPE_STALE; forever; return 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/ParticleLoop.h
/** * @author <NAME> 2016 * * The main loop implementation. */ #pragma once #include "Particle.h" /** * The main particle loop. It repetitively calls the state driven particle core implementation. */ extern inline void processLoop(void) __attribute__ ((noreturn)); inline void processLoop(void) { IO_PORTS_SETUP; // configure input/output pins constructParticle(&ParticleAttributes); ParticleAttributes.node.state = STATE_TYPE_START; forever { process(); } }
ProgrammableMatter/particle-firmware
src/particle/main/main.c
/** * @author <NAME> 2015 */ #include <uc-core/particle/ParticleLoop.h> FUSES = { .low = (FUSE_SUT_CKSEL0 & FUSE_SUT_CKSEL2 & FUSE_SUT_CKSEL3 & FUSE_SUT_CKSEL4 & FUSE_CKOUT), .high = HFUSE_DEFAULT, .extended = EFUSE_DEFAULT, }; int main(void) { processLoop(); return 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/CommunicationTypesCtors.h
<filename>src/avr-common/utils/uc-core/communication/CommunicationTypesCtors.h<gh_stars>1-10 /** * @author <NAME> 2016 * * Communication types constructor implementation. */ #pragma once #include <math.h> #include "CommunicationTypes.h" #include "ManchesterDecodingTypesCtors.h" /** * constructor function * @param o reference to the object to construct */ void constructBufferBitPointer(volatile BufferBitPointer *const o) { o->byteNumber = 0; o->__pad = 0; // do not remove! o->bitMask = 1; } /** * writes 0 to the port buffer */ void clearBufferBytes(volatile PortBuffer *const o) { for (uint8_t i = 0; i < sizeof(o->bytes); i++) { o->bytes[i] = 0; } } /** * constructor function * @param o reference to the object to construct */ void constructPortBuffer(volatile PortBuffer *const o) { clearBufferBytes(o); o->bytes[0] = 0x1; // set start bit constructBufferBitPointer(&(o->pointer)); o->receptionDuration = 0; o->firstFallingToRisingDuration = 0; o->lastFallingToRisingDuration = 0; o->nextLocalTimeInterruptOnPduReceived = 0; o->localTimeTrackingTimerCounterValueOnPduReceived = 0; } /** * constructor function * @param o reference to the object to construct */ void constructTxPort(TxPort *const o) { constructPortBuffer(&o->buffer); constructBufferBitPointer(&o->dataEndPos); o->isTransmitting = false; o->isTxClockPhase = false; o->isDataBuffered = false; o->isTxClockPhase = false; } /** * constructor function * @param o reference to the object to construct */ void constructTxPorts(TxPorts *const o) { constructTxPort(&o->north); constructTxPort(&o->east); constructTxPort(&o->south); } /** * constructor function * @param o reference to the object to construct */ void constructRxPort(RxPort *const o) { constructRxSnapshotBuffer(&o->snapshotsBuffer); constructPortBuffer(&o->buffer); o->isOverflowed = false; o->isDataBuffered = false; o->parityBitCounter = 0; } /** * constructor function * @param o reference to the object to construct */ void constructRxPorts(RxPorts *const o) { constructRxPort(&o->north); constructRxPort(&o->east); constructRxPort(&o->south); } /** * constructor function * @param o reference to the object to construct */ void constructCommunicationPorts(CommunicationPorts *const o) { constructTxPorts(&o->tx); constructRxPorts(&o->rx); } /** * constructor function * @param o reference to the object to construct */ void constructTransmissionTimerAdjustment(TransmissionTimerAdjustment *const o) { o->maxShortIntervalDuration = round(COMMUNICATION_DEFAULT_MAX_SHORT_RECEPTION_OVERTIME_PERCENTAGE_RATIO * COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY); o->maxLongIntervalDuration = roundf(COMMUNICATION_DEFAULT_MAX_LONG_RECEPTION_OVERTIME_PERCENTAGE_RATIO * COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY); o->transmissionClockDelay = COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY; o->transmissionClockDelayHalf = COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY / 2; o->newTransmissionClockDelay = o->transmissionClockDelay; o->newTransmissionClockDelayHalf = o->transmissionClockDelayHalf; o->isTransmissionClockDelayUpdateable = false; } /** * constructor function * @param o reference to the object to construct */ void constructCommunication(Communication *const o) { constructTransmissionTimerAdjustment(&o->timerAdjustment); constructCommunicationPorts(&o->ports); }
ProgrammableMatter/particle-firmware
src/avr-common/utils/common/PortInteraction.h
/** * @author <NAME> 2011 */ #pragma once /** * pin definition */ #define Pin0 1 #define Pin1 2 #define Pin2 4 #define Pin3 8 #define Pin4 16 #define Pin5 32 #define Pin6 64 #define Pin7 128 /** * better readable expressions for manipulating port direction */ #define setIn &= ~ #define setOut |= #define setHi |= #define pullUp |= #define pullDown &= ~ #define setLo &= ~ /** * some bit operators expressed nicer * <p> * int foo setBit bit(2); * <p> * AOut unsetBit Pin0; */ #define getBit & #define setBit |= #define unsetBit &= ~ #define toggleBit ^= #define bit _BV
ProgrammableMatter/particle-firmware
src/particle-reception-simulation/main/main.c
<gh_stars>1-10 /** * @author <NAME> 2016 */ #include "uc-core/particle/Particle.h" //unsigned char __stuff __attribute__((section(".noinit"))); /** * A mocked up particle loop. It puts the particle in an initialized reception state. */ extern inline void processLoop(void); inline void processLoop(void) { forever { process(); } } /** * starts */ int main(void) { // DELAY_US_150; DEBUG_CHAR_OUT('0'); // configure input/output pins IO_PORTS_SETUP; ParticleAttributes.discoveryPulseCounters.loopCount = UINT8_MAX; constructParticle(&ParticleAttributes); DEBUG_CHAR_OUT('1'); RX_INTERRUPTS_CLEAR_PENDING; ParticleAttributes.discoveryPulseCounters.north.isConnected = true; ParticleAttributes.node.type = NODE_TYPE_ORIGIN; ParticleAttributes.node.state = STATE_TYPE_IDLE; clearReceptionBuffers(); // setup and enable reception and counter interrupts ParticleAttributes.discoveryPulseCounters.north.isConnected = true; ParticleAttributes.discoveryPulseCounters.east.isConnected = true; ParticleAttributes.discoveryPulseCounters.south.isConnected = true; __enableReception(); SEI; processLoop(); return 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/SampleFifoTypesCtors.h
<filename>src/avr-common/utils/uc-core/synchronization/SampleFifoTypesCtors.h /** * @author <NAME> 26.09.2016 * * Synchronization FiFo constructors. */ #pragma once #include "SynchronizationTypes.h" #include "LeastSquareRegressionTypesCtors.h" void constructFifoElement(FifoElement *const o) { // The lightweight FiFo works only if full: // One can wait until enough observations have been stored to the queue // or speed up by pre-filling with synthetic values. o->value = (uint16_t) (roundf(SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL * COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY)) - TIME_SYNCHRONIZATION_SAMPLE_OFFSET; o->isRejected = false; } /** * constructor function * @param o reference to the object to construct */ void constructSamplesFifoBuffer(SamplesFifoBuffer *const o) { for (uint8_t i = 0; i < SAMPLE_FIFO_NUM_BUFFER_ELEMENTS; i++) { constructFifoElement(&o->samples[i]); } o->__startIdx = 0; o->__insertIndex = 0; // workaround for pre-filling with synthetic values: indicate that FiFo is full o->numSamples = SAMPLE_FIFO_NUM_BUFFER_ELEMENTS; // o->numSamples = 0; o->iterator = o->__startIdx; constructFifoElement(&o->dropOut); o->isDropOutValid = false; o->__isPreDropOutValid = false; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/TxRxTimer.h
/** * @author <NAME> 20.07.2016 * * Tx/rx related configuration. */ #pragma once #include "TimerCounter1.h" #if defined(__AVR_ATtiny1634__) || defined(__AVR_ATmega16__) # define __TIMER_TX_RX_COUNTER_PRESCALER_ENABLE __TIMER1_INTERRUPT_PRESCALER_ENABLE(__PRESCALER_1) # define __TIMER_TX_RX_COUNTER_PRESCALER_DISABLE __TIMER1_INTERRUPT_PRESCALER_DISABLE # define __TIMER_1_TX_RX_SETUP __TIMER1_INTERRUPT_CLEAR_PENDING; \ TCNT1 = 0; \ __TIMER1_INTERRUPT_OUTPUT_MODE_DISCONNECTED_SETUP; \ __TIMER1_INTERRUPT_WAVE_GENERATION_MODE_NORMAL_SETUP; \ __TIMER1_INTERRUPT_PRESCALER_DISABLE; \ __TIMER1_COMPARE_A_INTERRUPT_DISABLE; \ __TIMER1_OVERFLOW_INTERRUPT_DISABLE # define TIMER_TX_RX_COUNTER_VALUE (TCNT1) # define TIMER_TX_RX_COMPARE_VALUE (OCR1A) # define TIMER_TX_RX_COUNTER_CLEAR_PENDING_INTERRUPTS \ __TIMER1_INTERRUPT_CLEAR_PENDING # define TIMER_TX_RX_COUNTER_SETUP \ __TIMER_1_TX_RX_SETUP; \ __TIMER_TX_RX_COUNTER_PRESCALER_DISABLE # define TIMER_TX_RX_COUNTER_PAUSE __TIMER1_INTERRUPT_PRESCALER_DISABLE # define TIMER_TX_RX_COUNTER_DISABLE __TIMER1_INTERRUPT_PRESCALER_DISABLE # define TIMER_TX_RX_COUNTER_ENABLE __TIMER1_INTERRUPT_PRESCALER_ENABLE(__TIMER_COUNTER_PRESCALER_1); # define TIMER_TX_RX_COUNTER_RESUME __TIMER1_INTERRUPT_PRESCALER_ENABLE(__TIMER_COUNTER_PRESCALER_1); # define TIMER_TX_RX_DISABLE_COMPARE_INTERRUPT \ __TIMER1_COMPARE_A_INTERRUPT_DISABLE # define TIMER_TX_RX_ENABLE_COMPARE_INTERRUPT \ TIMER_TX_RX_COUNTER_CLEAR_PENDING_INTERRUPTS; \ __TIMER1_COMPARE_A_INTERRUPT_ENABLE # define TIMER_RX_RX_DISABLE_OVERFLOW_INTERRUPT \ __TIMER1_OVERFLOW_INTERRUPT_DISABLE # define TIMER_RX_RX_ENABLE_OVERFLOW_INTERRUPT \ __TIMER1_OVERFLOW_INTERRUPT_ENABLE # else # error # endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/AlertsTypes.h
<filename>src/avr-common/utils/uc-core/particle/types/AlertsTypes.h /* * @author <NAME> 09.10.2016 * * Alerts state definition. */ #pragma once #include <stdint.h> /** * alert switches to en-/disable alerts on runtime */ typedef struct Alerts { uint8_t isRxBufferOverflowEnabled : 1; uint8_t isRxParityErrorEnabled : 1; uint8_t isGenericErrorEnabled : 1; uint8_t __pad : 5; } Alerts;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/actuation/Actuation.h
/** * @author <NAME> 12.07.2016 * * Actuation related implementation. */ #pragma once #include "ActuationTypes.h" #include "uc-core/particle/Globals.h" #include "uc-core/configuration/IoPins.h" #include "uc-core/configuration/interrupts/ReceptionPCI.h" #include "uc-core/configuration/interrupts/ActuationTimer.h" #include "uc-core/delay/delay.h" #include "uc-core/communication/ManchesterDecodingTypesCtors.h" /** * Prepares affected wires and enables the actuation interrupt (PWM), * otherwise, on maximum power output, configures the corresponding wires. */ static void __startActuation(void) { // active actuation - north left if (ParticleAttributes.actuationCommand.actuators.northLeft) { NORTH_TX_LO; // do not drive MOSFET } // active actuation - north right if (ParticleAttributes.actuationCommand.actuators.northRight) { RX_NORTH_INTERRUPT_DISABLE; NORTH_RX_SWITCH_HI; // do not drive MOSFET } // passive actuation - east left if (ParticleAttributes.actuationCommand.actuators.eastLeft) { EAST_TX_HI; // drive MOSFET } // passive actuation - east right if (ParticleAttributes.actuationCommand.actuators.eastRight) { RX_EAST_INTERRUPT_DISABLE; // EAST_RX_SWITCH_LO; // drive MOSFET } // passive actuation - south left if (ParticleAttributes.actuationCommand.actuators.southLeft) { SOUTH_TX_HI; // drive MOSFET } // passive actuation - south right if (ParticleAttributes.actuationCommand.actuators.southRight) { RX_SOUTH_INTERRUPT_DISABLE; SOUTH_RX_SWITCH_LO; // drive MOSFET } // set up PWM duty cycle according to actuation command setting switch (ParticleAttributes.actuationCommand.actuationPower.dutyCycleLevel) { case HEATING_LEVEL_TYPE_MAXIMUM: if (ParticleAttributes.actuationCommand.actuators.northLeft) { NORTH_TX_HI; // drive MOSFET } if (ParticleAttributes.actuationCommand.actuators.northRight) { RX_NORTH_INTERRUPT_DISABLE; NORTH_RX_SWITCH_LO; // drive MOSFET } break; case HEATING_LEVEL_TYPE_STRONG: ACTUATOR_INTERRUPT_SET_PWM_DUTY_CYCLE_STRONG; ACTUATOR_INTERRUPT_ENABLE; break; case HEATING_LEVEL_TYPE_MEDIUM: ACTUATOR_INTERRUPT_SET_PWM_DUTY_CYCLE_MEDIUM; ACTUATOR_INTERRUPT_ENABLE; break; case HEATING_LEVEL_TYPE_WEAK: default: ACTUATOR_INTERRUPT_SET_PWM_DUTY_CYCLE_WEAK; ACTUATOR_INTERRUPT_ENABLE; break; } } /** * disables the actuation interrupt */ static void __stopActuationPWM(void) { ACTUATOR_INTERRUPT_DISABLE; } /** * return wires of affected ports to their default working states (reception state) */ static void __setDefaultWiresStates(void) { if (ParticleAttributes.actuationCommand.actuators.northLeft) { NORTH_TX_LO; } if (ParticleAttributes.actuationCommand.actuators.northRight) { NORTH_RX_SWITCH_HI; } if (ParticleAttributes.actuationCommand.actuators.eastLeft) { EAST_TX_LO; } // if (ParticleAttributes.actuationCommand.actuators.eastRight) { // EAST_RX_SWITCH_HI; // } if (ParticleAttributes.actuationCommand.actuators.southLeft) { SOUTH_TX_LO; } if (ParticleAttributes.actuationCommand.actuators.southRight) { SOUTH_RX_SWITCH_HI; } } /** * truncates snapshot buffers of affected ports */ static void __truncateReceptionBuffers(void) { if (ParticleAttributes.actuationCommand.actuators.northRight) { constructRxSnapshotBuffer(&ParticleAttributes.directionOrientedPorts.north.rxPort->snapshotsBuffer); } if (ParticleAttributes.actuationCommand.actuators.eastRight) { constructRxSnapshotBuffer(&ParticleAttributes.directionOrientedPorts.east.rxPort->snapshotsBuffer); } if (ParticleAttributes.actuationCommand.actuators.southRight) { constructRxSnapshotBuffer(&ParticleAttributes.directionOrientedPorts.south.rxPort->snapshotsBuffer); } } /** * clears pending interrupts and enables reception interrupts of affected ports */ static void __enableReceptionInterrupts(void) { if (ParticleAttributes.actuationCommand.actuators.northRight) { RX_NORTH_INTERRUPT_CLEAR_PENDING; RX_NORTH_INTERRUPT_ENABLE; } if (ParticleAttributes.actuationCommand.actuators.eastRight) { RX_EAST_INTERRUPT_CLEAR_PENDING; RX_EAST_INTERRUPT_ENABLE; } if (ParticleAttributes.actuationCommand.actuators.southRight) { RX_SOUTH_INTERRUPT_CLEAR_PENDING; RX_SOUTH_INTERRUPT_ENABLE; } } /** * handles actuation command states */ static void handleExecuteActuation(void (*const actuationDoneCallback)(void)) { uint8_t sreg; switch (ParticleAttributes.actuationCommand.executionState) { case ACTUATION_STATE_TYPE_IDLE: if (ParticleAttributes.actuationCommand.isScheduled) { ParticleAttributes.actuationCommand.isScheduled = false; ParticleAttributes.actuationCommand.executionState = ACTUATION_STATE_TYPE_START; goto __ACTUATION_STATE_TYPE_START; } else { // in case of race; actuator interrupt vs main loop ParticleAttributes.actuationCommand.executionState = ACTUATION_STATE_TYPE_DONE; goto __ACTUATION_STATE_TYPE_DONE; return; } break; __ACTUATION_STATE_TYPE_START: case ACTUATION_STATE_TYPE_START: // DEBUG_CHAR_OUT('y'); __startActuation(); ParticleAttributes.actuationCommand.executionState = ACTUATION_STATE_TYPE_WORKING; goto __ACTUATION_STATE_TYPE_WORKING; break; __ACTUATION_STATE_TYPE_WORKING: case ACTUATION_STATE_TYPE_WORKING: sreg = SREG; MEMORY_BARRIER; CLI; MEMORY_BARRIER; const uint16_t now = ParticleAttributes.localTime.numTimePeriodsPassed; MEMORY_BARRIER; SREG = sreg; MEMORY_BARRIER; // TODO: ev. move actuation impl. to scheduler if (ParticleAttributes.actuationCommand.actuationEnd.periodTimeStamp < now) { ParticleAttributes.actuationCommand.executionState = ACTUATION_STATE_TYPE_RELAXATION_PAUSE; goto __ACTUATION_STATE_TYPE_RELAXATION_PAUSE; } return; break; __ACTUATION_STATE_TYPE_RELAXATION_PAUSE: case ACTUATION_STATE_TYPE_RELAXATION_PAUSE: __stopActuationPWM(); __setDefaultWiresStates(); __truncateReceptionBuffers(); // let bouncing signals pass DELAY_US_150; ParticleAttributes.actuationCommand.executionState = ACTUATION_STATE_TYPE_DONE; goto __ACTUATION_STATE_TYPE_DONE; break; __ACTUATION_STATE_TYPE_DONE: case ACTUATION_STATE_TYPE_DONE: __enableReceptionInterrupts(); ParticleAttributes.actuationCommand.executionState = ACTUATION_STATE_TYPE_IDLE; actuationDoneCallback(); *((uint8_t *) &ParticleAttributes.actuationCommand.actuators) = 0; // DEBUG_CHAR_OUT('Y'); break; } }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/evaluation/EvaluationTypes.h
/* * @author <NAME> 15.10.2016 * * Evaluation state definition. */ #pragma once #include <stdint.h> #include "uc-core/particle/types/NodeAddressTypes.h" #include "uc-core/configuration/Evaluation.h" #ifdef EVALUATION_ENABLE_FLUCTUATE_CPU_FREQUENCY_ON_PURPOSE typedef struct RuntimeOscCalibration { uint8_t initialOscCal; uint8_t step; uint8_t minOscCal; uint8_t maxOscCal; uint8_t isDecrementing : 1; uint8_t __pad : 7; } RuntimeOscCalibration; #endif typedef struct Evaluation { #if defined(EVALUATION_SIMPLE_SYNC_AND_ACTUATION) || defined(EVALUATION_SYNC_CYCLICALLY) /** * network address to issue next heat wires command at **/ NodeAddress nextHeatWiresAddress; #endif #ifdef EVALUATION_ENABLE_FLUCTUATE_CPU_FREQUENCY_ON_PURPOSE /** * OSCCAL runtime boundaries */ RuntimeOscCalibration oscCalibration; #endif #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_THEN_ACTUATE_ONCE /** * total number of currently sent sync packages */ uint16_t totalSentSyncPackages; #endif } Evaluation;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/Particle.h
/** * @author <NAME> 2016 * * Particle core implementation. */ #pragma once #include <avr/sleep.h> #include "common/common.h" #include "Globals.h" #include "uc-core/particle/types/ParticleTypes.h" #include "uc-core/particle/types/ParticleTypesCtors.h" #include "uc-core/configuration/IoPins.h" #include "uc-core/delay/delay.h" #include "uc-core/discovery/Discovery.h" #include "uc-core/configuration/Particle.h" #include "uc-core/configuration/Periphery.h" #include "uc-core/configuration/interrupts/ReceptionPCI.h" #include "uc-core/configuration/interrupts/TxRxTimer.h" #include "uc-core/configuration/interrupts/DiscoveryPCI.h" #include "uc-core/configuration/interrupts/DiscoveryTimer.h" #include "uc-core/configuration/interrupts/ActuationTimer.h" #include "uc-core/interrupts/Interrupts.h" #include "uc-core/communication-protocol/CommunicationProtocol.h" #include "uc-core/communication-protocol/CommunicationProtocolTypesCtors.h" #include "uc-core/communication-protocol/CommunicationProtocolPackageTypesCtors.h" #include "uc-core/actuation/Actuation.h" #include "Commands.h" #include "uc-core/periphery/Periphery.h" #include "uc-core/stdout/Stdout.h" #include "uc-core/time/Time.h" #include "uc-core/scheduler/Scheduler.h" #include "uc-core/scheduler/SchedulerTypesCtors.h" #include "uc-core/configuration/Evaluation.h" #include "uc-core/evaluation/Evaluation.h" /** * Disables discovery sensing interrupts. */ static void __disableDiscoverySensing(void) { DISCOVERY_INTERRUPTS_DISABLE; } /** * Enables discovery sensing interrupts. */ static void __enableDiscoverySensing(void) { // DISCOVERY_INTERRUPTS_SETUP; // MEMORY_BARRIER; DISCOVERY_INTERRUPTS_ENABLE; } /** * Disables discovery pulsing. */ //extern FUNC_ATTRS void __disableDiscoveryPulsing(void); static void __disableDiscoveryPulsing(void) { TIMER_NEIGHBOUR_SENSE_PAUSE; TIMER_NEIGHBOUR_SENSE_DISABLE; NORTH_TX_LO; EAST_TX_HI; SOUTH_TX_LO; } /** * Enables discovery sensing. */ static void __enableDiscoveryPulsing(void) { TIMER_NEIGHBOUR_SENSE_ENABLE; MEMORY_BARRIER; TIMER_NEIGHBOUR_SENSE_RESUME; } static void __enableAlerts(SchedulerTask *const task) { ParticleAttributes.alerts.isRxBufferOverflowEnabled = true; ParticleAttributes.alerts.isRxParityErrorEnabled = true; ParticleAttributes.alerts.isGenericErrorEnabled = true; // to remove compiler warning, clearing this flag is redundant task->isEnabled = false; } /** * Sets up ports and interrupts but does not enable the global interrupt (I-flag in SREG). */ static void __initParticle(void) { // ---------------- basic setup ---------------- setupUart(); LED_STATUS1_OFF; LED_STATUS2_OFF; LED_STATUS3_OFF; LED_STATUS4_OFF; TEST_POINT1_LO; TEST_POINT2_LO; DELAY_MS_1; DELAY_MS_1; // ---------------- ISR setup ---------------- // RX_INTERRUPTS_SETUP; // configure input pins interrupts // RX_INTERRUPTS_ENABLE; // enable input pin interrupts DISCOVERY_INTERRUPTS_SETUP; // configure pin change interrupt TIMER_NEIGHBOUR_SENSE_SETUP; // configure timer interrupt for neighbour sensing LOCAL_TIME_INTERRUPT_COMPARE_DISABLE; // prepare local time timer interrupt ACTUATOR_INTERRUPT_SETUP; // prepare actuation interrupt sleep_disable(); set_sleep_mode(SLEEP_MODE_PWR_DOWN); // set sleep mode to power down // ---------------- add tasks to scheduler ---------------- // task for clearing leds before the basic process starts #ifndef PERIPHERY_REMOVE_IMPL addSingleShotTask(SCHEDULER_TASK_ID_SETUP_LEDS, setupLedsState, 128); #endif addSingleShotTask(SCHEDULER_TASK_ID_ENABLE_ALERTS, __enableAlerts, 255); // add toggle led task: for heartbeat indication // addCyclicTask(SCHEDULER_TASK_ID_HEARTBEAT_LED_TOGGLE, heartBeatToggle, 300, 400); #ifdef EVALUATION_SIMPLE_SYNC_AND_ACTUATION // add cyclic but count limited sync. time task addCyclicTask(SCHEDULER_TASK_ID_SYNC_PACKAGE, sendNextSyncTimePackageTask, SYNCHRONIZATION_TYPES_CTORS_FIRST_SYNC_PACKAGE_LOCAL_TIME, ParticleAttributes.timeSynchronization.fastSyncPackageSeparation); taskEnableNodeTypeLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, NODE_TYPE_ORIGIN); taskEnableCountLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, ParticleAttributes.timeSynchronization.totalFastSyncPackagesToTransmit); // prepare but disable task, is enabled by last call of sync. task addCyclicTask(SCHEDULER_TASK_ID_HEAT_WIRES, heatWiresTask, SYNCHRONIZATION_TYPES_CTORS_FIRST_SYNC_PACKAGE_LOCAL_TIME, 1500); taskEnableNodeTypeLimit(SCHEDULER_TASK_ID_HEAT_WIRES, NODE_TYPE_ORIGIN); taskDisable(SCHEDULER_TASK_ID_HEAT_WIRES); #endif #ifdef EVALUATION_SYNC_CYCLICALLY addCyclicTask(SCHEDULER_TASK_ID_SYNC_PACKAGE, sendNextSyncTimePackageTask, 350, 100); taskEnableNodeTypeLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, NODE_TYPE_ORIGIN); #endif #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG addCyclicTask(SCHEDULER_TASK_ID_SYNC_PACKAGE, sendSyncTimePackageAndUpdateRequestFlagTask, 350, ParticleAttributes.timeSynchronization.fastSyncPackageSeparation); taskEnableNodeTypeLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, NODE_TYPE_ORIGIN); taskEnableCountLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, 5); #endif #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_IN_PHASE_SHIFTING addCyclicTask(SCHEDULER_TASK_ID_SYNC_PACKAGE, sendSyncTimePackageAndUpdateRequestFlagForInPhaseShiftingEvaluationTask, 350, ParticleAttributes.timeSynchronization.fastSyncPackageSeparation); taskEnableNodeTypeLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, NODE_TYPE_ORIGIN); taskEnableCountLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, 30); #else #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_THEN_ACTUATE_ONCE addCyclicTask(SCHEDULER_TASK_ID_SYNC_PACKAGE, sendSyncTimeAndActuateOnceTask, SYNCHRONIZATION_TYPES_CTORS_FIRST_SYNC_PACKAGE_LOCAL_TIME, ParticleAttributes.timeSynchronization.fastSyncPackageSeparation); taskEnableNodeTypeLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, NODE_TYPE_ORIGIN); taskEnableCountLimit(SCHEDULER_TASK_ID_SYNC_PACKAGE, ParticleAttributes.timeSynchronization.totalFastSyncPackagesToTransmit); #endif #endif } /** * Disables all reception interrupts. */ static void __disableReceptionPinChangeInterrupts(void) { DEBUG_CHAR_OUT('O'); RX_NORTH_INTERRUPT_DISABLE; DEBUG_CHAR_OUT('Q'); RX_EAST_INTERRUPT_DISABLE; DEBUG_CHAR_OUT('N'); RX_SOUTH_INTERRUPT_DISABLE; } /** * Clears pending and enables reception interrupts for north port if connected. */ static void __enableReceptionHardwareNorth(void) { if (ParticleAttributes.discoveryPulseCounters.north.isConnected) { DEBUG_CHAR_OUT('o'); RX_NORTH_INTERRUPT_CLEAR_PENDING; MEMORY_BARRIER; RX_NORTH_INTERRUPT_ENABLE; } } /** * Clears pending and enables reception interrupts for east port if connected. */ static void __enableReceptionHardwareEast(void) { if (ParticleAttributes.discoveryPulseCounters.east.isConnected) { DEBUG_CHAR_OUT('q'); RX_EAST_INTERRUPT_CLEAR_PENDING; MEMORY_BARRIER; RX_EAST_INTERRUPT_ENABLE; } } /** * Clears pending and enables reception interrupts for south port if connected. */ static void __enableReceptionHardwareSouth(void) { if (ParticleAttributes.discoveryPulseCounters.south.isConnected) { DEBUG_CHAR_OUT('m'); RX_SOUTH_INTERRUPT_CLEAR_PENDING; MEMORY_BARRIER; RX_SOUTH_INTERRUPT_ENABLE; } } /** * Sets up and enables the tx/rx timer. */ static void __enableTxRxTimer(void) { TIMER_TX_RX_COUNTER_SETUP; MEMORY_BARRIER; TIMER_TX_RX_COUNTER_ENABLE; } /** * Disables the signal generating transmission interrupt. */ //static void __disableTransmission(void) { // TIMER_TX_RX_DISABLE_COMPARE_INTERRUPT; //} /** * Sets up and enables reception for all connected ports. */ static void __enableReceptionHardwareForConnectedPorts(void) { // RX_INTERRUPTS_SETUP; // MEMORY_BARRIER; // RX_INTERRUPTS_ENABLE; __enableReceptionHardwareNorth(); __enableReceptionHardwareEast(); __enableReceptionHardwareSouth(); } /** * Disables reception interrupts. */ void __disableReception(void) { __disableReceptionPinChangeInterrupts(); } /** * Enables reception timer and interrupts. */ void __enableReception(void) { __enableTxRxTimer(); __enableReceptionHardwareForConnectedPorts(); } /** * Increments the discovery loop counter. */ static void __discoveryLoopCount(void) { if (ParticleAttributes.discoveryPulseCounters.loopCount < (UINT8_MAX)) { ParticleAttributes.discoveryPulseCounters.loopCount++; } } /** * Sets the correct address if this node is the origin node. */ static void __updateOriginNodeAddress(void) { if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN) { ParticleAttributes.node.address.row = 1; ParticleAttributes.node.address.column = 1; } } /** * Handles (state driven) the wait for being enumerated node state. */ static void __handleWaitForBeingEnumerated(void) { CommunicationProtocolPortState *commPortState = &ParticleAttributes.protocol.ports.north; if (commPortState->stateTimeoutCounter == 0 && commPortState->receptionistState != COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK && commPortState->receptionistState != COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK_WAIT_TX_FINISHED) { // on timeout: fall back to start state DEBUG_CHAR_OUT('r'); commPortState->receptionistState = COMMUNICATION_RECEPTIONIST_STATE_TYPE_RECEIVE; commPortState->stateTimeoutCounter = COMMUNICATION_PROTOCOL_TIMEOUT_COUNTER_MAX; if (commPortState->reTransmissions > 0) { commPortState->reTransmissions--; } DEBUG_CHAR_OUT('b'); } if (commPortState->reTransmissions == 0) { // on retransmissions consumed: sort cut the global state machine to erroneous state ParticleAttributes.node.state = STATE_TYPE_ERRONEOUS; return; } switch (commPortState->receptionistState) { // receive case COMMUNICATION_RECEPTIONIST_STATE_TYPE_RECEIVE: ParticleAttributes.directionOrientedPorts.north.receivePimpl(); break; // transmit ack with local address case COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK: constructEnumerationACKWithAddressToParentPackage(); enableTransmission(&ParticleAttributes.communication.ports.tx.north); DEBUG_CHAR_OUT('g'); commPortState->receptionistState = COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK_WAIT_TX_FINISHED; break; // wait for tx finished case COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK_WAIT_TX_FINISHED: if (ParticleAttributes.communication.ports.tx.north.isTransmitting) { break; } clearReceptionPortBuffer(&ParticleAttributes.communication.ports.rx.north); DEBUG_CHAR_OUT('h'); commPortState->receptionistState = COMMUNICATION_RECEPTIONIST_STATE_TYPE_WAIT_FOR_RESPONSE; break; // wait for response case COMMUNICATION_RECEPTIONIST_STATE_TYPE_WAIT_FOR_RESPONSE: ParticleAttributes.directionOrientedPorts.north.receivePimpl(); break; case COMMUNICATION_RECEPTIONIST_STATE_TYPE_IDLE: break; } } /** * Handles (state driven) neighbour synchronization node states. * @param endState the state when handler has finished */ static void __handleSynchronizeNeighbour(const StateType endState) { CommunicationProtocolPortState *commPortState = ParticleAttributes.directionOrientedPorts.simultaneous.protocol; TxPort *txPort = ParticleAttributes.directionOrientedPorts.simultaneous.txPort; switch (commPortState->initiatorState) { // transmit local time simultaneously on east and south ports case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT: constructSyncTimePackage(txPort, ParticleAttributes.timeSynchronization.isNextSyncPackageTimeUpdateRequest); enableTransmission(txPort); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED; break; // wait for tx finished case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED: if (txPort->isTransmitting) { break; } commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; goto __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; break; case COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE: case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK: case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED: __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: case COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: ParticleAttributes.node.state = endState; break; } } /** * Handles the sync neighbour done state. * In general it simply switches to the specified state, * but if simulation/test macros are defined it redirects to other states accordingly. * @param endState the state after this call if no test macros defined */ static void __handleSynchronizeNeighbourDoneOrRunTest(const StateType endState) { #if defined(SIMULATION_SET_NEW_NETWORK_GEOMETRY_TEST) if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN) { ParticleAttributes.protocol.networkGeometry.rows = 2; ParticleAttributes.protocol.networkGeometry.columns = 1; DELAY_MS_1; setNewNetworkGeometry(); return; } #elif defined(SIMULATION_HEAT_WIRES_TEST) if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN) { Actuators actuators; actuators.northLeft = true; actuators.northRight = true; NodeAddress nodeAddress; nodeAddress.row = 2; nodeAddress.column = 2; DELAY_MS_1; sendHeatWires(&nodeAddress, &actuators, 5, 2); return; } #elif defined(SIMULATION_HEAT_WIRES_RANGE_TEST) if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN) { Actuators actuators; actuators.northLeft = false; actuators.northRight = true; NodeAddress fromAddress; fromAddress.row = 1; fromAddress.column = 2; NodeAddress toAddress; toAddress.row = 2; toAddress.column = 2; DELAY_MS_1; sendHeatWiresRange(&fromAddress, &toAddress, &actuators, 50000, 10); return; } #elif defined(SIMULATION_HEAT_WIRES_MODE_TEST) if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN) { DELAY_MS_1; sendHeatWiresModePackage(HEATING_LEVEL_TYPE_STRONG); return; } #elif defined(SIMULATION_SEND_HEADER_TEST) if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN) { HeaderPackage package; package.id = PACKAGE_HEADER_ID_HEADER; package.enableBroadcast = true; DELAY_MS_1; sendHeaderPackage(&package); return; } #endif ParticleAttributes.node.state = endState; } /** * Handles (state driven) relaying network geometry communication states. * @param endState the state when handler finished */ static void __handleRelayAnnounceNetworkGeometry(const StateType endState) { CommunicationProtocolPortState *commPortState = &ParticleAttributes.protocol.ports.north; switch (commPortState->initiatorState) { case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT: enableTransmission(&ParticleAttributes.communication.ports.tx.north); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED; break; // wait for tx finished case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED: if (ParticleAttributes.communication.ports.tx.north.isTransmitting) { break; } commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; goto __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; break; case COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE: case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK: case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED: __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: case COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: ParticleAttributes.node.state = endState; break; } } /** * Handles (event driven) network geometry announcement states. * @param endState the state when handler finished */ static void __handleSendAnnounceNetworkGeometry(const StateType endState) { TxPort *txPort = &ParticleAttributes.communication.ports.tx.north; CommunicationProtocolPortState *commPortState = &ParticleAttributes.protocol.ports.north; switch (ParticleAttributes.protocol.ports.north.initiatorState) { case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT: constructAnnounceNetworkGeometryPackage(ParticleAttributes.node.address.row, ParticleAttributes.node.address.column); enableTransmission(txPort); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED; break; // wait for tx finished case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED: if (txPort->isTransmitting) { break; } commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; goto __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; break; case COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE: case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK: case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED: __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: case COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: ParticleAttributes.node.state = endState; break; } } /** * Advance communication timeout counters. */ static void __advanceCommunicationProtocolCounters(void) { if (!ParticleAttributes.communication.ports.tx.north.isTransmitting && ParticleAttributes.protocol.ports.north.stateTimeoutCounter > 0) { ParticleAttributes.protocol.ports.north.stateTimeoutCounter--; } if (!ParticleAttributes.communication.ports.tx.east.isTransmitting && ParticleAttributes.protocol.ports.east.stateTimeoutCounter > 0) { ParticleAttributes.protocol.ports.east.stateTimeoutCounter--; } if (!ParticleAttributes.communication.ports.tx.south.isTransmitting && ParticleAttributes.protocol.ports.south.stateTimeoutCounter > 0) { ParticleAttributes.protocol.ports.south.stateTimeoutCounter--; } } /** * Handles discovery states, classifies the local node type and switches to next state. */ static void __handleNeighboursDiscovery(void) { __discoveryLoopCount(); // if (ParticleAttributes.discoveryPulseCounters.loopCount == 0) { // LED_STATUS1_TOGGLE; // } if (ParticleAttributes.discoveryPulseCounters.loopCount >= MAX_NEIGHBOURS_DISCOVERY_LOOPS) { // LED_STATUS1_ON; // on discovery timeout __disableDiscoverySensing(); ParticleAttributes.node.state = STATE_TYPE_NEIGHBOURS_DISCOVERED; } else if (ParticleAttributes.discoveryPulseCounters.loopCount >= // on min. discovery loops exceeded MIN_NEIGHBOURS_DISCOVERY_LOOPS) { if (updateAndDetermineNodeType()) { // on distinct discovery __disableDiscoverySensing(); ParticleAttributes.node.state = STATE_TYPE_NEIGHBOURS_DISCOVERED; } else { PARTICLE_DISCOVERY_LOOP_DELAY; } // show discovery status if (ParticleAttributes.discoveryPulseCounters.north.isConnected) { LED_STATUS1_ON; } if (ParticleAttributes.discoveryPulseCounters.east.isConnected) { LED_STATUS3_ON; } if (ParticleAttributes.discoveryPulseCounters.south.isConnected) { LED_STATUS4_ON; } __updateOriginNodeAddress(); } } /** * Handles the post discovery extended pulsing period with subsequent switch to next state. */ static void __handleDiscoveryPulsing(void) { if (ParticleAttributes.discoveryPulseCounters.loopCount >= MAX_NEIGHBOUR_PULSING_LOOPS) { __disableDiscoveryPulsing(); ParticleAttributes.node.state = STATE_TYPE_DISCOVERY_PULSING_DONE; } else { __discoveryLoopCount(); } } /** * Handle the discovery to enumeration state switch. */ static void __handleDiscoveryPulsingDone(void) { if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN) { ParticleAttributes.node.state = STATE_TYPE_ENUMERATING_NEIGHBOURS; PARTICLE_DISCOVERY_PULSE_DONE_POST_DELAY; } else if (ParticleAttributes.node.type == NODE_TYPE_ORPHAN) { ParticleAttributes.node.state = STATE_TYPE_DISCOVERY_DONE_ORPHAN_NODE; return; } else { setReceptionistStateStart(&ParticleAttributes.protocol.ports.north); ParticleAttributes.node.state = STATE_TYPE_WAIT_FOR_BEING_ENUMERATED; DEBUG_CHAR_OUT('W'); } __enableReception(); clearReceptionBuffers(); } ///** // * Sends the set network geometry package and switches to the given state. // * @param rows the new network geometry rows // * @param cols the new network geometry rows // * @param endState the state when handler finished // */ //static void __handleSetNetworkGeometry(const uint8_t rows, const uint8_t cols, // const StateType endState) { // CommunicationProtocolPortState *commPortState = ParticleAttributes.directionOrientedPorts.simultaneous.protocol; // TxPort *txPort = ParticleAttributes.directionOrientedPorts.simultaneous.txPort; // switch (commPortState->initiatorState) { // case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT: // constructSetNetworkGeometryPackage(txPort, rows, cols); // enableTransmission(txPort); // commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED; // break; // // // wait for tx finished // case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED: // if (txPort->isTransmitting) { // break; // } // commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; // goto __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; // break; // // case COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE: // case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK: // case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED: // __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: // case COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: // ParticleAttributes.node.state = endState; // break; // } //} /** * State driven handling of sending package states without ack requests. * @param port the designated port * @param endState the end state when handler finished */ static void __handleSendPackage(DirectionOrientedPort *const port, const StateType endState) { CommunicationProtocolPortState *commPortState = port->protocol; switch (commPortState->initiatorState) { case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT: enableTransmission(port->txPort); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED; break; // wait for tx finished case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED: if (port->txPort->isTransmitting) { break; } commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; goto __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; break; case COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE: case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK: case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED: __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: case COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: ParticleAttributes.node.state = endState; break; } } /** * Callback when actuation command has finished. */ static void __onActuationDoneCallback(void) { ParticleAttributes.node.state = STATE_TYPE_IDLE; } /** * Checks whether an actuation is to be executed. Switches state if an actuation * command is scheduled and the current local time indicates an actuation start. */ static void __handleIsActuationCommandPeriod(void) { if (ParticleAttributes.actuationCommand.isScheduled && ParticleAttributes.actuationCommand.executionState == ACTUATION_STATE_TYPE_IDLE) { if (ParticleAttributes.actuationCommand.actuationStart.periodTimeStamp <= ParticleAttributes.localTime.numTimePeriodsPassed) { ParticleAttributes.node.state = STATE_TYPE_EXECUTE_ACTUATION_COMMAND; } } } /** * The core function is called cyclically in the particle loop. It implements the * behaviour of the particle. */ static inline void process(void) { // DEBUG_CHAR_OUT('P'); // ---------------- init states ---------------- switch (ParticleAttributes.node.state) { case STATE_TYPE_RESET: __disableReception(); constructParticle(&ParticleAttributes); ParticleAttributes.node.state = STATE_TYPE_START; goto __STATE_TYPE_START; break; __STATE_TYPE_START: case STATE_TYPE_START: __initParticle(); ParticleAttributes.node.state = STATE_TYPE_ACTIVE; goto __STATE_TYPE_ACTIVE; break; __STATE_TYPE_ACTIVE: case STATE_TYPE_ACTIVE: ParticleAttributes.node.state = STATE_TYPE_NEIGHBOURS_DISCOVERY; __enableDiscoverySensing(); MEMORY_BARRIER; __enableDiscoveryPulsing(); SEI; goto __STATE_TYPE_NEIGHBOURS_DISCOVERY; break; // ---------------- boot states: discovery ---------------- __STATE_TYPE_NEIGHBOURS_DISCOVERY: case STATE_TYPE_NEIGHBOURS_DISCOVERY: __handleNeighboursDiscovery(); break; case STATE_TYPE_NEIGHBOURS_DISCOVERED: ParticleAttributes.node.state = STATE_TYPE_DISCOVERY_PULSING; goto __STATE_TYPE_DISCOVERY_PULSING; break; __STATE_TYPE_DISCOVERY_PULSING: case STATE_TYPE_DISCOVERY_PULSING: __handleDiscoveryPulsing(); break; case STATE_TYPE_DISCOVERY_PULSING_DONE: __handleDiscoveryPulsingDone(); break; case STATE_TYPE_DISCOVERY_DONE_ORPHAN_NODE: blinkKnightRidersKittForever(); break; // ---------------- boot states: local enumeration ---------------- // wait for incoming address from north neighbour case STATE_TYPE_WAIT_FOR_BEING_ENUMERATED: __handleWaitForBeingEnumerated(); break; case STATE_TYPE_LOCALLY_ENUMERATED: ParticleAttributes.node.state = STATE_TYPE_ENUMERATING_NEIGHBOURS; goto __STATE_TYPE_ENUMERATING_NEIGHBOURS; break; // ---------------- boot states: neighbour enumeration ---------------- __STATE_TYPE_ENUMERATING_NEIGHBOURS: case STATE_TYPE_ENUMERATING_NEIGHBOURS: setInitiatorStateStart(&ParticleAttributes.protocol.ports.east); DEBUG_CHAR_OUT('E'); ParticleAttributes.node.state = STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR; goto __STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR; break; // ---------------- boot states: east neighbour enumeration ---------------- __STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR: case STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR: handleEnumerateNeighbour(&ParticleAttributes.directionOrientedPorts.east, ParticleAttributes.node.address.row, ParticleAttributes.node.address.column + 1, STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR_DONE); __advanceCommunicationProtocolCounters(); break; case STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR_DONE: setInitiatorStateStart(&ParticleAttributes.protocol.ports.south); DEBUG_CHAR_OUT('e'); ParticleAttributes.node.state = STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR; goto __STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR; break; // ---------------- boot states: south neighbour enumeration ---------------- __STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR: case STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR: handleEnumerateNeighbour(&ParticleAttributes.directionOrientedPorts.south, ParticleAttributes.node.address.row + 1, ParticleAttributes.node.address.column, STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR_DONE); __advanceCommunicationProtocolCounters(); break; case STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR_DONE: ParticleAttributes.node.state = STATE_TYPE_ENUMERATING_NEIGHBOURS_DONE; goto __STATE_TYPE_ENUMERATING_NEIGHBOURS_DONE; break; __STATE_TYPE_ENUMERATING_NEIGHBOURS_DONE: case STATE_TYPE_ENUMERATING_NEIGHBOURS_DONE: setInitiatorStateStart(&ParticleAttributes.protocol.ports.north); ParticleAttributes.node.state = STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY; enableLocalTimeInterrupt(); goto __STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY; break; // ---------------- boot states: network geometry detection/announcement ---------------- __STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY: case STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY: // on right most and bottom most node if ((ParticleAttributes.node.type == NODE_TYPE_TAIL) && (true == ParticleAttributes.protocol.hasNetworkGeometryDiscoveryBreadCrumb)) { __handleSendAnnounceNetworkGeometry(STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_DONE); } else { ParticleAttributes.node.state = STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_DONE; goto __STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_DONE; } break; __STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_DONE: case STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_DONE: ParticleAttributes.node.state = STATE_TYPE_IDLE; goto __STATE_TYPE_IDLE; break; case STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_RELAY: __handleRelayAnnounceNetworkGeometry(STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_RELAY_DONE); break; case STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_RELAY_DONE: ParticleAttributes.node.state = STATE_TYPE_IDLE; goto __STATE_TYPE_IDLE; break; // ---------------- working states: sync neighbour ---------------- case STATE_TYPE_RESYNC_NEIGHBOUR: setInitiatorStateStart(ParticleAttributes.directionOrientedPorts.simultaneous.protocol); ParticleAttributes.node.state = STATE_TYPE_SYNC_NEIGHBOUR; break; case STATE_TYPE_SYNC_NEIGHBOUR: __handleSynchronizeNeighbour(STATE_TYPE_SYNC_NEIGHBOUR_DONE); break; case STATE_TYPE_SYNC_NEIGHBOUR_DONE: __handleSynchronizeNeighbourDoneOrRunTest(STATE_TYPE_IDLE); ParticleAttributes.timeSynchronization.isNextSyncPackageTransmissionEnabled = true; break; // // ---------------- working states: set network geometry---------------- // case STATE_TYPE_SEND_SET_NETWORK_GEOMETRY: // __handleSetNetworkGeometry(ParticleAttributes.protocol.networkGeometry.rows, // ParticleAttributes.protocol.networkGeometry.columns, // STATE_TYPE_IDLE); // break; // ---------------- working states: execute actuation command---------------- case STATE_TYPE_EXECUTE_ACTUATION_COMMAND: handleExecuteActuation(__onActuationDoneCallback); break; // ---------------- working states: sending package ---------------- case STATE_TYPE_SENDING_PACKAGE_TO_NORTH: __handleSendPackage(&ParticleAttributes.directionOrientedPorts.north, STATE_TYPE_IDLE); break; case STATE_TYPE_SENDING_PACKAGE_TO_EAST: __handleSendPackage(&ParticleAttributes.directionOrientedPorts.east, STATE_TYPE_IDLE); break; case STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH: __handleSendPackage(&ParticleAttributes.directionOrientedPorts.simultaneous, STATE_TYPE_IDLE); break; case STATE_TYPE_SENDING_PACKAGE_TO_SOUTH: __handleSendPackage(&ParticleAttributes.directionOrientedPorts.south, STATE_TYPE_IDLE); break; case STATE_TYPE_SENDING_PACKAGE_TO_NORTH_THEN_PREPARE_SLEEP: __handleSendPackage(&ParticleAttributes.directionOrientedPorts.north, STATE_TYPE_PREPARE_FOR_SLEEP); break; case STATE_TYPE_SENDING_PACKAGE_TO_EAST_THEN_PREPARE_SLEEP: __handleSendPackage(&ParticleAttributes.directionOrientedPorts.east, STATE_TYPE_PREPARE_FOR_SLEEP); break; case STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH_THEN_PREPARE_SLEEP: __handleSendPackage(&ParticleAttributes.directionOrientedPorts.simultaneous, STATE_TYPE_PREPARE_FOR_SLEEP); break; case STATE_TYPE_SENDING_PACKAGE_TO_SOUTH_THEN_PREPARE_SLEEP: __handleSendPackage(&ParticleAttributes.directionOrientedPorts.south, STATE_TYPE_PREPARE_FOR_SLEEP); break; // ---------------- working states: receiving/interpreting commands ---------------- __STATE_TYPE_IDLE: case STATE_TYPE_IDLE: ParticleAttributes.directionOrientedPorts.north.receivePimpl(); ParticleAttributes.directionOrientedPorts.east.receivePimpl(); ParticleAttributes.directionOrientedPorts.south.receivePimpl(); __handleIsActuationCommandPeriod(); // future time stamp dependent execution should be better placed in the scheduler processScheduler(); // shiftConsumableLocalTimeTrackingClockLagUnitsToIsr(); // // TODO: evaluation code // if (ParticleAttributes.localTime.numTimePeriodsPassed > 255) { // blinkAddressNonblocking(); // blinkTimeIntervalNonblocking(); // ParticleAttributes.periphery.isTxSouthToggleEnabled = true; // // } break; // ---------------- standby states: sleep mode related states ---------------- case STATE_TYPE_PREPARE_FOR_SLEEP: if (ParticleAttributes.directionOrientedPorts.north.txPort->isTransmitting || ParticleAttributes.directionOrientedPorts.east.txPort->isTransmitting || ParticleAttributes.directionOrientedPorts.south.txPort->isTransmitting) { break; } ParticleAttributes.node.state = STATE_TYPE_SLEEP_MODE; break; case STATE_TYPE_SLEEP_MODE: DEBUG_CHAR_OUT('z'); sleep_enable(); MEMORY_BARRIER; CLI; MEMORY_BARRIER; sleep_cpu(); sleep_disable(); DEBUG_CHAR_OUT('Z'); break; // ---------------- erroneous/dead end states ---------------- case STATE_TYPE_UNDEFINED: case STATE_TYPE_ERRONEOUS: case STATE_TYPE_STALE: // __STATE_TYPE_STALE: break; } }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/Evaluation.h
/** * @author <NAME> 16.10.2016 * * Evaluation related arguments. */ #pragma once //#define EVALUATION_SIMPLE_SYNC_AND_ACTUATION //#define EVALUATION_SYNC_CYCLICALLY //#define EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG //#define EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_IN_PHASE_SHIFTING #define EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_THEN_ACTUATE_ONCE /** * increment / decrement the cpu frequency after several transmitted sync packages * enable to enable oscillating frequency * disable for constant frequency */ //#define EVALUATION_ENABLE_FLUCTUATE_CPU_FREQUENCY_ON_PURPOSE #ifdef EVALUATION_ENABLE_FLUCTUATE_CPU_FREQUENCY_ON_PURPOSE # if defined(__AVR_ATmega16__) # define EVALUATION_OSC_CALIBRATION_REGISTER OSCCAL # endif # if defined(__AVR_ATtiny1634__) # define EVALUATION_OSC_CALIBRATION_REGISTER OSCCAL0 # endif # define EVALUATION_OSCCAL_MAX_OFFSET ((uint8_t)8) # define EVALUATION_OSCCAL_MIN_OFFSET ((uint8_t)8) # define EVALUATION_OSCCAL_STEP ((uint8_t)1) #endif #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_THEN_ACTUATE_ONCE #define EVALUATION_SYNC_PACKAGES_BEFORE_ACTUATION ((uint16_t) 20) #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/ReceptionPCI.h
/** * @author <NAME> 20.07.2016 * * Reception pin change interrupt configuration. */ #pragma once #include <avr/interrupt.h> #include "common/PortInteraction.h" #ifdef __AVR_ATtiny1634__ // for production MCU # define __RX_INTERRUPT_FLAG_NORTH PCIF2 # define __RX_INTERRUPT_FLAG_EAST PCIF1 # define __RX_INTERRUPT_FLAG_SOUTH PCIF0 # define RX_NORTH_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__RX_INTERRUPT_FLAG_NORTH)) != 0) ? GIFR = bit(__RX_INTERRUPT_FLAG_NORTH):0) # define RX_EAST_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__RX_INTERRUPT_FLAG_EAST)) != 0) ? GIFR = bit(__RX_INTERRUPT_FLAG_EAST):0) # define RX_SOUTH_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__RX_INTERRUPT_FLAG_SOUTH)) != 0) ? GIFR = bit(__RX_INTERRUPT_FLAG_SOUTH):0) # define RX_INTERRUPTS_CLEAR_PENDING \ RX_NORTH_INTERRUPT_CLEAR_PENDING; \ RX_EAST_INTERRUPT_CLEAR_PENDING; \ RX_SOUTH_INTERRUPT_CLEAR_PENDING # define RX_INT_ENABLE \ (GIMSK setBit (bit(PCIE0) | bit(PCIE1) | bit(PCIE2))) # define RX_NORTH_INTERRUPT_DISABLE \ (PCMSK2 unsetBit bit(PCINT17)) # define RX_NORTH_INTERRUPT_ENABLE \ (PCMSK2 setBit bit(PCINT17)) # define RX_SOUTH_INTERRUPT_DISABLE \ (PCMSK0 unsetBit bit(PCINT4)) # define RX_SOUTH_INTERRUPT_ENABLE \ (PCMSK0 setBit bit(PCINT4)) # define RX_EAST_INTERRUPT_DISABLE \ (PCMSK1 unsetBit bit(PCINT8)) # define RX_EAST_INTERRUPT_ENABLE \ (PCMSK1 setBit bit(PCINT8)) # define RX_INTERRUPTS_ENABLE \ RX_NORTH_INTERRUPT_ENABLE; \ RX_SOUTH_INTERRUPT_ENABLE; \ RX_EAST_INTERRUPT_ENABLE # define RX_INTERRUPTS_DISABLE \ RX_NORTH_INTERRUPT_DISABLE; \ RX_SOUTH_INTERRUPT_DISABLE; \ RX_EAST_INTERRUPT_DISABLE # define RX_INTERRUPTS_SETUP \ RX_INTERRUPTS_CLEAR_PENDING; \ RX_INT_ENABLE #else # if defined(__AVR_ATmega16__) // for simulator MCU # define __RX_INTERRUPT_FLAG_NORTH INTF2 # define __RX_INTERRUPT_FLAG_EAST INTF1 # define __RX_INTERRUPT_FLAG_SOUTH INTF0 # define RX_NORTH_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__RX_INTERRUPT_FLAG_NORTH)) != 0) ? GIFR = bit(__RX_INTERRUPT_FLAG_NORTH):0) # define RX_EAST_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__RX_INTERRUPT_FLAG_EAST)) != 0) ? GIFR = bit(__RX_INTERRUPT_FLAG_EAST):0) # define RX_SOUTH_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__RX_INTERRUPT_FLAG_SOUTH)) != 0) ? GIFR = bit(__RX_INTERRUPT_FLAG_SOUTH):0) # define RX_INTERRUPTS_CLEAR_PENDING \ RX_NORTH_INTERRUPT_CLEAR_PENDING; \ RX_EAST_INTERRUPT_CLEAR_PENDING; \ RX_SOUTH_INTERRUPT_CLEAR_PENDING //ISC2 - 0: on falling edge, 1: on rising edge //(ISCx1, ISCx0) - (0,1): on logic change # define __RX_INTERRUPTS_SENSE_CONTROL_SETUP \ MCUCR setBit (0 << ISC11) | (1 << ISC10) | (0 << ISC01) | (1 << ISC00); \ MCUCSR setBit (1 << ISC2) # define RX_NORTH_INTERRUPT_DISABLE GICR unsetBit bit(INT2); # define RX_NORTH_INTERRUPT_ENABLE GICR setBit bit(INT2); # define RX_EAST_INTERRUPT_DISABLE GICR unsetBit bit(INT1); # define RX_EAST_INTERRUPT_ENABLE GICR setBit bit(INT1); # define RX_SOUTH_INTERRUPT_DISABLE GICR unsetBit bit(INT0); # define RX_SOUTH_INTERRUPT_ENABLE GICR setBit bit(INT0); # define RX_INTERRUPTS_ENABLE GICR setBit ((1 << INT0) | (1 << INT1) | (1 << INT2)) # define RX_INTERRUPTS_DISABLE GICR unsetBit ((1 << INT0) | (1 << INT1) | (1 << INT2)) # define RX_INTERRUPTS_SETUP \ RX_INTERRUPTS_CLEAR_PENDING; \ __RX_INTERRUPTS_SENSE_CONTROL_SETUP # else # error # endif #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/periphery/Periphery.h
/** * @author <NAME> 17.09.2016 */ #pragma once #include "uc-core/particle/Globals.h" #include "uc-core/configuration/IoPins.h" #include "common/common.h" #include "uc-core/delay/delay.h" #include "uc-core/configuration/Periphery.h" #include "uc-core/configuration/interrupts/ReceptionPCI.h" #include "uc-core/scheduler/SchedulerTypes.h" #ifndef PERIPHERY_REMOVE_IMPL static void __disableInterruptsForBlockingBlinking(void) { RX_NORTH_INTERRUPT_DISABLE; RX_EAST_INTERRUPT_DISABLE; RX_SOUTH_INTERRUPT_DISABLE; } static void __ledsOff(void) { LED_STATUS1_OFF; LED_STATUS2_OFF; LED_STATUS3_OFF; LED_STATUS4_OFF; } static void __ledsOn(void) { LED_STATUS1_ON; LED_STATUS2_ON; LED_STATUS3_ON; LED_STATUS4_ON; } ///** // * Blinks row times, column times followed by a quitting flash signal. // */ //static void __blinkAddressBlocking(void) { // LED_STATUS1_OFF; // DELAY_MS_500; // for (int8_t row = 0; row < ParticleAttributes.node.address.row; row++) { // LED_STATUS1_TOGGLE; // DELAY_MS_196; // LED_STATUS1_TOGGLE; // DELAY_MS_196; // } // DELAY_MS_196; // DELAY_MS_196; // for (int8_t column = 0; column < ParticleAttributes.node.address.column; column++) { // LED_STATUS1_TOGGLE; // DELAY_MS_196; // LED_STATUS1_TOGGLE; // DELAY_MS_196; // } // DELAY_MS_196; // // LED_STATUS1_TOGGLE; // DELAY_MS_30; // DELAY_MS_30; // LED_STATUS1_TOGGLE; // DELAY_MS_30; // DELAY_MS_30; // LED_STATUS1_TOGGLE; // DELAY_MS_30; // DELAY_MS_30; // LED_STATUS1_TOGGLE; //} // ///** // * Blinks the current address on status led endlessly. // */ //void blinkAddressForever(void) { // __disableInterruptsForBlockingBlinking(); // LED_STATUS1_ON; // DELAY_MS_500; // forever { // __blinkAddressBlocking(); // DELAY_MS_500; // } //} /** * Blinks LEDs to indicate the error state. * This function never returns. */ static void __blinkBufferOverflowErrorForever(uint8_t portNumber) { if (ParticleAttributes.alerts.isRxBufferOverflowEnabled == false) { __ledsOff(); LED_STATUS2_ON; LED_STATUS3_ON; return; } __disableInterruptsForBlockingBlinking(); forever { LED_STATUS1_OFF; LED_STATUS2_ON; LED_STATUS3_OFF; DELAY_MS_196; LED_STATUS1_ON; LED_STATUS2_OFF; LED_STATUS3_ON; DELAY_MS_196; for (uint8_t i = 0; i < portNumber; i++) { LED_STATUS4_OFF; DELAY_MS_196; LED_STATUS4_ON; DELAY_MS_196; } } } void blinkReceptionBufferOverflowErrorForever(RxPort *const rxPort) { uint8_t portNumber = 5; if (rxPort == ParticleAttributes.directionOrientedPorts.north.rxPort) { portNumber = 1; } else if (rxPort == ParticleAttributes.directionOrientedPorts.east.rxPort) { portNumber = 2; } else if (rxPort == ParticleAttributes.directionOrientedPorts.south.rxPort) { portNumber = 3; } __blinkBufferOverflowErrorForever(2 * portNumber); } void blinkReceptionSnapshotBufferOverflowErrorForever(RxSnapshotBuffer *const snapshotBuffer) { uint8_t portNumber = 5; if (snapshotBuffer == &ParticleAttributes.directionOrientedPorts.north.rxPort->snapshotsBuffer) { portNumber = 1; } else if (snapshotBuffer == &ParticleAttributes.directionOrientedPorts.east.rxPort->snapshotsBuffer) { portNumber = 2; } else if (snapshotBuffer == &ParticleAttributes.directionOrientedPorts.south.rxPort->snapshotsBuffer) { portNumber = 3; __blinkBufferOverflowErrorForever(portNumber); } } /** * Blinks LEDs to indicate the error state. * This function never returns. */ void blinkGenericErrorForever(void) { __disableInterruptsForBlockingBlinking(); forever { __ledsOff(); DELAY_MS_196; __ledsOn(); DELAY_MS_196; } } static void __blinkLedNForever(uint8_t n) { __disableInterruptsForBlockingBlinking(); __ledsOn(); forever { DELAY_MS_196; switch (n) { case 1: LED_STATUS1_TOGGLE; break; case 2: LED_STATUS2_TOGGLE; break; case 3: LED_STATUS3_TOGGLE; break; case 4: LED_STATUS4_TOGGLE; break; } DELAY_MS_196; } } void blinkLed1Forever(void) { if (ParticleAttributes.alerts.isGenericErrorEnabled == false) { __ledsOff(); LED_STATUS1_ON; LED_STATUS2_ON; return; } __disableInterruptsForBlockingBlinking(); __blinkLedNForever(1); } void blinkLed2Forever(void) { if (ParticleAttributes.alerts.isGenericErrorEnabled == false) { __ledsOff(); LED_STATUS2_ON; return; } __disableInterruptsForBlockingBlinking(); __blinkLedNForever(2); } void blinkLed3Forever(void) { if (ParticleAttributes.alerts.isGenericErrorEnabled == false) { __ledsOff(); LED_STATUS3_ON; return; } __disableInterruptsForBlockingBlinking(); __blinkLedNForever(3); } void blinkLed4Forever(void) { if (ParticleAttributes.alerts.isGenericErrorEnabled == false) { __ledsOff(); LED_STATUS4_ON; return; } __disableInterruptsForBlockingBlinking(); __blinkLedNForever(4); } void blinkInterruptErrorForever(void) { __disableInterruptsForBlockingBlinking(); forever { LED_STATUS1_OFF; LED_STATUS2_ON; LED_STATUS3_OFF; LED_STATUS4_ON; DELAY_MS_196; LED_STATUS1_ON; LED_STATUS2_OFF; LED_STATUS3_ON; LED_STATUS4_OFF; DELAY_MS_196; } } /** * Blink LEDs to indicate a parity error state. * Sequence on parityBit == true: led 1, led2, led3 * otherwise: led 3, led 2, led 1. * This function never returns. */ void blinkParityErrorForever(bool parityBit) { if (ParticleAttributes.alerts.isRxParityErrorEnabled == false) { __ledsOff(); LED_STATUS1_ON; LED_STATUS2_ON; return; } __disableInterruptsForBlockingBlinking(); __ledsOff(); if (parityBit == true) { forever { LED_STATUS1_ON; DELAY_MS_500; LED_STATUS1_OFF; LED_STATUS2_ON; DELAY_MS_500; LED_STATUS2_OFF; LED_STATUS3_ON; DELAY_MS_500; LED_STATUS3_OFF; } } else { forever { LED_STATUS3_ON; DELAY_MS_500; LED_STATUS3_OFF; LED_STATUS2_ON; DELAY_MS_500; LED_STATUS2_OFF; LED_STATUS1_ON; DELAY_MS_500; LED_STATUS1_OFF; } } } void ledsOnForever(void) { __disableInterruptsForBlockingBlinking(); __ledsOn(); forever; } void blinkTimeIntervalNonblocking(void) { uint8_t sreg = SREG; MEMORY_BARRIER; CLI; MEMORY_BARRIER; const uint16_t now = ParticleAttributes.localTime.numTimePeriodsPassed; MEMORY_BARRIER; SREG = sreg; MEMORY_BARRIER; if (ParticleAttributes.periphery.blinkTimeInterval.lastExecutionTime == now) { return; } ParticleAttributes.periphery.blinkTimeInterval.lastExecutionTime = now; switch (ParticleAttributes.periphery.blinkTimeInterval.blinkState) { case TIME_INTERVAL_BLINK_STATES_LED_ON: LED_STATUS2_ON; if (ParticleAttributes.periphery.blinkTimeInterval.localTimeMultiplier-- > 1) { return; } ParticleAttributes.periphery.blinkTimeInterval.localTimeMultiplier = TIME_INTERVAL_BLINK_STATES_PERIOD_MULTIPLIER; ParticleAttributes.periphery.blinkTimeInterval.blinkState = TIME_INTERVAL_BLINK_STATES_LED_OFF; break; case TIME_INTERVAL_BLINK_STATES_LED_OFF: LED_STATUS2_OFF; if (ParticleAttributes.periphery.blinkTimeInterval.localTimeMultiplier-- > 1) { return; } ParticleAttributes.periphery.blinkTimeInterval.localTimeMultiplier = TIME_INTERVAL_BLINK_STATES_PERIOD_MULTIPLIER; ParticleAttributes.periphery.blinkTimeInterval.blinkState = TIME_INTERVAL_BLINK_STATES_LED_ON; break; default: break; } } void blinkAddressNonblocking(void) { uint8_t sreg = SREG; MEMORY_BARRIER; CLI; MEMORY_BARRIER; const uint16_t now = ParticleAttributes.localTime.numTimePeriodsPassed; MEMORY_BARRIER; SREG = sreg; MEMORY_BARRIER; if (ParticleAttributes.periphery.blinkAddress.lastExecutionTime == now) { return; } ParticleAttributes.periphery.blinkAddress.lastExecutionTime = now; switch (ParticleAttributes.periphery.blinkAddress.blinkAddressState) { case ADDRESS_BLINK_STATES_START: ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_BLINK_ROW; break; case ADDRESS_BLINK_STATES_BLINK_ROW: ParticleAttributes.periphery.blinkAddress.blinkRowCounter = ParticleAttributes.node.address.row; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_ROW_ON; ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_ON_COUNTER_MAX; break; case ADDRESS_BLINK_STATES_ROW_ON: LED_STATUS3_ON; if (ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay-- > 0) { return; } ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_OFF_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_ROW_OFF; break; case ADDRESS_BLINK_STATES_ROW_OFF: LED_STATUS3_OFF; if (ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay-- > 0) { return; } if (ParticleAttributes.periphery.blinkAddress.blinkRowCounter-- > 1) { ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_ON_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_ROW_ON; return; } ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_SEPARATION_BREAK_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_PAUSE; break; case ADDRESS_BLINK_STATES_PAUSE: LED_STATUS3_OFF; if (ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay-- > 0) { return; } ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_BLINK_COLUMN; break; case ADDRESS_BLINK_STATES_BLINK_COLUMN: ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_ON_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkColumnCounter = ParticleAttributes.node.address.column; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_COLUMN_ON; break; case ADDRESS_BLINK_STATES_COLUMN_ON: LED_STATUS3_ON; if (ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay-- > 0) { return; } ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_OFF_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_COLUMN_OFF; break; case ADDRESS_BLINK_STATES_COLUMN_OFF: LED_STATUS3_OFF; if (ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay-- > 0) { return; } if (ParticleAttributes.periphery.blinkAddress.blinkColumnCounter-- > 1) { ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_ON_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_COLUMN_ON; return; } ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_SEPARATION_BREAK_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_PAUSE2; break; case ADDRESS_BLINK_STATES_PAUSE2: LED_STATUS3_OFF; if (ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay-- > 0) { return; } ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_SEPARATION_FLASH_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_QUIT_SIGNAL; break; case ADDRESS_BLINK_STATES_QUIT_SIGNAL: LED_STATUS3_ON; if (ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay-- > 0) { return; } ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay = ADDRESS_BLINK_STATES_LED_SEPARATION_LONG_BREAK_COUNTER_MAX; ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_END; break; case ADDRESS_BLINK_STATES_END: LED_STATUS3_OFF; if (ParticleAttributes.periphery.blinkAddress.blinkAddressBlinkDelay-- > 0) { return; } ParticleAttributes.periphery.blinkAddress.blinkAddressState = ADDRESS_BLINK_STATES_START; break; default: break; } } void blinkKnightRidersKittForever(void) { __disableInterruptsForBlockingBlinking(); #define __kittDelay DELAY_MS_196 forever { LED_STATUS1_ON; LED_STATUS2_OFF; LED_STATUS3_OFF; LED_STATUS4_OFF; __kittDelay; LED_STATUS1_ON; LED_STATUS2_ON; LED_STATUS3_OFF; LED_STATUS4_OFF; __kittDelay; LED_STATUS1_OFF; LED_STATUS2_ON; LED_STATUS3_ON; LED_STATUS4_OFF; __kittDelay; LED_STATUS1_OFF; LED_STATUS2_OFF; LED_STATUS3_ON; LED_STATUS4_ON; __kittDelay; LED_STATUS1_OFF; LED_STATUS2_OFF; LED_STATUS3_OFF; LED_STATUS4_ON; __kittDelay; LED_STATUS1_OFF; LED_STATUS2_OFF; LED_STATUS3_ON; LED_STATUS4_ON; __kittDelay; LED_STATUS1_OFF; LED_STATUS2_ON; LED_STATUS3_ON; LED_STATUS4_OFF; __kittDelay; LED_STATUS1_ON; LED_STATUS2_ON; LED_STATUS3_OFF; LED_STATUS4_OFF; __kittDelay; } } /** * Puts all LEDs into a defined state. Since leds are toggled * during initialization process their state is undetermined. */ void setupLedsState(SchedulerTask *task) { __ledsOff(); if (ParticleAttributes.node.type == NODE_TYPE_ORIGIN || ParticleAttributes.node.type == NODE_TYPE_INTER_HEAD) { LED_STATUS1_ON; } if (ParticleAttributes.node.type == NODE_TYPE_TAIL) { LED_STATUS4_ON; } task->isEnabled = false; } /** * Toggles the heartbeat LED. */ void heartBeatToggle(SchedulerTask *task) { LED_STATUS4_TOGGLE; task->isEnabled = true; } #else #define blinkReceptionSnapshotBufferOverflowErrorForever(...) #define blinkReceptionBufferOverflowErrorForever(...) #define blinkGenericErrorForever(...) #define blinkLed1Forever(...) #define blinkLed2Forever(...) #define blinkLed3Forever(...) #define blinkLed4Forever(...) #define blinkInterruptErrorForever(...) #define blinkParityErrorForever(...) #define ledsOnForever(...) #define blinkTimeIntervalNonblocking(...) #define blinkAddressNonblocking(...) #define blinkKnightRidersKittForever(...) #define setupLedsBeforeProcessing(...) #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/IoPins.h
/** * @author <NAME> 2016 * * Input and output pin related arguments. */ #pragma once #include "common/PortADefinition.h" #include "common/PortBDefinition.h" #include "common/PortCDefinition.h" #include "uc-core/configuration/Leds.h" #if defined(__AVR_ATmega16__) # include "common/PortDDefinition.h" #endif #include "common/PortInteraction.h" /** * south tx/rx */ // tx south #define __SOUTH_TX_PIN Pin3 #define __SOUTH_TX_DIR ADir #define __SOUTH_TX_OUT AOut #define __SOUTH_TX_IN AIn #define SOUTH_TX_HI __SOUTH_TX_OUT setHi __SOUTH_TX_PIN #define SOUTH_TX_LO __SOUTH_TX_OUT setLo __SOUTH_TX_PIN #define __SOUTH_TX ((unsigned char)((false == (__SOUTH_TX_IN getBit __SOUTH_TX_PIN)) ? false : true)) #define SOUTH_TX_IS_HI (0 != (__SOUTH_TX)) #define SOUTH_TX_IS_LO (false == (__SOUTH_TX)) #define SOUTH_TX_TOGGLE __SOUTH_TX_OUT toggleBit __SOUTH_TX_PIN #define SOUTH_TX_SETUP __SOUTH_TX_DIR setOut __SOUTH_TX_PIN; SOUTH_TX_HI // rx south #ifdef __AVR_ATtiny1634__ # define __SOUTH_RX_PIN Pin4 # define __SOUTH_RX_DIR ADir # define __SOUTH_RX_OUT AOut # define __SOUTH_RX_IN AIn # define SOUTH_RX_PULL_UP PUEA pullUp __SOUTH_RX_PIN # define SOUTH_RX_PULL_UP_DISABLE PUEA setLo __SOUTH_RX_PIN #else # if defined(__AVR_ATmega16__) # define __SOUTH_RX_PIN Pin2 # define __SOUTH_RX_DIR DDir # define __SOUTH_RX_OUT DOut # define __SOUTH_RX_IN DIn # define SOUTH_RX_PULL_UP_DISABLE __SOUTH_RX_OUT setLo __SOUTH_RX_PIN # define SOUTH_RX_PULL_UP __SOUTH_RX_OUT pullUp __SOUTH_RX_PIN # else # error # endif #endif #define __SOUTH_RX ((unsigned char)((false == (__SOUTH_RX_IN getBit __SOUTH_RX_PIN)) ? false : true)) #define SOUTH_RX_IS_HI (__SOUTH_RX) #define SOUTH_RX_IS_LO (false == (__SOUTH_RX)) #define SOUTH_RX_SETUP __SOUTH_RX_DIR setIn __SOUTH_RX_PIN; SOUTH_RX_PULL_UP // rx-switch south #define __SOUTH_RX_SWITCH_PIN Pin2 #define __SOUTH_RX_SWITCH_DIR ADir #define __SOUTH_RX_SWITCH_OUT AOut #define __SOUTH_RX_SWITCH_IN AIn #define SOUTH_RX_SWITCH_HI __SOUTH_RX_SWITCH_OUT setHi __SOUTH_RX_SWITCH_PIN #define SOUTH_RX_SWITCH_LO __SOUTH_RX_SWITCH_OUT setLo __SOUTH_RX_SWITCH_PIN #define __SOUTH_RX_SWITCH ((unsigned char)((false == (__SOUTH_RX_IN getBit __SOUTH_RX_PIN)) ? false : true)) #define SOUTH_RX_SWITCH_IS_HI (__SOUTH_RX_SWITCH) #define SOUTH_RX_SWITCH_IS_LO (false == (__SOUTH_RX_SWITCH)) #define SOUTH_RX_SWITCH_SETUP __SOUTH_RX_SWITCH_DIR setOut __SOUTH_RX_SWITCH_PIN; SOUTH_RX_SWITCH_HI /** * north tx/rx */ // tx north #define __NORTH_TX_PIN Pin0 #define __NORTH_TX_DIR CDir #define __NORTH_TX_OUT COut #define __NORTH_TX_IN CIn #define NORTH_TX_HI __NORTH_TX_OUT setHi __NORTH_TX_PIN #define NORTH_TX_LO __NORTH_TX_OUT setLo __NORTH_TX_PIN #define __NORTH_TX ((unsigned char)((false == (__NORTH_TX_IN getBit __NORTH_TX_PIN)) ? false : true)) #define NORTH_TX_IS_HI (__NORTH_TX) #define NORTH_TX_IS_LO (false == (__NORTH_TX)) #define NORTH_TX_TOGGLE __NORTH_TX_OUT toggleBit __NORTH_TX_PIN #define NORTH_TX_SETUP __NORTH_TX_DIR setOut __NORTH_TX_PIN; NORTH_TX_HI // rx north #ifdef __AVR_ATtiny1634__ # define __NORTH_RX_PIN Pin5 # define __NORTH_RX_DIR CDir # define __NORTH_RX_OUT COut # define __NORTH_RX_IN CIn # define NORTH_RX_PULL_UP PUEC pullUp __NORTH_RX_PIN # define NORTH_RX_PULL_UP_DISABLE PUEC setLo __NORTH_RX_PIN #else # if defined(__AVR_ATmega16__) # define __NORTH_RX_PIN Pin2 # define __NORTH_RX_DIR BDir # define __NORTH_RX_OUT BOut # define __NORTH_RX_IN BIn # define NORTH_RX_PULL_UP __NORTH_RX_OUT pullUp __NORTH_RX_PIN # define NORTH_RX_PULL_UP_DISABLE __NORTH_RX_OUT setLo __NORTH_RX_PIN # else # error # endif #endif #define __NORTH_RX ((unsigned char)((false == (__NORTH_RX_IN getBit __NORTH_RX_PIN)) ? false : true)) #define NORTH_RX_IS_HI (__NORTH_RX) #define NORTH_RX_IS_LO (false == (__NORTH_RX)) #define NORTH_RX_SETUP __NORTH_RX_DIR setIn __NORTH_RX_PIN; NORTH_RX_PULL_UP // rx-switch north #define __NORTH_RX_SWITCH_PIN Pin4 #define __NORTH_RX_SWITCH_DIR CDir #define __NORTH_RX_SWITCH_OUT COut #define __NORTH_RX_SWITCH_IN CIn #define NORTH_RX_SWITCH_HI (__NORTH_RX_SWITCH_OUT setHi __NORTH_RX_SWITCH_PIN) #define NORTH_RX_SWITCH_LO (__NORTH_RX_SWITCH_OUT setLo __NORTH_RX_SWITCH_PIN) #define __NORTH_RX_SWITCH ((unsigned char)((false == (__NORTH_RX_SWITCH_IN getBit __NORTH_RX_SWITCH_PIN)) ? false : true)) #define NORTH_RX_SWITCH_IS_HI (__NORTH_RX_SWITCH) #define NORTH_RX_SWITCH_IS_LO (false == (__NORTH_RX_SWITCH)) #define NORTH_RX_SWITCH_TOGGLE (__NORTH_RX_SWITCH_OUT toggleBit __NORTH_RX_SWITCH_PIN) #define NORTH_RX_SWITCH_SETUP __NORTH_RX_SWITCH_DIR setOut __NORTH_RX_SWITCH_PIN; NORTH_RX_SWITCH_HI /** * east tx/rx */ // tx east #define __EAST_TX_PIN Pin7 #define __EAST_TX_DIR ADir #define __EAST_TX_OUT AOut #define __EAST_TX_IN AIn #define EAST_TX_HI __EAST_TX_OUT setHi __EAST_TX_PIN #define EAST_TX_LO __EAST_TX_OUT setLo __EAST_TX_PIN #define __EAST_TX ((unsigned char)((false == (__EAST_TX_IN getBit __EAST_TX_PIN)) ? false : true)) #define EAST_TX_IS_HI (__EAST_TX) #define EAST_TX_IS_LO (false == (__EAST_TX)) #define EAST_TX_TOGGLE __EAST_TX_OUT toggleBit __EAST_TX_PIN #define EAST_TX_SETUP __EAST_TX_DIR setOut __EAST_TX_PIN; EAST_TX_LO // rx east #ifdef __AVR_ATtiny1634__ # define __EAST_RX_PIN Pin0 # define __EAST_RX_DIR BDir # define __EAST_RX_OUT BOut # define __EAST_RX_IN BIn # define EAST_RX_PULL_UP PUEB pullUp __EAST_RX_PIN # define EAST_RX_PULL_UP_DISABLE PUEB setLo __EAST_RX_PIN #else # if defined(__AVR_ATmega16__) # define __EAST_RX_PIN Pin3 # define __EAST_RX_DIR DDir # define __EAST_RX_OUT DOut # define __EAST_RX_IN DIn # define EAST_RX_PULL_UP __EAST_RX_OUT pullUp __EAST_RX_PIN # define EAST_RX_PULL_UP_DISABLE __EAST_RX_OUT setLo __EAST_RX_PIN # else # error # endif #endif #define __EAST_RX ((unsigned char)((false == (__EAST_RX_IN getBit __EAST_RX_PIN)) ? false : true)) #define EAST_RX_IS_HI (__EAST_RX) #define EAST_RX_IS_LO (false == (__EAST_RX)) #define EAST_RX_SETUP __EAST_RX_DIR setIn __EAST_RX_PIN; EAST_RX_PULL_UP /** * LEDs */ // status led 1 #define __LED_STATUS1_PIN Pin3 #define __LED_STATUS1_DIR BDir #define __LED_STATUS1_OUT BOut #define __LED_STATUS1_IN BIn #define LED_STATUS1 __LED_STATUS1_IN getBit __LED_STATUS1_PIN #ifdef LEDS_SUPPRESS_OUTPUT #define LED_STATUS1_ON #define LED_STATUS1_OFF #else #define LED_STATUS1_ON __LED_STATUS1_OUT setHi __LED_STATUS1_PIN #define LED_STATUS1_OFF __LED_STATUS1_OUT setLo __LED_STATUS1_PIN #endif #define LED_STATUS1_IS_ON (0 != (LED_STATUS1)) #define LED_STATUS1_IS_OFF (false == (LED_STATUS1)) #ifdef LEDS_SUPPRESS_OUTPUT #define LED_STATUS1_TOGGLE #else #define LED_STATUS1_TOGGLE __LED_STATUS1_OUT toggleBit __LED_STATUS1_PIN #endif #define LED_STATUS1_SETUP __LED_STATUS1_DIR setOut __LED_STATUS1_PIN; LED_STATUS1_OFF // status led 2 #define __LED_STATUS2_PIN Pin0 #define __LED_STATUS2_DIR ADir #define __LED_STATUS2_OUT AOut #define __LED_STATUS2_IN AIn #define LED_STATUS2 __LED_STATUS2_IN getBit __LED_STATUS2_PIN #ifdef LEDS_SUPPRESS_OUTPUT #define LED_STATUS2_ON #define LED_STATUS2_OFF #else #define LED_STATUS2_ON __LED_STATUS2_OUT setHi __LED_STATUS2_PIN #define LED_STATUS2_OFF __LED_STATUS2_OUT setLo __LED_STATUS2_PIN #endif #define LED_STATUS2_IS_ON (0 != (LED_STATUS2)) #define LED_STATUS2_IS_OFF (false == (LED_STATUS2)) #ifdef LEDS_SUPPRESS_OUTPUT #define LED_STATUS2_TOGGLE #else #define LED_STATUS2_TOGGLE __LED_STATUS2_OUT toggleBit __LED_STATUS2_PIN #endif #define LED_STATUS2_SETUP __LED_STATUS2_DIR setOut __LED_STATUS2_PIN; LED_STATUS2_OFF // status led 3 #define __LED_STATUS3_PIN Pin1 #define __LED_STATUS3_DIR ADir #define __LED_STATUS3_OUT AOut #define __LED_STATUS3_IN AIn #define LED_STATUS3 __LED_STATUS3_IN getBit __LED_STATUS3_PIN #ifdef LEDS_SUPPRESS_OUTPUT #define LED_STATUS3_ON #define LED_STATUS3_OFF #else #define LED_STATUS3_ON __LED_STATUS3_OUT setHi __LED_STATUS3_PIN #define LED_STATUS3_OFF __LED_STATUS3_OUT setLo __LED_STATUS3_PIN #endif #define LED_STATUS3_IS_ON (0 != (LED_STATUS3)) #define LED_STATUS3_IS_OFF (false == (LED_STATUS3)) #ifdef LEDS_SUPPRESS_OUTPUT #define LED_STATUS3_TOGGLE #else #define LED_STATUS3_TOGGLE __LED_STATUS3_OUT toggleBit __LED_STATUS3_PIN #endif #define LED_STATUS3_SETUP __LED_STATUS3_DIR setOut __LED_STATUS3_PIN; LED_STATUS3_OFF // status led 4 #define __LED_STATUS4_PIN Pin6 #define __LED_STATUS4_DIR ADir #define __LED_STATUS4_OUT AOut #define __LED_STATUS4_IN AIn #define LED_STATUS4 __LED_STATUS4_IN getBit __LED_STATUS4_PIN #ifdef LEDS_SUPPRESS_OUTPUT #define LED_STATUS4_ON #define LED_STATUS4_OFF #else #define LED_STATUS4_ON __LED_STATUS4_OUT setHi __LED_STATUS4_PIN #define LED_STATUS4_OFF __LED_STATUS4_OUT setLo __LED_STATUS4_PIN #endif #define LED_STATUS4_IS_ON (0 != (LED_STATUS4)) #define LED_STATUS4_IS_OFF (false == (LED_STATUS4)) #ifdef LEDS_SUPPRESS_OUTPUT #define LED_STATUS4_TOGGLE #else #define LED_STATUS4_TOGGLE __LED_STATUS4_OUT toggleBit __LED_STATUS4_PIN #endif #define LED_STATUS4_SETUP __LED_STATUS4_DIR setOut __LED_STATUS4_PIN; LED_STATUS4_OFF //// status led 5 //#define __LED_STATUS5_PIN Pin5 //#define __LED_STATUS5_DIR ADir //#define __LED_STATUS5_OUT AOut //#define __LED_STATUS5_IN AIn // //#define LED_STATUS5 __LED_STATUS5_IN getBit __LED_STATUS5_PIN //#define LED_STATUS5_ON __LED_STATUS5_OUT setHi __LED_STATUS5_PIN //#define LED_STATUS5_OFF __LED_STATUS5_OUT setLo __LED_STATUS5_PIN //#define LED_STATUS5_IS_ON (0 != (LED_STATUS5)) //#define LED_STATUS5_IS_OFF (false == (LED_STATUS5)) //#define LED_STATUS5_TOGGLE __LED_STATUS5_OUT toggleBit __LED_STATUS5_PIN // //#define LED_STATUS5_SETUP __LED_STATUS5_DIR setOut __LED_STATUS5_PIN; LED_STATUS5_OFF //// status led 6 //#define __LED_STATUS6_PIN Pin2 //#define __LED_STATUS6_DIR CDir //#define __LED_STATUS6_OUT COut //#define __LED_STATUS6_IN CIn // //#define LED_STATUS6 __LED_STATUS6_IN getBit __LED_STATUS6_PIN //#define LED_STATUS6_ON __LED_STATUS6_OUT setHi __LED_STATUS6_PIN //#define LED_STATUS6_OFF __LED_STATUS6_OUT setLo __LED_STATUS6_PIN //#define LED_STATUS6_IS_ON (0 != (LED_STATUS6)) //#define LED_STATUS6_IS_OFF (false == (LED_STATUS6)) //#define LED_STATUS6_TOGGLE __LED_STATUS6_OUT toggleBit __LED_STATUS6_PIN // //#define LED_STATUS6_SETUP __LED_STATUS6_DIR setOut __LED_STATUS6_PIN; LED_STATUS6_OFF /** * Test points */ // test point 1 #define __TEST_POINT1_PIN Pin5 #define __TEST_POINT1_DIR ADir #define __TEST_POINT1_OUT AOut #define __TEST_POINT1_IN AIn #define TEST_POINT1 __TEST_POINT1_IN getBit __TEST_POINT1_PIN #define TEST_POINT1_HI __TEST_POINT1_OUT setHi __TEST_POINT1_PIN #define TEST_POINT1_LO __TEST_POINT1_OUT setLo __TEST_POINT1_PIN #define TEST_POINT1_IS_HI (0 != (TEST_POINT1)) #define TEST_POINT1_IS_LO (false == (TEST_POINT1)) #define TEST_POINT1_TOGGLE __TEST_POINT1_OUT toggleBit __TEST_POINT1_PIN #define TEST_POINT1_SETUP __TEST_POINT1_DIR setOut __TEST_POINT1_PIN; TEST_POINT1_LO // test point 2 #ifdef __AVR_ATtiny1634__ #define __TEST_POINT2_PIN Pin2 #define __TEST_POINT2_DIR BDir #define __TEST_POINT2_OUT BOut #define __TEST_POINT2_IN BIn #else # if defined(__AVR_ATmega16__) # define __TEST_POINT2_PIN Pin4 # define __TEST_POINT2_DIR BDir # define __TEST_POINT2_OUT BOut # define __TEST_POINT2_IN BIn # else # error # endif #endif #define TEST_POINT2 __TEST_POINT2_IN getBit __TEST_POINT2_PIN #define TEST_POINT2_HI __TEST_POINT2_OUT setHi __TEST_POINT2_PIN #define TEST_POINT2_LO __TEST_POINT2_OUT setLo __TEST_POINT2_PIN #define TEST_POINT2_IS_HI (0 != (TEST_POINT2)) #define TEST_POINT2_IS_LO (false == (TEST_POINT2)) #define TEST_POINT2_TOGGLE __TEST_POINT2_OUT toggleBit __TEST_POINT2_PIN #define TEST_POINT2_SETUP __TEST_POINT2_DIR setOut __TEST_POINT2_PIN; TEST_POINT2_LO // test point 3 #define __TEST_POINT3_DIR BDir #define __TEST_POINT3_PIN Pin1 #define __TEST_POINT3_OUT BOut #define __TEST_POINT3_IN BIn #define TEST_POINT3 __TEST_POINT3_IN getBit __TEST_POINT3_PIN #define TEST_POINT3_HI __TEST_POINT3_OUT setHi __TEST_POINT3_PIN #define TEST_POINT3_LO __TEST_POINT3_OUT setLo __TEST_POINT3_PIN #define TEST_POINT3_IS_HI (0 != (TEST_POINT3)) #define TEST_POINT3_IS_LO (false == (TEST_POINT3)) #define TEST_POINT3_TOGGLE __TEST_POINT3_OUT toggleBit __TEST_POINT3_PIN #define TEST_POINT3_SETUP __TEST_POINT3_DIR setOut __TEST_POINT3_PIN; TEST_POINT3_LO //// test point 4 is occupied by clock out //#define __TEST_POINT4_PIN Pin2 //#define __TEST_POINT4_DIR CDir //#define __TEST_POINT4_OUT COut //#define __TEST_POINT4_IN CIn // //#define TEST_POINT4 __TEST_POINT4_IN getBit __TEST_POINT4_PIN //#define TEST_POINT4_HI __TEST_POINT4_OUT setHi __TEST_POINT4_PIN //#define TEST_POINT4_LO __TEST_POINT4_OUT setLo __TEST_POINT4_PIN //#define TEST_POINT4_IS_HI (0 != (TEST_POINT4)) //#define TEST_POINT4_IS_LO (false == (TEST_POINT4)) //#define TEST_POINT4_TOGGLE __TEST_POINT4_OUT toggleBit __TEST_POINT4_PIN // //#define TEST_POINT4_SETUP __TEST_POINT4_DIR setOut __TEST_POINT4_PIN; TEST_POINT4_LO // unused pin #define __UNUSED1_PIN Pin1 #define __UNUSED1_DIR CDir #define __UNUSED1_OUT COut #define __UNUSED1_IN CIn #define __UNUSED1 __UNUSED1_IN getBit __UNUSED1_PIN #define __UNUSED1_HI __UNUSED1_OUT setHi __UNUSED1_PIN #define __UNUSED1_LO __UNUSED1_OUT setLo __UNUSED1_PIN #define __UNUSED1_IS_HI (0 != (__UNUSED1)) #define __UNUSED1_IS_LO (false == (__UNUSED1)) #define __UNUSED1_TOGGLE __UNUSED1_OUT toggleBit __UNUSED1_PIN #define __UNUSED1_SETUP __UNUSED1_DIR setOut __UNUSED1_PIN; __UNUSED1_LO /** * setup */ #define IO_PORTS_SETUP \ NORTH_RX_SETUP; NORTH_TX_SETUP; NORTH_RX_SWITCH_SETUP; \ EAST_RX_SETUP; EAST_TX_SETUP; \ SOUTH_RX_SETUP; SOUTH_TX_SETUP; SOUTH_RX_SWITCH_SETUP; \ LED_STATUS1_SETUP; LED_STATUS2_SETUP; LED_STATUS3_SETUP; \ LED_STATUS4_SETUP; \ TEST_POINT1_SETUP; TEST_POINT2_SETUP; TEST_POINT3_SETUP; \ __UNUSED1_SETUP
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/ManchesterDecoding.h
/** * @author <NAME> 2016 */ #pragma once #include <math.h> #include "Communication.h" #include "ManchesterDecodingTypes.h" #include "uc-core/configuration/interrupts/TxRxTimer.h" #include "simulation/SimulationMacros.h" #include "uc-core/configuration/Particle.h" #include "uc-core/configuration/communication/Communication.h" #include "uc-core/configuration/IoPins.h" #include "uc-core/delay/delay.h" #include "uc-core/periphery/Periphery.h" #include "uc-core/synchronization/Synchronization.h" /** * Resets the decoder phase state do default. * @param decoderPhaseState the phase state field to reset */ #define __resetDecoderPhaseState(decoderPhaseState) \ (decoderPhaseState = 0) /** * Evaluates to true if the phase state indicates a phase at data interval, otherwise to false. * <br/>true ... indicates a data phase * <br/>false ... indicates a clock phase * @param manchesterDecoderPhaseState the phase state field to evaluate */ #define __isDataPhase(manchesterDecoderPhaseState) \ (manchesterDecoderPhaseState == 1) /** * Updates the phase state by a short interval. * @param manchesterDecoderPhaseState the phase state field to update */ #define __phaseStateAdvanceShortInterval(manchesterDecoderPhaseState) \ (manchesterDecoderPhaseState += 1) /** * Updates the phase state by a long interval. * @param manchesterDecoderPhaseState the phase state field to update */ #define __phaseStateAdvanceLongInterval(manchesterDecoderPhaseState) \ (manchesterDecoderPhaseState += 2) /** * Updated/advance the cycle counter by a long interval. * @param numberHalfCyclesPassed the cycle field to update */ #define __cycleCounterAdvanceLongInterval(numberHalfCyclesPassed) \ (numberHalfCyclesPassed += 2) /** * Updated the cycle counter by a short interval. * @param numberHalfCyclesPassed the cycle field to update */ #define __cycleCounterAdvanceShortInterval(numberHalfCyclesPassed) \ (numberHalfCyclesPassed += 1) /** * evaluates to a snapshot's uint16_t timer value */ #ifdef MANCHESTER_DECODING_ENABLE_MERGE_TIMESTAMP_WITH_EDGE_DIRECTION #define __getTimerValue(snapshot) \ (snapshot->timerValue << 1) #else #define __getTimerValue(snapshot) \ (snapshot->timerValue) #endif /** * Stores the data bit to the reception buffer unless the buffer is saturated. * @param rxPort the port where to buffer the bit * @param isRisingEdge the signal edge */ static void __storeDataBit(RxPort *const rxPort, const bool isRisingEdge) { // save bit to buffer if (!isBufferEndPosition(&rxPort->buffer.pointer)) { if (isRisingEdge) { // DEBUG_CHAR_OUT('1'); // LED_STATUS2_TOGGLE; rxPort->buffer.bytes[rxPort->buffer.pointer.byteNumber] setBit rxPort->buffer.pointer.bitMask; rxPort->parityBitCounter++; } else { // DEBUG_CHAR_OUT('0'); // LED_STATUS3_TOGGLE; rxPort->buffer.bytes[rxPort->buffer.pointer.byteNumber] unsetBit rxPort->buffer.pointer.bitMask; } bufferBitPointerIncrement(&rxPort->buffer.pointer); } else { rxPort->isOverflowed = true; blinkReceptionBufferOverflowErrorForever(rxPort); } } //#ifdef SIMULATION_doesnotexist #ifdef SIMULATION #define __ifSimulationPrintSnapshotBufferSize(rxSnapshotBufferPtr) \ __printSnapshotBufferSizeToSimulationRegister(rxSnapshotBufferPtr) /** * for evaluation purpose */ static void __printSnapshotBufferSizeToSimulationRegister(RxSnapshotBuffer *o) { uint16_t size = 0; if (o->endIndex > o->startIndex) { size = o->endIndex - o->startIndex; } else if (o->endIndex < o->startIndex) { size = o->endIndex + (MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS - o->startIndex); } // cut off possible overflows due to race with incomint reception interrupt if (size <= MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS) { DEBUG_INT16_OUT(size); } } #else # define __ifSimulationPrintSnapshotBufferSize(rxSnapshotBufferPtr) #endif /** * Increments the snapshots circular buffer start index. * @param o the snapshot buffer reference */ static void __rxSnapshotBufferIncrementStartIndex(RxSnapshotBuffer *const o) { if (o->startIndex >= (MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS - 1)) { o->startIndex = 0; } else { o->startIndex++; } __ifSimulationPrintSnapshotBufferSize(o); } /** * Increments the snapshots circular buffer end index. * @param o the snapshot buffer reference */ static void __rxSnapshotBufferIncrementEndIndex(RxSnapshotBuffer *const o) { if (o->endIndex >= (MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS - 1)) { o->endIndex = 0; } else { o->endIndex++; } } /** * Releases the next element at the start of the queue. */ #define __rxSnapshotBufferDequeue(rxSnapshotBuffer) \ (__rxSnapshotBufferIncrementStartIndex(rxSnapshotBuffer)) /** * Evaluates to the next element at the start of the queue. */ #define __rxSnapshotBufferPeek(rxSnapshotBuffer) \ (&(rxSnapshotBuffer)->snapshots[(rxSnapshotBuffer)->startIndex]) /** * Evaluates to true if the buffer is empty, to false otherwise. */ #define __rxSnapshotBufferIsEmpty(rxSnapshotBuffer) \ ((rxSnapshotBuffer)->startIndex == (rxSnapshotBuffer)->endIndex) /** * Appends a value and the specified flank to the snapshot buffer. The least significant counter value * bit is discarded and used to store the flank. * @param timerCounterValue the counter value to store * @param isRisingEdge the signal edge * @param snapshotsBuffer a reference to the buffer to store to * */ void captureSnapshot(const uint16_t timerCounterValue, const bool isRisingEdge, const uint16_t nextLocalTimeInterruptCompareValue, RxPort *const rxPort) { RxSnapshotBuffer *const snapshotBuffer = &rxPort->snapshotsBuffer; uint8_t nextEndIdx = 0; if (snapshotBuffer->endIndex < (MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS - 1)) { nextEndIdx = snapshotBuffer->endIndex + 1; } if (nextEndIdx == snapshotBuffer->startIndex) { snapshotBuffer->isOverflowed = true; #ifdef SIMULATION DEBUG_CHAR_OUT('8'); #endif blinkReceptionSnapshotBufferOverflowErrorForever(snapshotBuffer); } volatile Snapshot *snapshot = &(snapshotBuffer->snapshots[snapshotBuffer->endIndex]); __rxSnapshotBufferIncrementEndIndex(snapshotBuffer); // TODO: the real observation between compressed and not compressed has not been measured yet #ifdef MANCHESTER_DECODING_ENABLE_MERGE_TIMESTAMP_WITH_EDGE_DIRECTION // using a more compressed storage of snapshot and edge direction with loosing least significant bit if (isRisingEdge) { (*((volatile uint16_t *) (snapshot))) = (*timerCounterValue & 0xFFFE) | 1; } else { (*((volatile uint16_t *) (snapshot))) = (*timerCounterValue & 0xFFFE); } #else // not compressed, but more accurate snapshot->timerValue = timerCounterValue; snapshot->isRisingEdge = isRisingEdge; #endif /** * The current local time tracking ISR * + timer compare value to * + snapshot timer value * relation is needed on last PDU edge for shifting local time tracking in phase with transmitter. */ /** * The timer compare value: * TODO: On consecutive package, if the decoder/interpreter has not been called and considered * before next package this value will be overwritten, thus invalid! */ rxPort->buffer.nextLocalTimeInterruptOnPduReceived = nextLocalTimeInterruptCompareValue; /** * The snapshot timer value. */ rxPort->buffer.localTimeTrackingTimerCounterValueOnPduReceived = timerCounterValue; __ifSimulationPrintSnapshotBufferSize(snapshotBuffer); } /** * State driven decoding of the specified snapshots buffer. The result is a bit oriented stream. * The order is the same as the snapshot buffer's. On package end/timeout calls the interpreter with * the respective port as argument. * @param port the port to decode from and buffer to * @param interpreterImpl a interpreter implementation reference */ void manchesterDecodeBuffer(DirectionOrientedPort *const port, void (*const interpreterImpl)(DirectionOrientedPort *)) { RxPort *rxPort = port->rxPort; if (rxPort->isDataBuffered == true) { return; } switch (rxPort->snapshotsBuffer.decoderStates.decodingState) { case DECODER_STATE_TYPE_START: if (!__rxSnapshotBufferIsEmpty(&rxPort->snapshotsBuffer)) { volatile Snapshot *snapshot = __rxSnapshotBufferPeek(&rxPort->snapshotsBuffer); if (snapshot->isRisingEdge == false) { bufferBitPointerStart(&rxPort->buffer.pointer); __resetDecoderPhaseState(rxPort->snapshotsBuffer.decoderStates.phaseState); rxPort->snapshotsBuffer.temporarySnapshotTimerValue = __getTimerValue(snapshot); DEBUG_CHAR_OUT('+'); rxPort->parityBitCounter = 0; rxPort->buffer.receptionDuration = 0; rxPort->buffer.firstFallingToRisingDuration = 0; // rxPort->buffer.receptionStartTimestamp = rxPort->snapshotsBuffer.temporarySnapshotTimerValue; rxPort->snapshotsBuffer.decoderStates.decodingState = DECODER_STATE_TYPE_DECODING; __rxSnapshotBufferDequeue(&rxPort->snapshotsBuffer); goto __DECODER_STATE_TYPE_DECODING; } else { __rxSnapshotBufferDequeue(&rxPort->snapshotsBuffer); } } break; // @pre: valid temporary snapshot register __DECODER_STATE_TYPE_DECODING: case DECODER_STATE_TYPE_DECODING: // for all snapshots while (!__rxSnapshotBufferIsEmpty(&rxPort->snapshotsBuffer)) { volatile Snapshot *snapshot = __rxSnapshotBufferPeek(&rxPort->snapshotsBuffer); const uint16_t timerValue = __getTimerValue(snapshot); const uint16_t difference = timerValue - rxPort->snapshotsBuffer.temporarySnapshotTimerValue; // DEBUG_INT16_OUT(difference); if (difference <= ParticleAttributes.communication.timerAdjustment.maxLongIntervalDuration) { // on short interval if (difference <= ParticleAttributes.communication.timerAdjustment.maxShortIntervalDuration) { __phaseStateAdvanceShortInterval(rxPort->snapshotsBuffer.decoderStates.phaseState); __cycleCounterAdvanceShortInterval(rxPort->snapshotsBuffer.numberHalfCyclesPassed); // DEBUG_CHAR_OUT('x'); } // on long interval else { __phaseStateAdvanceLongInterval(rxPort->snapshotsBuffer.decoderStates.phaseState); __cycleCounterAdvanceLongInterval(rxPort->snapshotsBuffer.numberHalfCyclesPassed); // DEBUG_CHAR_OUT('X'); } if (__isDataPhase(rxPort->snapshotsBuffer.decoderStates.phaseState)) { __storeDataBit(rxPort, snapshot->isRisingEdge); } else { } rxPort->snapshotsBuffer.temporarySnapshotTimerValue = timerValue; // store the delay from last bit until PDU end for later synchronization rxPort->buffer.lastFallingToRisingDuration = difference; // store the delay from PDU start until 1st bit for later synchronization if (rxPort->buffer.firstFallingToRisingDuration == 0) { rxPort->buffer.firstFallingToRisingDuration = difference; } rxPort->buffer.receptionDuration += difference; // rxPort->buffer.receptionEndTimestamp = timerValue; __rxSnapshotBufferDequeue(&rxPort->snapshotsBuffer); // on overdue: difference of two snapshots exceed the max. rx clock duration } else { #ifdef SIMULATION rxPort->snapshotsBuffer.decoderStates.decodingState = DECODER_STATE_TYPE_POST_TIMEOUT_PROCESS; #endif goto __DECODER_STATE_TYPE_POST_TIMEOUT_PROCESS; } } // on empty queue check for timeout if (__rxSnapshotBufferIsEmpty(&rxPort->snapshotsBuffer)) { uint8_t sreg = SREG; MEMORY_BARRIER; CLI; MEMORY_BARRIER; const uint16_t now = TIMER_TX_RX_COUNTER_VALUE; MEMORY_BARRIER; SREG = sreg; MEMORY_BARRIER; uint16_t difference = now - rxPort->snapshotsBuffer.temporarySnapshotTimerValue; // DEBUG_INT16_OUT(difference); if (difference >= (ParticleAttributes.communication.timerAdjustment.transmissionClockDelay * 2)) { #ifdef SIMULATION rxPort->snapshotsBuffer.decoderStates.decodingState = DECODER_STATE_TYPE_POST_TIMEOUT_PROCESS; #endif goto __DECODER_STATE_TYPE_POST_TIMEOUT_PROCESS; } } break; __DECODER_STATE_TYPE_POST_TIMEOUT_PROCESS: case DECODER_STATE_TYPE_POST_TIMEOUT_PROCESS: DEBUG_CHAR_OUT('|'); #ifdef SIMULATION uint16_t value = rxPort->buffer.pointer.byteNumber; DEBUG_INT16_OUT(value); value = rxPort->buffer.pointer.bitMask; DEBUG_INT16_OUT(rxPort->buffer.pointer.bitMask); #endif // __approximateNewTxClockSpeed(rxPort); rxPort->isDataBuffered = true; rxPort->snapshotsBuffer.decoderStates.decodingState = DECODER_STATE_TYPE_START; interpreterImpl(port); break; } }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/Transmission.h
<reponame>ProgrammableMatter/particle-firmware<gh_stars>1-10 /** * @author <NAME> 05.2016 * * Transmission related implementation. */ #pragma once #include "common/common.h" #include "uc-core/configuration/interrupts/TxRxTimer.h" #include "simulation/SimulationMacros.h" /** * Schedules the next transmission interrupt. * Write to TIMER_TX_RX_COMPARE_VALUE is not atomic. * Typically called within an ISR. */ void scheduleNextTxInterrupt(void) { TIMER_TX_RX_COMPARE_VALUE += ParticleAttributes.communication.timerAdjustment.transmissionClockDelayHalf; } /** * Schedules the next transmission start interrupt with atomic read/write to TIMER_TX_RX_COUNTER_VALUE. */ static void __scheduleStartTxInterrupt(void) { const uint16_t delay = ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelay * 2; uint8_t sreg = SREG; MEMORY_BARRIER; CLI; MEMORY_BARRIER; TIMER_TX_RX_COMPARE_VALUE = TIMER_TX_RX_COUNTER_VALUE + delay; // ParticleAttributes.communication.timerAdjustment.transmissionClockDelay * 2; MEMORY_BARRIER; SREG = sreg; MEMORY_BARRIER; TIMER_TX_RX_ENABLE_COMPARE_INTERRUPT; } /** * Activates the designated port to contribute to the next transmission until * there is no more data to transmit. * @param port the designated transmission port to read the buffer and transmit from */ void enableTransmission(TxPort *const port) { // uint8_t sreg = SREG; // MEMORY_BARRIER; // CLI; // MEMORY_BARRIER; DEBUG_CHAR_OUT('t'); bool startTransmission = true; // on already ongoing transmission: no need to schedule a transmission start if (ParticleAttributes.directionOrientedPorts.north.txPort->isTransmitting || ParticleAttributes.directionOrientedPorts.east.txPort->isTransmitting || ParticleAttributes.directionOrientedPorts.south.txPort->isTransmitting) { startTransmission = false; } port->isTxClockPhase = true; port->isTransmitting = true; port->isDataBuffered = true; MEMORY_BARRIER; if (startTransmission) { LED_STATUS4_TOGGLE; // update new transmission baud rate if (ParticleAttributes.communication.timerAdjustment.isTransmissionClockDelayUpdateable) { ParticleAttributes.communication.timerAdjustment.transmissionClockDelay = roundf(ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelay); ParticleAttributes.communication.timerAdjustment.transmissionClockDelayHalf = roundf(ParticleAttributes.communication.timerAdjustment.newTransmissionClockDelayHalf); MEMORY_BARRIER; ParticleAttributes.communication.timerAdjustment.isTransmissionClockDelayUpdateable = false; } __scheduleStartTxInterrupt(); } // MEMORY_BARRIER; // SREG = sreg; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/TimerCounter.h
/** * @author <NAME> 20.07.2016 * * General timer counter related configuration. */ #pragma once #if defined(__AVR_ATtiny1634__) || defined(__AVR_ATmega16__) # define __TIMER_COUNTER_PRESCALER_DISCONNECTED_FLAGS \ ((1 << CS02) | (1 << CS01) | (1 << CS00)) # define __TIMER_COUNTER_PRESCALER_1 \ ((0 << CS02) | (0 << CS01) | (1 << CS00)) # define __TIMER_COUNTER_PRESCALER_8 \ ((0 << CS02) | (1 << CS01) | (0 << CS00)) # define __TIMER_COUNTER_PRESCALER_64 \ ((0 << CS02) | (1 << CS01) | (1 << CS00)) # define __TIMER_COUNTER_PRESCALER_256 \ ((1 << CS02) | (0 << CS01) | (0 << CS00)) # define __TIMER_COUNTER_PRESCALER_1024 \ ((1 << CS02) | (0 << CS01) | (1 << CS00)) #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/CommunicationTypesCtors.h
/* * @author <NAME> 09.10.2016 * * Communication types constructor implementation. */ #pragma once #include "CommunicationTypes.h" #include "uc-core/particle/PointerImplementation.h" #include "uc-core/communication/PointerImplementation.h" /** * constructor function * @param o the object to construct */ void constructDirectionOrientedPort(DirectionOrientedPort *const o, DiscoveryPulseCounter *const discoveryPulseCounter, TxPort *const txPort, RxPort *const rxPort, void (*const receivePimpl)(void), void (*const txHighPimpl)(void), void (*const txLowPimpl)(void), CommunicationProtocolPortState *const protocolState) { o->discoveryPulseCounter = discoveryPulseCounter; o->rxPort = rxPort; o->txPort = txPort; o->receivePimpl = receivePimpl; o->txHighPimpl = txHighPimpl; o->txLowPimpl = txLowPimpl; o->protocol = protocolState; } /** * constructor function * @param o the object to construct */ void constructDirectionOrientedPorts(DirectionOrientedPorts *const o) { constructDirectionOrientedPort(&o->north, &ParticleAttributes.discoveryPulseCounters.north, &ParticleAttributes.communication.ports.tx.north, &ParticleAttributes.communication.ports.rx.north, receiveNorth, northTxHiImpl, northTxLoImpl, &ParticleAttributes.protocol.ports.north); constructDirectionOrientedPort(&o->east, &ParticleAttributes.discoveryPulseCounters.east, &ParticleAttributes.communication.ports.tx.east, &ParticleAttributes.communication.ports.rx.east, receiveEast, eastTxHiImpl, eastTxLoImpl, &ParticleAttributes.protocol.ports.east); constructDirectionOrientedPort(&o->south, &ParticleAttributes.discoveryPulseCounters.south, &ParticleAttributes.communication.ports.tx.south, &ParticleAttributes.communication.ports.rx.south, receiveSouth, southTxHiImpl, southTxLoImpl, &ParticleAttributes.protocol.ports.south); constructDirectionOrientedPort(&o->simultaneous, &ParticleAttributes.discoveryPulseCounters.east, &ParticleAttributes.communication.ports.tx.east, &ParticleAttributes.communication.ports.rx.east, receiveEast, simultaneousTxHiImpl, simultaneousTxLoImpl, &ParticleAttributes.protocol.ports.east); }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/NodeAddressTypesCtors.h
<reponame>ProgrammableMatter/particle-firmware /* * @author <NAME> 2016 * * Node address types constructor implementation. */ #pragma once #include "NodeAddressTypes.h" /** * constructor function * @param o the object to construct */ void constructNodeAddress(NodeAddress *const o) { o->row = 0; o->column = 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/interrupts/DiscoveryPCI.h
/** * @author <NAME> 16.09.2016 * * Discovery pin change interrupt configuration. */ #pragma once #include <avr/interrupt.h> #include "common/PortInteraction.h" #ifdef __AVR_ATtiny1634__ // for production MCU # define __DISCOVERY_INTERRUPT_FLAG_NORTH PCIF2 # define __DISCOVERY_INTERRUPT_FLAG_EAST PCIF1 # define __DISCOVERY_INTERRUPT_FLAG_SOUTH PCIF0 # define DISCOVERY_NORTH_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__DISCOVERY_INTERRUPT_FLAG_NORTH)) != 0) ? GIFR = bit(__DISCOVERY_INTERRUPT_FLAG_NORTH):0) # define DISCOVERY_EAST_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__DISCOVERY_INTERRUPT_FLAG_EAST)) != 0) ? GIFR = bit(__DISCOVERY_INTERRUPT_FLAG_EAST):0) # define DISCOVERY_SOUTH_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__DISCOVERY_INTERRUPT_FLAG_SOUTH)) != 0) ? GIFR = bit(__DISCOVERY_INTERRUPT_FLAG_SOUTH):0) # define DISCOVERY_INTERRUPTS_CLEAR_PENDING \ DISCOVERY_NORTH_INTERRUPT_CLEAR_PENDING; \ DISCOVERY_EAST_INTERRUPT_CLEAR_PENDING; \ DISCOVERY_SOUTH_INTERRUPT_CLEAR_PENDING # define DISCOVERY_INT_ENABLE \ (GIMSK setBit (bit(PCIE0) | bit(PCIE1) | bit(PCIE2))) # define DISCOVERY_NORTH_INTERRUPT_DISABLE \ (PCMSK2 unsetBit bit(PCINT17)) # define DISCOVERY_NORTH_INTERRUPT_ENABLE \ (PCMSK2 setBit bit(PCINT17)) # define DISCOVERY_EAST_INTERRUPT_DISABLE \ (PCMSK1 unsetBit bit(PCINT8)) # define DISCOVERY_EAST_INTERRUPT_ENABLE \ (PCMSK1 setBit bit(PCINT8)) # define DISCOVERY_SOUTH_INTERRUPT_DISABLE \ (PCMSK0 unsetBit bit(PCINT4)) # define DISCOVERY_SOUTH_INTERRUPT_ENABLE \ (PCMSK0 setBit bit(PCINT4)) # define DISCOVERY_INTERRUPTS_ENABLE \ DISCOVERY_NORTH_INTERRUPT_ENABLE; \ DISCOVERY_SOUTH_INTERRUPT_ENABLE; \ DISCOVERY_EAST_INTERRUPT_ENABLE # define DISCOVERY_INTERRUPTS_DISABLE \ DISCOVERY_NORTH_INTERRUPT_DISABLE; \ DISCOVERY_SOUTH_INTERRUPT_DISABLE; \ DISCOVERY_EAST_INTERRUPT_DISABLE # define DISCOVERY_INTERRUPTS_SETUP \ DISCOVERY_INTERRUPTS_CLEAR_PENDING; \ DISCOVERY_INT_ENABLE #else # if defined(__AVR_ATmega16__) // for simulator MCU # define __DISCOVERY_INTERRUPT_FLAG_NORTH \ INTF2 # define __DISCOVERY_INTERRUPT_FLAG_EAST \ INTF1 # define __DISCOVERY_INTERRUPT_FLAG_SOUTH \ INTF0 # define DISCOVERY_NORTH_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__DISCOVERY_INTERRUPT_FLAG_NORTH)) != 0) ? GIFR = bit(__DISCOVERY_INTERRUPT_FLAG_NORTH):0) # define DISCOVERY_EAST_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__DISCOVERY_INTERRUPT_FLAG_EAST)) != 0) ? GIFR = bit(__DISCOVERY_INTERRUPT_FLAG_EAST):0) # define DISCOVERY_SOUTH_INTERRUPT_CLEAR_PENDING \ (((GIFR & bit(__DISCOVERY_INTERRUPT_FLAG_SOUTH)) != 0) ? GIFR = bit(__DISCOVERY_INTERRUPT_FLAG_SOUTH):0) # define DISCOVERY_INTERRUPTS_CLEAR_PENDING \ DISCOVERY_NORTH_INTERRUPT_CLEAR_PENDING; \ DISCOVERY_EAST_INTERRUPT_CLEAR_PENDING; \ DISCOVERY_SOUTH_INTERRUPT_CLEAR_PENDING //ISC2 - 0: on falling edge, 1: on rising edge //(ISCx1, ISCx0) - (0,1): on logic change # define __DISCOVERY_INTERRUPTS_SENSE_CONTROL_SETUP \ MCUCR setBit (0 << ISC11) | (1 << ISC10) | (0 << ISC01) | (1 << ISC00); \ MCUCSR setBit (1 << ISC2) # define DISCOVERY_NORTH_INTERRUPT_DISABLE GICR unsetBit bit(INT2); # define DISCOVERY_NORTH_INTERRUPT_ENABLE GICR setBit bit(INT2); # define DISCOVERY_EAST_INTERRUPT_DISABLE GICR unsetBit bit(INT1); # define DISCOVERY_EAST_INTERRUPT_ENABLE GICR setBit bit(INT1); # define DISCOVERY_SOUTH_INTERRUPT_DISABLE GICR unsetBit bit(INT0); # define DISCOVERY_SOUTH_INTERRUPT_ENABLE GICR setBit bit(INT0); # define DISCOVERY_INTERRUPTS_ENABLE GICR setBit ((1 << INT0) | (1 << INT1) | (1 << INT2)) # define DISCOVERY_INTERRUPTS_DISABLE GICR unsetBit ((1 << INT0) | (1 << INT1) | (1 << INT2)) # define DISCOVERY_INTERRUPTS_SETUP \ DISCOVERY_INTERRUPTS_CLEAR_PENDING; \ __DISCOVERY_INTERRUPTS_SENSE_CONTROL_SETUP # else # error # endif #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication-protocol/CommunicationProtocolPackageTypes.h
<filename>src/avr-common/utils/uc-core/communication-protocol/CommunicationProtocolPackageTypes.h /** * @author <NAME> 13.07.2016 * * Definition of all package types that can be transmitted/received. */ #pragma once #include <stdint.h> /** * Convenience macro: evaluate to the number of bytes bit mask */ #define __pointerBytes(numBytes) ((uint16_t) numBytes) /** * Convenience macro: evaluates to the number of bits bit mask */ #define __pointerBits(numBits) (((uint16_t) 0x0100) << numBits) /** * Describes possible header IDs. Note the enum values must not exceed uint8_t max. */ typedef enum PackageHeaderId { PACKAGE_HEADER_ID_HEADER = 1, __PACKAGE_HEADER_ID_TYPE_SYNC_NETWORK_TIME = 2, __PACKAGE_HEADER_ID_TYPE_RELAY_HEADER = 2, __PACKAGE_HEADER_ID_TYPE_RESET = 3, PACKAGE_HEADER_ID_TYPE_ACK = 4, PACKAGE_HEADER_ID_TYPE_ACK_WITH_DATA = 5, PACKAGE_HEADER_ID_TYPE_NETWORK_GEOMETRY_RESPONSE = 6, PACKAGE_HEADER_ID_TYPE_SET_NETWORK_GEOMETRY = 7, PACKAGE_HEADER_ID_TYPE_ENUMERATE = 8, PACKAGE_HEADER_ID_TYPE_SYNC_TIME = 9, PACKAGE_HEADER_ID_TYPE_HEAT_WIRES = 10, PACKAGE_HEADER_ID_TYPE_HEAT_WIRES_MODE = 11, __UNUSED11 = 11, __UNUSED12 = 12, __UNUSED13 = 13, __UNUSED14 = 14, PACKAGE_HEADER_ID_TYPE_EXTENDED_HEADER = 15, __UNUSED00 = 0, } PackageHeaderId; /** * describes a package header */ typedef struct HeaderPackage { uint8_t startBit : 1; uint8_t id : 4; uint8_t isRangeCommand: 1; uint8_t parityBit: 1; uint8_t enableBroadcast : 1; } HeaderPackage; /** * HeaderPackage data length expressed as (uint16_t) BufferPointer */ #define HeaderPackagePointerSize (__pointerBytes(1) | __pointerBits(0)) /** * describes an acknowledge package */ typedef HeaderPackage AckPackage; /** * describes a package that is automatically relayed on the east and south port * TODO: implement handling in communication-protocol/Commands.h */ typedef HeaderPackage RelayHeaderPackage; /** * describes a package for master device to origin node comm.: re-synchronize network time * TODO: implement handling in communication-protocol/Commands.h */ typedef HeaderPackage SyncNetworkTimeHeaderPackage; /** * describes a package that triggers a node reset * TODO: implement handling in communication-protocol/Commands.h */ typedef HeaderPackage ResetPackage; /** * AckPackage data length expressed as (uint16_t) BufferPointer */ #define AckPackagePointerSize HeaderPackagePointerSize /** * describes an acknowledge package with subsequent address */ typedef struct AckWithAddressPackage { HeaderPackage header; uint8_t addressRow : 8; uint8_t addressColumn : 8; } AckWithAddressPackage; /** * PackageHeaderAddress length expressed as (uint16_t) BufferPointer */ #define AckWithAddressPackageBufferPointerSize (__pointerBytes(3) | __pointerBits(0)) /** * describes an announce network geometry package */ typedef struct AnnounceNetworkGeometryPackage { HeaderPackage header; uint8_t rows : 8; uint8_t columns : 8; } AnnounceNetworkGeometryPackage; /** * AnnounceNetworkGeometryPackage length expressed as (uint16_t) BufferPointer */ #define AnnounceNetworkGeometryPackageBufferPointerSize (__pointerBytes(3) | __pointerBits(0)) /** * describes a set network geometry package */ typedef struct SetNetworkGeometryPackage { HeaderPackage header; uint8_t rows : 8; uint8_t columns : 8; } SetNetworkGeometryPackage; /** * SetNetworkGeometryPackage length expressed as (uint16_t) BufferPointer */ #define SetNetworkGeometryPackageBufferPointerSize (__pointerBytes(3) | __pointerBits(0)) /** * describes an enumeration package */ typedef struct EnumerationPackage { HeaderPackage header; uint8_t addressRow : 8; uint8_t addressColumn : 8; /** * Bread crumb is passed until the highest network address is reached. */ uint8_t hasNetworkGeometryDiscoveryBreadCrumb : 1; } EnumerationPackage; /** * PackageHeaderAddress length expressed as (uint16_t) BufferPointer */ #define EnumerationPackageBufferPointerSize (__pointerBytes(3) | __pointerBits(1)) /** * Describes a synchronize time package. * The package size is chosen to take exactly as long as needed to overflow the timer/counter 1 interrupt. * Thus (1+2+2+2+1) * 8 * (512*2) = 65536 cycles * ^ bytes ^bits ^ line coding clock duration in cycles (see configuration/Communication.h) */ typedef struct TimePackage { HeaderPackage header; /** * delay until the next local time tracking ISR triggers when the package is constructed */ uint16_t delayUntilNextTimeTrackingIsr; /** * the current time period when the package is constructed */ uint16_t timePeriod; /** * the current local time tracking ISR delay */ uint16_t localTimeTrackingPeriodInterruptDelay; /** * indicate that the receiver should also update the local time according to timePeriod */ uint8_t forceTimePeriodUpdate : 1; /** * stuffing: can be set arbitrarily, alternating bits recommended since it decreases the coding frequency */ uint8_t stuffing : 6; /** * The time package must end with an UNset end bit. * Otherwise the measured synchronization time interval deduced from the time package * will be wrong and affect the whole time skew/synchronization calculation. */ uint8_t endBit : 1; } TimePackage; /** * PackageHeaderTime length expressed as (uint16_t) BufferPointer */ #define TimePackageBufferPointerSize (__pointerBytes(8) | __pointerBits(0)) /** * describes a heat wires package */ typedef struct HeatWiresPackage { HeaderPackage header; uint8_t addressRow : 8; uint8_t addressColumn: 8; uint16_t startTimeStamp : 16; uint8_t durationLsb : 8; uint8_t durationMsb : 2; uint8_t northLeft : 1; uint8_t northRight: 1; uint8_t __pad: 4; } HeatWiresPackage; /** * HeatWiresPackage length expressed as (uint16_t) BufferPointer */ #define HeatWiresPackageBufferPointerSize (__pointerBytes(6) | __pointerBits(4)) /** * describes a heat wires range package */ typedef struct HeatWiresRangePackage { HeaderPackage header; uint8_t addressRow0 : 8; uint8_t addressColumn0 : 8; uint8_t addressRow1 : 8; uint8_t addressColumn1 : 8; uint16_t startTimeStamp : 16; uint8_t durationLsb : 8; uint8_t durationMsb : 2; uint8_t northLeft : 1; uint8_t northRight: 1; uint8_t __pad: 4; } HeatWiresRangePackage; /** * HeatWiresRangePackage length expressed as (uint16_t) BufferPointer */ #define HeatWiresRangePackageBufferPointerSize (__pointerBytes(8) | __pointerBits(4)) /** * describes a heat wires mode package */ typedef struct HeatWiresModePackage { HeaderPackage header; uint8_t heatMode : 2; uint8_t __pad: 6; } HeatWiresModePackage; /** * HeatWiresModePackage length expressed as (uint16_t) BufferPointer */ #define HeatWiresModePackageBufferPointerSize (__pointerBytes(1) | __pointerBits(2)) /** * Union for a convenient way to access buffered packages. */ typedef union Package { /** * package without payload */ HeaderPackage asHeader; /** * general acknowledge package */ AckPackage asACKPackage; /** * package transmitted when acknowledging the local address */ AckWithAddressPackage asACKWithLocalAddress; /** * package received when neighbour acknowledges his address */ AckWithAddressPackage asACKWithRemoteAddress; /** * package transmitted when enumerating neighbour */ EnumerationPackage asEnumerationPackage; /** * package transmitted when synchronizing time */ TimePackage asSyncTimePackage; /** * package transmitted by the topmost, rightmost node when announcing the network geometry */ AnnounceNetworkGeometryPackage asAnnounceNetworkGeometryPackage; /** * package transmitted by the origin node when setting a new network geometry */ SetNetworkGeometryPackage asSetNetworkGeometryPackage; /** * package transmitted for scheduling one heat north wires action */ HeatWiresPackage asHeatWiresPackage; /** * package transmitted for scheduling one heat north wires action in a range of nodes */ HeatWiresRangePackage asHeatWiresRangePackage; /** * package transmitted to set up the heat wires mode/power */ HeatWiresModePackage asHeatWiresModePackage; } Package;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/Deviation.h
/** * @author <NAME> 23.09.2016 * * Linear Least Squares Regression related implementation. */ #pragma once #include "uc-core/configuration/synchronization/Deviation.h" #include "SynchronizationTypes.h" #include "Synchronization.h" //#include "uc-core/stdout/stdio.h" #ifndef DEVIATION_BINARY_SEARCH_SQRT # include <math.h> #endif #ifdef DEVIATION_BINARY_SEARCH_SQRT #define NAN __builtin_nan("") /** * Binary search for sqrt as proposed in: * http://www.avrfreaks.net/forum/where-sqrt-routine */ static void __binarySearchSqr(const CalculationType *const number, CalculationType *const result) { #define __binary_sqr_search_digits_accuracy 0.1 //#define __binary_sqr_search_digits_accuracy 0.01 if ((*number) >= 0) { CalculationType left = 0; CalculationType right = *number + 1; while ((right - left) > __binary_sqr_search_digits_accuracy) { *result = (left + right) / 2; if ((*result) * (*result) < (*number)) left = *result; else right = *result; }; *result = (left + right) / 2; } else { *result = NAN; } } #endif /** * Calculates the mean excluding outlier using the current µ and current σ. * @pre The arithmetic mean must be valid. * @pre The standard deviation must be valid. */ void calculateMeanWithoutOutlier(void) { TimeSynchronization *const timeSynchronization = &ParticleAttributes.timeSynchronization; timeSynchronization->meanWithoutOutlier = 0; IndexType numberCumulatedValues = 0; samplesFifoBufferIteratorStart(&timeSynchronization->timeIntervalSamples); do { SampleValueType sample = timeSynchronization->timeIntervalSamples.samples[timeSynchronization->timeIntervalSamples.iterator].value; if (sample >= timeSynchronization->adaptiveSampleRejection.outlierLowerBound && sample <= timeSynchronization->adaptiveSampleRejection.outlierUpperBound) { timeSynchronization->meanWithoutOutlier += sample; numberCumulatedValues++; } samplesFifoBufferFiFoBufferIteratorNext(&timeSynchronization->timeIntervalSamples); } while (timeSynchronization->timeIntervalSamples.iterator < TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END); timeSynchronization->meanWithoutOutlier /= (CalculationType) numberCumulatedValues; } /** * Calculates the mean (off-line) of all available samples in the FiFo. * A call to this function involves iterating the whole FiFo. */ void calculateMean(void) { TimeSynchronization *const timeSynchronization = &ParticleAttributes.timeSynchronization; timeSynchronization->mean = 0; IndexType numberCumulatedValues = 0; samplesFifoBufferIteratorStart(&timeSynchronization->timeIntervalSamples); do { SampleValueType sample = timeSynchronization->timeIntervalSamples.samples[timeSynchronization->timeIntervalSamples.iterator].value; timeSynchronization->mean = timeSynchronization->mean + sample; numberCumulatedValues++; samplesFifoBufferFiFoBufferIteratorNext(&timeSynchronization->timeIntervalSamples); } while (timeSynchronization->timeIntervalSamples.iterator < TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END); timeSynchronization->mean = timeSynchronization->mean / numberCumulatedValues; } /** * Calculates the mean (off-line) of all available samples in the FiFo, and the mean excluding * as outlier marked values. * A call to this function involves iterating the whole FiFo. */ void calculateMeanAndMeanWithoutMarkedOutlier(void) { TimeSynchronization *const timeSynchronization = &ParticleAttributes.timeSynchronization; timeSynchronization->mean = 0; timeSynchronization->meanWithoutMarkedOutlier = 0; IndexType numberCumulatedValues = 0; IndexType numberCumulatedValuesWithoutOutlier = 0; samplesFifoBufferIteratorStart(&timeSynchronization->timeIntervalSamples); do { SampleValueType sample = timeSynchronization->timeIntervalSamples.samples[timeSynchronization->timeIntervalSamples.iterator].value; if (timeSynchronization->timeIntervalSamples.samples[timeSynchronization->timeIntervalSamples.iterator].isRejected == false) { timeSynchronization->meanWithoutMarkedOutlier += sample; numberCumulatedValuesWithoutOutlier++; } timeSynchronization->mean = timeSynchronization->mean + sample; numberCumulatedValues++; samplesFifoBufferFiFoBufferIteratorNext(&timeSynchronization->timeIntervalSamples); } while (timeSynchronization->timeIntervalSamples.iterator < TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END); timeSynchronization->mean = timeSynchronization->mean / numberCumulatedValues; timeSynchronization->meanWithoutMarkedOutlier /= (CalculationType) numberCumulatedValuesWithoutOutlier; } /** * Calculates the mean of all available samples in the FiFo exclusive marked as outlier. * A call to this function involves iterating the whole FiFo. */ void calculateMeanWithoutMarkedOutlier(void) { TimeSynchronization *const timeSynchronization = &ParticleAttributes.timeSynchronization; timeSynchronization->meanWithoutMarkedOutlier = 0; IndexType numberCumulatedValuesWithoutOutlier = 0; samplesFifoBufferIteratorStart(&timeSynchronization->timeIntervalSamples); do { FifoElement sample = timeSynchronization->timeIntervalSamples.samples[timeSynchronization->timeIntervalSamples.iterator]; if (sample.isRejected == false) { timeSynchronization->meanWithoutMarkedOutlier += sample.value; numberCumulatedValuesWithoutOutlier++; } samplesFifoBufferFiFoBufferIteratorNext(&timeSynchronization->timeIntervalSamples); } while (timeSynchronization->timeIntervalSamples.iterator < TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END); timeSynchronization->meanWithoutMarkedOutlier /= (CalculationType) numberCumulatedValuesWithoutOutlier; } /** * Calculate the variance and std deviance of the values in the fifo buffer. * @pre The arithmetic mean must be valid. */ void calculateVarianceAndStdDeviance(void) { TimeSynchronization *const timeSynchronization = &ParticleAttributes.timeSynchronization; timeSynchronization->variance = 0; IndexType numberCumulatedValues = 0; samplesFifoBufferIteratorStart(&timeSynchronization->timeIntervalSamples); do { CalculationType difference = timeSynchronization->mean - timeSynchronization->timeIntervalSamples.samples[timeSynchronization->timeIntervalSamples.iterator].value; timeSynchronization->variance += difference * difference; numberCumulatedValues++; samplesFifoBufferFiFoBufferIteratorNext(&timeSynchronization->timeIntervalSamples); } while (timeSynchronization->timeIntervalSamples.iterator < TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END); timeSynchronization->variance = timeSynchronization->variance / (CalculationType) numberCumulatedValues; #ifdef DEVIATION_MATH_SQRT timeSynchronization->stdDeviance = sqrtf(timeSynchronization->variance); #else # if defined(DEVIATION_BINARY_SEARCH_SQRT) __binarySearchSqr(&timeSynchronization->variance, &timeSynchronization->stdDeviance); # else # error sqrt() implementation not specified # endif #endif }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/Particle.h
<filename>src/avr-common/utils/uc-core/configuration/Particle.h<gh_stars>1-10 /** * @author <NAME> 2016 * * Particle related arguments. */ #pragma once /** * Delay separating particle loops while in discovery state. */ #define PARTICLE_DISCOVERY_LOOP_DELAY \ DELAY_US_30 /** * Delay separating the following state switch after discovery has finished. */ #define PARTICLE_DISCOVERY_PULSE_DONE_POST_DELAY \ DELAY_MS_1; \ DELAY_MS_1; \ DELAY_MS_1; \ DELAY_US_500
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/Globals.h
/** * @author <NAME> 2016 * * Declaration of the global particle struct. * Do not declare globals __BEFORE__ the global Particle struct, * since simulated test cases will fail. */ #pragma once #include "uc-core/particle/types/ParticleTypes.h" /** * The global particle state structure containing attributes, buffers and alike. */ Particle ParticleAttributes __attribute__ ((section (".noinit"))); // Further globals can be safely declared here: // FooType YourGlobalVariable
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/Discovery.h
<reponame>ProgrammableMatter/particle-firmware<filename>src/avr-common/utils/uc-core/configuration/Discovery.h /** * @author <NAME> 2016 * * Discovery related arguments. */ #pragma once /** * Cut-off value. Pulses counted above are not stored. * When number of incoming pulses >= RX_DISCOVERY_PULSE_COUNTER_MAX * the affected port is marked as connected. */ #define RX_DISCOVERY_PULSE_COUNTER_MAX 30 /** * Earliest particle loop when local node discovery may be finished. */ #define MIN_NEIGHBOURS_DISCOVERY_LOOPS ((uint8_t)(50)) /** * Latest particle loop after local node discovery is to be aborted. */ #define MAX_NEIGHBOURS_DISCOVERY_LOOPS ((uint8_t)(250)) /** * Latest particle loop when post discovery pulsing to neighbours is to be deactivated. */ #define MAX_NEIGHBOUR_PULSING_LOOPS ((uint8_t)(254)) /** * Neighbour discovery counter 1 compare A value defines the pulse frequency * The lower the value, the higher the frequency. */ #ifdef SIMULATION #define DEFAULT_NEIGHBOUR_SENSING_COUNTER_COMPARE_VALUE ((uint16_t)0x70) #else //#define DEFAULT_NEIGHBOUR_SENSING_COUNTER_COMPARE_VALUE ((uint16_t)0x80) #define DEFAULT_NEIGHBOUR_SENSING_COUNTER_COMPARE_VALUE ((uint16_t)0x90) #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/CommunicationTypes.h
/** * @author <NAME> 2016 * * Communication types related definitions. */ #pragma once #include <stdint.h> #include "ManchesterDecodingTypes.h" #include "uc-core/configuration/Particle.h" #include "uc-core/configuration/communication/Communication.h" /** * Describes a bit within a 4 byte buffer. */ typedef struct BufferBitPointer { uint8_t byteNumber : 4; // the referenced byte index uint8_t __pad: 4; uint8_t bitMask; // the referenced bit in the byte } BufferBitPointer; /** * Provides a linear 4 byte buffer and a bit pointer per communication channel. * The struct is used for transmission. Received bits are stored in the buffer * after being decoded. */ typedef struct PortBuffer { uint8_t bytes[COMMUNICATION_TX_RX_NUMBER_BUFFER_BYTES]; // reception buffer BufferBitPointer pointer; // points to the next free position /** * total package reception duration */ uint32_t receptionDuration; /** * Duration from PDU start until the 1st bit edge. */ uint16_t firstFallingToRisingDuration; /** * Duration from last falling bit edge until PDU end. */ uint16_t lastFallingToRisingDuration; /** * compare value of time tracking ISR when last PDU was received */ volatile uint16_t nextLocalTimeInterruptOnPduReceived; /** * timer/counter value when lsat PDU was received */ volatile uint16_t localTimeTrackingTimerCounterValueOnPduReceived; } PortBuffer; /** * Transmission port structure. */ typedef struct TxPort { volatile PortBuffer buffer; volatile BufferBitPointer dataEndPos; // data in between buffer start and dataEndPos is to be transmitted volatile uint8_t isTransmitting : 1; // true during transmission, else false volatile uint8_t isTxClockPhase : 1; // true if clock phase, else on data phase volatile uint8_t isDataBuffered : 1; // true if the buffer contains data to be transmitted uint8_t __pad : 5; } TxPort; /** * Transmission ports bundle. */ typedef struct TxPorts { TxPort north; TxPort east; TxPort south; } TxPorts; /** * Reception port structure. */ typedef struct RxPort { // each pin interrupt stores snapshots and the flank direction into the buffer RxSnapshotBuffer snapshotsBuffer; PortBuffer buffer; volatile uint8_t isOverflowed : 1; volatile uint8_t isDataBuffered : 1; volatile uint8_t parityBitCounter : 1; // 1-bit counter to track odd number of 1-bits volatile uint8_t __pad : 5; } RxPort; /** * Transmission timing related fields that allows runtime changes. */ typedef struct TransmissionTimerAdjustment { /** * snapshot differences below this threshold are treated as short interval occurrences * maxShortIntervalDuration = (maxShortIntervalDuration / 100) * transmissionClockDelay */ uint16_t maxShortIntervalDuration; /** * snapshot differences below this threshold are treated as long interval occurrences * * maxShortIntervalDuration = (maxShortIntervalDuration / 100) * transmissionClockDelay */ uint16_t maxLongIntervalDuration; /** * The tx/rx clock delay for the manchester coding. * Regarding tx: transmission interrupts are scheduled according this delay * Regarding rx: the short and long interval durations are derived from this delay */ volatile uint16_t transmissionClockDelay; /** * transmissionClockDelayHalf = transmissionClockDelay / 2 */ volatile uint16_t transmissionClockDelayHalf; /** * the newly calculated / approximated transmission clock delay */ volatile float newTransmissionClockDelay; /** * the newly calculated / approximated transmission half clock delay */ volatile float newTransmissionClockDelayHalf; /** * Flag indicating that a new transmission clock delay is available. The value is considered * by the next corresponding ISR. */ volatile uint8_t isTransmissionClockDelayUpdateable : 1; uint8_t __pad : 7; } TransmissionTimerAdjustment; /** * Reception ports bundle. */ typedef struct RxPorts { RxPort north; RxPort east; RxPort south; } RxPorts; /** * Communication ports bundle. */ typedef struct CommunicationPorts { TxPorts tx; RxPorts rx; } CommunicationPorts; /** * Communication structure. */ typedef struct Communication { TransmissionTimerAdjustment timerAdjustment; CommunicationPorts ports; } Communication;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/delay/delay.h
/** * @author <NAME> 2016 * * Delay macros to overcome call of static inline in non static inline functions. * This macros are understood to be approximations but accurate enough for normal usage. */ #pragma once #include <stdint.h> extern inline void __delay_loop_2(uint16_t __count); /** * non static inline delay loop to be used in non static inline functions */ inline void __delay_loop_2(uint16_t __count) { __asm__ volatile ( "1: sbiw %0,1" "\n\t" "brne 1b" : "=w" (__count) : "0" (__count) ); } #define DELAY_US_5 \ __delay_loop_2(10) #define DELAY_US_15 \ __delay_loop_2(30) #define DELAY_US_30 \ __delay_loop_2(60) #define DELAY_US_150 \ __delay_loop_2(300) #define DELAY_US_250 \ __delay_loop_2(500) #define DELAY_US_500 \ __delay_loop_2(1000) #define DELAY_MS_1 \ __delay_loop_2(2000) #define DELAY_MS_10 \ __delay_loop_2(20000) #define DELAY_MS_20 \ __delay_loop_2(40000) #define DELAY_MS_30 \ __delay_loop_2(60000) #define DELAY_MS_196 \ for (int ctr = 0; ctr < 6; ++ctr) { \ __delay_loop_2(UINT16_MAX);\ } #define DELAY_MS_500 \ DELAY_MS_196; \ DELAY_MS_196; \ DELAY_MS_196; \ DELAY_MS_196; \ DELAY_MS_196
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/discovery/Discovery.h
<reponame>ProgrammableMatter/particle-firmware<filename>src/avr-common/utils/uc-core/discovery/Discovery.h /** * @author <NAME> 2015 */ #pragma once #include "uc-core/configuration/Discovery.h" #include "uc-core/configuration/IoPins.h" #include "uc-core/discovery/DiscoveryTypes.h" #include "uc-core/particle/Globals.h" /** * Increments the port discovery counter, but Overflows at RX_DISCOVERY_PULSE_COUNTER_MAX. * @param portCounter reference to the designated port counter */ void dispatchFallingDiscoveryEdge(DiscoveryPulseCounter *const portCounter) { if (portCounter->counter < RX_DISCOVERY_PULSE_COUNTER_MAX) { portCounter->counter++; // // evaluation code // if (portCounter == &ParticleAttributes.discoveryPulseCounters.north) { // LED_STATUS1_TOGGLE; // } else if (portCounter == &ParticleAttributes.discoveryPulseCounters.east) { // LED_STATUS2_TOGGLE; // } else if (portCounter == &ParticleAttributes.discoveryPulseCounters.south) { // LED_STATUS3_TOGGLE; // } else { // LED_STATUS1_TOGGLE; // LED_STATUS2_TOGGLE; // LED_STATUS3_TOGGLE; // } } else { portCounter->isConnected = true; // // evaluation code // if (portCounter == &ParticleAttributes.discoveryPulseCounters.north) { // LED_STATUS1_ON; // } else if (portCounter == &ParticleAttributes.discoveryPulseCounters.east) { // LED_STATUS2_ON; // } else if (portCounter == &ParticleAttributes.discoveryPulseCounters.south) { // LED_STATUS3_ON; // } else { // LED_STATUS1_ON; // LED_STATUS2_ON; // LED_STATUS3_ON; // } } } /** * Updates the node type according to the amount of incoming pulses. * The type {@link NodeType} is stored to the {@link ParticleAttributes.type} field. * @return true if the node is fully connected, false otherwise */ bool updateAndDetermineNodeType(void) { if (ParticleAttributes.discoveryPulseCounters.north.isConnected) { // N if (ParticleAttributes.discoveryPulseCounters.south.isConnected) { // N, S if (ParticleAttributes.discoveryPulseCounters.east.isConnected) { // N, S, E ParticleAttributes.node.type = NODE_TYPE_INTER_HEAD; return true; } else { // N,S,!E ParticleAttributes.node.type = NODE_TYPE_INTER_NODE; } } else { // N, !S if (ParticleAttributes.discoveryPulseCounters.east.isConnected) { // N, !S, E ParticleAttributes.node.type = NODE_TYPE_INTER_HEAD; } else { // N, !S, !E ParticleAttributes.node.type = NODE_TYPE_TAIL; } } } else { // !N if (ParticleAttributes.discoveryPulseCounters.south.isConnected) { // !N, S if (ParticleAttributes.discoveryPulseCounters.east.isConnected) { // !N, S, E ParticleAttributes.node.type = NODE_TYPE_ORIGIN; } else { // !N, S, !E ParticleAttributes.node.type = NODE_TYPE_ORIGIN; } } else { // !N, !S if (ParticleAttributes.discoveryPulseCounters.east.isConnected) { // !N, !S, E ParticleAttributes.node.type = NODE_TYPE_ORIGIN; } else { // !N, !S, !E ParticleAttributes.node.type = NODE_TYPE_ORPHAN; } } } return false; }
ProgrammableMatter/particle-firmware
src/manchester-code-tx-simulation/main/main.c
/** * @author <NAME> 2016 */ #include <avr/io.h> #include <avr/interrupt.h> #include <common/common.h> #include <uc-core/configuration/IoPins.h> #include <uc-core/particle/Globals.h> //#include <uc-core/particle/types/ParticleTypesCtors.h> #include <uc-core/communication/Communication.h> #include <uc-core/delay/delay.h> #include <uc-core/configuration/interrupts/TxRxTimer.h> #include <uc-core/communication/CommunicationTypesCtors.h> #define TIMER_TX_ENABLE_COMPARE_TOP_INTERRUPT \ __TIMER1_INTERRUPT_CLEAR_PENDING_COMPARE_A; \ __TIMER1_COMPARE_A_INTERRUPT_ENABLE #define TIMER_TX_ENABLE_COMPARE_CENTER_INTERRUPT \ __TIMER1_INTERRUPT_CLEAR_PENDING_COMPARE_B; \ __TIMER1_COMPARE_B_INTERRUPT_ENABLE //unsigned char__pad __attribute__((section(".noinit"))); #define TIMER_TX_COUNTER_TOP_VECTOR TIMER1_COMPA_vect // int #7 ISR(TIMER_TX_COUNTER_TOP_VECTOR) { OCR1A += COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY; if (ParticleAttributes.communication.ports.tx.south.buffer.pointer.bitMask & ParticleAttributes.communication.ports.tx.south.buffer.bytes[ParticleAttributes.communication.ports.tx. south.buffer.pointer.byteNumber]) { SOUTH_TX_HI; } else { SOUTH_TX_LO; } } // triggers on bit transmission: // reception at the receiver side of this transmission is inverted #define TIMER_TX_COUNTER_CENTER_VECTOR TIMER1_COMPB_vect // int #8 ISR(TIMER_TX_COUNTER_CENTER_VECTOR) { OCR1B += COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY; if (isDataEndPosition(&ParticleAttributes.communication.ports.tx.south)) { // return signal to default SOUTH_TX_LO; // inverted on receiver side TIMER_TX_RX_COUNTER_DISABLE; ParticleAttributes.node.state = STATE_TYPE_IDLE; } else { // write data bit to output (inverted) if (ParticleAttributes.communication.ports.tx.south.buffer.pointer.bitMask & ParticleAttributes.communication.ports.tx.south.buffer.bytes[ParticleAttributes.communication.ports.tx.south.buffer.pointer.byteNumber]) { SOUTH_TX_LO; } else { SOUTH_TX_HI; } bufferBitPointerIncrement(&ParticleAttributes.communication.ports.tx.south.buffer.pointer); } } inline void initTransmission(void) { // constructParticle(&ParticleAttributes); ParticleAttributes.__structStartMarker = 0xaa; ParticleAttributes.__structEndMarker = 0xaa; ParticleAttributes.node.address.row = 0; ParticleAttributes.node.address.column = 0; constructTxPort(&ParticleAttributes.communication.ports.tx.south); ParticleAttributes.node.state = STATE_TYPE_START; ParticleAttributes.node.type = NODE_TYPE_MASTER; bufferBitPointerStart(&ParticleAttributes.communication.ports.tx.south.buffer.pointer); ParticleAttributes.communication.ports.tx.south.dataEndPos.byteNumber = 8; ParticleAttributes.communication.ports.tx.south.dataEndPos.bitMask = 0x1; // the bytes to transmit ParticleAttributes.communication.ports.tx.south.buffer.bytes[0] = 0b10100110 | 0x1; ParticleAttributes.communication.ports.tx.south.buffer.bytes[1] = 0b10101010; ParticleAttributes.communication.ports.tx.south.buffer.bytes[2] = 0b10101010; ParticleAttributes.communication.ports.tx.south.buffer.bytes[3] = 0b01010101; ParticleAttributes.communication.ports.tx.south.buffer.bytes[4] = 0b10101010; ParticleAttributes.communication.ports.tx.south.buffer.bytes[5] = 0b01111110; ParticleAttributes.communication.ports.tx.south.buffer.bytes[6] = 0b00100110; ParticleAttributes.communication.ports.tx.south.buffer.bytes[7] = 0b01010110; SOUTH_TX_SETUP; // return signal to default (locally low means high at receiver side) SOUTH_TX_LO; TIMER_TX_RX_COUNTER_SETUP; OCR1A = COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY; OCR1B = COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY + (COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY / 2); // start transmission with TIMER_TX_COUNTER_TOP_VECTOR TCNT1 = COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY / 2; TIMER_TX_ENABLE_COMPARE_TOP_INTERRUPT; TIMER_TX_ENABLE_COMPARE_CENTER_INTERRUPT; } EMPTY_INTERRUPT(TIMER1_OVF_vect) extern inline void initTransmission(void); int main(void) { initTransmission(); // wait until receiver is ready DELAY_US_150; ParticleAttributes.node.state = STATE_TYPE_UNDEFINED; SEI; TIMER_TX_RX_COUNTER_ENABLE; while (ParticleAttributes.node.state != STATE_TYPE_IDLE); CLI; ParticleAttributes.node.state = STATE_TYPE_STALE; return 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/communication/Communication.h
<reponame>ProgrammableMatter/particle-firmware<filename>src/avr-common/utils/uc-core/configuration/communication/Communication.h<gh_stars>1-10 /** * @author <NAME> 2016 * * Communication related arguments. */ #pragma once /** * Clock speed vs. minimum error ratio table, deprecated transmitter isr handling: * * clock delay | short interval | long interval * | opt speed | opt speed * | opt size | opt size * -------------------------------------------------------------------- * 180 66 86 121 150 * 256 63 75 115 121 * 512 56 63 107 108 * 1024 53 57 104 104 * 2048 52 54 102 102 */ /** * Clock speed vs. minimum error ratio table (transmitter handles isr synchronous) * * clock delay | short interval | long interval | is setting * | opt speed | opt speed | usable * | opt size | opt size | * --------------------------------------------------------------------------------- * 180 NA NA NA NA false * 256 xxx 68 xxx 105 false * 512 xxx 59 xxx 102 false * 1024 xxx 55 xxx 101 true * --- 1170 is the max clock length due to counter adjustment impl. limitation --- * 2048 xxx 53 xxx 101 true * */ /** * Initial value for clock delay for Manchester (de-)coding (reception and transmission). */ #define COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY ((uint16_t) 1024) //#define DEFAULT_TX_RX_CLOCK_DELAY ((uint16_t) 2048) /** * Maximum short reception time lag. */ //#define COMMUNICATION_DEFAULT_MAX_SHORT_RECEPTION_OVERTIME_PERCENTAGE_RATIO ((uint8_t) 0.59) #define COMMUNICATION_DEFAULT_MAX_SHORT_RECEPTION_OVERTIME_PERCENTAGE_RATIO ((float) 0.75) /** * Maximum long reception time lag. If maximum long snapshot lag is exceeded the reception * experiences a timeout. */ //#define COMMUNICATION_DEFAULT_MAX_LONG_RECEPTION_OVERTIME_PERCENTAGE_RATIO ((uint8_t) 1.12) #define COMMUNICATION_DEFAULT_MAX_LONG_RECEPTION_OVERTIME_PERCENTAGE_RATIO ((float) 1.25) /** * Number of buffer bytes for reception and transmission. Received snapshots are decoded to * the reception buffer. Data to be sent is read from the transmission buffer. */ #define COMMUNICATION_TX_RX_NUMBER_BUFFER_BYTES 9
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/stdout/Stdout.h
<reponame>ProgrammableMatter/particle-firmware /** * @author <NAME> 07.10.2016 */ #pragma once #ifdef NDEBUG # define setupUart(...) #else # if defined(__AVR_ATtiny1634__) # include <avr/io.h> # include <stdio.h> # include "common/PortInteraction.h" # include "uc-core/configuration/Stdout.h" # define __STDOUT_BAUD_PRESCALE (((F_CPU / (STDOUT_UART_BAUD_RATE * 16UL))) - 1) uint8_t uartPutchar(char byte) { // if (byte == '\n') { // uartPutchar('\r'); // } while ((UCSR1A getBit bit(UDRE1)) == 0); UDR1 = byte; return 0; } FILE __UART_STD_OUT = FDEV_SETUP_STREAM(uartPutchar, NULL, _FDEV_SETUP_WRITE); void setupUart(void) { // set baud rate UBRR1H = (uint8_t) (__STDOUT_BAUD_PRESCALE >> 8); UBRR1L = (uint8_t) __STDOUT_BAUD_PRESCALE; // no 2x speed, no multiprocessor UCSR1A = 0; // enable receiver, disable interrupts UCSR1B = 0; UCSR1B setBit ( // bit(RXCIE1) // bit(TXCIE1) // | bit(UDRIE1) // | bit(RXEN1) bit(TXEN1) // | bit(UCSZ12) // | bit(RXB81) // | bit(TXB81) ); // frame format 8data, 1stop bit UCSR1C = 0; UCSR1C setBit ( // bit(UMSEL11) // | bit (UMSEL10) // | bit(UPM11) // | bit(UPM10) // | bit(USBS1) bit(UCSZ11) | bit(UCSZ10) // | bit(UCPOL1) ); stdout = &__UART_STD_OUT; } # else # define setupUart(...) # endif #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/BasicCalculationTypes.h
/** * @author <NAME> 02.10.2016 * * Calculation related types. */ #pragma once #include <stdint.h> #ifdef C_STRUCTS_TO_JSON_PARSER_TYPEDEF_NOT_SUPPORTED_SUPPRESS_REGULAR_TYPEDEFS # define CumulationType uint32_t # define SampleValueType uint16_t # define CalculationType float # define IndexType uint8_t #else typedef uint32_t CumulationType; typedef uint16_t SampleValueType; typedef float CalculationType; typedef uint8_t IndexType; #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/stdout/stdio.h
<reponame>ProgrammableMatter/particle-firmware<filename>src/avr-common/utils/uc-core/stdout/stdio.h /** * @author <NAME> 08.10.2016 */ #pragma once #ifdef __AVR_ATtiny1634__ #include <stdio.h> #else #define printf(...) #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/time/TimeTypes.h
<gh_stars>1-10 /** * @author <NAME> 12.07.2016 */ #pragma once #include <stdint.h> #include "uc-core/configuration/Time.h" /** * Structure to Keep track of number of intervals passed since time tracking was activated. * A time interval can be adjusted at runtime. */ typedef struct LocalTimeTracking { /** * The current local time. */ volatile uint16_t numTimePeriodsPassed; /** * The new local time to be considered in the next local time tracking ISR. */ volatile uint16_t newNumTimePeriodsPassed; /** * The current delay for local time tracking. The value is updated by the corresponding ISR only. * TODO: volatile declaration for this field may be unnecessary, since it is only by the ISR. */ volatile uint16_t timePeriodInterruptDelay; /** * The new value for local time tracking period interrupt delay. */ volatile uint16_t newTimePeriodInterruptDelay; /** The local time tracking timer/counter compare value shift. It is considered once after *flag isNewTimerCounterShiftUpdateable is set. The flag is cleared by the ISR. */ volatile int16_t newTimerCounterShift; /** * Flag indicating new time tracking period interrupt delay is available. * If true a new value is available which the ISR has to consider * and no new value is calculated until the ISR clears the flag. * If false a new value can be calculated. */ volatile uint8_t isTimePeriodInterruptDelayUpdateable : 1; /** * Flag indicating new time period value is available. */ volatile uint8_t isNumTimePeriodsPassedUpdateable : 1; /** * Flag indicating the newTimerCounterShift contains a value to be considered by the ISR. * Flag is cleared by the corresponding ISR. */ volatile uint8_t isNewTimerCounterShiftUpdateable : 1; uint8_t __pad : 5; } LocalTimeTracking;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/Commands.h
<gh_stars>1-10 /** * @author <NAME> 13.07.2016 * * Particle's higher level network commands ought to be used as network API. */ #pragma once #include "Globals.h" #include "uc-core/communication-protocol/Commands.h" /** * Transmits a new network geometry to the network. Particles outside the new boundary * switch to sleep mode. * * @pre the ParticleAttributes.protocol.networkGeometry.rows/cols are set accordingly */ void setNewNetworkGeometry(void) { TxPort temporaryPackagePort; constructSetNetworkGeometryPackage(&temporaryPackagePort, ParticleAttributes.protocol.networkGeometry.rows, ParticleAttributes.protocol.networkGeometry.columns); // interpret the constructed package executeSetNetworkGeometryPackage((SetNetworkGeometryPackage *) temporaryPackagePort.buffer.bytes); } ///** // * Schedules an actuation command starting and ending at the specified time stamps. // */ //FUNC_ATTRS void scheduleActuationCommand(uint16_t startPeriodTimeStamp, uint16_t endPeriodTimeStamp) { // ParticleAttributes.actuationCommand.actuationStart.periodTimeStamp = startPeriodTimeStamp; // ParticleAttributes.actuationCommand.actuationEnd.periodTimeStamp = endPeriodTimeStamp; // ParticleAttributes.actuationCommand.isScheduled = true; //} /** * State driven neighbour enumeration handler. * @param port the port at which to handle enumeration * @param remoteAddressRow the neighbour's address row to assign * @param remoteAddressColumn the neighbour's address column to assign * @param endState state when transaction has finished */ void handleEnumerateNeighbour(DirectionOrientedPort *const port, const uint8_t remoteAddressRow, const uint8_t remoteAddressColumn, const StateType endState) { // TODO: move function to ParticleCore.h CommunicationProtocolPortState *commPortState = port->protocol; if (commPortState->stateTimeoutCounter == 0 && commPortState->initiatorState != COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT && commPortState->initiatorState != COMMUNICATION_INITIATOR_STATE_TYPE_IDLE) { // on timeout: fall back to start state DEBUG_CHAR_OUT('T'); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT; commPortState->stateTimeoutCounter = COMMUNICATION_PROTOCOL_TIMEOUT_COUNTER_MAX; if (commPortState->reTransmissions > 0) { commPortState->reTransmissions--; } DEBUG_CHAR_OUT('b'); } if (commPortState->reTransmissions == 0) { // on retransmissions consumed: sort cut the state machine to end state commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; } TxPort *txPort = port->txPort; switch (commPortState->initiatorState) { // transmit new address case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT: if (port->discoveryPulseCounter->isConnected) { clearTransmissionPortBuffer(txPort); constructEnumeratePackage(txPort, remoteAddressRow, remoteAddressColumn); enableTransmission(txPort); DEBUG_CHAR_OUT('F'); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED; } else { ParticleAttributes.node.state = endState; } break; // wait for tx finished case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED: if (txPort->isTransmitting) { break; } DEBUG_CHAR_OUT('R'); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE; break; // wait fo ack with address case COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE: port->receivePimpl(); break; // send ack back case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK: clearTransmissionPortBuffer(txPort); constructEnumerationACKPackage(txPort); enableTransmission(txPort); DEBUG_CHAR_OUT('f'); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED; break; // switch state case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED: if (txPort->isTransmitting) { break; } DEBUG_CHAR_OUT('D'); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; goto __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; break; __COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: case COMMUNICATION_INITIATOR_STATE_TYPE_IDLE: ParticleAttributes.node.state = endState; break; } } /** * Sends a heat wires mode package to neighbours. * The package is propagated through the entire network. * @param heatingPowerLevel the new power level to set up */ void sendHeatWiresModePackage(HeatingLevelType heatingPowerLevel) { TxPort temporaryPackagePort; constructHeatWiresModePackage(&temporaryPackagePort, heatingPowerLevel); // interpret the constructed package executeHeatWiresModePackage((HeatWiresModePackage *) temporaryPackagePort.buffer.bytes); } /** * Constructs a heat wires command and puts the particle into sending mode. * Destination addresses must be route-able from this node on. That means * i) the destination must be in same column but row is greater than current node's row or * ii) the destination resides in a different column but the current row equals 1. * Otherwise the request is skipped. * For more details about duration see {@link constructHeatWiresRangePackage()} constructor. * @param nodeAddress the node address * @param wires affected actuator flags * @param timeStamp the time stamp when the actuation should start * @param duration 10bit actuation duration {@link #HeatWiresPackage} */ void sendHeatWires(const NodeAddress *const nodeAddress, const Actuators *const wires, const uint16_t timeStamp, uint16_t duration) { if (ParticleAttributes.node.address.row > nodeAddress->row && ParticleAttributes.node.address.column > nodeAddress->column) { // illegal address return; } TxPort temporaryPackagePort; constructHeatWiresPackage(&temporaryPackagePort, nodeAddress, wires, timeStamp, duration); // interpret the constructed package executeHeatWiresPackage((HeatWiresPackage *) temporaryPackagePort.buffer.bytes); } /** * Constructs a heat wires range command and puts the particle into sending mode. The * rectangular range span is defined by the first address (left top) and second address (bottom right). * It must span at least two nodes. The top left address must be route-able from this node on. That means * i) the top left address must be in same column but row is greater than current node's row or * ii) the top left address resides in a different column but the current row equals 1. * Otherwise the request is skipped. * For more details about duration see {@link constructHeatWiresRangePackage()} constructor. * @param nodeAddressTopLeft top left node address * @param nodeAddressBottomRight bottom right node address * @param wires affected actuator flags * @param timeStamp the time stamp when the actuation should start * @param duration 10bit actuation duration {@link #HeatWiresPackage} */ void sendHeatWiresRange(const NodeAddress *const nodeAddressTopLeft, const NodeAddress *const nodeAddressBottomRight, const Actuators *const wires, const uint16_t timeStamp, const uint16_t duration) { if (nodeAddressBottomRight->row < nodeAddressTopLeft->row || nodeAddressBottomRight->column < nodeAddressTopLeft->column) { // illegal range defined return; } if (((nodeAddressBottomRight->row - nodeAddressTopLeft->row) + (nodeAddressBottomRight->column - nodeAddressTopLeft->column)) < 1) { // illegal range defined return; } if (ParticleAttributes.node.address.row != 1 && (nodeAddressTopLeft->column != ParticleAttributes.node.address.column || nodeAddressBottomRight->column != ParticleAttributes.node.address.column)) { // not route-able top left address return; } if (nodeAddressTopLeft->row < ParticleAttributes.node.address.row || nodeAddressTopLeft->column < ParticleAttributes.node.address.column) { // not route-able top left address return; } // @ pre: range spans at least 2 nodes // @ pre: top left is route-able from this node TxPort temporaryPackagePort; constructHeatWiresRangePackage(&temporaryPackagePort, nodeAddressTopLeft, nodeAddressBottomRight, wires, timeStamp, duration); // interpret the constructed package executeHeatWiresRangePackage( (HeatWiresRangePackage *) temporaryPackagePort.buffer.bytes); } /** * Sends a header package to adjacent neighbours. * @param package the package to send */ void sendHeaderPackage(HeaderPackage *const package) { package->startBit = 1; // interpret the package executeHeaderPackage(package); } void sendSyncPackage(void) { ParticleAttributes.node.state = STATE_TYPE_RESYNC_NEIGHBOUR; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/simulation/SimulationMacros.h
/** * @author <NAME> 2016 */ #ifndef __SIMULATION_MACROS_H__ #define __SIMULATION_MACROS_H__ # ifdef SIMULATION # include <avr/io.h> # define IF_DEBUG_SWITCH_TO_ERRONEOUS_STATE \ CLI; \ ParticleAttributes.node.state = STATE_TYPE_ERRONEOUS # define DEBUG_CHAR_OUT(value) UDR=(value) # define DEBUG_INT16_OUT(value) \ EEARL=((value) & 0xff00) >> 8; \ EEDR=((value) & 0x00ff) /** * Write a string to UDR register that is monitored in simulation. */ inline void writeToUart(const char *string) { if (string != 0) { # ifdef UDR while (*string != 0) { UDR = *string; string++; } UDR = '\n'; # else while (*string != 0) { UDR0 = *string; string++; } UDR0 = '\n'; # endif } } extern inline void writeToUart(const char *); # else # define IF_DEBUG_SWITCH_TO_ERRONEOUS_STATE # define DEBUG_CHAR_OUT(value) # define DEBUG_INT16_OUT(value) #define UNUSED(x) (void)(x) inline void writeToUart(const char *string) { UNUSED(string); } #undef UNUSED extern inline void writeToUart(const char *string); # endif #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/LeastSquareRegressionTypesCtors.h
<gh_stars>1-10 /** * @author <NAME> 23.09.2016 * * Linear Least Squares Regression related types. */ #pragma once #include "LeastSquareRegressionTypes.h" /** * constructor function * @param o reference to the object to construct */ void constructLeastSquareRegressionResult(LeastSquareRegressionResult *const o) { o->k = 0; o->d = 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/ParticleStateTypes.h
/* * @author <NAME> 11.10.2016 * * Particle state definition. */ #pragma once /** * Possible particle's state machine states are listed in this enum. */ typedef enum StateType { // uninitialized state STATE_TYPE_UNDEFINED = 0, // state when particle is initializing STATE_TYPE_START, // state when particle is fully initialized STATE_TYPE_ACTIVE, // state when evaluating discovery pulses STATE_TYPE_NEIGHBOURS_DISCOVERY, // state wen discovery ended STATE_TYPE_NEIGHBOURS_DISCOVERED, // state of discovery pulsing period post discovery STATE_TYPE_DISCOVERY_PULSING, // state when discovery pulsing ended STATE_TYPE_DISCOVERY_PULSING_DONE, // state when discovery is performed but node has no neighbors STATE_TYPE_DISCOVERY_DONE_ORPHAN_NODE, // state after reset STATE_TYPE_RESET, // state when waiting for /receiving local address from parent neighbor STATE_TYPE_WAIT_FOR_BEING_ENUMERATED, // state when local address is assigned successfully STATE_TYPE_LOCALLY_ENUMERATED, // state when starting neighbour enumeration STATE_TYPE_ENUMERATING_NEIGHBOURS, // state wen assigning network address to east neighbour STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR, // state when east enumeration finished STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR_DONE, // state when assigning network address to south neighbour STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR, // state when south enumeration finished STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR_DONE, // state when neighbour enumeration finished STATE_TYPE_ENUMERATING_NEIGHBOURS_DONE, // state when last particle sends local address to the origin STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY, // state when relaying the network address announcement to origin STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_RELAY, // state when relaying is finished STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_RELAY_DONE, // state when announcing network geometry is finished STATE_TYPE_ANNOUNCE_NETWORK_GEOMETRY_DONE, // state set by interrupt handler indicating new synchronization to be scheduled STATE_TYPE_RESYNC_NEIGHBOUR, // state when origin node sends local time to neighbours STATE_TYPE_SYNC_NEIGHBOUR, // state when origin sending local time to neighbours has finished STATE_TYPE_SYNC_NEIGHBOUR_DONE, // // working state when origin broadcasts a new network geometry // STATE_TYPE_SEND_SET_NETWORK_GEOMETRY, // working state when actuation command is executed STATE_TYPE_EXECUTE_ACTUATION_COMMAND, // working state when transmitting package to north STATE_TYPE_SENDING_PACKAGE_TO_NORTH, // working state when transmitting package to east STATE_TYPE_SENDING_PACKAGE_TO_EAST, // working state while transmitting package to east and south simultaneously STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH, // working state while transmitting package to south STATE_TYPE_SENDING_PACKAGE_TO_SOUTH, // working state when transmitting package to north followed by preparing for sleep mode STATE_TYPE_SENDING_PACKAGE_TO_NORTH_THEN_PREPARE_SLEEP, // working state when transmitting package to east followed by preparing for sleep mode STATE_TYPE_SENDING_PACKAGE_TO_EAST_THEN_PREPARE_SLEEP, // working state while transmitting package to east and south simultaneously followed by preparing for sleep mode STATE_TYPE_SENDING_PACKAGE_TO_EAST_AND_SOUTH_THEN_PREPARE_SLEEP, // working state while transmitting package to south followed by preparing for sleep mode STATE_TYPE_SENDING_PACKAGE_TO_SOUTH_THEN_PREPARE_SLEEP, // working state when waiting for commands or executing scheduled tasks STATE_TYPE_IDLE, // erroneous machine state STATE_TYPE_ERRONEOUS, // dead lock state; usually before shutdown STATE_TYPE_STALE, // working state when waiting for all transmissions to be finished followed by sleep mode STATE_TYPE_PREPARE_FOR_SLEEP, // state when before MCU goes int sleep mode STATE_TYPE_SLEEP_MODE, } StateType; /** * The node type describes node type according to the connectivity detected when discovery process * finished. */ typedef enum NodeType { // invalid or uninitialized note NODE_TYPE_INVALID = 0, // not connected node NODE_TYPE_ORPHAN, // node connected at south or south and east NODE_TYPE_ORIGIN, // node connected at north and south and east NODE_TYPE_INTER_HEAD, // node connected at north and south NODE_TYPE_INTER_NODE, // node connected at north NODE_TYPE_TAIL, // for testing purposes when the node is attached to the NODE_TYPE_ORIGIN node NODE_TYPE_MASTER } NodeType;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/synchronization/Deviation.h
<gh_stars>1-10 /** * @author <NAME> 23.09.2016 * * Deviation related configuration. */ #pragma once /** * use * double sqrt(double val) of math.h or binary search * sqrt(float *val, float *result) */ #define DEVIATION_MATH_SQRT //#define DEVIATION_BINARY_SEARCH_SQRT
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/communication/ManchesterDecoding.h
<gh_stars>1-10 /** * @author <NAME> 3.10.2016 * * Communication related arguments. */ #pragma once /** * If defined enables merging the high bits [15:1] of the time stamp with * the edge direction bit to one uint8_t which uses 1/3 less memory for * decoding buffer but looses the least significant bit for timestamp accuracy. */ //#define MANCHESTER_DECODING_ENABLE_MERGE_TIMESTAMP_WITH_EDGE_DIRECTION /** * Size of reception snapshot buffer per port. */ // 88% snapshots buffer of 9 byte PDU max. events //#define MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS 127 // 44% snapshots buffer of max. 9 byte PDU max. events //#define MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS 64 // 22% snapshots buffer of 9 byte PDU max. events //#define MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS 32 // 20% snapshots buffer of 9 byte PDU max. events #define MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS 29
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/synchronization/SamplesFifo.h
/** * @author <NAME> 26.09.2016 * * Synchronization FiFo related implementation. */ #pragma once #include "uc-core/configuration/synchronization/SampleFifoTypes.h" #include "SynchronizationTypes.h" #include <math.h> #include "uc-core/stdout/stdio.h" bool isFiFoFull(const SamplesFifoBuffer *const samplesFifoBuffer) { return samplesFifoBuffer->numSamples >= SAMPLE_FIFO_NUM_BUFFER_ELEMENTS; } /** * circular-increment an index with respect to the fifo buffer boundaries */ static void __samplesFifoBufferIncrementIndex(IndexType *const index) { if (*index < (SAMPLE_FIFO_NUM_BUFFER_ELEMENTS - 1)) { (*index)++; } else { *index = 0; } } /** * Increments the iterator until the iterator reaches the start position. * If the position equals TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END * the buffer's end as been reached. The end is the first element before start. The iterator * is not aware of the number of elements stored. */ void samplesFifoBufferFiFoBufferIteratorNext(SamplesFifoBuffer *const samplesBuffer) { __samplesFifoBufferIncrementIndex(&samplesBuffer->iterator); if (samplesBuffer->iterator == samplesBuffer->__startIdx) { samplesBuffer->iterator = TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END; } } /** * Sets the iterator to start position. */ void samplesFifoBufferIteratorStart(SamplesFifoBuffer *const samplesBuffer) { samplesBuffer->iterator = samplesBuffer->__startIdx; } #if !defined(SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN) && !defined(SYNCHRONIZATION_STRATEGY_RAW_OBSERVATION) /** * Increments the end index for the next value to be inserted (First-in). * Also updates the start index for next value to be removed (First-out). */ static void __samplesFifoBufferIncrementInsertIndex(SamplesFifoBuffer *const samplesBuffer) { if (samplesBuffer->numSamples <= 0) { samplesBuffer->__insertIndex++; } else { __samplesFifoBufferIncrementIndex(&samplesBuffer->__insertIndex); if (samplesBuffer->__insertIndex == samplesBuffer->__startIdx) { if (samplesBuffer->__isPreDropOutValid == true) { samplesBuffer->dropOut.value = samplesBuffer->samples[samplesBuffer->__startIdx].value; samplesBuffer->dropOut.isRejected = samplesBuffer->samples[samplesBuffer->__startIdx].isRejected; samplesBuffer->isDropOutValid = true; } else { samplesBuffer->__isPreDropOutValid = true; } __samplesFifoBufferIncrementIndex(&samplesBuffer->__startIdx); } } } #endif #if defined(SYNCHRONIZATION_STRATEGY_MEAN_ENABLE_ONLINE_CALCULATION) \ && (defined(SYNCHRONIZATION_STRATEGY_MEAN) || defined(SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_OUTLIER)) /** * Updates the mean of all available samples using only observations of incoming and outgoing FiFo values. * One call to this function does not iterate the whole FiFo. * An updated is performed if the TIME_SYNCHRONIZATION_MINIMUM_SAMPLES limit is exceeded. */ static void __calculateMeanUsingFifoInOutObservations(TimeSynchronization *const timeSynchronization, const FifoElement *const fifoIn, const FifoElement *const fifoOut) { // consider mean with rejected outlier if (fifoIn->isRejected == false) { timeSynchronization->__unnormalizedCumulativeMeanWithoutMarkedOutlier += (CumulationType) fifoIn->value; // // TODO: evaluation code // if (timeSynchronization->__numberCumulatedValuesWithoutMarkedOutlier >= UINT16_MAX) { // blinkParityErrorForever(&ParticleAttributes.alerts, 1); // } timeSynchronization->__numberCumulatedValuesWithoutMarkedOutlier++; } // consider mean with rejected outlier if (fifoOut->isRejected == false) { timeSynchronization->__unnormalizedCumulativeMeanWithoutMarkedOutlier -= (CumulationType) fifoOut->value; // // TODO: evaluation code // if (timeSynchronization->__numberCumulatedValuesWithoutMarkedOutlier == 0) { // blinkParityErrorForever(&ParticleAttributes.alerts, 0); // } timeSynchronization->__numberCumulatedValuesWithoutMarkedOutlier--; } // consider mean timeSynchronization->__unnormalizedCumulativeMean += (CumulationType) fifoIn->value; timeSynchronization->__unnormalizedCumulativeMean -= (CumulationType) fifoOut->value; // // // TODO: evaluation code // if (timeSynchronization->__unnormalizedCumulativeMean >= (UINT32_MAX / 2)) { // blinkParityErrorForever(&ParticleAttributes.alerts, 0); // } // mean timeSynchronization->mean = (CalculationType) timeSynchronization->__unnormalizedCumulativeMean / (CalculationType) SAMPLE_FIFO_NUM_BUFFER_ELEMENTS; // mean without outlier timeSynchronization->meanWithoutMarkedOutlier = (CalculationType) timeSynchronization->__unnormalizedCumulativeMeanWithoutMarkedOutlier / (CalculationType) timeSynchronization->__numberCumulatedValuesWithoutMarkedOutlier; } /** * Updates the mean of all available samples using only observations of incoming and outgoing FiFo values. * One call to this function does not iterate the whole FiFo. * An updated is performed if the TIME_SYNCHRONIZATION_MINIMUM_SAMPLES limit is exceeded. */ static void __calculateMeanUsingFifoInObservations(TimeSynchronization *const timeSynchronization, const FifoElement *const fifoIn) { // consider mean without outlier if (fifoIn->isRejected == false) { timeSynchronization->__unnormalizedCumulativeMeanWithoutMarkedOutlier += fifoIn->value; timeSynchronization->__numberCumulatedValuesWithoutMarkedOutlier++; } // consider mean timeSynchronization->__unnormalizedCumulativeMean += (CumulationType) fifoIn->value; // mean timeSynchronization->mean = (CalculationType) timeSynchronization->__unnormalizedCumulativeMean / (CalculationType) timeSynchronization->timeIntervalSamples.numSamples; // mean without outlier timeSynchronization->meanWithoutMarkedOutlier = (CalculationType) timeSynchronization->__unnormalizedCumulativeMeanWithoutMarkedOutlier / (CalculationType) timeSynchronization->__numberCumulatedValuesWithoutMarkedOutlier; } #endif #ifdef SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN /** * Calculates a quick and simple approximated mean value. * This method is not very stable against outlier. */ static void __calculateProgressiveMean(const SampleValueType *const sample, TimeSynchronization *const timeSynchronization) { const CalculationType newProgressiveMean = (CalculationType) *sample * SYNCHRONIZATION_STRATEGY_MEAN_NEW_VALUE_WEIGHT + (CalculationType) timeSynchronization->progressiveMean * SYNCHRONIZATION_STRATEGY_MEAN_OLD_VALUE_WEIGHT; // printf("fifo old %u new %u\n", (uint16_t) timeSynchronization->progressiveMean, *sample); timeSynchronization->progressiveMean = newProgressiveMean; // printf("fifo -> %u \n", (uint16_t) timeSynchronization->progressiveMean); // workaround timeSynchronization->timeIntervalSamples.numSamples = SAMPLE_FIFO_NUM_BUFFER_ELEMENTS; } #endif #if defined(SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_OUTLIER) /** * Update the outlier limits. */ void updateOutlierRejectionLimitDependingOnSigma(void) { TimeSynchronization *const timeSynchronization = &ParticleAttributes.timeSynchronization; CalculationType rejectionLimit = SYNCHRONIZATION_OUTLIER_REJECTION_SIGMA_FACTOR * timeSynchronization->stdDeviance; timeSynchronization->adaptiveSampleRejection.outlierLowerBound = roundf(timeSynchronization->mean - rejectionLimit); timeSynchronization->adaptiveSampleRejection.outlierUpperBound = roundf(timeSynchronization->mean + rejectionLimit); timeSynchronization->adaptiveSampleRejection.isOutlierRejectionBoundValid = true; } #endif #ifdef SYNCHRONIZATION_ENABLE_ADAPTIVE_MARKED_OUTLIER_REJECTION static void __reduceRejectionCounters(void) { AdaptiveSampleRejection *const adaptiveSampleRejection = &ParticleAttributes.timeSynchronization.adaptiveSampleRejection; if ((adaptiveSampleRejection->rejected >= SAMPLE_FIFO_ADAPTIVE_REJECTION_REDUCE_COUNTERS_LIMIT) || (adaptiveSampleRejection->accepted >= SAMPLE_FIFO_ADAPTIVE_REJECTION_REDUCE_COUNTERS_LIMIT)) { adaptiveSampleRejection->rejected /= 2; adaptiveSampleRejection->accepted /= 2; } if (adaptiveSampleRejection->accepted <= 0 || adaptiveSampleRejection->rejected <= 0) { adaptiveSampleRejection->accepted++; adaptiveSampleRejection->rejected++; } } static void __updateCurrentRejectionBoundariesDependingOnCounters(void) { AdaptiveSampleRejection *const adaptiveSampleRejection = &ParticleAttributes.timeSynchronization->adaptiveSampleRejection; // update rejection interval if (adaptiveSampleRejection->accepted > (SAMPLE_FIFO_ADAPTIVE_REJECTION_ACCEPTANCE_RATIO * adaptiveSampleRejection->rejected + SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_INTERVAL_THRESHOLD)) { // on accepted above limit, decrease rejection interval adaptiveSampleRejection->currentAcceptedDeviation -= SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_STEP; if (adaptiveSampleRejection->currentAcceptedDeviation <= SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_MIN_INTERVAL) { adaptiveSampleRejection->currentAcceptedDeviation = SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_MIN_INTERVAL; // LED_STATUS2_ON; } // else { // LED_STATUS2_TOGGLE; // } } else if ((adaptiveSampleRejection->accepted + SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_INTERVAL_THRESHOLD) < (SAMPLE_FIFO_ADAPTIVE_REJECTION_ACCEPTANCE_RATIO * adaptiveSampleRejection->rejected)) { // on accepted below limit, increase rejection interval adaptiveSampleRejection->currentAcceptedDeviation += SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_STEP; if (adaptiveSampleRejection->currentAcceptedDeviation >= SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_MAX_INTERVAL) { adaptiveSampleRejection->currentAcceptedDeviation = SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_MAX_INTERVAL; // LED_STATUS3_ON; } // else { // LED_STATUS3_TOGGLE; // } } // else { // LED_STATUS3_TOGGLE; // LED_STATUS2_TOGGLE; // } // update new rejection boundaries adaptiveSampleRejection->outlierLowerBound = (SampleValueType) roundf(timeSynchronization->mean - (CalculationType) adaptiveSampleRejection->currentAcceptedDeviation); adaptiveSampleRejection->outlierUpperBound = (SampleValueType) roundf(timeSynchronization->mean + (CalculationType) adaptiveSampleRejection->currentAcceptedDeviation); adaptiveSampleRejection->isOutlierRejectionBoundValid = true; } #include "Deviation.h" /** * Adds a value to the FiFo buffer. */ void samplesFifoBufferAddSample(const SampleValueType *const sample) { TimeSynchronization *const timeSynchronization = &ParticleAttributes.timeSynchronization; bool isToBeRejected = false; // on overfull start rejecting on overfull FiFo if (timeSynchronization->timeIntervalSamples.isDropOutValid) { if (*sample < timeSynchronization->adaptiveSampleRejection.outlierLowerBound || *sample > timeSynchronization->adaptiveSampleRejection.outlierUpperBound) { timeSynchronization->adaptiveSampleRejection.rejected++; isToBeRejected = true; } else { timeSynchronization->adaptiveSampleRejection.accepted++; } __reduceRejectionCounters(&timeSynchronization->adaptiveSampleRejection); // reject means: sample does not enter the queue if (isToBeRejected) { return; } } // add sample to FiFo if (timeSynchronization->timeIntervalSamples.numSamples < SAMPLE_FIFO_NUM_BUFFER_ELEMENTS) { timeSynchronization->timeIntervalSamples.numSamples++; } __samplesFifoBufferIncrementInsertIndex(&timeSynchronization->timeIntervalSamples); timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex].value = *sample; timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex].isRejected = isToBeRejected; #ifdef SYNCHRONIZATION_STRATEGY_MEAN_ENABLE_ONLINE_CALCULATION // calculate mean stepwise / on-line if (timeSynchronization->timeIntervalSamples.isDropOutValid) { // on fifo has dropped out a first-in value __calculateMeanUsingFifoInOutObservations(timeSynchronization, &timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex], &timeSynchronization->timeIntervalSamples.dropOut); } else { // on fifo not entirely saturated __calculateMeanUsingFifoInObservations(timeSynchronization, &timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex]); } #else // off-line mean calculation if (isFiFoFull(&timeSynchronization->timeIntervalSamples)) { calculateMean(); } // on full FiFo update the rejection boundaries if (isFiFoFull(&timeSynchronization->timeIntervalSamples)) { __updateCurrentRejectionBoundariesDependingOnCounters(); } #endif } #endif #ifdef SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_MARKED_OUTLIER #include "Deviation.h" /** * Adds a value to the FiFo buffer. */ void samplesFifoBufferAddSample(const SampleValueType *const sample, TimeSynchronization *const timeSynchronization) { bool isToBeRejected = false; if (isFiFoFull(&timeSynchronization->timeIntervalSamples) && timeSynchronization->adaptiveSampleRejection.isOutlierRejectionBoundValid) { if (*sample < timeSynchronization->adaptiveSampleRejection.outlierLowerBound || *sample > timeSynchronization->adaptiveSampleRejection.outlierUpperBound) { // reject means: marking the value which enters the queue as outlier // according to current mean/deviation isToBeRejected = true; } } // add sample to FiFo if (timeSynchronization->timeIntervalSamples.numSamples < SAMPLE_FIFO_NUM_BUFFER_ELEMENTS) { timeSynchronization->timeIntervalSamples.numSamples++; } __samplesFifoBufferIncrementInsertIndex(&timeSynchronization->timeIntervalSamples); timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex].value = *sample; timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex].isRejected = isToBeRejected; // update mean exclusive marked outlier calculateMeanWithoutMarkedOutlier(); } #endif #if defined(SYNCHRONIZATION_STRATEGY_MEAN) \ || defined(SYNCHRONIZATION_STRATEGY_MEAN_WITHOUT_OUTLIER) #include "Deviation.h" /** * Adds a value to the FiFo buffer. */ void samplesFifoBufferAddSample(const SampleValueType *const sample, TimeSynchronization *const timeSynchronization) { // add any sample to FiFo regardless of outlier if (timeSynchronization->timeIntervalSamples.numSamples < SAMPLE_FIFO_NUM_BUFFER_ELEMENTS) { timeSynchronization->timeIntervalSamples.numSamples++; } __samplesFifoBufferIncrementInsertIndex(&timeSynchronization->timeIntervalSamples); timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex].value = *sample; // timeSynchronization->timeIntervalSamples. // samples[timeSynchronization->timeIntervalSamples.__insertIndex].isRejected = false; #ifdef SYNCHRONIZATION_STRATEGY_MEAN_ENABLE_ONLINE_CALCULATION // calculate mean stepwise / on-line if (timeSynchronization->timeIntervalSamples.isDropOutValid) { // on fifo has dropped out a first-in value __calculateMeanUsingFifoInOutObservations(timeSynchronization, &timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex], &timeSynchronization->timeIntervalSamples.dropOut); } else { // on fifo not entirely saturated __calculateMeanUsingFifoInObservations(timeSynchronization, &timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex]); } #else // off-line mean calculation if (isFiFoFull(&timeSynchronization->timeIntervalSamples)) { calculateMean(); } #endif } #endif #ifdef SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN /** * Does not add any value to the FiFo buffer but calculates a very naive mean immediately. */ void samplesFifoBufferAddSample(const SampleValueType *const sample, TimeSynchronization *const timeSynchronization) { // very naive implementation used for evaluation/comparison __calculateProgressiveMean(sample, timeSynchronization); } #endif #ifdef SYNCHRONIZATION_STRATEGY_LEAST_SQUARE_LINEAR_FITTING /** * Adds a value to the FiFo buffer. */ void samplesFifoBufferAddSample(const SampleValueType *const sample, TimeSynchronization *const timeSynchronization) { // add sample to FiFo if (timeSynchronization->timeIntervalSamples.numSamples < SAMPLE_FIFO_NUM_BUFFER_ELEMENTS) { timeSynchronization->timeIntervalSamples.numSamples++; } __samplesFifoBufferIncrementInsertIndex(&timeSynchronization->timeIntervalSamples); timeSynchronization->timeIntervalSamples. samples[timeSynchronization->timeIntervalSamples.__insertIndex].value = *sample; // timeSynchronization->timeIntervalSamples. // samples[timeSynchronization->timeIntervalSamples.__insertIndex].isRejected = isToBeRejected; // printf("%u\n", *sample); } #endif #ifdef SYNCHRONIZATION_STRATEGY_RAW_OBSERVATION /** * Adds a value to the FiFo buffer. */ void samplesFifoBufferAddSample(const SampleValueType *const sample, TimeSynchronization *const timeSynchronization) { // very naive implementation: use current observation as mean timeSynchronization->mean = *sample; // workaround timeSynchronization->timeIntervalSamples.numSamples = SAMPLE_FIFO_NUM_BUFFER_ELEMENTS; } #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication-protocol/CommunicationProtocol.h
/** * Created by <NAME> on 11.05.2016 * * Protocol tx/rx relevant implementation. */ #pragma once #include "uc-core/particle/Globals.h" #include "CommunicationProtocolTypes.h" #include "simulation/SimulationMacros.h" #include "uc-core/configuration/CommunicationProtocol.h" #include "uc-core/configuration/IoPins.h" #include "uc-core/delay/delay.h" /** * Sets the data end pointer to the specified position. * For optimization purpose the pointer struct is casted to uint16_t. * @param bufferDataEndPointer the pointer field * @param uint16tNewDataEndPointer the new pointer field value */ void setBufferDataEndPointer(volatile BufferBitPointer *const dataEndPointer, const uint16_t newDataEndPointer) { (*((volatile uint16_t *) dataEndPointer) = newDataEndPointer); } /** * Evaluates to true if the buffered data's end position equals the specified end position, * to false otherwise. * For optimization purpose the pointer struct is casted to uint16_t. * @param bufferDataEndPointer the pointer field * @param uint16tExpectedDataEndPointer the expected pointer field value */ bool equalsPackageSize(const BufferBitPointer *const bufferDataEndPointer, const uint16_t uint16tExpectedDataEndPointer) { return ((*((uint16_t *) (bufferDataEndPointer))) == uint16tExpectedDataEndPointer); } /** * invalidates all reception buffers */ void clearReceptionBuffers(void) { DEBUG_CHAR_OUT('c'); ParticleAttributes.communication.ports.rx.north.isDataBuffered = false; ParticleAttributes.communication.ports.rx.north.isOverflowed = false; ParticleAttributes.communication.ports.rx.east.isDataBuffered = false; ParticleAttributes.communication.ports.rx.east.isOverflowed = false; ParticleAttributes.communication.ports.rx.south.isDataBuffered = false; ParticleAttributes.communication.ports.rx.south.isOverflowed = false; } /** * Invalidates the given port's reception buffer. * @param o the port to invalidate the reception buffer */ void clearReceptionPortBuffer(RxPort *const o) { o->isDataBuffered = false; o->isOverflowed = false; DEBUG_CHAR_OUT('c'); } /** * Prepares the given transmission port for buffering and later transmission. * @param o the port to prepare */ void clearTransmissionPortBuffer(TxPort *const o) { o->isTransmitting = false; bufferBitPointerStart(&o->buffer.pointer); } /** * Puts the receptionist in start state and sets the timeout counter. * @param commPortState a reference to the designated port state */ void setReceptionistStateStart(CommunicationProtocolPortState *const commPortState) { // ParticleAttributes.communicationProtocol.stateTimeoutCounter = COMMUNICATION_STATE_TIMEOUT_COUNTER; DEBUG_CHAR_OUT('r'); commPortState->receptionistState = COMMUNICATION_RECEPTIONIST_STATE_TYPE_RECEIVE; commPortState->stateTimeoutCounter = COMMUNICATION_PROTOCOL_TIMEOUT_COUNTER_MAX; commPortState->reTransmissions = COMMUNICATION_PROTOCOL_RETRANSMISSION_COUNTER_MAX; } /** * Puts the initiator in start state and set the timeout counter. * @param commPortState a reference to the designated port state */ void setInitiatorStateStart(CommunicationProtocolPortState *const commPortState) { DEBUG_CHAR_OUT('T'); commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT; commPortState->stateTimeoutCounter = COMMUNICATION_PROTOCOL_TIMEOUT_COUNTER_MAX; commPortState->reTransmissions = COMMUNICATION_PROTOCOL_RETRANSMISSION_COUNTER_MAX; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/synchronization/SampleFifoTypes.h
<filename>src/avr-common/utils/uc-core/configuration/synchronization/SampleFifoTypes.h /** * @author <NAME> 24.09.2016 * * Sample capturing related arguments. */ #pragma once /** * Amount of uint16 samples the synchronization buffers for clock skew approximation. */ //#define SAMPLE_FIFO_NUM_BUFFER_ELEMENTS 120 #define SAMPLE_FIFO_NUM_BUFFER_ELEMENTS 4 /** * default numeric value indicating buffer's end position */ #define TIME_SYNCHRONIZATION_SAMPLES_FIFO_BUFFER_ITERATOR_END ((uint8_t)(SAMPLE_FIFO_NUM_BUFFER_ELEMENTS + 1)) /** * if rejected or accepted counter >= SAMPLE_FIFO_ADAPTIVE_REJECTION_REDUCE_COUNTERS_LIMIT * both counters are reduced by factor 2.0 */ # define SAMPLE_FIFO_ADAPTIVE_REJECTION_REDUCE_COUNTERS_LIMIT ((uint16_t) 2000) /** * threshold where no interval updates are performed */ # define SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_INTERVAL_THRESHOLD ((uint8_t) 25) /** * step to increase/decrease the acceptance interval */ # define SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_STEP ((uint8_t) 10) /** * minimum acceptance interval: * mean +/- SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_MIN_INTERVAL */ # define SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_MIN_INTERVAL ((int8_t) 10) /** * maximum acceptance interval: * mean +/- SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_MAX_INTERVAL */ # define SAMPLE_FIFO_ADAPTIVE_REJECTION_UPDATE_REJECTION_MAX_INTERVAL ((int16_t) 20000) /** * the factor of accepted versus rejected: * accpeted ~ SAMPLE_FIFO_ADAPTIVE_REJECTION_ACCEPTANCE_RATIO * rejected */ # define SAMPLE_FIFO_ADAPTIVE_REJECTION_ACCEPTANCE_RATIO ((uint16_t) 9)
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/PointerImplementation.h
/** * @author <NAME> 13.07.2016 * * Particle core related implementation that is ought to be passed as pointer or callback. */ #pragma once #include "uc-core/communication/ManchesterDecoding.h" #include "uc-core/communication-protocol/Interpreter.h" /** * North port reception implementation. */ void receiveNorth(void) { if (ParticleAttributes.discoveryPulseCounters.north.isConnected) { manchesterDecodeBuffer(&ParticleAttributes.directionOrientedPorts.north, interpretRxBuffer); } } /** * East port reception implementation. */ void receiveEast(void) { if (ParticleAttributes.discoveryPulseCounters.east.isConnected) { manchesterDecodeBuffer(&ParticleAttributes.directionOrientedPorts.east, interpretRxBuffer); } } /** * South port reception implementation. */ void receiveSouth(void) { if (ParticleAttributes.discoveryPulseCounters.south.isConnected) { manchesterDecodeBuffer(&ParticleAttributes.directionOrientedPorts.south, interpretRxBuffer); } }
ProgrammableMatter/particle-firmware
src/particle-simulation-setnewnetworkgeometry-test/main/main.c
/** * @author <NAME> 2016 */ #define SIMULATION_SET_NEW_NETWORK_GEOMETRY_TEST #include <uc-core/particle/ParticleLoop.h> int main(void) { processLoop(); return 0; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/ManchesterDecodingTypes.h
/** * @author <NAME> 2016 * * Manchester decoding related types definition. */ #pragma once #include <stdint.h> #include "uc-core/configuration/communication/ManchesterDecoding.h" /** * Possible manchester decoder states. */ typedef enum ManchesterDecodingStateType { DECODER_STATE_TYPE_START, // initialization state before decoding DECODER_STATE_TYPE_DECODING, // state when decoding DECODER_STATE_TYPE_POST_TIMEOUT_PROCESS, // state after last decoding } ManchesterDecodingStateType; /** * Manchester decoder state and phase state struct. */ typedef struct ManchesterDecoderStates { ManchesterDecodingStateType decodingState; /** * phase state: the 1 bit counter is incremented by 1 on short intervals and * by increased by 2 on long intervals */ uint8_t phaseState: 1; uint8_t __pad : 7; } ManchesterDecoderStates; /** * A snapshot consists of a 16 bit value and the flank direction information. The least significant snapshot * bit is scarified for the flank direction information. Thus only the bits [15:1] of the snapshot are stored. */ #ifdef MANCHESTER_DECODING_ENABLE_MERGE_TIMESTAMP_WITH_EDGE_DIRECTION typedef struct Snapshot { volatile uint16_t isRisingEdge : 1; /** * The least significant snapshot value bit is ignored; this should be used as: * foo = s.snapshot << 1 */ volatile uint16_t timerValue : 15; } Snapshot; #else typedef struct Snapshot { volatile uint16_t timerValue; volatile uint8_t isRisingEdge : 1; volatile uint8_t __pad : 7; } Snapshot; #endif /** * The struct is used as buffer for storing timestamps of received pin change interrupts. * The timestamps are then decoded to bits and stored to a RxBuffer struct. */ typedef struct RxSnapshotBuffer { /** * Manchester decoder states */ ManchesterDecoderStates decoderStates; /** * snapshot buffer */ volatile Snapshot snapshots[MANCHESTER_DECODING_RX_NUMBER_SNAPSHOTS]; /** * field stores the previous dequeue value */ uint16_t temporarySnapshotTimerValue; /** * field describes the 1st buffered position */ volatile uint8_t startIndex : 7; volatile uint8_t __pad : 1; /** * describes the 1st invalid buffer position */ volatile uint8_t endIndex : 7; volatile uint8_t isOverflowed : 1; /** * number of passed half cycles reflects the number of π's passed from 1st snapshot * until the last snapshot before timeout * -------<=========>------ * -------^---------^------ */ uint8_t numberHalfCyclesPassed; } RxSnapshotBuffer;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/DiscoveryPulseCountersTypes.h
/* * @author <NAME> 09.10.2016 * * Discovery state definition. */ #pragma once #include <stdint.h> #include "uc-core/discovery/DiscoveryTypes.h" /** * Stores the amount of incoming pulses for each communication channel. The isConnected flags are set * if the number of incoming pulses exceeds a specific threshold. */ typedef struct DiscoveryPulseCounters { DiscoveryPulseCounter north; DiscoveryPulseCounter east; DiscoveryPulseCounter south; // discovery loop counter uint8_t loopCount; } DiscoveryPulseCounters;
ProgrammableMatter/particle-firmware
src/particle-initial-io-test/main/Interrupts.c
<gh_stars>1-10 /** * @author <NAME> 2015 */ #include <avr/io.h> #include <avr/interrupt.h> /** * pin on port A change interrupt request */ ISR(PCINT0_vect) { // rx-A or rx-B } /** * External Pin, Power-on Reset, Brown-Out Reset, Watchdog Reset */ ISR(_VECTOR(0)) { } /** * Watchdog Time-out */ ISR(WDT_vect) { } /** * Timer/Counter1 Input Capture */ ISR(TIM1_CAPT_vect) { } /** * Timer/Counter1 Compare Match A */ ISR(TIM1_COMPA_vect) { } /** * Timer/Counter1 Compare Match B */ ISR(TIM1_COMPB_vect) { } /** * Timer/Counter1 Overflow - 16 bit counter */ ISR(TIM1_OVF_vect) { } /** * Timer/Counter0 Compare Match A */ ISR(TIM0_COMPA_vect) { } /** * Timer/Counter0 Compare Match B */ ISR(TIM0_COMPB_vect) { } /** * Timer/Counter0 Overflow - 8bit counter */ ISR(TIM0_OVF_vect) { }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/synchronization/SynchronizationTypesCtors.h
/** * @author <NAME> 24.09.2016 * * Synchronization related arguments. */ #pragma once #include "uc-core/configuration/Evaluation.h" #ifdef EVALUATION_SYNC_CYCLICALLY # define SYNCHRONIZATION_TYPES_CTORS_FIRST_SYNC_PACKAGE_LOCAL_TIME ((uint16_t) 160) # define SYNCHRONIZATION_TYPES_CTORS_FAST_SYNC_PACKAGE_SEPARATION ((uint8_t) 20) # define SYNCHRONIZATION_TYPES_CTORS_SYNC_PACKAGE_SEPARATION ((uint16_t) 340) # define SYNCHRONIZATION_TYPES_CTORS_TOTAL_FAST_SYNC_PACKAGES ((uint16_t) 5) #endif #ifdef EVALUATION_SIMPLE_SYNC_AND_ACTUATION # define SYNCHRONIZATION_TYPES_CTORS_FIRST_SYNC_PACKAGE_LOCAL_TIME ((uint16_t) 350) # define SYNCHRONIZATION_TYPES_CTORS_FAST_SYNC_PACKAGE_SEPARATION ((uint8_t) 40) # define SYNCHRONIZATION_TYPES_CTORS_SYNC_PACKAGE_SEPARATION ((uint16_t) 80) # define SYNCHRONIZATION_TYPES_CTORS_TOTAL_FAST_SYNC_PACKAGES ((uint16_t) 30) #endif #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG # define SYNCHRONIZATION_TYPES_CTORS_FAST_SYNC_PACKAGE_SEPARATION ((uint16_t) 64) # define SYNCHRONIZATION_TYPES_CTORS_SYNC_PACKAGE_SEPARATION ((uint16_t) 64) //# define SYNCHRONIZATION_TYPES_CTORS_SYNC_PACKAGE_SEPARATION ((uint16_t) 300) //# define SYNCHRONIZATION_TYPES_CTORS_TOTAL_FAST_SYNC_PACKAGES ((uint16_t) 50) # define SYNCHRONIZATION_TYPES_CTORS_TOTAL_FAST_SYNC_PACKAGES ((uint16_t) 5) #endif #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_IN_PHASE_SHIFTING # define SYNCHRONIZATION_TYPES_CTORS_FAST_SYNC_PACKAGE_SEPARATION ((uint16_t) 64) # define SYNCHRONIZATION_TYPES_CTORS_SYNC_PACKAGE_SEPARATION ((uint16_t) 64) # define SYNCHRONIZATION_TYPES_CTORS_TOTAL_FAST_SYNC_PACKAGES ((uint16_t) 5) #endif #ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_THEN_ACTUATE_ONCE # define SYNCHRONIZATION_TYPES_CTORS_FIRST_SYNC_PACKAGE_LOCAL_TIME ((uint16_t) 350) # define SYNCHRONIZATION_TYPES_CTORS_FAST_SYNC_PACKAGE_SEPARATION ((uint16_t) 40) # define SYNCHRONIZATION_TYPES_CTORS_SYNC_PACKAGE_SEPARATION ((uint16_t) 80) # define SYNCHRONIZATION_TYPES_CTORS_TOTAL_FAST_SYNC_PACKAGES ((uint16_t) 30) #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/particle/types/ParticleTypes.h
/* * @author <NAME>016 * * Particle state definition. */ #pragma once #include <stdint.h> #include "uc-core/particle/types/NodeAddressTypes.h" #include "uc-core/actuation/ActuationTypes.h" #include "uc-core/time/TimeTypes.h" #include "uc-core/periphery/PeripheryTypes.h" #include "uc-core/synchronization/SynchronizationTypes.h" #include "uc-core/particle/types/AlertsTypes.h" #include "uc-core/particle/types/DiscoveryPulseCountersTypes.h" #include "uc-core/particle/types/CommunicationTypes.h" #include "uc-core/scheduler/SchedulerTypes.h" #include "uc-core/particle/types/ParticleStateTypes.h" #include "uc-core/evaluation/EvaluationTypes.h" /** * Describes the node state type and address. */ typedef struct Node { /** * Describes the global node states. */ volatile StateType state; volatile NodeType type; NodeAddress address; } Node; /** * The global particle structure containing buffers, states, counters and alike. */ typedef struct Particle { #ifdef SIMULATION // a marker used to assure the correct interpretation of the particle structure when simulating uint8_t __structStartMarker; #endif /** * Node type, state and address fields. */ Node node; /** * Node connectivity settings and states. */ DiscoveryPulseCounters discoveryPulseCounters; /** * Communication (physical layer) related states and buffers. */ Communication communication; /** * Resources needed for non-essential periphery implementation such as LEDs, test points and alike. */ Periphery periphery; /** * Communication protocol (layer 1) related settings and states. */ CommunicationProtocol protocol; /** * Settings related to actuation command. */ ActuationCommand actuationCommand; /** * clock skew adjustment */ TimeSynchronization timeSynchronization; /** * Local time and settings are stored to this field. */ LocalTimeTracking localTime; /** * Facade to bundle the DiscoveryPulseCounters, Communication and CommunicationProtocol port * related resources in a direction oriented way. */ DirectionOrientedPorts directionOrientedPorts; /** * flags arming/disarming alerts on run time */ Alerts alerts; /** * Simple scheduler to plan and execute tasks from the main loop. */ Scheduler scheduler; /** * Evaluation relevant fields. Can be removed in productive application. */ Evaluation evaluation; #ifdef SIMULATION // a marker used to assure the correct interpretation of the particle structure when simulating uint8_t __structEndMarker; #endif } Particle;
ProgrammableMatter/particle-firmware
src/particle-simulation-io-test/main/main.c
<filename>src/particle-simulation-io-test/main/main.c /** * @author <NAME> 2016 */ #include <avr/pgmspace.h> #include "../libs/common/common.h" #include <uc-core/configuration/IoPins.h> #define SIMULATION #include <simulation/SimulationMacros.h> //const char testMessage[] PROGMEM = "test"; /** * Generates a certain amount of transitions/writes per output wires/registers. The expected amount of * transitions are monitored and evaluated in the simulation by test cases. */ int main(void) { int extraTransitions = 2; extraTransitions++; LED_STATUS1_SETUP; for (int i = 0; i < extraTransitions; ++i) { LED_STATUS1_OFF; LED_STATUS1_ON; } extraTransitions++; LED_STATUS2_SETUP; for (int i = 0; i < extraTransitions; ++i) { LED_STATUS2_OFF; LED_STATUS2_ON; } extraTransitions++; LED_STATUS3_SETUP; for (int i = 0; i < extraTransitions; ++i) { LED_STATUS3_OFF; LED_STATUS3_ON; } extraTransitions++; LED_STATUS4_SETUP; for (int i = 0; i < extraTransitions; ++i) { LED_STATUS4_OFF; LED_STATUS4_ON; } // extraTransitions++; // LED_STATUS5_SETUP; // for (int i = 0; i < extraTransitions; ++i) { // LED_STATUS5_OFF; // LED_STATUS5_ON; // } // extraTransitions++; // LED_STATUS6_SETUP; // for (int i = 0; i < extraTransitions; ++i) { // LED_STATUS6_OFF; // LED_STATUS6_ON; // } extraTransitions++; TEST_POINT1_SETUP; for (int i = 0; i < extraTransitions; ++i) { TEST_POINT1_LO; TEST_POINT1_HI; } extraTransitions++; TEST_POINT2_SETUP; for (int i = 0; i < extraTransitions; ++i) { TEST_POINT2_LO; TEST_POINT2_HI; } extraTransitions++; TEST_POINT3_SETUP; for (int i = 0; i < extraTransitions; ++i) { TEST_POINT3_LO; TEST_POINT3_HI; } // extraTransitions++; // TEST_POINT4_SETUP; // for (int i = 0; i < extraTransitions; ++i) { // TEST_POINT4_LO; // TEST_POINT4_HI; // } extraTransitions++; NORTH_TX_SETUP; for (int i = 0; i < extraTransitions; ++i) { NORTH_TX_LO; NORTH_TX_HI; } extraTransitions++; NORTH_RX_SWITCH_SETUP; for (int i = 0; i < extraTransitions; ++i) { NORTH_RX_SWITCH_LO; NORTH_RX_SWITCH_HI; } extraTransitions++; SOUTH_TX_SETUP; for (int i = 0; i < extraTransitions; ++i) { SOUTH_TX_LO; SOUTH_TX_HI; } extraTransitions++; SOUTH_RX_SWITCH_SETUP; for (int i = 0; i < extraTransitions; ++i) { SOUTH_RX_SWITCH_LO; SOUTH_RX_SWITCH_HI; } extraTransitions++; EAST_TX_SETUP; for (int i = 0; i < extraTransitions; ++i) { EAST_TX_HI; EAST_TX_LO; } int writes = extraTransitions; writes++; NORTH_RX_SETUP; for (int i = 0; i < writes; ++i) { NORTH_RX_PULL_UP_DISABLE; NORTH_RX_PULL_UP; } writes++; SOUTH_RX_SETUP; for (int i = 0; i < writes; ++i) { SOUTH_RX_PULL_UP_DISABLE; SOUTH_RX_PULL_UP; } writes++; EAST_RX_SETUP; for (int i = 0; i < writes; ++i) { EAST_RX_PULL_UP_DISABLE; EAST_RX_PULL_UP; } // writeToUart((PGM_P) pgm_read_word(&(testMessage))); writeToUart("test"); forever { }; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/ManchesterCoding.h
/** * @author <NAME> 2016 * * Manchester coding related implementation. */ #pragma once #include "ManchesterDecodingTypes.h" /** * rectifies the transmission signal according to the upcoming bit * @param port the designated port to read buffered data and write signal to */ static void __rectifyTransmissionBit(DirectionOrientedPort *const port) { if (isDataEndPosition(port->txPort)) { // on tx pointer match end position port->txLowPimpl(); // return signal to default (inverted at receiver side) port->txPort->isTransmitting = false; } else { if (port->txPort->buffer.pointer.bitMask & port->txPort->buffer.bytes[port->txPort->buffer.pointer.byteNumber]) { port->txHighPimpl(); } else { port->txLowPimpl(); } } } /** * modulates the transmission signal according to the current bit and increments the buffer pointer * @param port the designated port to read buffered data from and write signal to */ static void __modulateTransmissionBit(DirectionOrientedPort *const port) { if (port->txPort->buffer.pointer.bitMask & port->txPort->buffer.bytes[port->txPort->buffer.pointer.byteNumber]) { port->txLowPimpl(); } else { port->txHighPimpl(); } bufferBitPointerIncrement(&port->txPort->buffer.pointer); } /** * writes the next signal on the port pin * @param port the designated port to read buffered data from and write signal to */ void transmit(DirectionOrientedPort *port) { if (!port->txPort->isDataBuffered || !port->txPort->isTransmitting) { return; } if (port->txPort->isTxClockPhase) { __rectifyTransmissionBit(port); } else { __modulateTransmissionBit(port); } port->txPort->isTxClockPhase++; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/periphery/PeripheryTypes.h
<gh_stars>1-10 /* * @author <NAME> 18.09.2016 * * Particle state definition. */ #pragma once #include <stdint.h> typedef enum AddressBlinkStates { ADDRESS_BLINK_STATES_START, ADDRESS_BLINK_STATES_BLINK_ROW, ADDRESS_BLINK_STATES_ROW_ON, ADDRESS_BLINK_STATES_ROW_OFF, ADDRESS_BLINK_STATES_PAUSE, ADDRESS_BLINK_STATES_BLINK_COLUMN, ADDRESS_BLINK_STATES_COLUMN_ON, ADDRESS_BLINK_STATES_COLUMN_OFF, ADDRESS_BLINK_STATES_PAUSE2, ADDRESS_BLINK_STATES_QUIT_SIGNAL, ADDRESS_BLINK_STATES_END, } AddressBlinkStates; typedef struct BlinkAddress { uint8_t blinkRowCounter; uint8_t blinkColumnCounter; uint8_t blinkAddressBlinkDelay; uint16_t lastExecutionTime; AddressBlinkStates blinkAddressState; } BlinkAddress; typedef enum TimeIntervalBlinkStates { TIME_INTERVAL_BLINK_STATES_LED_ON, TIME_INTERVAL_BLINK_STATES_LED_OFF, } TimeIntervalBlinkStates; typedef struct BlinkTimeInterval { uint8_t localTimeMultiplier; uint16_t lastExecutionTime; TimeIntervalBlinkStates blinkState; } BlinkTimeInterval; /** * Counters/resources needed for non vital platform's periphery such as LEDs, test points and alike. */ typedef struct Periphery { BlinkAddress blinkAddress; BlinkTimeInterval blinkTimeInterval; uint8_t doClearLeds : 1; // // validation code for emasuring forward latency // volatile uint8_t isTxSouthToggleEnabled : 1; uint8_t __pad: 7; } Periphery;
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication-protocol/CommunicationProtocolTypesCtors.h
<reponame>ProgrammableMatter/particle-firmware /** * Created by <NAME> on 11.05.2016 * * Communication protocol types constructor implementation. */ #pragma once #include "uc-core/particle/Globals.h" #include "./CommunicationProtocolTypes.h" /** * constructor function * @param o reference to the object to construct */ void constructCommunicationProtocolPortState(CommunicationProtocolPortState *const o) { o->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_IDLE; o->receptionistState = COMMUNICATION_RECEPTIONIST_STATE_TYPE_IDLE; o->stateTimeoutCounter = COMMUNICATION_PROTOCOL_TIMEOUT_COUNTER_MAX; o->reTransmissions = COMMUNICATION_PROTOCOL_RETRANSMISSION_COUNTER_MAX; } /** * constructor function * @param o reference to the object to construct */ void constructCommunicationProtocolPorts(CommunicationProtocolPorts *const o) { constructCommunicationProtocolPortState(&o->north); constructCommunicationProtocolPortState(&o->east); constructCommunicationProtocolPortState(&o->south); } /** * constructor function * @param o reference to the object to construct */ void constructNetworkGeometry(NetworkGeometry *const o) { o->rows = 0; o->columns = 0; } /** * constructor function * @param o reference to the object to construct */ void constructCommunicationProtocol(CommunicationProtocol *const o) { constructCommunicationProtocolPorts(&o->ports); constructNetworkGeometry(&o->networkGeometry); o->hasNetworkGeometryDiscoveryBreadCrumb = false; o->isBroadcastEnabled = false; o->isSimultaneousTransmissionEnabled = false; o->isLastReceptionInterpreted = false; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/Stdout.h
<filename>src/avr-common/utils/uc-core/configuration/Stdout.h /** * @author <NAME> 08.10.2016 * * USART related arguments. */ #pragma once #ifdef __AVR_ATtiny1634__ /** * Baud rate for USART1 output (RS232). * Default setup is 8bit, no parity bit, 1 stop bit or better known as "8N1". * Note: The USART transmission is implemented for AVR ATtiny1634 in DEBUG compilation only. */ # define STDOUT_UART_BAUD_RATE (19200) #endif
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/time/Time.h
/** * @author <NAME> 12.07.2016 */ #pragma once #include "TimeTypes.h" #include "uc-core/particle/Globals.h" /** * Enables the local time interrupt using current adjustment argument * {@link ParticleAttributes.localTime.timePeriodInterruptDelay}. * Write to LOCAL_TIME_INTERRUPT_COMPARE_VALUE is not atomic. */ void enableLocalTimeInterrupt(void) { LOCAL_TIME_INTERRUPT_COMPARE_DISABLE; MEMORY_BARRIER; LOCAL_TIME_INTERRUPT_COMPARE_VALUE = ParticleAttributes.localTime.timePeriodInterruptDelay; MEMORY_BARRIER; LOCAL_TIME_INTERRUPT_COMPARE_ENABLE; }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/configuration/Periphery.h
/** * @author <NAME> 2016 * * Periphery related arguments. */ #pragma once /** * To shrink flash usage on target device, the periphery implementation can be removed safely * without to influence the compilation except the output size. * Enable the define to remove the implementation, disable the define to compile the implementation. */ #define PERIPHERY_REMOVE_IMPL /** * address blinking: led on duration */ #define ADDRESS_BLINK_STATES_LED_ON_COUNTER_MAX ((uint8_t)30) /** * address blinking: led off duration */ #define ADDRESS_BLINK_STATES_LED_OFF_COUNTER_MAX ((uint8_t)30) /** * address blinking: separation of rows column blinking */ #define ADDRESS_BLINK_STATES_LED_SEPARATION_BREAK_COUNTER_MAX ((uint8_t)90) /** * address blinking: signal quitting the end of column blinking */ #define ADDRESS_BLINK_STATES_LED_SEPARATION_FLASH_COUNTER_MAX ((uint8_t)7) /** * address blinking: separation of one address blinking process */ #define ADDRESS_BLINK_STATES_LED_SEPARATION_LONG_BREAK_COUNTER_MAX ((uint8_t)140) /** * simple heartbeat blinking: on/off */ #define TIME_INTERVAL_BLINK_STATES_PERIOD_MULTIPLIER ((uint8_t)60)
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/communication/Communication.h
<gh_stars>1-10 /** * @author <NAME> 2016 * * Byte oriented communication related implementation. */ #pragma once #include "common/common.h" #include "CommunicationTypes.h" #include "ManchesterDecodingTypes.h" /** * Increments the bit mask and the byte number accordingly. * @param o the buffer bit pointer reference */ void bufferBitPointerIncrement(volatile BufferBitPointer *const o) { o->bitMask <<= 1; if ((o->bitMask == 0) && (o->byteNumber < (sizeof(((PortBuffer *) 0)->bytes)))) { o->bitMask = 1; o->byteNumber++; } } /** * points the reception buffer pointer to the start position (lowest bit) * @param o the buffer bit pointer reference */ void bufferBitPointerStart(volatile BufferBitPointer *const o) { o->bitMask = 1; o->byteNumber = 0; } /** * Returns true if the transmission buffer pointer points exactly at the data end marker. * The marker is set one bit beyond the last data bit. * @param o the transmission port reference */ bool isDataEndPosition(const TxPort *const txPort) { return (txPort->dataEndPos.bitMask == txPort->buffer.pointer.bitMask) && (txPort->dataEndPos.byteNumber == txPort->buffer.pointer.byteNumber); } /** * Evaluates to true if the buffer bit pointer points beyond the last buffer bit. * @param bufferBitPointer the pointer to compare to */ bool isBufferEndPosition(const BufferBitPointer *const bufferBitPointer) { return (bufferBitPointer->byteNumber == (sizeof(((PortBuffer *const) (0))->bytes))) && (bufferBitPointer->bitMask == 0x1); }
ProgrammableMatter/particle-firmware
src/avr-common/utils/uc-core/interrupts/Interrupts.h
<gh_stars>1-10 /** * @author <NAME> 2015 */ #pragma once #include "uc-core/particle/Globals.h" #include "uc-core/configuration/IoPins.h" #include "uc-core/configuration/interrupts/Vectors.h" #include "uc-core/configuration/interrupts/TxRxTimer.h" #include "uc-core/configuration/interrupts/LocalTime.h" #include "uc-core/configuration/interrupts/ReceptionPCI.h" #include "uc-core/discovery/Discovery.h" #include "uc-core/communication/Transmission.h" #include "uc-core/communication/ManchesterCoding.h" #include "uc-core/communication/ManchesterDecoding.h" #include "uc-core/time/Time.h" #include "uc-core/particle/Commands.h" #ifdef SIMULATION # include <avr/pgmspace.h> # include "simulation/SimulationMacros.h" #endif /** * Handles input pins interrupts according to the particle state. * @param port the designated port * @param isRxHigh the logic signal level */ static inline void __handleInputInterrupt(DirectionOrientedPort *const port, const bool isRxHigh, uint16_t timerCounterValue, uint16_t nextLocalTimeInterruptCompareValue) { switch (ParticleAttributes.node.state) { case STATE_TYPE_NEIGHBOURS_DISCOVERY: // on discovery pulse if (!isRxHigh) { dispatchFallingDiscoveryEdge(port->discoveryPulseCounter); } break; default: // on data received captureSnapshot(timerCounterValue, isRxHigh, nextLocalTimeInterruptCompareValue, port->rxPort); break; } } /** * Schedules the next transmission interrupt if transmission data is buffered. */ static void __scheduleNextTransmission(void) { if (ParticleAttributes.communication.ports.tx.north.isTransmitting || ParticleAttributes.communication.ports.tx.east.isTransmitting || ParticleAttributes.communication.ports.tx.south.isTransmitting) { scheduleNextTxInterrupt(); } else { TIMER_TX_RX_DISABLE_COMPARE_INTERRUPT; DEBUG_CHAR_OUT('U'); } } /** * Interrupt routine on logical north pin change (reception). * simulator int. #19 */ ISR(NORTH_PIN_CHANGE_INTERRUPT_VECT) { // TEST_POINT1_TOGGLE; // // validation code to measure signal forwarding latency // if (ParticleAttributes.periphery.isTxSouthToggleEnabled) { // SOUTH_TX_TOGGLE; // return; // } // DEBUG_INT16_OUT(TIMER_TX_RX_COUNTER_VALUE); if (ParticleAttributes.protocol.isBroadcastEnabled) { if (NORTH_RX_IS_HI) { simultaneousTxLoImpl(); } else { simultaneousTxHiImpl(); } } __handleInputInterrupt(&ParticleAttributes.directionOrientedPorts.north, NORTH_RX_IS_HI, TIMER_TX_RX_COUNTER_VALUE, LOCAL_TIME_INTERRUPT_COMPARE_VALUE); // TEST_POINT1_TOGGLE; } /** * Interrupt routine on logical east pin change (reception). * simulator int. #3 */ ISR(EAST_PIN_CHANGE_INTERRUPT_VECT) { // TEST_POINT1_TOGGLE; // // TODO: evaluation code to prove that east pin change ISR is sporadic triggered during discovery phase // // to reproduce activate the source and follow the discovery period on the oscilloscope // if (!EAST_RX_IS_HI) // TEST_POINT1_TOGGLE; __handleInputInterrupt(&ParticleAttributes.directionOrientedPorts.east, EAST_RX_IS_HI, TIMER_TX_RX_COUNTER_VALUE, LOCAL_TIME_INTERRUPT_COMPARE_VALUE); } /** * Interrupt routine on logical south pin change (reception). * simulator int. #2 */ ISR(SOUTH_PIN_CHANGE_INTERRUPT_VECT) { __handleInputInterrupt(&ParticleAttributes.directionOrientedPorts.south, SOUTH_RX_IS_HI, TIMER_TX_RX_COUNTER_VALUE, LOCAL_TIME_INTERRUPT_COMPARE_VALUE); } /** * On transmission/discovery timer compare match. * simulator int. #7 */ ISR(TX_TIMER_INTERRUPT_VECT) { switch (ParticleAttributes.node.state) { case STATE_TYPE_START: case STATE_TYPE_ACTIVE: break; case STATE_TYPE_NEIGHBOURS_DISCOVERY: case STATE_TYPE_NEIGHBOURS_DISCOVERED: case STATE_TYPE_DISCOVERY_PULSING: // on generate discovery pulse NORTH_TX_TOGGLE; EAST_TX_TOGGLE; SOUTH_TX_TOGGLE; break; default: // otherwise process transmission if (ParticleAttributes.protocol.isSimultaneousTransmissionEnabled) { transmit(&ParticleAttributes.directionOrientedPorts.simultaneous); } else { transmit(&ParticleAttributes.directionOrientedPorts.north); transmit(&ParticleAttributes.directionOrientedPorts.east); transmit(&ParticleAttributes.directionOrientedPorts.south); } __scheduleNextTransmission(); break; } } /** * On local time period passed interrupt. * simulator int. #8 */ //EMPTY_INTERRUPT(LOCAL_TIME_INTERRUPT_VECT) ISR(LOCAL_TIME_INTERRUPT_VECT) { TEST_POINT1_TOGGLE; ParticleAttributes.localTime.numTimePeriodsPassed++; // consider eventually new updateable period duration if (ParticleAttributes.localTime.isTimePeriodInterruptDelayUpdateable) { ParticleAttributes.localTime.timePeriodInterruptDelay = ParticleAttributes.localTime.newTimePeriodInterruptDelay; ParticleAttributes.localTime.isTimePeriodInterruptDelayUpdateable = false; } // consider eventually new local time counter if (ParticleAttributes.localTime.isNumTimePeriodsPassedUpdateable) { ParticleAttributes.localTime.numTimePeriodsPassed = ParticleAttributes.localTime.newNumTimePeriodsPassed; ParticleAttributes.localTime.isNumTimePeriodsPassedUpdateable = false; } LOCAL_TIME_INTERRUPT_COMPARE_VALUE += ParticleAttributes.localTime.timePeriodInterruptDelay; #ifdef LOCAL_TIME_IN_PHASE_SHIFTING_ON_LOCAL_TIME_UPDATE // consider new clock shift to be considered if (ParticleAttributes.localTime.isNewTimerCounterShiftUpdateable) { LOCAL_TIME_INTERRUPT_COMPARE_VALUE = (int32_t) LOCAL_TIME_INTERRUPT_COMPARE_VALUE + ParticleAttributes.localTime.newTimerCounterShift; ParticleAttributes.localTime.isNewTimerCounterShiftUpdateable = false; } #endif if ((ParticleAttributes.localTime.numTimePeriodsPassed >> 6) & 1) { TEST_POINT3_HI; } else { TEST_POINT3_LO; } } /** * Actuator PWM interrupt routine: On compare match toggle wires. * simulator int. #20 */ ISR(ACTUATOR_PWM_INTERRUPT_VECT) { if (ParticleAttributes.actuationCommand.actuators.northLeft) { // on actuate north transmission wire // @pre deactivated: NORTH_TX_LO; NORTH_TX_TOGGLE; } if (ParticleAttributes.actuationCommand.actuators.northRight) { // on actuate north reception wire // @pre deactivated: NORTH_RX_SWITCH_HI; NORTH_RX_SWITCH_TOGGLE; } } //EMPTY_INTERRUPT(__UNUSED_TIMER0_OVERFLOW_INTERRUPT_VECT) //EMPTY_INTERRUPT(__UNUSED_TIMER1_OVERFLOW_INTERRUPT_VECT) //ISR(__UNUSED_TIMER1_OVERFLOW_INTERRUPT_VECT) { // LED_STATUS3_TOGGLE; //} # ifdef SIMULATION const char isrVector0Msg[] PROGMEM = "BAD ISR"; ISR(RESET_VECT) { writeToUart((PGM_P) pgm_read_word(&(isrVector0Msg))); IF_DEBUG_SWITCH_TO_ERRONEOUS_STATE; } ISR(BADISR_vect) { IF_DEBUG_SWITCH_TO_ERRONEOUS_STATE; } # else //EMPTY_INTERRUPT(RESET_VECT) ISR(BADISR_vect) { // TODO: activate code again // blinkInterruptErrorForever(); } # endif
ProgrammableMatter/particle-firmware
src/particle-initial-io-test/main/main.c
<filename>src/particle-initial-io-test/main/main.c<gh_stars>1-10 /** * @author <NAME> 2015 */ #include <util/delay.h> #include <common/common.h> #include <common/PortADefinition.h> #include <common/PortBDefinition.h> #include <common/PortCDefinition.h> FUSES = { .low = LFUSE_DEFAULT, .high = HFUSE_DEFAULT, .extended = EFUSE_DEFAULT, }; void __init(void) { } void toggleOutputPins(void) { ADir setIn Pin4; // rx pin CDir setIn Pin5; // rx pin ADir setOut (Pin0 | Pin1 | Pin2 | Pin3 | Pin5 | Pin6 | Pin7); BDir setOut (Pin0 | Pin1 | Pin2 | Pin3); CDir setOut (Pin0 | Pin1 | Pin2 | Pin3 | Pin4); forever { AOut toggleBit (Pin0 | Pin1 | Pin2 | Pin3 | Pin5 | Pin6 | Pin7); BOut toggleBit (Pin0 | Pin1 | Pin2 | Pin3); COut toggleBit (Pin0 | Pin1 | Pin2 | Pin3 | Pin4); _delay_ms(1.0); } } void toggleReceptionPins(void) { ADir setIn(Pin0 | Pin1 | Pin2 | Pin3 | Pin4 | Pin5 | Pin6 | Pin7); BDir setIn(Pin0 | Pin1 | Pin2 | Pin3); CDir setIn(Pin0 | Pin1 | Pin2 | Pin3 | Pin4 | Pin5); BDir setOut Pin2; ADir setOut Pin2; CDir setOut Pin4; AOut setHi Pin2; COut setHi Pin4; ADir setOut Pin4; // rx pin CDir setOut Pin5; // rx pin forever { BOut toggleBit Pin2; // for trigger AOut toggleBit Pin4; COut toggleBit Pin5; _delay_ms(1.0); } } void toggleMosFets(void) { ADir setIn(Pin0 | Pin1 | Pin2 | Pin3 | Pin4 | Pin5 | Pin6 | Pin7); BDir setIn(Pin0 | Pin1 | Pin2 | Pin3); CDir setIn(Pin0 | Pin1 | Pin2 | Pin3 | Pin4 | Pin5); BDir setOut Pin2; ADir setOut (Pin2 | Pin3); CDir setOut (Pin0 | Pin4); forever { BOut toggleBit Pin2; // for trigger AOut toggleBit (Pin2 | Pin3); COut toggleBit (Pin0 | Pin4); _delay_ms(1.0); } } void togglePinsSubsequently(void) { uint8_t bitMask; ADir setIn(Pin0 | Pin1 | Pin2 | Pin3 | Pin4 | Pin5 | Pin6 | Pin7); BDir setIn(Pin0 | Pin1 | Pin2 | Pin3); CDir setIn(Pin0 | Pin1 | Pin2 | Pin3 | Pin4 | Pin5); forever { bitMask = Pin0; while (bitMask > 0) { ADir setOut bitMask; AOut toggleBit bitMask; _delay_us(500); AOut toggleBit bitMask; _delay_us(500); ADir setIn bitMask; bitMask <<= 1; } bitMask = Pin0; while (bitMask > 0) { BDir setOut bitMask; BOut toggleBit bitMask; _delay_us(500); BOut toggleBit bitMask; _delay_us(500); BDir setIn bitMask; bitMask <<= 1; } bitMask = Pin0; while (bitMask > 0) { CDir setOut bitMask; COut toggleBit bitMask; _delay_us(500); COut toggleBit bitMask; _delay_us(500); CDir setIn bitMask; bitMask <<= 1; } } } int main(void) { // toggleOutputPins(); // toggleReceptionPins(); toggleMosFets(); // togglePinsSubsequently(); }
ProgrammableMatter/particle-firmware
src/particle-simulation-heatwiresrange-test/main/main.c
<reponame>ProgrammableMatter/particle-firmware /** * @author <NAME> 2016 */ #define SIMULATION_HEAT_WIRES_RANGE_TEST #include <uc-core/particle/ParticleLoop.h> int main(void) { processLoop(); return 0; }
amplework/ZAlertView
Example/Pods/Target Support Files/Pods-ZAlertView_Example/Pods-ZAlertView_Example-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_ZAlertView_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_ZAlertView_ExampleVersionString[];