Usb Code c Chuẩn
Usb Code c Chuẩn
#define MODE_RED 1
#define MODE_YELLOW 2
#define in_size 64
#define out_size 64
if (USBIF_bit) {
USBIF_bit = 0;
USB_Interrupt_Proc();
}
}
char checkButtons() {
static unsigned char prevState = 0b000;
unsigned char currentState = (PORTB & 0b00000111);
prevState = currentState;
return 0;
}
void switchLight(unsigned char red, unsigned char yellow, unsigned char green) {
LATE0_bit = red;
LATE1_bit = yellow;
LATE2_bit = green;
}
void autoMode() {
static unsigned long stateStartTime = 0;
unsigned long currentTime = millis();
if (checkButtons()) return;
switch (state) {
case 0:
switchLight(1, 0, 0);
writebuff[0] = 'D';
HID_Write(&writebuff, out_size);
stateStartTime = currentTime;
state = 1;
break;
case 1:
if (currentTime - stateStartTime >= T_RED) {
switchLight(0, 1, 0);
writebuff[0] = 'V';
HID_Write(&writebuff, out_size);
stateStartTime = currentTime;
state = 2;
}
break;
case 2:
if (currentTime - stateStartTime >= T_YELLOW) {
switchLight(0, 0, 1);
writebuff[0] = 'X';
HID_Write(&writebuff, out_size);
stateStartTime = currentTime;
state = 3;
}
break;
case 3:
if (currentTime - stateStartTime >= T_GREEN) {
state = 0;
}
break;
}
}
void yellowBlinkMode() {
unsigned long currentTime = millis();
if (currentTime - lastUpdateTime >= T_BLINK) {
lastUpdateTime = currentTime;
lightState = !lightState;
switchLight(0, lightState, 0);
writebuff[0] = lightState ? 'O' : 'F';
HID_Write(&writebuff, out_size);
}
}
void processUSB() {
if (HID_Read()) {
LATE1_bit = 1;
switch (readbuff[0]) {
case 'A':
currentMode = MODE_RED;
writebuff[0] = 'D';
break;
case 'B':
currentMode = MODE_YELLOW;
writebuff[0] = 'V';
break;
case 'C':
currentMode = MODE_AUTO;
state = 0; // Reset ch? d? t? d?ng v? dèn d?
writebuff[0] = 'A';
break;
HID_Write(&writebuff, out_size);
LATE1_bit = 0;
}
}
void setupTimer0() {
T0CON = 0b11000011;
TMR0L = 100;
INTCON.TMR0IE = 1;
INTCON.TMR0IF = 0;
}
void main() {
ADCON1 |= 0x0F;
CMCON |= 7;
PORTB = 0x00;
LATB = 0x00;
TRISB0_bit = 1;
TRISB1_bit = 1;
TRISB2_bit = 1;
PORTE = 0x00;
LATE = 0x00;
TRISE0_bit = 0;
TRISE1_bit = 0;
TRISE2_bit = 0;
delay_ms(100);
UPUEN_bit = 1;
FSEN_bit = 1;
HID_Enable(&readbuff, &writebuff);
USBIF_bit = 0;
USBIE_bit = 1;
GIE_bit = 1;
PEIE_bit = 1;
setupTimer0();
lastUpdateTime = millis();
while (1) {
checkButtons();
processUSB();
switch (currentMode) {
case MODE_AUTO:
autoMode();
break;
case MODE_RED:
switchLight(1, 0, 0);
break;
case MODE_YELLOW:
yellowBlinkMode();
break;
}
}
}