下面是 MSP430G2 微 Controller 的代码。到目前为止,我无法将中断服务例程添加到我的代码中,无法添加到此作业中。该代码是一个两位计数器,它使用启动板上的 S2 按钮进行递增计数,然后使用连接到引脚 1.7 和 2.4 的外部连接开关进行递减计数,这可以在代码中看到。如果有人可以帮助解释如何将 ISR 添加到此代码中,我将不胜感激!
#include <msp430.h>
#define LEDS (BIT6 + BIT0)
// Global variables to hold current state and # of pushes
char pushes;
// Initialization function
void init(void)
{
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
P1DIR |= LEDS; // Set P1.0, P1.6 to output direction
P1DIR &= ~ BIT3; // Turn P1.3 into input
P1REN |= BIT3; // Enable internal resistor
P1OUT |= BIT3; // Enable as pullup resistor
P1DIR |= BIT7; // Set BIT 7 to output
P1OUT |= BIT7; // Set BIT 7 as VCC
P2DIR &= ~ (BIT4); // Makes this an input
P2REN |= (BIT4); // Turns on internal resistor
P2OUT &= ~(BIT4); // Make internal resistor pulldown
pushes = 0; // Initialize global variable
P1OUT &= ~(LEDS); // Clear output LEDs
}
// Read input function
char readInput(void)
{
char local = 0;
if (!(BIT3 & P1IN)) // Check for button push
{
local = 1;
_delay_cycles(10000); // Wait for bouncing to end
}
if ((P2IN & BIT4)) // Check for button push
{
local = 2;
_delay_cycles(10000); // Wait for bouncing to end
}
return local;
}
// Count up function
void countUp(void)
{
pushes += 1; // increment pushes variable
if (pushes & BIT0){
P1OUT |= BIT6;
}
else{
P1OUT &= ~BIT6;
}
if (pushes & BIT1){
P1OUT |= BIT0;
}
else{
P1OUT &= ~BIT0;
}
}
// Count down function
void countDown(void)
{
pushes -= 1; // decrement pushes variable
if (pushes & BIT0){
P1OUT |= BIT6;
}
else{
P1OUT &= ~BIT6;
}
if (pushes & BIT1){
P1OUT |= BIT0;
}
else{
P1OUT &= ~BIT0;
}
}
// Main function
int main(void)
{
char enable = 0; // Holds status of the S2 button
char previousState = 0; // Holds previous state of S2 button
init(); // One time initialization function
while (1)
{
enable = readInput(); // Check the buttons
if(enable && !previousState){
// If button is pressed, allow counter to increment/decrement once
if(readInput()==1){
countUp();
}
if(readInput()==2){
countDown();
}
}
previousState = enable;
}
}
最佳答案
要为特定端口和引脚添加中断,您需要做几件事。我们以P1.3为例; P2.4的中断可以用类似的方式添加。
设置微 Controller 的“中断允许”位:
P1IE |= BIT3;//P1.3 中断使能
并配置中断是发生在上升沿还是下降沿:
P1IES |= BIT3;//P1.3 下降沿中断
为端口定义中断服务例程 (ISR)。看到您使用 CCS,我相信
#pragma vector=PORT1_VECTOR
是正确的选择。清除 ISR 中的中断标志以避免重复触发。另一个警告是每个端口只能有一个 ISR,而且并非所有端口都支持中断。如果您需要处理多个引脚上的中断,则需要通过查看中断标志状态在处理程序中对其进行多路分解。
代码:
#pragma vector=PORT1_VECTOR
__interrupt void Port_1(void)
{
if (P1IFG & BIT3) { // P1.3 interrupt?
// TODO: add the application logic here
P1IFG &= ~BIT3; // clear the P1.3 interrupt flag
}
确保设置了状态寄存器的全局中断启用 (
GIE
) 位。如有疑问,设置为,例如:__bis_SR_register(GIE);
关于c - 我如何使用中断服务例程来检测此 MSP430 代码上的按钮事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49932678/