我有一个以模式发送的python代码,其中灯必须闪烁 . (比如说101010.每次运行代码时模式都可能不同) . 当它无限地执行时,我想要一个中断(再次由python代码发送)来保存灯的当前条件(比如运行1的序列)并执行特定任务,如关灯10秒钟然后恢复序列 . 一种方法是通过使中断引脚为高电平来中断程序 . 问题是这可以由pyserial控制高/低 . 所以一个简单的伪代码将是:
PYTHON部分代码:
Read the sequence:
Send the sequence to the arduino board using pyserial.
while(1)
{
Run a timer for 15 second.
When the timer overflows interrupt the arduino.
}
ARDUINO代码的一部分:
Read the sequence
while (1)
{
keep repeating the sequence on the LED.
}
// if interrupted on pin2 // assuming pin2 has the interrupt procedure
// Pyserial has to enable the interrupt WITHOUT using a switch for enabling the pin.
ISR
{
Save the present state of execution.
Turn off the LED.
}
更好的理解:
我 Build 了小代码来表明我的疑虑:
ARDUINO的代码是:
int ledpin1 = 13;
int speedy;
int patterns;
void setup()
{
Serial.begin(9600);
Serial.print("Program Initiated: \n");
pinMode(ledpin1,OUTPUT);
//activate the blackout ISR when a interrupt is achieved at a certain pin. In this case pin2 of the arduino
attachInterrupt(0,blackout,CHANGE);
}
void loop()
{
if (Serial.available()>1)
{
Serial.print("starting loop \n");
patterns = Serial.read();
patterns = patterns-48;
speedy = Serial.read();
speedy = (speedy-48)*1000;
while(1)
{
patterns = !(patterns);
Serial.print(patterns);
digitalWrite(ledpin1,patterns);
delay(speedy);
}
}
}
/*
void blackout()
{
// ***Save the present state of the LED(on pin13)***
Serial.print ("The turning off LED's for performing the python code\n");
digitalWrite(ledpin,LOW);
//wait for the Python code to complete the task it wants to perform,
//so got to dealy the completion of the ISR
delay(2000);// delay the whole thing by 2 seconds
//***Continue with the while loop by setting the condition of the light to the saved condition.***
}
*/
================================================== ================================
PYTHON FRONT的代码是:
import serial
import time
patterns=1
speedy=1
ser = serial.Serial()
ser.setPort("COM4")
ser.baudrate = 9600
ser.open()
def main():
if (ser.isOpen()):
#while(1):
ser.write(patterns)
ser.write(speedy)
blackoutfunc()
#ser.close()
def blackoutfunc():
while(1):
time.sleep(2)
print "Performing operations as required"
================================================== =============================
现在我的问题是:
1)有没有办法能够激活“中断ISR”,具体取决于引脚的条件(在这种情况下,引脚2是INT0引脚),而不使用引脚上的物理开关 . 因此,引脚状态必须由软件操纵 .
2)是否可以执行停电功能注释中提到的操作?
3)在python代码中,可以只发送一次数据(即模式,快速),并使arduino以无限的方式执行模式,而不再通过 serial.write
命令发送数据 . 因此避免在 ser.isOpen()
之后的 while(1)
循环 .
1 回答
看看这个:
https://github.com/ajfisher/arduino-command-server
这是我在Arduino端一起发出的任意命令,例如切换引脚高/低并设置PWM电平等 . 它可以在串行和网络上工作,虽然它在网络端是一个触摸错误 .
要使用它,将代码放在你的arduino然后你只需编写一个python脚本(或任何其他可以使用串行连接的语言)通过串行连接连接,然后告诉它你想做什么,例如DIGW 1 HIGH等
另外看看:https://github.com/ajfisher/arduino-django-visualiser这是我使用这个库的变体来控制一些LED基于Django中发生的一些事情 - 它更基于python .