#include #include #include int motor1_Stop = 63; int motor1_Back = 64; int motor1_Forward = 128; int motor2_Stop = 252; int motor2_Back = 1; int motor2_Forward = 2; int motor1First = 0; int packetSignature = 108; int pwmMax; int pwm = 0; int PWMFACTOR = 5; int motor1Speed = 0; int motor2Speed = 0; int motor1Direction = 0; int motor2Direction = 0; //int packetsRecieved = 0; int portBData = 0; unsigned long lastPacketCounterTics; unsigned char lastPacketData = 0; void main(void) { // Init USART driver USART_Init(200); // 8 MHz, 2400 BAUD (4800=100) //set PORT B and C for out DDRC = 0xff; DDRB = 0xff; // Set PWM setting pwmMax = 3 * PWMFACTOR; int data; while(1) { data = (int)USART_Recieve(); // Wait for serial data Styrning(data); } return 0; } // Lights Control void Styrning(int data) { // Car lights control int lightData = data & 3; switch(lightData) { // No lights case 0: PORTC = PORTC & 252; break; // Activate brakes case 1: PORTC = PORTC | 2; break; // Activate lights case 2: PORTC = PORTC | 1; break; // Activate both lights/brakes case 3: PORTC = PORTC | 3; break; } // Motor 1 if ((data & 128) == 128) // Bit 7=1 motor1Direction = 1; else motor1Direction = 0; if ((data & 96) == 0) motor1Speed = 0; // Bit 5,6= 0,0 if ((data & 96) == 32) motor1Speed = 1; // Bit 5,6= 0,1 if ((data & 96) == 64) motor1Speed = 2; // Bit 5,6= 1,0 if ((data & 96) == 96) motor1Speed = 3; // Bit 5,6= 1,1 // Motor 2 if ((data & 16) == 16) // Bit 4=1 motor2Direction = 1; else motor2Direction = 0; if ((data & 12) == 0) motor2Speed = 0; // Bit 2,3= 0,0 if ((data & 12) == 4) motor2Speed = 1; // Bit 2,3= 0,1 if ((data & 12) == 8) motor2Speed = 2; // Bit 2,3= 1,0 if ((data & 12) == 12) motor2Speed = 3; // Bit 2,3= 1,1 if (((motor1Speed > 0) || (motor2Speed > 0)) && ((motor1Direction == 0) || (motor2Direction == 0))) { if (motor1Speed != 3 && motor2Speed != 3) PORTC = PORTC | 128; } else { PORTC = PORTC & 127; } if (motor1Speed == 0 || motor2Speed == 0) PORTC = PORTC & 253; } // Poll for data on USART unsigned char USART_Recieve (void) { int dataPacketState = 0; unsigned char dataPacket; unsigned char packet1 = 0; unsigned char packet2 = 0; int loopDelay = 0; lastPacketCounterTics = 1000000; //Size? // Poll for data on USART while (1) { while (1) { // Shut down motor when no packets has been recieved //if ((loopDelay >= 8) && lastPacketCounterTics > 0) //{ // if (lastPacketCounterTics > 0) lastPacketCounterTics--; // if (lastPacketCounterTics == 1) // { // PORTB = 0; // portBData = 0; // } // loopDelay = 0; //} //loopDelay++; if (motor1First == 1) { PWM_M2(pwm); PWM_M1(pwm); motor1First = 0; } else { PWM_M1(pwm); PWM_M2(pwm); motor1First = 1; } // Increase PWM ramp value. If the max value is reached, start over again pwm++; if (pwm > pwmMax) pwm = 0; if ((UCSRA & ( 1<>8); UBRRL = (unsigned char)baud; UCSRB = (1<