www.thachdt.com www.thachdt.com www.thachdt.com www.thachdt.com Điện thoại: 0901965800

Thứ Bảy, 28 tháng 10, 2017

Mạch hẹn giờ tắt mở thiết bị điện

 Thật bất tiện khi bạn chạy lui chạy tới chổ có công tắt để tắt một thiết bị điện trong nhà nào đó trong một khoản thời gian ngắn hoạt động , vậy bạn có mún thiết bị điện của bạn sẽ tự động tắt sau một khoản thời gian hoạt động cần thiết không ví dự như sau 5- 10 phút hoặc sau 1 tiếng 2 tiếng thì thiết bị tự động tắt , khi ấy bạn sẽ không cần phải chạy tới chổ có công tắt để tắt thiết bị đó nữa , 220von sẽ giới thiệu cho bạn một mạch giúp bạn với chức năng như vậy , và giá thành ché tạo mạch này rất rẻ với cách sử dụng rất đơn giản như video mà 220von sẽ giới thiệu sau đây

Mạch hẹn giờ tắt mở thiết bị điện dùng vi điều khiển STM8S103 , sử dụng biến trở để chỉnh thời gian hẹn từ 0 đến 60 phút , hiển thị lên màn hình LED
Mạch sử dụng điện áp 220V , và đóng cắt được tải 220V - 10A bằng relay



Video test mạch với máy bơm nước : 


Sơ đồ mạch : 
Sơ đồ


Mach IN


Code :
Code được viết bằng STVD với trình biên dịch Cosmic 16

 Hàm main.h :

/**
  ******************************************************************************
  * @file        main.h
  * @author      220von
  * @version      V1.0.0
  * @date   
  * @brief   This file is header for module main.c
  ******************************************************************************
  * @attention
  */

/* Define to prevent recursive inclusion -------------------------------------*/

#ifndef __MAIN_H__
#define __MAIN_H__

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/


#define NUT_PORT        (GPIOD)
#define NUT_PIN            (GPIO_PIN_4)

#define ADC_PORT        (GPIOD)
#define ADC_PIN            (GPIO_PIN_5)

#define A_PORT  (GPIOC)
#define A_PIN  (GPIO_PIN_4)
#define B_PORT  (GPIOC)
#define B_PIN  (GPIO_PIN_3)
#define C_PORT  (GPIOD)
#define C_PIN  (GPIO_PIN_1)
#define D_PORT  (GPIOC)
#define D_PIN  (GPIO_PIN_7)
#define E_PORT  (GPIOD)
#define E_PIN  (GPIO_PIN_3)
#define F_PORT  (GPIOC)
#define F_PIN  (GPIO_PIN_5)
#define G_PORT  (GPIOC)
#define G_PIN  (GPIO_PIN_6)

#define DOT_PORT  (GPIOD)
#define DOT_PIN  (GPIO_PIN_2)

#define LED1_PORT  (GPIOB)
#define LED1_PIN  (GPIO_PIN_4)
#define LED2_PORT  (GPIOB)
#define LED2_PIN  (GPIO_PIN_5)


#define R_PORT  (GPIOA)
#define R_PIN  (GPIO_PIN_3)


/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Public functions ----------------------------------------------------------*/

#endif /* __MAIN_H__ */

/******************* (C) COPYRIGHT 220von *****END OF FILE****/



Hàm main.c:
/**
  ******************************************************************************
  * @file        main.c
  * @author     220von
  * @version      V1.0.0
  * @date   
  * @brief   This file contains the main function for GPIO Toggle example.
  ******************************************************************************
  * @attention
  */

/* Includes ------------------------------------------------------------------*/
/*#include "stm8s_conf.h"*/
#include "main.h"
#include "stm8s_gpio.h"
#include "stm8s_adc1.h"
#include "stm8s_clk.h"
#include "stm8s_tim4.h"
#include "stm8s_tim1.h"
#include "stm8s.h"
#include "stm8s_it.h"
#include "stm8s_flash.h"

BitStatus dot_set=0,menu=0;
u8 min=0,sec=0;
u16 i=0;
u16 adc_val=1000;
 const u8 so[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};


void delay(uint16_t nCount)
{
  /* Decrement nCount value */
  while (nCount != 0)
  {
    nCount--;
  }
}
///////////////////////////////////////////////////////////////////////////
void send_led7seg(u8 giatri, BitStatus dot)
{
    if(giatri&0x01)GPIO_WriteLow(A_PORT, (GPIO_Pin_TypeDef)A_PIN);
    else GPIO_WriteHigh(A_PORT, (GPIO_Pin_TypeDef)A_PIN);
   
    if(giatri&0x02)GPIO_WriteLow(B_PORT, (GPIO_Pin_TypeDef)B_PIN);
    else GPIO_WriteHigh(B_PORT, (GPIO_Pin_TypeDef)B_PIN);   
   
    if(giatri&0x04)GPIO_WriteLow(C_PORT, (GPIO_Pin_TypeDef)C_PIN);
    else GPIO_WriteHigh(C_PORT, (GPIO_Pin_TypeDef)C_PIN);   

    if(giatri&0x08)GPIO_WriteLow(D_PORT, (GPIO_Pin_TypeDef)D_PIN);
    else GPIO_WriteHigh(D_PORT, (GPIO_Pin_TypeDef)D_PIN);
   
    if(giatri&0x10)GPIO_WriteLow(E_PORT, (GPIO_Pin_TypeDef)E_PIN);
    else GPIO_WriteHigh(E_PORT, (GPIO_Pin_TypeDef)E_PIN);

    if(giatri&0x20)GPIO_WriteLow(F_PORT, (GPIO_Pin_TypeDef)F_PIN);
    else GPIO_WriteHigh(F_PORT, (GPIO_Pin_TypeDef)F_PIN);
   
    if(giatri&0x40)GPIO_WriteLow(G_PORT, (GPIO_Pin_TypeDef)G_PIN);
    else GPIO_WriteHigh(G_PORT, (GPIO_Pin_TypeDef)G_PIN);
   
    if(dot==1)GPIO_WriteLow(DOT_PORT, (GPIO_Pin_TypeDef)DOT_PIN);
    else GPIO_WriteHigh(DOT_PORT, (GPIO_Pin_TypeDef)DOT_PIN);
}
///////////////////////////////////////////////////////////////////////////
u8 quetled=0;
void putc_to_3_led7seg(u8 value1,u8 value2,BitStatus dot)
{
    switch(quetled)
     {
         case 1:
           {
                GPIO_WriteHigh(LED2_PORT, (GPIO_Pin_TypeDef)LED2_PIN);
                send_led7seg(value1,0);
                GPIO_WriteLow(LED1_PORT, (GPIO_Pin_TypeDef)LED1_PIN);
                break;
             }
         case 2:
           {
                GPIO_WriteHigh(LED1_PORT, (GPIO_Pin_TypeDef)LED1_PIN);
                send_led7seg(value2,dot);
                GPIO_WriteLow(LED2_PORT, (GPIO_Pin_TypeDef)LED2_PIN);
                break;
             }             
           
     }
}
///////////////////////////////////////////////////////////////////////////
void hienthi_led7seg(u8 value1,BitStatus dot)
{
    u8 chuc;
    u8 le;
    chuc = value1/10;
    le = value1%10;
    if(value1<10)putc_to_3_led7seg(0x00,so[value1],dot);
  else  putc_to_3_led7seg(so[chuc],so[le],dot);
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
void main(void)
{
    CLK_DeInit();
        CLK_HSICmd( ENABLE);
    /* Configure the Fcpu to DIV1*/
    CLK_SYSCLKConfig(CLK_PRESCALER_CPUDIV1);
    /* Configure the HSI prescaler to the optimal value */
    CLK_SYSCLKConfig(CLK_PRESCALER_HSIDIV1);
    /* Output Fcpu on CLK_CCO pin */
    /*CLK_CCOConfig(CLK_OUTPUT_CPU);*/
    /* Configure the system clock to use HSI clock source and to run at 16Mhz */
    CLK_ClockSwitchConfig(CLK_SWITCHMODE_AUTO, CLK_SOURCE_HSI, DISABLE, CLK_CURRENTCLOCKSTATE_DISABLE);
       
         /* Define flash programming Time*/
    FLASH_SetProgrammingTime(FLASH_PROGRAMTIME_STANDARD);
        /* Unlock Data memory */
    FLASH_Unlock(FLASH_MEMTYPE_DATA);
       
       
    TIM1_DeInit();
    TIM1_TimeBaseInit(16, TIM1_COUNTERMODE_UP, 65535,0);
    TIM1_Cmd(ENABLE);

   
       
     ADC1_DeInit();
         ADC1_Cmd(ENABLE);
     ADC1_ConversionConfig(ADC1_CONVERSIONMODE_CONTINUOUS,ADC1_CHANNEL_5 ,ADC1_ALIGN_RIGHT);
     ADC1_PrescalerConfig(ADC1_PRESSEL_FCPU_D2);
     ADC1_StartConversion();
 
  /* Time base configuration */
  TIM4_TimeBaseInit(TIM4_PRESCALER_128, 124); // ngắt timer4 mỗi 1ms
  /* Clear TIM4 update flag */
  TIM4_ClearFlag(TIM4_FLAG_UPDATE);
  /* Enable update interrupt */
  TIM4_ITConfig(TIM4_IT_UPDATE, ENABLE);
  /* Enable TIM4 */
  TIM4_Cmd(ENABLE);
   
   
  /* Initialize I/Os in Output Mode */
    GPIO_Init(ADC_PORT, (GPIO_Pin_TypeDef)ADC_PIN, GPIO_MODE_IN_FL_NO_IT );
   
    GPIO_Init(LED1_PORT, (GPIO_Pin_TypeDef)LED1_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_Init(LED2_PORT, (GPIO_Pin_TypeDef)LED2_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
   
    GPIO_WriteHigh (LED1_PORT, (GPIO_Pin_TypeDef)LED1_PIN);
    GPIO_WriteHigh  (LED2_PORT, (GPIO_Pin_TypeDef)LED2_PIN);

    GPIO_Init(A_PORT, (GPIO_Pin_TypeDef)A_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_Init(B_PORT, (GPIO_Pin_TypeDef)B_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_Init(C_PORT, (GPIO_Pin_TypeDef)C_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_Init(D_PORT, (GPIO_Pin_TypeDef)D_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_Init(E_PORT, (GPIO_Pin_TypeDef)E_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_Init(F_PORT, (GPIO_Pin_TypeDef)F_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_Init(G_PORT, (GPIO_Pin_TypeDef)G_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_Init(DOT_PORT, (GPIO_Pin_TypeDef)DOT_PIN,      GPIO_MODE_OUT_PP_HIGH_FAST);
   
    GPIO_Init(R_PORT, (GPIO_Pin_TypeDef)R_PIN, GPIO_MODE_OUT_PP_HIGH_FAST);
    GPIO_WriteLow(R_PORT, (GPIO_Pin_TypeDef)R_PIN);   
    GPIO_Init(NUT_PORT, (GPIO_Pin_TypeDef)NUT_PIN, GPIO_MODE_IN_FL_NO_IT );
   
     enableInterrupts();
  while (1)
  {

    ////////////////////////////////////////////////////////////////////////
    switch(menu)
    {
        case 0:
        {
            for(i=0;i<50;i++)
            {
                adc_val += ADC1_GetConversionValue ();
                delay(10);
            }
            adc_val=adc_val/50;
            min=adc_val/33;
            if(min>=30)min=30; // chỉnh max thời gian hẹn là 30 phút      
            sec=0;
            GPIO_WriteLow(R_PORT, (GPIO_Pin_TypeDef)R_PIN);   
            hienthi_led7seg(min,0);
            break;
        }
        case 1:
        {
            if(min==0)GPIO_WriteLow(R_PORT, (GPIO_Pin_TypeDef)R_PIN);   
            else GPIO_WriteHigh(R_PORT, (GPIO_Pin_TypeDef)R_PIN);   
            hienthi_led7seg(min,dot_set);
            break;
        }
    }

////////////////////////////////////////////////////////////////////////////
  }

}

/**
  * @brief Delay
  * @param nCount
  * @retval None
  */


#ifdef USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *   where the assert_param error has occurred.
  * @param file: pointer to the source file name
  * @param line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/**
  * @}
  */

/******************* (C) COPYRIGHT 220von *****END OF FILE****/



Và cuối cùng là hàm ngắt phục vụ cho phần đếm thời gian :

/**
  ******************************************************************************
  * @file     stm8s_it.c
  * @author   MCD Application Team
  * @version  V2.0.1
  * @date     18-November-2011
  * @brief    Main Interrupt Service Routines.
  ******************************************************************************
  * @attention
  *
  * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
  * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
  * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
  * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
  * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
  * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
  *
  * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/

#include "stm8s_it.h"
#include "stm8s_tim1.h"
#include "main.h"
#include "stm8s_tim4.h"
#include "stm8s_gpio.h"


/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/* Public functions ----------------------------------------------------------*/

/** @addtogroup GPIO_Toggle
  * @{
  */
#ifdef _COSMIC_
/**
  * @brief  Dummy interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(NonHandledInterrupt, 25)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#endif /*_COSMIC_*/

/**
  * @brief  TRAP interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER_TRAP(TRAP_IRQHandler)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
/**
  * @brief  Top Level Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(TLI_IRQHandler, 0)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  Auto Wake Up Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(AWU_IRQHandler, 1)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  Clock Controller Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(CLK_IRQHandler, 2)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  External Interrupt PORTA Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(EXTI_PORTA_IRQHandler, 3)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  External Interrupt PORTB Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(EXTI_PORTB_IRQHandler, 4)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  External Interrupt PORTC Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(EXTI_PORTC_IRQHandler, 5)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  External Interrupt PORTD Interrupt routine
  * @param  None
  * @retval None
  */
   
   
INTERRUPT_HANDLER(EXTI_PORTD_IRQHandler, 6)
{
   

  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  External Interrupt PORTE Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(EXTI_PORTE_IRQHandler, 7)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#ifdef STM8S903
/**
  * @brief  External Interrupt PORTF Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(EXTI_PORTF_IRQHandler, 8)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#endif /*STM8S903*/

#if defined (STM8S208) || defined (STM8AF52Ax)
/**
  * @brief CAN RX Interrupt routine.
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(CAN_RX_IRQHandler, 8)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  CAN TX Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(CAN_TX_IRQHandler, 9)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#endif /*STM8S208 || STM8AF52Ax */

/**
  * @brief  SPI Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(SPI_IRQHandler, 10)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  Timer1 Update/Overflow/Trigger/Break Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(TIM1_UPD_OVF_TRG_BRK_IRQHandler, 11)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  Timer1 Capture/Compare Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(TIM1_CAP_COM_IRQHandler, 12)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

#ifdef STM8S903
/**
  * @brief  Timer5 Update/Overflow/Break/Trigger Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(TIM5_UPD_OVF_BRK_TRG_IRQHandler, 13)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
/**
  * @brief  Timer5 Capture/Compare Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(TIM5_CAP_COM_IRQHandler, 14)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

#else /*STM8S208, STM8S207, STM8S105 or STM8S103 or STM8AF62Ax or STM8AF52Ax or STM8AF626x */
/**
  * @brief  Timer2 Update/Overflow/Break Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(TIM2_UPD_OVF_BRK_IRQHandler, 13)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  Timer2 Capture/Compare Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(TIM2_CAP_COM_IRQHandler, 14)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#endif /*STM8S903*/

#if defined (STM8S208) || defined(STM8S207) || defined(STM8S007) || defined(STM8S105) || \
    defined(STM8S005) ||  defined (STM8AF62Ax) || defined (STM8AF52Ax) || defined (STM8AF626x)
/**
  * @brief Timer3 Update/Overflow/Break Interrupt routine.
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(TIM3_UPD_OVF_BRK_IRQHandler, 15)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  Timer3 Capture/Compare Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(TIM3_CAP_COM_IRQHandler, 16)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#endif /*STM8S208, STM8S207 or STM8S105 or STM8AF62Ax or STM8AF52Ax or STM8AF626x */

#if defined (STM8S208) || defined(STM8S207) || defined(STM8S007) || defined(STM8S103) || \
    defined(STM8S003) ||  defined (STM8AF62Ax) || defined (STM8AF52Ax) || defined (STM8S903)
/**
  * @brief  UART1 TX Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(UART1_TX_IRQHandler, 17)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @brief  UART1 RX Interrupt routine
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(UART1_RX_IRQHandler, 18)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#endif /*STM8S105*/

/**
  * @brief  I2C Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(I2C_IRQHandler, 19)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

#if defined(STM8S105) || defined(STM8S005) ||  defined (STM8AF626x)
/**
  * @brief  UART2 TX interrupt routine.
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(UART2_TX_IRQHandler, 20)
{
    /* In order to detect unexpected events during development,
       it is recommended to set a breakpoint on the following instruction.
    */
  }

/**
  * @brief  UART2 RX interrupt routine.
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(UART2_RX_IRQHandler, 21)
{
    /* In order to detect unexpected events during development,
       it is recommended to set a breakpoint on the following instruction.
    */
  }
#endif /* STM8S105*/

#if defined(STM8S207) || defined(STM8S007) || defined(STM8S208) || defined (STM8AF52Ax) || defined (STM8AF62Ax)
/**
  * @brief  UART3 TX interrupt routine.
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(UART3_TX_IRQHandler, 20)
{
    /* In order to detect unexpected events during development,
       it is recommended to set a breakpoint on the following instruction.
    */
  }

/**
  * @brief  UART3 RX interrupt routine.
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(UART3_RX_IRQHandler, 21)
{
    /* In order to detect unexpected events during development,
       it is recommended to set a breakpoint on the following instruction.
    */
  }
#endif /*STM8S208 or STM8S207 or STM8AF52Ax or STM8AF62Ax */

#if defined(STM8S207) || defined(STM8S007) || defined(STM8S208) || defined (STM8AF52Ax) || defined (STM8AF62Ax)
/**
  * @brief  ADC2 interrupt routine.
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(ADC2_IRQHandler, 22)
{

    /* In order to detect unexpected events during development,
       it is recommended to set a breakpoint on the following instruction.
    */
    return;

}
#else /*STM8S105, STM8S103 or STM8S903 or STM8AF626x */
/**
  * @brief  ADC1 interrupt routine.
  * @param  None
  * @retval None
  */
 INTERRUPT_HANDLER(ADC1_IRQHandler, 22)
{

    /* In order to detect unexpected events during development,
       it is recommended to set a breakpoint on the following instruction.
    */
    return;

}
#endif /*STM8S208 or STM8S207 or STM8AF52Ax or STM8AF62Ax */

#ifdef STM8S903
/**
  * @brief  Timer6 Update/Overflow/Trigger Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(TIM6_UPD_OVF_TRG_IRQHandler, 23)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#else /*STM8S208, STM8S207, STM8S105 or STM8S103 or STM8AF62Ax or STM8AF52Ax or STM8AF626x */
/**
  * @brief  Timer4 Update/Overflow Interrupt routine
  * @param  None
  * @retval None
  */
   
extern u8 quetled;
extern  BitStatus dot_set,menu;
BitStatus nut_set =0;
u16 msec=0;
u8 count=0;
extern u8 sec;
extern u8 min;
 INTERRUPT_HANDLER(TIM4_UPD_OVF_IRQHandler, 23) // ngắt timer
{
   
      /* Cleat Interrupt Pending bit */
    msec++;
  if(msec>=1000){sec++;msec=0;dot_set ^= 1;}
  if(sec>=60){min--;sec=0;}
  if(min==0){menu=0;sec=0;}
    quetled++;
    if(quetled>2)quetled=0;
   
    if((!(GPIO_ReadInputPin(NUT_PORT,(GPIO_Pin_TypeDef)NUT_PIN)))&&(nut_set==1))count++;
  if(GPIO_ReadInputPin(NUT_PORT,(GPIO_Pin_TypeDef)NUT_PIN)) {count=0;nut_set=1;}
   
  if(count>=100){menu ^=1;nut_set=0;count=0;}
  TIM4_ClearITPendingBit(TIM4_IT_UPDATE);
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}
#endif /*STM8S903*/

/**
  * @brief  Eeprom EEC Interrupt routine
  * @param  None
  * @retval None
  */
INTERRUPT_HANDLER(EEPROM_EEC_IRQHandler, 24)
{
  /* In order to detect unexpected events during development,
     it is recommended to set a breakpoint on the following instruction.
  */
}

/**
  * @}
  */

/******************* (C) COPYRIGHT 220von *****END OF FILE****/

Toàn bộ chi phí linh kiện chế tạo mạch này rơi vào khoản 60k

Nếu các bạn muốn hợp tác với mình để mở rộng chức năng cho ứng dụng này hoặc chia sẻ ý tưởng ứng dụng vào cuộc sống thì gửi mail cho mình theo địa chỉ : 220von.com@gmail.com
Hoặc theo dõi trang fan page facebook : https://www.facebook.com/220von/

Thứ Tư, 18 tháng 10, 2017

Điều khiển góc quay 10 động cơ servo từ xa bằng biến trở dùng NRF24L01 - 2.4GHz

Chào các bạn !
220von tiếp tục chia sẽ toàn bộ project điều khiển góc quay 10 động cơ servo từ xa bằng 10 biến trở dùng module NRF24L01 và IC vi điều khiển PIC16F886

Khoảng cách khi dùng module này là 10m trở lại , nếu dùng module có PA công xuất cao hơn thì khoản cách thu phát lên đến 500m
Ảnh chụp mạch thực tế :




Sơ đồ mạch thu và phát :
 
sơ đồ mạch thu


sơ đồ mạch phát

Video test mạch :



Code C của mạch phát : 
////////////////////////////////////////////////
Blog : 220von.blogspot.com

Email : 220von.com@gmail.com
///////////////////////////////////////////////
#include <16F886.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 NOMCLR                   //Master Clear pin used for I/O
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NOCPD                    //No EE protection
#FUSES NOBROWNOUT               //No brownout reset
#FUSES IESO                     //Internal External Switch Over mode enabled
#FUSES FCMEN                    //Fail-safe clock monitor enabled
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NODEBUG                  //No Debug mode for ICD
#FUSES NOWRT                    //Program memory not write protected
#FUSES BORV40                   //Brownout reset at 4.0V
#FUSES RESERVED                 //Used to set the reserved FUSE bits

#use delay(clock=16000000)

extern unsigned char TxBuf[32];
//*********************************************NRF24L01*************************************
#define TX_ADR_WIDTH    5      // 5 uints TX address width
#define RX_ADR_WIDTH    5      // 5 uints RX address width
#define TX_PLOAD_WIDTH  10     // 32 uints TX payload
#define RX_PLOAD_WIDTH  10     // 32 uints TX payload

//***************************************NRF24L01*******************************************************
#define READ_REG        0x00     //
#define WRITE_REG       0x20    //
#define RD_RX_PLOAD     0x61     //
#define WR_TX_PLOAD     0xA0     //
#define FLUSH_TX        0xE1    //
#define FLUSH_RX        0xE2     //
#define REUSE_TX_PL     0xE3     //
#define NOP             0xFF     //
//*************************************SPI(nRF24L01)·****************************************************
#define CONFIG          0x00  //
#define EN_AA           0x01  //
#define EN_RXADDR       0x02  //
#define SETUP_AW        0x03  //
#define SETUP_RETR      0x04  //
#define RF_CH           0x05  //
#define RF_SETUP        0x06  //
#define STATUS          0x07  //
#define OBSERVE_TX      0x08  // ·
#define CD              0x09  //
#define RX_ADDR_P0      0x0A  //
#define RX_ADDR_P1      0x0B  //
#define RX_ADDR_P2      0x0C  //
#define RX_ADDR_P3      0x0D  //
#define RX_ADDR_P4      0x0E  //
#define RX_ADDR_P5      0x0F  //
#define TX_ADDR         0x10  //
#define RX_PW_P0        0x11  //
#define RX_PW_P1        0x12  //
#define RX_PW_P2        0x13  //
#define RX_PW_P3        0x14  //
#define RX_PW_P4        0x15  //
#define RX_PW_P5        0x16  //
#define FIFO_STATUS     0x17  //
//**************************************************************************************
#define CE PIN_C7
#define CSN PIN_C3
#define SCK PIN_C6
#define MOSI PIN_C2
#define MISO PIN_C5
#define LED PIN_C1
//**************************************************************************************
unsigned char TxBuf[10]=
{
   0x01,0x02,0x03,0x4,0x05,0x06,0x07,0x08,
   0x09,0x10,
};
unsigned char  TX_ADDRESS[TX_ADR_WIDTH]= {0x34,0x43,0x10,0x10,0x01};   //
unsigned char  RX_ADDRESS[RX_ADR_WIDTH]= {0x34,0x43,0x10,0x10,0x01};   //
//****************************************************************************************
void init_NRF24L01(void);
unsigned char SPI_RW(unsigned char Buff);
unsigned char SPI_Read_reg(unsigned char reg);
unsigned char SPI_RW_Reg(unsigned char reg, unsigned char value);
unsigned char SPI_Read_Buf(unsigned char reg, unsigned char *pBuf, unsigned char uchars);
unsigned char SPI_Write_Buf(unsigned char reg, unsigned char *pBuf, unsigned uchars);
void SetRX_Mode(void);
void SetTX_Mode(void);
unsigned char nRF24L01_RxPacket(unsigned char* rx_buf);
void nRF24L01_TxPacket(unsigned char * tx_buf);

// -------------------------------------------------------
void main()
{
 set_tris_c(0b00100000);
 output_c(0x00);
 char RxBuf[10];
 setup_adc_ports(sAN0|sAN1|sAN2|sAN3|sAN4|sAN8|sAN9|sAN10|sAN11|sAN12|VSS_VDD);
 setup_adc(ADC_CLOCK_DIV_2);
 delay_ms(1000);
 init_NRF24L01(); 
 SetTX_Mode();
 char sv1,sv2,sv3,sv4,sv5;
 char sv6,sv7,sv8,sv9,sv10;
 while(true)
  {
           set_adc_channel(0);
           delay_us(10);
           sv1 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[0] = sv1;
           delay_us(10);
          
           set_adc_channel(1);
           delay_us(10);
           sv2 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[1] = sv2;
           delay_us(10);       

           set_adc_channel(2);
           delay_us(10);
           sv3 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[2] = sv3;
           delay_us(10);
          
           set_adc_channel(3);
           delay_us(10);
           sv4 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[3] = sv4;
           delay_us(10);        
          
           set_adc_channel(4);
           delay_us(10);
           sv5 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[4] = sv5;
           delay_us(10);          
/////////////////////////////////////////
           set_adc_channel(11);
           delay_us(10);
           sv6 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[5] = sv6;
           delay_us(10);
          
           set_adc_channel(9);
           delay_us(10);
           sv7 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[6] = sv7;
           delay_us(10);

           set_adc_channel(8);
           delay_us(10);
           sv8 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[7] = sv8;
           delay_us(10);          
          
           set_adc_channel(10);
           delay_us(10);
           sv9 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[8] = sv9;
           delay_us(10);
          
           set_adc_channel(12);
           delay_us(10);
           sv10 = 6 + read_adc()/13;
           delay_us(10);
           RxBuf[9] = sv10;
           delay_us(10);         
/////////////////////////////////////////////////////////////          
          //  SetTX_Mode();              
          //  delay_ms(10);
            nRF24L01_TxPacket(RxBuf); // Transmit Tx buffer data
            SPI_RW_Reg(WRITE_REG+STATUS,0XFF); // Clear Bit Send
            output_toggle(LED);
            delay_ms(1);
  }
}
//*NRF24L01
//***************************************************************************************/
void init_NRF24L01(void)
{
     delay_us(100);
   output_low(CE);    // chip enable
   output_high(CSN);   // Spi disable
   output_low(SCK);   // Spi clock line init high
   SPI_Write_Buf(WRITE_REG + TX_ADDR, TX_ADDRESS, TX_ADR_WIDTH);    //
   SPI_Write_Buf(WRITE_REG + RX_ADDR_P0, RX_ADDRESS, RX_ADR_WIDTH); //
   SPI_RW_Reg(WRITE_REG + EN_AA, 0x01);      // EN P0, 2-->P1
   SPI_RW_Reg(WRITE_REG + EN_RXADDR, 0x01);  //Enable data P0
   SPI_RW_Reg(WRITE_REG + RF_CH, 0);        // Chanel 0 RF = 2400 + RF_CH* (1or 2 M)
   SPI_RW_Reg(WRITE_REG + RX_PW_P0, RX_PLOAD_WIDTH); // Do rong data truyen 32 byte
   SPI_RW_Reg(WRITE_REG + RF_SETUP, 0x07);         // 1M, 0dbm
   SPI_RW_Reg(WRITE_REG + CONFIG, 0x0e);          // Enable CRC, 2 byte CRC, Send

}
/****************************************************************************************************/
//unsigned char SPI_RW(unsigned char Buff)
//NRF24L01
/****************************************************************************************************/
unsigned char SPI_RW(unsigned char Buff)
{
      unsigned char bit_ctr;
      for(bit_ctr=0;bit_ctr<8;bit_ctr++) // output 8-bit
      {
         if(Buff & 0x80) output_high(MOSI) ;   // output 'uchar', MSB to MOSI 
         else output_low(MOSI);
         delay_us(5);
         Buff = (Buff << 1);           // shift next bit into MSB..
         output_high(SCK);                      // Set SCK high..         
         delay_us(5);
         if((input(MISO))==1)Buff |= 0x01;             // capture current MISO bit
         output_low(SCK);                    // ..then set SCK low again
      }
      return(Buff);                   // return read uchar
}
/****************************************************************************************************/
//unsigned char SPI_Read(unsigned char reg)
//NRF24L01
/****************************************************************************************************/
unsigned char SPI_Read_reg(unsigned char reg)
{
   unsigned char reg_val=0;
   output_low(CSN);                // CSN low, initialize SPI communication...
   SPI_RW(reg);            // Select register to read from..
   reg_val = SPI_RW(0);    // ..then read registervalue
   output_high(CSN);                // CSN high, terminate SPI communication
   return (reg_val);        // return register value
}
/****************************************************************************************************/
//unsigned char SPI_RW_Reg(unsigned char reg, unsigned char value)
/****************************************************************************************************/
unsigned char SPI_RW_Reg(unsigned char reg,unsigned char value)
{
   unsigned char status1;
   output_low(CSN);                   // CSN low, init SPI transaction
   status1 = SPI_RW(reg);      // select register
   SPI_RW(value);             // ..and write value to it..
   output_high(CSN);     // CSN high again
   return(status1);            // return nRF24L01 status uchar
}
/****************************************************************************************************/
//unsigned char SPI_Read_Buf(unsigned char reg, unsigned char *pBuf, unsigned char uchars)
//
/****************************************************************************************************/
unsigned char SPI_Read_Buf(unsigned char reg,unsigned char *pBuf,unsigned char uchars)
{
   unsigned char status1,uchar_ctr;

   output_low(CSN);                           // Set CSN low, init SPI tranaction
   status1 = SPI_RW(reg);             // Select register to write to and read status uchar
   for(uchar_ctr=0;uchar_ctr<uchars;uchar_ctr++) pBuf[uchar_ctr] = SPI_RW(0);    //
   output_high(CSN);
   return(status1);                    // return nRF24L01 status uchar
}
/*********************************************************************************************************/
//uint SPI_Write_Buf(uchar reg, uchar *pBuf, uchar uchars)
/*****************************************************************************************************/
unsigned char SPI_Write_Buf(unsigned char reg,unsigned char *pBuf,unsigned char uchars)
{
   unsigned char status1,uchar_ctr;
   output_low(CSN);           //SPI
   status1 = SPI_RW(reg);
   for(uchar_ctr=0; uchar_ctr<uchars; uchar_ctr++) //
   SPI_RW(*pBuf++);
   output_high(CSN);           //SPI
   return(status1);    //
}
/****************************************************************************************************/
//void SetRX_Mode(void)
//
/****************************************************************************************************/
void SetRX_Mode(void)
{
   output_low(CE);
   SPI_RW_Reg(WRITE_REG + CONFIG, 0x0f);         // Enable CRC, 2 byte CRC, Recive
   output_high(CE);
   delay_us(130);    //
}
/****************************************************************************************************/
//void SetTX_Mode(void)
//
/****************************************************************************************************/
void SetTX_Mode(void)
{
   output_low(CE);
   SPI_RW_Reg(WRITE_REG + CONFIG, 0x0e);         // Enable CRC, 2 byte CRC, Send
   output_high(CE);
   delay_us(130);    //
}

/******************************************************************************************************/
//unsigned char nRF24L01_RxPacket(unsigned char* rx_buf)
/******************************************************************************************************/
unsigned char nRF24L01_RxPacket(unsigned char* rx_buf)
{
    unsigned char revale=0;
    unsigned char sta;
   //if(RX_DR)            // Data in RX FIFO
   sta=SPI_Read_reg(STATUS);   // Read Status 
   if(sta&0x40)      // Data in RX FIFO
   {
      output_low(CE);          //SPI
      SPI_Read_Buf(RD_RX_PLOAD,rx_buf,TX_PLOAD_WIDTH);// read receive payload from RX_FIFO buffer
      revale =1;  
   }
   SPI_RW_Reg(WRITE_REG+STATUS,sta);
   return(revale);
}
/***********************************************************************************************************/
//void nRF24L01_TxPacket(unsigned char * tx_buf)
//
/**********************************************************************************************************/
void nRF24L01_TxPacket(unsigned char * tx_buf)
{
   output_low(CE);     
   SPI_Write_Buf(WRITE_REG + RX_ADDR_P0, TX_ADDRESS, TX_ADR_WIDTH); // Send Address
   SPI_Write_Buf(WR_TX_PLOAD, tx_buf, TX_PLOAD_WIDTH);           //send data
   SPI_RW_Reg(WRITE_REG + CONFIG, 0x0e);          // Send Out
   output_high(CE);      
}

// --------------------END OF FILE------------------------
// -------------------------------------------------------



Code C mạch thu :

////////////////////////////////////////////////
Blog : 220von.blogspot.com

Email : 220von.com@gmail.com
///////////////////////////////////////////////

#include <16F886.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 NOMCLR                   //Master Clear pin used for I/O
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NOCPD                    //No EE protection
#FUSES NOBROWNOUT               //No brownout reset
#FUSES IESO                     //Internal External Switch Over mode enabled
#FUSES FCMEN                    //Fail-safe clock monitor enabled
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NODEBUG                  //No Debug mode for ICD
#FUSES NOWRT                    //Program memory not write protected
#FUSES BORV40                   //Brownout reset at 4.0V
#FUSES RESERVED                 //Used to set the reserved FUSE bits

#use delay(clock=16000000)

//************************************************************************************************8

extern unsigned char TxBuf[32];
//*********************************************NRF24L01*************************************
#define TX_ADR_WIDTH    5      // 5 uints TX address width
#define RX_ADR_WIDTH    5      // 5 uints RX address width
#define TX_PLOAD_WIDTH  10     // 32 uints TX payload
#define RX_PLOAD_WIDTH  10     // 32 uints TX payload

//***************************************NRF24L01*******************************************************
#define READ_REG        0x00     //
#define WRITE_REG       0x20    //
#define RD_RX_PLOAD     0x61     //
#define WR_TX_PLOAD     0xA0     //
#define FLUSH_TX        0xE1    //
#define FLUSH_RX        0xE2     //
#define REUSE_TX_PL     0xE3     //
#define NOP             0xFF     //
//*************************************SPI(nRF24L01)·****************************************************
#define CONFIG          0x00  //
#define EN_AA           0x01  //
#define EN_RXADDR       0x02  //
#define SETUP_AW        0x03  //
#define SETUP_RETR      0x04  //
#define RF_CH           0x05  //
#define RF_SETUP        0x06  //
#define STATUS          0x07  //
#define OBSERVE_TX      0x08  // ·
#define CD              0x09  //
#define RX_ADDR_P0      0x0A  //
#define RX_ADDR_P1      0x0B  //
#define RX_ADDR_P2      0x0C  //
#define RX_ADDR_P3      0x0D  //
#define RX_ADDR_P4      0x0E  //
#define RX_ADDR_P5      0x0F  //
#define TX_ADDR         0x10  //
#define RX_PW_P0        0x11  //
#define RX_PW_P1        0x12  //
#define RX_PW_P2        0x13  //
#define RX_PW_P3        0x14  //
#define RX_PW_P4        0x15  //
#define RX_PW_P5        0x16  //
#define FIFO_STATUS     0x17  //
//**************************************************************************************
#define CE PIN_C7
#define CSN PIN_C3
#define SCK PIN_C6
#define MOSI PIN_C2
#define MISO PIN_C5
#define LED PIN_C1
//**************************************************************************************
unsigned char TxBuf[10]=
{
   0x01,0x02,0x03,0x4,0x05,0x06,0x07,0x08,
   0x09,0x10,
};
unsigned char  TX_ADDRESS[TX_ADR_WIDTH]= {0x34,0x43,0x10,0x10,0x01};   //
unsigned char  RX_ADDRESS[RX_ADR_WIDTH]= {0x34,0x43,0x10,0x10,0x01};   //
//****************************************************************************************
void init_NRF24L01(void);
unsigned char SPI_RW(unsigned char Buff);
unsigned char SPI_Read_reg(unsigned char reg);
unsigned char SPI_RW_Reg(unsigned char reg, unsigned char value);
unsigned char SPI_Read_Buf(unsigned char reg, unsigned char *pBuf, unsigned char uchars);
unsigned char SPI_Write_Buf(unsigned char reg, unsigned char *pBuf, unsigned uchars);
void SetRX_Mode(void);
void SetTX_Mode(void);
unsigned char nRF24L01_RxPacket(unsigned char* rx_buf);
void nRF24L01_TxPacket(unsigned char * tx_buf);
 char count=0;
 char sv1=15,sv2=15,sv3=15,sv4=15,sv5=15;
 char sv6=15,sv7=15,sv8=15,sv9=15,sv10=15;
// -------------------------------------------------------
#int_TIMER0
void  TIMER0_isr(void)
{
set_timer0(168);
count++;
if(count>=200)
  {
 
  output_b(0xFF);
  output_a(0xFF);
  count=0;
  }
 if(count>=sv1)output_low(PIN_A0); 
 if(count>=sv2)output_low(PIN_A1);
 if(count>=sv3)output_low(PIN_A2);
 if(count>=sv4)output_low(PIN_A3);
 if(count>=sv5)output_low(PIN_A4);
 /////////////////////////////////
 if(count>=sv6)output_low(PIN_B6);
 if(count>=sv7)output_low(PIN_B5);
 if(count>=sv8)output_low(PIN_B4);
 if(count>=sv9)output_low(PIN_B3);
 if(count>=sv10)output_low(PIN_B2);
}
void main()
{
 set_tris_c(0b00100000);
 set_tris_b(0x00);
 set_tris_a(0x00);
 output_a(0x00);
 output_b(0x00);
 output_c(0x00);
 delay_ms(1000);
 setup_timer_0(RTCC_INTERNAL|RTCC_DIV_4);
 set_timer0(164);
 setup_timer_1(T1_DISABLED);
 setup_timer_2(T2_DISABLED,0,1);
 char RxBuf[10];
 output_low(LED); 
 init_NRF24L01(); 
 SetRX_Mode();
 enable_interrupts(INT_TIMER0);
 enable_interrupts(GLOBAL);
 char st=0;
 while(true)
  {
   if(nRF24L01_RxPacket(RxBuf)==1)   // Neu nhan duoc du lieu
       {  
       sv1=RxBuf[0];
       sv2=RxBuf[1];
       sv3=RxBuf[2];
       sv4=RxBuf[3];
       sv5=RxBuf[4];
       ////////////
       sv6=RxBuf[5];
       sv7=RxBuf[6];
       sv8=RxBuf[7];
       sv9=RxBuf[8];
       sv10=RxBuf[9];
       output_toggle(LED);
       SetRX_Mode();
       } 
  }
}

//*NRF24L01
//***************************************************************************************/
void init_NRF24L01(void)
{
     delay_us(100);
   output_low(CE);    // chip enable
   output_high(CSN);   // Spi disable
   output_low(SCK);   // Spi clock line init high
   SPI_Write_Buf(WRITE_REG + TX_ADDR, TX_ADDRESS, TX_ADR_WIDTH);    //
   SPI_Write_Buf(WRITE_REG + RX_ADDR_P0, RX_ADDRESS, RX_ADR_WIDTH); //
   SPI_RW_Reg(WRITE_REG + EN_AA, 0x01);      // EN P0, 2-->P1
   SPI_RW_Reg(WRITE_REG + EN_RXADDR, 0x01);  //Enable data P0
   SPI_RW_Reg(WRITE_REG + RF_CH, 0);        // Chanel 0 RF = 2400 + RF_CH* (1or 2 M)
   SPI_RW_Reg(WRITE_REG + RX_PW_P0, RX_PLOAD_WIDTH); // Do rong data truyen 32 byte
   SPI_RW_Reg(WRITE_REG + RF_SETUP, 0x07);         // 1M, 0dbm
   SPI_RW_Reg(WRITE_REG + CONFIG, 0x0e);          // Enable CRC, 2 byte CRC, Send

}
/****************************************************************************************************/
//unsigned char SPI_RW(unsigned char Buff)
//NRF24L01
/****************************************************************************************************/
unsigned char SPI_RW(unsigned char Buff)
{
      unsigned char bit_ctr;
      for(bit_ctr=0;bit_ctr<8;bit_ctr++) // output 8-bit
      {
         if(Buff & 0x80) output_high(MOSI) ; // output 'uchar', MSB to MOSI 
         else output_low(MOSI);
         delay_us(5);
         Buff = (Buff << 1);           // shift next bit into MSB..
         output_high(SCK);                      // Set SCK high..         
         delay_us(5);
         if((input(MISO))==1)Buff |= 0x01;               // capture current MISO bit
         output_low(SCK);                    // ..then set SCK low again
      }
      return(Buff);                   // return read uchar
}
/****************************************************************************************************/
//unsigned char SPI_Read(unsigned char reg)
//NRF24L01
/****************************************************************************************************/
unsigned char SPI_Read_reg(unsigned char reg)
{
   unsigned char reg_val;
   output_low(CSN);                // CSN low, initialize SPI communication...
   SPI_RW(reg);            // Select register to read from..
   reg_val = SPI_RW(0);    // ..then read registervalue
   output_high(CSN);                // CSN high, terminate SPI communication
   return (reg_val);        // return register value
}
/****************************************************************************************************/
//unsigned char SPI_RW_Reg(unsigned char reg, unsigned char value)
/****************************************************************************************************/
unsigned char SPI_RW_Reg(unsigned char reg,unsigned char value)
{
   unsigned char status1;
   output_low(CSN);                   // CSN low, init SPI transaction
   status1 = SPI_RW(reg);      // select register
   SPI_RW(value);             // ..and write value to it..
   output_high(CSN);     // CSN high again
   return(status1);            // return nRF24L01 status uchar
}
/****************************************************************************************************/
//unsigned char SPI_Read_Buf(unsigned char reg, unsigned char *pBuf, unsigned char uchars)
//
/****************************************************************************************************/
unsigned char SPI_Read_Buf(unsigned char reg,unsigned char *pBuf,unsigned char uchars)
{
   unsigned char status1,uchar_ctr;
   output_low(CSN);                           // Set CSN low, init SPI tranaction
   status1 = SPI_RW(reg);             // Select register to write to and read status uchar
   for(uchar_ctr=0;uchar_ctr<uchars;uchar_ctr++) pBuf[uchar_ctr] = SPI_RW(0);    //
   output_high(CSN);
   return(status1);                    // return nRF24L01 status uchar
}
/*********************************************************************************************************/
//uint SPI_Write_Buf(uchar reg, uchar *pBuf, uchar uchars)
/*****************************************************************************************************/
unsigned char SPI_Write_Buf(unsigned char reg,unsigned char *pBuf,unsigned char uchars)
{
   unsigned char status1,uchar_ctr;
   output_low(CSN);           //SPI
   status1 = SPI_RW(reg);
   for(uchar_ctr=0; uchar_ctr<uchars; uchar_ctr++) //
   SPI_RW(*pBuf++);
   output_high(CSN);           //SPI
   return(status1);    //
}
/****************************************************************************************************/
//void SetRX_Mode(void)
//
/****************************************************************************************************/
void SetRX_Mode(void)
{
   output_low(CE);
   SPI_RW_Reg(WRITE_REG + CONFIG, 0x0f);         // Enable CRC, 2 byte CRC, Recive
   output_high(CE);
   delay_us(130);    //
}
/****************************************************************************************************/
//void SetTX_Mode(void)
//
/****************************************************************************************************/
void SetTX_Mode(void)
{
   output_low(CE);
   SPI_RW_Reg(WRITE_REG + CONFIG, 0x0e);         // Enable CRC, 2 byte CRC, Send
   output_high(CE);
   delay_us(130);    //
}

/******************************************************************************************************/
//unsigned char nRF24L01_RxPacket(unsigned char* rx_buf)
/******************************************************************************************************/
unsigned char nRF24L01_RxPacket(unsigned char* rx_buf)
{
    unsigned char revale=0;
    unsigned char sta;
   //if(RX_DR)            // Data in RX FIFO
   sta=SPI_Read_reg(STATUS);   // Read Status 
   if(sta&0x40)      // Data in RX FIFO
   {
      output_low(CE);          //SPI
      SPI_Read_Buf(RD_RX_PLOAD,rx_buf,TX_PLOAD_WIDTH);// read receive payload from RX_FIFO buffer
      revale =1;  
   }
   SPI_RW_Reg(WRITE_REG+STATUS,sta);
   return(revale);
}
/***********************************************************************************************************/
//void nRF24L01_TxPacket(unsigned char * tx_buf)
//
/**********************************************************************************************************/
void nRF24L01_TxPacket(unsigned char * tx_buf)
{
   output_low(CE);     
   SPI_Write_Buf(WRITE_REG + RX_ADDR_P0, TX_ADDRESS, TX_ADR_WIDTH); // Send Address
   SPI_Write_Buf(WR_TX_PLOAD, tx_buf, TX_PLOAD_WIDTH);           //send data
   SPI_RW_Reg(WRITE_REG + CONFIG, 0x0e);          // Send Out
   output_high(CE);      
}

// --------------------END OF FILE------------------------
// ------------------------------------------------------- 


 Các bạn có thể mở rộng code để điều khiển nhiều động cơ servo hơn

Nếu các bạn muốn hợp tác với mình để mở rộng chức năng cho ứng dụng này hoặc chia sẻ ý tưởng ứng dụng vào cuộc sống thì gửi mail cho mình theo địa chỉ : 220von.com@gmail.com
Hoặc theo dõi trang fan page facebook : https://www.facebook.com/220von/

Mạch test động cơ rc servo:

220von


220v



 

Mạch cảnh báo rò khí gas và chống trộm báo qua điện thoại bằng tin nhắn sms



Chào các bạn !
Hôm nay 220von tiếp tục chia sẽ với các bạn mạch chống trộm và cảnh báo rò khí gas báo qua tín nhắn sms
 + Mạch sẽ tự động bật còi hú khi cảm biến chống trộm hồng ngoại bị trộm kích hoạt và gửi tin nhắn sms cho chủ nhà qua điện thoại
 +  Bật relay quạt gió khi phát hiện rò rỉ khí gas và báo động còi hú , gửi tin nhắn sms cho chủ nhà biết qua điện thoại

Mạch sử dụng module sim 900A, vi điều khiển PIC16F877A

Video test mạch :


Sơ đồ và layout mạch in mình vẽ trên proteus :
220von

220von



Sơ đồ mạch nguồn 12V - 3.3V cấp cho mạch :
220von

Code C : mình viết trên phần mềm biên dịch CCS

#include <16F877A.h>
#include <def_877a.h>
#include <string.h>
#FUSES NOWDT                
#FUSES HS                      
#FUSES NOPUT                   
#FUSES NOPROTECT              
#FUSES NODEBUG              
#FUSES NOBROWNOUT            
#FUSES NOLVP                  
#FUSES NOCPD                  
#FUSES NOWRT                  
#FUSES RESERVED 

#use delay(clock=10000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
#include <ce_lcd.c>
#define use_portb_lcd TRUE
#define      PWU            RD6
#define      TXD            RC6
#define      RXD            RC7
#define  buffer_size          80      
char     buffer[buffer_size];          
int      xbuff=0x00;                 
char     c=0x00;                      
char     c1=0x00;                    
short    sms_mode=false;

char gas,ir;
int1 x=0,y=1;
char z=0;
char so[13]="01216512808";
void send_sms(char so[12],char vitri);
void erase_buffer(void);   
void init_sim900(void);   
void read_sms();          
void at(void);            
short wait_ok (void);     
short wait_error (void);  
/////////////////////////////////////////////////////////////////////////////////
#INT_RDA
RDA_isr()
   {
   c=getc();
      if(c=='*'){                
        c1=c;             
        xbuff=0;  
        }
   if (c=='#' && c1=='*')
      {
       sms_mode=true;
       }
   if (xbuff >= buffer_size) 
      {xbuff=0;}
      else{  buffer[xbuff++]=c;}
   return 0;
   }
//////////////////////////////////////////////////////////////////////////////  
void main()
{
char ir_temp;
set_tris_a(0b11111111);
set_tris_d(0x00);
set_tris_c(0b10000000);
RD3=0;RD2=0;
RD1=1;
RD7=1;
enable_interrupts(INT_RDA);
enable_interrupts(GLOBAL);
setup_adc(ADC_CLOCK_INTERNAL); 
setup_adc_ports(AN0_AN1_AN3);
lcd_init();
lcd_putc("\f");
lcd_gotoxy(1,1);
lcd_putc("Dang khoi dong..");
init_sim900();
RD7=0;
lcd_gotoxy(1,1);
lcd_putc("     xong...    ");
delay_ms(1500);
lcd_putc("\f");
lcd_putc("    Xin Chao    \n");
lcd_putc("   220von.com    ") ;
send_sms(so,1);
lcd_putc("\f");
lcd_putc(" Module SIM 900 \n");
lcd_putc(" ............... ") ;
delay_ms(1000);
set_adc_channel(1);
delay_us(20);
ir_temp=read_adc();
delay_us(20);

lcd_putc("\f");
while(true)
 {
  set_adc_channel(0);
  delay_us(20);
  gas=read_adc();
  delay_us(20);
  set_adc_channel(1);
  delay_us(20);
  ir=read_adc();
  delay_us(20);
  if((gas>120)&&(x==1)){z=1;RD3=1;RD2=1;lcd_putc("\f");lcd_gotoxy(1,1);lcd_putc("Ro ri khi gas");
                        send_sms(so,3);

                        x=0;
                       }
  if((gas<100)&&(x==0)){x=1;lcd_putc("\f");lcd_gotoxy(1,1);lcd_putc("He thong an toan") ;z=0;}
  if(z==1){RD3=1;RD2=1;RD1=1;delay_ms(200);RD1=0;delay_ms(200);}
  if(z==2){RD2=1;RD1=1;delay_ms(200);RD1=0;delay_ms(200);}
  if(z==0){RD3=0;RD2=0;RD1=0;}
  if((ir<(ir_temp-30))&&(y==1)){z=2;RD2=1;lcd_putc("\f");lcd_gotoxy(1,0);lcd_putc("Co trom dot nhap");
                               send_sms(so,4);
                               y=0;
                               }
  if(sms_mode==TRUE){read_sms();erase_buffer();}
 }
}
/////////////////////////////////////////////////////////////////////////////////////////
void erase_buffer(void)
   {
   int i;
   for(i=0;i<buffer_size;i++){ buffer[i]=0x00;  }
   xbuff=0x00;
   c=0x00;
   c1=0x00;
   sms_mode=false;
   return;
   }
//////////////////////////////////////////////////////////////////////////////////////////
void init_sim900(void)
   {
   PWU=1;           
   delay_ms(1000);
   PWU=0;
   delay_ms(9000);
   do           
   {
   printf("AT");
   putc(13);  
   delay_ms(800);
   }
   while (wait_ok()==false);
   return;
   }
///////////////////////////////////////////////////////////////////////////////////////
 void read_sms() 
   {
   char *ptr;
   char text1[]="tat bao dong";
  
      ptr=strstr(buffer,text1);  
      if(strncmp(ptr,text1,12)==0)     
         {
         z=0;
         y=1;
         RD3=0;RD2=0;
         lcd_putc("\f");lcd_gotoxy(1,1);lcd_putc("He thong an toan");
         send_sms(so,2);
        
         }
   }
////////////////////////////////////////////////////////////////////////////////////////
void send_sms(char so[12],char vitri)
{
  printf("AT+CMGS=");
  delay_ms(100);
   putc(34); // "
   delay_ms(100);
   printf(so);
   delay_ms(100);
   putc(34); //
   printf(";");
   delay_ms(100);
   putc(13);  
   delay_ms(1500);
   switch(vitri)
    {
     case 0:break;
     case 1:
          {
          printf("Thiet bi da khoi dong thanh cong ...\n\r");
          break;
          }
     case 2:
          {
          printf("Da tat bao dong ...\n\r");
          break;
          }
     case 3:
          {
          printf("Canh bao ! : Phat hien ro ri khi GAS. Da bat quat thong gio...\n\r");
          break;
          }
     case 4:
          {
          printf("Canh bao ! : Co trom dot nhap vao nha. Da bat coi hu...\n\r");
          break;
          }         
    }
   delay_ms(1000);
   putc(26);
   delay_ms(6000);
}
///////////////////////////////////////////////////////////////////////////////////////////
void at(void)
{
   do                  
   {
   printf("AT");
   putc(13);
   delay_ms(1000);
   }
   while (wait_ok()==false);
   return;
}
///////////////////////////////////////////////////////////////////////////////////////
short wait_ok (void){
char *ptr;
char r1_ok[]="OK";
ptr=strstr(buffer,r1_ok);

if(strncmp(ptr,r1_ok,2)==0){
   return true;
   }
   else{return false;}
erase_buffer();
}


Nếu các bạn muốn hợp tác với mình để mở rộng chức năng cho ứng dụng này hoặc chia sẻ ý tưởng ứng dụng vào cuộc sống thì gửi mail cho mình theo địa chỉ : 220von.com@gmail.com
Hoặc theo dõi trang fan page facebook : https://www.facebook.com/220von/