Social Icons

Thứ Ba, 12 tháng 11, 2013

PIC truyền thông SPI

                                                 SOURCE

*******************************
Project : PIC16F Giao Tiếp SPI
Date    : 11-Nov-2013
Author  : quinguyen
Company : Vinasemiconductor
Chip type               : PIC16F88
Program type            : Application

Core Clock frequency: 20.000000 MHz
*******************************
                                                 MASTER

#include <pic16f88>
#use delay(clock=20000000)
#use rs232(baud=9600,parity=N,xmit=PIN_A2,rcv=PIN_A3)
int8 x=66, data;
#INT_SSP
void spi()
{
 if( spi_data_is_in() )

  {
     data=spi_read();
     printf("%u\n\r",data);
  }
}
void main()
{
  // port_b_pullups(TRUE);
   setup_spi(spi_master|spi_l_to_h|spi_clk_div_16);
   enable_interrupts(INT_SSP);
   enable_interrupts(GLOBAL);
   while(1)
   {
   delay_ms(1000);
   output_low(PIN_A5);//Chân C2 dùng Select chip.
   delay_ms(10);//Tao tre de Slave chuan bi.
   spi_write(x);
   output_high(PIN_A5);
   }
}

                                               SLAVE
#include <pic16f88>
#use delay(clock=20000000)
#use rs232(baud=9600,parity=N,xmit=PIN_A2,rcv=PIN_A3)
int8 data=0,x=22;
#INT_SSP
void spi()
{
      data=spi_read(x);//Vua nhan vua truyen.
      printf("%u\n\r",data);
}
void main()
{
   setup_spi(spi_slave|spi_l_to_h|spi_clk_div_16);
   enable_interrupts(INT_SSP);
   enable_interrupts(GLOBAL);
   while(1)
   {
   }
}

                                KẾT QUẢ MÔ PHỎNG


Mô tả: Master ghi giá trị vào Slave, Slave đọc giá trị đồng thời gửi lái Master một dữ liệu mới, tất cả được in ra màn hình

Chúc các bạn thành công với Project này!

Thanks and Best Regards 

Nguyễn Ngọc Qui
Automation Engineer
Email: quinguyentgvn@gmail.com
Phone: 0938 430 305

PIC giao tiếp MODBUS

                                                              SOURCE

*******************************
Project : PIC16F Giao Tiếp MODBUS
Date    : 11-Nov-2013
Author  : quinguyen
Company : Vinasemiconductor
Chip type               : PIC16F877A
Program type            : Application

Core Clock frequency: 20.000000 MHz
*******************************
                                                                 MASTER
#include<pic16f877a>
#fuses HS, NOWDT
#use delay(clock=20M)
#define MODBUS_TYPE MODBUS_TYPE_MASTER
#define MODBUS_SERIAL_TYPE MODBUS_RTU     //use MODBUS_ASCII for ASCII mode
#define MODBUS_SERIAL_RX_BUFFER_SIZE 64
#define MODBUS_SERIAL_BAUD 9600
#define ERRLED PIN_D1   //led bao loi truyen
#define ADD1 PIN_D7   //ADD1
#define ADD2 PIN_D6
#define ADD3 PIN_D5
#define ADD4 PIN_D4
#define ADD5 PIN_C5
#define ADD6 PIN_C4
#define ADD7 PIN_D3
#define ADD8 PIN_D2
#ifndef USE_WITH_PC
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, stream=PC, errors)
#define MODBUS_SERIAL_INT_SOURCE MODBUS_INT_EXT
#define MODBUS_SERIAL_TX_PIN PIN_B1   // Data transmit pin
#define MODBUS_SERIAL_RX_PIN PIN_B0   // Data receive pin
//The following should be defined for RS485 communication
#define MODBUS_SERIAL_ENABLE_PIN   PIN_B4   // Controls DE pin for RS485
#define MODBUS_SERIAL_RX_ENABLE    PIN_B5   // Controls RE pin for RS485
#define DEBUG_MSG(msg) fprintf(PC, msg)
#define DEBUG_DATA(msg,data) fprintf(PC, msg, data)
#else
#define MODBUS_SERIAL_INT_SOURCE MODBUS_INT_RDA
#define DEBUG_MSG(msg) if(0)
#define DEBUG_DATA(msg,data) if(0)
#endif
//#define MODBUS_SLAVE_ADDRESS1 0x01
//#define MODBUS_SLAVE_ADDRESS2 0x02
int8 MODBUS_SLAVE_ADDRESS;
int i;
/*This function may come in handy for you since MODBUS uses MSB first.*/
int8 swap_bits(int8 c)
{
   return ((c&1)?128:0)|((c&2)?64:0)|((c&4)?32:0)|((c&8)?16:0)|((c&16)?8:0)
          |((c&32)?4:0)|((c&64)?2:0)|((c&128)?1:0);
}
void read_all_holding()
{
   DEBUG_MSG("Holding Registers:\r\n");
   if(!(modbus_read_holding_registers(MODBUS_SLAVE_ADDRESS,0,8)))
   {    
      DEBUG_MSG("Data: ");
      /*Started at 1 since 0 is quantity of coils*/
      for(i=1; i < (modbus_rx.len); ++i)
         DEBUG_DATA("%X ", modbus_rx.data[i]);
      DEBUG_MSG("\r\n\r\n");
      output_low(ERRLED);
       switch (MODBUS_SLAVE_ADDRESS)
     {
     case 1:
     output_high(ADD1);
     break;
     case 2:
     output_high(ADD2);
     break;
     case 3:
     output_high(ADD3);
     break;
     case 4:
     output_high(ADD4);
     break;
     case 5:
     output_high(ADD5);
     break;
     case 6:
     output_high(ADD6);
     break;
     case 7:
     output_high(ADD7);
     break;
     case 8:
     output_high(ADD8);
     break;
     }
   }
   else
   {
      DEBUG_DATA("<-**Exception %X**->\r\n\r\n", modbus_rx.error);
      output_high(ERRLED);
   
   }
}

void unknown_func()
{
   DEBUG_MSG("Trying unknown function\r\n");
   DEBUG_MSG("Diagnostic:\r\n");
   if(!(modbus_diagnostics(MODBUS_SLAVE_ADDRESS,0,0)))
   {
      DEBUG_MSG("Data:");
      for(i=0; i < (modbus_rx.len); ++i)
         DEBUG_DATA("%X ", modbus_rx.data[i]);
      DEBUG_MSG("\r\n\r\n");
   }
   else
   {
      DEBUG_DATA("<-**Exception %X**->\r\n\r\n", modbus_rx.error);
   }
}
void main()
{
   DEBUG_MSG("\r\nInitializing...");
 // MODBUS_SLAVE_ADDRESS=MODBUS_SLAVE_ADDRESS1;
   modbus_init();
   DEBUG_MSG("...ready\r\n");
      while(TRUE)
{
   output_d(0);
   for (MODBUS_SLAVE_ADDRESS=1;MODBUS_SLAVE_ADDRESS<=8;MODBUS_SLAVE_ADDRESS++)
   {
   read_all_holding();
   delay_ms(2000);
   }
}
}

                                                                            SLAVE 


#include <pic16f877a>
#fuses HS, NOWDT
#use delay(clock=4000000)
#define MODBUS_TYPE MODBUS_TYPE_SLAVE
#define MODBUS_SERIAL_TYPE MODBUS_RTU     //use MODBUS_ASCII for ASCII mode
#define MODBUS_SERIAL_RX_BUFFER_SIZE 64
#define MODBUS_SERIAL_BAUD 9600
#ifndef USE_WITH_PC
#define MODBUS_SERIAL_INT_SOURCE MODBUS_INT_EXT
#define MODBUS_SERIAL_TX_PIN PIN_B1   // Data transmit pin
#define MODBUS_SERIAL_RX_PIN PIN_B0   // Data receive pin
//The following should be defined for RS485 communication
#define MODBUS_SERIAL_ENABLE_PIN   PIN_B2   // Controls DE pin for RS485
#define MODBUS_SERIAL_RX_ENABLE    PIN_B3   // Controls RE pin for RS485
#else
#define MODBUS_SERIAL_INT_SOURCE MODBUS_INT_RDA
#endif
#define MODBUS_ADDRESS 1 // Địa chỉ của slave, mỗi slave địa chỉ khác nhau
/*This function may come in handy for you since MODBUS uses MSB first.*/
int8 swap_bits(int8 c)
{
   return ((c&1)?128:0)|((c&2)?64:0)|((c&4)?32:0)|((c&8)?16:0)|((c&16)?8:0)
          |((c&32)?4:0)|((c&64)?2:0)|((c&128)?1:0);
}
void main()
{
   int8 coils = 0b00000101;
   int8 inputs = 0b00001001;
   int16 hold_regs[] = {0x1111,0x1111,0x1111,0x1111,0x1111,0x1111,0x1111,0x1111,0x1111};
   int16 input_regs[] = {0x1100,0x2200,0x3300,0x4400,0x5500,0x6600,0x7700,0x8800};
   int16 event_count = 0;
   modbus_init();

   while(TRUE)
   {
      while(!modbus_kbhit());  
      delay_us(50);
      //check address against our address, 0 is broadcast
      if((modbus_rx.address == MODBUS_ADDRESS) || modbus_rx.address == 0)
      {
         switch(modbus_rx.func)
         {
            case FUNC_READ_COILS:    //read coils
            case FUNC_READ_DISCRETE_INPUT:    //read inputs
               if(modbus_rx.data[0] || modbus_rx.data[2] ||
                  modbus_rx.data[1] >= 8 || modbus_rx.data[3]+modbus_rx.data[1] > 8)
                  modbus_exception_rsp(MODBUS_ADDRESS,modbus_rx.func,ILLEGAL_DATA_ADDRESS);
               else
               {
                  int8 data;          
                  if(modbus_rx.func == FUNC_READ_COILS)
                     data = coils>>(modbus_rx.data[1]);      //move to the starting coil
                  else
                    data = inputs>>(modbus_rx.data[1]);      //move to the starting input
                  data = data & (0xFF>>(8-modbus_rx.data[3]));  //0 out values after quantity
                  if(modbus_rx.func == FUNC_READ_COILS)
                     modbus_read_discrete_input_rsp(MODBUS_ADDRESS, 0x01, &data);
                  else
                     modbus_read_discrete_input_rsp(MODBUS_ADDRESS, 0x01, &data);              
                  event_count++;
               }
               break;
            case FUNC_READ_HOLDING_REGISTERS:
            case FUNC_READ_INPUT_REGISTERS:
               if(modbus_rx.data[0] || modbus_rx.data[2] ||
                  modbus_rx.data[1] >= 8 || modbus_rx.data[3]+modbus_rx.data[1] > 8)
                  modbus_exception_rsp(MODBUS_ADDRESS,modbus_rx.func,ILLEGAL_DATA_ADDRESS);
               else
               {
                  if(modbus_rx.func == FUNC_READ_HOLDING_REGISTERS)
                  {
                     modbus_read_holding_registers_rsp(MODBUS_ADDRESS,(modbus_rx.data[3]*2),hold_regs+modbus_rx.data[1]);
                     output_high(PIN_E1);
                     delay_ms(200);
                     output_low(PIN_E1);
                     delay_ms(200);
                  }                  
                  else
                     modbus_read_input_registers_rsp(MODBUS_ADDRESS,(modbus_rx.data[3]*2),input_regs+modbus_rx.data[1]);                
                  event_count++;
               }
               break;
            case FUNC_WRITE_SINGLE_COIL:      //write coil
               if(modbus_rx.data[0] || modbus_rx.data[3] || modbus_rx.data[1] > 8)
                  modbus_exception_rsp(MODBUS_ADDRESS,modbus_rx.func,ILLEGAL_DATA_ADDRESS);
               else if(modbus_rx.data[2] != 0xFF && modbus_rx.data[2] != 0x00)
                  modbus_exception_rsp(MODBUS_ADDRESS,modbus_rx.func,ILLEGAL_DATA_VALUE);
               else
               {
                  //coils are stored msb->lsb so we must use 7-address
                  if(modbus_rx.data[2] == 0xFF)
                     bit_set(coils,modbus_rx.data[1]);
                  else
                     bit_clear(coils,modbus_rx.data[1]);
                  modbus_write_single_coil_rsp(MODBUS_ADDRESS,modbus_rx.data[1],((int16)(modbus_rx.data[2]))<<8);
               
                  event_count++;
               }
               break;
            case FUNC_WRITE_SINGLE_REGISTER:
               if(modbus_rx.data[0] || modbus_rx.data[1] >= 8)
                  modbus_exception_rsp(MODBUS_ADDRESS,modbus_rx.func,ILLEGAL_DATA_ADDRESS);
               else
               {
                  //the registers are stored in little endian format
                  hold_regs[modbus_rx.data[1]] = make16(modbus_rx.data[3],modbus_rx.data[2]);

                  modbus_write_single_register_rsp(MODBUS_ADDRESS,
                               make16(modbus_rx.data[0],modbus_rx.data[1]),
                               make16(modbus_rx.data[2],modbus_rx.data[3]));
               }
               break;
            case FUNC_WRITE_MULTIPLE_COILS:
               if(modbus_rx.data[0] || modbus_rx.data[2] ||
                  modbus_rx.data[1] >= 8 || modbus_rx.data[3]+modbus_rx.data[1] > 8)
              modbus_exception_rsp(MODBUS_ADDRESS,modbus_rx.func,ILLEGAL_DATA_ADDRESS);
               else
               {
                  int i,j;
                  modbus_rx.data[5] = swap_bits(modbus_rx.data[5]);
                  for(i=modbus_rx.data[1],j=0; i < modbus_rx.data[1]+modbus_rx.data[3]; ++i,++j)
                  {
                     if(bit_test(modbus_rx.data[5],j))
                        bit_set(coils,7-i);
                     else
                        bit_clear(coils,7-i);
                  }

                  modbus_write_multiple_coils_rsp(MODBUS_ADDRESS,
                                 make16(modbus_rx.data[0],modbus_rx.data[1]),
                                 make16(modbus_rx.data[2],modbus_rx.data[3]));              
                  event_count++;
               }
               break;
            case FUNC_WRITE_MULTIPLE_REGISTERS:
               if(modbus_rx.data[0] || modbus_rx.data[2] ||
                  modbus_rx.data[1] >= 8 || modbus_rx.data[3]+modbus_rx.data[1] > 8)               modbus_exception_rsp(MODBUS_ADDRESS,modbus_rx.func,ILLEGAL_DATA_ADDRESS);
               else
               {
                  int i,j;
                  for(i=0,j=5; i < modbus_rx.data[4]/2; ++i,j+=2)
                     hold_regs[i] = make16(modbus_rx.data[j+1],modbus_rx.data[j]);
                  modbus_write_multiple_registers_rsp(MODBUS_ADDRESS,
                                 make16(modbus_rx.data[0],modbus_rx.data[1]),
                                 make16(modbus_rx.data[2],modbus_rx.data[3]));        
                  event_count++;
               }
               break;        
            default:    //We don't support the function, so return exception
               modbus_exception_rsp(MODBUS_ADDRESS,modbus_rx.func,ILLEGAL_FUNCTION);
         }
      }
  }
}

                                       KẾT QUẢ MÔ PHỎNG


c
Chú ý: Master và slave truyền thông qua chuẩn RS485, chương trình slave là như nhau chỉ khác ở địa chỉ Mô tả: Master đọc dữ liệu 2 slave và in ra màn hình


Chúc các bạn thành công với project này!

Thanks and Best Regards 

Nguyễn Ngọc Qui
Automation Engineer
Email: quinguyentgvn@gmail.com
Phone: 0938 430 305

PIC16F Giao Tiếp CAN BUS

                                             SOURCE
*******************************
Project : PIC16F Giao Tiếp Mạng CAN
Date    : 11-Nov-2013
Author  : quinguyen
Company : Vinasemiconductor
Chip type               : PIC16F876
Program type            : Application

Core Clock frequency: 20.000000 MHz
*******************************

                                             TRẠM 1

#include <16F876.h>
#fuses HS,NOPROTECT,NOLVP,WDT
#use delay(clock=20000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
#define CAN_DO_DEBUG TRUE
#define PIN_LED1  PIN_B1
#define PIN_LED2  PIN_B2
#define LED1_HIGH output_high(PIN_LED1)
#define LED1_LOW  output_low(PIN_LED1)
#define LED2_HIGH output_high(PIN_LED2)
#define LED2_LOW  output_low(PIN_LED2)
int16 ms;
#int_timer2
void isr_timer2(void) {
   ms++;        
}

#define ASK_TO_ID_AD   0x201
#define ASK_TO_ID_LED  0x202

void main() {
   struct rx_stat rxstat;
   int32 rx_id;
   int buffer[8];
   int rx_len;
   int i,k=10,x=99;
   setup_wdt(WDT_2304MS);
   setup_port_a(RA0_ANALOG);
   setup_adc(ADC_CLOCK_INTERNAL);
   set_adc_channel(0);
   setup_timer_2(T2_DIV_BY_4,53,3);
   can_init();
   enable_interrupts(INT_TIMER2);                       //Cho phép ngắt Timer2
   enable_interrupts(GLOBAL);                             //Cho phép tất cả ngắt
   LED1_HIGH;
   LED2_HIGH;
   delay_ms(1000); 
   LED1_LOW;
   LED2_LOW;
   while(TRUE)
   {
restart_wdt();
i=read_adc();                                                                   // Đọc ADC
can_putd(ASK_TO_ID_LED, &i, 1,1,1,0);                   //Đưa dữ liệu vào bộ đệm
      if ( can_kbhit() )   //if data is waiting in buffer...
       restart_wdt();
         if(can_getd(rx_id, &buffer[0], rx_len, rxstat)) {      // Lấy dữ liệu từ bộ đệm
            if (rx_id == ASK_TO_ID_LED) {
            LED1_HIGH;
            LED2_LOW;
            }
            if (rx_id == ASK_TO_ID_AD) {
               LED2_HIGH;
               LED1_LOW;
            }
         }
      }
      
   }

}
                                                                      TRẠM 2

#include <16F876.h>
#fuses HS,NOPROTECT,NOLVP,WDT
#use delay(clock=20000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
#define CAN_DO_DEBUG TRUE
#define PIN_LED1  PIN_B1
#define PIN_LED2  PIN_B2
#define LED1_HIGH output_high(PIN_LED1)
#define LED1_LOW  output_low(PIN_LED1)
#define LED2_HIGH output_high(PIN_LED2)
#define LED2_LOW  output_low(PIN_LED2)
#define LCD_RS PIN_A3                      
#define LCD_RW PIN_A2
#define LCD_EN PIN_A1
#define LCD_D4 PIN_B4              
#define LCD_D5 PIN_B5
#define LCD_D6 PIN_B6
#define LCD_D7 PIN_B7

#include "lcd_qui.c"

int16 ms;
   int8 str[20];
   int8 x;
 
#int_timer2
void isr_timer2(void) {
   ms++;              
}
#define RESPOND_TO_ID_AD   0x201
#define RESPOND_TO_ID_LED  0x202
void khoitaoLCD(void)
{
 restart_wdt();
   LCD_Init();
   delay_ms(10);
   sprintf(str,"CAN DEMO");
   LCD_Gotoxy(4,0);
   LCD_Puts(str);
   delay_ms(1000);
   LCD_Clear();
   LCD_Gotoxy(1,0);
   sprintf(str,"CAN INTERFACE");
   LCD_Puts(str);
   LCD_Gotoxy(1,1);
   sprintf(str,"CAN DATA :");
   LCD_Puts(str);
}
void main() {
   struct rx_stat rxstat;
   int32 rx_id;
   int buffer[8];
   int rx_len;
   int i,k=10,w=22;
   setup_wdt(WDT_2304MS);
   setup_port_a(RA0_ANALOG);
   setup_adc(ADC_CLOCK_INTERNAL);
   set_adc_channel(0);
   for(i=0;i<8;i++) {
      buffer[i]=0;
   }
   LED1_HIGH;
   LED2_HIGH;
   delay_ms(100);
   LED1_LOW;
   LED2_LOW;
 khoitaoLCD();
   setup_timer_2(T2_DIV_BY_4,53,3);
   delay_ms(100);
   can_init();
   enable_interrupts(INT_TIMER2);        //Cho phép ngắt Timer2
   enable_interrupts(GLOBAL);              //Cho phép tất cả ngắt
   while(TRUE)
   {
LED2_HIGH;
delay_ms(50);
LED2_LOW;
delay_ms(50);
 restart_wdt();
      if ( can_kbhit() )                             //Nếu có dữ liệu đợi trong bộ đệm
      { LED1_HIGH;
         if(can_getd(rx_id, &buffer[0], rx_len, rxstat)) {    //...Lấy dữ liệu từ bộ đệm
            if (rx_id == RESPOND_TO_ID_LED) {
                  LCD_Gotoxy(11,1);                                 // Hiển thị lên LCD
                  sprintf(str,"%u",buffer[0]);
                  LCD_Puts(str);
              LED1_HIGH;
              LED2_LOW;
            }
         }
      }
   
   }

}

                                     SƠ ĐỒ MẠCH ĐIỆN VÀ KẾT QUẢ




Mô tả: Trạm 1 đọc ADC được chỉnh từ biến trở sau đó gửi đến Trạm 2 theo giao thức CAN

Sơ đồ mạch cho 2 Trạm như nhau hết, mình đã làm và hoạt động rất tốt, chúc các bạn thành công! Phần lý thuyết các bạn tìm hiểu trên các diễn đàn khác nhé, ai ko rõ có thể liên hệ mình.

Thanks and Best Regards 

Nguyễn Ngọc Qui
Automation Engineer
Email: quinguyentgvn@gmail.com
Phone: 0938 430 305

Thứ Hai, 11 tháng 11, 2013

PIC Giao Tiếp USB 3G Viettel (Huawei E173Eu-1)

                                                      SOURCE DEMO
Đây chỉ là đoạn chương trình main mẫu, chỉ mang tính chất tham khảo, chương trình rất lớn các bạn có thể tham khảo trong thư viện của Microchip

*****************************************************************
Project :  PIC24FJGB106 Giao Tiếp 3G USB Modem Viettel (Huawei E173Eu-1)
Complier : MPLAB
Date    : 11-Nov-2013
Author  : quinguyen
Company : Vinasemiconductor
Chip type               : PIC24FJ family
Program type            : Application
Core Clock frequency: 20.000000 MHz
*****************************************************************
int main (void)
{
    // Initialize the processor and peripherals.
    if ( InitializeSystem() != TRUE )
    {
        UART2PrintString( "\r\n\r\nCould not initialize system.  Halting.\r\n\r\n" );
        while (1);
    }
UART2PrintString( "****WELCOM****\r\n" );
UART2PrintString( "Vinasemiconductor\r\n" );
UART2PrintString( "3G USB MODEM\r\n" );


    // Initialize USB layers
    USBInitialize( 0 );
    APPL_Demo_State = DEMO_INITIALIZE;
    CDC_AT_Command_State = CDC_NOT_READY;
    while(1)
    {
        USBTasks();
        CDCSequence();
        if(DemoTimeUp==TRUE)
        {
            DemoTimeUp = FALSE;
            if(DemoStallCount > DEMO_STALL_COUNT)
            {
                displayOnce = TRUE;
                APPL_Demo_State = APP_DEMO_TIME_UP;
            }
            else
            {
                DemoStallCount++;
                UART2PrintString( "-----------------------------------------------\r\n" );
                UART2PrintString( "This is 3G USB Demo on MicroChip PIC24FJ series\r\n" );
                UART2PrintString( "Work by Vinasemiconductor \r\n" );
                UART2PrintString( "-----------------------------------------------\r\n" );
            }
        }

        switch(APPL_Demo_State)
        {
            case DEMO_INITIALIZE:       // Khởi tạo USB Host
                #ifdef DISABLE_DEMO
                    UART2PrintString( "3G USB Application Initialize \r\n" );
                #else
                    UART2PrintString( "3G USB Application (DEMO) Initialize \r\n" );
                #endif
                FoundDevice = FALSE;
                APPL_Demo_State = DEVICE_NOT_CONNECTED;
                break;

            case DEVICE_NOT_CONNECTED:
                USBTasks();
                if(displayOnce == FALSE)
                {
                    UART2PrintString( "No USB Device Connected \r\n" );
                    FoundDevice = FALSE;
                    displayOnce = TRUE;
                }
                if(USBHostCDC_ApiDeviceDetect()) /* TRUE if device is enumerated without error */
                {
UART2PrintString( "USB Device Connected \r\n" );
                    APPL_Demo_State = DEVICE_CONNECTED;
                    displayOnce = FALSE;
                }
                #if 0
                    if(get_uart_ch(&AT_command_buffer[1]))
                    {
                        UART2PutChar(AT_command_buffer[1]);
                    }
                #endif
                break;

            case DEVICE_3G_SWITCH:                // Chuyển sang Modem
                if(USBHostCDC_ApiDeviceDetect()) /* TRUE if device is enumerated without error */
                {
                    APPL_Demo_State = DEVICE_CONNECTED;
                    displayOnce = FALSE;
                }
                break;

            case DEVICE_CONNECTED:
                UART2PrintString( "VIETTEL Huawei E173Eu-1 Connected \r\n" ); // Modem đã kết nối
                deviceAttached = TRUE;
                DeviceReady = FALSE;
                set_timer_wait(100);
                APPL_Demo_State = DEVICE_3G_QUERY;
                break;

            case DEVICE_3G_QUERY:
                if(SystemTimeUp == TRUE)
                {
                  UART2PrintString( "VIETTEL Huawei E173Eu-1 Ready \r\n" );   // Modem sẵn sàng
                    set_timer_wait(100);
                  APPL_Demo_State = DEVICE_3G_IDLE;
                }
                break;

            case DEVICE_3G_IDLE:
                if(SystemTimeUp == TRUE)
                {
                    set_timer_wait(1000);
                                      UART2PrintString("SMS Polling \r\n" );
                                      AT_Command_Send("ATZ");                     // Gửi lệnh ATcommand
                }
                break;

            case APP_DEMO_TIME_UP:
                if(displayOnce == TRUE)
                {
                    displayOnce = FALSE;
                    CDC_AT_Command_State = CDC_NOT_READY;
                }
                break;
            default :
                break;
        }
    }
}

                  HÌNH ẢNH THỰC TẾ VÀ KẾT QUẢ





Đến đây các bạn có thể gửi lệnh ATcommand và làm việc như các Modem khác, điều khiển hay thu thập dữ liệu gì thì tùy vào mục đích ứng dụng của mỗi người, chúc các bạn thành công
Sơ đồ mạch điện các bạn có thể tìm trên mạng hoặc trong datasheet con PIC24FJ256GB106, vì làm bằng boad đục lỗ nên chưa có sơ đồ mạch cụ thể!

Thanks and Best Regards 

Nguyễn Ngọc Qui
Automation Engineer
Email: quinguyentgvn@gmail.com
Phone: 0938 430 305


AVR sử dụng ADC và LCD

                                             SOURCE  

/*****************************************************
Project : ADC_LCD
Version :
Date    : 11-Nov-2013
Author  : QuiNguyen
Company : Vinasemiconductor
Comments:
Chip type               : ATmega16
Program type            : Application
AVR Core Clock frequency: 12.000000 MHz
Memory model            : Small
External RAM size       : 0
Data Stack size         : 256
*****************************************************/

#include <mega16.h>

#include <delay.h>

// Alphanumeric LCD Module functions
#include <alcd.h>

#define ADC_VREF_TYPE 0x20

// Read the 8 most significant bits
// of the AD conversion result
unsigned char read_adc(unsigned char adc_input)
{
ADMUX=adc_input | (ADC_VREF_TYPE & 0xff);
// Delay needed for the stabilization of the ADC input voltage
delay_us(10);
// Start the AD conversion
ADCSRA|=0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCH;
}

// Declare your global variables here
void lcd_putnum(unsigned int so)
{
     unsigned int Nghin, Tram, Chuc, Donvi;
     Nghin = so/1000;
     Tram = (so%1000)/100;
     Chuc = (so%100)/10;
     Donvi = so%10;
     lcd_putchar(Nghin + 48);
     lcd_putchar(Tram + 48);
     lcd_putchar(Chuc + 48);
     lcd_putchar(Donvi + 48);
}
void main(void)
{

unsigned char i;
// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;

// ADC initialization
// ADC Clock frequency: 750.000 kHz
// ADC Voltage Reference: AREF pin
// ADC Auto Trigger Source: ADC Stopped
// Only the 8 most significant bits of
// the AD conversion result are used
ADMUX=ADC_VREF_TYPE & 0xff;
ADCSRA=0x84;

// SPI initialization
// SPI disabled
SPCR=0x00;

// TWI initialization
// TWI disabled
TWCR=0x00;

// Alphanumeric LCD initialization
// Connections specified in the
// Project|Configure|C Compiler|Libraries|Alphanumeric LCD menu:
// RS - PORTD Bit 4
// RD - PORTD Bit 3
// EN - PORTD Bit 2
// D4 - PORTB Bit 4
// D5 - PORTB Bit 5
// D6 - PORTB Bit 6
// D7 - PORTB Bit 7
// Characters/line: 16
lcd_init(16);
lcd_gotoxy(0,0);
lcd_puts("Vinasemi...");
delay_ms(500);
lcd_clear();
while (1)
      {
      // Place your code here
    i=read_adc(0);
    lcd_gotoxy(0,0);
     lcd_puts("ADC Value=");
     lcd_gotoxy(0,16);
     lcd_putnum(i);
      }
}

                                         MÔ PHỎNG


Thứ Hai, 7 tháng 10, 2013

PIC sử dụng 2 cổng COM UART và SUART

                                                                     SOURCE

********************************
File Name:       UART.c
Dependencies:    None
Processor:       PIC16F/PIC18F
Compiler:        CCS C
Company:         vinasemiconductor
********************************

Chuong trinh co huong dan co ban ve truyen thong trong PIC,    
Truyen nhan mot ky tu, mot chuoi va mot so integer len 2 cong COM
 Ta co the su dung dong thoi bo UART cung va SUART (UART mem)    

#include <16F877A.h>
//#device adc=8
#FUSES NOWDT                    //No Watch Dog Timer
#FUSES HS                       //High speed Osc (> 4mhz for PCM/PCH) (>10mhz for PCD)
#FUSES NOPUT                    //No Power Up Timer
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NODEBUG                  //No Debug mode for ICD
#FUSES NOBROWNOUT               //No brownout reset
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NOCPD                    //No EE protection
#FUSES NOWRT                    //Program memory not write protected
#FUSES RESERVED                 //Used to set the reserved FUSE bits
#use delay(clock=20000000)
#use rs232(baud=9600, xmit=PIN_A2,rcv=PIN_A3,stream=COM1,errors)   // COM1 su dung USART ( UART mem)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7,stream=COM2,errors)  // COM2 su dung UART (UART cung)
void main()
{
int x=10,y=20;
char kytu_1,kytu_2;
char string[30],s[30];
fprintf(COM1,"COM1: Vinasemiconductor\n\r"); // truyen mot chuoi len cong COM1
delay_ms(100);
fprintf(COM2,"COM2: Vinasemiconductor\n\r"); // truyen mot chuoi len cong COM2
delay_ms(100);
fputc('A',COM1);                             // truyen mot ky tu len cong COM1
fprintf(COM1,"\n\r");                        // xuong dong
delay_ms(100);
fputc('B',COM2);                             // truyen mot ky tu len cong COM2
fprintf(COM2,"\n\r");                        // xuong dong
delay_ms(100);
fprintf(COM1,"%u\n\r",x);                    // truyen mot so integer len COM1
delay_ms(100);
fprintf(COM2,"%u\n\r",y);                    // truyen mot so integer len COM2
delay_ms(100);
while(1)
{

fgets(string,COM1);                          // nhan mot chuoi tu COM1
fprintf(COM1,"string=%s\n\r",string);        // truyen len COM1 chuoi vua nhan

kytu_1 = fgetc(COM1);                        // nhan mot ky tu tu COM1
if(kytu_1=='1')                              // neu ky tu la '1' thi truyen len COM1 ky tu do
{
fputc(kytu_1,COM1);
}

fgets(string,COM2);                          // nhan mot chuoi tu COM2
fprintf(COM2,"string=%s\n\r",string);        // truyen len COM2 chuoi vua nhan

kytu_2 = fgetc(COM2);                        // nhan mot ky tu tu COM2
if(kytu_2=='2')
{
fputc(kytu_2,COM2);                          // truyen len COM2 chuoi vua nhan
}
//delay_ms(500);
//value2 = fgetc(PC2);
//if (value1=='a')
//fprintf(PC1,"%u\n\r",x);
}
}

                                                   KẾT QUẢ MÔ PHỎNG
Mô tả: các bạn có thể sử dụng đồng thồi UART và SUART để truyền dữ liệu, tùy theo ứng dụng

Chúc các bạn thành công!

Thanks and Best Regards 

Nguyễn Ngọc Qui
Automation Engineer
Email: quinguyentgvn@gmail.com
Phone: 0938 430 305

Chủ Nhật, 6 tháng 10, 2013

PIC đọc ADC

                                                                    SOURCE

***************************
File Name:       ADC.c
Dependencies:    None
Processor:       PIC16F/PIC18F
Compiler:        CCS C
Company:         vinasemiconductor                      
***************************

#include <16F877A.h>
#device adc=8

#FUSES NOWDT                    //No Watch Dog Timer
#FUSES HS                       //High speed Osc (> 4mhz for PCM/PCH) (>10mhz for PCD)
#FUSES NOPUT                    //No Power Up Timer
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NODEBUG                  //No Debug mode for ICD
#FUSES NOBROWNOUT               //No brownout reset
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NOCPD                    //No EE protection
#FUSES NOWRT                    //Program memory not write protected
#FUSES RESERVED                 //Used to set the reserved FUSE bits
#use delay(clock=20000000)
int8 x;
void main()
{
setup_adc_ports( ALL_ANALOG );// All pins analog
setup_adc(ADC_CLOCK_INTERNAL );
set_adc_channel( 0 );// chon kenh su dung analog, o day chon kenh 0 (tuc chan AN0 trong datasheet)
while(1)
{
x = read_adc();// gia tri doc ADC
output_b(x);// xuat ra port B, cac chan cua port B tuong ung voi gia tri nhi phan cua gia tri doc ADC ve
}
}

                                   KẾT QUẢ MÔ PHỎNG



Mô tả: PIC đọc ADC sau đó xuất giá trị ra PORTB
Chúc các bạn thành công!

Thanks and Best Regards 

Nguyễn Ngọc Qui
Automation Engineer
Email: quinguyentgvn@gmail.com
Phone: 0938 430 305

Bài Viết 3

kwflkmeflml

Bài viết thứ 2

Bài viết thứ 2

bài viết đầu tiên

bài viết đầu tiên
 

Sample text

Sample Text

Sample Text