PIC18上输入引脚的读取状态 [英] Reading state of input pins on a PIC18
问题描述
当我将各种输出锁存器设置为高/低时,我已经能够使输出在我的PIC上工作,并且可以使一堆LED点亮或熄灭.但是,在固定状态下阅读时会遇到很多困难.
I have been able to get outputs working on my PIC and can make a bunch of LEDs dance on and off as I set various output latches high/low. However, I'm having a lot o difficulty reading in the state of a pin.
请参见下面的代码.我设置了配置,并将TRISC定义为输入,将TRISB定义为输出.在无限循环中,我检查RC6是高电平还是低电平,然后根据结果将整个B锁存器设置为高电平或低电平.
See the code below. I set up my config, and define the TRISC as input and TRISB as output. In an infinite loop, I check to see whether RC6 is high or low, and set the entire B latch high or low depending on the result.
#include <htc.h>
__CONFIG(1, FOSC_IRC & FCMEN_OFF & IESO_OFF);
__CONFIG(2, PWRTEN_OFF & BOREN_OFF & WDTEN_OFF);
__CONFIG(3, MCLRE_OFF);
__CONFIG(4, STVREN_ON & LVP_OFF & DEBUG_OFF);
__CONFIG(5, 0xFFFF);
__CONFIG(6, 0xFFFF);
__CONFIG(7, 0xFFFF);
void main(void)
{
TRISC = 0xFF; // input
TRISB = 0x00; // output
while (1)
{
if (PORTCbits.RC6 == 0)
LATB = 0b00000000;
else
LATB = 0b11111111;
}
return;
}
代码可以正常编译,没有警告或错误.如果我的代码逻辑只是将锁存器设置为高电平和低电平,则可以正常工作,但是我无法成功读取引脚的状态.
The code compiles fine with no warnings or errors. If my code logic is simply setting latches high and low then that works fine, but I haven't been able to successfully read the state of a pin.
有什么想法吗?
我正在使用PIC18F14K50和MPLAB v8.43和HiTech ANSI C编译器.
I'm using a PIC18F14K50 and MPLAB v8.43 and the HiTech ANSI C Compiler.
我的连接是VDD(引脚1)为+ 5V,VSS(引脚20)为接地.我有+ 5V到C6(引脚8),以及一个100K电阻器和从B7(引脚10)接地的LED.要切换RC6,我将电线连接/断开到C6.
My connections are +5V to the VDD (pin 1), VSS (pin 20) to ground. I have +5V to C6 (pin 8), and a 100K resistor and LED from B7 (pin 10) to ground. To toggle RC6, I connect/disconncet the wire to C6.
┌────────┐
+5v -│ 01 20 │- gnd
-│ 02 19 │-
-│ 03 18 │-
-│ 04 17 │-
-│ 05 16 │-
-│ 06 15 │-
-│ 07 14 │-
+5v -│ 08 13 │-
-│ 09 12 │-
led -│ 10 11 │-
└────────┘
推荐答案
不幸的是,PIC上的ADC引脚在加电时被配置为模拟输入.您需要禁用该引脚上的ADC功能才能将其用作数字输入.
The ADC pins on the PICs unfortunately are configured as analog inputs on powerup. You need to disable the ADC functionality on that pin to use it as a digital input.
清除ANSELH的位0将把RC6设置为数字输入.然后您的代码将起作用.
Clearing bit 0 of ANSELH will set RC6 to digital input. Then your code will work.
这在数据表的第9.4节端口模拟控制"中有记录
This is documented in the datasheet in section 9.4 : Port Analog Control
这篇关于PIC18上输入引脚的读取状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!