Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * main.c
- *
- * Created on: 18.06.2011
- * Author: peka
- */
- //#define F_CPU = 20MHz //(ext Crystal)
- // Defines
- #define setBit(ADDRESS, BIT) (ADDRESS |= (1<<BIT))
- #define clrBit(ADDRESS, BIT) (ADDRESS &= ~(1<<BIT))
- #define tglBit(ADDRESS, BIT) (ADDRESS ^= (1<<BIT))
- #define getBit(ADDRESS, BIT) ((ADDRESS & (1<<BIT))?1:0)
- #define lowByte(WORD) ((uint8_t)(WORD))
- #define highByte(WORD) ((uint8_t)(((uint16_t)(WORD)) >> 8))
- #define getWord(HIGH,LOW) (((uint16_t)HIGH << 8) | LOW)
- #define TWI_ADDR 20 <<1 // --> Address 20
- // Includes
- #include <avr/io.h>
- #include <avr/interrupt.h>
- #include "usiTwiSlave.h" //I2C Lib
- // Global Vars
- volatile uint16_t timerCounter = 0;
- volatile uint16_t pulseTimer = 0;
- volatile uint8_t servoIndex = 0;
- volatile uint16_t servoPos[] =
- { 0, 0, 0, 0, 0, 0, 0, 0 };
- volatile uint16_t syncTime = 0;
- volatile uint8_t updateFlag = 0;
- // Main Program
- int main(void)
- {
- // Timer 1
- setBit(TCCR1, CS10);
- setBit(TCCR1, CS12); // Prescaler 16 - 800ns Auflösung
- setBit(TIMSK, OCIE1A); // Timer/Counter1, Output Compare A Match Interrupt Enable
- OCR1A = 250; // 200µs
- // RCRx Interrupt
- clrBit(DDRB, PB1); //Input
- setBit(PORTB, PB1); //int. Pullup
- setBit(GIMSK, PCIE); //Pin Change Interrupt Enable
- PCMSK = 0x00;
- setBit(PCMSK, PCINT1); //Enable PCINT only on PB1
- // TWI
- usiTwiSlaveInit(TWI_ADDR); // TWI starten
- for (int i = 0; i < 24; i++) // Buffer füllen
- txbuffer[i] = 0xFF;
- // Interrupts aktivieren
- sei();
- // Hauptprogrammschleife
- while (1)
- {
- while (updateFlag == 0)
- {
- ; //warte auf neue servoPosition
- }
- txbuffer[0] = 0; //dataReady Flag
- for (uint8_t i = 0; i < 7; i++)
- {
- txbuffer[1 + 2 * i] = highByte(servoPos[i]);
- txbuffer[1 + 2 * i + 1] = lowByte(servoPos[i]);
- }
- txbuffer[17] = highByte(syncTime);
- txbuffer[18] = lowByte(syncTime);
- txbuffer[0] = 1; //dataReady Flag
- updateFlag = 0;
- }
- }
- ISR( TIMER1_COMPA_vect )
- {
- TCNT1 = 0;
- pulseTimer++; // 1 tick = 200µs
- }
- ISR( PCINT0_vect )
- {
- if (getBit(PINB, PB1) == 0) //reagiere nur auf fallende Flanke
- {
- uint16_t pulseTimerFraction = 4 * TCNT1 / 5;
- uint16_t pulseTime = pulseTimer * 200 + pulseTimerFraction; // 1 tick = 1µs
- TCNT1 = 0; // timer zurücksetzen
- pulseTimer = 0;
- if (pulseTime > 3000) //Pulspause > 3000µs --> Sync
- {
- servoIndex = 0; //nächster Puls wird wieder die länge von Servo0 angeben
- syncTime = pulseTime;
- updateFlag = 1; //servowerte dürfen in der hauptschleife ins i2c buffer geschrieben werden
- }
- else if (servoIndex < 8)
- {
- servoPos[servoIndex] = pulseTime;
- servoIndex++; //nächster Puls wird nächsten Servowert geben oder sync sein.
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement