In SX Microcontrollers, SX/B Compiler and SX-Key Tool, Zoot wrote: There are a *lot* of ways to approach this. This is just one way (pseudo code): [code] Interrupt 100000 ' 10us ticks SensorMeasure: sensorTmr = sensorTmr + 1 ' used for timekeeping in main loop (non-interrupt code) IF sensorState = 2 THEN ' taking measurement IF SensorPin = 1 ' say if you are measuring a ping pulse sensorVal = sensorVal + 1 ENDIF ENDIF StepperOut: motorFrame = motorFrame + 1 ' this and 100 below lets you control speed; I leave that to you IF motorFrame > = 100 THEN ' step once per 10 milliseconds (100 * 100us) = 10000us = 10ms motorFrame = 0 IF motor < 128 THEN ' say if 128 = neutral, 255 = full forward; i'm not counting pulses here nor speed here, but you could motorIdx = motorIdx - 1 ELSEIF motor > 128 THEN motorIdx = motorIdx + 1 ENDIF motorIdx = motorIdx & %11 ' 0-3 IF motorIdx = 0 THEN ' move stepper pulse pattern to output pins use your patterns MotorPins = %0001 ELSEIF motorIdx = 1 THEN MotorPins = %1000 ELSEIF motorIdx = 2 THEN MotorPins = %0010 ELSE MotorPins = %0100 ENDIF ENDIF ' if motor frame RETURNINT ' interrupt over Main: ' now in the main line, you can use the timer and set the state for triggering/reading sensors, and setting motor stuff Sensor_State_Stuff: IF sensorState = 0 THEN ' waiting to read... IF sensorTmr >= 200 ' 200 * 10 us = 20ms between reads sensorTmr = 0 ' clear the timer HIGH SensorPin ' trigger Ping ultrasonic sensorState = 1 ' next state ENDIF ENDIF IF sensorState = 1 THEN ' waiting for high pulse on ping to finish triggering the ultrasonics IF sensorTmr >= 1 THEN ' 10us trigger LOW SensorPin ' end pulse IF sensorTmr >=2 THEN ' wait for at least 10us low sensorTmr = 0 ' clear the timer sensorVal = 0 ' clear the last measured value INPUT SensorPin ' make pin input sensorState = 2 ' next state ENDIF ENDIF ENDIF IF sensorState = 2 THEN ' measuring IF SensorPin = 0 THEN ' wait for pulse to end LOW SensorPin ' turn pin off to keep trigger low SensorReading = SensorVal ' move count to stable variable sensorTmr = 0 sensorState = 0 ' back to waiting for next measure cycle ENDIF Motor_Stuff: IF SensorReading < 20 THEN motor = 10 ' turn one direction ELSEIF SensorReading > 200 THEN motor = 245 ELSE motor = 128 ' stop ENDIF Done: GOTO Main [/code] The idea here is your main loop keeps moving through and checking the timers or setting parameters for the interrupt. Even if your main loop "lags", it doesn't matter, the motor will continue to pulse, and the last sensor reading is available, etc. ---------- End of Message ---------- You can view the post on-line at: http://forums.parallax.com/forums/default.aspx?f=7&p=1&m=394074#m394080 Need assistance? Send an email to the Forum Administrator at forumadmin@parallax.com The Parallax Forums are powered by dotNetBB Forums, copyright 2002-2009 (http://www.dotNetBB.com)