<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>程式教學 &#8211; 龍冥 Blog</title>
	<atom:link href="https://dragongo.co/tag/%E7%A8%8B%E5%BC%8F%E6%95%99%E5%AD%B8/feed/" rel="self" type="application/rss+xml" />
	<link>https://dragongo.co</link>
	<description>Code &#38; Read</description>
	<lastBuildDate>Wed, 14 Jul 2021 06:59:37 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://dragongo.co/wp-content/uploads/2021/05/cropped-cropped-LOGO-2-e1655437907165-32x32.png</url>
	<title>程式教學 &#8211; 龍冥 Blog</title>
	<link>https://dragongo.co</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>PIC18單燈閃爍教學</title>
		<link>https://dragongo.co/pic18%e5%96%ae%e7%87%88%e9%96%83%e7%88%8d%e6%95%99%e5%ad%b8/</link>
		
		<dc:creator><![CDATA[龍冥]]></dc:creator>
		<pubDate>Tue, 13 Jul 2021 06:05:25 +0000</pubDate>
				<category><![CDATA[PIC18]]></category>
		<category><![CDATA[程式教學]]></category>
		<category><![CDATA[PIC18F25K83]]></category>
		<category><![CDATA[PIC18單燈閃爍]]></category>
		<guid isPermaLink="false">https://dragongo.co/?p=1595</guid>

					<description><![CDATA[基於上一篇文章「PIC18 Configurat&#8230;]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">基於上一篇文章「<a href="https://dragongo.co/pic18-configuration-bits%e6%95%99%e5%ad%b8%e5%9f%ba%e7%a4%8e%e8%a8%ad%e5%ae%9a/" target="_blank" data-type="URL" data-id="https://dragongo.co/pic18-configuration-bits%e6%95%99%e5%ad%b8%e5%9f%ba%e7%a4%8e%e8%a8%ad%e5%ae%9a/" rel="noreferrer noopener">PIC18 Configuration Bits教學(基礎設定)</a>」可以將PIC18的基礎設定設定完成，接下來這篇教學將教你如何用PIC18做一顆LED燈間隔一秒閃爍。</p>



<h2 class="wp-block-heading">目錄</h2>



<p class="wp-block-paragraph"><a href="#1" data-type="internal" data-id="#1">電路圖接線</a><br><a href="#2" data-type="internal" data-id="#2">完整的程式</a><br><a href="#3">Config Bits基礎設定</a><br><a href="#4">初始化設定</a><br><a href="#5">主程式</a><br><a href="#6">延伸思考</a></p>



<h2 class="wp-block-heading" id="1">電路圖接線</h2>



<p class="wp-block-paragraph">RB0為我們的LED燈輸出的腳位，MCLR要接reset按鈕，RA6、7接石英震盪器。（請接受我這畢卡索一般的畫.·´¯`(&gt;▂&lt;)´¯`·. ）</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img fetchpriority="high" decoding="async" src="https://dragongo.co/wp-content/uploads/2021/07/未命名-2-1.png" alt="未命名 2 1" class="wp-image-1615" width="698" height="510" title="PIC18單燈閃爍教學 1"></figure></div>



<h2 class="wp-block-heading" id="2">完整的程式</h2>



<pre><code class="c">/*
 * version:Y 2010707 V1.0
 * Blink the LED every second(RB0 output)
 * Config Bits：Watch dog timer:OFF、Extenal Oscillator(EXTTOSC)16MHZ(OSC1、OSC2)
*/
#include <xc.h>
#include "config.h"
#define _XTAL_FREQ 16000000
void Initial();

void main(void) {
    Initial();
    while(1){
        LATBbits.LATB0 = ~LATBbits.LATB0;
        __delay_ms(1000);
    }
    return;
}
void Initial(){
    TRISBbits.TRISB0 = 0;
    ANSELBbits.ANSELB0 = 1;
}
</xc.h></code></pre>



<p class="wp-block-paragraph">請點及此連結下載完整程式：<span class="removed_link" title="https://drive.google.com/file/d/19mzLzTu42GXtbv1cgaGvOQyanK07AqfS/view?usp=sharing"></span></p>



<h2 class="wp-block-heading" id="3">Config Bits基礎設定</h2>



<p class="wp-block-paragraph">Config Bits的基礎設定，做以下幾件事情：</p>



<ul class="wp-block-list"><li>關閉<a href="https://www.edntaiwan.com/20170630ta01-watchdog-timer/" target="_blank" data-type="URL" data-id="https://www.edntaiwan.com/20170630ta01-watchdog-timer/" rel="noreferrer noopener">看門狗</a>(WDT)，不是<a href="https://zh.wikipedia.org/zh-tw/%E7%9C%8B%E9%96%80%E7%8B%97_(%E9%81%8A%E6%88%B2)" target="_blank" data-type="URL" data-id="https://zh.wikipedia.org/zh-tw/%E7%9C%8B%E9%96%80%E7%8B%97_(%E9%81%8A%E6%88%B2)" rel="noreferrer noopener">看門狗</a>遊戲&#8230;（我知道那很好玩，我有玩?）</li><li>設定外接時英振盪器（16MHz,HS）</li><li>關閉CP保護，開啟他的話，燒錄程式碼後，此晶片會被燒死，無法重新寫入程式。</li></ul>



<pre><code class="c">// PIC18F25K83 Configuration Bit Settings

// 'C' source line config statements

// CONFIG1L
#pragma config FEXTOSC = HS     // External Oscillator Selection (HS (crystal oscillator) above 8 MHz; PFM set to high power)
#pragma config RSTOSC = EXTOSC  // Reset Oscillator Selection (EXTOSC operating per FEXTOSC bits (device manufacturing default))

// CONFIG1H
#pragma config CLKOUTEN = OFF   // Clock out Enable bit (CLKOUT function is disabled)
#pragma config PR1WAY = ON      // PRLOCKED One-Way Set Enable bit (PRLOCK bit can be cleared and set only once)
#pragma config CSWEN = ON       // Clock Switch Enable bit (Writing to NOSC and NDIV is allowed)
#pragma config FCMEN = ON       // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor enabled)

// CONFIG2L
#pragma config MCLRE = EXTMCLR  // MCLR Enable bit (If LVP = 0, MCLR pin is MCLR; If LVP = 1, RE3 pin function is MCLR )
#pragma config PWRTS = PWRT_OFF // Power-up timer selection bits (PWRT is disabled)
#pragma config MVECEN = ON      // Multi-vector enable bit (Multi-vector enabled, Vector table used for interrupts)
#pragma config IVT1WAY = ON     // IVTLOCK bit One-way set enable bit (IVTLOCK bit can be cleared and set only once)
#pragma config LPBOREN = OFF    // Low Power BOR Enable bit (ULPBOR disabled)
#pragma config BOREN = SBORDIS  // Brown-out Reset Enable bits (Brown-out Reset enabled , SBOREN bit is ignored)

// CONFIG2H
#pragma config BORV = VBOR_2P45 // Brown-out Reset Voltage Selection bits (Brown-out Reset Voltage (VBOR) set to 2.45V)
#pragma config ZCD = OFF        // ZCD Disable bit (ZCD disabled. ZCD can be enabled by setting the ZCDSEN bit of ZCDCON)
#pragma config PPS1WAY = ON     // PPSLOCK bit One-Way Set Enable bit (PPSLOCK bit can be cleared and set only once; PPS registers remain locked after one clear/set cycle)
#pragma config STVREN = ON      // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
#pragma config DEBUG = OFF      // Debugger Enable bit (Background debugger disabled)
#pragma config XINST = OFF      // Extended Instruction Set Enable bit (Extended Instruction Set and Indexed Addressing Mode disabled)

// CONFIG3L
#pragma config WDTCPS = WDTCPS_31// WDT Period selection bits (Divider ratio 1:65536; software control of WDTPS)
#pragma config WDTE = OFF       // WDT operating mode (WDT Disabled; SWDTEN is ignored)

// CONFIG3H
#pragma config WDTCWS = WDTCWS_7// WDT Window Select bits (window always open (100%); software control; keyed access not required)
#pragma config WDTCCS = SC      // WDT input clock selector (Software Control)

// CONFIG4L
#pragma config BBSIZE = BBSIZE_512// Boot Block Size selection bits (Boot Block size is 512 words)
#pragma config BBEN = OFF       // Boot Block enable bit (Boot block disabled)
#pragma config SAFEN = OFF      // Storage Area Flash enable bit (SAF disabled)
#pragma config WRTAPP = OFF     // Application Block write protection bit (Application Block not write protected)

// CONFIG4H
#pragma config WRTB = OFF       // Configuration Register Write Protection bit (Configuration registers (300000-30000Bh) not write-protected)
#pragma config WRTC = OFF       // Boot Block Write Protection bit (Boot Block (000000-0007FFh) not write-protected)
#pragma config WRTD = OFF       // Data EEPROM Write Protection bit (Data EEPROM not write-protected)
#pragma config WRTSAF = OFF     // SAF Write protection bit (SAF not Write Protected)
#pragma config LVP = ON         // Low Voltage Programming Enable bit (Low voltage programming enabled. MCLR/VPP pin function is MCLR. MCLRE configuration bit is ignored)
// CONFIG5L
#pragma config CP = OFF         // PFM and Data EEPROM Code Protection bit (PFM and Data EEPROM code protection disabled)

// CONFIG5H

// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.

#include <xc.h>
</xc.h></code></pre>



<h2 class="wp-block-heading" id="4">初始化設定</h2>



<p class="wp-block-paragraph">我習慣會將初始化設定都用一個副程式（void Initial）包住，即便他可能很簡短，但也會將用副程式寫起來，因為可以讓主程式比較容易理解哪一些事初始化設定。</p>



<pre><code class="c">void Initial(){
    TRISBbits.TRISB0 = 0;
    ANSELBbits.ANSELB0 = 1;
}
</code></pre>



<p class="wp-block-paragraph">「TRISBbits.TRISB0 = 0;」。TRISX，在<a href="https://dragongo.co/wp-content/uploads/2021/06/pic18datasheet.pdf" data-type="URL" data-id="https://dragongo.co/wp-content/uploads/2021/06/pic18datasheet.pdf">datasheet</a>中用「Ctrl+F」搜尋TRIS可以找到這一頁，裡面有提到當該Bit設為1的時候會該腳位被設定為輸出，設為0時候該腳位會被設定為輸入。</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img decoding="async" src="https://dragongo.co/wp-content/uploads/2021/07/image.png" alt="image" class="wp-image-1602" width="823" height="531" title="PIC18單燈閃爍教學 2" srcset="https://dragongo.co/wp-content/uploads/2021/07/image.png 991w, https://dragongo.co/wp-content/uploads/2021/07/image-300x194.png 300w, https://dragongo.co/wp-content/uploads/2021/07/image-768x496.png 768w" sizes="(max-width: 823px) 100vw, 823px" /><figcaption>TRISx的datasheet</figcaption></figure></div>



<p class="wp-block-paragraph">「ANSELBbits.ANSELB0 = 1;」從<a href="https://dragongo.co/wp-content/uploads/2021/06/pic18datasheet.pdf" target="_blank" data-type="URL" data-id="https://dragongo.co/wp-content/uploads/2021/06/pic18datasheet.pdf" rel="noreferrer noopener">Datasheet</a>去尋找ansel的關鍵字(第16章)，可找這兩段資料，此暫存器可以設定此腳位是作為類比還是數位，若今天是要做ADC類比轉數位時，腳位要設為類比的，在這份專案中，我們先將其設為1，將此腳位設定為類比腳位。</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img decoding="async" src="https://dragongo.co/wp-content/uploads/2021/07/image-1.png" alt="image 1" class="wp-image-1604" width="563" height="537" title="PIC18單燈閃爍教學 3" srcset="https://dragongo.co/wp-content/uploads/2021/07/image-1.png 776w, https://dragongo.co/wp-content/uploads/2021/07/image-1-300x286.png 300w, https://dragongo.co/wp-content/uploads/2021/07/image-1-768x732.png 768w" sizes="(max-width: 563px) 100vw, 563px" /></figure></div>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" decoding="async" src="https://dragongo.co/wp-content/uploads/2021/07/image-2-1024x581.png" alt="image 2" class="wp-image-1605" width="836" height="475" title="PIC18單燈閃爍教學 4" srcset="https://dragongo.co/wp-content/uploads/2021/07/image-2-1024x581.png 1024w, https://dragongo.co/wp-content/uploads/2021/07/image-2-300x170.png 300w, https://dragongo.co/wp-content/uploads/2021/07/image-2-768x436.png 768w, https://dragongo.co/wp-content/uploads/2021/07/image-2-1140x647.png 1140w, https://dragongo.co/wp-content/uploads/2021/07/image-2.png 1302w" sizes="(max-width: 836px) 100vw, 836px" /></figure></div>



<h2 class="wp-block-heading" id="5">主程式</h2>



<p class="wp-block-paragraph">主程式通常會包括在main裡面，為了要讓程式能重複無限次執行，使用while(1)，也有人是使用for(;;)，皆為重複無限次執行，在執行while(1)之前，會先呼叫Initial的副程式，執行初始化設定，在做主程式的動作。</p>



<p class="wp-block-paragraph">重複無限次動作的只有兩行，「LATBbits.LATB0 = ~LATBbits.LATB0;」這一行會將原本RB0的狀態做NOT運算，再存回RB0，LED燈本來是亮的，就會變成暗的，反之本來是暗的，就會在這一行之後變成亮的。</p>



<p class="wp-block-paragraph">「__delay_ms(1000);」這一行是等待1秒鐘，這是XC8編譯器內建的延遲功能，為了要使其可以正常運作，通常還會要在程式前面增加</p>



<pre><code class="c">void main(void) {
    Initial();
    while(1){
        LATBbits.LATB0 = ~LATBbits.LATB0;
        __delay_ms(1000);
    }
    return;
}
</code></pre>



<h2 class="wp-block-heading" id="6">延伸思考</h2>



<p class="wp-block-paragraph">透過此文章你可以知道單燈如何閃爍了，那如果今天要像是霹靂燈一樣從第一顆閃到最後一顆再從最後一顆閃回第一顆的話，主程式的架構上該如何修改呢？</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
