mr_Gish 0 6 февраля, 2014 Опубликовано 6 февраля, 2014 (изменено) · Жалоба Доброго времени суток! Имеется самодельная плата для измерения однородности магнитного поля на мк AT90s8535, и написан код, не мой. Помогите пожалуйста разобраться и найти ошибку. Работой устройства управляет микропроцессор Atmel At90s8535, который соединен с компьютером через последовательный промышленный интерфейс. Для настройки, контроля и возможности автономной работы данного устройства предусмотрено ручное управление, которое представляет собой набор кнопок и жидкокристаллический индикатор. Так же микропроцессор управляет платой мультиплексоров. Для подключения нужного контура датчика однородности драйвер nmrtmux.dll формирует команду, которая передается через интерфейс RS232 на микропроцессор. Команда содержит номер датчика, который нужно прокомутировать. Микропроцессор преобразует номер контура по таблице соответствия в коды каналов Master.mux, Slave.mux мультиплексоров. Далее микропроцессор по интерфейсу SPI записывает соответствующие коды на плату мультиплексоров. На жидко кристаллическом индикаторе отображается номер активного контура. Кнопки ручного управления имеют следующее предназначение: кнопка ZERO – выбирает нулевой контур, кнопка +1 - подключает следующий контур, кнопка +10 – увеличивает номер контура на десять, кнопка WR – осуществляет повторная запись заданного кода на плату мультиплексоров. Светодиоды отображают текущий режим работы. Один светодиод показывает, выполнение команды поступающей с компьютера, второй светодиод информирует о передаче данных на плату мультиплексоров. На данный момент, код при компиляции не выдает ошибок, при прошивки в МК, у МК ноль реакции. Я конечно понимаю, что код большой, я новичок в этом деле, посоветуйте мне, с чего начать и как можно проверить устройство на работоспособность. Схема прикреплена ниже. #ifndef ENABLE_BIT_DEFINITIONS #define ENABLE_BIT_DEFINITIONS // включает битовые определения в файле iom128.h #endif #include <io8535v.h> #include <macros.h> #include <stdlib.h> char buf[17]; char keys; char coil; extern const unsigned char lut[];// внешний массив char rx_buf[16]; char rx_pos; // IRQ handlers #pragma interrupt_handler irqRxc:12 //прототип процедуры обработки прерываний void irqRxc(void) { char v=UDR;// UDR - UART ввода/вывода регистров if(rx_pos<=16) rx_buf[rx_pos++]=v; } void InitUart(void) //подключение сом порта { UBRR=12; //bps=34800 registr ckorosti obmena UART // скорость передачи 64 стр UCR=(1<<TXEN)|(1<<RXEN)|(1<<RXCIE); //|(1<<TXCIE) registr upravl UART 63 стр rx_pos=0; } void TxChar(char ch) { while ((USR & 0x20) != 0x20); // пустой буфер передачи // USR - передатчик готов к приему нового сигнала UDR = ch; // чтение char UDR - чтение из регистра while ((USR & 0x40) != 0x40); // Wait for the char to be cue off ??? USR |= 0x40; //очистка флага //передача завершена void Send(char *sz) { while(*sz) TxChar(*sz++); } char rcvlen; char SCmp(char *cmd,char cmdlen) { char len=rcvlen; char i; if(cmdlen<len) len=cmdlen; for(i=0;i<len;i++) if(rx_buf[i]!=cmd[i]) return 2; //рассоглосование ??? if(rcvlen<cmdlen) return 0; //continue rcv return 1; //match } char Rx_Cmp(char *cmd,char *val,char vlen) { char cmdlen=0,rv,j; char *pcmd; rcvlen=rx_pos; if(!rcvlen) return 0; pcmd=cmd; while(*pcmd++) cmdlen++; // Send(cmd); // Send(" - "); rv=SCmp(cmd,cmdlen); if(!rv) { // Send("continue\r\n"); return 0; } if(rv==2) { // Send("no match\r\n"); return 2; } if(vlen) { if(rcvlen<cmdlen+vlen) { // Send("SCmp - w. v continue rcv\r\n"); return 0; //continue rcv } for(j=0;j<vlen;j++) val[j]=rx_buf[cmdlen+j]; rx_pos=0; // Send("match cmd w. val\r\n"); return 1; //match cmd w. val } rx_pos=0; // Send("match cmd w/o val\r\n"); return 1; //match cmd w/o val } #include <io8535v.h> #include <macros.h> #include <stdlib.h> void GotoXY(unsigned char,unsigned char); void WriteStrLCDConst(const char *); void format(const char *tag,char num,char len3); #define SCLK_0 PORTA|=(1<<PA0) // мультиплексоры #define SCLK_1 PORTA&=~(1<<PA0) #define DIN_M0 PORTA|=(1<<PA6) #define DIN_M1 PORTA&=~(1<<PA6) #define DIN_S0 PORTA|=(1<<PA1) #define DIN_S1 PORTA&=~(1<<PA1) #define SYNC_0 PORTA|=(1<<PA2) #define SYNC_1 PORTA&=~(1<<PA2) #define DIN_M(on) if(on) DIN_M1; else DIN_M0; #define DIN_S(on) if(on) DIN_S1; else DIN_S0; char coil; extern const unsigned char lut[]; //#define SPI_DELAY for(int k=0;k<100;k++) asm("nop"); void SPI_DELAY(void) { int k; for(k=0;k<100;k++) asm("nop"); } void InitMuxIo(void) { DDRA|=(1<<PA0); // судя по схеме, подключение к мультиплексорам DDRA|=(1<<PA6); DDRA|=(1<<PA1); DDRA|=(1<<PA2); SCLK_0; DIN_M0; DIN_S0; SYNC_1; } void cahnnel_lut(char *m,char *s) { if(coil<103) { *m=lut[coil*2]; *s=lut[coil*2+1]; } else { *m=lut[0]; *s=lut[1]; } GotoXY(1,2); if(!coil) { WriteStrLCDConst("Name=4-17 @"); return; } else if(coil<=14) format("Name=1-",coil,0); else if(coil<=14*2) format("Name=2-",coil-14,0); else if(coil<=14*3) format("Name=3-",coil-14*2,0); else if(coil<=14*4) format("Name=4-",coil-14*3,0); else if(coil<=14*5) format("Name=5-",coil-14*4,0); else if(coil<=14*6) format("Name=6-",coil-14*5,0); else if(coil<=14*7) format("Name=7-",coil-14*6,0); else if(coil<=14*7+2) format("Name=4-",coil-14*7+14,0); else if(coil<=14*7+4) format("Name=4-",coil-14*7+14+1,0); else { WriteStrLCDConst("Name=Unk"); return; } WriteStrLCDConst(buf); } void spi_mux_code_write(void) { char m,s,i; cahnnel_lut(&m,&s); m--;s--; //begin SYNC_1; SCLK_0; DIN_M0; DIN_S0; SPI_DELAY(); SYNC_0; SPI_DELAY(); SPI_DELAY(); SPI_DELAY(); SYNC_1; SPI_DELAY(); //write 3 first bits SCLK_1; SPI_DELAY(); SCLK_0; SPI_DELAY(); SCLK_1; SPI_DELAY(); SCLK_0; SPI_DELAY(); SCLK_1; SPI_DELAY(); SCLK_0; SPI_DELAY(); for(i=0;i<5;i++) { DIN_M(m&(1<<4-i)); DIN_S(s&(1<<4-i)); SPI_DELAY(); SCLK_1; SPI_DELAY(); SCLK_0; SPI_DELAY(); } } //************************************** // D E F I N E //************************************** // User dependent BEGIN #include <io8535v.h> #include <macros.h> #include <stdlib.h> #define D7 (1<<PC1) #define D6 (1<<PC2) #define D5 (1<<PC3) #define D4 (1<<PC4) #define E (1<<PC6) #define RW (1<<PC5) #define RS (1<<PC7) #define LCDPIN (/**(volatile unsigned char *)*/PINC) // PIN register #define LCDDDR (/**(volatile unsigned char *)*/DDRC) // Data Direction Register #define LCDPORT (/**(volatile unsigned char *)*/PORTC) // PORT // User dependent END //************************************** // P R O T O T Y P E //************************************** void InitLCD(void); void ClrLCD(); void GotoXY(unsigned char,unsigned char); void WriteStrLCD(char *); void WriteStrLCDConst(const char *); void WriteByteLCD(char); void WriteLCD(unsigned char,unsigned char); void Delay_50us(int Delay); //********************************************************* // LCD Code //********************************************************* /********************************************************** Name: void ClrLCD(void) Description: Clear the LCD Input: none Output: none Misc: **********************************************************/ void ClrLCD() { WriteLCD(0,0x01); // Clear display Delay_50us(50); } /********************************************************** Name: GotoXY(unsigned char x, unsigned char y) Description: Position cursor on the LCD at X & Y location Input: X -> X position on the LCD Y -> Y position on the LCD Output: none Misc: **********************************************************/ void GotoXY(unsigned char x,unsigned char y) { unsigned char address; x--; if (y > 1) address = 64 + x; else address = x; WriteLCD(0,address | 0x80); } /********************************************************** Name: WtireByteLCD(char byte) Description: Write a byte on the LCD at cursor position Input: byte Output: none Misc: **********************************************************/ void WriteByteLCD(char byte) { char tmp; tmp = byte & 0xf0; tmp = tmp >> 4; tmp += 0x30; if (tmp > 0x39) tmp += 0x07; WriteLCD(1,tmp); tmp = byte & 0x0f; tmp += 0x30; if (tmp > 0x39) tmp += 0x07; WriteLCD(1,tmp); } /********************************************************** Name: void WriteStrLCD(char *ptr) Description: Write a string from RAM on the LCD Input: string pointer Output: none Misc: **********************************************************/ void WriteStrLCD(char *ptr) { unsigned char i; for (i=1;i<41;i++) { if (*ptr == 0x00) break; WriteLCD(1,*ptr); *ptr++ = 0x00; } } /********************************************************** Name: void WriteStrLCDConst(const char *ptr) Description: Write a constant string on the LCD Input: string pointer Output: none Misc: **********************************************************/ void WriteStrLCDConst(const char *ptr) { unsigned char i; for (i=1;i<41;i++) { if (*ptr == 0x00) break; WriteLCD(1,*ptr++); } } /********************************************************** Name: void WriteLCD(unsigned char rs, unsigned char ch) Description: Write a byte in rs of the LCD Input: rs -> Register select ch -> byte to write Output: none Misc: **********************************************************/ void WriteLCD(unsigned char rs,unsigned char ch) { unsigned char Stat; Stat = LCDPIN & 0x01; LCDPORT = Stat; if ((ch & 0x80) == 0x80) LCDPORT |= D7; if ((ch & 0x40) == 0x40) LCDPORT |= D6; if ((ch & 0x20) == 0x20) LCDPORT |= D5; if ((ch & 0x10) == 0x10) LCDPORT |= D4; if (rs == 1) LCDPORT |= RS; LCDPORT |= E; LCDPORT &= ~E; Delay_50us(1); LCDPORT = Stat; if ((ch & 0x08) == 0x08) LCDPORT |= D7; if ((ch & 0x04) == 0x04) LCDPORT |= D6; if ((ch & 0x02) == 0x02) LCDPORT |= D5; if ((ch & 0x01) == 0x01) LCDPORT |= D4; if (rs == 1) LCDPORT |= RS; LCDPORT |= E; LCDPORT &= ~E; Delay_50us(1); } /********************************************************** Name: void Delay_50us(int Delay) Description: Delay of 50 us with a 4Mhz resonator Input: Delay X x 50us Output: none Misc: **********************************************************/ void Delay_50us(int Delay) { int i,j; for (i=0;i<Delay;i++) { for (j=1;j<20*10;j++) asm("WDR"); } } /********************************************************** Name: void InitLCD(void) Description: Initialize LCD in 4bit mode Input: none Output: none Misc: **********************************************************/ void InitLCD(void) { LCDDDR = D7 + D6 + D5 + D4 + E + RS + RW; LCDPORT = !(D7 + D6 + D5 + D4 + E + RS + RW); Delay_50us(340); LCDPORT = (D5 + D4); // Function Set 8 bit 3 time LCDPORT |= E; LCDPORT &= ~E; Delay_50us(100); LCDPORT |= E; LCDPORT &= ~E; Delay_50us(100); LCDPORT |= E; LCDPORT &= ~E; Delay_50us(100); LCDPORT = D5; // Function Set 4 bit LCDPORT |= E; LCDPORT &= ~E; Delay_50us(100); WriteLCD(0,0x28); // 2 line Delay_50us(100); WriteLCD(0,0x0c); // Display ON Cursor OFF Blink OFF Delay_50us(100); WriteLCD(0,0x01); // Clear display Delay_50us(50); WriteLCD(0,0x06); // Cursor INC Shift OFF Delay_50us(100); } /* */ void LedA(char on) { if(on) PORTB&=~1; else PORTB|=1; } void LedB(char on) { if(on) PORTB&=~2; else PORTB|=2; } void format(const char *tag,char num,char len3) { char *p=buf; if(tag) while(*tag) *p++=*tag++; if(len3) *p++=num/100+'0'; *p++=(num%100)/10+'0'; *p++=num%10+'0'; *p++=0; } void main( void ) { char led=0,key; char rv,cnt=0; DDRB=19; // (Data Derection Register для порта В) задает направление ножек ввода/вывода LedA(0); // выключает первый светодиод LedB(0); // выключает второй светодиод keys=PIND; // записывается состояние кнопок coil=0; //номер контура, который должен быть подключен InitMuxIo(); // Настройка ножек ввода/вывода для управления мультиплексором InitUart(); // инициализация UART InitLCD(); // инициализация ЖКИ ClrLCD(); // очищение ЖКИ GotoXY(1,1);// установка курсора в позицию (1,1) дисплея #ifndef ENABLE_BIT_DEFINITIONS #define ENABLE_BIT_DEFINITIONS // Enable the bit definitions in the iom128.h file #endif #include <io8535v.h> #include <macros.h> #include <stdlib.h> char buf[17]; char keys; char coil; extern const unsigned char lut[]; char rx_buf[16]; char rx_pos; // IRQ handlers #pragma interrupt_handler irqRxc:12 void irqRxc(void) { char v=UDR; if(rx_pos<=16) rx_buf[rx_pos++]=v; } void InitUart(void) { UBRR=12; //bps=34800 регистр, в котором устанавливается скорость передачи данных UCR=(1<<TXEN)|(1<<RXEN)|(1<<RXCIE); //|(1<<TXCIE) registr upravl UART //:::: TXEN - включает модуль передачи данных :::: RXEN - включает прием, если 0 - выключен, 1 - включен rx_pos=0; // обнуляет индекс в приемном массиве } void TxChar(char ch) { while ((USR & 0x20) != 0x20); // Wait for empty transmit buffer UDR = ch; // Write char while ((USR & 0x40) != 0x40); // Wait for the char to be cue off USR |= 0x40; // Clear Tx finish flag } void Send(char *sz) { while(*sz) TxChar(*sz++); } char rcvlen; // длина принятых данных char SCmp(char *cmd,char cmdlen) { char len=rcvlen; char i; if(cmdlen<len) len=cmdlen; for(i=0;i<len;i++) if(rx_buf[i]!=cmd[i]) return 2; //mismath if(rcvlen<cmdlen) return 0; //continue rcv return 1; //match } char Rx_Cmp(char *cmd,char *val,char vlen) // функция, которая производит проверку на наличие // команды в приемном буфере. имеет три параметра : символ команды, // адрес буфера аргумента команды, размер буфера аргумента команды { char cmdlen=0,rv,j; char *pcmd; rcvlen=rx_pos; if(!rcvlen) return 0; pcmd=cmd; while(*pcmd++) cmdlen++; // Send(cmd); // Send(" - "); rv=SCmp(cmd,cmdlen); if(!rv) { // Send("continue\r\n"); return 0; } if(rv==2) { // Send("no match\r\n"); return 2; } if(vlen) { if(rcvlen<cmdlen+vlen) { // Send("SCmp - w. v continue rcv\r\n"); return 0; //continue rcv } for(j=0;j<vlen;j++) val[j]=rx_buf[cmdlen+j]; rx_pos=0; // Send("match cmd w. val\r\n"); return 1; //match cmd w. val } rx_pos=0; // Send("match cmd w/o val\r\n"); return 1; //match cmd w/o val } #include <io8535v.h> #include <macros.h> #include <stdlib.h> void GotoXY(unsigned char,unsigned char); void WriteStrLCDConst(const char *); void format(const char *tag,char num,char len3); #define SCLK_0 PORTA|=(1<<PA0) #define SCLK_1 PORTA&=~(1<<PA0) #define DIN_M0 PORTA|=(1<<PA6) #define DIN_M1 PORTA&=~(1<<PA6) #define DIN_S0 PORTA|=(1<<PA1) #define DIN_S1 PORTA&=~(1<<PA1) #define SYNC_0 PORTA|=(1<<PA2) #define SYNC_1 PORTA&=~(1<<PA2) #define DIN_M(on) if(on) DIN_M1; else DIN_M0; #define DIN_S(on) if(on) DIN_S1; else DIN_S0; char coil; extern const unsigned char lut[]; //#define SPI_DELAY for(int k=0;k<100;k++) asm("nop"); void SPI_DELAY(void) { int k; for(k=0;k<100;k++) asm("nop"); } void InitMuxIo(void) { DDRA|=(1<<PA0); DDRA|=(1<<PA6); DDRA|=(1<<PA1); DDRA|=(1<<PA2); SCLK_0; DIN_M0; DIN_S0; SYNC_1; } void cahnnel_lut(char *m,char *s) { if(coil<103) { *m=lut[coil*2]; *s=lut[coil*2+1]; } else { *m=lut[0]; *s=lut[1]; } GotoXY(1,2); if(!coil) { WriteStrLCDConst("Name=4-17 @"); return; } else if(coil<=14) format("Name=1-",coil,0); else if(coil<=14*2) format("Name=2-",coil-14,0); else if(coil<=14*3) format("Name=3-",coil-14*2,0); else if(coil<=14*4) format("Name=4-",coil-14*3,0); else if(coil<=14*5) format("Name=5-",coil-14*4,0); else if(coil<=14*6) format("Name=6-",coil-14*5,0); else if(coil<=14*7) format("Name=7-",coil-14*6,0); else if(coil<=14*7+2) format("Name=4-",coil-14*7+14,0); else if(coil<=14*7+4) format("Name=4-",coil-14*7+14+1,0); else { WriteStrLCDConst("Name=Unk"); return; } WriteStrLCDConst(buf); } void spi_mux_code_write(void) { char m,s,i; cahnnel_lut(&m,&s); m--;s--; //begin SYNC_1; SCLK_0; DIN_M0; DIN_S0; SPI_DELAY(); SYNC_0; SPI_DELAY(); SPI_DELAY(); SPI_DELAY(); SYNC_1; SPI_DELAY(); //write 3 first bits SCLK_1; SPI_DELAY(); SCLK_0; SPI_DELAY(); SCLK_1; SPI_DELAY(); SCLK_0; SPI_DELAY(); SCLK_1; SPI_DELAY(); SCLK_0; SPI_DELAY(); for(i=0;i<5;i++) { DIN_M(m&(1<<4-i)); DIN_S(s&(1<<4-i)); SPI_DELAY(); SCLK_1; SPI_DELAY(); SCLK_0; SPI_DELAY(); } } //************************************** // D E F I N E //************************************** // User dependent BEGIN #include <io8535v.h> #include <macros.h> #include <stdlib.h> #define D7 (1<<PC1) #define D6 (1<<PC2) #define D5 (1<<PC3) #define D4 (1<<PC4) #define E (1<<PC6) #define RW (1<<PC5) #define RS (1<<PC7) #define LCDPIN (/**(volatile unsigned char *)*/PINC) // PIN register #define LCDDDR (/**(volatile unsigned char *)*/DDRC) // Data Direction Register #define LCDPORT (/**(volatile unsigned char *)*/PORTC) // PORT // User dependent END //************************************** // P R O T O T Y P E //************************************** void InitLCD(void); void ClrLCD(); void GotoXY(unsigned char,unsigned char); void WriteStrLCD(char *); void WriteStrLCDConst(const char *); void WriteByteLCD(char); void WriteLCD(unsigned char,unsigned char); void Delay_50us(int Delay); //********************************************************* // LCD Code //********************************************************* /********************************************************** Name: void ClrLCD(void) Description: Clear the LCD Input: none Output: none Misc: **********************************************************/ void ClrLCD() { WriteLCD(0,0x01); // Clear display Delay_50us(50); } /********************************************************** Name: GotoXY(unsigned char x, unsigned char y) Description: Position cursor on the LCD at X & Y location Input: X -> X position on the LCD Y -> Y position on the LCD Output: none Misc: **********************************************************/ void GotoXY(unsigned char x,unsigned char y) { unsigned char address; x--; if (y > 1) address = 64 + x; else address = x; WriteLCD(0,address | 0x80); } /********************************************************** Name: WtireByteLCD(char byte) Description: Write a byte on the LCD at cursor position Input: byte Output: none Misc: **********************************************************/ void WriteByteLCD(char byte) { char tmp; tmp = byte & 0xf0; tmp = tmp >> 4; tmp += 0x30; if (tmp > 0x39) tmp += 0x07; WriteLCD(1,tmp); tmp = byte & 0x0f; tmp += 0x30; if (tmp > 0x39) tmp += 0x07; WriteLCD(1,tmp); } /********************************************************** Name: void WriteStrLCD(char *ptr) Description: Write a string from RAM on the LCD Input: string pointer Output: none Misc: **********************************************************/ void WriteStrLCD(char *ptr) { unsigned char i; for (i=1;i<41;i++) { if (*ptr == 0x00) break; WriteLCD(1,*ptr); *ptr++ = 0x00; } } /********************************************************** Name: void WriteStrLCDConst(const char *ptr) Description: Write a constant string on the LCD Input: string pointer Output: none Misc: **********************************************************/ void WriteStrLCDConst(const char *ptr) { unsigned char i; for (i=1;i<41;i++) { if (*ptr == 0x00) break; WriteLCD(1,*ptr++); } } /********************************************************** Name: void WriteLCD(unsigned char rs, unsigned char ch) Description: Write a byte in rs of the LCD Input: rs -> Register select ch -> byte to write Output: none Misc: **********************************************************/ void WriteLCD(unsigned char rs,unsigned char ch) { unsigned char Stat; Stat = LCDPIN & 0x01; LCDPORT = Stat; if ((ch & 0x80) == 0x80) LCDPORT |= D7; if ((ch & 0x40) == 0x40) LCDPORT |= D6; if ((ch & 0x20) == 0x20) LCDPORT |= D5; if ((ch & 0x10) == 0x10) LCDPORT |= D4; if (rs == 1) LCDPORT |= RS; LCDPORT |= E; LCDPORT &= ~E; Delay_50us(1); LCDPORT = Stat; if ((ch & 0x08) == 0x08) LCDPORT |= D7; if ((ch & 0x04) == 0x04) LCDPORT |= D6; if ((ch & 0x02) == 0x02) LCDPORT |= D5; if ((ch & 0x01) == 0x01) LCDPORT |= D4; if (rs == 1) LCDPORT |= RS; LCDPORT |= E; LCDPORT &= ~E; Delay_50us(1); } /********************************************************** Name: void Delay_50us(int Delay) Description: Delay of 50 us with a 4Mhz resonator Input: Delay X x 50us Output: none Misc: **********************************************************/ void Delay_50us(int Delay) { int i,j; for (i=0;i<Delay;i++) { for (j=1;j<20*10;j++) asm("WDR"); } } /********************************************************** Name: void InitLCD(void) Description: Initialize LCD in 4bit mode Input: none Output: none Misc: **********************************************************/ void InitLCD(void) { LCDDDR = D7 + D6 + D5 + D4 + E + RS + RW; LCDPORT = !(D7 + D6 + D5 + D4 + E + RS + RW); Delay_50us(340); LCDPORT = (D5 + D4); // Function Set 8 bit 3 time LCDPORT |= E; LCDPORT &= ~E; Delay_50us(100); LCDPORT |= E; LCDPORT &= ~E; Delay_50us(100); LCDPORT |= E; LCDPORT &= ~E; Delay_50us(100); LCDPORT = D5; // Function Set 4 bit LCDPORT |= E; LCDPORT &= ~E; Delay_50us(100); WriteLCD(0,0x28); // 2 line Delay_50us(100); WriteLCD(0,0x0c); // Display ON Cursor OFF Blink OFF Delay_50us(100); WriteLCD(0,0x01); // Clear display Delay_50us(50); WriteLCD(0,0x06); // Cursor INC Shift OFF Delay_50us(100); } /* */ void LedA(char on) { if(on) PORTB&=~1; else PORTB|=1; } void LedB(char on) { if(on) PORTB&=~2; else PORTB|=2; } void format(const char *tag,char num,char len3) { char *p=buf; if(tag) while(*tag) *p++=*tag++; if(len3) *p++=num/100+'0'; *p++=(num%100)/10+'0'; *p++=num%10+'0'; *p++=0; } void main( void ) { char led=0,key; char rv,cnt=0; DDRB=19; LedA(0); LedB(0); keys=PIND; coil=0; InitMuxIo(); InitUart(); InitLCD(); ClrLCD(); GotoXY(1,1); WriteStrLCDConst("Ready.\0"); _SEI(); key=PIND; while(1) { //keys handler key=PIND; if(keys&(1<<7)&&(!(key&(1<<7)))) //K1 { spi_mux_code_write(); ClrLCD(); GotoXY(1,1); WriteStrLCDConst(" NmrtMux 1.0\0"); GotoXY(1,2); WriteStrLCDConst("Make it easy! :)\0"); } if(keys&(1<<6)&&(!(key&(1<<6)))) //K2 { coil=0; ClrLCD(); spi_mux_code_write(); GotoXY(1,1); format("Coil=",coil,3); WriteStrLCDConst(buf); } if(keys&(1<<5)&&(!(key&(1<<5)))) //K3 { coil++; if(coil>102) coil=102; ClrLCD(); spi_mux_code_write(); GotoXY(1,1); format("Coil=",coil,3); WriteStrLCDConst(buf); } if(keys&(1<<4)&&(!(key&(1<<4)))) //K4 { coil+=10; if(coil>102) coil=102; ClrLCD(); spi_mux_code_write(); GotoXY(1,1); format("Coil=",coil,3); WriteStrLCDConst(buf); } keys=key; //Serial iface cnt+=rv=Rx_Cmp("I",0,0); if(rv==1) Send("\r\nNMRT MuxCtrl Board v1.0.0.1\r\nLab MPhM ZPTI KSC RAS 2005 Copyright\r\n\r\n"); cnt+=rv=Rx_Cmp("L",&led,1); if(rv==1) LedA(led=='1'?1:0); cnt+=rv=Rx_Cmp("C",buf,3); if(rv==1) { LedB(1); coil=(buf[0]-'0')*100+(buf[1]-'0')*10+(buf[2]-'0'); if(coil>102) coil=102; ClrLCD(); spi_mux_code_write(); GotoXY(1,1); format("Coil=",coil,3); WriteStrLCDConst(buf); format("Coil=",coil,3); Send(buf); Send("\r\n"); LedB(0); } if((cnt==2*3)||(rx_pos==16)) rx_pos=0; } } #include <io8535v.h> #include <macros.h> #include <stdlib.h> const unsigned char lut[103*2]= { 3,8, //0=4-17 1,3, //1=1-01 1,5, 1,7, 1,9, 1,11, 1,13, 1,15, 1,32, 1,30, 1,28, 1,26, 1,24, 1,22, 1,20, 3,3, //15=2-01 3,5, 3,7, 3,9, 3,11, 3,13, 3,15, 3,32, 3,30, 3,28, 3,26, 3,24, 3,22, 3,20, 18,64, //29=3-01 5,64, 7,64, 9,64, 11,64, 13,64, 15,64, 32,64, 30,64, 28,64, 26,64, 24,64, 22,64, 20,64, 4,64, //43=4-01 6,64, 8,64, 3,1, //46=4-04: old_0(10,64) => new_1(3,1) 12,64, 14,64, 16,64, 31,64, 29,64, 27,64, 25,64, 23,64, 21,64, 19,64, 2,19, //57=5-01 2,21, 2,23, 2,25, 2,27, 2,29, 2,31, 2,16, 2,14, 2,12, 2,10, 2,8, 2,6, 2,4, 2,3, //71=6-01 2,5, 2,7, 2,9, 2,11, 2,13, 2,15, 2,32, 2,30, 2,28, 2,26, 2,24, 2,22, 2,20, 1,19, //85=7-01 1,21, 1,23, 1,25, 1,27, 1,29, 1,31, 1,16, 1,14, 1,12, 1,10, 1,8, 1,6, 1,4, 3,4, //99=4-15 3,6, 3,10, 3,12 }; WriteStrLCDConst("Ready.\0"); _SEI(); key=PIND; while(1) { //keys handler key=PIND; if(keys&(1<<7)&&(!(key&(1<<7)))) //K1 { spi_mux_code_write(); ClrLCD(); GotoXY(1,1); WriteStrLCDConst(" NmrtMux 1.0\0"); GotoXY(1,2); WriteStrLCDConst("Make it easy! :)\0"); } if(keys&(1<<6)&&(!(key&(1<<6)))) //K2 { coil=0; ClrLCD(); spi_mux_code_write(); GotoXY(1,1); format("Coil=",coil,3); WriteStrLCDConst(buf); } if(keys&(1<<5)&&(!(key&(1<<5)))) //K3 { coil++; if(coil>102) coil=102; ClrLCD(); spi_mux_code_write(); GotoXY(1,1); format("Coil=",coil,3); WriteStrLCDConst(buf); } if(keys&(1<<4)&&(!(key&(1<<4)))) //K4 { coil+=10; if(coil>102) coil=102; ClrLCD(); spi_mux_code_write(); GotoXY(1,1); format("Coil=",coil,3); WriteStrLCDConst(buf); } keys=key; //Serial iface cnt+=rv=Rx_Cmp("I",0,0); if(rv==1) Send("\r\nNMRT MuxCtrl Board v1.0.0.1\r\nLab MPhM ZPTI KSC RAS 2005 Copyright\r\n\r\n"); cnt+=rv=Rx_Cmp("L",&led,1); if(rv==1) LedA(led=='1'?1:0); cnt+=rv=Rx_Cmp("C",buf,3); if(rv==1) { LedB(1); coil=(buf[0]-'0')*100+(buf[1]-'0')*10+(buf[2]-'0'); if(coil>102) coil=102; ClrLCD(); spi_mux_code_write(); GotoXY(1,1); format("Coil=",coil,3); WriteStrLCDConst(buf); format("Coil=",coil,3); Send(buf); Send("\r\n"); LedB(0); } if((cnt==2*3)||(rx_pos==16)) rx_pos=0; } } #include <io8535v.h> #include <macros.h> #include <stdlib.h> const unsigned char lut[103*2]= { 3,8, //0=4-17 1,3, //1=1-01 1,5, 1,7, 1,9, 1,11, 1,13, 1,15, 1,32, 1,30, 1,28, 1,26, 1,24, 1,22, 1,20, 3,3, //15=2-01 3,5, 3,7, 3,9, 3,11, 3,13, 3,15, 3,32, 3,30, 3,28, 3,26, 3,24, 3,22, 3,20, 18,64, //29=3-01 5,64, 7,64, 9,64, 11,64, 13,64, 15,64, 32,64, 30,64, 28,64, 26,64, 24,64, 22,64, 20,64, 4,64, //43=4-01 6,64, 8,64, 3,1, //46=4-04: old_0(10,64) => new_1(3,1) 12,64, 14,64, 16,64, 31,64, 29,64, 27,64, 25,64, 23,64, 21,64, 19,64, 2,19, //57=5-01 2,21, 2,23, 2,25, 2,27, 2,29, 2,31, 2,16, 2,14, 2,12, 2,10, 2,8, 2,6, 2,4, 2,3, //71=6-01 2,5, 2,7, 2,9, 2,11, 2,13, 2,15, 2,32, 2,30, 2,28, 2,26, 2,24, 2,22, 2,20, 1,19, //85=7-01 1,21, 1,23, 1,25, 1,27, 1,29, 1,31, 1,16, 1,14, 1,12, 1,10, 1,8, 1,6, 1,4, 3,4, //99=4-15 3,6, 3,10, 3,12 }; MuxCtrl.pdf Изменено 6 февраля, 2014 пользователем IgorKossak [codebox] для длинного кода, [code] - для короткого!!! Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
Палыч 7 6 февраля, 2014 Опубликовано 6 февраля, 2014 · Жалоба На данный момент, код при компиляции не выдает ошибок, при прошивки в МК, у МК ноль реакции. Компиляция без ошибок - не факт того, что программа будет как-то "осмысленно" работать... Ранее это программа была опробована в устройстве? Вполне может быть, что при программировании ("заливки" программы в устройство) не были правильно установлены fuse... Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
mr_Gish 0 6 февраля, 2014 Опубликовано 6 февраля, 2014 · Жалоба Ранее это программа была опробована в устройстве? На дисплее выводил значения, а подключение com-порта не осуществлялось Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
navovvol 0 6 февраля, 2014 Опубликовано 6 февраля, 2014 · Жалоба Ааа! Используйте codebox плиз. Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
Палыч 7 6 февраля, 2014 Опубликовано 6 февраля, 2014 · Жалоба На дисплее выводил значения, а подключение com-порта не осуществлялось Опять же: возможно из-за неправильно запраграммированных fuse тактирование МК осуществлялось не от нужного источника. Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
navovvol 0 6 февраля, 2014 Опубликовано 6 февраля, 2014 (изменено) · Жалоба Блин, походу топикстартер сначало вставил сюда половину кода, а потом еще раз вставил, но уже весь код. Полтора раза одно и тоже. Mr_Gish, посмотрите, что вообще на ножках разъема осциллографом или хотя бы мультиметром. И вы вообще к какому разъему подключились ? Вам нужен DB9F, это тот, что типа-мама. Изменено 6 февраля, 2014 пользователем Navovvol Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
mr_Gish 0 10 февраля, 2014 Опубликовано 10 февраля, 2014 · Жалоба Mr_Gish, посмотрите, что вообще на ножках разъема осциллографом или хотя бы мультиметром. И вы вообще к какому разъему подключились ? Вам нужен DB9F, это тот, что типа-мама. Прозванивал я мультиметром, с контактами все в порядке. У меня DB9F. Опять же: возможно из-за неправильно запраграммированных fuse тактирование МК осуществлялось не от нужного источника. Не могли бы Вы подробнее рассказать про fuse, точнее знаю, что из себя это представляет, вот где именно происходит управление с нимим .... Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
Палыч 7 10 февраля, 2014 Опубликовано 10 февраля, 2014 · Жалоба Не могли бы Вы подробнее рассказать про fuse, точнее знаю, что из себя это представляет, вот где именно происходит управление с нимим .... Извините, не сразу заметил что в устройстве используется "древний" AT90s8535 - про fuse можно не вспоминать, ввиду почти полнейшего отсутствия таковых. Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
mr_Gish 0 10 февраля, 2014 Опубликовано 10 февраля, 2014 · Жалоба Извините, не сразу заметил что в устройстве используется "древний" AT90s8535 - про fuse можно не вспоминать, ввиду почти полнейшего отсутствия таковых. "С установкой фьюзов нужно быть предельно внимательным, так как при неправильной установке некоторых из них, Вы рискуете потерять микроконтроллер для дальнейшего программирования через последовательный программатор." читал в одной статье. я подумал, что из-за своих незнаний во фьюзах я потерял МК ... Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
mr_Gish 0 17 марта, 2014 Опубликовано 17 марта, 2014 · Жалоба Доброго времени суток! Все же хотелось бы решить эту проблему, не могли бы мне помочь с этим делом? Дело в том, что при прошивки МК никак не реагирует на это дело Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
alexeyv 0 17 марта, 2014 Опубликовано 17 марта, 2014 · Жалоба 1. Есть рабочий код 2. Есть нерабочий код Выясняем отличия двух версий и комментируем добавленное. Проверяем что МК работает. После потихоньку расскомментируем и выясняем где МК ступорится. Локализируем этот код, разбираемся и исправляем его. Зашиваем и убеждаемся что все работает Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться
gormih 0 21 марта, 2014 Опубликовано 21 марта, 2014 · Жалоба Доброго времени суток! Все же хотелось бы решить эту проблему, не могли бы мне помочь с этим делом? Дело в том, что при прошивки МК никак не реагирует на это дело Что мешает воспользоваться отладкой на "железе"? В AVR STUDIO прекрасный интерфейс, показывающий состояние любого регистра в любой момент времени и точки останова. Этого вполне достаточно для отладки любой сложности. Если "ничего не выводит" - первое, что приходит на ум - поставить точку останова в функции void TxChar(char ch), и проанализировать состояние регистров контроллера во время ее работы, если она вообще вызывается. Если с регистрами норма - ищите проблемы в железе. Подключите осциллограф или логический анализатор на uart, посмотрите как дергаются / не дергаются пины. Причин может быть много - от ошибки в коде, до сгоревшего пина котроллера/ драйвера на плате, и здесь могут дать только советы а не выполнить за Вас работу:) Цитата Поделиться сообщением Ссылка на сообщение Поделиться на другие сайты Поделиться