I'm a c++ programmer and I'm having some issue with managed array. I'll explain what i mean. I'm using Visual Studio to code a Windows Form to handle a device.
I need to plot datas from a MCU connected to my PC thru a serial port. To save the values incoming from serial port, I'm using an array like that:
array<double, 1>^ datas = gcnew array<double, 1>(ndatas);
array<Byte, 1>^ byteDatas = gcnew array<Byte, 1>(2*ndatas);
where ndatas is the number of values of my series and byteDatas is the array where I will save the bytes that compose every value. Every value is made by 2 bytes.
After that, I will fill this array like this:
for(int i = 0; <=ndatas; ) {
if(bytes = serialPort1->BytesToRead>=2) {
datas[i] = getData(serialPort1, byteDatas, i);
}
i++;
}
The funcion getData is this one:
double getData(serialPort^ sp, array<Byte,1> data, int i) {
union Level {
char L[2];
signed short level;
} lvl;
sp->Read(data, i, 2);
for(int j = 0; j<=2; j++) {
lvl.L[j]= data[i+j];
}
return safe_cast<double>(lvl.level/100.00);
}
This function is on another .cpp file, so I had to use the variable SerialPort.
Everything goes like charm. If I try to use a MessageBox to display my datas, I can see how my array is correctly filled with the right values.
My next step to do, is to plot this data on a pictureBox using drawLine. But I really can't cause half of the values of the array datas are set to 0. For istance, if my series has 100 values, I can draw only the first values with the right amplitude. The other are represented, of course, as a horizontal line of zeroes.
To find this out, I have used a for cycle like that.
for(int i = 0; i<=datas->Length; i++) {
MessageBox::Show(Convert::ToString(datas[i]+" " + Convert::ToString(i+1));
}
just to be sure from when I will find the problem.
The strange part of this one is that, if I put the same MessageBox line of code under
datas[i] = getData(serialPort1, byteDatas, i);
I can display all of values without zeroes.
I'm stuck, and I don't know how to get rid of this problem. I hope I can find a little help to overcome this annoying issue.
I wish everything is crystal clear and I would like to thank everyone will give me a feedback.
Cheers,
Emiliano
When you do call getData, you're getting a valid value.
But BytesToRead goes down as you read data. At some point it drops below 2, and the rest of the for loop does nothing.
You might need to save where you are in the array when you run out of data, and when more serial data arrives, continue filling in the array from where you left off.
Plus, of course, right now you appear to be putting every data value into element 0 of the array, because you never increment i.
Also, you're reading each data point at index i, which means that you overwrite the second byte from the previous sample.
There's no need for safe_cast, the result of the division is already a double. And even if you needed a conversion, safe_cast isn't appropriate, since none of these data types are polymorphic.
Furthermore, your use of the union causes undefined behavior.
Finally, you're in C++. So why are you using what is probably the worst designed serial port API Microsoft ever made? This is C++. Calling Win32 APIs is easy, just #include <windows.h> and go, no p/invoke needed.
Related
So here's an example of someone (me) writing very bad C# code.
I'm trying to figure out the best method of storing values and replacing them with values as they become known.
Here's how I had been doing it earlier:
int
EMA_Value_Prev4,
EMA_Value_Prev3,
EMA_Value_Prev2,
EMA_Value_Prev,
EMA_Value;
EMA_Value_Prev4 = EMA_Value_Prev3;
EMA_Value_Prev3 = EMA_Value_Prev2;
EMA_Value_Prev2 = EMA_Value_Prev;
EMA_Value_Prev = EMA_Value;
EMA_Value = 0;
// In the below space, some code figures out what EMA_Value is
/* Some amazing code */
// EMA_Value now equals 245 (hypothetically).
Since then, I've used arrays to store this with for loops, like this:
int [] EMA_Value = new int [5];
for (xCount=4; xCount>1; xCount--)
{EMA_Value[xCount] = EMA_Value[xCount - 1]; }
For the way more advanced and experienced (and smarter) coder than I, what I should be doing instead that's either more efficient/elegant/process friendly?
Thanks in advance for any time or attention you give this question. :)
If the reason you're doing it that way is because you want to get the previous values in some case. You can think about using something like a Stack. .NET has a built in stack
Stack<int> stack = new Stack<int>();
stack.push(10)
int topValue = stack.pop()
Every time you get a new value, you call stack.push(newValue). If you want that the previous value, (behaving in the same way as the back button on a browser), you then use pop.
If you're using last N values for something like a runge-kutta ODE solver, than your solution with an array is as good as any other implementation
i've been trying to make a program that takes (for example) 3 cards at random.
But i don't want my program to grab the same card twice, so that means it can't have duplicates, but i don't know how to do this with a image Array.
String[] card = {
"Aclubs.png",
"2clubs.png",
"3clubs.png",
};
PImage[] cards = new PImage [card.length];
void setup() {
size(1000,1000);
randomCards();
drawCards();
}
int randomCards() {
int i = (round(random(0,2)));
cards[i] = loadImage(card[i]);
return i;
}
void drawCards() {
for (int g = 0; g < 12000; g = g+round((displayWidth * 0.9))/12) {
image(cards[randomCards()], 25+g, 50);
}
}
Instead of using an array, use an ArrayList. Then remove the cards you use. Here's a small example:
ArrayList<String> things = new ArrayList<String>();
things.add("cat");
things.add("dog");
things.add("lizard");
while (!things.isEmpty()) {
int index = int(random(things.size()));
String thing = things.remove(index);
println(thing);
}
Of course, this isn't the only way to do it. You could use a Java Set, or you could use a data structure that holds what you've already picked, or you could store all of the options in a data structure, then shuffle it, then just chose from an index that you increment. Or you could use one of the array functions in the reference to do it.
It's hard to answer general "how do I do this" type questions. Stack Overflow is designed for more specific "I tried X, expected Y, but got Z instead" type questions. So you really should get into the habit of trying things out first. Ask yourself how you would do this in real life, then look at the reference to see if there are any classes or functions that would help with that. Break your problem down into smaller pieces. Write down how you would do this in real life, in English. Pretend you're handing those instructions to a friend. Could they follow your instructions to accomplish the goal? When you have those instructions written out, that's an algorithm that you can start thinking about implementing in code. Staring at code you've already written won't get you very far. Then when you do get stuck, you can ask a more specific question, and it'll be a lot easier to help you.
I am using an Arduino UNO with 32.000 bytes of storage.
While writing my program I made a small function that filled an array with random numbers.
This function uses a variable I defined at the top of the script as:
int mode1[100];
And this is the function that fills the array above. RandomSeed takes a number for its seed, whcih is provided by analogRead(0), with the 0 meaning pin 0 on my Arduino board.
void fillArray(int aSize){
if (aSize == 100){
randomSeed(analogRead(0));
for (int i=0; i < aSize; i++){
mode1[i] = random(1, aSize);}
When I call the fillArray function like fillArray(100); it will generate my integers. I then read them on my computer via this piece of code:
Serial.println("Filled array");
for (int i=0; i <= 99; i++){Serial.println((int)mode1[i]);}
Everything seemed to work fine but I noticed that the first 10 integers that my function will generate are always 0. My main problem is that I don't know how to troubleshoot this because the script gives me no errors. My question therefore is: What is the cause of the first 10 integers of that array always being 0?
My possible explanations for the cause are that the AnalogRead function does something strange (Currently it just has a pin in the A0 slot with nothing connected to it, which should work. I also know it's not the storage capacity, since 32.000 bytes is enough to store 100 integers in an array, and my script is only 5000 bytes.
I'm a bit stuck on this because I do not know what is causing the problem, any help would on the subject would be appreciated.
I cannot comment (not enough reputation yet), but did you check the number of lines that are on your output ? You may have "something" else in your code sending data before your start your log. You may want to write lines with "mode1[xxx]= yyy" where xxx is the index and yyy the value stored at index to make sure you that are looking at your array content.
I'm currently making a random number generator for the Arduino which is going to act as the lottery. I need six numbers all different and all between 1 and 50. With the code I have put together can achieve this easily but the random numbers are not quite as random and they do duplicate at times. The variables are stored into an array and not separate variables so it isn't straight forward (for me anyway) to add say OR statements etc. Also I want to keep it in a While loop and not a For loop.
Any help and advice would be greatly appreciated.
Here is the code I have put together so far:
int counter = 0; // Counter to be incremented
int maxNum = 6; // Max amount to increment to
int randNums[0]; // Random numbers array
void setup(){
Serial.begin(9600);
randomSeed(analogRead(0));
delay(300);
}
void loop(){
while(counter < maxNum){
randNums[counter] = random(1,50);
Serial.println(randNums[counter]);
delay(500);
counter++;
}
}
I see two parts in your question:
- the quality of the randomness
- how to use a temp array storage (? i don't fully understand this issue)
Concerning the quality of randomness, you could have a look at this Arduino library: http://code.google.com/p/tinkerit/wiki/TrueRandom, but, as said here: http://www.instructables.com/id/Arduino-True-Random-Number-Generator/
this is not NIST compliant. Although, I think that it is a step in the good direction.
Concerning your array issue, the first problem I see is that you reserve only 0 items in your declaration. Why? Either you reserve memory at compile time with int randNums[6], or you declare a pointer to an int, and use malloc during execution time.
HTH
So what I have is an array that's size is decided by me and then the elements in the array are randomly generated. It's supposed to take an integer array,its size, and an integer number
and find how many times the number is present in the array and return that count at the end.I keep trying stuff and nothing seems to be getting me anywhere close to an answer. I was just trying to see if someone could point me in the right direction on where to start
count_numbers(int array[], int size, int z)
Hhave you tried running a loop through the array and trying a match expression to the array value in another loop. This seems like a logic question rather than actual code related. Maybe a search around the internet looking at how to count in arrays could help you.
This should point you in the right direction...
for (int i = 0; i < arraySize; i++) {
if (array[i] == z /*z being your search value**/) {
you may have to alter this a little
//dosomething
// e.g. increment a count here
}
else
do-nothing essentially.
There is a method for checking array size - so don't worry about defining it's size. have a look at the java method for this and use it.
Hope this helps