I want to drive up to 10 stepper motors at the same. All with a constant but individual speed. Meanwhile other calculations and data transfer is to be done.
All Steppers have their own driver with dir/step pin. I use AccelStepper for non blocking functions to run the steppers. It is very important that the steppers run as smooth as possible.
First I simply put the runSpeed function for every stepper in the main loop, resulting in stuttering when data was written to the serial by the arduino. I now use Timer5 of the Mega to run a function that does nothing but call all runSpeed functions every 200 µs or so. This works very good with the steppers and the rest of the code except for the serial communication. I want to send commands to the arduino but with the interrupt being active some bytes never reach the arduino. Right now I am sending a notification byte that data will be transfered, the arduino answers and stops the interrupt, receives the command and starts the interrupt again. Works like a charm except for the 0.5 s stepper pause inbetween. This is to be solved.
Now I thought about the following:
1. Making the interrupt adoptable. Means: Track alls steps on every motor and calculate when a motor has to do the next step. Make the timer interrupt at exactly that time. Of course the interrupt has to be adjusted after every step of any motor. My fear is that the time demand for the calculations would be quite high, if not too high, so that the arduino gets stuck in interrupts and does not execute other code anymore.
2. Using a second arduino which only runs the steppers in the loop so the timing is no problem and serial data can be received. However, if I want that arduino to confirm the new settings to the main arduino, then I will get short pauses again... Solution would be to switch to interrupts when sending data, else use the main loop (sending data with interrupt works, receiving has the issue).
This is my idea of how to do it. But before I put all the effort in it, I wanted to discuss this with you and ask you, if you have another, better solution that for me.
I attached an exemplary code which with which the arduino cannot receive longer texts without missing bytes.
#include "AccelStepper.h"
#include "TimerFive.h"
AccelStepper m1(AccelStepper::DRIVER, 24, 25);
AccelStepper m2(AccelStepper::DRIVER, 26, 27);
AccelStepper m3(AccelStepper::DRIVER, 28, 29);
void setup() {
m1.setMaxSpeed(1000);
m2.setMaxSpeed(1000);
m3.setMaxSpeed(1000);
m1.setSpeed(50);
m2.setSpeed(70);
m3.setSpeed(90);
Timer5.initialize(250);
Timer5.attachInterrupt(run);
}
void run() {
m1.runSpeed();
m2.runSpeed();
m3.runSpeed();
}
void loop() {} {
//some calculations...
if (Serial.available() > 0) Serial.println(Serial.readString());
delay(1000);
}
Related
I have steppers stepping during an interrupt timer at 50 and have all my code working between the interrupts until I tried reading serial commands more than one character long.
I'm getting dropped bytes so my strings are missing a letter every 4-5 chars. I researched all day to try and figure out a solution but have come up with nothing. If I don't use an interrupt my stepper stops for 2 seconds reading a one char serial input as a string.
My goal is to have a remote control app sending speed commands. I need help working this problem out.
https://sourceforge.net/p/open-slider/code/ci/master/tree/OpenSliderFirmware/
String incomingString = "";
if (Serial.available() > 0) {
incomingString = Serial.readString();
Serial.println(incomingString);
}
Using Accelstepper library
interrupt:
//Interrupt Timer1
void ISR_stepperManager() {
Slide.runSpeed();
Xaxis.runSpeed();
Yaxis.runSpeed();
}
Quick answer: you don't if the interrupt timer is cutting in too often.
I resolved the problem by using a variable interrupt timer and a step multiplier. Basically the steps are called every time the timer interrupts instead of checking millis inside the interrupt function. This solved many issues. The speed of the stepper is now controlled by the interrupt timer. This gave me more free cycles to fully read the incoming serial without corruption and improved efficiency. Calling more steps per cycle when doing over 4k steps/s also improved efficiency requiring less cycles for a high rate of steps.
The serial is processed one char per cycle to prevent blocking.
Overall, if you are using serial and an interrupt timer, any interrupt happening < 100us you should be cautious how much code you are running during the interrupt. It will cause issues with incoming serial and user inputs. A few lines of code in a 25us timer interrupt, incoming serial will not function.
i'm not sure if it will help to your problem, but i saw along the time that the String type is not safe to use when other things need to happened.
i prefer to use char array and read one char at a time.
while(Serial.available())
{
data[x] = Serial.read();
x++;
}
i'm finding it much more reliable.
hope it's help!
In the following code, why does ISR2 never run?
const int in = 19;
const int LED = 9;
int flag;
void setup() {
pinMode(in, INPUT_PULLUP);
pinMode(LED, OUTPUT);
attachInterrupt(digitalPinToInterrupt(in), ISR2, RISING);
attachInterrupt(digitalPinToInterrupt(in), ISR1, FALLING);
}
void loop() {
if (flag) {delay (100); flag = false;}// debounce
}
void ISR1(){
digitalWrite(LED, LOW);
// Turn Off the motor, since, Limit Switch was engaged
flag = true;
}
void ISR2(){ // Limit Switch was disengaged.
digitalWrite(LED, HIGH);
delay(100); // Debounce, so I do not receive spurious FALLING edges from this.
}
Does the Arduino not allow you to attach two interrupts on the same pin even if the interrupts are programmed for different events?
In my setup, pin 19 gets a signal from a limit switch used in a motion control setup. When the limit switch is engaged, the in pin gets LOW signal. Thus, I first see a FALLING edge followed by RISING edges and FALLING edges due to mechanical bounce. I handle the debouncing correctly in this case.
However, imagine the Limit Switch was sitting in engaged state for a while, and then I reverse the motor causing the Limit Switch to disengage, this will send a RISING edge followed by FALLING and RISING edges. I need to ignore these edges since nothing is in danger. The ISR2 was written with purpose of capturing the first RISING edge when the Limit switch disengages, and then debouncing it so that the following FALLING edges are ignored. But now that ISR2 never gets called, how can I deal with this situation?
P.S. My microcontroller is ATMEGA 2650, It's a Arduino Mega board.
ISR2 never runs because there can be only one interrupt service routine for any interrupt source and you have replaced ISR2 with ISR1 as the sercice routine for this interrupt. If you reordered your code and attached ISR1 before ISR2 then you might see ISR2 run but not ISR1.
A typical microcontroller has an interrupt vector table that associates an interrupt service routine with each interrupt source. There can be only one service routine for each interrupt source. If you assign an new service routine then you're replacing the old service routine. There are not separate service routines for the rising and falling edges. Rising versus falling edge is a configuration setting for the interrupt source to determine when that interrupt should fire. The interrupt source cannot be configured to fire on both edges simultaneously.
However you may be able to reconfigure the interrupt for the other edge after you have received the interrupt for the first edge and debounced the transition. This way your code will ping-pong back and forth configuring for one ISR and then the other.
Why are you saying that it never gets called? I think that it is called, but you don't notice it because the led does not change its state (because there are bounces).
Anyway, you are NOT debouncing it correctly. Let's do an example: you hit the endstop. ISR1 gets called, so flag is true. Ok, at next loop the motor will be stopped. But... Now the switch bounces. ISR2 gets called, and the delay function in it waits for 100ms before exiting the ISR. Result: you delayed the motor stop function by 100ms.
I suggest you to read my answer here, particularly the second case. And I suggest you to use my code instead of yours, since this way you will be able to IMMEDIATELY stop the motor, without bounces nor any other kind of problems.
The function of the program I am writing is to stream incoming analog data from a sensor to a program on my computer across the USB port. For a little fun, I've decided to add a button to the program that will turn on/off a lamp. The lamp will be connected to a relay, which is connected to the arduino. I know how to go about programming it, but I want to know if this will interrupt the sensor data transfer?
I will get the current state of the light (HIGH(1) or LOW(0)) from the arduino when the button is pressed, then write to the arduino (HIGH(1) or LOW(0)) depending on the current state. I have a 5 second delay between each loop of the arduino program, for reasons related to the sensor output; however, I think I'm going to have to change this so that when the button is pressed, it is not missed by the arduino loop, or is that not possible?
I thought I read somewhere that you can't transmit/receive streaming data on the same serial line...in which case, I will need the Mega.
You have to remember and think of the Arduino as a single threaded device. While it is doing anything it is not able to do anything else. Period! In regard to the serial port however, the buffer will still accept incoming data on RX, however if an overflow situation occurs whilst blocked, management is impossible.
See the following taken directly from the Arduino reference
Certain things do go on while the delay() function is controlling the Atmega chip however, because the delay function does not disable interrupts. Serial communication that appears at the RX pin is recorded, PWM (analogWrite) values and pin states are maintained, and interrupts will work as they should. Reference
Now in saying that when you are setting the delay to 5 seconds between loops ( delay(5000) ) you are essentially blocking it from doing anything else almost full stop.
The Arduino framework exposes a a counter ( millis() ) that basically runs from the moment of boot for roughly 50 days in increments of one (1) millisecond. See Arduino - millis()
In your application you would define (remember) what loop you were due to run & when the said loop had finished so to not allow the other loop to run until the millis() counter was a defined amount more than your count. (Remember to define the count as a long)
Then what you do is move your loops out into separate functions that will only execute if the if statement return true...
for example...
long interval = 5000; // Define interval outside of the main loop
long previousCount = 0; // Used to store milli count when finished
int loopPosition = 1;
void loop()
{
if ((long)millis() - previousCount >= 5000 )
// This if statement will only return true every 5 seconds (5000ms)
{
if (loopPosition == 1)
{
function_One();
previousCount = millis(); // Redefine previousCount to now
loopPosition++; // Increment loop position
}
else if (loopPosition == 2)
{
function_Two();
previousCount = millis();
loopPosition--; // Decrement loop position
}
}
// Do Anything Here You Want
// - While ever the if statement above returns false
// the loop will move to this without hesitation so
// you can do things like monitor a pin low / high scenario.
}
void function_One()
{
// Do Your First Loop
}
void function_Two()
{
// Do Your Second Loop
}
The above will stop any delay you are using from blocking awesomeness, and to more of a point, almost make delay obsolete if implemented correctly under the right scenarios.
In regard to your serial data comment, like i said at the top of this article, the Arduino can only do one thing at a time. Transmitting and receiving at exactly the same time is impossible even with the Mega. In saying that a board like the 'Uno' for example is only capable of one serial interface, where as the 'Mega' is capable of four.
Best of luck....
NB- For a beginner reading this, the following tutorial / example covers what i have above in fairly simple terms and is a great building block for further awesomeness! Arduino - Blink Without Delay
Background
I have need for a data logging application running on a "Arduino compatible" chipKit UNO32 board, with a connected sensor. Data should be logged to an SD-card found on a "Arduino Wireless SD shield".
The sensor is connected via I2C.
My problem is that when I use the Arduino SD library writing is slow: 25 ms per print() operation, which gives me a maximum of 40 Hz which is laughable compared to the 100-800Hz data rate of my sensor.
My faulty solution
Luckily the sensor comes equipped with both an on-chip FIFO that can store 32 sensor values. This means I can go to at least 200Hz without any troubles since the time to fill the FIFO is way larger than the time to write to the card.
But I'd still really like to get to at least 400Hz, so I thought I'd have the following setup:
Tell sensor to put data in the FIFO
When the FIFO is almost full, the sensor triggers an interrupt (sensor does this, and it works, I can catch the interrupt)
When the Arduino receives the interrupt, it polls the sensor for data (via I2C) and stores the data in a buffer in SRAM.
When the SRAM buffer is getting full, write its contents to the SD-card.
Unfortunately, this does not seem to work since the Arduino Wire library that handles I2C use interrupts, and can not be called from within an interrupt handler. I have tried it, and it freezes the microcontroller.
My question
There seems to be other I2C libraries for Arduino that do not rely on interrupts. Should I try that route?
Or is my way of thinking (grabbing a load of data in an ISR) bad from start? Is there another approach I should take?
Just use the interrupt to set a flag and finish the ISR. from the main loop do the calling I2C instead of directly calling from ISR.
boolean fifoFull = false;
void fifoISR() {
fifoFull = true;
}
void loop() {
if(fifoFull) {
// Do I2C
fifoFull = false;
}
}
i am having trouble getting data from two sensors using two software serial ports with an arduino board. I noticed a similar question might have been asked before but the answers suggest it can't be done and I know fully well it can based on the example here (http://arduino.cc/en/Tutorial/TwoPortReceive)!
I am using an arduino ethernet. The devices I am trying to get data from include a GPS and an IMU both from sparkfun.
I can get data from either devices using just on software serial port but as soon as I add the second software serial port, neither ports will work. I can't use the hardware serial port because that is being used byt another device.
My code is exactly similar to the example:
#include <SoftwareSerial.h>
SoftwareSerial portOne(7,8);
SoftwareSerial portTwo(5,6);
void setup()
{
Serial.begin(9600);
portOne.begin(9600);
portTwo.begin(9600);
}
void loop()
{
portOne.listen();
while (portOne.available() > 0) {
char inByte = portOne.read();
Serial.write(inByte);
}
delay(500);
portTwo.listen();
while (portTwo.available() > 0) {
char inByte = portTwo.read();
Serial.write(inByte);
}
Serial.println();
}
Anyone with any ideas?
This code will not work, or will work poorly if it works at all. SoftwareSerial only has one internal buffer. Yes, you can have multiple SoftwareSerial objects in existence, but only one of them controls the internal buffer. When any RX pin gets asserted, that generates an interrupt, but only the listen()ing RX pin gets checked for a start bit.
What's really needed is the ability to check on multiple pins when an interrupt comes along from the start bit. Then you'd have to set up pointers to the appropriate data structures. It would be complicated, but possible.
Or maybe just give up on interrupt-driven reception, and spin on checking both/all of the RX pins, and start the receive based on the pin you see. Be forwarned that this code has much hair, and you WILL need an oscilloscope to make it work.
I'm having a similar problem, which is why I found your sensor. After talking it over with my co-workers, we've decided to read our sensors in rotating order. Our sensors report the current state of the sensor, and not specific events, so it's okay if we lose some reports. So we'll read from port 1, then read from port 2, then port 1, etc. Our sensors spit out lines of text, so we know when to switch to the next sensor.
The referenced example only actively listens to one port at a time. The recommended solution would be to upgrade to an Arduino Mega (https://www.sparkfun.com/products/11061) which has 4 hardware serial ports.
In order to simultaneously support two software serial ports is going to require a lot of the CPU resources. It also be a difficult design and excessive programming time far outweighing the cost of $58 + shipping.
Looking at you code again it occurs to me that you are immediately checking for characters after your portOne.listen command. At 9600 baud it will take approximately 1ms for the first character to arrive, your while test will have been completed and the portTwo.listen command executed long before the first character arrives.
For testing purposes try adding a 1-2 ms delay after the portOne.listen command and see if you get a character.
As an example (untested and note, if port one is sending characters with no intercharacter gaps, the first while will never fail, preventing reading portTwo characters):
void loop()
{
portOne.listen();
delay(2);
while (portOne.available() > 0) {
char inByte = portOne.read();
Serial.write(inByte);
delay(1);
}
portTwo.listen();
delay(2);
while (portTwo.available() > 0) {
char inByte = portTwo.read();
Serial.write(inByte);
delay(1);
}
Serial.println();
}
Don't use while ......
Use:
{ portOne.listen();
if (PortOne.available() ) {
ricevo = myPort1.read(); }
// delay(2); // ridiculos waiting time
// delay(1); // extra ridiculos waiting time
Than 500 ms is a too big time for switching, no time.....