#include "picsys18.h"
// 整備中

void
setup()
{
	pinMode(LED1, OUTPUT) ;
	digitalWrite(LED1, LOW) ;

	pinMode(CN4, OUT_SERVO1) ;

	pinMode(SW1, INPUT) ;
	pinMode(SW2, INPUT) ;
	pinMode(SW3, INPUT) ;

	USB_begin() ;
}


int cIndex = 0 ;
char buff[50] ;
BOOL eol = FALSE ;

//byte dxIndex[] = {DX0, DX1, DX2, DX3, DX4, DX5, DX6, DX7, DX8, DX9, DX10, DX11, DX12, DX13, DX14, DX15, DX16, DX17, DX18, DX19} ;
//byte axIndex[] = {AX0, AX1, AX2, AX3, AX4, AX5} ;
BYTE ledIndex[] = {NULL, LED1} ;
BYTE swIndex[] = {NULL, SW1, SW2, SW3} ;
BYTE servoIndex[] = {NULL, CN4} ;

char
posParam(void)
{
	int i ;
	for (i = 1 ; buff[i]; i++) {
		if (buff[i] == ':') {
			return i+1 ;
		}
	}
	
	return 0 ;	
}	

void
loop()
{
    int c, v, i, j ;
    float temp ; // 温度の計算は実数で
	
	if (USB_attached() && USB_ready(30)) {
		while (USB_available()) {
			c = USB_getc() ;
			USB_putc(c) ;
			if (c == '\r') {
				USB_putc('\n') ;
				buff[cIndex] = '\0' ;
				eol = TRUE ;
			} else {
				buff[cIndex++] = c ;
				eol = FALSE ;
			}					
		}		
		
		if (eol) {
			switch (buff[0]) {
				case 'h':
				case 'H':
					USB_putrs("PIC18F-MOD-2553") ;
					USB_putrs("\r\nUP:") ;
					USB_puti(millis()) ;
					USB_putrs("\r\nBR:") ;
					USB_puti(USB_baudrate()) ;
					break ;
#if 0
				case 'd':
				case 'D':
					i = atoi(&buff[1]) ;
					if ((j = posParam()) == 0) {
						USB_puti(digitalRead(dxIndex[i])) ;
					} else {
						digitalWrite(dxIndex[i], atoi(&buff[j])) ;
					}
					break ;
				case 'a':
				case 'A':
					i = atoi(&buff[1]) ;
					USB_puti(analogRead(axIndex[i])) ;
					break ;
#endif
				case 'l':
				case 'L':
					i = atoi(&buff[1]) ;
					if ((j = posParam()) == 0) {
						USB_puti(digitalRead(ledIndex[i])) ;
					} else {
						digitalWrite(ledIndex[i], atoi(&buff[j])) ;
					}
					break ;
				case 's':
				case 'S':
					i = atoi(&buff[1]) ;
					USB_putc(digitalRead(swIndex[i]) ? '0' : '1') ;
					break ;
				case 'v':
				case 'V':
					i = atoi(&buff[1]) ;
					if ((j = posParam()) == 0) {
						USB_puti(digitalRead(servoIndex[i])) ;
					} else {
						digitalWrite(servoIndex[i], atoi(&buff[j])) ;
					}
					break ;
			}
			
			USB_putrs("\r\n") ;
			cIndex = 0 ;
			eol = FALSE ;
		}
	}
	
	digitalWrite(LED1, (millis()/500) & 1) ;
}
