我有一个 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.
}
为了更好地理解:
我建立了一些小代码来显示我的疑虑:
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 前端的代码是:
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)有没有办法能够根据引脚(在本例中为 INT0 引脚)的条件激活“停电 ISR”,而无需使用引脚上的物理开关。因此,引脚状态必须由软件操作。
2)是否可以执行停电功能评论中提到的操作?
3)在python代码中是否可以只发送一次数据(即模式,快速)并使arduino以无限的方式执行模式,而无需再次通过serial.write
命令发送数据。因此避免while(1)
了ser.isOpen()
.