A lot of hardware comes with a Tx/Rx status LED, but what if your hardware doesn't and you want to see if data is transmitting? If you just set the LED to the value of the line it may go on and off before you even see it (<1/100th of a sec.).
My question is, how do I write an interrupt driven function to drive the LED state? I've searched the internet and found nothing and I could use a counter with a modulus, but that seems clunky. Any other ideas?
PS - I'd like to use this in either Arduino or Mbed, but I doubt it makes a difference to the question as to which one...
void receive_or_transmit_interrupt()
{
g_traffic = true;
/* other stuff. */
}
void timer_that_fires_every_100_milliseconds()
{
if ( led == ON)
{
led = OFF;
g_traffic = false;
}
else if ( g_traffic )
{
led = ON;
}
}
If you don't want the timer to always be firing even when there's not traffic, you could change the receive_or_transmit_interrupt to enable the timer, and the timer could disable itself when it turns off the LED.
A simple way is to switch the LED on in the Tx/Rx interrupt and initiate a timer of say 200ms (long enough to perceive). You then switch the LED off in the timer ISR.
That way the indicator is extinguished 200 ms after the last tx/rx activity. If the activity is sustained, the indicator will remain illuminated.
If the tx/rx bursts are intermittent with greater than 200ms gaps, the indicator will flicker. So the states of off, on and flickering give a broad indication of the data activity.
Related
I'm making an LED control program (using FastLED, of course) and using Serial (with the Serial monitor) to control it. I just connected it via USB and for the most part it works just fine. However, I noticed with the long, flashing routines that I couldn't stop them and make the LEDs do something else. The flash routine in my code is very simple:
void flash(CRGB color, int count, int del){
for(int i = 0; i < count; i++){
if(pause){
break;
}
fillLeds(color.r, color.g, color.b);
milliDelay(del);
fillLeds(0,0,0);
milliDelay(del);
}
}
With fillLeds(r,g,b) being a for loop, looping through and setting all LEDs to a certain color, and milliDelay is just delay() using millis and not the delay() function.
I need to be able to pause not just this, but other functions as well (probably using break;) and then execute other code. It seems easy, right? Well, I've noticed that when I send a byte over Serial, it goes into this "queue," if you will, and then is sequentially read.
I can’t have this happen. I need the next byte entering Serial to activate some kind of event that pauses the other flash() function running, and then be used. I have implemented this like:
void loop()
{
if (Serial.available() > 0)
{
int x = Serial.read();
Serial.print(x);
handleRequest(x);
}
FastLED.show();
FastLED.delay(1000 / UPDATES_PER_SECOND);
}
Where handleRequest(x); is just a long switch statement with calls to the flash method, with different colors being used, etc.
How can I make the Arduino pause other loops whenever a new byte is received, instead of adding it to this "queue" to be acted upon later? If this is not possible thanks for reading anyway. I've tried using serialEvent() which doesn't appear to work.
I think you need two loops. You have one, which is your main loop, and you can add another (like a multi threading) with the TimerOne library. Like this:
Timer1.initialize(your desired delay in this loop);
Timer1.attachInterrupt(your desired function in this loop);
So maybe you can add an if statement with a variable in your second loop to prevent some function and update the variable in your first loop or something like that.
Presuming you want interrupt-like functionality when a new byte arrives:
Unfortunately, serialEvent() is not a true interrupt. It only runs at the end of loop(), if there is serial data available.
However, serialEvent() is just a function, and there isn't any reason why you can't call it in your code as often as you like. This is effectively polling for new serial data as often as possible. So, while your loops are running, call serialEvent() during your delays and handle the serial data there.
You may need to restructure your code to avoid recursion though. If flash calls serialEvent(), which calls flash, which calls serialEvent, etc... then you may end up overflowing the stack.
Working on a SAMD Arduino, I found myself in need for multiple alarms, triggering events at interrupt time.
Most people suggest TimeAlarm.h, which is a library to schedule timers and alarms with the Time.h library. Unfortunately the alarms don't run on interrupt time.
Instead of adding Time and TimeAlarms libraries I came up with "daisychaining" RTC alarms. I am wondering if this is good or bad practice. Could such a thing bite back?
A snapshot of the code:
void main() {
...
//set alarm at 16:0:0 and trigger Event_1 at interrupt time
rtc.enableAlarm(16,0,0);
rtc.attachInterrupt(Event_1_isr);
...
}
void Event_1_isr() {
...some code...
//Set next alarm and interrupt Event_2
rtc.setAlarmTime(16, 0, 15);
rtc.enableAlarm(rtc.MATCH_HHMMSS);
rtc.detachInterrupt();
rtc.attachInterrupt(Event_2_isr);
}
void Event_2_isr() {
...some code...
//I guess you get the point
rtc.setAlarmTime(16, 0, 30);
rtc.enableAlarm(rtc.MATCH_HHMMSS);
rtc.detachInterrupt();
rtc.attachInterrupt(Event_3_isr);
}
I would try to get in and out of the interrupts as fast as possible. I think that's nearly always good advice.
You ask "could such a think bite back" - yes, in maintenance headaches. Your logic and settings are scattered throughout the code.
I would consider turning it around: make one or two routines responsible for setting up and handling the RTC interrupts. Let it use a table of times and routines to set the correct delay and dispatch the appropriate action. Then you don't need the overhead of attach/detach-interrupts, all the relevant code is in one place, and your data tells you what to do.
Im trying to figure out how to track when a user has been idle from the computer, meaning not only my application. The reason is that i want my application to be able to set the user as "Away" after a certain amount of time. Think like Skype which takes you away after X minutes.
Any ideas how to accomplish this?
Edit
What i've got so far to track the mouse:
//Init
mouseTimer = new QTimer();
mouseLastPos = QCursor::pos();
mouseIdleSeconds = 0;
//Connect and Start
connect(mouseTimer, SIGNAL(timeout()), this, SLOT(mouseTimerTick()));
mouseTimer->start(1000);
void MainWindow::mouseTimerTick()
{
QPoint point = QCursor::pos();
if(point != mouseLastPos)
mouseIdleSeconds = 0;
else
mouseIdleSeconds++;
mouseLastPos = point;
//Here you could determine whatever to do
//with the total number of idle seconds.
qDebug() << mouseIdleSeconds;
}
Any way to add keyboard to this also?
There are platform-specific ways of getting idle user notifications. You should almost always use those, instead of rolling your own.
Suppose you insist on rolling your own code. On X11, OS X and Windows, applications simply don't receive any events that are targeted at other applications. Qt doesn't offer much help in monitoring such global events. You need hook into the relevant global events, and filter them. This is platform specific.
So, no matter what you do, you have to write some front-end API that exposes the functionality you're after, and write one or more platform-specific backends.
The preferred platform-specific idle time APIs are:
On Windows, GetLastInputInfo, see this answer.
On OS X, NSWorkspaceWillSleepNotification and NSWorkspaceDidWakeNotification, see this answer.
On X11, it is the screensaver API:
/* gcc -o getIdleTime getIdleTime.c -lXss */
#include <X11/extensions/scrnsaver.h>
#include <stdio.h>
int main(void) {
Display *dpy = XOpenDisplay(NULL);
if (!dpy) {
return(1);
}
XScreenSaverInfo *info = XScreenSaverAllocInfo();
XScreenSaverQueryInfo(dpy, DefaultRootWindow(dpy), info);
printf("%u", info->idle);
return(0);
}
Best bet would be to check for mouse and keyboard events.
If you override the eventFilter function and in that check for:
QEvent::MouseButtonPress
QEvent::MouseButtonRelease
QEvent::Wheel
QEvent::KeyPress
QEvent::KeyRelease
Create a QTimer, which will be reset on any of the events, and if not, just let the timer tick and fire a callback at whatever intervalls you wish.
Edit:
Please see comments and Kuba Ober's answer for more info.
I have a problem with arduino due timers. First let me explain what i know of them.I don't know if there is a way to solve this issue for general timers. Due timers features:
1) They always start from zero,
2) They work as UP-COUNTING or UP-DOWN counting timers,
3) Each timer has two compare registers.
My project involves cases to work in sampled times(period), i.e. timer runs for a sampled time and based on values in compare registers the outputs TIOA and TIOB toggles.I am working in up-down mode. Now the problem is when I have zero in a compare register I expect a zero output (on TIOA and TIOB) for whole period. But the timer is toggling output for zero comparison also. i.e. instead of getting a zero always i am getting a square wave with (2*period) as its time period. Is this common problem for other timers also?
Can you guys suggest me a workaround for this problem?
Thanks in advance.
#include <AdvaDueTC.h>
int default_clock = 1;
int RCcntS = 2187*2;
int period0 = 65536;
int a = 2180;
int b = 0;
void subrtn()
{
changeTC_TC3_Period(RCcntS); // loading sampler TC3 with RCcntS
changeTC_TC0_Period(RCcntS/2,a,b); // loading timer TC0 with RCcntT
}
void setup() {
setupTC3_Interrupt(period0,default_clock ,subrtn);//setup sampler interrupt
setupTC_TC0_Timing(period0, default_clock);
}
void loop() {
// put your main code here, to run repeatedly:
}
functions used are :
Here TC3 is in UP mode and TC0 is in UPDOWN mode of operation. TIOA0 and TIOB0 are used for obtaining toggling output.(i.e. in REG_TC0_CMR0, ACPA,BCPB are set to 3). Here TIOB0 is toggling and I want to stay at one valve (0 or 3.3v) for whole period.
Thanks for your suggestion.
when I have zero in a compare register I expect a zero output
i expect the output to be triggered two times (UP and DOWN) every tick (i think you call it period), because the timer is overflowing EVERY tick.
Solution is turn off the timer comparison.
this seems to me a PWM, maybe you'll get better result using the dedicated HW
Yes what you said is correct. At first I couldn't get it but this MCU timer has option to set or clear the timer output value for whole period. so without going for TOGGLE always, I used these options to get desired operation.
As stated in stackoverflow-17135805 the millis() function does not return the correct time, if the interrupts where disabled, while Arduino had to detect an overflow of timer0.
I have a time critical program that uses a lot of functions which have to disable the interrupts. So my program runs 1:30 while it thinks it was running only for 1:00.
Is there another timer that I can use to avoid this problem?
It happens to me when I use the GSM Module:
// startpoint
unsigned long t = 0;
unsigned long start = millis();
while ( (millis()-start) < 30000 ){
//read a chunk from the gprs module
for (int i=0;i<8;i++)
client.read();
//do this loop every 10ms
while( (millis()-start) < t*10 ){};
t++;
}
//endpoint
From the startpoint to the endpoint it should take 30 seconds. Instead it takes 65 seconds.
If you have to disable interrupts so often and so long your best bet would be to use an external timer. I highly recommend DS3231. Since it has a build in crystal it is easier to setup than a 1307 and it is also significantly more accurate.
You could use one of the other hardware timers
to keep track of the time. For example, on the Leonardo Timer 1 is a 16 bit timer.
To set it up directly (this obliterates code portability) there are a couple steps.
TCCR1A = 0;
this puts the timer in "normal" mode, meaning it just runs to 0xFFFF and wraps back to 0x0000.
TCCR3B = 0;
TCCR3B = _BV(CS11) | _BV(CS10);
this starts the timer and sets it to use a clock/64 prescale, which equates to 1 tic every 4us.
To check the time:
long time; // declared somewhere in scope.
time = TCNT1; // this reads the timer count register
time *= 4; // this multiplies time by 4 to give you us.
As mentioned earlier, TCNT1 wraps around at 0xFFFF = 65536. So, with the pre-scaler set as above, that gives you about 65536 * 4E-6 = .262 seconds of counting before your program needs to put the data into a bigger variable (assuming you care). Hopefully it isn't a problem to poll things more often than 4 times a second, which gets you away from interrupts.
Several arduino core functions utilize these timers, so you'll need to verify that the core functions you need don't depend on the timer you choose. For example, doing the above will break analogWrite() on certain pins.